index.cjs 1.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807
  1. var __create = Object.create;
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __getProtoOf = Object.getPrototypeOf;
  6. var __hasOwnProp = Object.prototype.hasOwnProperty;
  7. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  8. var __glob = (map) => (path) => {
  9. var fn = map[path];
  10. if (fn) return fn();
  11. throw new Error("Module not found in bundle: " + path);
  12. };
  13. var __esm = (fn, res) => function __init() {
  14. return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  15. };
  16. var __commonJS = (cb, mod) => function __require() {
  17. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  18. };
  19. var __export = (target, all) => {
  20. for (var name in all)
  21. __defProp(target, name, { get: all[name], enumerable: true });
  22. };
  23. var __copyProps = (to, from, except, desc) => {
  24. if (from && typeof from === "object" || typeof from === "function") {
  25. for (let key of __getOwnPropNames(from))
  26. if (!__hasOwnProp.call(to, key) && key !== except)
  27. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  28. }
  29. return to;
  30. };
  31. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  32. // If the importer is in node compatibility mode or this is not an ESM
  33. // file that has been converted to a CommonJS file using a Babel-
  34. // compatible transform (i.e. "__esModule" has not been set), then set
  35. // "default" to the CommonJS "module.exports" for node compatibility.
  36. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  37. mod
  38. ));
  39. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  40. // node_modules/mongodb/lib/error.js
  41. var require_error = __commonJS({
  42. "node_modules/mongodb/lib/error.js"(exports2) {
  43. "use strict";
  44. Object.defineProperty(exports2, "__esModule", { value: true });
  45. exports2.isResumableError = exports2.isNetworkTimeoutError = exports2.isSDAMUnrecoverableError = exports2.isNodeShuttingDownError = exports2.isRetryableReadError = exports2.isRetryableWriteError = exports2.needsRetryableWriteLabel = exports2.MongoWriteConcernError = exports2.MongoServerSelectionError = exports2.MongoSystemError = exports2.MongoMissingDependencyError = exports2.MongoMissingCredentialsError = exports2.MongoCompatibilityError = exports2.MongoInvalidArgumentError = exports2.MongoParseError = exports2.MongoNetworkTimeoutError = exports2.MongoNetworkError = exports2.isNetworkErrorBeforeHandshake = exports2.MongoTopologyClosedError = exports2.MongoCursorExhaustedError = exports2.MongoServerClosedError = exports2.MongoCursorInUseError = exports2.MongoUnexpectedServerResponseError = exports2.MongoGridFSChunkError = exports2.MongoGridFSStreamError = exports2.MongoTailableCursorError = exports2.MongoChangeStreamError = exports2.MongoAzureError = exports2.MongoAWSError = exports2.MongoKerberosError = exports2.MongoExpiredSessionError = exports2.MongoTransactionError = exports2.MongoNotConnectedError = exports2.MongoDecompressionError = exports2.MongoBatchReExecutionError = exports2.MongoRuntimeError = exports2.MongoAPIError = exports2.MongoDriverError = exports2.MongoServerError = exports2.MongoError = exports2.MongoErrorLabel = exports2.GET_MORE_RESUMABLE_CODES = exports2.MONGODB_ERROR_CODES = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE = exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = void 0;
  46. var kErrorLabels = Symbol("errorLabels");
  47. exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp("not master", "i");
  48. exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp("not master or secondary", "i");
  49. exports2.NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp("node is recovering", "i");
  50. exports2.MONGODB_ERROR_CODES = Object.freeze({
  51. HostUnreachable: 6,
  52. HostNotFound: 7,
  53. NetworkTimeout: 89,
  54. ShutdownInProgress: 91,
  55. PrimarySteppedDown: 189,
  56. ExceededTimeLimit: 262,
  57. SocketException: 9001,
  58. NotWritablePrimary: 10107,
  59. InterruptedAtShutdown: 11600,
  60. InterruptedDueToReplStateChange: 11602,
  61. NotPrimaryNoSecondaryOk: 13435,
  62. NotPrimaryOrSecondary: 13436,
  63. StaleShardVersion: 63,
  64. StaleEpoch: 150,
  65. StaleConfig: 13388,
  66. RetryChangeStream: 234,
  67. FailedToSatisfyReadPreference: 133,
  68. CursorNotFound: 43,
  69. LegacyNotPrimary: 10058,
  70. WriteConcernFailed: 64,
  71. NamespaceNotFound: 26,
  72. IllegalOperation: 20,
  73. MaxTimeMSExpired: 50,
  74. UnknownReplWriteConcern: 79,
  75. UnsatisfiableWriteConcern: 100,
  76. Reauthenticate: 391
  77. });
  78. exports2.GET_MORE_RESUMABLE_CODES = /* @__PURE__ */ new Set([
  79. exports2.MONGODB_ERROR_CODES.HostUnreachable,
  80. exports2.MONGODB_ERROR_CODES.HostNotFound,
  81. exports2.MONGODB_ERROR_CODES.NetworkTimeout,
  82. exports2.MONGODB_ERROR_CODES.ShutdownInProgress,
  83. exports2.MONGODB_ERROR_CODES.PrimarySteppedDown,
  84. exports2.MONGODB_ERROR_CODES.ExceededTimeLimit,
  85. exports2.MONGODB_ERROR_CODES.SocketException,
  86. exports2.MONGODB_ERROR_CODES.NotWritablePrimary,
  87. exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown,
  88. exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
  89. exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,
  90. exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary,
  91. exports2.MONGODB_ERROR_CODES.StaleShardVersion,
  92. exports2.MONGODB_ERROR_CODES.StaleEpoch,
  93. exports2.MONGODB_ERROR_CODES.StaleConfig,
  94. exports2.MONGODB_ERROR_CODES.RetryChangeStream,
  95. exports2.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference,
  96. exports2.MONGODB_ERROR_CODES.CursorNotFound
  97. ]);
  98. exports2.MongoErrorLabel = Object.freeze({
  99. RetryableWriteError: "RetryableWriteError",
  100. TransientTransactionError: "TransientTransactionError",
  101. UnknownTransactionCommitResult: "UnknownTransactionCommitResult",
  102. ResumableChangeStreamError: "ResumableChangeStreamError",
  103. HandshakeError: "HandshakeError",
  104. ResetPool: "ResetPool",
  105. InterruptInUseConnections: "InterruptInUseConnections",
  106. NoWritesPerformed: "NoWritesPerformed"
  107. });
  108. function isAggregateError(e) {
  109. return "errors" in e && Array.isArray(e.errors);
  110. }
  111. __name(isAggregateError, "isAggregateError");
  112. var _MongoError = class _MongoError extends Error {
  113. constructor(message) {
  114. super(_MongoError.buildErrorMessage(message));
  115. if (message instanceof Error) {
  116. this.cause = message;
  117. }
  118. this[kErrorLabels] = /* @__PURE__ */ new Set();
  119. }
  120. /** @internal */
  121. static buildErrorMessage(e) {
  122. if (typeof e === "string") {
  123. return e;
  124. }
  125. if (isAggregateError(e) && e.message.length === 0) {
  126. return e.errors.length === 0 ? "AggregateError has an empty errors array. Please check the `cause` property for more information." : e.errors.map(({ message }) => message).join(", ");
  127. }
  128. return e.message;
  129. }
  130. get name() {
  131. return "MongoError";
  132. }
  133. /** Legacy name for server error responses */
  134. get errmsg() {
  135. return this.message;
  136. }
  137. /**
  138. * Checks the error to see if it has an error label
  139. *
  140. * @param label - The error label to check for
  141. * @returns returns true if the error has the provided error label
  142. */
  143. hasErrorLabel(label) {
  144. return this[kErrorLabels].has(label);
  145. }
  146. addErrorLabel(label) {
  147. this[kErrorLabels].add(label);
  148. }
  149. get errorLabels() {
  150. return Array.from(this[kErrorLabels]);
  151. }
  152. };
  153. __name(_MongoError, "MongoError");
  154. var MongoError = _MongoError;
  155. exports2.MongoError = MongoError;
  156. var _MongoServerError = class _MongoServerError extends MongoError {
  157. constructor(message) {
  158. super(message.message || message.errmsg || message.$err || "n/a");
  159. if (message.errorLabels) {
  160. this[kErrorLabels] = new Set(message.errorLabels);
  161. }
  162. for (const name in message) {
  163. if (name !== "errorLabels" && name !== "errmsg" && name !== "message")
  164. this[name] = message[name];
  165. }
  166. }
  167. get name() {
  168. return "MongoServerError";
  169. }
  170. };
  171. __name(_MongoServerError, "MongoServerError");
  172. var MongoServerError = _MongoServerError;
  173. exports2.MongoServerError = MongoServerError;
  174. var _MongoDriverError = class _MongoDriverError extends MongoError {
  175. constructor(message) {
  176. super(message);
  177. }
  178. get name() {
  179. return "MongoDriverError";
  180. }
  181. };
  182. __name(_MongoDriverError, "MongoDriverError");
  183. var MongoDriverError = _MongoDriverError;
  184. exports2.MongoDriverError = MongoDriverError;
  185. var _MongoAPIError = class _MongoAPIError extends MongoDriverError {
  186. constructor(message) {
  187. super(message);
  188. }
  189. get name() {
  190. return "MongoAPIError";
  191. }
  192. };
  193. __name(_MongoAPIError, "MongoAPIError");
  194. var MongoAPIError = _MongoAPIError;
  195. exports2.MongoAPIError = MongoAPIError;
  196. var _MongoRuntimeError = class _MongoRuntimeError extends MongoDriverError {
  197. constructor(message) {
  198. super(message);
  199. }
  200. get name() {
  201. return "MongoRuntimeError";
  202. }
  203. };
  204. __name(_MongoRuntimeError, "MongoRuntimeError");
  205. var MongoRuntimeError = _MongoRuntimeError;
  206. exports2.MongoRuntimeError = MongoRuntimeError;
  207. var _MongoBatchReExecutionError = class _MongoBatchReExecutionError extends MongoAPIError {
  208. constructor(message = "This batch has already been executed, create new batch to execute") {
  209. super(message);
  210. }
  211. get name() {
  212. return "MongoBatchReExecutionError";
  213. }
  214. };
  215. __name(_MongoBatchReExecutionError, "MongoBatchReExecutionError");
  216. var MongoBatchReExecutionError = _MongoBatchReExecutionError;
  217. exports2.MongoBatchReExecutionError = MongoBatchReExecutionError;
  218. var _MongoDecompressionError = class _MongoDecompressionError extends MongoRuntimeError {
  219. constructor(message) {
  220. super(message);
  221. }
  222. get name() {
  223. return "MongoDecompressionError";
  224. }
  225. };
  226. __name(_MongoDecompressionError, "MongoDecompressionError");
  227. var MongoDecompressionError = _MongoDecompressionError;
  228. exports2.MongoDecompressionError = MongoDecompressionError;
  229. var _MongoNotConnectedError = class _MongoNotConnectedError extends MongoAPIError {
  230. constructor(message) {
  231. super(message);
  232. }
  233. get name() {
  234. return "MongoNotConnectedError";
  235. }
  236. };
  237. __name(_MongoNotConnectedError, "MongoNotConnectedError");
  238. var MongoNotConnectedError = _MongoNotConnectedError;
  239. exports2.MongoNotConnectedError = MongoNotConnectedError;
  240. var _MongoTransactionError = class _MongoTransactionError extends MongoAPIError {
  241. constructor(message) {
  242. super(message);
  243. }
  244. get name() {
  245. return "MongoTransactionError";
  246. }
  247. };
  248. __name(_MongoTransactionError, "MongoTransactionError");
  249. var MongoTransactionError = _MongoTransactionError;
  250. exports2.MongoTransactionError = MongoTransactionError;
  251. var _MongoExpiredSessionError = class _MongoExpiredSessionError extends MongoAPIError {
  252. constructor(message = "Cannot use a session that has ended") {
  253. super(message);
  254. }
  255. get name() {
  256. return "MongoExpiredSessionError";
  257. }
  258. };
  259. __name(_MongoExpiredSessionError, "MongoExpiredSessionError");
  260. var MongoExpiredSessionError = _MongoExpiredSessionError;
  261. exports2.MongoExpiredSessionError = MongoExpiredSessionError;
  262. var _MongoKerberosError = class _MongoKerberosError extends MongoRuntimeError {
  263. constructor(message) {
  264. super(message);
  265. }
  266. get name() {
  267. return "MongoKerberosError";
  268. }
  269. };
  270. __name(_MongoKerberosError, "MongoKerberosError");
  271. var MongoKerberosError = _MongoKerberosError;
  272. exports2.MongoKerberosError = MongoKerberosError;
  273. var _MongoAWSError = class _MongoAWSError extends MongoRuntimeError {
  274. constructor(message) {
  275. super(message);
  276. }
  277. get name() {
  278. return "MongoAWSError";
  279. }
  280. };
  281. __name(_MongoAWSError, "MongoAWSError");
  282. var MongoAWSError = _MongoAWSError;
  283. exports2.MongoAWSError = MongoAWSError;
  284. var _MongoAzureError = class _MongoAzureError extends MongoRuntimeError {
  285. constructor(message) {
  286. super(message);
  287. }
  288. get name() {
  289. return "MongoAzureError";
  290. }
  291. };
  292. __name(_MongoAzureError, "MongoAzureError");
  293. var MongoAzureError = _MongoAzureError;
  294. exports2.MongoAzureError = MongoAzureError;
  295. var _MongoChangeStreamError = class _MongoChangeStreamError extends MongoRuntimeError {
  296. constructor(message) {
  297. super(message);
  298. }
  299. get name() {
  300. return "MongoChangeStreamError";
  301. }
  302. };
  303. __name(_MongoChangeStreamError, "MongoChangeStreamError");
  304. var MongoChangeStreamError = _MongoChangeStreamError;
  305. exports2.MongoChangeStreamError = MongoChangeStreamError;
  306. var _MongoTailableCursorError = class _MongoTailableCursorError extends MongoAPIError {
  307. constructor(message = "Tailable cursor does not support this operation") {
  308. super(message);
  309. }
  310. get name() {
  311. return "MongoTailableCursorError";
  312. }
  313. };
  314. __name(_MongoTailableCursorError, "MongoTailableCursorError");
  315. var MongoTailableCursorError = _MongoTailableCursorError;
  316. exports2.MongoTailableCursorError = MongoTailableCursorError;
  317. var _MongoGridFSStreamError = class _MongoGridFSStreamError extends MongoRuntimeError {
  318. constructor(message) {
  319. super(message);
  320. }
  321. get name() {
  322. return "MongoGridFSStreamError";
  323. }
  324. };
  325. __name(_MongoGridFSStreamError, "MongoGridFSStreamError");
  326. var MongoGridFSStreamError = _MongoGridFSStreamError;
  327. exports2.MongoGridFSStreamError = MongoGridFSStreamError;
  328. var _MongoGridFSChunkError = class _MongoGridFSChunkError extends MongoRuntimeError {
  329. constructor(message) {
  330. super(message);
  331. }
  332. get name() {
  333. return "MongoGridFSChunkError";
  334. }
  335. };
  336. __name(_MongoGridFSChunkError, "MongoGridFSChunkError");
  337. var MongoGridFSChunkError = _MongoGridFSChunkError;
  338. exports2.MongoGridFSChunkError = MongoGridFSChunkError;
  339. var _MongoUnexpectedServerResponseError = class _MongoUnexpectedServerResponseError extends MongoRuntimeError {
  340. constructor(message) {
  341. super(message);
  342. }
  343. get name() {
  344. return "MongoUnexpectedServerResponseError";
  345. }
  346. };
  347. __name(_MongoUnexpectedServerResponseError, "MongoUnexpectedServerResponseError");
  348. var MongoUnexpectedServerResponseError = _MongoUnexpectedServerResponseError;
  349. exports2.MongoUnexpectedServerResponseError = MongoUnexpectedServerResponseError;
  350. var _MongoCursorInUseError = class _MongoCursorInUseError extends MongoAPIError {
  351. constructor(message = "Cursor is already initialized") {
  352. super(message);
  353. }
  354. get name() {
  355. return "MongoCursorInUseError";
  356. }
  357. };
  358. __name(_MongoCursorInUseError, "MongoCursorInUseError");
  359. var MongoCursorInUseError = _MongoCursorInUseError;
  360. exports2.MongoCursorInUseError = MongoCursorInUseError;
  361. var _MongoServerClosedError = class _MongoServerClosedError extends MongoAPIError {
  362. constructor(message = "Server is closed") {
  363. super(message);
  364. }
  365. get name() {
  366. return "MongoServerClosedError";
  367. }
  368. };
  369. __name(_MongoServerClosedError, "MongoServerClosedError");
  370. var MongoServerClosedError = _MongoServerClosedError;
  371. exports2.MongoServerClosedError = MongoServerClosedError;
  372. var _MongoCursorExhaustedError = class _MongoCursorExhaustedError extends MongoAPIError {
  373. constructor(message) {
  374. super(message || "Cursor is exhausted");
  375. }
  376. get name() {
  377. return "MongoCursorExhaustedError";
  378. }
  379. };
  380. __name(_MongoCursorExhaustedError, "MongoCursorExhaustedError");
  381. var MongoCursorExhaustedError = _MongoCursorExhaustedError;
  382. exports2.MongoCursorExhaustedError = MongoCursorExhaustedError;
  383. var _MongoTopologyClosedError = class _MongoTopologyClosedError extends MongoAPIError {
  384. constructor(message = "Topology is closed") {
  385. super(message);
  386. }
  387. get name() {
  388. return "MongoTopologyClosedError";
  389. }
  390. };
  391. __name(_MongoTopologyClosedError, "MongoTopologyClosedError");
  392. var MongoTopologyClosedError = _MongoTopologyClosedError;
  393. exports2.MongoTopologyClosedError = MongoTopologyClosedError;
  394. var kBeforeHandshake = Symbol("beforeHandshake");
  395. function isNetworkErrorBeforeHandshake(err) {
  396. return err[kBeforeHandshake] === true;
  397. }
  398. __name(isNetworkErrorBeforeHandshake, "isNetworkErrorBeforeHandshake");
  399. exports2.isNetworkErrorBeforeHandshake = isNetworkErrorBeforeHandshake;
  400. var _MongoNetworkError = class _MongoNetworkError extends MongoError {
  401. constructor(message, options) {
  402. super(message);
  403. if (options && typeof options.beforeHandshake === "boolean") {
  404. this[kBeforeHandshake] = options.beforeHandshake;
  405. }
  406. }
  407. get name() {
  408. return "MongoNetworkError";
  409. }
  410. };
  411. __name(_MongoNetworkError, "MongoNetworkError");
  412. var MongoNetworkError = _MongoNetworkError;
  413. exports2.MongoNetworkError = MongoNetworkError;
  414. var _MongoNetworkTimeoutError = class _MongoNetworkTimeoutError extends MongoNetworkError {
  415. constructor(message, options) {
  416. super(message, options);
  417. }
  418. get name() {
  419. return "MongoNetworkTimeoutError";
  420. }
  421. };
  422. __name(_MongoNetworkTimeoutError, "MongoNetworkTimeoutError");
  423. var MongoNetworkTimeoutError = _MongoNetworkTimeoutError;
  424. exports2.MongoNetworkTimeoutError = MongoNetworkTimeoutError;
  425. var _MongoParseError = class _MongoParseError extends MongoDriverError {
  426. constructor(message) {
  427. super(message);
  428. }
  429. get name() {
  430. return "MongoParseError";
  431. }
  432. };
  433. __name(_MongoParseError, "MongoParseError");
  434. var MongoParseError = _MongoParseError;
  435. exports2.MongoParseError = MongoParseError;
  436. var _MongoInvalidArgumentError = class _MongoInvalidArgumentError extends MongoAPIError {
  437. constructor(message) {
  438. super(message);
  439. }
  440. get name() {
  441. return "MongoInvalidArgumentError";
  442. }
  443. };
  444. __name(_MongoInvalidArgumentError, "MongoInvalidArgumentError");
  445. var MongoInvalidArgumentError = _MongoInvalidArgumentError;
  446. exports2.MongoInvalidArgumentError = MongoInvalidArgumentError;
  447. var _MongoCompatibilityError = class _MongoCompatibilityError extends MongoAPIError {
  448. constructor(message) {
  449. super(message);
  450. }
  451. get name() {
  452. return "MongoCompatibilityError";
  453. }
  454. };
  455. __name(_MongoCompatibilityError, "MongoCompatibilityError");
  456. var MongoCompatibilityError = _MongoCompatibilityError;
  457. exports2.MongoCompatibilityError = MongoCompatibilityError;
  458. var _MongoMissingCredentialsError = class _MongoMissingCredentialsError extends MongoAPIError {
  459. constructor(message) {
  460. super(message);
  461. }
  462. get name() {
  463. return "MongoMissingCredentialsError";
  464. }
  465. };
  466. __name(_MongoMissingCredentialsError, "MongoMissingCredentialsError");
  467. var MongoMissingCredentialsError = _MongoMissingCredentialsError;
  468. exports2.MongoMissingCredentialsError = MongoMissingCredentialsError;
  469. var _MongoMissingDependencyError = class _MongoMissingDependencyError extends MongoAPIError {
  470. constructor(message, { cause } = {}) {
  471. super(message);
  472. if (cause)
  473. this.cause = cause;
  474. }
  475. get name() {
  476. return "MongoMissingDependencyError";
  477. }
  478. };
  479. __name(_MongoMissingDependencyError, "MongoMissingDependencyError");
  480. var MongoMissingDependencyError = _MongoMissingDependencyError;
  481. exports2.MongoMissingDependencyError = MongoMissingDependencyError;
  482. var _MongoSystemError = class _MongoSystemError extends MongoError {
  483. constructor(message, reason) {
  484. var _a;
  485. if (reason && reason.error) {
  486. super(reason.error.message || reason.error);
  487. } else {
  488. super(message);
  489. }
  490. if (reason) {
  491. this.reason = reason;
  492. }
  493. this.code = (_a = reason.error) == null ? void 0 : _a.code;
  494. }
  495. get name() {
  496. return "MongoSystemError";
  497. }
  498. };
  499. __name(_MongoSystemError, "MongoSystemError");
  500. var MongoSystemError = _MongoSystemError;
  501. exports2.MongoSystemError = MongoSystemError;
  502. var _MongoServerSelectionError = class _MongoServerSelectionError extends MongoSystemError {
  503. constructor(message, reason) {
  504. super(message, reason);
  505. }
  506. get name() {
  507. return "MongoServerSelectionError";
  508. }
  509. };
  510. __name(_MongoServerSelectionError, "MongoServerSelectionError");
  511. var MongoServerSelectionError = _MongoServerSelectionError;
  512. exports2.MongoServerSelectionError = MongoServerSelectionError;
  513. function makeWriteConcernResultObject(input) {
  514. const output = Object.assign({}, input);
  515. if (output.ok === 0) {
  516. output.ok = 1;
  517. delete output.errmsg;
  518. delete output.code;
  519. delete output.codeName;
  520. }
  521. return output;
  522. }
  523. __name(makeWriteConcernResultObject, "makeWriteConcernResultObject");
  524. var _MongoWriteConcernError = class _MongoWriteConcernError extends MongoServerError {
  525. constructor(message, result) {
  526. if (result && Array.isArray(result.errorLabels)) {
  527. message.errorLabels = result.errorLabels;
  528. }
  529. super(message);
  530. this.errInfo = message.errInfo;
  531. if (result != null) {
  532. this.result = makeWriteConcernResultObject(result);
  533. }
  534. }
  535. get name() {
  536. return "MongoWriteConcernError";
  537. }
  538. };
  539. __name(_MongoWriteConcernError, "MongoWriteConcernError");
  540. var MongoWriteConcernError = _MongoWriteConcernError;
  541. exports2.MongoWriteConcernError = MongoWriteConcernError;
  542. var RETRYABLE_READ_ERROR_CODES = /* @__PURE__ */ new Set([
  543. exports2.MONGODB_ERROR_CODES.HostUnreachable,
  544. exports2.MONGODB_ERROR_CODES.HostNotFound,
  545. exports2.MONGODB_ERROR_CODES.NetworkTimeout,
  546. exports2.MONGODB_ERROR_CODES.ShutdownInProgress,
  547. exports2.MONGODB_ERROR_CODES.PrimarySteppedDown,
  548. exports2.MONGODB_ERROR_CODES.SocketException,
  549. exports2.MONGODB_ERROR_CODES.NotWritablePrimary,
  550. exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown,
  551. exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
  552. exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,
  553. exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary
  554. ]);
  555. var RETRYABLE_WRITE_ERROR_CODES = /* @__PURE__ */ new Set([
  556. ...RETRYABLE_READ_ERROR_CODES,
  557. exports2.MONGODB_ERROR_CODES.ExceededTimeLimit
  558. ]);
  559. function needsRetryableWriteLabel(error, maxWireVersion) {
  560. var _a;
  561. if (error instanceof MongoNetworkError) {
  562. return true;
  563. }
  564. if (error instanceof MongoError) {
  565. if ((maxWireVersion >= 9 || error.hasErrorLabel(exports2.MongoErrorLabel.RetryableWriteError)) && !error.hasErrorLabel(exports2.MongoErrorLabel.HandshakeError)) {
  566. return false;
  567. }
  568. }
  569. if (error instanceof MongoWriteConcernError) {
  570. return RETRYABLE_WRITE_ERROR_CODES.has(((_a = error.result) == null ? void 0 : _a.code) ?? error.code ?? 0);
  571. }
  572. if (error instanceof MongoError && typeof error.code === "number") {
  573. return RETRYABLE_WRITE_ERROR_CODES.has(error.code);
  574. }
  575. const isNotWritablePrimaryError2 = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message);
  576. if (isNotWritablePrimaryError2) {
  577. return true;
  578. }
  579. const isNodeIsRecoveringError = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message);
  580. if (isNodeIsRecoveringError) {
  581. return true;
  582. }
  583. return false;
  584. }
  585. __name(needsRetryableWriteLabel, "needsRetryableWriteLabel");
  586. exports2.needsRetryableWriteLabel = needsRetryableWriteLabel;
  587. function isRetryableWriteError(error) {
  588. return error.hasErrorLabel(exports2.MongoErrorLabel.RetryableWriteError);
  589. }
  590. __name(isRetryableWriteError, "isRetryableWriteError");
  591. exports2.isRetryableWriteError = isRetryableWriteError;
  592. function isRetryableReadError(error) {
  593. const hasRetryableErrorCode = typeof error.code === "number" ? RETRYABLE_READ_ERROR_CODES.has(error.code) : false;
  594. if (hasRetryableErrorCode) {
  595. return true;
  596. }
  597. if (error instanceof MongoNetworkError) {
  598. return true;
  599. }
  600. const isNotWritablePrimaryError2 = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message);
  601. if (isNotWritablePrimaryError2) {
  602. return true;
  603. }
  604. const isNodeIsRecoveringError = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message);
  605. if (isNodeIsRecoveringError) {
  606. return true;
  607. }
  608. return false;
  609. }
  610. __name(isRetryableReadError, "isRetryableReadError");
  611. exports2.isRetryableReadError = isRetryableReadError;
  612. var SDAM_RECOVERING_CODES = /* @__PURE__ */ new Set([
  613. exports2.MONGODB_ERROR_CODES.ShutdownInProgress,
  614. exports2.MONGODB_ERROR_CODES.PrimarySteppedDown,
  615. exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown,
  616. exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
  617. exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary
  618. ]);
  619. var SDAM_NOT_PRIMARY_CODES = /* @__PURE__ */ new Set([
  620. exports2.MONGODB_ERROR_CODES.NotWritablePrimary,
  621. exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,
  622. exports2.MONGODB_ERROR_CODES.LegacyNotPrimary
  623. ]);
  624. var SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = /* @__PURE__ */ new Set([
  625. exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown,
  626. exports2.MONGODB_ERROR_CODES.ShutdownInProgress
  627. ]);
  628. function isRecoveringError(err) {
  629. if (typeof err.code === "number") {
  630. return SDAM_RECOVERING_CODES.has(err.code);
  631. }
  632. return exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message);
  633. }
  634. __name(isRecoveringError, "isRecoveringError");
  635. function isNotWritablePrimaryError(err) {
  636. if (typeof err.code === "number") {
  637. return SDAM_NOT_PRIMARY_CODES.has(err.code);
  638. }
  639. if (isRecoveringError(err)) {
  640. return false;
  641. }
  642. return exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message);
  643. }
  644. __name(isNotWritablePrimaryError, "isNotWritablePrimaryError");
  645. function isNodeShuttingDownError(err) {
  646. return !!(typeof err.code === "number" && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code));
  647. }
  648. __name(isNodeShuttingDownError, "isNodeShuttingDownError");
  649. exports2.isNodeShuttingDownError = isNodeShuttingDownError;
  650. function isSDAMUnrecoverableError(error) {
  651. if (error instanceof MongoParseError || error == null) {
  652. return true;
  653. }
  654. return isRecoveringError(error) || isNotWritablePrimaryError(error);
  655. }
  656. __name(isSDAMUnrecoverableError, "isSDAMUnrecoverableError");
  657. exports2.isSDAMUnrecoverableError = isSDAMUnrecoverableError;
  658. function isNetworkTimeoutError(err) {
  659. return !!(err instanceof MongoNetworkError && err.message.match(/timed out/));
  660. }
  661. __name(isNetworkTimeoutError, "isNetworkTimeoutError");
  662. exports2.isNetworkTimeoutError = isNetworkTimeoutError;
  663. function isResumableError(error, wireVersion) {
  664. if (error == null || !(error instanceof MongoError)) {
  665. return false;
  666. }
  667. if (error instanceof MongoNetworkError) {
  668. return true;
  669. }
  670. if (wireVersion != null && wireVersion >= 9) {
  671. if (error.code === exports2.MONGODB_ERROR_CODES.CursorNotFound) {
  672. return true;
  673. }
  674. return error.hasErrorLabel(exports2.MongoErrorLabel.ResumableChangeStreamError);
  675. }
  676. if (typeof error.code === "number") {
  677. return exports2.GET_MORE_RESUMABLE_CODES.has(error.code);
  678. }
  679. return false;
  680. }
  681. __name(isResumableError, "isResumableError");
  682. exports2.isResumableError = isResumableError;
  683. }
  684. });
  685. // node_modules/bson/lib/bson.cjs
  686. var require_bson = __commonJS({
  687. "node_modules/bson/lib/bson.cjs"(exports2) {
  688. "use strict";
  689. function isAnyArrayBuffer(value) {
  690. return ["[object ArrayBuffer]", "[object SharedArrayBuffer]"].includes(Object.prototype.toString.call(value));
  691. }
  692. __name(isAnyArrayBuffer, "isAnyArrayBuffer");
  693. function isUint8Array(value) {
  694. return Object.prototype.toString.call(value) === "[object Uint8Array]";
  695. }
  696. __name(isUint8Array, "isUint8Array");
  697. function isRegExp(d) {
  698. return Object.prototype.toString.call(d) === "[object RegExp]";
  699. }
  700. __name(isRegExp, "isRegExp");
  701. function isMap(d) {
  702. return Object.prototype.toString.call(d) === "[object Map]";
  703. }
  704. __name(isMap, "isMap");
  705. function isDate(d) {
  706. return Object.prototype.toString.call(d) === "[object Date]";
  707. }
  708. __name(isDate, "isDate");
  709. var BSON_MAJOR_VERSION = 5;
  710. var BSON_INT32_MAX = 2147483647;
  711. var BSON_INT32_MIN = -2147483648;
  712. var BSON_INT64_MAX = Math.pow(2, 63) - 1;
  713. var BSON_INT64_MIN = -Math.pow(2, 63);
  714. var JS_INT_MAX = Math.pow(2, 53);
  715. var JS_INT_MIN = -Math.pow(2, 53);
  716. var BSON_DATA_NUMBER = 1;
  717. var BSON_DATA_STRING = 2;
  718. var BSON_DATA_OBJECT = 3;
  719. var BSON_DATA_ARRAY = 4;
  720. var BSON_DATA_BINARY = 5;
  721. var BSON_DATA_UNDEFINED = 6;
  722. var BSON_DATA_OID = 7;
  723. var BSON_DATA_BOOLEAN = 8;
  724. var BSON_DATA_DATE = 9;
  725. var BSON_DATA_NULL = 10;
  726. var BSON_DATA_REGEXP = 11;
  727. var BSON_DATA_DBPOINTER = 12;
  728. var BSON_DATA_CODE = 13;
  729. var BSON_DATA_SYMBOL = 14;
  730. var BSON_DATA_CODE_W_SCOPE = 15;
  731. var BSON_DATA_INT = 16;
  732. var BSON_DATA_TIMESTAMP = 17;
  733. var BSON_DATA_LONG = 18;
  734. var BSON_DATA_DECIMAL128 = 19;
  735. var BSON_DATA_MIN_KEY = 255;
  736. var BSON_DATA_MAX_KEY = 127;
  737. var BSON_BINARY_SUBTYPE_DEFAULT = 0;
  738. var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
  739. var BSONType = Object.freeze({
  740. double: 1,
  741. string: 2,
  742. object: 3,
  743. array: 4,
  744. binData: 5,
  745. undefined: 6,
  746. objectId: 7,
  747. bool: 8,
  748. date: 9,
  749. null: 10,
  750. regex: 11,
  751. dbPointer: 12,
  752. javascript: 13,
  753. symbol: 14,
  754. javascriptWithScope: 15,
  755. int: 16,
  756. timestamp: 17,
  757. long: 18,
  758. decimal: 19,
  759. minKey: -1,
  760. maxKey: 127
  761. });
  762. var _BSONError = class _BSONError extends Error {
  763. get bsonError() {
  764. return true;
  765. }
  766. get name() {
  767. return "BSONError";
  768. }
  769. constructor(message) {
  770. super(message);
  771. }
  772. static isBSONError(value) {
  773. return value != null && typeof value === "object" && "bsonError" in value && value.bsonError === true && "name" in value && "message" in value && "stack" in value;
  774. }
  775. };
  776. __name(_BSONError, "BSONError");
  777. var BSONError = _BSONError;
  778. var _BSONVersionError = class _BSONVersionError extends BSONError {
  779. get name() {
  780. return "BSONVersionError";
  781. }
  782. constructor() {
  783. super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
  784. }
  785. };
  786. __name(_BSONVersionError, "BSONVersionError");
  787. var BSONVersionError = _BSONVersionError;
  788. var _BSONRuntimeError = class _BSONRuntimeError extends BSONError {
  789. get name() {
  790. return "BSONRuntimeError";
  791. }
  792. constructor(message) {
  793. super(message);
  794. }
  795. };
  796. __name(_BSONRuntimeError, "BSONRuntimeError");
  797. var BSONRuntimeError = _BSONRuntimeError;
  798. function nodejsMathRandomBytes(byteLength) {
  799. return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
  800. }
  801. __name(nodejsMathRandomBytes, "nodejsMathRandomBytes");
  802. var nodejsRandomBytes = (() => {
  803. try {
  804. return require("crypto").randomBytes;
  805. } catch {
  806. return nodejsMathRandomBytes;
  807. }
  808. })();
  809. var nodeJsByteUtils = {
  810. toLocalBufferType(potentialBuffer) {
  811. if (Buffer.isBuffer(potentialBuffer)) {
  812. return potentialBuffer;
  813. }
  814. if (ArrayBuffer.isView(potentialBuffer)) {
  815. return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
  816. }
  817. const stringTag = (potentialBuffer == null ? void 0 : potentialBuffer[Symbol.toStringTag]) ?? Object.prototype.toString.call(potentialBuffer);
  818. if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") {
  819. return Buffer.from(potentialBuffer);
  820. }
  821. throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`);
  822. },
  823. allocate(size) {
  824. return Buffer.alloc(size);
  825. },
  826. equals(a, b) {
  827. return nodeJsByteUtils.toLocalBufferType(a).equals(b);
  828. },
  829. fromNumberArray(array) {
  830. return Buffer.from(array);
  831. },
  832. fromBase64(base64) {
  833. return Buffer.from(base64, "base64");
  834. },
  835. toBase64(buffer2) {
  836. return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64");
  837. },
  838. fromISO88591(codePoints) {
  839. return Buffer.from(codePoints, "binary");
  840. },
  841. toISO88591(buffer2) {
  842. return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary");
  843. },
  844. fromHex(hex) {
  845. return Buffer.from(hex, "hex");
  846. },
  847. toHex(buffer2) {
  848. return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex");
  849. },
  850. fromUTF8(text) {
  851. return Buffer.from(text, "utf8");
  852. },
  853. toUTF8(buffer2, start, end) {
  854. return nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8", start, end);
  855. },
  856. utf8ByteLength(input) {
  857. return Buffer.byteLength(input, "utf8");
  858. },
  859. encodeUTF8Into(buffer2, source, byteOffset) {
  860. return nodeJsByteUtils.toLocalBufferType(buffer2).write(source, byteOffset, void 0, "utf8");
  861. },
  862. randomBytes: nodejsRandomBytes
  863. };
  864. function isReactNative() {
  865. const { navigator: navigator2 } = globalThis;
  866. return typeof navigator2 === "object" && navigator2.product === "ReactNative";
  867. }
  868. __name(isReactNative, "isReactNative");
  869. function webMathRandomBytes(byteLength) {
  870. if (byteLength < 0) {
  871. throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
  872. }
  873. return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
  874. }
  875. __name(webMathRandomBytes, "webMathRandomBytes");
  876. var webRandomBytes = (() => {
  877. var _a2;
  878. const { crypto } = globalThis;
  879. if (crypto != null && typeof crypto.getRandomValues === "function") {
  880. return (byteLength) => {
  881. return crypto.getRandomValues(webByteUtils.allocate(byteLength));
  882. };
  883. } else {
  884. if (isReactNative()) {
  885. const { console } = globalThis;
  886. (_a2 = console == null ? void 0 : console.warn) == null ? void 0 : _a2.call(console, "BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.");
  887. }
  888. return webMathRandomBytes;
  889. }
  890. })();
  891. var HEX_DIGIT = /(\d|[a-f])/i;
  892. var webByteUtils = {
  893. toLocalBufferType(potentialUint8array) {
  894. const stringTag = (potentialUint8array == null ? void 0 : potentialUint8array[Symbol.toStringTag]) ?? Object.prototype.toString.call(potentialUint8array);
  895. if (stringTag === "Uint8Array") {
  896. return potentialUint8array;
  897. }
  898. if (ArrayBuffer.isView(potentialUint8array)) {
  899. return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
  900. }
  901. if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") {
  902. return new Uint8Array(potentialUint8array);
  903. }
  904. throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`);
  905. },
  906. allocate(size) {
  907. if (typeof size !== "number") {
  908. throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
  909. }
  910. return new Uint8Array(size);
  911. },
  912. equals(a, b) {
  913. if (a.byteLength !== b.byteLength) {
  914. return false;
  915. }
  916. for (let i = 0; i < a.byteLength; i++) {
  917. if (a[i] !== b[i]) {
  918. return false;
  919. }
  920. }
  921. return true;
  922. },
  923. fromNumberArray(array) {
  924. return Uint8Array.from(array);
  925. },
  926. fromBase64(base64) {
  927. return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
  928. },
  929. toBase64(uint8array) {
  930. return btoa(webByteUtils.toISO88591(uint8array));
  931. },
  932. fromISO88591(codePoints) {
  933. return Uint8Array.from(codePoints, (c) => c.charCodeAt(0) & 255);
  934. },
  935. toISO88591(uint8array) {
  936. return Array.from(Uint16Array.from(uint8array), (b) => String.fromCharCode(b)).join("");
  937. },
  938. fromHex(hex) {
  939. const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
  940. const buffer2 = [];
  941. for (let i = 0; i < evenLengthHex.length; i += 2) {
  942. const firstDigit = evenLengthHex[i];
  943. const secondDigit = evenLengthHex[i + 1];
  944. if (!HEX_DIGIT.test(firstDigit)) {
  945. break;
  946. }
  947. if (!HEX_DIGIT.test(secondDigit)) {
  948. break;
  949. }
  950. const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
  951. buffer2.push(hexDigit);
  952. }
  953. return Uint8Array.from(buffer2);
  954. },
  955. toHex(uint8array) {
  956. return Array.from(uint8array, (byte) => byte.toString(16).padStart(2, "0")).join("");
  957. },
  958. fromUTF8(text) {
  959. return new TextEncoder().encode(text);
  960. },
  961. toUTF8(uint8array, start, end) {
  962. return new TextDecoder("utf8", { fatal: false }).decode(uint8array.slice(start, end));
  963. },
  964. utf8ByteLength(input) {
  965. return webByteUtils.fromUTF8(input).byteLength;
  966. },
  967. encodeUTF8Into(buffer2, source, byteOffset) {
  968. const bytes = webByteUtils.fromUTF8(source);
  969. buffer2.set(bytes, byteOffset);
  970. return bytes.byteLength;
  971. },
  972. randomBytes: webRandomBytes
  973. };
  974. var _a;
  975. var hasGlobalBuffer = typeof Buffer === "function" && ((_a = Buffer.prototype) == null ? void 0 : _a._isBuffer) !== true;
  976. var ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
  977. var _BSONDataView = class _BSONDataView extends DataView {
  978. static fromUint8Array(input) {
  979. return new DataView(input.buffer, input.byteOffset, input.byteLength);
  980. }
  981. };
  982. __name(_BSONDataView, "BSONDataView");
  983. var BSONDataView = _BSONDataView;
  984. var _BSONValue = class _BSONValue {
  985. get [Symbol.for("@@mdb.bson.version")]() {
  986. return BSON_MAJOR_VERSION;
  987. }
  988. };
  989. __name(_BSONValue, "BSONValue");
  990. var BSONValue = _BSONValue;
  991. var _Binary = class _Binary extends BSONValue {
  992. get _bsontype() {
  993. return "Binary";
  994. }
  995. constructor(buffer2, subType) {
  996. super();
  997. if (!(buffer2 == null) && !(typeof buffer2 === "string") && !ArrayBuffer.isView(buffer2) && !(buffer2 instanceof ArrayBuffer) && !Array.isArray(buffer2)) {
  998. throw new BSONError("Binary can only be constructed from string, Buffer, TypedArray, or Array<number>");
  999. }
  1000. this.sub_type = subType ?? _Binary.BSON_BINARY_SUBTYPE_DEFAULT;
  1001. if (buffer2 == null) {
  1002. this.buffer = ByteUtils.allocate(_Binary.BUFFER_SIZE);
  1003. this.position = 0;
  1004. } else {
  1005. if (typeof buffer2 === "string") {
  1006. this.buffer = ByteUtils.fromISO88591(buffer2);
  1007. } else if (Array.isArray(buffer2)) {
  1008. this.buffer = ByteUtils.fromNumberArray(buffer2);
  1009. } else {
  1010. this.buffer = ByteUtils.toLocalBufferType(buffer2);
  1011. }
  1012. this.position = this.buffer.byteLength;
  1013. }
  1014. }
  1015. put(byteValue) {
  1016. if (typeof byteValue === "string" && byteValue.length !== 1) {
  1017. throw new BSONError("only accepts single character String");
  1018. } else if (typeof byteValue !== "number" && byteValue.length !== 1)
  1019. throw new BSONError("only accepts single character Uint8Array or Array");
  1020. let decodedByte;
  1021. if (typeof byteValue === "string") {
  1022. decodedByte = byteValue.charCodeAt(0);
  1023. } else if (typeof byteValue === "number") {
  1024. decodedByte = byteValue;
  1025. } else {
  1026. decodedByte = byteValue[0];
  1027. }
  1028. if (decodedByte < 0 || decodedByte > 255) {
  1029. throw new BSONError("only accepts number in a valid unsigned byte range 0-255");
  1030. }
  1031. if (this.buffer.byteLength > this.position) {
  1032. this.buffer[this.position++] = decodedByte;
  1033. } else {
  1034. const newSpace = ByteUtils.allocate(_Binary.BUFFER_SIZE + this.buffer.length);
  1035. newSpace.set(this.buffer, 0);
  1036. this.buffer = newSpace;
  1037. this.buffer[this.position++] = decodedByte;
  1038. }
  1039. }
  1040. write(sequence, offset) {
  1041. offset = typeof offset === "number" ? offset : this.position;
  1042. if (this.buffer.byteLength < offset + sequence.length) {
  1043. const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
  1044. newSpace.set(this.buffer, 0);
  1045. this.buffer = newSpace;
  1046. }
  1047. if (ArrayBuffer.isView(sequence)) {
  1048. this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
  1049. this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
  1050. } else if (typeof sequence === "string") {
  1051. const bytes = ByteUtils.fromISO88591(sequence);
  1052. this.buffer.set(bytes, offset);
  1053. this.position = offset + sequence.length > this.position ? offset + sequence.length : this.position;
  1054. }
  1055. }
  1056. read(position, length) {
  1057. length = length && length > 0 ? length : this.position;
  1058. return this.buffer.slice(position, position + length);
  1059. }
  1060. value(asRaw) {
  1061. asRaw = !!asRaw;
  1062. if (asRaw && this.buffer.length === this.position) {
  1063. return this.buffer;
  1064. }
  1065. if (asRaw) {
  1066. return this.buffer.slice(0, this.position);
  1067. }
  1068. return ByteUtils.toISO88591(this.buffer.subarray(0, this.position));
  1069. }
  1070. length() {
  1071. return this.position;
  1072. }
  1073. toJSON() {
  1074. return ByteUtils.toBase64(this.buffer);
  1075. }
  1076. toString(encoding) {
  1077. if (encoding === "hex")
  1078. return ByteUtils.toHex(this.buffer);
  1079. if (encoding === "base64")
  1080. return ByteUtils.toBase64(this.buffer);
  1081. if (encoding === "utf8" || encoding === "utf-8")
  1082. return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
  1083. return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
  1084. }
  1085. toExtendedJSON(options) {
  1086. options = options || {};
  1087. const base64String = ByteUtils.toBase64(this.buffer);
  1088. const subType = Number(this.sub_type).toString(16);
  1089. if (options.legacy) {
  1090. return {
  1091. $binary: base64String,
  1092. $type: subType.length === 1 ? "0" + subType : subType
  1093. };
  1094. }
  1095. return {
  1096. $binary: {
  1097. base64: base64String,
  1098. subType: subType.length === 1 ? "0" + subType : subType
  1099. }
  1100. };
  1101. }
  1102. toUUID() {
  1103. if (this.sub_type === _Binary.SUBTYPE_UUID) {
  1104. return new UUID(this.buffer.slice(0, this.position));
  1105. }
  1106. throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${_Binary.SUBTYPE_UUID}" is currently supported.`);
  1107. }
  1108. static createFromHexString(hex, subType) {
  1109. return new _Binary(ByteUtils.fromHex(hex), subType);
  1110. }
  1111. static createFromBase64(base64, subType) {
  1112. return new _Binary(ByteUtils.fromBase64(base64), subType);
  1113. }
  1114. static fromExtendedJSON(doc, options) {
  1115. options = options || {};
  1116. let data;
  1117. let type;
  1118. if ("$binary" in doc) {
  1119. if (options.legacy && typeof doc.$binary === "string" && "$type" in doc) {
  1120. type = doc.$type ? parseInt(doc.$type, 16) : 0;
  1121. data = ByteUtils.fromBase64(doc.$binary);
  1122. } else {
  1123. if (typeof doc.$binary !== "string") {
  1124. type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  1125. data = ByteUtils.fromBase64(doc.$binary.base64);
  1126. }
  1127. }
  1128. } else if ("$uuid" in doc) {
  1129. type = 4;
  1130. data = UUID.bytesFromString(doc.$uuid);
  1131. }
  1132. if (!data) {
  1133. throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
  1134. }
  1135. return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new _Binary(data, type);
  1136. }
  1137. [Symbol.for("nodejs.util.inspect.custom")]() {
  1138. return this.inspect();
  1139. }
  1140. inspect() {
  1141. const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
  1142. return `Binary.createFromBase64("${base64}", ${this.sub_type})`;
  1143. }
  1144. };
  1145. __name(_Binary, "Binary");
  1146. var Binary = _Binary;
  1147. Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
  1148. Binary.BUFFER_SIZE = 256;
  1149. Binary.SUBTYPE_DEFAULT = 0;
  1150. Binary.SUBTYPE_FUNCTION = 1;
  1151. Binary.SUBTYPE_BYTE_ARRAY = 2;
  1152. Binary.SUBTYPE_UUID_OLD = 3;
  1153. Binary.SUBTYPE_UUID = 4;
  1154. Binary.SUBTYPE_MD5 = 5;
  1155. Binary.SUBTYPE_ENCRYPTED = 6;
  1156. Binary.SUBTYPE_COLUMN = 7;
  1157. Binary.SUBTYPE_USER_DEFINED = 128;
  1158. var UUID_BYTE_LENGTH = 16;
  1159. var UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
  1160. var UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
  1161. var _UUID = class _UUID extends Binary {
  1162. constructor(input) {
  1163. let bytes;
  1164. if (input == null) {
  1165. bytes = _UUID.generate();
  1166. } else if (input instanceof _UUID) {
  1167. bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
  1168. } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
  1169. bytes = ByteUtils.toLocalBufferType(input);
  1170. } else if (typeof input === "string") {
  1171. bytes = _UUID.bytesFromString(input);
  1172. } else {
  1173. throw new BSONError("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).");
  1174. }
  1175. super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
  1176. }
  1177. get id() {
  1178. return this.buffer;
  1179. }
  1180. set id(value) {
  1181. this.buffer = value;
  1182. }
  1183. toHexString(includeDashes = true) {
  1184. if (includeDashes) {
  1185. return [
  1186. ByteUtils.toHex(this.buffer.subarray(0, 4)),
  1187. ByteUtils.toHex(this.buffer.subarray(4, 6)),
  1188. ByteUtils.toHex(this.buffer.subarray(6, 8)),
  1189. ByteUtils.toHex(this.buffer.subarray(8, 10)),
  1190. ByteUtils.toHex(this.buffer.subarray(10, 16))
  1191. ].join("-");
  1192. }
  1193. return ByteUtils.toHex(this.buffer);
  1194. }
  1195. toString(encoding) {
  1196. if (encoding === "hex")
  1197. return ByteUtils.toHex(this.id);
  1198. if (encoding === "base64")
  1199. return ByteUtils.toBase64(this.id);
  1200. return this.toHexString();
  1201. }
  1202. toJSON() {
  1203. return this.toHexString();
  1204. }
  1205. equals(otherId) {
  1206. if (!otherId) {
  1207. return false;
  1208. }
  1209. if (otherId instanceof _UUID) {
  1210. return ByteUtils.equals(otherId.id, this.id);
  1211. }
  1212. try {
  1213. return ByteUtils.equals(new _UUID(otherId).id, this.id);
  1214. } catch {
  1215. return false;
  1216. }
  1217. }
  1218. toBinary() {
  1219. return new Binary(this.id, Binary.SUBTYPE_UUID);
  1220. }
  1221. static generate() {
  1222. const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
  1223. bytes[6] = bytes[6] & 15 | 64;
  1224. bytes[8] = bytes[8] & 63 | 128;
  1225. return bytes;
  1226. }
  1227. static isValid(input) {
  1228. if (!input) {
  1229. return false;
  1230. }
  1231. if (typeof input === "string") {
  1232. return _UUID.isValidUUIDString(input);
  1233. }
  1234. if (isUint8Array(input)) {
  1235. return input.byteLength === UUID_BYTE_LENGTH;
  1236. }
  1237. return input._bsontype === "Binary" && input.sub_type === this.SUBTYPE_UUID && input.buffer.byteLength === 16;
  1238. }
  1239. static createFromHexString(hexString) {
  1240. const buffer2 = _UUID.bytesFromString(hexString);
  1241. return new _UUID(buffer2);
  1242. }
  1243. static createFromBase64(base64) {
  1244. return new _UUID(ByteUtils.fromBase64(base64));
  1245. }
  1246. static bytesFromString(representation) {
  1247. if (!_UUID.isValidUUIDString(representation)) {
  1248. throw new BSONError("UUID string representation must be 32 hex digits or canonical hyphenated representation");
  1249. }
  1250. return ByteUtils.fromHex(representation.replace(/-/g, ""));
  1251. }
  1252. static isValidUUIDString(representation) {
  1253. return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
  1254. }
  1255. [Symbol.for("nodejs.util.inspect.custom")]() {
  1256. return this.inspect();
  1257. }
  1258. inspect() {
  1259. return `new UUID("${this.toHexString()}")`;
  1260. }
  1261. };
  1262. __name(_UUID, "UUID");
  1263. var UUID = _UUID;
  1264. UUID.cacheHexString = false;
  1265. var _Code = class _Code extends BSONValue {
  1266. get _bsontype() {
  1267. return "Code";
  1268. }
  1269. constructor(code, scope) {
  1270. super();
  1271. this.code = code.toString();
  1272. this.scope = scope ?? null;
  1273. }
  1274. toJSON() {
  1275. if (this.scope != null) {
  1276. return { code: this.code, scope: this.scope };
  1277. }
  1278. return { code: this.code };
  1279. }
  1280. toExtendedJSON() {
  1281. if (this.scope) {
  1282. return { $code: this.code, $scope: this.scope };
  1283. }
  1284. return { $code: this.code };
  1285. }
  1286. static fromExtendedJSON(doc) {
  1287. return new _Code(doc.$code, doc.$scope);
  1288. }
  1289. [Symbol.for("nodejs.util.inspect.custom")]() {
  1290. return this.inspect();
  1291. }
  1292. inspect() {
  1293. const codeJson = this.toJSON();
  1294. return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ""})`;
  1295. }
  1296. };
  1297. __name(_Code, "Code");
  1298. var Code = _Code;
  1299. function isDBRefLike(value) {
  1300. return value != null && typeof value === "object" && "$id" in value && value.$id != null && "$ref" in value && typeof value.$ref === "string" && (!("$db" in value) || "$db" in value && typeof value.$db === "string");
  1301. }
  1302. __name(isDBRefLike, "isDBRefLike");
  1303. var _DBRef = class _DBRef extends BSONValue {
  1304. get _bsontype() {
  1305. return "DBRef";
  1306. }
  1307. constructor(collection, oid, db, fields) {
  1308. super();
  1309. const parts = collection.split(".");
  1310. if (parts.length === 2) {
  1311. db = parts.shift();
  1312. collection = parts.shift();
  1313. }
  1314. this.collection = collection;
  1315. this.oid = oid;
  1316. this.db = db;
  1317. this.fields = fields || {};
  1318. }
  1319. get namespace() {
  1320. return this.collection;
  1321. }
  1322. set namespace(value) {
  1323. this.collection = value;
  1324. }
  1325. toJSON() {
  1326. const o = Object.assign({
  1327. $ref: this.collection,
  1328. $id: this.oid
  1329. }, this.fields);
  1330. if (this.db != null)
  1331. o.$db = this.db;
  1332. return o;
  1333. }
  1334. toExtendedJSON(options) {
  1335. options = options || {};
  1336. let o = {
  1337. $ref: this.collection,
  1338. $id: this.oid
  1339. };
  1340. if (options.legacy) {
  1341. return o;
  1342. }
  1343. if (this.db)
  1344. o.$db = this.db;
  1345. o = Object.assign(o, this.fields);
  1346. return o;
  1347. }
  1348. static fromExtendedJSON(doc) {
  1349. const copy = Object.assign({}, doc);
  1350. delete copy.$ref;
  1351. delete copy.$id;
  1352. delete copy.$db;
  1353. return new _DBRef(doc.$ref, doc.$id, doc.$db, copy);
  1354. }
  1355. [Symbol.for("nodejs.util.inspect.custom")]() {
  1356. return this.inspect();
  1357. }
  1358. inspect() {
  1359. const oid = this.oid === void 0 || this.oid.toString === void 0 ? this.oid : this.oid.toString();
  1360. return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db ? `, "${this.db}"` : ""})`;
  1361. }
  1362. };
  1363. __name(_DBRef, "DBRef");
  1364. var DBRef = _DBRef;
  1365. var wasm = void 0;
  1366. try {
  1367. wasm = new WebAssembly.Instance(new WebAssembly.Module(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;
  1368. } catch {
  1369. }
  1370. var TWO_PWR_16_DBL = 1 << 16;
  1371. var TWO_PWR_24_DBL = 1 << 24;
  1372. var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  1373. var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  1374. var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  1375. var INT_CACHE = {};
  1376. var UINT_CACHE = {};
  1377. var MAX_INT64_STRING_LENGTH = 20;
  1378. var DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
  1379. var _Long = class _Long extends BSONValue {
  1380. get _bsontype() {
  1381. return "Long";
  1382. }
  1383. get __isLong__() {
  1384. return true;
  1385. }
  1386. constructor(low = 0, high, unsigned) {
  1387. super();
  1388. if (typeof low === "bigint") {
  1389. Object.assign(this, _Long.fromBigInt(low, !!high));
  1390. } else if (typeof low === "string") {
  1391. Object.assign(this, _Long.fromString(low, !!high));
  1392. } else {
  1393. this.low = low | 0;
  1394. this.high = high | 0;
  1395. this.unsigned = !!unsigned;
  1396. }
  1397. }
  1398. static fromBits(lowBits, highBits, unsigned) {
  1399. return new _Long(lowBits, highBits, unsigned);
  1400. }
  1401. static fromInt(value, unsigned) {
  1402. let obj, cachedObj, cache;
  1403. if (unsigned) {
  1404. value >>>= 0;
  1405. if (cache = 0 <= value && value < 256) {
  1406. cachedObj = UINT_CACHE[value];
  1407. if (cachedObj)
  1408. return cachedObj;
  1409. }
  1410. obj = _Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  1411. if (cache)
  1412. UINT_CACHE[value] = obj;
  1413. return obj;
  1414. } else {
  1415. value |= 0;
  1416. if (cache = -128 <= value && value < 128) {
  1417. cachedObj = INT_CACHE[value];
  1418. if (cachedObj)
  1419. return cachedObj;
  1420. }
  1421. obj = _Long.fromBits(value, value < 0 ? -1 : 0, false);
  1422. if (cache)
  1423. INT_CACHE[value] = obj;
  1424. return obj;
  1425. }
  1426. }
  1427. static fromNumber(value, unsigned) {
  1428. if (isNaN(value))
  1429. return unsigned ? _Long.UZERO : _Long.ZERO;
  1430. if (unsigned) {
  1431. if (value < 0)
  1432. return _Long.UZERO;
  1433. if (value >= TWO_PWR_64_DBL)
  1434. return _Long.MAX_UNSIGNED_VALUE;
  1435. } else {
  1436. if (value <= -TWO_PWR_63_DBL)
  1437. return _Long.MIN_VALUE;
  1438. if (value + 1 >= TWO_PWR_63_DBL)
  1439. return _Long.MAX_VALUE;
  1440. }
  1441. if (value < 0)
  1442. return _Long.fromNumber(-value, unsigned).neg();
  1443. return _Long.fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
  1444. }
  1445. static fromBigInt(value, unsigned) {
  1446. return _Long.fromString(value.toString(), unsigned);
  1447. }
  1448. static fromString(str, unsigned, radix) {
  1449. if (str.length === 0)
  1450. throw new BSONError("empty string");
  1451. if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
  1452. return _Long.ZERO;
  1453. if (typeof unsigned === "number") {
  1454. radix = unsigned, unsigned = false;
  1455. } else {
  1456. unsigned = !!unsigned;
  1457. }
  1458. radix = radix || 10;
  1459. if (radix < 2 || 36 < radix)
  1460. throw new BSONError("radix");
  1461. let p;
  1462. if ((p = str.indexOf("-")) > 0)
  1463. throw new BSONError("interior hyphen");
  1464. else if (p === 0) {
  1465. return _Long.fromString(str.substring(1), unsigned, radix).neg();
  1466. }
  1467. const radixToPower = _Long.fromNumber(Math.pow(radix, 8));
  1468. let result = _Long.ZERO;
  1469. for (let i = 0; i < str.length; i += 8) {
  1470. const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
  1471. if (size < 8) {
  1472. const power = _Long.fromNumber(Math.pow(radix, size));
  1473. result = result.mul(power).add(_Long.fromNumber(value));
  1474. } else {
  1475. result = result.mul(radixToPower);
  1476. result = result.add(_Long.fromNumber(value));
  1477. }
  1478. }
  1479. result.unsigned = unsigned;
  1480. return result;
  1481. }
  1482. static fromBytes(bytes, unsigned, le) {
  1483. return le ? _Long.fromBytesLE(bytes, unsigned) : _Long.fromBytesBE(bytes, unsigned);
  1484. }
  1485. static fromBytesLE(bytes, unsigned) {
  1486. 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);
  1487. }
  1488. static fromBytesBE(bytes, unsigned) {
  1489. 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);
  1490. }
  1491. static isLong(value) {
  1492. return value != null && typeof value === "object" && "__isLong__" in value && value.__isLong__ === true;
  1493. }
  1494. static fromValue(val, unsigned) {
  1495. if (typeof val === "number")
  1496. return _Long.fromNumber(val, unsigned);
  1497. if (typeof val === "string")
  1498. return _Long.fromString(val, unsigned);
  1499. return _Long.fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
  1500. }
  1501. add(addend) {
  1502. if (!_Long.isLong(addend))
  1503. addend = _Long.fromValue(addend);
  1504. const a48 = this.high >>> 16;
  1505. const a32 = this.high & 65535;
  1506. const a16 = this.low >>> 16;
  1507. const a00 = this.low & 65535;
  1508. const b48 = addend.high >>> 16;
  1509. const b32 = addend.high & 65535;
  1510. const b16 = addend.low >>> 16;
  1511. const b00 = addend.low & 65535;
  1512. let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1513. c00 += a00 + b00;
  1514. c16 += c00 >>> 16;
  1515. c00 &= 65535;
  1516. c16 += a16 + b16;
  1517. c32 += c16 >>> 16;
  1518. c16 &= 65535;
  1519. c32 += a32 + b32;
  1520. c48 += c32 >>> 16;
  1521. c32 &= 65535;
  1522. c48 += a48 + b48;
  1523. c48 &= 65535;
  1524. return _Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
  1525. }
  1526. and(other) {
  1527. if (!_Long.isLong(other))
  1528. other = _Long.fromValue(other);
  1529. return _Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  1530. }
  1531. compare(other) {
  1532. if (!_Long.isLong(other))
  1533. other = _Long.fromValue(other);
  1534. if (this.eq(other))
  1535. return 0;
  1536. const thisNeg = this.isNegative(), otherNeg = other.isNegative();
  1537. if (thisNeg && !otherNeg)
  1538. return -1;
  1539. if (!thisNeg && otherNeg)
  1540. return 1;
  1541. if (!this.unsigned)
  1542. return this.sub(other).isNegative() ? -1 : 1;
  1543. return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
  1544. }
  1545. comp(other) {
  1546. return this.compare(other);
  1547. }
  1548. divide(divisor) {
  1549. if (!_Long.isLong(divisor))
  1550. divisor = _Long.fromValue(divisor);
  1551. if (divisor.isZero())
  1552. throw new BSONError("division by zero");
  1553. if (wasm) {
  1554. if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
  1555. return this;
  1556. }
  1557. const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
  1558. return _Long.fromBits(low, wasm.get_high(), this.unsigned);
  1559. }
  1560. if (this.isZero())
  1561. return this.unsigned ? _Long.UZERO : _Long.ZERO;
  1562. let approx, rem, res;
  1563. if (!this.unsigned) {
  1564. if (this.eq(_Long.MIN_VALUE)) {
  1565. if (divisor.eq(_Long.ONE) || divisor.eq(_Long.NEG_ONE))
  1566. return _Long.MIN_VALUE;
  1567. else if (divisor.eq(_Long.MIN_VALUE))
  1568. return _Long.ONE;
  1569. else {
  1570. const halfThis = this.shr(1);
  1571. approx = halfThis.div(divisor).shl(1);
  1572. if (approx.eq(_Long.ZERO)) {
  1573. return divisor.isNegative() ? _Long.ONE : _Long.NEG_ONE;
  1574. } else {
  1575. rem = this.sub(divisor.mul(approx));
  1576. res = approx.add(rem.div(divisor));
  1577. return res;
  1578. }
  1579. }
  1580. } else if (divisor.eq(_Long.MIN_VALUE))
  1581. return this.unsigned ? _Long.UZERO : _Long.ZERO;
  1582. if (this.isNegative()) {
  1583. if (divisor.isNegative())
  1584. return this.neg().div(divisor.neg());
  1585. return this.neg().div(divisor).neg();
  1586. } else if (divisor.isNegative())
  1587. return this.div(divisor.neg()).neg();
  1588. res = _Long.ZERO;
  1589. } else {
  1590. if (!divisor.unsigned)
  1591. divisor = divisor.toUnsigned();
  1592. if (divisor.gt(this))
  1593. return _Long.UZERO;
  1594. if (divisor.gt(this.shru(1)))
  1595. return _Long.UONE;
  1596. res = _Long.UZERO;
  1597. }
  1598. rem = this;
  1599. while (rem.gte(divisor)) {
  1600. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  1601. const log2 = Math.ceil(Math.log(approx) / Math.LN2);
  1602. const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
  1603. let approxRes = _Long.fromNumber(approx);
  1604. let approxRem = approxRes.mul(divisor);
  1605. while (approxRem.isNegative() || approxRem.gt(rem)) {
  1606. approx -= delta;
  1607. approxRes = _Long.fromNumber(approx, this.unsigned);
  1608. approxRem = approxRes.mul(divisor);
  1609. }
  1610. if (approxRes.isZero())
  1611. approxRes = _Long.ONE;
  1612. res = res.add(approxRes);
  1613. rem = rem.sub(approxRem);
  1614. }
  1615. return res;
  1616. }
  1617. div(divisor) {
  1618. return this.divide(divisor);
  1619. }
  1620. equals(other) {
  1621. if (!_Long.isLong(other))
  1622. other = _Long.fromValue(other);
  1623. if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
  1624. return false;
  1625. return this.high === other.high && this.low === other.low;
  1626. }
  1627. eq(other) {
  1628. return this.equals(other);
  1629. }
  1630. getHighBits() {
  1631. return this.high;
  1632. }
  1633. getHighBitsUnsigned() {
  1634. return this.high >>> 0;
  1635. }
  1636. getLowBits() {
  1637. return this.low;
  1638. }
  1639. getLowBitsUnsigned() {
  1640. return this.low >>> 0;
  1641. }
  1642. getNumBitsAbs() {
  1643. if (this.isNegative()) {
  1644. return this.eq(_Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  1645. }
  1646. const val = this.high !== 0 ? this.high : this.low;
  1647. let bit;
  1648. for (bit = 31; bit > 0; bit--)
  1649. if ((val & 1 << bit) !== 0)
  1650. break;
  1651. return this.high !== 0 ? bit + 33 : bit + 1;
  1652. }
  1653. greaterThan(other) {
  1654. return this.comp(other) > 0;
  1655. }
  1656. gt(other) {
  1657. return this.greaterThan(other);
  1658. }
  1659. greaterThanOrEqual(other) {
  1660. return this.comp(other) >= 0;
  1661. }
  1662. gte(other) {
  1663. return this.greaterThanOrEqual(other);
  1664. }
  1665. ge(other) {
  1666. return this.greaterThanOrEqual(other);
  1667. }
  1668. isEven() {
  1669. return (this.low & 1) === 0;
  1670. }
  1671. isNegative() {
  1672. return !this.unsigned && this.high < 0;
  1673. }
  1674. isOdd() {
  1675. return (this.low & 1) === 1;
  1676. }
  1677. isPositive() {
  1678. return this.unsigned || this.high >= 0;
  1679. }
  1680. isZero() {
  1681. return this.high === 0 && this.low === 0;
  1682. }
  1683. lessThan(other) {
  1684. return this.comp(other) < 0;
  1685. }
  1686. lt(other) {
  1687. return this.lessThan(other);
  1688. }
  1689. lessThanOrEqual(other) {
  1690. return this.comp(other) <= 0;
  1691. }
  1692. lte(other) {
  1693. return this.lessThanOrEqual(other);
  1694. }
  1695. modulo(divisor) {
  1696. if (!_Long.isLong(divisor))
  1697. divisor = _Long.fromValue(divisor);
  1698. if (wasm) {
  1699. const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
  1700. return _Long.fromBits(low, wasm.get_high(), this.unsigned);
  1701. }
  1702. return this.sub(this.div(divisor).mul(divisor));
  1703. }
  1704. mod(divisor) {
  1705. return this.modulo(divisor);
  1706. }
  1707. rem(divisor) {
  1708. return this.modulo(divisor);
  1709. }
  1710. multiply(multiplier) {
  1711. if (this.isZero())
  1712. return _Long.ZERO;
  1713. if (!_Long.isLong(multiplier))
  1714. multiplier = _Long.fromValue(multiplier);
  1715. if (wasm) {
  1716. const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
  1717. return _Long.fromBits(low, wasm.get_high(), this.unsigned);
  1718. }
  1719. if (multiplier.isZero())
  1720. return _Long.ZERO;
  1721. if (this.eq(_Long.MIN_VALUE))
  1722. return multiplier.isOdd() ? _Long.MIN_VALUE : _Long.ZERO;
  1723. if (multiplier.eq(_Long.MIN_VALUE))
  1724. return this.isOdd() ? _Long.MIN_VALUE : _Long.ZERO;
  1725. if (this.isNegative()) {
  1726. if (multiplier.isNegative())
  1727. return this.neg().mul(multiplier.neg());
  1728. else
  1729. return this.neg().mul(multiplier).neg();
  1730. } else if (multiplier.isNegative())
  1731. return this.mul(multiplier.neg()).neg();
  1732. if (this.lt(_Long.TWO_PWR_24) && multiplier.lt(_Long.TWO_PWR_24))
  1733. return _Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  1734. const a48 = this.high >>> 16;
  1735. const a32 = this.high & 65535;
  1736. const a16 = this.low >>> 16;
  1737. const a00 = this.low & 65535;
  1738. const b48 = multiplier.high >>> 16;
  1739. const b32 = multiplier.high & 65535;
  1740. const b16 = multiplier.low >>> 16;
  1741. const b00 = multiplier.low & 65535;
  1742. let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1743. c00 += a00 * b00;
  1744. c16 += c00 >>> 16;
  1745. c00 &= 65535;
  1746. c16 += a16 * b00;
  1747. c32 += c16 >>> 16;
  1748. c16 &= 65535;
  1749. c16 += a00 * b16;
  1750. c32 += c16 >>> 16;
  1751. c16 &= 65535;
  1752. c32 += a32 * b00;
  1753. c48 += c32 >>> 16;
  1754. c32 &= 65535;
  1755. c32 += a16 * b16;
  1756. c48 += c32 >>> 16;
  1757. c32 &= 65535;
  1758. c32 += a00 * b32;
  1759. c48 += c32 >>> 16;
  1760. c32 &= 65535;
  1761. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  1762. c48 &= 65535;
  1763. return _Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
  1764. }
  1765. mul(multiplier) {
  1766. return this.multiply(multiplier);
  1767. }
  1768. negate() {
  1769. if (!this.unsigned && this.eq(_Long.MIN_VALUE))
  1770. return _Long.MIN_VALUE;
  1771. return this.not().add(_Long.ONE);
  1772. }
  1773. neg() {
  1774. return this.negate();
  1775. }
  1776. not() {
  1777. return _Long.fromBits(~this.low, ~this.high, this.unsigned);
  1778. }
  1779. notEquals(other) {
  1780. return !this.equals(other);
  1781. }
  1782. neq(other) {
  1783. return this.notEquals(other);
  1784. }
  1785. ne(other) {
  1786. return this.notEquals(other);
  1787. }
  1788. or(other) {
  1789. if (!_Long.isLong(other))
  1790. other = _Long.fromValue(other);
  1791. return _Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  1792. }
  1793. shiftLeft(numBits) {
  1794. if (_Long.isLong(numBits))
  1795. numBits = numBits.toInt();
  1796. if ((numBits &= 63) === 0)
  1797. return this;
  1798. else if (numBits < 32)
  1799. return _Long.fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
  1800. else
  1801. return _Long.fromBits(0, this.low << numBits - 32, this.unsigned);
  1802. }
  1803. shl(numBits) {
  1804. return this.shiftLeft(numBits);
  1805. }
  1806. shiftRight(numBits) {
  1807. if (_Long.isLong(numBits))
  1808. numBits = numBits.toInt();
  1809. if ((numBits &= 63) === 0)
  1810. return this;
  1811. else if (numBits < 32)
  1812. return _Long.fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
  1813. else
  1814. return _Long.fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
  1815. }
  1816. shr(numBits) {
  1817. return this.shiftRight(numBits);
  1818. }
  1819. shiftRightUnsigned(numBits) {
  1820. if (_Long.isLong(numBits))
  1821. numBits = numBits.toInt();
  1822. numBits &= 63;
  1823. if (numBits === 0)
  1824. return this;
  1825. else {
  1826. const high = this.high;
  1827. if (numBits < 32) {
  1828. const low = this.low;
  1829. return _Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
  1830. } else if (numBits === 32)
  1831. return _Long.fromBits(high, 0, this.unsigned);
  1832. else
  1833. return _Long.fromBits(high >>> numBits - 32, 0, this.unsigned);
  1834. }
  1835. }
  1836. shr_u(numBits) {
  1837. return this.shiftRightUnsigned(numBits);
  1838. }
  1839. shru(numBits) {
  1840. return this.shiftRightUnsigned(numBits);
  1841. }
  1842. subtract(subtrahend) {
  1843. if (!_Long.isLong(subtrahend))
  1844. subtrahend = _Long.fromValue(subtrahend);
  1845. return this.add(subtrahend.neg());
  1846. }
  1847. sub(subtrahend) {
  1848. return this.subtract(subtrahend);
  1849. }
  1850. toInt() {
  1851. return this.unsigned ? this.low >>> 0 : this.low;
  1852. }
  1853. toNumber() {
  1854. if (this.unsigned)
  1855. return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  1856. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  1857. }
  1858. toBigInt() {
  1859. return BigInt(this.toString());
  1860. }
  1861. toBytes(le) {
  1862. return le ? this.toBytesLE() : this.toBytesBE();
  1863. }
  1864. toBytesLE() {
  1865. const hi = this.high, lo = this.low;
  1866. return [
  1867. lo & 255,
  1868. lo >>> 8 & 255,
  1869. lo >>> 16 & 255,
  1870. lo >>> 24,
  1871. hi & 255,
  1872. hi >>> 8 & 255,
  1873. hi >>> 16 & 255,
  1874. hi >>> 24
  1875. ];
  1876. }
  1877. toBytesBE() {
  1878. const hi = this.high, lo = this.low;
  1879. return [
  1880. hi >>> 24,
  1881. hi >>> 16 & 255,
  1882. hi >>> 8 & 255,
  1883. hi & 255,
  1884. lo >>> 24,
  1885. lo >>> 16 & 255,
  1886. lo >>> 8 & 255,
  1887. lo & 255
  1888. ];
  1889. }
  1890. toSigned() {
  1891. if (!this.unsigned)
  1892. return this;
  1893. return _Long.fromBits(this.low, this.high, false);
  1894. }
  1895. toString(radix) {
  1896. radix = radix || 10;
  1897. if (radix < 2 || 36 < radix)
  1898. throw new BSONError("radix");
  1899. if (this.isZero())
  1900. return "0";
  1901. if (this.isNegative()) {
  1902. if (this.eq(_Long.MIN_VALUE)) {
  1903. const radixLong = _Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
  1904. return div.toString(radix) + rem1.toInt().toString(radix);
  1905. } else
  1906. return "-" + this.neg().toString(radix);
  1907. }
  1908. const radixToPower = _Long.fromNumber(Math.pow(radix, 6), this.unsigned);
  1909. let rem = this;
  1910. let result = "";
  1911. while (true) {
  1912. const remDiv = rem.div(radixToPower);
  1913. const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
  1914. let digits = intval.toString(radix);
  1915. rem = remDiv;
  1916. if (rem.isZero()) {
  1917. return digits + result;
  1918. } else {
  1919. while (digits.length < 6)
  1920. digits = "0" + digits;
  1921. result = "" + digits + result;
  1922. }
  1923. }
  1924. }
  1925. toUnsigned() {
  1926. if (this.unsigned)
  1927. return this;
  1928. return _Long.fromBits(this.low, this.high, true);
  1929. }
  1930. xor(other) {
  1931. if (!_Long.isLong(other))
  1932. other = _Long.fromValue(other);
  1933. return _Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  1934. }
  1935. eqz() {
  1936. return this.isZero();
  1937. }
  1938. le(other) {
  1939. return this.lessThanOrEqual(other);
  1940. }
  1941. toExtendedJSON(options) {
  1942. if (options && options.relaxed)
  1943. return this.toNumber();
  1944. return { $numberLong: this.toString() };
  1945. }
  1946. static fromExtendedJSON(doc, options) {
  1947. const { useBigInt64 = false, relaxed = true } = { ...options };
  1948. if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
  1949. throw new BSONError("$numberLong string is too long");
  1950. }
  1951. if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
  1952. throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
  1953. }
  1954. if (useBigInt64) {
  1955. const bigIntResult = BigInt(doc.$numberLong);
  1956. return BigInt.asIntN(64, bigIntResult);
  1957. }
  1958. const longResult = _Long.fromString(doc.$numberLong);
  1959. if (relaxed) {
  1960. return longResult.toNumber();
  1961. }
  1962. return longResult;
  1963. }
  1964. [Symbol.for("nodejs.util.inspect.custom")]() {
  1965. return this.inspect();
  1966. }
  1967. inspect() {
  1968. return `new Long("${this.toString()}"${this.unsigned ? ", true" : ""})`;
  1969. }
  1970. };
  1971. __name(_Long, "Long");
  1972. var Long = _Long;
  1973. Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
  1974. Long.MAX_UNSIGNED_VALUE = Long.fromBits(4294967295 | 0, 4294967295 | 0, true);
  1975. Long.ZERO = Long.fromInt(0);
  1976. Long.UZERO = Long.fromInt(0, true);
  1977. Long.ONE = Long.fromInt(1);
  1978. Long.UONE = Long.fromInt(1, true);
  1979. Long.NEG_ONE = Long.fromInt(-1);
  1980. Long.MAX_VALUE = Long.fromBits(4294967295 | 0, 2147483647 | 0, false);
  1981. Long.MIN_VALUE = Long.fromBits(0, 2147483648 | 0, false);
  1982. var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  1983. var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  1984. var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  1985. var EXPONENT_MAX = 6111;
  1986. var EXPONENT_MIN = -6176;
  1987. var EXPONENT_BIAS = 6176;
  1988. var MAX_DIGITS = 34;
  1989. var NAN_BUFFER = ByteUtils.fromNumberArray([
  1990. 124,
  1991. 0,
  1992. 0,
  1993. 0,
  1994. 0,
  1995. 0,
  1996. 0,
  1997. 0,
  1998. 0,
  1999. 0,
  2000. 0,
  2001. 0,
  2002. 0,
  2003. 0,
  2004. 0,
  2005. 0
  2006. ].reverse());
  2007. var INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
  2008. 248,
  2009. 0,
  2010. 0,
  2011. 0,
  2012. 0,
  2013. 0,
  2014. 0,
  2015. 0,
  2016. 0,
  2017. 0,
  2018. 0,
  2019. 0,
  2020. 0,
  2021. 0,
  2022. 0,
  2023. 0
  2024. ].reverse());
  2025. var INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
  2026. 120,
  2027. 0,
  2028. 0,
  2029. 0,
  2030. 0,
  2031. 0,
  2032. 0,
  2033. 0,
  2034. 0,
  2035. 0,
  2036. 0,
  2037. 0,
  2038. 0,
  2039. 0,
  2040. 0,
  2041. 0
  2042. ].reverse());
  2043. var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  2044. var COMBINATION_MASK = 31;
  2045. var EXPONENT_MASK = 16383;
  2046. var COMBINATION_INFINITY = 30;
  2047. var COMBINATION_NAN = 31;
  2048. function isDigit(value) {
  2049. return !isNaN(parseInt(value, 10));
  2050. }
  2051. __name(isDigit, "isDigit");
  2052. function divideu128(value) {
  2053. const DIVISOR = Long.fromNumber(1e3 * 1e3 * 1e3);
  2054. let _rem = Long.fromNumber(0);
  2055. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  2056. return { quotient: value, rem: _rem };
  2057. }
  2058. for (let i = 0; i <= 3; i++) {
  2059. _rem = _rem.shiftLeft(32);
  2060. _rem = _rem.add(new Long(value.parts[i], 0));
  2061. value.parts[i] = _rem.div(DIVISOR).low;
  2062. _rem = _rem.modulo(DIVISOR);
  2063. }
  2064. return { quotient: value, rem: _rem };
  2065. }
  2066. __name(divideu128, "divideu128");
  2067. function multiply64x2(left, right) {
  2068. if (!left && !right) {
  2069. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  2070. }
  2071. const leftHigh = left.shiftRightUnsigned(32);
  2072. const leftLow = new Long(left.getLowBits(), 0);
  2073. const rightHigh = right.shiftRightUnsigned(32);
  2074. const rightLow = new Long(right.getLowBits(), 0);
  2075. let productHigh = leftHigh.multiply(rightHigh);
  2076. let productMid = leftHigh.multiply(rightLow);
  2077. const productMid2 = leftLow.multiply(rightHigh);
  2078. let productLow = leftLow.multiply(rightLow);
  2079. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  2080. productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32));
  2081. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  2082. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  2083. return { high: productHigh, low: productLow };
  2084. }
  2085. __name(multiply64x2, "multiply64x2");
  2086. function lessThan(left, right) {
  2087. const uhleft = left.high >>> 0;
  2088. const uhright = right.high >>> 0;
  2089. if (uhleft < uhright) {
  2090. return true;
  2091. } else if (uhleft === uhright) {
  2092. const ulleft = left.low >>> 0;
  2093. const ulright = right.low >>> 0;
  2094. if (ulleft < ulright)
  2095. return true;
  2096. }
  2097. return false;
  2098. }
  2099. __name(lessThan, "lessThan");
  2100. function invalidErr(string, message) {
  2101. throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
  2102. }
  2103. __name(invalidErr, "invalidErr");
  2104. var _Decimal128 = class _Decimal128 extends BSONValue {
  2105. get _bsontype() {
  2106. return "Decimal128";
  2107. }
  2108. constructor(bytes) {
  2109. super();
  2110. if (typeof bytes === "string") {
  2111. this.bytes = _Decimal128.fromString(bytes).bytes;
  2112. } else if (isUint8Array(bytes)) {
  2113. if (bytes.byteLength !== 16) {
  2114. throw new BSONError("Decimal128 must take a Buffer of 16 bytes");
  2115. }
  2116. this.bytes = bytes;
  2117. } else {
  2118. throw new BSONError("Decimal128 must take a Buffer or string");
  2119. }
  2120. }
  2121. static fromString(representation) {
  2122. return _Decimal128._fromString(representation, { allowRounding: false });
  2123. }
  2124. static fromStringWithRounding(representation) {
  2125. return _Decimal128._fromString(representation, { allowRounding: true });
  2126. }
  2127. static _fromString(representation, options) {
  2128. let isNegative = false;
  2129. let sawSign = false;
  2130. let sawRadix = false;
  2131. let foundNonZero = false;
  2132. let significantDigits = 0;
  2133. let nDigitsRead = 0;
  2134. let nDigits = 0;
  2135. let radixPosition = 0;
  2136. let firstNonZero = 0;
  2137. const digits = [0];
  2138. let nDigitsStored = 0;
  2139. let digitsInsert = 0;
  2140. let lastDigit = 0;
  2141. let exponent = 0;
  2142. let significandHigh = new Long(0, 0);
  2143. let significandLow = new Long(0, 0);
  2144. let biasedExponent = 0;
  2145. let index = 0;
  2146. if (representation.length >= 7e3) {
  2147. throw new BSONError("" + representation + " not a valid Decimal128 string");
  2148. }
  2149. const stringMatch = representation.match(PARSE_STRING_REGEXP);
  2150. const infMatch = representation.match(PARSE_INF_REGEXP);
  2151. const nanMatch = representation.match(PARSE_NAN_REGEXP);
  2152. if (!stringMatch && !infMatch && !nanMatch || representation.length === 0) {
  2153. throw new BSONError("" + representation + " not a valid Decimal128 string");
  2154. }
  2155. if (stringMatch) {
  2156. const unsignedNumber = stringMatch[2];
  2157. const e = stringMatch[4];
  2158. const expSign = stringMatch[5];
  2159. const expNumber = stringMatch[6];
  2160. if (e && expNumber === void 0)
  2161. invalidErr(representation, "missing exponent power");
  2162. if (e && unsignedNumber === void 0)
  2163. invalidErr(representation, "missing exponent base");
  2164. if (e === void 0 && (expSign || expNumber)) {
  2165. invalidErr(representation, "missing e before exponent");
  2166. }
  2167. }
  2168. if (representation[index] === "+" || representation[index] === "-") {
  2169. sawSign = true;
  2170. isNegative = representation[index++] === "-";
  2171. }
  2172. if (!isDigit(representation[index]) && representation[index] !== ".") {
  2173. if (representation[index] === "i" || representation[index] === "I") {
  2174. return new _Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
  2175. } else if (representation[index] === "N") {
  2176. return new _Decimal128(NAN_BUFFER);
  2177. }
  2178. }
  2179. while (isDigit(representation[index]) || representation[index] === ".") {
  2180. if (representation[index] === ".") {
  2181. if (sawRadix)
  2182. invalidErr(representation, "contains multiple periods");
  2183. sawRadix = true;
  2184. index = index + 1;
  2185. continue;
  2186. }
  2187. if (nDigitsStored < MAX_DIGITS) {
  2188. if (representation[index] !== "0" || foundNonZero) {
  2189. if (!foundNonZero) {
  2190. firstNonZero = nDigitsRead;
  2191. }
  2192. foundNonZero = true;
  2193. digits[digitsInsert++] = parseInt(representation[index], 10);
  2194. nDigitsStored = nDigitsStored + 1;
  2195. }
  2196. }
  2197. if (foundNonZero)
  2198. nDigits = nDigits + 1;
  2199. if (sawRadix)
  2200. radixPosition = radixPosition + 1;
  2201. nDigitsRead = nDigitsRead + 1;
  2202. index = index + 1;
  2203. }
  2204. if (sawRadix && !nDigitsRead)
  2205. throw new BSONError("" + representation + " not a valid Decimal128 string");
  2206. if (representation[index] === "e" || representation[index] === "E") {
  2207. const match = representation.substr(++index).match(EXPONENT_REGEX);
  2208. if (!match || !match[2])
  2209. return new _Decimal128(NAN_BUFFER);
  2210. exponent = parseInt(match[0], 10);
  2211. index = index + match[0].length;
  2212. }
  2213. if (representation[index])
  2214. return new _Decimal128(NAN_BUFFER);
  2215. if (!nDigitsStored) {
  2216. digits[0] = 0;
  2217. nDigits = 1;
  2218. nDigitsStored = 1;
  2219. significantDigits = 0;
  2220. } else {
  2221. lastDigit = nDigitsStored - 1;
  2222. significantDigits = nDigits;
  2223. if (significantDigits !== 1) {
  2224. while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === "0") {
  2225. significantDigits = significantDigits - 1;
  2226. }
  2227. }
  2228. }
  2229. if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
  2230. exponent = EXPONENT_MIN;
  2231. } else {
  2232. exponent = exponent - radixPosition;
  2233. }
  2234. while (exponent > EXPONENT_MAX) {
  2235. lastDigit = lastDigit + 1;
  2236. if (lastDigit >= MAX_DIGITS) {
  2237. if (significantDigits === 0) {
  2238. exponent = EXPONENT_MAX;
  2239. break;
  2240. }
  2241. invalidErr(representation, "overflow");
  2242. }
  2243. exponent = exponent - 1;
  2244. }
  2245. if (options.allowRounding) {
  2246. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  2247. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  2248. exponent = EXPONENT_MIN;
  2249. significantDigits = 0;
  2250. break;
  2251. }
  2252. if (nDigitsStored < nDigits) {
  2253. nDigits = nDigits - 1;
  2254. } else {
  2255. lastDigit = lastDigit - 1;
  2256. }
  2257. if (exponent < EXPONENT_MAX) {
  2258. exponent = exponent + 1;
  2259. } else {
  2260. const digitsString = digits.join("");
  2261. if (digitsString.match(/^0+$/)) {
  2262. exponent = EXPONENT_MAX;
  2263. break;
  2264. }
  2265. invalidErr(representation, "overflow");
  2266. }
  2267. }
  2268. if (lastDigit + 1 < significantDigits) {
  2269. let endOfString = nDigitsRead;
  2270. if (sawRadix) {
  2271. firstNonZero = firstNonZero + 1;
  2272. endOfString = endOfString + 1;
  2273. }
  2274. if (sawSign) {
  2275. firstNonZero = firstNonZero + 1;
  2276. endOfString = endOfString + 1;
  2277. }
  2278. const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  2279. let roundBit = 0;
  2280. if (roundDigit >= 5) {
  2281. roundBit = 1;
  2282. if (roundDigit === 5) {
  2283. roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
  2284. for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  2285. if (parseInt(representation[i], 10)) {
  2286. roundBit = 1;
  2287. break;
  2288. }
  2289. }
  2290. }
  2291. }
  2292. if (roundBit) {
  2293. let dIdx = lastDigit;
  2294. for (; dIdx >= 0; dIdx--) {
  2295. if (++digits[dIdx] > 9) {
  2296. digits[dIdx] = 0;
  2297. if (dIdx === 0) {
  2298. if (exponent < EXPONENT_MAX) {
  2299. exponent = exponent + 1;
  2300. digits[dIdx] = 1;
  2301. } else {
  2302. return new _Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
  2303. }
  2304. }
  2305. } else {
  2306. break;
  2307. }
  2308. }
  2309. }
  2310. }
  2311. } else {
  2312. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  2313. if (lastDigit === 0) {
  2314. if (significantDigits === 0) {
  2315. exponent = EXPONENT_MIN;
  2316. break;
  2317. }
  2318. invalidErr(representation, "exponent underflow");
  2319. }
  2320. if (nDigitsStored < nDigits) {
  2321. if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== "0" && significantDigits !== 0) {
  2322. invalidErr(representation, "inexact rounding");
  2323. }
  2324. nDigits = nDigits - 1;
  2325. } else {
  2326. if (digits[lastDigit] !== 0) {
  2327. invalidErr(representation, "inexact rounding");
  2328. }
  2329. lastDigit = lastDigit - 1;
  2330. }
  2331. if (exponent < EXPONENT_MAX) {
  2332. exponent = exponent + 1;
  2333. } else {
  2334. invalidErr(representation, "overflow");
  2335. }
  2336. }
  2337. if (lastDigit + 1 < significantDigits) {
  2338. if (sawRadix) {
  2339. firstNonZero = firstNonZero + 1;
  2340. }
  2341. if (sawSign) {
  2342. firstNonZero = firstNonZero + 1;
  2343. }
  2344. const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  2345. if (roundDigit !== 0) {
  2346. invalidErr(representation, "inexact rounding");
  2347. }
  2348. }
  2349. }
  2350. significandHigh = Long.fromNumber(0);
  2351. significandLow = Long.fromNumber(0);
  2352. if (significantDigits === 0) {
  2353. significandHigh = Long.fromNumber(0);
  2354. significandLow = Long.fromNumber(0);
  2355. } else if (lastDigit < 17) {
  2356. let dIdx = 0;
  2357. significandLow = Long.fromNumber(digits[dIdx++]);
  2358. significandHigh = new Long(0, 0);
  2359. for (; dIdx <= lastDigit; dIdx++) {
  2360. significandLow = significandLow.multiply(Long.fromNumber(10));
  2361. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  2362. }
  2363. } else {
  2364. let dIdx = 0;
  2365. significandHigh = Long.fromNumber(digits[dIdx++]);
  2366. for (; dIdx <= lastDigit - 17; dIdx++) {
  2367. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  2368. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  2369. }
  2370. significandLow = Long.fromNumber(digits[dIdx++]);
  2371. for (; dIdx <= lastDigit; dIdx++) {
  2372. significandLow = significandLow.multiply(Long.fromNumber(10));
  2373. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  2374. }
  2375. }
  2376. const significand = multiply64x2(significandHigh, Long.fromString("100000000000000000"));
  2377. significand.low = significand.low.add(significandLow);
  2378. if (lessThan(significand.low, significandLow)) {
  2379. significand.high = significand.high.add(Long.fromNumber(1));
  2380. }
  2381. biasedExponent = exponent + EXPONENT_BIAS;
  2382. const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  2383. if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
  2384. dec.high = dec.high.or(Long.fromNumber(3).shiftLeft(61));
  2385. dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(16383).shiftLeft(47)));
  2386. dec.high = dec.high.or(significand.high.and(Long.fromNumber(140737488355327)));
  2387. } else {
  2388. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 16383).shiftLeft(49));
  2389. dec.high = dec.high.or(significand.high.and(Long.fromNumber(562949953421311)));
  2390. }
  2391. dec.low = significand.low;
  2392. if (isNegative) {
  2393. dec.high = dec.high.or(Long.fromString("9223372036854775808"));
  2394. }
  2395. const buffer2 = ByteUtils.allocate(16);
  2396. index = 0;
  2397. buffer2[index++] = dec.low.low & 255;
  2398. buffer2[index++] = dec.low.low >> 8 & 255;
  2399. buffer2[index++] = dec.low.low >> 16 & 255;
  2400. buffer2[index++] = dec.low.low >> 24 & 255;
  2401. buffer2[index++] = dec.low.high & 255;
  2402. buffer2[index++] = dec.low.high >> 8 & 255;
  2403. buffer2[index++] = dec.low.high >> 16 & 255;
  2404. buffer2[index++] = dec.low.high >> 24 & 255;
  2405. buffer2[index++] = dec.high.low & 255;
  2406. buffer2[index++] = dec.high.low >> 8 & 255;
  2407. buffer2[index++] = dec.high.low >> 16 & 255;
  2408. buffer2[index++] = dec.high.low >> 24 & 255;
  2409. buffer2[index++] = dec.high.high & 255;
  2410. buffer2[index++] = dec.high.high >> 8 & 255;
  2411. buffer2[index++] = dec.high.high >> 16 & 255;
  2412. buffer2[index++] = dec.high.high >> 24 & 255;
  2413. return new _Decimal128(buffer2);
  2414. }
  2415. toString() {
  2416. let biased_exponent;
  2417. let significand_digits = 0;
  2418. const significand = new Array(36);
  2419. for (let i = 0; i < significand.length; i++)
  2420. significand[i] = 0;
  2421. let index = 0;
  2422. let is_zero = false;
  2423. let significand_msb;
  2424. let significand128 = { parts: [0, 0, 0, 0] };
  2425. let j, k;
  2426. const string = [];
  2427. index = 0;
  2428. const buffer2 = this.bytes;
  2429. const low = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  2430. const midl = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  2431. const midh = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  2432. const high = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  2433. index = 0;
  2434. const dec = {
  2435. low: new Long(low, midl),
  2436. high: new Long(midh, high)
  2437. };
  2438. if (dec.high.lessThan(Long.ZERO)) {
  2439. string.push("-");
  2440. }
  2441. const combination = high >> 26 & COMBINATION_MASK;
  2442. if (combination >> 3 === 3) {
  2443. if (combination === COMBINATION_INFINITY) {
  2444. return string.join("") + "Infinity";
  2445. } else if (combination === COMBINATION_NAN) {
  2446. return "NaN";
  2447. } else {
  2448. biased_exponent = high >> 15 & EXPONENT_MASK;
  2449. significand_msb = 8 + (high >> 14 & 1);
  2450. }
  2451. } else {
  2452. significand_msb = high >> 14 & 7;
  2453. biased_exponent = high >> 17 & EXPONENT_MASK;
  2454. }
  2455. const exponent = biased_exponent - EXPONENT_BIAS;
  2456. significand128.parts[0] = (high & 16383) + ((significand_msb & 15) << 14);
  2457. significand128.parts[1] = midh;
  2458. significand128.parts[2] = midl;
  2459. significand128.parts[3] = low;
  2460. if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) {
  2461. is_zero = true;
  2462. } else {
  2463. for (k = 3; k >= 0; k--) {
  2464. let least_digits = 0;
  2465. const result = divideu128(significand128);
  2466. significand128 = result.quotient;
  2467. least_digits = result.rem.low;
  2468. if (!least_digits)
  2469. continue;
  2470. for (j = 8; j >= 0; j--) {
  2471. significand[k * 9 + j] = least_digits % 10;
  2472. least_digits = Math.floor(least_digits / 10);
  2473. }
  2474. }
  2475. }
  2476. if (is_zero) {
  2477. significand_digits = 1;
  2478. significand[index] = 0;
  2479. } else {
  2480. significand_digits = 36;
  2481. while (!significand[index]) {
  2482. significand_digits = significand_digits - 1;
  2483. index = index + 1;
  2484. }
  2485. }
  2486. const scientific_exponent = significand_digits - 1 + exponent;
  2487. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  2488. if (significand_digits > 34) {
  2489. string.push(`${0}`);
  2490. if (exponent > 0)
  2491. string.push(`E+${exponent}`);
  2492. else if (exponent < 0)
  2493. string.push(`E${exponent}`);
  2494. return string.join("");
  2495. }
  2496. string.push(`${significand[index++]}`);
  2497. significand_digits = significand_digits - 1;
  2498. if (significand_digits) {
  2499. string.push(".");
  2500. }
  2501. for (let i = 0; i < significand_digits; i++) {
  2502. string.push(`${significand[index++]}`);
  2503. }
  2504. string.push("E");
  2505. if (scientific_exponent > 0) {
  2506. string.push(`+${scientific_exponent}`);
  2507. } else {
  2508. string.push(`${scientific_exponent}`);
  2509. }
  2510. } else {
  2511. if (exponent >= 0) {
  2512. for (let i = 0; i < significand_digits; i++) {
  2513. string.push(`${significand[index++]}`);
  2514. }
  2515. } else {
  2516. let radix_position = significand_digits + exponent;
  2517. if (radix_position > 0) {
  2518. for (let i = 0; i < radix_position; i++) {
  2519. string.push(`${significand[index++]}`);
  2520. }
  2521. } else {
  2522. string.push("0");
  2523. }
  2524. string.push(".");
  2525. while (radix_position++ < 0) {
  2526. string.push("0");
  2527. }
  2528. for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  2529. string.push(`${significand[index++]}`);
  2530. }
  2531. }
  2532. }
  2533. return string.join("");
  2534. }
  2535. toJSON() {
  2536. return { $numberDecimal: this.toString() };
  2537. }
  2538. toExtendedJSON() {
  2539. return { $numberDecimal: this.toString() };
  2540. }
  2541. static fromExtendedJSON(doc) {
  2542. return _Decimal128.fromString(doc.$numberDecimal);
  2543. }
  2544. [Symbol.for("nodejs.util.inspect.custom")]() {
  2545. return this.inspect();
  2546. }
  2547. inspect() {
  2548. return `new Decimal128("${this.toString()}")`;
  2549. }
  2550. };
  2551. __name(_Decimal128, "Decimal128");
  2552. var Decimal128 = _Decimal128;
  2553. var _Double = class _Double extends BSONValue {
  2554. get _bsontype() {
  2555. return "Double";
  2556. }
  2557. constructor(value) {
  2558. super();
  2559. if (value instanceof Number) {
  2560. value = value.valueOf();
  2561. }
  2562. this.value = +value;
  2563. }
  2564. valueOf() {
  2565. return this.value;
  2566. }
  2567. toJSON() {
  2568. return this.value;
  2569. }
  2570. toString(radix) {
  2571. return this.value.toString(radix);
  2572. }
  2573. toExtendedJSON(options) {
  2574. if (options && (options.legacy || options.relaxed && isFinite(this.value))) {
  2575. return this.value;
  2576. }
  2577. if (Object.is(Math.sign(this.value), -0)) {
  2578. return { $numberDouble: "-0.0" };
  2579. }
  2580. return {
  2581. $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
  2582. };
  2583. }
  2584. static fromExtendedJSON(doc, options) {
  2585. const doubleValue = parseFloat(doc.$numberDouble);
  2586. return options && options.relaxed ? doubleValue : new _Double(doubleValue);
  2587. }
  2588. [Symbol.for("nodejs.util.inspect.custom")]() {
  2589. return this.inspect();
  2590. }
  2591. inspect() {
  2592. const eJSON = this.toExtendedJSON();
  2593. return `new Double(${eJSON.$numberDouble})`;
  2594. }
  2595. };
  2596. __name(_Double, "Double");
  2597. var Double = _Double;
  2598. var _Int32 = class _Int32 extends BSONValue {
  2599. get _bsontype() {
  2600. return "Int32";
  2601. }
  2602. constructor(value) {
  2603. super();
  2604. if (value instanceof Number) {
  2605. value = value.valueOf();
  2606. }
  2607. this.value = +value | 0;
  2608. }
  2609. valueOf() {
  2610. return this.value;
  2611. }
  2612. toString(radix) {
  2613. return this.value.toString(radix);
  2614. }
  2615. toJSON() {
  2616. return this.value;
  2617. }
  2618. toExtendedJSON(options) {
  2619. if (options && (options.relaxed || options.legacy))
  2620. return this.value;
  2621. return { $numberInt: this.value.toString() };
  2622. }
  2623. static fromExtendedJSON(doc, options) {
  2624. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new _Int32(doc.$numberInt);
  2625. }
  2626. [Symbol.for("nodejs.util.inspect.custom")]() {
  2627. return this.inspect();
  2628. }
  2629. inspect() {
  2630. return `new Int32(${this.valueOf()})`;
  2631. }
  2632. };
  2633. __name(_Int32, "Int32");
  2634. var Int32 = _Int32;
  2635. var _MaxKey = class _MaxKey extends BSONValue {
  2636. get _bsontype() {
  2637. return "MaxKey";
  2638. }
  2639. toExtendedJSON() {
  2640. return { $maxKey: 1 };
  2641. }
  2642. static fromExtendedJSON() {
  2643. return new _MaxKey();
  2644. }
  2645. [Symbol.for("nodejs.util.inspect.custom")]() {
  2646. return this.inspect();
  2647. }
  2648. inspect() {
  2649. return "new MaxKey()";
  2650. }
  2651. };
  2652. __name(_MaxKey, "MaxKey");
  2653. var MaxKey = _MaxKey;
  2654. var _MinKey = class _MinKey extends BSONValue {
  2655. get _bsontype() {
  2656. return "MinKey";
  2657. }
  2658. toExtendedJSON() {
  2659. return { $minKey: 1 };
  2660. }
  2661. static fromExtendedJSON() {
  2662. return new _MinKey();
  2663. }
  2664. [Symbol.for("nodejs.util.inspect.custom")]() {
  2665. return this.inspect();
  2666. }
  2667. inspect() {
  2668. return "new MinKey()";
  2669. }
  2670. };
  2671. __name(_MinKey, "MinKey");
  2672. var MinKey = _MinKey;
  2673. var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
  2674. var PROCESS_UNIQUE = null;
  2675. var kId = Symbol("id");
  2676. var _ObjectId = class _ObjectId extends BSONValue {
  2677. get _bsontype() {
  2678. return "ObjectId";
  2679. }
  2680. constructor(inputId) {
  2681. super();
  2682. let workingId;
  2683. if (typeof inputId === "object" && inputId && "id" in inputId) {
  2684. if (typeof inputId.id !== "string" && !ArrayBuffer.isView(inputId.id)) {
  2685. throw new BSONError("Argument passed in must have an id that is of type string or Buffer");
  2686. }
  2687. if ("toHexString" in inputId && typeof inputId.toHexString === "function") {
  2688. workingId = ByteUtils.fromHex(inputId.toHexString());
  2689. } else {
  2690. workingId = inputId.id;
  2691. }
  2692. } else {
  2693. workingId = inputId;
  2694. }
  2695. if (workingId == null || typeof workingId === "number") {
  2696. this[kId] = _ObjectId.generate(typeof workingId === "number" ? workingId : void 0);
  2697. } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
  2698. this[kId] = ByteUtils.toLocalBufferType(workingId);
  2699. } else if (typeof workingId === "string") {
  2700. if (workingId.length === 12) {
  2701. const bytes = ByteUtils.fromUTF8(workingId);
  2702. if (bytes.byteLength === 12) {
  2703. this[kId] = bytes;
  2704. } else {
  2705. throw new BSONError("Argument passed in must be a string of 12 bytes");
  2706. }
  2707. } else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
  2708. this[kId] = ByteUtils.fromHex(workingId);
  2709. } else {
  2710. throw new BSONError("Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer");
  2711. }
  2712. } else {
  2713. throw new BSONError("Argument passed in does not match the accepted types");
  2714. }
  2715. if (_ObjectId.cacheHexString) {
  2716. this.__id = ByteUtils.toHex(this.id);
  2717. }
  2718. }
  2719. get id() {
  2720. return this[kId];
  2721. }
  2722. set id(value) {
  2723. this[kId] = value;
  2724. if (_ObjectId.cacheHexString) {
  2725. this.__id = ByteUtils.toHex(value);
  2726. }
  2727. }
  2728. toHexString() {
  2729. if (_ObjectId.cacheHexString && this.__id) {
  2730. return this.__id;
  2731. }
  2732. const hexString = ByteUtils.toHex(this.id);
  2733. if (_ObjectId.cacheHexString && !this.__id) {
  2734. this.__id = hexString;
  2735. }
  2736. return hexString;
  2737. }
  2738. static getInc() {
  2739. return _ObjectId.index = (_ObjectId.index + 1) % 16777215;
  2740. }
  2741. static generate(time) {
  2742. if ("number" !== typeof time) {
  2743. time = Math.floor(Date.now() / 1e3);
  2744. }
  2745. const inc = _ObjectId.getInc();
  2746. const buffer2 = ByteUtils.allocate(12);
  2747. BSONDataView.fromUint8Array(buffer2).setUint32(0, time, false);
  2748. if (PROCESS_UNIQUE === null) {
  2749. PROCESS_UNIQUE = ByteUtils.randomBytes(5);
  2750. }
  2751. buffer2[4] = PROCESS_UNIQUE[0];
  2752. buffer2[5] = PROCESS_UNIQUE[1];
  2753. buffer2[6] = PROCESS_UNIQUE[2];
  2754. buffer2[7] = PROCESS_UNIQUE[3];
  2755. buffer2[8] = PROCESS_UNIQUE[4];
  2756. buffer2[11] = inc & 255;
  2757. buffer2[10] = inc >> 8 & 255;
  2758. buffer2[9] = inc >> 16 & 255;
  2759. return buffer2;
  2760. }
  2761. toString(encoding) {
  2762. if (encoding === "base64")
  2763. return ByteUtils.toBase64(this.id);
  2764. if (encoding === "hex")
  2765. return this.toHexString();
  2766. return this.toHexString();
  2767. }
  2768. toJSON() {
  2769. return this.toHexString();
  2770. }
  2771. equals(otherId) {
  2772. if (otherId === void 0 || otherId === null) {
  2773. return false;
  2774. }
  2775. if (otherId instanceof _ObjectId) {
  2776. return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]);
  2777. }
  2778. if (typeof otherId === "string" && _ObjectId.isValid(otherId) && otherId.length === 12 && isUint8Array(this.id)) {
  2779. return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId));
  2780. }
  2781. if (typeof otherId === "string" && _ObjectId.isValid(otherId) && otherId.length === 24) {
  2782. return otherId.toLowerCase() === this.toHexString();
  2783. }
  2784. if (typeof otherId === "string" && _ObjectId.isValid(otherId) && otherId.length === 12) {
  2785. return ByteUtils.equals(ByteUtils.fromUTF8(otherId), this.id);
  2786. }
  2787. if (typeof otherId === "object" && "toHexString" in otherId && typeof otherId.toHexString === "function") {
  2788. const otherIdString = otherId.toHexString();
  2789. const thisIdString = this.toHexString().toLowerCase();
  2790. return typeof otherIdString === "string" && otherIdString.toLowerCase() === thisIdString;
  2791. }
  2792. return false;
  2793. }
  2794. getTimestamp() {
  2795. const timestamp = /* @__PURE__ */ new Date();
  2796. const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false);
  2797. timestamp.setTime(Math.floor(time) * 1e3);
  2798. return timestamp;
  2799. }
  2800. static createPk() {
  2801. return new _ObjectId();
  2802. }
  2803. static createFromTime(time) {
  2804. const buffer2 = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  2805. BSONDataView.fromUint8Array(buffer2).setUint32(0, time, false);
  2806. return new _ObjectId(buffer2);
  2807. }
  2808. static createFromHexString(hexString) {
  2809. if ((hexString == null ? void 0 : hexString.length) !== 24) {
  2810. throw new BSONError("hex string must be 24 characters");
  2811. }
  2812. return new _ObjectId(ByteUtils.fromHex(hexString));
  2813. }
  2814. static createFromBase64(base64) {
  2815. if ((base64 == null ? void 0 : base64.length) !== 16) {
  2816. throw new BSONError("base64 string must be 16 characters");
  2817. }
  2818. return new _ObjectId(ByteUtils.fromBase64(base64));
  2819. }
  2820. static isValid(id) {
  2821. if (id == null)
  2822. return false;
  2823. try {
  2824. new _ObjectId(id);
  2825. return true;
  2826. } catch {
  2827. return false;
  2828. }
  2829. }
  2830. toExtendedJSON() {
  2831. if (this.toHexString)
  2832. return { $oid: this.toHexString() };
  2833. return { $oid: this.toString("hex") };
  2834. }
  2835. static fromExtendedJSON(doc) {
  2836. return new _ObjectId(doc.$oid);
  2837. }
  2838. [Symbol.for("nodejs.util.inspect.custom")]() {
  2839. return this.inspect();
  2840. }
  2841. inspect() {
  2842. return `new ObjectId("${this.toHexString()}")`;
  2843. }
  2844. };
  2845. __name(_ObjectId, "ObjectId");
  2846. var ObjectId3 = _ObjectId;
  2847. ObjectId3.index = Math.floor(Math.random() * 16777215);
  2848. function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
  2849. let totalLength = 4 + 1;
  2850. if (Array.isArray(object)) {
  2851. for (let i = 0; i < object.length; i++) {
  2852. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  2853. }
  2854. } else {
  2855. if (typeof (object == null ? void 0 : object.toBSON) === "function") {
  2856. object = object.toBSON();
  2857. }
  2858. for (const key of Object.keys(object)) {
  2859. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  2860. }
  2861. }
  2862. return totalLength;
  2863. }
  2864. __name(internalCalculateObjectSize, "internalCalculateObjectSize");
  2865. function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
  2866. if (typeof (value == null ? void 0 : value.toBSON) === "function") {
  2867. value = value.toBSON();
  2868. }
  2869. switch (typeof value) {
  2870. case "string":
  2871. return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
  2872. case "number":
  2873. if (Math.floor(value) === value && value >= JS_INT_MIN && value <= JS_INT_MAX) {
  2874. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  2875. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
  2876. } else {
  2877. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2878. }
  2879. } else {
  2880. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2881. }
  2882. case "undefined":
  2883. if (isArray || !ignoreUndefined)
  2884. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
  2885. return 0;
  2886. case "boolean":
  2887. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
  2888. case "object":
  2889. if (value != null && typeof value._bsontype === "string" && value[Symbol.for("@@mdb.bson.version")] !== BSON_MAJOR_VERSION) {
  2890. throw new BSONVersionError();
  2891. } else if (value == null || value._bsontype === "MinKey" || value._bsontype === "MaxKey") {
  2892. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
  2893. } else if (value._bsontype === "ObjectId") {
  2894. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
  2895. } else if (value instanceof Date || isDate(value)) {
  2896. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2897. } else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || isAnyArrayBuffer(value)) {
  2898. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength;
  2899. } else if (value._bsontype === "Long" || value._bsontype === "Double" || value._bsontype === "Timestamp") {
  2900. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2901. } else if (value._bsontype === "Decimal128") {
  2902. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
  2903. } else if (value._bsontype === "Code") {
  2904. if (value.scope != null && Object.keys(value.scope).length > 0) {
  2905. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1 + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined);
  2906. } else {
  2907. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1;
  2908. }
  2909. } else if (value._bsontype === "Binary") {
  2910. const binary = value;
  2911. if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  2912. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1 + 4);
  2913. } else {
  2914. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1);
  2915. }
  2916. } else if (value._bsontype === "Symbol") {
  2917. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + ByteUtils.utf8ByteLength(value.value) + 4 + 1 + 1;
  2918. } else if (value._bsontype === "DBRef") {
  2919. const ordered_values = Object.assign({
  2920. $ref: value.collection,
  2921. $id: value.oid
  2922. }, value.fields);
  2923. if (value.db != null) {
  2924. ordered_values["$db"] = value.db;
  2925. }
  2926. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined);
  2927. } else if (value instanceof RegExp || isRegExp(value)) {
  2928. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.source) + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1;
  2929. } else if (value._bsontype === "BSONRegExp") {
  2930. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.pattern) + 1 + ByteUtils.utf8ByteLength(value.options) + 1;
  2931. } else {
  2932. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1;
  2933. }
  2934. case "function":
  2935. if (serializeFunctions) {
  2936. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.toString()) + 1;
  2937. }
  2938. }
  2939. return 0;
  2940. }
  2941. __name(calculateElement, "calculateElement");
  2942. function alphabetize(str) {
  2943. return str.split("").sort().join("");
  2944. }
  2945. __name(alphabetize, "alphabetize");
  2946. var _BSONRegExp = class _BSONRegExp extends BSONValue {
  2947. get _bsontype() {
  2948. return "BSONRegExp";
  2949. }
  2950. constructor(pattern, options) {
  2951. super();
  2952. this.pattern = pattern;
  2953. this.options = alphabetize(options ?? "");
  2954. if (this.pattern.indexOf("\0") !== -1) {
  2955. throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
  2956. }
  2957. if (this.options.indexOf("\0") !== -1) {
  2958. throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
  2959. }
  2960. for (let i = 0; i < this.options.length; i++) {
  2961. if (!(this.options[i] === "i" || this.options[i] === "m" || this.options[i] === "x" || this.options[i] === "l" || this.options[i] === "s" || this.options[i] === "u")) {
  2962. throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
  2963. }
  2964. }
  2965. }
  2966. static parseOptions(options) {
  2967. return options ? options.split("").sort().join("") : "";
  2968. }
  2969. toExtendedJSON(options) {
  2970. options = options || {};
  2971. if (options.legacy) {
  2972. return { $regex: this.pattern, $options: this.options };
  2973. }
  2974. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  2975. }
  2976. static fromExtendedJSON(doc) {
  2977. if ("$regex" in doc) {
  2978. if (typeof doc.$regex !== "string") {
  2979. if (doc.$regex._bsontype === "BSONRegExp") {
  2980. return doc;
  2981. }
  2982. } else {
  2983. return new _BSONRegExp(doc.$regex, _BSONRegExp.parseOptions(doc.$options));
  2984. }
  2985. }
  2986. if ("$regularExpression" in doc) {
  2987. return new _BSONRegExp(doc.$regularExpression.pattern, _BSONRegExp.parseOptions(doc.$regularExpression.options));
  2988. }
  2989. throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
  2990. }
  2991. [Symbol.for("nodejs.util.inspect.custom")]() {
  2992. return this.inspect();
  2993. }
  2994. inspect() {
  2995. return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`;
  2996. }
  2997. };
  2998. __name(_BSONRegExp, "BSONRegExp");
  2999. var BSONRegExp = _BSONRegExp;
  3000. var _BSONSymbol = class _BSONSymbol extends BSONValue {
  3001. get _bsontype() {
  3002. return "BSONSymbol";
  3003. }
  3004. constructor(value) {
  3005. super();
  3006. this.value = value;
  3007. }
  3008. valueOf() {
  3009. return this.value;
  3010. }
  3011. toString() {
  3012. return this.value;
  3013. }
  3014. inspect() {
  3015. return `new BSONSymbol("${this.value}")`;
  3016. }
  3017. toJSON() {
  3018. return this.value;
  3019. }
  3020. toExtendedJSON() {
  3021. return { $symbol: this.value };
  3022. }
  3023. static fromExtendedJSON(doc) {
  3024. return new _BSONSymbol(doc.$symbol);
  3025. }
  3026. [Symbol.for("nodejs.util.inspect.custom")]() {
  3027. return this.inspect();
  3028. }
  3029. };
  3030. __name(_BSONSymbol, "BSONSymbol");
  3031. var BSONSymbol = _BSONSymbol;
  3032. var LongWithoutOverridesClass = Long;
  3033. var _Timestamp = class _Timestamp extends LongWithoutOverridesClass {
  3034. get _bsontype() {
  3035. return "Timestamp";
  3036. }
  3037. constructor(low) {
  3038. if (low == null) {
  3039. super(0, 0, true);
  3040. } else if (typeof low === "bigint") {
  3041. super(low, true);
  3042. } else if (Long.isLong(low)) {
  3043. super(low.low, low.high, true);
  3044. } else if (typeof low === "object" && "t" in low && "i" in low) {
  3045. if (typeof low.t !== "number" && (typeof low.t !== "object" || low.t._bsontype !== "Int32")) {
  3046. throw new BSONError("Timestamp constructed from { t, i } must provide t as a number");
  3047. }
  3048. if (typeof low.i !== "number" && (typeof low.i !== "object" || low.i._bsontype !== "Int32")) {
  3049. throw new BSONError("Timestamp constructed from { t, i } must provide i as a number");
  3050. }
  3051. const t = Number(low.t);
  3052. const i = Number(low.i);
  3053. if (t < 0 || Number.isNaN(t)) {
  3054. throw new BSONError("Timestamp constructed from { t, i } must provide a positive t");
  3055. }
  3056. if (i < 0 || Number.isNaN(i)) {
  3057. throw new BSONError("Timestamp constructed from { t, i } must provide a positive i");
  3058. }
  3059. if (t > 4294967295) {
  3060. throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");
  3061. }
  3062. if (i > 4294967295) {
  3063. throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");
  3064. }
  3065. super(i, t, true);
  3066. } else {
  3067. throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }");
  3068. }
  3069. }
  3070. toJSON() {
  3071. return {
  3072. $timestamp: this.toString()
  3073. };
  3074. }
  3075. static fromInt(value) {
  3076. return new _Timestamp(Long.fromInt(value, true));
  3077. }
  3078. static fromNumber(value) {
  3079. return new _Timestamp(Long.fromNumber(value, true));
  3080. }
  3081. static fromBits(lowBits, highBits) {
  3082. return new _Timestamp({ i: lowBits, t: highBits });
  3083. }
  3084. static fromString(str, optRadix) {
  3085. return new _Timestamp(Long.fromString(str, true, optRadix));
  3086. }
  3087. toExtendedJSON() {
  3088. return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
  3089. }
  3090. static fromExtendedJSON(doc) {
  3091. const i = Long.isLong(doc.$timestamp.i) ? doc.$timestamp.i.getLowBitsUnsigned() : doc.$timestamp.i;
  3092. const t = Long.isLong(doc.$timestamp.t) ? doc.$timestamp.t.getLowBitsUnsigned() : doc.$timestamp.t;
  3093. return new _Timestamp({ t, i });
  3094. }
  3095. [Symbol.for("nodejs.util.inspect.custom")]() {
  3096. return this.inspect();
  3097. }
  3098. inspect() {
  3099. return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`;
  3100. }
  3101. };
  3102. __name(_Timestamp, "Timestamp");
  3103. var Timestamp = _Timestamp;
  3104. Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
  3105. var FIRST_BIT = 128;
  3106. var FIRST_TWO_BITS = 192;
  3107. var FIRST_THREE_BITS = 224;
  3108. var FIRST_FOUR_BITS = 240;
  3109. var FIRST_FIVE_BITS = 248;
  3110. var TWO_BIT_CHAR = 192;
  3111. var THREE_BIT_CHAR = 224;
  3112. var FOUR_BIT_CHAR = 240;
  3113. var CONTINUING_CHAR = 128;
  3114. function validateUtf8(bytes, start, end) {
  3115. let continuation = 0;
  3116. for (let i = start; i < end; i += 1) {
  3117. const byte = bytes[i];
  3118. if (continuation) {
  3119. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  3120. return false;
  3121. }
  3122. continuation -= 1;
  3123. } else if (byte & FIRST_BIT) {
  3124. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  3125. continuation = 1;
  3126. } else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  3127. continuation = 2;
  3128. } else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  3129. continuation = 3;
  3130. } else {
  3131. return false;
  3132. }
  3133. }
  3134. }
  3135. return !continuation;
  3136. }
  3137. __name(validateUtf8, "validateUtf8");
  3138. var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
  3139. var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
  3140. function internalDeserialize(buffer2, options, isArray) {
  3141. options = options == null ? {} : options;
  3142. const index = options && options.index ? options.index : 0;
  3143. const size = buffer2[index] | buffer2[index + 1] << 8 | buffer2[index + 2] << 16 | buffer2[index + 3] << 24;
  3144. if (size < 5) {
  3145. throw new BSONError(`bson size must be >= 5, is ${size}`);
  3146. }
  3147. if (options.allowObjectSmallerThanBufferSize && buffer2.length < size) {
  3148. throw new BSONError(`buffer length ${buffer2.length} must be >= bson size ${size}`);
  3149. }
  3150. if (!options.allowObjectSmallerThanBufferSize && buffer2.length !== size) {
  3151. throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`);
  3152. }
  3153. if (size + index > buffer2.byteLength) {
  3154. throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`);
  3155. }
  3156. if (buffer2[index + size - 1] !== 0) {
  3157. throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  3158. }
  3159. return deserializeObject(buffer2, index, options, isArray);
  3160. }
  3161. __name(internalDeserialize, "internalDeserialize");
  3162. var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
  3163. function deserializeObject(buffer2, index, options, isArray = false) {
  3164. const fieldsAsRaw = options["fieldsAsRaw"] == null ? null : options["fieldsAsRaw"];
  3165. const raw = options["raw"] == null ? false : options["raw"];
  3166. const bsonRegExp = typeof options["bsonRegExp"] === "boolean" ? options["bsonRegExp"] : false;
  3167. const promoteBuffers = options.promoteBuffers ?? false;
  3168. const promoteLongs = options.promoteLongs ?? true;
  3169. const promoteValues = options.promoteValues ?? true;
  3170. const useBigInt64 = options.useBigInt64 ?? false;
  3171. if (useBigInt64 && !promoteValues) {
  3172. throw new BSONError("Must either request bigint or Long for int64 deserialization");
  3173. }
  3174. if (useBigInt64 && !promoteLongs) {
  3175. throw new BSONError("Must either request bigint or Long for int64 deserialization");
  3176. }
  3177. const validation = options.validation == null ? { utf8: true } : options.validation;
  3178. let globalUTFValidation = true;
  3179. let validationSetting;
  3180. const utf8KeysSet = /* @__PURE__ */ new Set();
  3181. const utf8ValidatedKeys = validation.utf8;
  3182. if (typeof utf8ValidatedKeys === "boolean") {
  3183. validationSetting = utf8ValidatedKeys;
  3184. } else {
  3185. globalUTFValidation = false;
  3186. const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function(key) {
  3187. return utf8ValidatedKeys[key];
  3188. });
  3189. if (utf8ValidationValues.length === 0) {
  3190. throw new BSONError("UTF-8 validation setting cannot be empty");
  3191. }
  3192. if (typeof utf8ValidationValues[0] !== "boolean") {
  3193. throw new BSONError("Invalid UTF-8 validation option, must specify boolean values");
  3194. }
  3195. validationSetting = utf8ValidationValues[0];
  3196. if (!utf8ValidationValues.every((item) => item === validationSetting)) {
  3197. throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false");
  3198. }
  3199. }
  3200. if (!globalUTFValidation) {
  3201. for (const key of Object.keys(utf8ValidatedKeys)) {
  3202. utf8KeysSet.add(key);
  3203. }
  3204. }
  3205. const startIndex = index;
  3206. if (buffer2.length < 5)
  3207. throw new BSONError("corrupt bson message < 5 bytes long");
  3208. const size = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3209. if (size < 5 || size > buffer2.length)
  3210. throw new BSONError("corrupt bson message");
  3211. const object = isArray ? [] : {};
  3212. let arrayIndex = 0;
  3213. const done = false;
  3214. let isPossibleDBRef = isArray ? false : null;
  3215. const dataview = new DataView(buffer2.buffer, buffer2.byteOffset, buffer2.byteLength);
  3216. while (!done) {
  3217. const elementType = buffer2[index++];
  3218. if (elementType === 0)
  3219. break;
  3220. let i = index;
  3221. while (buffer2[i] !== 0 && i < buffer2.length) {
  3222. i++;
  3223. }
  3224. if (i >= buffer2.byteLength)
  3225. throw new BSONError("Bad BSON Document: illegal CString");
  3226. const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer2, index, i);
  3227. let shouldValidateKey = true;
  3228. if (globalUTFValidation || utf8KeysSet.has(name)) {
  3229. shouldValidateKey = validationSetting;
  3230. } else {
  3231. shouldValidateKey = !validationSetting;
  3232. }
  3233. if (isPossibleDBRef !== false && name[0] === "$") {
  3234. isPossibleDBRef = allowedDBRefKeys.test(name);
  3235. }
  3236. let value;
  3237. index = i + 1;
  3238. if (elementType === BSON_DATA_STRING) {
  3239. const stringSize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3240. if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) {
  3241. throw new BSONError("bad string length in bson");
  3242. }
  3243. value = getValidatedString(buffer2, index, index + stringSize - 1, shouldValidateKey);
  3244. index = index + stringSize;
  3245. } else if (elementType === BSON_DATA_OID) {
  3246. const oid = ByteUtils.allocate(12);
  3247. oid.set(buffer2.subarray(index, index + 12));
  3248. value = new ObjectId3(oid);
  3249. index = index + 12;
  3250. } else if (elementType === BSON_DATA_INT && promoteValues === false) {
  3251. value = new Int32(buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24);
  3252. } else if (elementType === BSON_DATA_INT) {
  3253. value = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3254. } else if (elementType === BSON_DATA_NUMBER && promoteValues === false) {
  3255. value = new Double(dataview.getFloat64(index, true));
  3256. index = index + 8;
  3257. } else if (elementType === BSON_DATA_NUMBER) {
  3258. value = dataview.getFloat64(index, true);
  3259. index = index + 8;
  3260. } else if (elementType === BSON_DATA_DATE) {
  3261. const lowBits = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3262. const highBits = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3263. value = new Date(new Long(lowBits, highBits).toNumber());
  3264. } else if (elementType === BSON_DATA_BOOLEAN) {
  3265. if (buffer2[index] !== 0 && buffer2[index] !== 1)
  3266. throw new BSONError("illegal boolean type value");
  3267. value = buffer2[index++] === 1;
  3268. } else if (elementType === BSON_DATA_OBJECT) {
  3269. const _index = index;
  3270. const objectSize = buffer2[index] | buffer2[index + 1] << 8 | buffer2[index + 2] << 16 | buffer2[index + 3] << 24;
  3271. if (objectSize <= 0 || objectSize > buffer2.length - index)
  3272. throw new BSONError("bad embedded document length in bson");
  3273. if (raw) {
  3274. value = buffer2.slice(index, index + objectSize);
  3275. } else {
  3276. let objectOptions = options;
  3277. if (!globalUTFValidation) {
  3278. objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
  3279. }
  3280. value = deserializeObject(buffer2, _index, objectOptions, false);
  3281. }
  3282. index = index + objectSize;
  3283. } else if (elementType === BSON_DATA_ARRAY) {
  3284. const _index = index;
  3285. const objectSize = buffer2[index] | buffer2[index + 1] << 8 | buffer2[index + 2] << 16 | buffer2[index + 3] << 24;
  3286. let arrayOptions = options;
  3287. const stopIndex = index + objectSize;
  3288. if (fieldsAsRaw && fieldsAsRaw[name]) {
  3289. arrayOptions = { ...options, raw: true };
  3290. }
  3291. if (!globalUTFValidation) {
  3292. arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
  3293. }
  3294. value = deserializeObject(buffer2, _index, arrayOptions, true);
  3295. index = index + objectSize;
  3296. if (buffer2[index - 1] !== 0)
  3297. throw new BSONError("invalid array terminator byte");
  3298. if (index !== stopIndex)
  3299. throw new BSONError("corrupted array bson");
  3300. } else if (elementType === BSON_DATA_UNDEFINED) {
  3301. value = void 0;
  3302. } else if (elementType === BSON_DATA_NULL) {
  3303. value = null;
  3304. } else if (elementType === BSON_DATA_LONG) {
  3305. const dataview2 = BSONDataView.fromUint8Array(buffer2.subarray(index, index + 8));
  3306. const lowBits = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3307. const highBits = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3308. const long = new Long(lowBits, highBits);
  3309. if (useBigInt64) {
  3310. value = dataview2.getBigInt64(0, true);
  3311. } else if (promoteLongs && promoteValues === true) {
  3312. value = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long;
  3313. } else {
  3314. value = long;
  3315. }
  3316. } else if (elementType === BSON_DATA_DECIMAL128) {
  3317. const bytes = ByteUtils.allocate(16);
  3318. bytes.set(buffer2.subarray(index, index + 16), 0);
  3319. index = index + 16;
  3320. value = new Decimal128(bytes);
  3321. } else if (elementType === BSON_DATA_BINARY) {
  3322. let binarySize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3323. const totalBinarySize = binarySize;
  3324. const subType = buffer2[index++];
  3325. if (binarySize < 0)
  3326. throw new BSONError("Negative binary type element size found");
  3327. if (binarySize > buffer2.byteLength)
  3328. throw new BSONError("Binary type size larger than document size");
  3329. if (buffer2["slice"] != null) {
  3330. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  3331. binarySize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3332. if (binarySize < 0)
  3333. throw new BSONError("Negative binary type element size found for subtype 0x02");
  3334. if (binarySize > totalBinarySize - 4)
  3335. throw new BSONError("Binary type with subtype 0x02 contains too long binary size");
  3336. if (binarySize < totalBinarySize - 4)
  3337. throw new BSONError("Binary type with subtype 0x02 contains too short binary size");
  3338. }
  3339. if (promoteBuffers && promoteValues) {
  3340. value = ByteUtils.toLocalBufferType(buffer2.slice(index, index + binarySize));
  3341. } else {
  3342. value = new Binary(buffer2.slice(index, index + binarySize), subType);
  3343. if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
  3344. value = value.toUUID();
  3345. }
  3346. }
  3347. } else {
  3348. const _buffer = ByteUtils.allocate(binarySize);
  3349. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  3350. binarySize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3351. if (binarySize < 0)
  3352. throw new BSONError("Negative binary type element size found for subtype 0x02");
  3353. if (binarySize > totalBinarySize - 4)
  3354. throw new BSONError("Binary type with subtype 0x02 contains too long binary size");
  3355. if (binarySize < totalBinarySize - 4)
  3356. throw new BSONError("Binary type with subtype 0x02 contains too short binary size");
  3357. }
  3358. for (i = 0; i < binarySize; i++) {
  3359. _buffer[i] = buffer2[index + i];
  3360. }
  3361. if (promoteBuffers && promoteValues) {
  3362. value = _buffer;
  3363. } else {
  3364. value = new Binary(buffer2.slice(index, index + binarySize), subType);
  3365. if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
  3366. value = value.toUUID();
  3367. }
  3368. }
  3369. }
  3370. index = index + binarySize;
  3371. } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
  3372. i = index;
  3373. while (buffer2[i] !== 0 && i < buffer2.length) {
  3374. i++;
  3375. }
  3376. if (i >= buffer2.length)
  3377. throw new BSONError("Bad BSON Document: illegal CString");
  3378. const source = ByteUtils.toUTF8(buffer2, index, i);
  3379. index = i + 1;
  3380. i = index;
  3381. while (buffer2[i] !== 0 && i < buffer2.length) {
  3382. i++;
  3383. }
  3384. if (i >= buffer2.length)
  3385. throw new BSONError("Bad BSON Document: illegal CString");
  3386. const regExpOptions = ByteUtils.toUTF8(buffer2, index, i);
  3387. index = i + 1;
  3388. const optionsArray = new Array(regExpOptions.length);
  3389. for (i = 0; i < regExpOptions.length; i++) {
  3390. switch (regExpOptions[i]) {
  3391. case "m":
  3392. optionsArray[i] = "m";
  3393. break;
  3394. case "s":
  3395. optionsArray[i] = "g";
  3396. break;
  3397. case "i":
  3398. optionsArray[i] = "i";
  3399. break;
  3400. }
  3401. }
  3402. value = new RegExp(source, optionsArray.join(""));
  3403. } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
  3404. i = index;
  3405. while (buffer2[i] !== 0 && i < buffer2.length) {
  3406. i++;
  3407. }
  3408. if (i >= buffer2.length)
  3409. throw new BSONError("Bad BSON Document: illegal CString");
  3410. const source = ByteUtils.toUTF8(buffer2, index, i);
  3411. index = i + 1;
  3412. i = index;
  3413. while (buffer2[i] !== 0 && i < buffer2.length) {
  3414. i++;
  3415. }
  3416. if (i >= buffer2.length)
  3417. throw new BSONError("Bad BSON Document: illegal CString");
  3418. const regExpOptions = ByteUtils.toUTF8(buffer2, index, i);
  3419. index = i + 1;
  3420. value = new BSONRegExp(source, regExpOptions);
  3421. } else if (elementType === BSON_DATA_SYMBOL) {
  3422. const stringSize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3423. if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) {
  3424. throw new BSONError("bad string length in bson");
  3425. }
  3426. const symbol = getValidatedString(buffer2, index, index + stringSize - 1, shouldValidateKey);
  3427. value = promoteValues ? symbol : new BSONSymbol(symbol);
  3428. index = index + stringSize;
  3429. } else if (elementType === BSON_DATA_TIMESTAMP) {
  3430. const i2 = buffer2[index++] + buffer2[index++] * (1 << 8) + buffer2[index++] * (1 << 16) + buffer2[index++] * (1 << 24);
  3431. const t = buffer2[index++] + buffer2[index++] * (1 << 8) + buffer2[index++] * (1 << 16) + buffer2[index++] * (1 << 24);
  3432. value = new Timestamp({ i: i2, t });
  3433. } else if (elementType === BSON_DATA_MIN_KEY) {
  3434. value = new MinKey();
  3435. } else if (elementType === BSON_DATA_MAX_KEY) {
  3436. value = new MaxKey();
  3437. } else if (elementType === BSON_DATA_CODE) {
  3438. const stringSize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3439. if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) {
  3440. throw new BSONError("bad string length in bson");
  3441. }
  3442. const functionString = getValidatedString(buffer2, index, index + stringSize - 1, shouldValidateKey);
  3443. value = new Code(functionString);
  3444. index = index + stringSize;
  3445. } else if (elementType === BSON_DATA_CODE_W_SCOPE) {
  3446. const totalSize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3447. if (totalSize < 4 + 4 + 4 + 1) {
  3448. throw new BSONError("code_w_scope total size shorter minimum expected length");
  3449. }
  3450. const stringSize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3451. if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) {
  3452. throw new BSONError("bad string length in bson");
  3453. }
  3454. const functionString = getValidatedString(buffer2, index, index + stringSize - 1, shouldValidateKey);
  3455. index = index + stringSize;
  3456. const _index = index;
  3457. const objectSize = buffer2[index] | buffer2[index + 1] << 8 | buffer2[index + 2] << 16 | buffer2[index + 3] << 24;
  3458. const scopeObject = deserializeObject(buffer2, _index, options, false);
  3459. index = index + objectSize;
  3460. if (totalSize < 4 + 4 + objectSize + stringSize) {
  3461. throw new BSONError("code_w_scope total size is too short, truncating scope");
  3462. }
  3463. if (totalSize > 4 + 4 + objectSize + stringSize) {
  3464. throw new BSONError("code_w_scope total size is too long, clips outer document");
  3465. }
  3466. value = new Code(functionString, scopeObject);
  3467. } else if (elementType === BSON_DATA_DBPOINTER) {
  3468. const stringSize = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
  3469. if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0)
  3470. throw new BSONError("bad string length in bson");
  3471. if (validation != null && validation.utf8) {
  3472. if (!validateUtf8(buffer2, index, index + stringSize - 1)) {
  3473. throw new BSONError("Invalid UTF-8 string in BSON document");
  3474. }
  3475. }
  3476. const namespace = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1);
  3477. index = index + stringSize;
  3478. const oidBuffer = ByteUtils.allocate(12);
  3479. oidBuffer.set(buffer2.subarray(index, index + 12), 0);
  3480. const oid = new ObjectId3(oidBuffer);
  3481. index = index + 12;
  3482. value = new DBRef(namespace, oid);
  3483. } else {
  3484. throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
  3485. }
  3486. if (name === "__proto__") {
  3487. Object.defineProperty(object, name, {
  3488. value,
  3489. writable: true,
  3490. enumerable: true,
  3491. configurable: true
  3492. });
  3493. } else {
  3494. object[name] = value;
  3495. }
  3496. }
  3497. if (size !== index - startIndex) {
  3498. if (isArray)
  3499. throw new BSONError("corrupt array bson");
  3500. throw new BSONError("corrupt object bson");
  3501. }
  3502. if (!isPossibleDBRef)
  3503. return object;
  3504. if (isDBRefLike(object)) {
  3505. const copy = Object.assign({}, object);
  3506. delete copy.$ref;
  3507. delete copy.$id;
  3508. delete copy.$db;
  3509. return new DBRef(object.$ref, object.$id, object.$db, copy);
  3510. }
  3511. return object;
  3512. }
  3513. __name(deserializeObject, "deserializeObject");
  3514. function getValidatedString(buffer2, start, end, shouldValidateUtf8) {
  3515. const value = ByteUtils.toUTF8(buffer2, start, end);
  3516. if (shouldValidateUtf8) {
  3517. for (let i = 0; i < value.length; i++) {
  3518. if (value.charCodeAt(i) === 65533) {
  3519. if (!validateUtf8(buffer2, start, end)) {
  3520. throw new BSONError("Invalid UTF-8 string in BSON document");
  3521. }
  3522. break;
  3523. }
  3524. }
  3525. }
  3526. return value;
  3527. }
  3528. __name(getValidatedString, "getValidatedString");
  3529. var regexp = /\x00/;
  3530. var ignoreKeys = /* @__PURE__ */ new Set(["$db", "$ref", "$id", "$clusterTime"]);
  3531. function serializeString(buffer2, key, value, index) {
  3532. buffer2[index++] = BSON_DATA_STRING;
  3533. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3534. index = index + numberOfWrittenBytes + 1;
  3535. buffer2[index - 1] = 0;
  3536. const size = ByteUtils.encodeUTF8Into(buffer2, value, index + 4);
  3537. buffer2[index + 3] = size + 1 >> 24 & 255;
  3538. buffer2[index + 2] = size + 1 >> 16 & 255;
  3539. buffer2[index + 1] = size + 1 >> 8 & 255;
  3540. buffer2[index] = size + 1 & 255;
  3541. index = index + 4 + size;
  3542. buffer2[index++] = 0;
  3543. return index;
  3544. }
  3545. __name(serializeString, "serializeString");
  3546. var NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8);
  3547. var FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4);
  3548. var EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8);
  3549. function serializeNumber(buffer2, key, value, index) {
  3550. const isNegativeZero = Object.is(value, -0);
  3551. const type = !isNegativeZero && Number.isSafeInteger(value) && value <= BSON_INT32_MAX && value >= BSON_INT32_MIN ? BSON_DATA_INT : BSON_DATA_NUMBER;
  3552. if (type === BSON_DATA_INT) {
  3553. NUMBER_SPACE.setInt32(0, value, true);
  3554. } else {
  3555. NUMBER_SPACE.setFloat64(0, value, true);
  3556. }
  3557. const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER;
  3558. buffer2[index++] = type;
  3559. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3560. index = index + numberOfWrittenBytes;
  3561. buffer2[index++] = 0;
  3562. buffer2.set(bytes, index);
  3563. index += bytes.byteLength;
  3564. return index;
  3565. }
  3566. __name(serializeNumber, "serializeNumber");
  3567. function serializeBigInt(buffer2, key, value, index) {
  3568. buffer2[index++] = BSON_DATA_LONG;
  3569. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3570. index += numberOfWrittenBytes;
  3571. buffer2[index++] = 0;
  3572. NUMBER_SPACE.setBigInt64(0, value, true);
  3573. buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
  3574. index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;
  3575. return index;
  3576. }
  3577. __name(serializeBigInt, "serializeBigInt");
  3578. function serializeNull(buffer2, key, _, index) {
  3579. buffer2[index++] = BSON_DATA_NULL;
  3580. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3581. index = index + numberOfWrittenBytes;
  3582. buffer2[index++] = 0;
  3583. return index;
  3584. }
  3585. __name(serializeNull, "serializeNull");
  3586. function serializeBoolean(buffer2, key, value, index) {
  3587. buffer2[index++] = BSON_DATA_BOOLEAN;
  3588. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3589. index = index + numberOfWrittenBytes;
  3590. buffer2[index++] = 0;
  3591. buffer2[index++] = value ? 1 : 0;
  3592. return index;
  3593. }
  3594. __name(serializeBoolean, "serializeBoolean");
  3595. function serializeDate(buffer2, key, value, index) {
  3596. buffer2[index++] = BSON_DATA_DATE;
  3597. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3598. index = index + numberOfWrittenBytes;
  3599. buffer2[index++] = 0;
  3600. const dateInMilis = Long.fromNumber(value.getTime());
  3601. const lowBits = dateInMilis.getLowBits();
  3602. const highBits = dateInMilis.getHighBits();
  3603. buffer2[index++] = lowBits & 255;
  3604. buffer2[index++] = lowBits >> 8 & 255;
  3605. buffer2[index++] = lowBits >> 16 & 255;
  3606. buffer2[index++] = lowBits >> 24 & 255;
  3607. buffer2[index++] = highBits & 255;
  3608. buffer2[index++] = highBits >> 8 & 255;
  3609. buffer2[index++] = highBits >> 16 & 255;
  3610. buffer2[index++] = highBits >> 24 & 255;
  3611. return index;
  3612. }
  3613. __name(serializeDate, "serializeDate");
  3614. function serializeRegExp(buffer2, key, value, index) {
  3615. buffer2[index++] = BSON_DATA_REGEXP;
  3616. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3617. index = index + numberOfWrittenBytes;
  3618. buffer2[index++] = 0;
  3619. if (value.source && value.source.match(regexp) != null) {
  3620. throw new BSONError("value " + value.source + " must not contain null bytes");
  3621. }
  3622. index = index + ByteUtils.encodeUTF8Into(buffer2, value.source, index);
  3623. buffer2[index++] = 0;
  3624. if (value.ignoreCase)
  3625. buffer2[index++] = 105;
  3626. if (value.global)
  3627. buffer2[index++] = 115;
  3628. if (value.multiline)
  3629. buffer2[index++] = 109;
  3630. buffer2[index++] = 0;
  3631. return index;
  3632. }
  3633. __name(serializeRegExp, "serializeRegExp");
  3634. function serializeBSONRegExp(buffer2, key, value, index) {
  3635. buffer2[index++] = BSON_DATA_REGEXP;
  3636. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3637. index = index + numberOfWrittenBytes;
  3638. buffer2[index++] = 0;
  3639. if (value.pattern.match(regexp) != null) {
  3640. throw new BSONError("pattern " + value.pattern + " must not contain null bytes");
  3641. }
  3642. index = index + ByteUtils.encodeUTF8Into(buffer2, value.pattern, index);
  3643. buffer2[index++] = 0;
  3644. const sortedOptions = value.options.split("").sort().join("");
  3645. index = index + ByteUtils.encodeUTF8Into(buffer2, sortedOptions, index);
  3646. buffer2[index++] = 0;
  3647. return index;
  3648. }
  3649. __name(serializeBSONRegExp, "serializeBSONRegExp");
  3650. function serializeMinMax(buffer2, key, value, index) {
  3651. if (value === null) {
  3652. buffer2[index++] = BSON_DATA_NULL;
  3653. } else if (value._bsontype === "MinKey") {
  3654. buffer2[index++] = BSON_DATA_MIN_KEY;
  3655. } else {
  3656. buffer2[index++] = BSON_DATA_MAX_KEY;
  3657. }
  3658. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3659. index = index + numberOfWrittenBytes;
  3660. buffer2[index++] = 0;
  3661. return index;
  3662. }
  3663. __name(serializeMinMax, "serializeMinMax");
  3664. function serializeObjectId(buffer2, key, value, index) {
  3665. buffer2[index++] = BSON_DATA_OID;
  3666. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3667. index = index + numberOfWrittenBytes;
  3668. buffer2[index++] = 0;
  3669. if (isUint8Array(value.id)) {
  3670. buffer2.set(value.id.subarray(0, 12), index);
  3671. } else {
  3672. throw new BSONError("object [" + JSON.stringify(value) + "] is not a valid ObjectId");
  3673. }
  3674. return index + 12;
  3675. }
  3676. __name(serializeObjectId, "serializeObjectId");
  3677. function serializeBuffer(buffer2, key, value, index) {
  3678. buffer2[index++] = BSON_DATA_BINARY;
  3679. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3680. index = index + numberOfWrittenBytes;
  3681. buffer2[index++] = 0;
  3682. const size = value.length;
  3683. buffer2[index++] = size & 255;
  3684. buffer2[index++] = size >> 8 & 255;
  3685. buffer2[index++] = size >> 16 & 255;
  3686. buffer2[index++] = size >> 24 & 255;
  3687. buffer2[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
  3688. buffer2.set(value, index);
  3689. index = index + size;
  3690. return index;
  3691. }
  3692. __name(serializeBuffer, "serializeBuffer");
  3693. function serializeObject(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
  3694. if (path.has(value)) {
  3695. throw new BSONError("Cannot convert circular structure to BSON");
  3696. }
  3697. path.add(value);
  3698. buffer2[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
  3699. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3700. index = index + numberOfWrittenBytes;
  3701. buffer2[index++] = 0;
  3702. const endIndex = serializeInto(buffer2, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  3703. path.delete(value);
  3704. return endIndex;
  3705. }
  3706. __name(serializeObject, "serializeObject");
  3707. function serializeDecimal128(buffer2, key, value, index) {
  3708. buffer2[index++] = BSON_DATA_DECIMAL128;
  3709. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3710. index = index + numberOfWrittenBytes;
  3711. buffer2[index++] = 0;
  3712. buffer2.set(value.bytes.subarray(0, 16), index);
  3713. return index + 16;
  3714. }
  3715. __name(serializeDecimal128, "serializeDecimal128");
  3716. function serializeLong(buffer2, key, value, index) {
  3717. buffer2[index++] = value._bsontype === "Long" ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
  3718. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3719. index = index + numberOfWrittenBytes;
  3720. buffer2[index++] = 0;
  3721. const lowBits = value.getLowBits();
  3722. const highBits = value.getHighBits();
  3723. buffer2[index++] = lowBits & 255;
  3724. buffer2[index++] = lowBits >> 8 & 255;
  3725. buffer2[index++] = lowBits >> 16 & 255;
  3726. buffer2[index++] = lowBits >> 24 & 255;
  3727. buffer2[index++] = highBits & 255;
  3728. buffer2[index++] = highBits >> 8 & 255;
  3729. buffer2[index++] = highBits >> 16 & 255;
  3730. buffer2[index++] = highBits >> 24 & 255;
  3731. return index;
  3732. }
  3733. __name(serializeLong, "serializeLong");
  3734. function serializeInt32(buffer2, key, value, index) {
  3735. value = value.valueOf();
  3736. buffer2[index++] = BSON_DATA_INT;
  3737. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3738. index = index + numberOfWrittenBytes;
  3739. buffer2[index++] = 0;
  3740. buffer2[index++] = value & 255;
  3741. buffer2[index++] = value >> 8 & 255;
  3742. buffer2[index++] = value >> 16 & 255;
  3743. buffer2[index++] = value >> 24 & 255;
  3744. return index;
  3745. }
  3746. __name(serializeInt32, "serializeInt32");
  3747. function serializeDouble(buffer2, key, value, index) {
  3748. buffer2[index++] = BSON_DATA_NUMBER;
  3749. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3750. index = index + numberOfWrittenBytes;
  3751. buffer2[index++] = 0;
  3752. NUMBER_SPACE.setFloat64(0, value.value, true);
  3753. buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
  3754. index = index + 8;
  3755. return index;
  3756. }
  3757. __name(serializeDouble, "serializeDouble");
  3758. function serializeFunction(buffer2, key, value, index) {
  3759. buffer2[index++] = BSON_DATA_CODE;
  3760. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3761. index = index + numberOfWrittenBytes;
  3762. buffer2[index++] = 0;
  3763. const functionString = value.toString();
  3764. const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1;
  3765. buffer2[index] = size & 255;
  3766. buffer2[index + 1] = size >> 8 & 255;
  3767. buffer2[index + 2] = size >> 16 & 255;
  3768. buffer2[index + 3] = size >> 24 & 255;
  3769. index = index + 4 + size - 1;
  3770. buffer2[index++] = 0;
  3771. return index;
  3772. }
  3773. __name(serializeFunction, "serializeFunction");
  3774. function serializeCode(buffer2, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
  3775. if (value.scope && typeof value.scope === "object") {
  3776. buffer2[index++] = BSON_DATA_CODE_W_SCOPE;
  3777. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3778. index = index + numberOfWrittenBytes;
  3779. buffer2[index++] = 0;
  3780. let startIndex = index;
  3781. const functionString = value.code;
  3782. index = index + 4;
  3783. const codeSize = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1;
  3784. buffer2[index] = codeSize & 255;
  3785. buffer2[index + 1] = codeSize >> 8 & 255;
  3786. buffer2[index + 2] = codeSize >> 16 & 255;
  3787. buffer2[index + 3] = codeSize >> 24 & 255;
  3788. buffer2[index + 4 + codeSize - 1] = 0;
  3789. index = index + codeSize + 4;
  3790. const endIndex = serializeInto(buffer2, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  3791. index = endIndex - 1;
  3792. const totalSize = endIndex - startIndex;
  3793. buffer2[startIndex++] = totalSize & 255;
  3794. buffer2[startIndex++] = totalSize >> 8 & 255;
  3795. buffer2[startIndex++] = totalSize >> 16 & 255;
  3796. buffer2[startIndex++] = totalSize >> 24 & 255;
  3797. buffer2[index++] = 0;
  3798. } else {
  3799. buffer2[index++] = BSON_DATA_CODE;
  3800. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3801. index = index + numberOfWrittenBytes;
  3802. buffer2[index++] = 0;
  3803. const functionString = value.code.toString();
  3804. const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1;
  3805. buffer2[index] = size & 255;
  3806. buffer2[index + 1] = size >> 8 & 255;
  3807. buffer2[index + 2] = size >> 16 & 255;
  3808. buffer2[index + 3] = size >> 24 & 255;
  3809. index = index + 4 + size - 1;
  3810. buffer2[index++] = 0;
  3811. }
  3812. return index;
  3813. }
  3814. __name(serializeCode, "serializeCode");
  3815. function serializeBinary(buffer2, key, value, index) {
  3816. buffer2[index++] = BSON_DATA_BINARY;
  3817. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3818. index = index + numberOfWrittenBytes;
  3819. buffer2[index++] = 0;
  3820. const data = value.buffer;
  3821. let size = value.position;
  3822. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
  3823. size = size + 4;
  3824. buffer2[index++] = size & 255;
  3825. buffer2[index++] = size >> 8 & 255;
  3826. buffer2[index++] = size >> 16 & 255;
  3827. buffer2[index++] = size >> 24 & 255;
  3828. buffer2[index++] = value.sub_type;
  3829. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  3830. size = size - 4;
  3831. buffer2[index++] = size & 255;
  3832. buffer2[index++] = size >> 8 & 255;
  3833. buffer2[index++] = size >> 16 & 255;
  3834. buffer2[index++] = size >> 24 & 255;
  3835. }
  3836. buffer2.set(data, index);
  3837. index = index + value.position;
  3838. return index;
  3839. }
  3840. __name(serializeBinary, "serializeBinary");
  3841. function serializeSymbol(buffer2, key, value, index) {
  3842. buffer2[index++] = BSON_DATA_SYMBOL;
  3843. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3844. index = index + numberOfWrittenBytes;
  3845. buffer2[index++] = 0;
  3846. const size = ByteUtils.encodeUTF8Into(buffer2, value.value, index + 4) + 1;
  3847. buffer2[index] = size & 255;
  3848. buffer2[index + 1] = size >> 8 & 255;
  3849. buffer2[index + 2] = size >> 16 & 255;
  3850. buffer2[index + 3] = size >> 24 & 255;
  3851. index = index + 4 + size - 1;
  3852. buffer2[index++] = 0;
  3853. return index;
  3854. }
  3855. __name(serializeSymbol, "serializeSymbol");
  3856. function serializeDBRef(buffer2, key, value, index, depth, serializeFunctions, path) {
  3857. buffer2[index++] = BSON_DATA_OBJECT;
  3858. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index);
  3859. index = index + numberOfWrittenBytes;
  3860. buffer2[index++] = 0;
  3861. let startIndex = index;
  3862. let output = {
  3863. $ref: value.collection || value.namespace,
  3864. $id: value.oid
  3865. };
  3866. if (value.db != null) {
  3867. output.$db = value.db;
  3868. }
  3869. output = Object.assign(output, value.fields);
  3870. const endIndex = serializeInto(buffer2, output, false, index, depth + 1, serializeFunctions, true, path);
  3871. const size = endIndex - startIndex;
  3872. buffer2[startIndex++] = size & 255;
  3873. buffer2[startIndex++] = size >> 8 & 255;
  3874. buffer2[startIndex++] = size >> 16 & 255;
  3875. buffer2[startIndex++] = size >> 24 & 255;
  3876. return endIndex;
  3877. }
  3878. __name(serializeDBRef, "serializeDBRef");
  3879. function serializeInto(buffer2, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  3880. if (path == null) {
  3881. if (object == null) {
  3882. buffer2[0] = 5;
  3883. buffer2[1] = 0;
  3884. buffer2[2] = 0;
  3885. buffer2[3] = 0;
  3886. buffer2[4] = 0;
  3887. return 5;
  3888. }
  3889. if (Array.isArray(object)) {
  3890. throw new BSONError("serialize does not support an array as the root input");
  3891. }
  3892. if (typeof object !== "object") {
  3893. throw new BSONError("serialize does not support non-object as the root input");
  3894. } else if ("_bsontype" in object && typeof object._bsontype === "string") {
  3895. throw new BSONError(`BSON types cannot be serialized as a document`);
  3896. } else if (isDate(object) || isRegExp(object) || isUint8Array(object) || isAnyArrayBuffer(object)) {
  3897. throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
  3898. }
  3899. path = /* @__PURE__ */ new Set();
  3900. }
  3901. path.add(object);
  3902. let index = startingIndex + 4;
  3903. if (Array.isArray(object)) {
  3904. for (let i = 0; i < object.length; i++) {
  3905. const key = `${i}`;
  3906. let value = object[i];
  3907. if (typeof (value == null ? void 0 : value.toBSON) === "function") {
  3908. value = value.toBSON();
  3909. }
  3910. if (typeof value === "string") {
  3911. index = serializeString(buffer2, key, value, index);
  3912. } else if (typeof value === "number") {
  3913. index = serializeNumber(buffer2, key, value, index);
  3914. } else if (typeof value === "bigint") {
  3915. index = serializeBigInt(buffer2, key, value, index);
  3916. } else if (typeof value === "boolean") {
  3917. index = serializeBoolean(buffer2, key, value, index);
  3918. } else if (value instanceof Date || isDate(value)) {
  3919. index = serializeDate(buffer2, key, value, index);
  3920. } else if (value === void 0) {
  3921. index = serializeNull(buffer2, key, value, index);
  3922. } else if (value === null) {
  3923. index = serializeNull(buffer2, key, value, index);
  3924. } else if (isUint8Array(value)) {
  3925. index = serializeBuffer(buffer2, key, value, index);
  3926. } else if (value instanceof RegExp || isRegExp(value)) {
  3927. index = serializeRegExp(buffer2, key, value, index);
  3928. } else if (typeof value === "object" && value._bsontype == null) {
  3929. index = serializeObject(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3930. } else if (typeof value === "object" && value[Symbol.for("@@mdb.bson.version")] !== BSON_MAJOR_VERSION) {
  3931. throw new BSONVersionError();
  3932. } else if (value._bsontype === "ObjectId") {
  3933. index = serializeObjectId(buffer2, key, value, index);
  3934. } else if (value._bsontype === "Decimal128") {
  3935. index = serializeDecimal128(buffer2, key, value, index);
  3936. } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") {
  3937. index = serializeLong(buffer2, key, value, index);
  3938. } else if (value._bsontype === "Double") {
  3939. index = serializeDouble(buffer2, key, value, index);
  3940. } else if (typeof value === "function" && serializeFunctions) {
  3941. index = serializeFunction(buffer2, key, value, index);
  3942. } else if (value._bsontype === "Code") {
  3943. index = serializeCode(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3944. } else if (value._bsontype === "Binary") {
  3945. index = serializeBinary(buffer2, key, value, index);
  3946. } else if (value._bsontype === "BSONSymbol") {
  3947. index = serializeSymbol(buffer2, key, value, index);
  3948. } else if (value._bsontype === "DBRef") {
  3949. index = serializeDBRef(buffer2, key, value, index, depth, serializeFunctions, path);
  3950. } else if (value._bsontype === "BSONRegExp") {
  3951. index = serializeBSONRegExp(buffer2, key, value, index);
  3952. } else if (value._bsontype === "Int32") {
  3953. index = serializeInt32(buffer2, key, value, index);
  3954. } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") {
  3955. index = serializeMinMax(buffer2, key, value, index);
  3956. } else if (typeof value._bsontype !== "undefined") {
  3957. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3958. }
  3959. }
  3960. } else if (object instanceof Map || isMap(object)) {
  3961. const iterator = object.entries();
  3962. let done = false;
  3963. while (!done) {
  3964. const entry = iterator.next();
  3965. done = !!entry.done;
  3966. if (done)
  3967. continue;
  3968. const key = entry.value[0];
  3969. let value = entry.value[1];
  3970. if (typeof (value == null ? void 0 : value.toBSON) === "function") {
  3971. value = value.toBSON();
  3972. }
  3973. const type = typeof value;
  3974. if (typeof key === "string" && !ignoreKeys.has(key)) {
  3975. if (key.match(regexp) != null) {
  3976. throw new BSONError("key " + key + " must not contain null bytes");
  3977. }
  3978. if (checkKeys) {
  3979. if ("$" === key[0]) {
  3980. throw new BSONError("key " + key + " must not start with '$'");
  3981. } else if (~key.indexOf(".")) {
  3982. throw new BSONError("key " + key + " must not contain '.'");
  3983. }
  3984. }
  3985. }
  3986. if (type === "string") {
  3987. index = serializeString(buffer2, key, value, index);
  3988. } else if (type === "number") {
  3989. index = serializeNumber(buffer2, key, value, index);
  3990. } else if (type === "bigint") {
  3991. index = serializeBigInt(buffer2, key, value, index);
  3992. } else if (type === "boolean") {
  3993. index = serializeBoolean(buffer2, key, value, index);
  3994. } else if (value instanceof Date || isDate(value)) {
  3995. index = serializeDate(buffer2, key, value, index);
  3996. } else if (value === null || value === void 0 && ignoreUndefined === false) {
  3997. index = serializeNull(buffer2, key, value, index);
  3998. } else if (isUint8Array(value)) {
  3999. index = serializeBuffer(buffer2, key, value, index);
  4000. } else if (value instanceof RegExp || isRegExp(value)) {
  4001. index = serializeRegExp(buffer2, key, value, index);
  4002. } else if (type === "object" && value._bsontype == null) {
  4003. index = serializeObject(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  4004. } else if (typeof value === "object" && value[Symbol.for("@@mdb.bson.version")] !== BSON_MAJOR_VERSION) {
  4005. throw new BSONVersionError();
  4006. } else if (value._bsontype === "ObjectId") {
  4007. index = serializeObjectId(buffer2, key, value, index);
  4008. } else if (type === "object" && value._bsontype === "Decimal128") {
  4009. index = serializeDecimal128(buffer2, key, value, index);
  4010. } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") {
  4011. index = serializeLong(buffer2, key, value, index);
  4012. } else if (value._bsontype === "Double") {
  4013. index = serializeDouble(buffer2, key, value, index);
  4014. } else if (value._bsontype === "Code") {
  4015. index = serializeCode(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  4016. } else if (typeof value === "function" && serializeFunctions) {
  4017. index = serializeFunction(buffer2, key, value, index);
  4018. } else if (value._bsontype === "Binary") {
  4019. index = serializeBinary(buffer2, key, value, index);
  4020. } else if (value._bsontype === "BSONSymbol") {
  4021. index = serializeSymbol(buffer2, key, value, index);
  4022. } else if (value._bsontype === "DBRef") {
  4023. index = serializeDBRef(buffer2, key, value, index, depth, serializeFunctions, path);
  4024. } else if (value._bsontype === "BSONRegExp") {
  4025. index = serializeBSONRegExp(buffer2, key, value, index);
  4026. } else if (value._bsontype === "Int32") {
  4027. index = serializeInt32(buffer2, key, value, index);
  4028. } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") {
  4029. index = serializeMinMax(buffer2, key, value, index);
  4030. } else if (typeof value._bsontype !== "undefined") {
  4031. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  4032. }
  4033. }
  4034. } else {
  4035. if (typeof (object == null ? void 0 : object.toBSON) === "function") {
  4036. object = object.toBSON();
  4037. if (object != null && typeof object !== "object") {
  4038. throw new BSONError("toBSON function did not return an object");
  4039. }
  4040. }
  4041. for (const key of Object.keys(object)) {
  4042. let value = object[key];
  4043. if (typeof (value == null ? void 0 : value.toBSON) === "function") {
  4044. value = value.toBSON();
  4045. }
  4046. const type = typeof value;
  4047. if (typeof key === "string" && !ignoreKeys.has(key)) {
  4048. if (key.match(regexp) != null) {
  4049. throw new BSONError("key " + key + " must not contain null bytes");
  4050. }
  4051. if (checkKeys) {
  4052. if ("$" === key[0]) {
  4053. throw new BSONError("key " + key + " must not start with '$'");
  4054. } else if (~key.indexOf(".")) {
  4055. throw new BSONError("key " + key + " must not contain '.'");
  4056. }
  4057. }
  4058. }
  4059. if (type === "string") {
  4060. index = serializeString(buffer2, key, value, index);
  4061. } else if (type === "number") {
  4062. index = serializeNumber(buffer2, key, value, index);
  4063. } else if (type === "bigint") {
  4064. index = serializeBigInt(buffer2, key, value, index);
  4065. } else if (type === "boolean") {
  4066. index = serializeBoolean(buffer2, key, value, index);
  4067. } else if (value instanceof Date || isDate(value)) {
  4068. index = serializeDate(buffer2, key, value, index);
  4069. } else if (value === void 0) {
  4070. if (ignoreUndefined === false)
  4071. index = serializeNull(buffer2, key, value, index);
  4072. } else if (value === null) {
  4073. index = serializeNull(buffer2, key, value, index);
  4074. } else if (isUint8Array(value)) {
  4075. index = serializeBuffer(buffer2, key, value, index);
  4076. } else if (value instanceof RegExp || isRegExp(value)) {
  4077. index = serializeRegExp(buffer2, key, value, index);
  4078. } else if (type === "object" && value._bsontype == null) {
  4079. index = serializeObject(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  4080. } else if (typeof value === "object" && value[Symbol.for("@@mdb.bson.version")] !== BSON_MAJOR_VERSION) {
  4081. throw new BSONVersionError();
  4082. } else if (value._bsontype === "ObjectId") {
  4083. index = serializeObjectId(buffer2, key, value, index);
  4084. } else if (type === "object" && value._bsontype === "Decimal128") {
  4085. index = serializeDecimal128(buffer2, key, value, index);
  4086. } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") {
  4087. index = serializeLong(buffer2, key, value, index);
  4088. } else if (value._bsontype === "Double") {
  4089. index = serializeDouble(buffer2, key, value, index);
  4090. } else if (value._bsontype === "Code") {
  4091. index = serializeCode(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  4092. } else if (typeof value === "function" && serializeFunctions) {
  4093. index = serializeFunction(buffer2, key, value, index);
  4094. } else if (value._bsontype === "Binary") {
  4095. index = serializeBinary(buffer2, key, value, index);
  4096. } else if (value._bsontype === "BSONSymbol") {
  4097. index = serializeSymbol(buffer2, key, value, index);
  4098. } else if (value._bsontype === "DBRef") {
  4099. index = serializeDBRef(buffer2, key, value, index, depth, serializeFunctions, path);
  4100. } else if (value._bsontype === "BSONRegExp") {
  4101. index = serializeBSONRegExp(buffer2, key, value, index);
  4102. } else if (value._bsontype === "Int32") {
  4103. index = serializeInt32(buffer2, key, value, index);
  4104. } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") {
  4105. index = serializeMinMax(buffer2, key, value, index);
  4106. } else if (typeof value._bsontype !== "undefined") {
  4107. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  4108. }
  4109. }
  4110. }
  4111. path.delete(object);
  4112. buffer2[index++] = 0;
  4113. const size = index - startingIndex;
  4114. buffer2[startingIndex++] = size & 255;
  4115. buffer2[startingIndex++] = size >> 8 & 255;
  4116. buffer2[startingIndex++] = size >> 16 & 255;
  4117. buffer2[startingIndex++] = size >> 24 & 255;
  4118. return index;
  4119. }
  4120. __name(serializeInto, "serializeInto");
  4121. function isBSONType(value) {
  4122. return value != null && typeof value === "object" && "_bsontype" in value && typeof value._bsontype === "string";
  4123. }
  4124. __name(isBSONType, "isBSONType");
  4125. var keysToCodecs = {
  4126. $oid: ObjectId3,
  4127. $binary: Binary,
  4128. $uuid: Binary,
  4129. $symbol: BSONSymbol,
  4130. $numberInt: Int32,
  4131. $numberDecimal: Decimal128,
  4132. $numberDouble: Double,
  4133. $numberLong: Long,
  4134. $minKey: MinKey,
  4135. $maxKey: MaxKey,
  4136. $regex: BSONRegExp,
  4137. $regularExpression: BSONRegExp,
  4138. $timestamp: Timestamp
  4139. };
  4140. function deserializeValue(value, options = {}) {
  4141. if (typeof value === "number") {
  4142. const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
  4143. const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
  4144. if (options.relaxed || options.legacy) {
  4145. return value;
  4146. }
  4147. if (Number.isInteger(value) && !Object.is(value, -0)) {
  4148. if (in32BitRange) {
  4149. return new Int32(value);
  4150. }
  4151. if (in64BitRange) {
  4152. if (options.useBigInt64) {
  4153. return BigInt(value);
  4154. }
  4155. return Long.fromNumber(value);
  4156. }
  4157. }
  4158. return new Double(value);
  4159. }
  4160. if (value == null || typeof value !== "object")
  4161. return value;
  4162. if (value.$undefined)
  4163. return null;
  4164. const keys = Object.keys(value).filter((k) => k.startsWith("$") && value[k] != null);
  4165. for (let i = 0; i < keys.length; i++) {
  4166. const c = keysToCodecs[keys[i]];
  4167. if (c)
  4168. return c.fromExtendedJSON(value, options);
  4169. }
  4170. if (value.$date != null) {
  4171. const d = value.$date;
  4172. const date = /* @__PURE__ */ new Date();
  4173. if (options.legacy) {
  4174. if (typeof d === "number")
  4175. date.setTime(d);
  4176. else if (typeof d === "string")
  4177. date.setTime(Date.parse(d));
  4178. else if (typeof d === "bigint")
  4179. date.setTime(Number(d));
  4180. else
  4181. throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
  4182. } else {
  4183. if (typeof d === "string")
  4184. date.setTime(Date.parse(d));
  4185. else if (Long.isLong(d))
  4186. date.setTime(d.toNumber());
  4187. else if (typeof d === "number" && options.relaxed)
  4188. date.setTime(d);
  4189. else if (typeof d === "bigint")
  4190. date.setTime(Number(d));
  4191. else
  4192. throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
  4193. }
  4194. return date;
  4195. }
  4196. if (value.$code != null) {
  4197. const copy = Object.assign({}, value);
  4198. if (value.$scope) {
  4199. copy.$scope = deserializeValue(value.$scope);
  4200. }
  4201. return Code.fromExtendedJSON(value);
  4202. }
  4203. if (isDBRefLike(value) || value.$dbPointer) {
  4204. const v = value.$ref ? value : value.$dbPointer;
  4205. if (v instanceof DBRef)
  4206. return v;
  4207. const dollarKeys = Object.keys(v).filter((k) => k.startsWith("$"));
  4208. let valid = true;
  4209. dollarKeys.forEach((k) => {
  4210. if (["$ref", "$id", "$db"].indexOf(k) === -1)
  4211. valid = false;
  4212. });
  4213. if (valid)
  4214. return DBRef.fromExtendedJSON(v);
  4215. }
  4216. return value;
  4217. }
  4218. __name(deserializeValue, "deserializeValue");
  4219. function serializeArray(array, options) {
  4220. return array.map((v, index) => {
  4221. options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
  4222. try {
  4223. return serializeValue(v, options);
  4224. } finally {
  4225. options.seenObjects.pop();
  4226. }
  4227. });
  4228. }
  4229. __name(serializeArray, "serializeArray");
  4230. function getISOString(date) {
  4231. const isoStr = date.toISOString();
  4232. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + "Z";
  4233. }
  4234. __name(getISOString, "getISOString");
  4235. function serializeValue(value, options) {
  4236. if (value instanceof Map || isMap(value)) {
  4237. const obj = /* @__PURE__ */ Object.create(null);
  4238. for (const [k, v] of value) {
  4239. if (typeof k !== "string") {
  4240. throw new BSONError("Can only serialize maps with string keys");
  4241. }
  4242. obj[k] = v;
  4243. }
  4244. return serializeValue(obj, options);
  4245. }
  4246. if ((typeof value === "object" || typeof value === "function") && value !== null) {
  4247. const index = options.seenObjects.findIndex((entry) => entry.obj === value);
  4248. if (index !== -1) {
  4249. const props = options.seenObjects.map((entry) => entry.propertyName);
  4250. const leadingPart = props.slice(0, index).map((prop) => `${prop} -> `).join("");
  4251. const alreadySeen = props[index];
  4252. const circularPart = " -> " + props.slice(index + 1, props.length - 1).map((prop) => `${prop} -> `).join("");
  4253. const current = props[props.length - 1];
  4254. const leadingSpace = " ".repeat(leadingPart.length + alreadySeen.length / 2);
  4255. const dashes = "-".repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  4256. throw new BSONError(`Converting circular structure to EJSON:
  4257. ${leadingPart}${alreadySeen}${circularPart}${current}
  4258. ${leadingSpace}\\${dashes}/`);
  4259. }
  4260. options.seenObjects[options.seenObjects.length - 1].obj = value;
  4261. }
  4262. if (Array.isArray(value))
  4263. return serializeArray(value, options);
  4264. if (value === void 0)
  4265. return null;
  4266. if (value instanceof Date || isDate(value)) {
  4267. const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 2534023188e5;
  4268. if (options.legacy) {
  4269. return options.relaxed && inRange ? { $date: value.getTime() } : { $date: getISOString(value) };
  4270. }
  4271. return options.relaxed && inRange ? { $date: getISOString(value) } : { $date: { $numberLong: value.getTime().toString() } };
  4272. }
  4273. if (typeof value === "number" && (!options.relaxed || !isFinite(value))) {
  4274. if (Number.isInteger(value) && !Object.is(value, -0)) {
  4275. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  4276. return { $numberInt: value.toString() };
  4277. }
  4278. if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
  4279. return { $numberLong: value.toString() };
  4280. }
  4281. }
  4282. return { $numberDouble: Object.is(value, -0) ? "-0.0" : value.toString() };
  4283. }
  4284. if (typeof value === "bigint") {
  4285. if (!options.relaxed) {
  4286. return { $numberLong: BigInt.asIntN(64, value).toString() };
  4287. }
  4288. return Number(BigInt.asIntN(64, value));
  4289. }
  4290. if (value instanceof RegExp || isRegExp(value)) {
  4291. let flags = value.flags;
  4292. if (flags === void 0) {
  4293. const match = value.toString().match(/[gimuy]*$/);
  4294. if (match) {
  4295. flags = match[0];
  4296. }
  4297. }
  4298. const rx = new BSONRegExp(value.source, flags);
  4299. return rx.toExtendedJSON(options);
  4300. }
  4301. if (value != null && typeof value === "object")
  4302. return serializeDocument(value, options);
  4303. return value;
  4304. }
  4305. __name(serializeValue, "serializeValue");
  4306. var BSON_TYPE_MAPPINGS = {
  4307. Binary: /* @__PURE__ */ __name((o) => new Binary(o.value(), o.sub_type), "Binary"),
  4308. Code: /* @__PURE__ */ __name((o) => new Code(o.code, o.scope), "Code"),
  4309. DBRef: /* @__PURE__ */ __name((o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), "DBRef"),
  4310. Decimal128: /* @__PURE__ */ __name((o) => new Decimal128(o.bytes), "Decimal128"),
  4311. Double: /* @__PURE__ */ __name((o) => new Double(o.value), "Double"),
  4312. Int32: /* @__PURE__ */ __name((o) => new Int32(o.value), "Int32"),
  4313. Long: /* @__PURE__ */ __name((o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), "Long"),
  4314. MaxKey: /* @__PURE__ */ __name(() => new MaxKey(), "MaxKey"),
  4315. MinKey: /* @__PURE__ */ __name(() => new MinKey(), "MinKey"),
  4316. ObjectId: /* @__PURE__ */ __name((o) => new ObjectId3(o), "ObjectId"),
  4317. BSONRegExp: /* @__PURE__ */ __name((o) => new BSONRegExp(o.pattern, o.options), "BSONRegExp"),
  4318. BSONSymbol: /* @__PURE__ */ __name((o) => new BSONSymbol(o.value), "BSONSymbol"),
  4319. Timestamp: /* @__PURE__ */ __name((o) => Timestamp.fromBits(o.low, o.high), "Timestamp")
  4320. };
  4321. function serializeDocument(doc, options) {
  4322. if (doc == null || typeof doc !== "object")
  4323. throw new BSONError("not an object instance");
  4324. const bsontype = doc._bsontype;
  4325. if (typeof bsontype === "undefined") {
  4326. const _doc = {};
  4327. for (const name of Object.keys(doc)) {
  4328. options.seenObjects.push({ propertyName: name, obj: null });
  4329. try {
  4330. const value = serializeValue(doc[name], options);
  4331. if (name === "__proto__") {
  4332. Object.defineProperty(_doc, name, {
  4333. value,
  4334. writable: true,
  4335. enumerable: true,
  4336. configurable: true
  4337. });
  4338. } else {
  4339. _doc[name] = value;
  4340. }
  4341. } finally {
  4342. options.seenObjects.pop();
  4343. }
  4344. }
  4345. return _doc;
  4346. } else if (doc != null && typeof doc === "object" && typeof doc._bsontype === "string" && doc[Symbol.for("@@mdb.bson.version")] !== BSON_MAJOR_VERSION) {
  4347. throw new BSONVersionError();
  4348. } else if (isBSONType(doc)) {
  4349. let outDoc = doc;
  4350. if (typeof outDoc.toExtendedJSON !== "function") {
  4351. const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  4352. if (!mapper) {
  4353. throw new BSONError("Unrecognized or invalid _bsontype: " + doc._bsontype);
  4354. }
  4355. outDoc = mapper(outDoc);
  4356. }
  4357. if (bsontype === "Code" && outDoc.scope) {
  4358. outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
  4359. } else if (bsontype === "DBRef" && outDoc.oid) {
  4360. outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  4361. }
  4362. return outDoc.toExtendedJSON(options);
  4363. } else {
  4364. throw new BSONError("_bsontype must be a string, but was: " + typeof bsontype);
  4365. }
  4366. }
  4367. __name(serializeDocument, "serializeDocument");
  4368. function parse(text, options) {
  4369. const ejsonOptions = {
  4370. useBigInt64: (options == null ? void 0 : options.useBigInt64) ?? false,
  4371. relaxed: (options == null ? void 0 : options.relaxed) ?? true,
  4372. legacy: (options == null ? void 0 : options.legacy) ?? false
  4373. };
  4374. return JSON.parse(text, (key, value) => {
  4375. if (key.indexOf("\0") !== -1) {
  4376. throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
  4377. }
  4378. return deserializeValue(value, ejsonOptions);
  4379. });
  4380. }
  4381. __name(parse, "parse");
  4382. function stringify(value, replacer, space, options) {
  4383. if (space != null && typeof space === "object") {
  4384. options = space;
  4385. space = 0;
  4386. }
  4387. if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
  4388. options = replacer;
  4389. replacer = void 0;
  4390. space = 0;
  4391. }
  4392. const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  4393. seenObjects: [{ propertyName: "(root)", obj: null }]
  4394. });
  4395. const doc = serializeValue(value, serializeOptions);
  4396. return JSON.stringify(doc, replacer, space);
  4397. }
  4398. __name(stringify, "stringify");
  4399. function EJSONserialize(value, options) {
  4400. options = options || {};
  4401. return JSON.parse(stringify(value, options));
  4402. }
  4403. __name(EJSONserialize, "EJSONserialize");
  4404. function EJSONdeserialize(ejson, options) {
  4405. options = options || {};
  4406. return parse(JSON.stringify(ejson), options);
  4407. }
  4408. __name(EJSONdeserialize, "EJSONdeserialize");
  4409. var EJSON = /* @__PURE__ */ Object.create(null);
  4410. EJSON.parse = parse;
  4411. EJSON.stringify = stringify;
  4412. EJSON.serialize = EJSONserialize;
  4413. EJSON.deserialize = EJSONdeserialize;
  4414. Object.freeze(EJSON);
  4415. var MAXSIZE = 1024 * 1024 * 17;
  4416. var buffer = ByteUtils.allocate(MAXSIZE);
  4417. function setInternalBufferSize(size) {
  4418. if (buffer.length < size) {
  4419. buffer = ByteUtils.allocate(size);
  4420. }
  4421. }
  4422. __name(setInternalBufferSize, "setInternalBufferSize");
  4423. function serialize(object, options = {}) {
  4424. const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false;
  4425. const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
  4426. const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true;
  4427. const minInternalBufferSize = typeof options.minInternalBufferSize === "number" ? options.minInternalBufferSize : MAXSIZE;
  4428. if (buffer.length < minInternalBufferSize) {
  4429. buffer = ByteUtils.allocate(minInternalBufferSize);
  4430. }
  4431. const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
  4432. const finishedBuffer = ByteUtils.allocate(serializationIndex);
  4433. finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
  4434. return finishedBuffer;
  4435. }
  4436. __name(serialize, "serialize");
  4437. function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
  4438. const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false;
  4439. const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
  4440. const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true;
  4441. const startIndex = typeof options.index === "number" ? options.index : 0;
  4442. const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
  4443. finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
  4444. return startIndex + serializationIndex - 1;
  4445. }
  4446. __name(serializeWithBufferAndIndex, "serializeWithBufferAndIndex");
  4447. function deserialize(buffer2, options = {}) {
  4448. return internalDeserialize(ByteUtils.toLocalBufferType(buffer2), options);
  4449. }
  4450. __name(deserialize, "deserialize");
  4451. function calculateObjectSize(object, options = {}) {
  4452. options = options || {};
  4453. const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
  4454. const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true;
  4455. return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
  4456. }
  4457. __name(calculateObjectSize, "calculateObjectSize");
  4458. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  4459. const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
  4460. const bufferData = ByteUtils.toLocalBufferType(data);
  4461. let index = startIndex;
  4462. for (let i = 0; i < numberOfDocuments; i++) {
  4463. const size = bufferData[index] | bufferData[index + 1] << 8 | bufferData[index + 2] << 16 | bufferData[index + 3] << 24;
  4464. internalOptions.index = index;
  4465. documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
  4466. index = index + size;
  4467. }
  4468. return index;
  4469. }
  4470. __name(deserializeStream, "deserializeStream");
  4471. var bson = /* @__PURE__ */ Object.freeze({
  4472. __proto__: null,
  4473. BSONError,
  4474. BSONRegExp,
  4475. BSONRuntimeError,
  4476. BSONSymbol,
  4477. BSONType,
  4478. BSONValue,
  4479. BSONVersionError,
  4480. Binary,
  4481. Code,
  4482. DBRef,
  4483. Decimal128,
  4484. Double,
  4485. EJSON,
  4486. Int32,
  4487. Long,
  4488. MaxKey,
  4489. MinKey,
  4490. ObjectId: ObjectId3,
  4491. Timestamp,
  4492. UUID,
  4493. calculateObjectSize,
  4494. deserialize,
  4495. deserializeStream,
  4496. serialize,
  4497. serializeWithBufferAndIndex,
  4498. setInternalBufferSize
  4499. });
  4500. exports2.BSON = bson;
  4501. exports2.BSONError = BSONError;
  4502. exports2.BSONRegExp = BSONRegExp;
  4503. exports2.BSONRuntimeError = BSONRuntimeError;
  4504. exports2.BSONSymbol = BSONSymbol;
  4505. exports2.BSONType = BSONType;
  4506. exports2.BSONValue = BSONValue;
  4507. exports2.BSONVersionError = BSONVersionError;
  4508. exports2.Binary = Binary;
  4509. exports2.Code = Code;
  4510. exports2.DBRef = DBRef;
  4511. exports2.Decimal128 = Decimal128;
  4512. exports2.Double = Double;
  4513. exports2.EJSON = EJSON;
  4514. exports2.Int32 = Int32;
  4515. exports2.Long = Long;
  4516. exports2.MaxKey = MaxKey;
  4517. exports2.MinKey = MinKey;
  4518. exports2.ObjectId = ObjectId3;
  4519. exports2.Timestamp = Timestamp;
  4520. exports2.UUID = UUID;
  4521. exports2.calculateObjectSize = calculateObjectSize;
  4522. exports2.deserialize = deserialize;
  4523. exports2.deserializeStream = deserializeStream;
  4524. exports2.serialize = serialize;
  4525. exports2.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
  4526. exports2.setInternalBufferSize = setInternalBufferSize;
  4527. }
  4528. });
  4529. // node_modules/mongodb/lib/bson.js
  4530. var require_bson2 = __commonJS({
  4531. "node_modules/mongodb/lib/bson.js"(exports2) {
  4532. "use strict";
  4533. Object.defineProperty(exports2, "__esModule", { value: true });
  4534. exports2.resolveBSONOptions = exports2.pluckBSONSerializeOptions = exports2.Timestamp = exports2.serialize = exports2.ObjectId = exports2.MinKey = exports2.MaxKey = exports2.Long = exports2.Int32 = exports2.Double = exports2.deserialize = exports2.Decimal128 = exports2.DBRef = exports2.Code = exports2.calculateObjectSize = exports2.BSONType = exports2.BSONSymbol = exports2.BSONRegExp = exports2.BSON = exports2.Binary = void 0;
  4535. var bson_1 = require_bson();
  4536. Object.defineProperty(exports2, "Binary", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4537. return bson_1.Binary;
  4538. }, "get") });
  4539. Object.defineProperty(exports2, "BSON", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4540. return bson_1.BSON;
  4541. }, "get") });
  4542. Object.defineProperty(exports2, "BSONRegExp", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4543. return bson_1.BSONRegExp;
  4544. }, "get") });
  4545. Object.defineProperty(exports2, "BSONSymbol", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4546. return bson_1.BSONSymbol;
  4547. }, "get") });
  4548. Object.defineProperty(exports2, "BSONType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4549. return bson_1.BSONType;
  4550. }, "get") });
  4551. Object.defineProperty(exports2, "calculateObjectSize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4552. return bson_1.calculateObjectSize;
  4553. }, "get") });
  4554. Object.defineProperty(exports2, "Code", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4555. return bson_1.Code;
  4556. }, "get") });
  4557. Object.defineProperty(exports2, "DBRef", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4558. return bson_1.DBRef;
  4559. }, "get") });
  4560. Object.defineProperty(exports2, "Decimal128", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4561. return bson_1.Decimal128;
  4562. }, "get") });
  4563. Object.defineProperty(exports2, "deserialize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4564. return bson_1.deserialize;
  4565. }, "get") });
  4566. Object.defineProperty(exports2, "Double", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4567. return bson_1.Double;
  4568. }, "get") });
  4569. Object.defineProperty(exports2, "Int32", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4570. return bson_1.Int32;
  4571. }, "get") });
  4572. Object.defineProperty(exports2, "Long", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4573. return bson_1.Long;
  4574. }, "get") });
  4575. Object.defineProperty(exports2, "MaxKey", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4576. return bson_1.MaxKey;
  4577. }, "get") });
  4578. Object.defineProperty(exports2, "MinKey", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4579. return bson_1.MinKey;
  4580. }, "get") });
  4581. Object.defineProperty(exports2, "ObjectId", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4582. return bson_1.ObjectId;
  4583. }, "get") });
  4584. Object.defineProperty(exports2, "serialize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4585. return bson_1.serialize;
  4586. }, "get") });
  4587. Object.defineProperty(exports2, "Timestamp", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  4588. return bson_1.Timestamp;
  4589. }, "get") });
  4590. function pluckBSONSerializeOptions(options) {
  4591. const { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw, enableUtf8Validation } = options;
  4592. return {
  4593. fieldsAsRaw,
  4594. useBigInt64,
  4595. promoteValues,
  4596. promoteBuffers,
  4597. promoteLongs,
  4598. serializeFunctions,
  4599. ignoreUndefined,
  4600. bsonRegExp,
  4601. raw,
  4602. enableUtf8Validation
  4603. };
  4604. }
  4605. __name(pluckBSONSerializeOptions, "pluckBSONSerializeOptions");
  4606. exports2.pluckBSONSerializeOptions = pluckBSONSerializeOptions;
  4607. function resolveBSONOptions(options, parent) {
  4608. const parentOptions = parent == null ? void 0 : parent.bsonOptions;
  4609. return {
  4610. raw: (options == null ? void 0 : options.raw) ?? (parentOptions == null ? void 0 : parentOptions.raw) ?? false,
  4611. useBigInt64: (options == null ? void 0 : options.useBigInt64) ?? (parentOptions == null ? void 0 : parentOptions.useBigInt64) ?? false,
  4612. promoteLongs: (options == null ? void 0 : options.promoteLongs) ?? (parentOptions == null ? void 0 : parentOptions.promoteLongs) ?? true,
  4613. promoteValues: (options == null ? void 0 : options.promoteValues) ?? (parentOptions == null ? void 0 : parentOptions.promoteValues) ?? true,
  4614. promoteBuffers: (options == null ? void 0 : options.promoteBuffers) ?? (parentOptions == null ? void 0 : parentOptions.promoteBuffers) ?? false,
  4615. ignoreUndefined: (options == null ? void 0 : options.ignoreUndefined) ?? (parentOptions == null ? void 0 : parentOptions.ignoreUndefined) ?? false,
  4616. bsonRegExp: (options == null ? void 0 : options.bsonRegExp) ?? (parentOptions == null ? void 0 : parentOptions.bsonRegExp) ?? false,
  4617. serializeFunctions: (options == null ? void 0 : options.serializeFunctions) ?? (parentOptions == null ? void 0 : parentOptions.serializeFunctions) ?? false,
  4618. fieldsAsRaw: (options == null ? void 0 : options.fieldsAsRaw) ?? (parentOptions == null ? void 0 : parentOptions.fieldsAsRaw) ?? {},
  4619. enableUtf8Validation: (options == null ? void 0 : options.enableUtf8Validation) ?? (parentOptions == null ? void 0 : parentOptions.enableUtf8Validation) ?? true
  4620. };
  4621. }
  4622. __name(resolveBSONOptions, "resolveBSONOptions");
  4623. exports2.resolveBSONOptions = resolveBSONOptions;
  4624. }
  4625. });
  4626. // node_modules/mongodb/lib/cmap/wire_protocol/constants.js
  4627. var require_constants = __commonJS({
  4628. "node_modules/mongodb/lib/cmap/wire_protocol/constants.js"(exports2) {
  4629. "use strict";
  4630. Object.defineProperty(exports2, "__esModule", { value: true });
  4631. exports2.OP_MSG = exports2.OP_COMPRESSED = exports2.OP_DELETE = exports2.OP_QUERY = exports2.OP_INSERT = exports2.OP_UPDATE = exports2.OP_REPLY = exports2.MIN_SUPPORTED_QE_SERVER_VERSION = exports2.MIN_SUPPORTED_QE_WIRE_VERSION = exports2.MAX_SUPPORTED_WIRE_VERSION = exports2.MIN_SUPPORTED_WIRE_VERSION = exports2.MAX_SUPPORTED_SERVER_VERSION = exports2.MIN_SUPPORTED_SERVER_VERSION = void 0;
  4632. exports2.MIN_SUPPORTED_SERVER_VERSION = "3.6";
  4633. exports2.MAX_SUPPORTED_SERVER_VERSION = "7.0";
  4634. exports2.MIN_SUPPORTED_WIRE_VERSION = 6;
  4635. exports2.MAX_SUPPORTED_WIRE_VERSION = 21;
  4636. exports2.MIN_SUPPORTED_QE_WIRE_VERSION = 21;
  4637. exports2.MIN_SUPPORTED_QE_SERVER_VERSION = "7.0";
  4638. exports2.OP_REPLY = 1;
  4639. exports2.OP_UPDATE = 2001;
  4640. exports2.OP_INSERT = 2002;
  4641. exports2.OP_QUERY = 2004;
  4642. exports2.OP_DELETE = 2006;
  4643. exports2.OP_COMPRESSED = 2012;
  4644. exports2.OP_MSG = 2013;
  4645. }
  4646. });
  4647. // node_modules/mongodb/lib/constants.js
  4648. var require_constants2 = __commonJS({
  4649. "node_modules/mongodb/lib/constants.js"(exports2) {
  4650. "use strict";
  4651. Object.defineProperty(exports2, "__esModule", { value: true });
  4652. exports2.TOPOLOGY_EVENTS = exports2.CMAP_EVENTS = exports2.HEARTBEAT_EVENTS = exports2.RESUME_TOKEN_CHANGED = exports2.END = exports2.CHANGE = exports2.INIT = exports2.MORE = exports2.RESPONSE = exports2.SERVER_HEARTBEAT_FAILED = exports2.SERVER_HEARTBEAT_SUCCEEDED = exports2.SERVER_HEARTBEAT_STARTED = exports2.COMMAND_FAILED = exports2.COMMAND_SUCCEEDED = exports2.COMMAND_STARTED = exports2.CLUSTER_TIME_RECEIVED = exports2.CONNECTION_CHECKED_IN = exports2.CONNECTION_CHECKED_OUT = exports2.CONNECTION_CHECK_OUT_FAILED = exports2.CONNECTION_CHECK_OUT_STARTED = exports2.CONNECTION_CLOSED = exports2.CONNECTION_READY = exports2.CONNECTION_CREATED = exports2.CONNECTION_POOL_READY = exports2.CONNECTION_POOL_CLEARED = exports2.CONNECTION_POOL_CLOSED = exports2.CONNECTION_POOL_CREATED = exports2.TOPOLOGY_DESCRIPTION_CHANGED = exports2.TOPOLOGY_CLOSED = exports2.TOPOLOGY_OPENING = exports2.SERVER_DESCRIPTION_CHANGED = exports2.SERVER_CLOSED = exports2.SERVER_OPENING = exports2.DESCRIPTION_RECEIVED = exports2.UNPINNED = exports2.PINNED = exports2.MESSAGE = exports2.ENDED = exports2.CLOSED = exports2.CONNECT = exports2.OPEN = exports2.CLOSE = exports2.TIMEOUT = exports2.ERROR = exports2.SYSTEM_JS_COLLECTION = exports2.SYSTEM_COMMAND_COLLECTION = exports2.SYSTEM_USER_COLLECTION = exports2.SYSTEM_PROFILE_COLLECTION = exports2.SYSTEM_INDEX_COLLECTION = exports2.SYSTEM_NAMESPACE_COLLECTION = void 0;
  4653. exports2.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports2.LEGACY_HELLO_COMMAND = exports2.MONGO_CLIENT_EVENTS = exports2.LOCAL_SERVER_EVENTS = exports2.SERVER_RELAY_EVENTS = exports2.APM_EVENTS = void 0;
  4654. exports2.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
  4655. exports2.SYSTEM_INDEX_COLLECTION = "system.indexes";
  4656. exports2.SYSTEM_PROFILE_COLLECTION = "system.profile";
  4657. exports2.SYSTEM_USER_COLLECTION = "system.users";
  4658. exports2.SYSTEM_COMMAND_COLLECTION = "$cmd";
  4659. exports2.SYSTEM_JS_COLLECTION = "system.js";
  4660. exports2.ERROR = "error";
  4661. exports2.TIMEOUT = "timeout";
  4662. exports2.CLOSE = "close";
  4663. exports2.OPEN = "open";
  4664. exports2.CONNECT = "connect";
  4665. exports2.CLOSED = "closed";
  4666. exports2.ENDED = "ended";
  4667. exports2.MESSAGE = "message";
  4668. exports2.PINNED = "pinned";
  4669. exports2.UNPINNED = "unpinned";
  4670. exports2.DESCRIPTION_RECEIVED = "descriptionReceived";
  4671. exports2.SERVER_OPENING = "serverOpening";
  4672. exports2.SERVER_CLOSED = "serverClosed";
  4673. exports2.SERVER_DESCRIPTION_CHANGED = "serverDescriptionChanged";
  4674. exports2.TOPOLOGY_OPENING = "topologyOpening";
  4675. exports2.TOPOLOGY_CLOSED = "topologyClosed";
  4676. exports2.TOPOLOGY_DESCRIPTION_CHANGED = "topologyDescriptionChanged";
  4677. exports2.CONNECTION_POOL_CREATED = "connectionPoolCreated";
  4678. exports2.CONNECTION_POOL_CLOSED = "connectionPoolClosed";
  4679. exports2.CONNECTION_POOL_CLEARED = "connectionPoolCleared";
  4680. exports2.CONNECTION_POOL_READY = "connectionPoolReady";
  4681. exports2.CONNECTION_CREATED = "connectionCreated";
  4682. exports2.CONNECTION_READY = "connectionReady";
  4683. exports2.CONNECTION_CLOSED = "connectionClosed";
  4684. exports2.CONNECTION_CHECK_OUT_STARTED = "connectionCheckOutStarted";
  4685. exports2.CONNECTION_CHECK_OUT_FAILED = "connectionCheckOutFailed";
  4686. exports2.CONNECTION_CHECKED_OUT = "connectionCheckedOut";
  4687. exports2.CONNECTION_CHECKED_IN = "connectionCheckedIn";
  4688. exports2.CLUSTER_TIME_RECEIVED = "clusterTimeReceived";
  4689. exports2.COMMAND_STARTED = "commandStarted";
  4690. exports2.COMMAND_SUCCEEDED = "commandSucceeded";
  4691. exports2.COMMAND_FAILED = "commandFailed";
  4692. exports2.SERVER_HEARTBEAT_STARTED = "serverHeartbeatStarted";
  4693. exports2.SERVER_HEARTBEAT_SUCCEEDED = "serverHeartbeatSucceeded";
  4694. exports2.SERVER_HEARTBEAT_FAILED = "serverHeartbeatFailed";
  4695. exports2.RESPONSE = "response";
  4696. exports2.MORE = "more";
  4697. exports2.INIT = "init";
  4698. exports2.CHANGE = "change";
  4699. exports2.END = "end";
  4700. exports2.RESUME_TOKEN_CHANGED = "resumeTokenChanged";
  4701. exports2.HEARTBEAT_EVENTS = Object.freeze([
  4702. exports2.SERVER_HEARTBEAT_STARTED,
  4703. exports2.SERVER_HEARTBEAT_SUCCEEDED,
  4704. exports2.SERVER_HEARTBEAT_FAILED
  4705. ]);
  4706. exports2.CMAP_EVENTS = Object.freeze([
  4707. exports2.CONNECTION_POOL_CREATED,
  4708. exports2.CONNECTION_POOL_READY,
  4709. exports2.CONNECTION_POOL_CLEARED,
  4710. exports2.CONNECTION_POOL_CLOSED,
  4711. exports2.CONNECTION_CREATED,
  4712. exports2.CONNECTION_READY,
  4713. exports2.CONNECTION_CLOSED,
  4714. exports2.CONNECTION_CHECK_OUT_STARTED,
  4715. exports2.CONNECTION_CHECK_OUT_FAILED,
  4716. exports2.CONNECTION_CHECKED_OUT,
  4717. exports2.CONNECTION_CHECKED_IN
  4718. ]);
  4719. exports2.TOPOLOGY_EVENTS = Object.freeze([
  4720. exports2.SERVER_OPENING,
  4721. exports2.SERVER_CLOSED,
  4722. exports2.SERVER_DESCRIPTION_CHANGED,
  4723. exports2.TOPOLOGY_OPENING,
  4724. exports2.TOPOLOGY_CLOSED,
  4725. exports2.TOPOLOGY_DESCRIPTION_CHANGED,
  4726. exports2.ERROR,
  4727. exports2.TIMEOUT,
  4728. exports2.CLOSE
  4729. ]);
  4730. exports2.APM_EVENTS = Object.freeze([
  4731. exports2.COMMAND_STARTED,
  4732. exports2.COMMAND_SUCCEEDED,
  4733. exports2.COMMAND_FAILED
  4734. ]);
  4735. exports2.SERVER_RELAY_EVENTS = Object.freeze([
  4736. exports2.SERVER_HEARTBEAT_STARTED,
  4737. exports2.SERVER_HEARTBEAT_SUCCEEDED,
  4738. exports2.SERVER_HEARTBEAT_FAILED,
  4739. exports2.COMMAND_STARTED,
  4740. exports2.COMMAND_SUCCEEDED,
  4741. exports2.COMMAND_FAILED,
  4742. ...exports2.CMAP_EVENTS
  4743. ]);
  4744. exports2.LOCAL_SERVER_EVENTS = Object.freeze([
  4745. exports2.CONNECT,
  4746. exports2.DESCRIPTION_RECEIVED,
  4747. exports2.CLOSED,
  4748. exports2.ENDED
  4749. ]);
  4750. exports2.MONGO_CLIENT_EVENTS = Object.freeze([
  4751. ...exports2.CMAP_EVENTS,
  4752. ...exports2.APM_EVENTS,
  4753. ...exports2.TOPOLOGY_EVENTS,
  4754. ...exports2.HEARTBEAT_EVENTS
  4755. ]);
  4756. exports2.LEGACY_HELLO_COMMAND = "ismaster";
  4757. exports2.LEGACY_HELLO_COMMAND_CAMEL_CASE = "isMaster";
  4758. }
  4759. });
  4760. // node_modules/mongodb/lib/read_concern.js
  4761. var require_read_concern = __commonJS({
  4762. "node_modules/mongodb/lib/read_concern.js"(exports2) {
  4763. "use strict";
  4764. Object.defineProperty(exports2, "__esModule", { value: true });
  4765. exports2.ReadConcern = exports2.ReadConcernLevel = void 0;
  4766. exports2.ReadConcernLevel = Object.freeze({
  4767. local: "local",
  4768. majority: "majority",
  4769. linearizable: "linearizable",
  4770. available: "available",
  4771. snapshot: "snapshot"
  4772. });
  4773. var _ReadConcern = class _ReadConcern {
  4774. /** Constructs a ReadConcern from the read concern level.*/
  4775. constructor(level) {
  4776. this.level = exports2.ReadConcernLevel[level] ?? level;
  4777. }
  4778. /**
  4779. * Construct a ReadConcern given an options object.
  4780. *
  4781. * @param options - The options object from which to extract the write concern.
  4782. */
  4783. static fromOptions(options) {
  4784. if (options == null) {
  4785. return;
  4786. }
  4787. if (options.readConcern) {
  4788. const { readConcern } = options;
  4789. if (readConcern instanceof _ReadConcern) {
  4790. return readConcern;
  4791. } else if (typeof readConcern === "string") {
  4792. return new _ReadConcern(readConcern);
  4793. } else if ("level" in readConcern && readConcern.level) {
  4794. return new _ReadConcern(readConcern.level);
  4795. }
  4796. }
  4797. if (options.level) {
  4798. return new _ReadConcern(options.level);
  4799. }
  4800. return;
  4801. }
  4802. static get MAJORITY() {
  4803. return exports2.ReadConcernLevel.majority;
  4804. }
  4805. static get AVAILABLE() {
  4806. return exports2.ReadConcernLevel.available;
  4807. }
  4808. static get LINEARIZABLE() {
  4809. return exports2.ReadConcernLevel.linearizable;
  4810. }
  4811. static get SNAPSHOT() {
  4812. return exports2.ReadConcernLevel.snapshot;
  4813. }
  4814. toJSON() {
  4815. return { level: this.level };
  4816. }
  4817. };
  4818. __name(_ReadConcern, "ReadConcern");
  4819. var ReadConcern = _ReadConcern;
  4820. exports2.ReadConcern = ReadConcern;
  4821. }
  4822. });
  4823. // node_modules/mongodb/lib/read_preference.js
  4824. var require_read_preference = __commonJS({
  4825. "node_modules/mongodb/lib/read_preference.js"(exports2) {
  4826. "use strict";
  4827. Object.defineProperty(exports2, "__esModule", { value: true });
  4828. exports2.ReadPreference = exports2.ReadPreferenceMode = void 0;
  4829. var error_1 = require_error();
  4830. exports2.ReadPreferenceMode = Object.freeze({
  4831. primary: "primary",
  4832. primaryPreferred: "primaryPreferred",
  4833. secondary: "secondary",
  4834. secondaryPreferred: "secondaryPreferred",
  4835. nearest: "nearest"
  4836. });
  4837. var _ReadPreference = class _ReadPreference {
  4838. /**
  4839. * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
  4840. * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary.
  4841. * @param options - Additional read preference options
  4842. */
  4843. constructor(mode, tags, options) {
  4844. if (!_ReadPreference.isValid(mode)) {
  4845. throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`);
  4846. }
  4847. if (options == null && typeof tags === "object" && !Array.isArray(tags)) {
  4848. options = tags;
  4849. tags = void 0;
  4850. } else if (tags && !Array.isArray(tags)) {
  4851. throw new error_1.MongoInvalidArgumentError("ReadPreference tags must be an array");
  4852. }
  4853. this.mode = mode;
  4854. this.tags = tags;
  4855. this.hedge = options == null ? void 0 : options.hedge;
  4856. this.maxStalenessSeconds = void 0;
  4857. this.minWireVersion = void 0;
  4858. options = options ?? {};
  4859. if (options.maxStalenessSeconds != null) {
  4860. if (options.maxStalenessSeconds <= 0) {
  4861. throw new error_1.MongoInvalidArgumentError("maxStalenessSeconds must be a positive integer");
  4862. }
  4863. this.maxStalenessSeconds = options.maxStalenessSeconds;
  4864. this.minWireVersion = 5;
  4865. }
  4866. if (this.mode === _ReadPreference.PRIMARY) {
  4867. if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) {
  4868. throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with tags");
  4869. }
  4870. if (this.maxStalenessSeconds) {
  4871. throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with maxStalenessSeconds");
  4872. }
  4873. if (this.hedge) {
  4874. throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with hedge");
  4875. }
  4876. }
  4877. }
  4878. // Support the deprecated `preference` property introduced in the porcelain layer
  4879. get preference() {
  4880. return this.mode;
  4881. }
  4882. static fromString(mode) {
  4883. return new _ReadPreference(mode);
  4884. }
  4885. /**
  4886. * Construct a ReadPreference given an options object.
  4887. *
  4888. * @param options - The options object from which to extract the read preference.
  4889. */
  4890. static fromOptions(options) {
  4891. var _a;
  4892. if (!options)
  4893. return;
  4894. const readPreference = options.readPreference ?? ((_a = options.session) == null ? void 0 : _a.transaction.options.readPreference);
  4895. const readPreferenceTags = options.readPreferenceTags;
  4896. if (readPreference == null) {
  4897. return;
  4898. }
  4899. if (typeof readPreference === "string") {
  4900. return new _ReadPreference(readPreference, readPreferenceTags, {
  4901. maxStalenessSeconds: options.maxStalenessSeconds,
  4902. hedge: options.hedge
  4903. });
  4904. } else if (!(readPreference instanceof _ReadPreference) && typeof readPreference === "object") {
  4905. const mode = readPreference.mode || readPreference.preference;
  4906. if (mode && typeof mode === "string") {
  4907. return new _ReadPreference(mode, readPreference.tags ?? readPreferenceTags, {
  4908. maxStalenessSeconds: readPreference.maxStalenessSeconds,
  4909. hedge: options.hedge
  4910. });
  4911. }
  4912. }
  4913. if (readPreferenceTags) {
  4914. readPreference.tags = readPreferenceTags;
  4915. }
  4916. return readPreference;
  4917. }
  4918. /**
  4919. * Replaces options.readPreference with a ReadPreference instance
  4920. */
  4921. static translate(options) {
  4922. if (options.readPreference == null)
  4923. return options;
  4924. const r = options.readPreference;
  4925. if (typeof r === "string") {
  4926. options.readPreference = new _ReadPreference(r);
  4927. } else if (r && !(r instanceof _ReadPreference) && typeof r === "object") {
  4928. const mode = r.mode || r.preference;
  4929. if (mode && typeof mode === "string") {
  4930. options.readPreference = new _ReadPreference(mode, r.tags, {
  4931. maxStalenessSeconds: r.maxStalenessSeconds
  4932. });
  4933. }
  4934. } else if (!(r instanceof _ReadPreference)) {
  4935. throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r}`);
  4936. }
  4937. return options;
  4938. }
  4939. /**
  4940. * Validate if a mode is legal
  4941. *
  4942. * @param mode - The string representing the read preference mode.
  4943. */
  4944. static isValid(mode) {
  4945. const VALID_MODES = /* @__PURE__ */ new Set([
  4946. _ReadPreference.PRIMARY,
  4947. _ReadPreference.PRIMARY_PREFERRED,
  4948. _ReadPreference.SECONDARY,
  4949. _ReadPreference.SECONDARY_PREFERRED,
  4950. _ReadPreference.NEAREST,
  4951. null
  4952. ]);
  4953. return VALID_MODES.has(mode);
  4954. }
  4955. /**
  4956. * Validate if a mode is legal
  4957. *
  4958. * @param mode - The string representing the read preference mode.
  4959. */
  4960. isValid(mode) {
  4961. return _ReadPreference.isValid(typeof mode === "string" ? mode : this.mode);
  4962. }
  4963. /**
  4964. * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire
  4965. * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query
  4966. */
  4967. secondaryOk() {
  4968. const NEEDS_SECONDARYOK = /* @__PURE__ */ new Set([
  4969. _ReadPreference.PRIMARY_PREFERRED,
  4970. _ReadPreference.SECONDARY,
  4971. _ReadPreference.SECONDARY_PREFERRED,
  4972. _ReadPreference.NEAREST
  4973. ]);
  4974. return NEEDS_SECONDARYOK.has(this.mode);
  4975. }
  4976. /**
  4977. * Check if the two ReadPreferences are equivalent
  4978. *
  4979. * @param readPreference - The read preference with which to check equality
  4980. */
  4981. equals(readPreference) {
  4982. return readPreference.mode === this.mode;
  4983. }
  4984. /** Return JSON representation */
  4985. toJSON() {
  4986. const readPreference = { mode: this.mode };
  4987. if (Array.isArray(this.tags))
  4988. readPreference.tags = this.tags;
  4989. if (this.maxStalenessSeconds)
  4990. readPreference.maxStalenessSeconds = this.maxStalenessSeconds;
  4991. if (this.hedge)
  4992. readPreference.hedge = this.hedge;
  4993. return readPreference;
  4994. }
  4995. };
  4996. __name(_ReadPreference, "ReadPreference");
  4997. var ReadPreference = _ReadPreference;
  4998. ReadPreference.PRIMARY = exports2.ReadPreferenceMode.primary;
  4999. ReadPreference.PRIMARY_PREFERRED = exports2.ReadPreferenceMode.primaryPreferred;
  5000. ReadPreference.SECONDARY = exports2.ReadPreferenceMode.secondary;
  5001. ReadPreference.SECONDARY_PREFERRED = exports2.ReadPreferenceMode.secondaryPreferred;
  5002. ReadPreference.NEAREST = exports2.ReadPreferenceMode.nearest;
  5003. ReadPreference.primary = new ReadPreference(exports2.ReadPreferenceMode.primary);
  5004. ReadPreference.primaryPreferred = new ReadPreference(exports2.ReadPreferenceMode.primaryPreferred);
  5005. ReadPreference.secondary = new ReadPreference(exports2.ReadPreferenceMode.secondary);
  5006. ReadPreference.secondaryPreferred = new ReadPreference(exports2.ReadPreferenceMode.secondaryPreferred);
  5007. ReadPreference.nearest = new ReadPreference(exports2.ReadPreferenceMode.nearest);
  5008. exports2.ReadPreference = ReadPreference;
  5009. }
  5010. });
  5011. // node_modules/mongodb/lib/sdam/common.js
  5012. var require_common = __commonJS({
  5013. "node_modules/mongodb/lib/sdam/common.js"(exports2) {
  5014. "use strict";
  5015. Object.defineProperty(exports2, "__esModule", { value: true });
  5016. exports2._advanceClusterTime = exports2.drainTimerQueue = exports2.ServerType = exports2.TopologyType = exports2.STATE_CONNECTED = exports2.STATE_CONNECTING = exports2.STATE_CLOSED = exports2.STATE_CLOSING = void 0;
  5017. var timers_1 = require("timers");
  5018. exports2.STATE_CLOSING = "closing";
  5019. exports2.STATE_CLOSED = "closed";
  5020. exports2.STATE_CONNECTING = "connecting";
  5021. exports2.STATE_CONNECTED = "connected";
  5022. exports2.TopologyType = Object.freeze({
  5023. Single: "Single",
  5024. ReplicaSetNoPrimary: "ReplicaSetNoPrimary",
  5025. ReplicaSetWithPrimary: "ReplicaSetWithPrimary",
  5026. Sharded: "Sharded",
  5027. Unknown: "Unknown",
  5028. LoadBalanced: "LoadBalanced"
  5029. });
  5030. exports2.ServerType = Object.freeze({
  5031. Standalone: "Standalone",
  5032. Mongos: "Mongos",
  5033. PossiblePrimary: "PossiblePrimary",
  5034. RSPrimary: "RSPrimary",
  5035. RSSecondary: "RSSecondary",
  5036. RSArbiter: "RSArbiter",
  5037. RSOther: "RSOther",
  5038. RSGhost: "RSGhost",
  5039. Unknown: "Unknown",
  5040. LoadBalancer: "LoadBalancer"
  5041. });
  5042. function drainTimerQueue(queue) {
  5043. queue.forEach(timers_1.clearTimeout);
  5044. queue.clear();
  5045. }
  5046. __name(drainTimerQueue, "drainTimerQueue");
  5047. exports2.drainTimerQueue = drainTimerQueue;
  5048. function _advanceClusterTime(entity, $clusterTime) {
  5049. if (entity.clusterTime == null) {
  5050. entity.clusterTime = $clusterTime;
  5051. } else {
  5052. if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) {
  5053. entity.clusterTime = $clusterTime;
  5054. }
  5055. }
  5056. }
  5057. __name(_advanceClusterTime, "_advanceClusterTime");
  5058. exports2._advanceClusterTime = _advanceClusterTime;
  5059. }
  5060. });
  5061. // node_modules/mongodb/lib/write_concern.js
  5062. var require_write_concern = __commonJS({
  5063. "node_modules/mongodb/lib/write_concern.js"(exports2) {
  5064. "use strict";
  5065. Object.defineProperty(exports2, "__esModule", { value: true });
  5066. exports2.WriteConcern = exports2.WRITE_CONCERN_KEYS = void 0;
  5067. exports2.WRITE_CONCERN_KEYS = ["w", "wtimeout", "j", "journal", "fsync"];
  5068. var _WriteConcern = class _WriteConcern {
  5069. /**
  5070. * Constructs a WriteConcern from the write concern properties.
  5071. * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
  5072. * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely
  5073. * @param journal - request acknowledgment that the write operation has been written to the on-disk journal
  5074. * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version.
  5075. */
  5076. constructor(w, wtimeoutMS, journal, fsync) {
  5077. if (w != null) {
  5078. if (!Number.isNaN(Number(w))) {
  5079. this.w = Number(w);
  5080. } else {
  5081. this.w = w;
  5082. }
  5083. }
  5084. if (wtimeoutMS != null) {
  5085. this.wtimeoutMS = this.wtimeout = wtimeoutMS;
  5086. }
  5087. if (journal != null) {
  5088. this.journal = this.j = journal;
  5089. }
  5090. if (fsync != null) {
  5091. this.journal = this.j = fsync ? true : false;
  5092. }
  5093. }
  5094. /**
  5095. * Apply a write concern to a command document. Will modify and return the command.
  5096. */
  5097. static apply(command, writeConcern) {
  5098. const wc = {};
  5099. if (writeConcern.w != null)
  5100. wc.w = writeConcern.w;
  5101. if (writeConcern.wtimeoutMS != null)
  5102. wc.wtimeout = writeConcern.wtimeoutMS;
  5103. if (writeConcern.journal != null)
  5104. wc.j = writeConcern.j;
  5105. command.writeConcern = wc;
  5106. return command;
  5107. }
  5108. /** Construct a WriteConcern given an options object. */
  5109. static fromOptions(options, inherit) {
  5110. if (options == null)
  5111. return void 0;
  5112. inherit = inherit ?? {};
  5113. let opts;
  5114. if (typeof options === "string" || typeof options === "number") {
  5115. opts = { w: options };
  5116. } else if (options instanceof _WriteConcern) {
  5117. opts = options;
  5118. } else {
  5119. opts = options.writeConcern;
  5120. }
  5121. const parentOpts = inherit instanceof _WriteConcern ? inherit : inherit.writeConcern;
  5122. const { w = void 0, wtimeout = void 0, j = void 0, fsync = void 0, journal = void 0, wtimeoutMS = void 0 } = {
  5123. ...parentOpts,
  5124. ...opts
  5125. };
  5126. if (w != null || wtimeout != null || wtimeoutMS != null || j != null || journal != null || fsync != null) {
  5127. return new _WriteConcern(w, wtimeout ?? wtimeoutMS, j ?? journal, fsync);
  5128. }
  5129. return void 0;
  5130. }
  5131. };
  5132. __name(_WriteConcern, "WriteConcern");
  5133. var WriteConcern = _WriteConcern;
  5134. exports2.WriteConcern = WriteConcern;
  5135. }
  5136. });
  5137. // node_modules/mongodb/lib/utils.js
  5138. var require_utils = __commonJS({
  5139. "node_modules/mongodb/lib/utils.js"(exports2) {
  5140. "use strict";
  5141. Object.defineProperty(exports2, "__esModule", { value: true });
  5142. exports2.matchesParentDomain = exports2.parseUnsignedInteger = exports2.parseInteger = exports2.compareObjectId = exports2.getMongoDBClientEncryption = exports2.commandSupportsReadConcern = exports2.shuffle = exports2.supportsRetryableWrites = exports2.enumToString = exports2.emitWarningOnce = exports2.emitWarning = exports2.MONGODB_WARNING_CODE = exports2.DEFAULT_PK_FACTORY = exports2.HostAddress = exports2.BufferPool = exports2.List = exports2.deepCopy = exports2.isRecord = exports2.setDifference = exports2.isHello = exports2.isSuperset = exports2.resolveOptions = exports2.hasAtomicOperators = exports2.calculateDurationInMs = exports2.now = exports2.makeStateMachine = exports2.errorStrictEqual = exports2.arrayStrictEqual = exports2.eachAsync = exports2.maxWireVersion = exports2.uuidV4 = exports2.databaseNamespace = exports2.maybeCallback = exports2.makeCounter = exports2.MongoDBCollectionNamespace = exports2.MongoDBNamespace = exports2.ns = exports2.getTopology = exports2.decorateWithExplain = exports2.decorateWithReadConcern = exports2.decorateWithCollation = exports2.isPromiseLike = exports2.applyRetryableWrites = exports2.filterOptions = exports2.mergeOptions = exports2.isObject = exports2.normalizeHintField = exports2.checkCollectionName = exports2.hostMatchesWildcards = exports2.ByteUtils = void 0;
  5143. exports2.request = void 0;
  5144. var crypto = require("crypto");
  5145. var http = require("http");
  5146. var url = require("url");
  5147. var url_1 = require("url");
  5148. var bson_1 = require_bson2();
  5149. var constants_1 = require_constants();
  5150. var constants_2 = require_constants2();
  5151. var error_1 = require_error();
  5152. var read_concern_1 = require_read_concern();
  5153. var read_preference_1 = require_read_preference();
  5154. var common_1 = require_common();
  5155. var write_concern_1 = require_write_concern();
  5156. exports2.ByteUtils = {
  5157. toLocalBufferType(buffer) {
  5158. return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  5159. },
  5160. equals(seqA, seqB) {
  5161. return exports2.ByteUtils.toLocalBufferType(seqA).equals(seqB);
  5162. },
  5163. compare(seqA, seqB) {
  5164. return exports2.ByteUtils.toLocalBufferType(seqA).compare(seqB);
  5165. },
  5166. toBase64(uint8array) {
  5167. return exports2.ByteUtils.toLocalBufferType(uint8array).toString("base64");
  5168. }
  5169. };
  5170. function hostMatchesWildcards(host, wildcards) {
  5171. for (const wildcard of wildcards) {
  5172. if (host === wildcard || wildcard.startsWith("*.") && (host == null ? void 0 : host.endsWith(wildcard.substring(2, wildcard.length))) || wildcard.startsWith("*/") && (host == null ? void 0 : host.endsWith(wildcard.substring(2, wildcard.length)))) {
  5173. return true;
  5174. }
  5175. }
  5176. return false;
  5177. }
  5178. __name(hostMatchesWildcards, "hostMatchesWildcards");
  5179. exports2.hostMatchesWildcards = hostMatchesWildcards;
  5180. function checkCollectionName(collectionName) {
  5181. if ("string" !== typeof collectionName) {
  5182. throw new error_1.MongoInvalidArgumentError("Collection name must be a String");
  5183. }
  5184. if (!collectionName || collectionName.indexOf("..") !== -1) {
  5185. throw new error_1.MongoInvalidArgumentError("Collection names cannot be empty");
  5186. }
  5187. if (collectionName.indexOf("$") !== -1 && collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) {
  5188. throw new error_1.MongoInvalidArgumentError("Collection names must not contain '$'");
  5189. }
  5190. if (collectionName.match(/^\.|\.$/) != null) {
  5191. throw new error_1.MongoInvalidArgumentError("Collection names must not start or end with '.'");
  5192. }
  5193. if (collectionName.indexOf("\0") !== -1) {
  5194. throw new error_1.MongoInvalidArgumentError("Collection names cannot contain a null character");
  5195. }
  5196. }
  5197. __name(checkCollectionName, "checkCollectionName");
  5198. exports2.checkCollectionName = checkCollectionName;
  5199. function normalizeHintField(hint) {
  5200. let finalHint = void 0;
  5201. if (typeof hint === "string") {
  5202. finalHint = hint;
  5203. } else if (Array.isArray(hint)) {
  5204. finalHint = {};
  5205. hint.forEach((param) => {
  5206. finalHint[param] = 1;
  5207. });
  5208. } else if (hint != null && typeof hint === "object") {
  5209. finalHint = {};
  5210. for (const name in hint) {
  5211. finalHint[name] = hint[name];
  5212. }
  5213. }
  5214. return finalHint;
  5215. }
  5216. __name(normalizeHintField, "normalizeHintField");
  5217. exports2.normalizeHintField = normalizeHintField;
  5218. var TO_STRING = /* @__PURE__ */ __name((object) => Object.prototype.toString.call(object), "TO_STRING");
  5219. function isObject(arg) {
  5220. return "[object Object]" === TO_STRING(arg);
  5221. }
  5222. __name(isObject, "isObject");
  5223. exports2.isObject = isObject;
  5224. function mergeOptions(target, source) {
  5225. return { ...target, ...source };
  5226. }
  5227. __name(mergeOptions, "mergeOptions");
  5228. exports2.mergeOptions = mergeOptions;
  5229. function filterOptions(options, names) {
  5230. const filterOptions2 = {};
  5231. for (const name in options) {
  5232. if (names.includes(name)) {
  5233. filterOptions2[name] = options[name];
  5234. }
  5235. }
  5236. return filterOptions2;
  5237. }
  5238. __name(filterOptions, "filterOptions");
  5239. exports2.filterOptions = filterOptions;
  5240. function applyRetryableWrites(target, db) {
  5241. var _a;
  5242. if (db && ((_a = db.s.options) == null ? void 0 : _a.retryWrites)) {
  5243. target.retryWrites = true;
  5244. }
  5245. return target;
  5246. }
  5247. __name(applyRetryableWrites, "applyRetryableWrites");
  5248. exports2.applyRetryableWrites = applyRetryableWrites;
  5249. function isPromiseLike(value) {
  5250. return !!value && typeof value.then === "function";
  5251. }
  5252. __name(isPromiseLike, "isPromiseLike");
  5253. exports2.isPromiseLike = isPromiseLike;
  5254. function decorateWithCollation(command, target, options) {
  5255. const capabilities = getTopology(target).capabilities;
  5256. if (options.collation && typeof options.collation === "object") {
  5257. if (capabilities && capabilities.commandsTakeCollation) {
  5258. command.collation = options.collation;
  5259. } else {
  5260. throw new error_1.MongoCompatibilityError(`Current topology does not support collation`);
  5261. }
  5262. }
  5263. }
  5264. __name(decorateWithCollation, "decorateWithCollation");
  5265. exports2.decorateWithCollation = decorateWithCollation;
  5266. function decorateWithReadConcern(command, coll, options) {
  5267. if (options && options.session && options.session.inTransaction()) {
  5268. return;
  5269. }
  5270. const readConcern = Object.assign({}, command.readConcern || {});
  5271. if (coll.s.readConcern) {
  5272. Object.assign(readConcern, coll.s.readConcern);
  5273. }
  5274. if (Object.keys(readConcern).length > 0) {
  5275. Object.assign(command, { readConcern });
  5276. }
  5277. }
  5278. __name(decorateWithReadConcern, "decorateWithReadConcern");
  5279. exports2.decorateWithReadConcern = decorateWithReadConcern;
  5280. function decorateWithExplain(command, explain) {
  5281. if (command.explain) {
  5282. return command;
  5283. }
  5284. return { explain: command, verbosity: explain.verbosity };
  5285. }
  5286. __name(decorateWithExplain, "decorateWithExplain");
  5287. exports2.decorateWithExplain = decorateWithExplain;
  5288. function getTopology(provider) {
  5289. if ("topology" in provider && provider.topology) {
  5290. return provider.topology;
  5291. } else if ("client" in provider && provider.client.topology) {
  5292. return provider.client.topology;
  5293. }
  5294. throw new error_1.MongoNotConnectedError("MongoClient must be connected to perform this operation");
  5295. }
  5296. __name(getTopology, "getTopology");
  5297. exports2.getTopology = getTopology;
  5298. function ns(ns2) {
  5299. return MongoDBNamespace.fromString(ns2);
  5300. }
  5301. __name(ns, "ns");
  5302. exports2.ns = ns;
  5303. var _MongoDBNamespace = class _MongoDBNamespace {
  5304. /**
  5305. * Create a namespace object
  5306. *
  5307. * @param db - database name
  5308. * @param collection - collection name
  5309. */
  5310. constructor(db, collection) {
  5311. this.db = db;
  5312. this.collection = collection;
  5313. this.collection = collection === "" ? void 0 : collection;
  5314. }
  5315. toString() {
  5316. return this.collection ? `${this.db}.${this.collection}` : this.db;
  5317. }
  5318. withCollection(collection) {
  5319. return new MongoDBCollectionNamespace(this.db, collection);
  5320. }
  5321. static fromString(namespace) {
  5322. if (typeof namespace !== "string" || namespace === "") {
  5323. throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`);
  5324. }
  5325. const [db, ...collectionParts] = namespace.split(".");
  5326. const collection = collectionParts.join(".");
  5327. return new _MongoDBNamespace(db, collection === "" ? void 0 : collection);
  5328. }
  5329. };
  5330. __name(_MongoDBNamespace, "MongoDBNamespace");
  5331. var MongoDBNamespace = _MongoDBNamespace;
  5332. exports2.MongoDBNamespace = MongoDBNamespace;
  5333. var _MongoDBCollectionNamespace = class _MongoDBCollectionNamespace extends MongoDBNamespace {
  5334. constructor(db, collection) {
  5335. super(db, collection);
  5336. this.collection = collection;
  5337. }
  5338. };
  5339. __name(_MongoDBCollectionNamespace, "MongoDBCollectionNamespace");
  5340. var MongoDBCollectionNamespace = _MongoDBCollectionNamespace;
  5341. exports2.MongoDBCollectionNamespace = MongoDBCollectionNamespace;
  5342. function* makeCounter(seed = 0) {
  5343. let count = seed;
  5344. while (true) {
  5345. const newCount = count;
  5346. count += 1;
  5347. yield newCount;
  5348. }
  5349. }
  5350. __name(makeCounter, "makeCounter");
  5351. exports2.makeCounter = makeCounter;
  5352. function maybeCallback(promiseFn, callback) {
  5353. const promise = promiseFn();
  5354. if (callback == null) {
  5355. return promise;
  5356. }
  5357. promise.then((result) => callback(void 0, result), (error) => callback(error));
  5358. return;
  5359. }
  5360. __name(maybeCallback, "maybeCallback");
  5361. exports2.maybeCallback = maybeCallback;
  5362. function databaseNamespace(ns2) {
  5363. return ns2.split(".")[0];
  5364. }
  5365. __name(databaseNamespace, "databaseNamespace");
  5366. exports2.databaseNamespace = databaseNamespace;
  5367. function uuidV4() {
  5368. const result = crypto.randomBytes(16);
  5369. result[6] = result[6] & 15 | 64;
  5370. result[8] = result[8] & 63 | 128;
  5371. return result;
  5372. }
  5373. __name(uuidV4, "uuidV4");
  5374. exports2.uuidV4 = uuidV4;
  5375. function maxWireVersion(topologyOrServer) {
  5376. if (topologyOrServer) {
  5377. if (topologyOrServer.loadBalanced) {
  5378. return constants_1.MAX_SUPPORTED_WIRE_VERSION;
  5379. }
  5380. if (topologyOrServer.hello) {
  5381. return topologyOrServer.hello.maxWireVersion;
  5382. }
  5383. if ("lastHello" in topologyOrServer && typeof topologyOrServer.lastHello === "function") {
  5384. const lastHello = topologyOrServer.lastHello();
  5385. if (lastHello) {
  5386. return lastHello.maxWireVersion;
  5387. }
  5388. }
  5389. if (topologyOrServer.description && "maxWireVersion" in topologyOrServer.description && topologyOrServer.description.maxWireVersion != null) {
  5390. return topologyOrServer.description.maxWireVersion;
  5391. }
  5392. }
  5393. return 0;
  5394. }
  5395. __name(maxWireVersion, "maxWireVersion");
  5396. exports2.maxWireVersion = maxWireVersion;
  5397. function eachAsync(arr, eachFn, callback) {
  5398. arr = arr || [];
  5399. let idx = 0;
  5400. let awaiting = 0;
  5401. for (idx = 0; idx < arr.length; ++idx) {
  5402. awaiting++;
  5403. eachFn(arr[idx], eachCallback);
  5404. }
  5405. if (awaiting === 0) {
  5406. callback();
  5407. return;
  5408. }
  5409. function eachCallback(err) {
  5410. awaiting--;
  5411. if (err) {
  5412. callback(err);
  5413. return;
  5414. }
  5415. if (idx === arr.length && awaiting <= 0) {
  5416. callback();
  5417. }
  5418. }
  5419. __name(eachCallback, "eachCallback");
  5420. }
  5421. __name(eachAsync, "eachAsync");
  5422. exports2.eachAsync = eachAsync;
  5423. function arrayStrictEqual(arr, arr2) {
  5424. if (!Array.isArray(arr) || !Array.isArray(arr2)) {
  5425. return false;
  5426. }
  5427. return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]);
  5428. }
  5429. __name(arrayStrictEqual, "arrayStrictEqual");
  5430. exports2.arrayStrictEqual = arrayStrictEqual;
  5431. function errorStrictEqual(lhs, rhs) {
  5432. if (lhs === rhs) {
  5433. return true;
  5434. }
  5435. if (!lhs || !rhs) {
  5436. return lhs === rhs;
  5437. }
  5438. if (lhs == null && rhs != null || lhs != null && rhs == null) {
  5439. return false;
  5440. }
  5441. if (lhs.constructor.name !== rhs.constructor.name) {
  5442. return false;
  5443. }
  5444. if (lhs.message !== rhs.message) {
  5445. return false;
  5446. }
  5447. return true;
  5448. }
  5449. __name(errorStrictEqual, "errorStrictEqual");
  5450. exports2.errorStrictEqual = errorStrictEqual;
  5451. function makeStateMachine(stateTable) {
  5452. return /* @__PURE__ */ __name(function stateTransition(target, newState) {
  5453. const legalStates = stateTable[target.s.state];
  5454. if (legalStates && legalStates.indexOf(newState) < 0) {
  5455. throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`);
  5456. }
  5457. target.emit("stateChanged", target.s.state, newState);
  5458. target.s.state = newState;
  5459. }, "stateTransition");
  5460. }
  5461. __name(makeStateMachine, "makeStateMachine");
  5462. exports2.makeStateMachine = makeStateMachine;
  5463. function now() {
  5464. const hrtime = process.hrtime();
  5465. return Math.floor(hrtime[0] * 1e3 + hrtime[1] / 1e6);
  5466. }
  5467. __name(now, "now");
  5468. exports2.now = now;
  5469. function calculateDurationInMs(started) {
  5470. if (typeof started !== "number") {
  5471. throw new error_1.MongoInvalidArgumentError("Numeric value required to calculate duration");
  5472. }
  5473. const elapsed = now() - started;
  5474. return elapsed < 0 ? 0 : elapsed;
  5475. }
  5476. __name(calculateDurationInMs, "calculateDurationInMs");
  5477. exports2.calculateDurationInMs = calculateDurationInMs;
  5478. function hasAtomicOperators(doc) {
  5479. if (Array.isArray(doc)) {
  5480. for (const document of doc) {
  5481. if (hasAtomicOperators(document)) {
  5482. return true;
  5483. }
  5484. }
  5485. return false;
  5486. }
  5487. const keys = Object.keys(doc);
  5488. return keys.length > 0 && keys[0][0] === "$";
  5489. }
  5490. __name(hasAtomicOperators, "hasAtomicOperators");
  5491. exports2.hasAtomicOperators = hasAtomicOperators;
  5492. function resolveOptions(parent, options) {
  5493. const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent));
  5494. const session = options == null ? void 0 : options.session;
  5495. if (!(session == null ? void 0 : session.inTransaction())) {
  5496. const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? (parent == null ? void 0 : parent.readConcern);
  5497. if (readConcern) {
  5498. result.readConcern = readConcern;
  5499. }
  5500. const writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? (parent == null ? void 0 : parent.writeConcern);
  5501. if (writeConcern) {
  5502. result.writeConcern = writeConcern;
  5503. }
  5504. }
  5505. const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? (parent == null ? void 0 : parent.readPreference);
  5506. if (readPreference) {
  5507. result.readPreference = readPreference;
  5508. }
  5509. return result;
  5510. }
  5511. __name(resolveOptions, "resolveOptions");
  5512. exports2.resolveOptions = resolveOptions;
  5513. function isSuperset(set, subset) {
  5514. set = Array.isArray(set) ? new Set(set) : set;
  5515. subset = Array.isArray(subset) ? new Set(subset) : subset;
  5516. for (const elem of subset) {
  5517. if (!set.has(elem)) {
  5518. return false;
  5519. }
  5520. }
  5521. return true;
  5522. }
  5523. __name(isSuperset, "isSuperset");
  5524. exports2.isSuperset = isSuperset;
  5525. function isHello(doc) {
  5526. return doc[constants_2.LEGACY_HELLO_COMMAND] || doc.hello ? true : false;
  5527. }
  5528. __name(isHello, "isHello");
  5529. exports2.isHello = isHello;
  5530. function setDifference(setA, setB) {
  5531. const difference = new Set(setA);
  5532. for (const elem of setB) {
  5533. difference.delete(elem);
  5534. }
  5535. return difference;
  5536. }
  5537. __name(setDifference, "setDifference");
  5538. exports2.setDifference = setDifference;
  5539. var HAS_OWN = /* @__PURE__ */ __name((object, prop) => Object.prototype.hasOwnProperty.call(object, prop), "HAS_OWN");
  5540. function isRecord(value, requiredKeys = void 0) {
  5541. if (!isObject(value)) {
  5542. return false;
  5543. }
  5544. const ctor = value.constructor;
  5545. if (ctor && ctor.prototype) {
  5546. if (!isObject(ctor.prototype)) {
  5547. return false;
  5548. }
  5549. if (!HAS_OWN(ctor.prototype, "isPrototypeOf")) {
  5550. return false;
  5551. }
  5552. }
  5553. if (requiredKeys) {
  5554. const keys = Object.keys(value);
  5555. return isSuperset(keys, requiredKeys);
  5556. }
  5557. return true;
  5558. }
  5559. __name(isRecord, "isRecord");
  5560. exports2.isRecord = isRecord;
  5561. function deepCopy(value) {
  5562. if (value == null) {
  5563. return value;
  5564. } else if (Array.isArray(value)) {
  5565. return value.map((item) => deepCopy(item));
  5566. } else if (isRecord(value)) {
  5567. const res = {};
  5568. for (const key in value) {
  5569. res[key] = deepCopy(value[key]);
  5570. }
  5571. return res;
  5572. }
  5573. const ctor = value.constructor;
  5574. if (ctor) {
  5575. switch (ctor.name.toLowerCase()) {
  5576. case "date":
  5577. return new ctor(Number(value));
  5578. case "map":
  5579. return new Map(value);
  5580. case "set":
  5581. return new Set(value);
  5582. case "buffer":
  5583. return Buffer.from(value);
  5584. }
  5585. }
  5586. return value;
  5587. }
  5588. __name(deepCopy, "deepCopy");
  5589. exports2.deepCopy = deepCopy;
  5590. var _List = class _List {
  5591. get length() {
  5592. return this.count;
  5593. }
  5594. get [Symbol.toStringTag]() {
  5595. return "List";
  5596. }
  5597. constructor() {
  5598. this.count = 0;
  5599. this.head = {
  5600. next: null,
  5601. prev: null,
  5602. value: null
  5603. };
  5604. this.head.next = this.head;
  5605. this.head.prev = this.head;
  5606. }
  5607. toArray() {
  5608. return Array.from(this);
  5609. }
  5610. toString() {
  5611. return `head <=> ${this.toArray().join(" <=> ")} <=> head`;
  5612. }
  5613. *[Symbol.iterator]() {
  5614. for (const node of this.nodes()) {
  5615. yield node.value;
  5616. }
  5617. }
  5618. *nodes() {
  5619. let ptr = this.head.next;
  5620. while (ptr !== this.head) {
  5621. const { next } = ptr;
  5622. yield ptr;
  5623. ptr = next;
  5624. }
  5625. }
  5626. /** Insert at end of list */
  5627. push(value) {
  5628. this.count += 1;
  5629. const newNode = {
  5630. next: this.head,
  5631. prev: this.head.prev,
  5632. value
  5633. };
  5634. this.head.prev.next = newNode;
  5635. this.head.prev = newNode;
  5636. }
  5637. /** Inserts every item inside an iterable instead of the iterable itself */
  5638. pushMany(iterable) {
  5639. for (const value of iterable) {
  5640. this.push(value);
  5641. }
  5642. }
  5643. /** Insert at front of list */
  5644. unshift(value) {
  5645. this.count += 1;
  5646. const newNode = {
  5647. next: this.head.next,
  5648. prev: this.head,
  5649. value
  5650. };
  5651. this.head.next.prev = newNode;
  5652. this.head.next = newNode;
  5653. }
  5654. remove(node) {
  5655. if (node === this.head || this.length === 0) {
  5656. return null;
  5657. }
  5658. this.count -= 1;
  5659. const prevNode = node.prev;
  5660. const nextNode = node.next;
  5661. prevNode.next = nextNode;
  5662. nextNode.prev = prevNode;
  5663. return node.value;
  5664. }
  5665. /** Removes the first node at the front of the list */
  5666. shift() {
  5667. return this.remove(this.head.next);
  5668. }
  5669. /** Removes the last node at the end of the list */
  5670. pop() {
  5671. return this.remove(this.head.prev);
  5672. }
  5673. /** Iterates through the list and removes nodes where filter returns true */
  5674. prune(filter) {
  5675. for (const node of this.nodes()) {
  5676. if (filter(node.value)) {
  5677. this.remove(node);
  5678. }
  5679. }
  5680. }
  5681. clear() {
  5682. this.count = 0;
  5683. this.head.next = this.head;
  5684. this.head.prev = this.head;
  5685. }
  5686. /** Returns the first item in the list, does not remove */
  5687. first() {
  5688. return this.head.next.value;
  5689. }
  5690. /** Returns the last item in the list, does not remove */
  5691. last() {
  5692. return this.head.prev.value;
  5693. }
  5694. };
  5695. __name(_List, "List");
  5696. var List = _List;
  5697. exports2.List = List;
  5698. var _BufferPool = class _BufferPool {
  5699. constructor() {
  5700. this.buffers = new List();
  5701. this.totalByteLength = 0;
  5702. }
  5703. get length() {
  5704. return this.totalByteLength;
  5705. }
  5706. /** Adds a buffer to the internal buffer pool list */
  5707. append(buffer) {
  5708. this.buffers.push(buffer);
  5709. this.totalByteLength += buffer.length;
  5710. }
  5711. /**
  5712. * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes,
  5713. * otherwise return null. Size can be negative, caller should error check.
  5714. */
  5715. getInt32() {
  5716. if (this.totalByteLength < 4) {
  5717. return null;
  5718. }
  5719. const firstBuffer = this.buffers.first();
  5720. if (firstBuffer != null && firstBuffer.byteLength >= 4) {
  5721. return firstBuffer.readInt32LE(0);
  5722. }
  5723. const top4Bytes = this.read(4);
  5724. const value = top4Bytes.readInt32LE(0);
  5725. this.totalByteLength += 4;
  5726. this.buffers.unshift(top4Bytes);
  5727. return value;
  5728. }
  5729. /** Reads the requested number of bytes, optionally consuming them */
  5730. read(size) {
  5731. if (typeof size !== "number" || size < 0) {
  5732. throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number');
  5733. }
  5734. if (size > this.totalByteLength) {
  5735. return Buffer.alloc(0);
  5736. }
  5737. const result = Buffer.allocUnsafe(size);
  5738. for (let bytesRead = 0; bytesRead < size; ) {
  5739. const buffer = this.buffers.shift();
  5740. if (buffer == null) {
  5741. break;
  5742. }
  5743. const bytesRemaining = size - bytesRead;
  5744. const bytesReadable = Math.min(bytesRemaining, buffer.byteLength);
  5745. const bytes = buffer.subarray(0, bytesReadable);
  5746. result.set(bytes, bytesRead);
  5747. bytesRead += bytesReadable;
  5748. this.totalByteLength -= bytesReadable;
  5749. if (bytesReadable < buffer.byteLength) {
  5750. this.buffers.unshift(buffer.subarray(bytesReadable));
  5751. }
  5752. }
  5753. return result;
  5754. }
  5755. };
  5756. __name(_BufferPool, "BufferPool");
  5757. var BufferPool = _BufferPool;
  5758. exports2.BufferPool = BufferPool;
  5759. var _HostAddress = class _HostAddress {
  5760. constructor(hostString) {
  5761. this.host = void 0;
  5762. this.port = void 0;
  5763. this.socketPath = void 0;
  5764. this.isIPv6 = false;
  5765. const escapedHost = hostString.split(" ").join("%20");
  5766. if (escapedHost.endsWith(".sock")) {
  5767. this.socketPath = decodeURIComponent(escapedHost);
  5768. return;
  5769. }
  5770. const urlString = `iLoveJS://${escapedHost}`;
  5771. let url2;
  5772. try {
  5773. url2 = new url_1.URL(urlString);
  5774. } catch (urlError) {
  5775. const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`);
  5776. runtimeError.cause = urlError;
  5777. throw runtimeError;
  5778. }
  5779. const hostname = url2.hostname;
  5780. const port = url2.port;
  5781. let normalized = decodeURIComponent(hostname).toLowerCase();
  5782. if (normalized.startsWith("[") && normalized.endsWith("]")) {
  5783. this.isIPv6 = true;
  5784. normalized = normalized.substring(1, hostname.length - 1);
  5785. }
  5786. this.host = normalized.toLowerCase();
  5787. if (typeof port === "number") {
  5788. this.port = port;
  5789. } else if (typeof port === "string" && port !== "") {
  5790. this.port = Number.parseInt(port, 10);
  5791. } else {
  5792. this.port = 27017;
  5793. }
  5794. if (this.port === 0) {
  5795. throw new error_1.MongoParseError("Invalid port (zero) with hostname");
  5796. }
  5797. Object.freeze(this);
  5798. }
  5799. [Symbol.for("nodejs.util.inspect.custom")]() {
  5800. return this.inspect();
  5801. }
  5802. inspect() {
  5803. return `new HostAddress('${this.toString()}')`;
  5804. }
  5805. toString() {
  5806. if (typeof this.host === "string") {
  5807. if (this.isIPv6) {
  5808. return `[${this.host}]:${this.port}`;
  5809. }
  5810. return `${this.host}:${this.port}`;
  5811. }
  5812. return `${this.socketPath}`;
  5813. }
  5814. static fromString(s) {
  5815. return new _HostAddress(s);
  5816. }
  5817. static fromHostPort(host, port) {
  5818. if (host.includes(":")) {
  5819. host = `[${host}]`;
  5820. }
  5821. return _HostAddress.fromString(`${host}:${port}`);
  5822. }
  5823. static fromSrvRecord({ name, port }) {
  5824. return _HostAddress.fromHostPort(name, port);
  5825. }
  5826. toHostPort() {
  5827. if (this.socketPath) {
  5828. return { host: this.socketPath, port: 0 };
  5829. }
  5830. const host = this.host ?? "";
  5831. const port = this.port ?? 0;
  5832. return { host, port };
  5833. }
  5834. };
  5835. __name(_HostAddress, "HostAddress");
  5836. var HostAddress = _HostAddress;
  5837. exports2.HostAddress = HostAddress;
  5838. exports2.DEFAULT_PK_FACTORY = {
  5839. // We prefer not to rely on ObjectId having a createPk method
  5840. createPk() {
  5841. return new bson_1.ObjectId();
  5842. }
  5843. };
  5844. exports2.MONGODB_WARNING_CODE = "MONGODB DRIVER";
  5845. function emitWarning(message) {
  5846. return process.emitWarning(message, { code: exports2.MONGODB_WARNING_CODE });
  5847. }
  5848. __name(emitWarning, "emitWarning");
  5849. exports2.emitWarning = emitWarning;
  5850. var emittedWarnings = /* @__PURE__ */ new Set();
  5851. function emitWarningOnce(message) {
  5852. if (!emittedWarnings.has(message)) {
  5853. emittedWarnings.add(message);
  5854. return emitWarning(message);
  5855. }
  5856. }
  5857. __name(emitWarningOnce, "emitWarningOnce");
  5858. exports2.emitWarningOnce = emitWarningOnce;
  5859. function enumToString(en) {
  5860. return Object.values(en).join(", ");
  5861. }
  5862. __name(enumToString, "enumToString");
  5863. exports2.enumToString = enumToString;
  5864. function supportsRetryableWrites(server) {
  5865. if (!server) {
  5866. return false;
  5867. }
  5868. if (server.loadBalanced) {
  5869. return true;
  5870. }
  5871. if (server.description.logicalSessionTimeoutMinutes != null) {
  5872. if (server.description.type !== common_1.ServerType.Standalone) {
  5873. return true;
  5874. }
  5875. }
  5876. return false;
  5877. }
  5878. __name(supportsRetryableWrites, "supportsRetryableWrites");
  5879. exports2.supportsRetryableWrites = supportsRetryableWrites;
  5880. function shuffle(sequence, limit = 0) {
  5881. const items = Array.from(sequence);
  5882. if (limit > items.length) {
  5883. throw new error_1.MongoRuntimeError("Limit must be less than the number of items");
  5884. }
  5885. let remainingItemsToShuffle = items.length;
  5886. const lowerBound = limit % items.length === 0 ? 1 : items.length - limit;
  5887. while (remainingItemsToShuffle > lowerBound) {
  5888. const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle);
  5889. remainingItemsToShuffle -= 1;
  5890. const swapHold = items[remainingItemsToShuffle];
  5891. items[remainingItemsToShuffle] = items[randomIndex];
  5892. items[randomIndex] = swapHold;
  5893. }
  5894. return limit % items.length === 0 ? items : items.slice(lowerBound);
  5895. }
  5896. __name(shuffle, "shuffle");
  5897. exports2.shuffle = shuffle;
  5898. function commandSupportsReadConcern(command, options) {
  5899. if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) {
  5900. return true;
  5901. }
  5902. if (command.mapReduce && options && options.out && (options.out.inline === 1 || options.out === "inline")) {
  5903. return true;
  5904. }
  5905. return false;
  5906. }
  5907. __name(commandSupportsReadConcern, "commandSupportsReadConcern");
  5908. exports2.commandSupportsReadConcern = commandSupportsReadConcern;
  5909. function getMongoDBClientEncryption() {
  5910. let mongodbClientEncryption = null;
  5911. if (typeof process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE === "string" && process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE.length > 0) {
  5912. try {
  5913. mongodbClientEncryption = require(process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE);
  5914. } catch {
  5915. }
  5916. } else {
  5917. try {
  5918. mongodbClientEncryption = require("mongodb-client-encryption");
  5919. } catch {
  5920. }
  5921. }
  5922. return mongodbClientEncryption;
  5923. }
  5924. __name(getMongoDBClientEncryption, "getMongoDBClientEncryption");
  5925. exports2.getMongoDBClientEncryption = getMongoDBClientEncryption;
  5926. function compareObjectId(oid1, oid2) {
  5927. if (oid1 == null && oid2 == null) {
  5928. return 0;
  5929. }
  5930. if (oid1 == null) {
  5931. return -1;
  5932. }
  5933. if (oid2 == null) {
  5934. return 1;
  5935. }
  5936. return exports2.ByteUtils.compare(oid1.id, oid2.id);
  5937. }
  5938. __name(compareObjectId, "compareObjectId");
  5939. exports2.compareObjectId = compareObjectId;
  5940. function parseInteger(value) {
  5941. if (typeof value === "number")
  5942. return Math.trunc(value);
  5943. const parsedValue = Number.parseInt(String(value), 10);
  5944. return Number.isNaN(parsedValue) ? null : parsedValue;
  5945. }
  5946. __name(parseInteger, "parseInteger");
  5947. exports2.parseInteger = parseInteger;
  5948. function parseUnsignedInteger(value) {
  5949. const parsedInt = parseInteger(value);
  5950. return parsedInt != null && parsedInt >= 0 ? parsedInt : null;
  5951. }
  5952. __name(parseUnsignedInteger, "parseUnsignedInteger");
  5953. exports2.parseUnsignedInteger = parseUnsignedInteger;
  5954. function matchesParentDomain(address, srvHost) {
  5955. const normalizedAddress = address.endsWith(".") ? address.slice(0, address.length - 1) : address;
  5956. const normalizedSrvHost = srvHost.endsWith(".") ? srvHost.slice(0, srvHost.length - 1) : srvHost;
  5957. const allCharacterBeforeFirstDot = /^.*?\./;
  5958. const addressDomain = `.${normalizedAddress.replace(allCharacterBeforeFirstDot, "")}`;
  5959. const srvHostDomain = `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, "")}`;
  5960. return addressDomain.endsWith(srvHostDomain);
  5961. }
  5962. __name(matchesParentDomain, "matchesParentDomain");
  5963. exports2.matchesParentDomain = matchesParentDomain;
  5964. async function request(uri, options = {}) {
  5965. return new Promise((resolve, reject) => {
  5966. const requestOptions = {
  5967. method: "GET",
  5968. timeout: 1e4,
  5969. json: true,
  5970. ...url.parse(uri),
  5971. ...options
  5972. };
  5973. const req = http.request(requestOptions, (res) => {
  5974. res.setEncoding("utf8");
  5975. let data = "";
  5976. res.on("data", (d) => {
  5977. data += d;
  5978. });
  5979. res.once("end", () => {
  5980. if (options.json === false) {
  5981. resolve(data);
  5982. return;
  5983. }
  5984. try {
  5985. const parsed = JSON.parse(data);
  5986. resolve(parsed);
  5987. } catch {
  5988. reject(new error_1.MongoRuntimeError(`Invalid JSON response: "${data}"`));
  5989. }
  5990. });
  5991. });
  5992. req.once("timeout", () => req.destroy(new error_1.MongoNetworkTimeoutError(`Network request to ${uri} timed out after ${options.timeout} ms`)));
  5993. req.once("error", (error) => reject(error));
  5994. req.end();
  5995. });
  5996. }
  5997. __name(request, "request");
  5998. exports2.request = request;
  5999. }
  6000. });
  6001. // node_modules/mongodb/lib/explain.js
  6002. var require_explain = __commonJS({
  6003. "node_modules/mongodb/lib/explain.js"(exports2) {
  6004. "use strict";
  6005. Object.defineProperty(exports2, "__esModule", { value: true });
  6006. exports2.Explain = exports2.ExplainVerbosity = void 0;
  6007. var error_1 = require_error();
  6008. exports2.ExplainVerbosity = Object.freeze({
  6009. queryPlanner: "queryPlanner",
  6010. queryPlannerExtended: "queryPlannerExtended",
  6011. executionStats: "executionStats",
  6012. allPlansExecution: "allPlansExecution"
  6013. });
  6014. var _Explain = class _Explain {
  6015. constructor(verbosity) {
  6016. if (typeof verbosity === "boolean") {
  6017. this.verbosity = verbosity ? exports2.ExplainVerbosity.allPlansExecution : exports2.ExplainVerbosity.queryPlanner;
  6018. } else {
  6019. this.verbosity = verbosity;
  6020. }
  6021. }
  6022. static fromOptions(options) {
  6023. if ((options == null ? void 0 : options.explain) == null)
  6024. return;
  6025. const explain = options.explain;
  6026. if (typeof explain === "boolean" || typeof explain === "string") {
  6027. return new _Explain(explain);
  6028. }
  6029. throw new error_1.MongoInvalidArgumentError('Field "explain" must be a string or a boolean');
  6030. }
  6031. };
  6032. __name(_Explain, "Explain");
  6033. var Explain = _Explain;
  6034. exports2.Explain = Explain;
  6035. }
  6036. });
  6037. // node_modules/mongodb/lib/sdam/server_selection.js
  6038. var require_server_selection = __commonJS({
  6039. "node_modules/mongodb/lib/sdam/server_selection.js"(exports2) {
  6040. "use strict";
  6041. Object.defineProperty(exports2, "__esModule", { value: true });
  6042. exports2.readPreferenceServerSelector = exports2.secondaryWritableServerSelector = exports2.sameServerSelector = exports2.writableServerSelector = exports2.MIN_SECONDARY_WRITE_WIRE_VERSION = void 0;
  6043. var error_1 = require_error();
  6044. var read_preference_1 = require_read_preference();
  6045. var common_1 = require_common();
  6046. var IDLE_WRITE_PERIOD = 1e4;
  6047. var SMALLEST_MAX_STALENESS_SECONDS = 90;
  6048. exports2.MIN_SECONDARY_WRITE_WIRE_VERSION = 13;
  6049. function writableServerSelector() {
  6050. return (topologyDescription, servers) => latencyWindowReducer(topologyDescription, servers.filter((s) => s.isWritable));
  6051. }
  6052. __name(writableServerSelector, "writableServerSelector");
  6053. exports2.writableServerSelector = writableServerSelector;
  6054. function sameServerSelector(description) {
  6055. return (topologyDescription, servers) => {
  6056. if (!description)
  6057. return [];
  6058. return servers.filter((sd) => {
  6059. return sd.address === description.address && sd.type !== common_1.ServerType.Unknown;
  6060. });
  6061. };
  6062. }
  6063. __name(sameServerSelector, "sameServerSelector");
  6064. exports2.sameServerSelector = sameServerSelector;
  6065. function secondaryWritableServerSelector(wireVersion, readPreference) {
  6066. if (!readPreference || !wireVersion || wireVersion && wireVersion < exports2.MIN_SECONDARY_WRITE_WIRE_VERSION) {
  6067. return readPreferenceServerSelector(read_preference_1.ReadPreference.primary);
  6068. }
  6069. return readPreferenceServerSelector(readPreference);
  6070. }
  6071. __name(secondaryWritableServerSelector, "secondaryWritableServerSelector");
  6072. exports2.secondaryWritableServerSelector = secondaryWritableServerSelector;
  6073. function maxStalenessReducer(readPreference, topologyDescription, servers) {
  6074. if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) {
  6075. return servers;
  6076. }
  6077. const maxStaleness = readPreference.maxStalenessSeconds;
  6078. const maxStalenessVariance = (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1e3;
  6079. if (maxStaleness < maxStalenessVariance) {
  6080. throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`);
  6081. }
  6082. if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) {
  6083. throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`);
  6084. }
  6085. if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) {
  6086. const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0];
  6087. return servers.reduce((result, server) => {
  6088. const stalenessMS = server.lastUpdateTime - server.lastWriteDate - (primary.lastUpdateTime - primary.lastWriteDate) + topologyDescription.heartbeatFrequencyMS;
  6089. const staleness = stalenessMS / 1e3;
  6090. const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0;
  6091. if (staleness <= maxStalenessSeconds) {
  6092. result.push(server);
  6093. }
  6094. return result;
  6095. }, []);
  6096. }
  6097. if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) {
  6098. if (servers.length === 0) {
  6099. return servers;
  6100. }
  6101. const sMax = servers.reduce((max, s) => s.lastWriteDate > max.lastWriteDate ? s : max);
  6102. return servers.reduce((result, server) => {
  6103. const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS;
  6104. const staleness = stalenessMS / 1e3;
  6105. const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0;
  6106. if (staleness <= maxStalenessSeconds) {
  6107. result.push(server);
  6108. }
  6109. return result;
  6110. }, []);
  6111. }
  6112. return servers;
  6113. }
  6114. __name(maxStalenessReducer, "maxStalenessReducer");
  6115. function tagSetMatch(tagSet, serverTags) {
  6116. const keys = Object.keys(tagSet);
  6117. const serverTagKeys = Object.keys(serverTags);
  6118. for (let i = 0; i < keys.length; ++i) {
  6119. const key = keys[i];
  6120. if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) {
  6121. return false;
  6122. }
  6123. }
  6124. return true;
  6125. }
  6126. __name(tagSetMatch, "tagSetMatch");
  6127. function tagSetReducer(readPreference, servers) {
  6128. if (readPreference.tags == null || Array.isArray(readPreference.tags) && readPreference.tags.length === 0) {
  6129. return servers;
  6130. }
  6131. for (let i = 0; i < readPreference.tags.length; ++i) {
  6132. const tagSet = readPreference.tags[i];
  6133. const serversMatchingTagset = servers.reduce((matched, server) => {
  6134. if (tagSetMatch(tagSet, server.tags))
  6135. matched.push(server);
  6136. return matched;
  6137. }, []);
  6138. if (serversMatchingTagset.length) {
  6139. return serversMatchingTagset;
  6140. }
  6141. }
  6142. return [];
  6143. }
  6144. __name(tagSetReducer, "tagSetReducer");
  6145. function latencyWindowReducer(topologyDescription, servers) {
  6146. const low = servers.reduce((min, server) => min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min), -1);
  6147. const high = low + topologyDescription.localThresholdMS;
  6148. return servers.reduce((result, server) => {
  6149. if (server.roundTripTime <= high && server.roundTripTime >= low)
  6150. result.push(server);
  6151. return result;
  6152. }, []);
  6153. }
  6154. __name(latencyWindowReducer, "latencyWindowReducer");
  6155. function primaryFilter(server) {
  6156. return server.type === common_1.ServerType.RSPrimary;
  6157. }
  6158. __name(primaryFilter, "primaryFilter");
  6159. function secondaryFilter(server) {
  6160. return server.type === common_1.ServerType.RSSecondary;
  6161. }
  6162. __name(secondaryFilter, "secondaryFilter");
  6163. function nearestFilter(server) {
  6164. return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary;
  6165. }
  6166. __name(nearestFilter, "nearestFilter");
  6167. function knownFilter(server) {
  6168. return server.type !== common_1.ServerType.Unknown;
  6169. }
  6170. __name(knownFilter, "knownFilter");
  6171. function loadBalancerFilter(server) {
  6172. return server.type === common_1.ServerType.LoadBalancer;
  6173. }
  6174. __name(loadBalancerFilter, "loadBalancerFilter");
  6175. function readPreferenceServerSelector(readPreference) {
  6176. if (!readPreference.isValid()) {
  6177. throw new error_1.MongoInvalidArgumentError("Invalid read preference specified");
  6178. }
  6179. return (topologyDescription, servers) => {
  6180. const commonWireVersion = topologyDescription.commonWireVersion;
  6181. if (commonWireVersion && readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) {
  6182. throw new error_1.MongoCompatibilityError(`Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`);
  6183. }
  6184. if (topologyDescription.type === common_1.TopologyType.LoadBalanced) {
  6185. return servers.filter(loadBalancerFilter);
  6186. }
  6187. if (topologyDescription.type === common_1.TopologyType.Unknown) {
  6188. return [];
  6189. }
  6190. if (topologyDescription.type === common_1.TopologyType.Single || topologyDescription.type === common_1.TopologyType.Sharded) {
  6191. return latencyWindowReducer(topologyDescription, servers.filter(knownFilter));
  6192. }
  6193. const mode = readPreference.mode;
  6194. if (mode === read_preference_1.ReadPreference.PRIMARY) {
  6195. return servers.filter(primaryFilter);
  6196. }
  6197. if (mode === read_preference_1.ReadPreference.PRIMARY_PREFERRED) {
  6198. const result = servers.filter(primaryFilter);
  6199. if (result.length) {
  6200. return result;
  6201. }
  6202. }
  6203. const filter = mode === read_preference_1.ReadPreference.NEAREST ? nearestFilter : secondaryFilter;
  6204. const selectedServers = latencyWindowReducer(topologyDescription, tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter))));
  6205. if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) {
  6206. return servers.filter(primaryFilter);
  6207. }
  6208. return selectedServers;
  6209. };
  6210. }
  6211. __name(readPreferenceServerSelector, "readPreferenceServerSelector");
  6212. exports2.readPreferenceServerSelector = readPreferenceServerSelector;
  6213. }
  6214. });
  6215. // node_modules/mongodb/lib/operations/operation.js
  6216. var require_operation = __commonJS({
  6217. "node_modules/mongodb/lib/operations/operation.js"(exports2) {
  6218. "use strict";
  6219. Object.defineProperty(exports2, "__esModule", { value: true });
  6220. exports2.defineAspects = exports2.AbstractCallbackOperation = exports2.AbstractOperation = exports2.Aspect = void 0;
  6221. var util_1 = require("util");
  6222. var bson_1 = require_bson2();
  6223. var read_preference_1 = require_read_preference();
  6224. exports2.Aspect = {
  6225. READ_OPERATION: Symbol("READ_OPERATION"),
  6226. WRITE_OPERATION: Symbol("WRITE_OPERATION"),
  6227. RETRYABLE: Symbol("RETRYABLE"),
  6228. EXPLAINABLE: Symbol("EXPLAINABLE"),
  6229. SKIP_COLLATION: Symbol("SKIP_COLLATION"),
  6230. CURSOR_CREATING: Symbol("CURSOR_CREATING"),
  6231. MUST_SELECT_SAME_SERVER: Symbol("MUST_SELECT_SAME_SERVER")
  6232. };
  6233. var kSession = Symbol("session");
  6234. var _AbstractOperation = class _AbstractOperation {
  6235. constructor(options = {}) {
  6236. this.readPreference = this.hasAspect(exports2.Aspect.WRITE_OPERATION) ? read_preference_1.ReadPreference.primary : read_preference_1.ReadPreference.fromOptions(options) ?? read_preference_1.ReadPreference.primary;
  6237. this.bsonOptions = (0, bson_1.resolveBSONOptions)(options);
  6238. this[kSession] = options.session != null ? options.session : void 0;
  6239. this.options = options;
  6240. this.bypassPinningCheck = !!options.bypassPinningCheck;
  6241. this.trySecondaryWrite = false;
  6242. }
  6243. hasAspect(aspect) {
  6244. const ctor = this.constructor;
  6245. if (ctor.aspects == null) {
  6246. return false;
  6247. }
  6248. return ctor.aspects.has(aspect);
  6249. }
  6250. get session() {
  6251. return this[kSession];
  6252. }
  6253. clearSession() {
  6254. this[kSession] = void 0;
  6255. }
  6256. get canRetryRead() {
  6257. return true;
  6258. }
  6259. get canRetryWrite() {
  6260. return true;
  6261. }
  6262. };
  6263. __name(_AbstractOperation, "AbstractOperation");
  6264. var AbstractOperation = _AbstractOperation;
  6265. exports2.AbstractOperation = AbstractOperation;
  6266. var _AbstractCallbackOperation = class _AbstractCallbackOperation extends AbstractOperation {
  6267. constructor(options = {}) {
  6268. super(options);
  6269. }
  6270. execute(server, session) {
  6271. return (0, util_1.promisify)((callback) => {
  6272. this.executeCallback(server, session, callback);
  6273. })();
  6274. }
  6275. };
  6276. __name(_AbstractCallbackOperation, "AbstractCallbackOperation");
  6277. var AbstractCallbackOperation = _AbstractCallbackOperation;
  6278. exports2.AbstractCallbackOperation = AbstractCallbackOperation;
  6279. function defineAspects(operation, aspects) {
  6280. if (!Array.isArray(aspects) && !(aspects instanceof Set)) {
  6281. aspects = [aspects];
  6282. }
  6283. aspects = new Set(aspects);
  6284. Object.defineProperty(operation, "aspects", {
  6285. value: aspects,
  6286. writable: false
  6287. });
  6288. return aspects;
  6289. }
  6290. __name(defineAspects, "defineAspects");
  6291. exports2.defineAspects = defineAspects;
  6292. }
  6293. });
  6294. // node_modules/mongodb/lib/operations/command.js
  6295. var require_command = __commonJS({
  6296. "node_modules/mongodb/lib/operations/command.js"(exports2) {
  6297. "use strict";
  6298. Object.defineProperty(exports2, "__esModule", { value: true });
  6299. exports2.CommandCallbackOperation = exports2.CommandOperation = void 0;
  6300. var error_1 = require_error();
  6301. var explain_1 = require_explain();
  6302. var read_concern_1 = require_read_concern();
  6303. var server_selection_1 = require_server_selection();
  6304. var utils_1 = require_utils();
  6305. var write_concern_1 = require_write_concern();
  6306. var operation_1 = require_operation();
  6307. var _CommandOperation = class _CommandOperation extends operation_1.AbstractCallbackOperation {
  6308. constructor(parent, options) {
  6309. super(options);
  6310. this.options = options ?? {};
  6311. const dbNameOverride = (options == null ? void 0 : options.dbName) || (options == null ? void 0 : options.authdb);
  6312. if (dbNameOverride) {
  6313. this.ns = new utils_1.MongoDBNamespace(dbNameOverride, "$cmd");
  6314. } else {
  6315. this.ns = parent ? parent.s.namespace.withCollection("$cmd") : new utils_1.MongoDBNamespace("admin", "$cmd");
  6316. }
  6317. this.readConcern = read_concern_1.ReadConcern.fromOptions(options);
  6318. this.writeConcern = write_concern_1.WriteConcern.fromOptions(options);
  6319. if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) {
  6320. this.explain = explain_1.Explain.fromOptions(options);
  6321. } else if ((options == null ? void 0 : options.explain) != null) {
  6322. throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`);
  6323. }
  6324. }
  6325. get canRetryWrite() {
  6326. if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) {
  6327. return this.explain == null;
  6328. }
  6329. return true;
  6330. }
  6331. async executeCommand(server, session, cmd) {
  6332. this.server = server;
  6333. const options = {
  6334. ...this.options,
  6335. ...this.bsonOptions,
  6336. readPreference: this.readPreference,
  6337. session
  6338. };
  6339. const serverWireVersion = (0, utils_1.maxWireVersion)(server);
  6340. const inTransaction = this.session && this.session.inTransaction();
  6341. if (this.readConcern && (0, utils_1.commandSupportsReadConcern)(cmd) && !inTransaction) {
  6342. Object.assign(cmd, { readConcern: this.readConcern });
  6343. }
  6344. if (this.trySecondaryWrite && serverWireVersion < server_selection_1.MIN_SECONDARY_WRITE_WIRE_VERSION) {
  6345. options.omitReadPreference = true;
  6346. }
  6347. if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) {
  6348. write_concern_1.WriteConcern.apply(cmd, this.writeConcern);
  6349. }
  6350. if (options.collation && typeof options.collation === "object" && !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) {
  6351. Object.assign(cmd, { collation: options.collation });
  6352. }
  6353. if (typeof options.maxTimeMS === "number") {
  6354. cmd.maxTimeMS = options.maxTimeMS;
  6355. }
  6356. if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) {
  6357. cmd = (0, utils_1.decorateWithExplain)(cmd, this.explain);
  6358. }
  6359. return server.commandAsync(this.ns, cmd, options);
  6360. }
  6361. };
  6362. __name(_CommandOperation, "CommandOperation");
  6363. var CommandOperation = _CommandOperation;
  6364. exports2.CommandOperation = CommandOperation;
  6365. var _CommandCallbackOperation = class _CommandCallbackOperation extends CommandOperation {
  6366. constructor(parent, options) {
  6367. super(parent, options);
  6368. }
  6369. executeCommandCallback(server, session, cmd, callback) {
  6370. super.executeCommand(server, session, cmd).then((res) => callback(void 0, res), (err) => callback(err, void 0));
  6371. }
  6372. };
  6373. __name(_CommandCallbackOperation, "CommandCallbackOperation");
  6374. var CommandCallbackOperation = _CommandCallbackOperation;
  6375. exports2.CommandCallbackOperation = CommandCallbackOperation;
  6376. }
  6377. });
  6378. // node_modules/mongodb/lib/operations/add_user.js
  6379. var require_add_user = __commonJS({
  6380. "node_modules/mongodb/lib/operations/add_user.js"(exports2) {
  6381. "use strict";
  6382. Object.defineProperty(exports2, "__esModule", { value: true });
  6383. exports2.AddUserOperation = void 0;
  6384. var crypto = require("crypto");
  6385. var error_1 = require_error();
  6386. var utils_1 = require_utils();
  6387. var command_1 = require_command();
  6388. var operation_1 = require_operation();
  6389. var _AddUserOperation = class _AddUserOperation extends command_1.CommandCallbackOperation {
  6390. constructor(db, username, password, options) {
  6391. super(db, options);
  6392. this.db = db;
  6393. this.username = username;
  6394. this.password = password;
  6395. this.options = options ?? {};
  6396. }
  6397. executeCallback(server, session, callback) {
  6398. const db = this.db;
  6399. const username = this.username;
  6400. const password = this.password;
  6401. const options = this.options;
  6402. if ("digestPassword" in options && options.digestPassword != null) {
  6403. return callback(new error_1.MongoInvalidArgumentError('Option "digestPassword" not supported via addUser, use db.command(...) instead'));
  6404. }
  6405. let roles;
  6406. if (!options.roles || Array.isArray(options.roles) && options.roles.length === 0) {
  6407. (0, utils_1.emitWarningOnce)('Creating a user without roles is deprecated. Defaults to "root" if db is "admin" or "dbOwner" otherwise');
  6408. if (db.databaseName.toLowerCase() === "admin") {
  6409. roles = ["root"];
  6410. } else {
  6411. roles = ["dbOwner"];
  6412. }
  6413. } else {
  6414. roles = Array.isArray(options.roles) ? options.roles : [options.roles];
  6415. }
  6416. let topology;
  6417. try {
  6418. topology = (0, utils_1.getTopology)(db);
  6419. } catch (error) {
  6420. return callback(error);
  6421. }
  6422. const digestPassword = topology.lastHello().maxWireVersion >= 7;
  6423. let userPassword = password;
  6424. if (!digestPassword) {
  6425. const md5 = crypto.createHash("md5");
  6426. md5.update(`${username}:mongo:${password}`);
  6427. userPassword = md5.digest("hex");
  6428. }
  6429. const command = {
  6430. createUser: username,
  6431. customData: options.customData || {},
  6432. roles,
  6433. digestPassword
  6434. };
  6435. if (typeof password === "string") {
  6436. command.pwd = userPassword;
  6437. }
  6438. super.executeCommandCallback(server, session, command, callback);
  6439. }
  6440. };
  6441. __name(_AddUserOperation, "AddUserOperation");
  6442. var AddUserOperation = _AddUserOperation;
  6443. exports2.AddUserOperation = AddUserOperation;
  6444. (0, operation_1.defineAspects)(AddUserOperation, [operation_1.Aspect.WRITE_OPERATION]);
  6445. }
  6446. });
  6447. // node_modules/mongodb/lib/operations/execute_operation.js
  6448. var require_execute_operation = __commonJS({
  6449. "node_modules/mongodb/lib/operations/execute_operation.js"(exports2) {
  6450. "use strict";
  6451. Object.defineProperty(exports2, "__esModule", { value: true });
  6452. exports2.executeOperation = void 0;
  6453. var error_1 = require_error();
  6454. var read_preference_1 = require_read_preference();
  6455. var server_selection_1 = require_server_selection();
  6456. var utils_1 = require_utils();
  6457. var operation_1 = require_operation();
  6458. var MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation;
  6459. var MMAPv1_RETRY_WRITES_ERROR_MESSAGE = "This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";
  6460. function executeOperation(client, operation, callback) {
  6461. return (0, utils_1.maybeCallback)(() => executeOperationAsync(client, operation), callback);
  6462. }
  6463. __name(executeOperation, "executeOperation");
  6464. exports2.executeOperation = executeOperation;
  6465. async function executeOperationAsync(client, operation) {
  6466. var _a;
  6467. if (!(operation instanceof operation_1.AbstractCallbackOperation)) {
  6468. throw new error_1.MongoRuntimeError("This method requires a valid operation instance");
  6469. }
  6470. if (client.topology == null) {
  6471. if (client.s.hasBeenClosed) {
  6472. throw new error_1.MongoNotConnectedError("Client must be connected before running operations");
  6473. }
  6474. client.s.options[Symbol.for("@@mdb.skipPingOnConnect")] = true;
  6475. try {
  6476. await client.connect();
  6477. } finally {
  6478. delete client.s.options[Symbol.for("@@mdb.skipPingOnConnect")];
  6479. }
  6480. }
  6481. const { topology } = client;
  6482. if (topology == null) {
  6483. throw new error_1.MongoRuntimeError("client.connect did not create a topology but also did not throw");
  6484. }
  6485. let session = operation.session;
  6486. let owner;
  6487. if (session == null) {
  6488. owner = Symbol();
  6489. session = client.startSession({ owner, explicit: false });
  6490. } else if (session.hasEnded) {
  6491. throw new error_1.MongoExpiredSessionError("Use of expired sessions is not permitted");
  6492. } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) {
  6493. throw new error_1.MongoCompatibilityError("Snapshot reads require MongoDB 5.0 or later");
  6494. }
  6495. const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary;
  6496. const inTransaction = !!(session == null ? void 0 : session.inTransaction());
  6497. if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) {
  6498. throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`);
  6499. }
  6500. if ((session == null ? void 0 : session.isPinned) && session.transaction.isCommitted && !operation.bypassPinningCheck) {
  6501. session.unpin();
  6502. }
  6503. let selector;
  6504. if (operation.hasAspect(operation_1.Aspect.MUST_SELECT_SAME_SERVER)) {
  6505. selector = (0, server_selection_1.sameServerSelector)((_a = operation.server) == null ? void 0 : _a.description);
  6506. } else if (operation.trySecondaryWrite) {
  6507. selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference);
  6508. } else {
  6509. selector = readPreference;
  6510. }
  6511. const server = await topology.selectServerAsync(selector, { session });
  6512. if (session == null) {
  6513. return operation.execute(server, void 0);
  6514. }
  6515. if (!operation.hasAspect(operation_1.Aspect.RETRYABLE)) {
  6516. try {
  6517. return await operation.execute(server, session);
  6518. } finally {
  6519. if ((session == null ? void 0 : session.owner) != null && session.owner === owner) {
  6520. await session.endSession().catch(() => null);
  6521. }
  6522. }
  6523. }
  6524. const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead;
  6525. const willRetryWrite = topology.s.options.retryWrites && !inTransaction && (0, utils_1.supportsRetryableWrites)(server) && operation.canRetryWrite;
  6526. const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION);
  6527. const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION);
  6528. const willRetry = hasReadAspect && willRetryRead || hasWriteAspect && willRetryWrite;
  6529. if (hasWriteAspect && willRetryWrite) {
  6530. operation.options.willRetryWrite = true;
  6531. session.incrementTransactionNumber();
  6532. }
  6533. try {
  6534. return await operation.execute(server, session);
  6535. } catch (operationError) {
  6536. if (willRetry && operationError instanceof error_1.MongoError) {
  6537. return await retryOperation(operation, operationError, {
  6538. session,
  6539. topology,
  6540. selector
  6541. });
  6542. }
  6543. throw operationError;
  6544. } finally {
  6545. if ((session == null ? void 0 : session.owner) != null && session.owner === owner) {
  6546. await session.endSession().catch(() => null);
  6547. }
  6548. }
  6549. }
  6550. __name(executeOperationAsync, "executeOperationAsync");
  6551. async function retryOperation(operation, originalError, { session, topology, selector }) {
  6552. const isWriteOperation = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION);
  6553. const isReadOperation = operation.hasAspect(operation_1.Aspect.READ_OPERATION);
  6554. if (isWriteOperation && originalError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) {
  6555. throw new error_1.MongoServerError({
  6556. message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,
  6557. errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,
  6558. originalError
  6559. });
  6560. }
  6561. if (isWriteOperation && !(0, error_1.isRetryableWriteError)(originalError)) {
  6562. throw originalError;
  6563. }
  6564. if (isReadOperation && !(0, error_1.isRetryableReadError)(originalError)) {
  6565. throw originalError;
  6566. }
  6567. if (originalError instanceof error_1.MongoNetworkError && session.isPinned && !session.inTransaction() && operation.hasAspect(operation_1.Aspect.CURSOR_CREATING)) {
  6568. session.unpin({ force: true, forceClear: true });
  6569. }
  6570. const server = await topology.selectServerAsync(selector, { session });
  6571. if (isWriteOperation && !(0, utils_1.supportsRetryableWrites)(server)) {
  6572. throw new error_1.MongoUnexpectedServerResponseError("Selected server does not support retryable writes");
  6573. }
  6574. try {
  6575. return await operation.execute(server, session);
  6576. } catch (retryError) {
  6577. if (retryError instanceof error_1.MongoError && retryError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) {
  6578. throw originalError;
  6579. }
  6580. throw retryError;
  6581. }
  6582. }
  6583. __name(retryOperation, "retryOperation");
  6584. }
  6585. });
  6586. // node_modules/mongodb/lib/operations/list_databases.js
  6587. var require_list_databases = __commonJS({
  6588. "node_modules/mongodb/lib/operations/list_databases.js"(exports2) {
  6589. "use strict";
  6590. Object.defineProperty(exports2, "__esModule", { value: true });
  6591. exports2.ListDatabasesOperation = void 0;
  6592. var utils_1 = require_utils();
  6593. var command_1 = require_command();
  6594. var operation_1 = require_operation();
  6595. var _ListDatabasesOperation = class _ListDatabasesOperation extends command_1.CommandCallbackOperation {
  6596. constructor(db, options) {
  6597. super(db, options);
  6598. this.options = options ?? {};
  6599. this.ns = new utils_1.MongoDBNamespace("admin", "$cmd");
  6600. }
  6601. executeCallback(server, session, callback) {
  6602. const cmd = { listDatabases: 1 };
  6603. if (typeof this.options.nameOnly === "boolean") {
  6604. cmd.nameOnly = this.options.nameOnly;
  6605. }
  6606. if (this.options.filter) {
  6607. cmd.filter = this.options.filter;
  6608. }
  6609. if (typeof this.options.authorizedDatabases === "boolean") {
  6610. cmd.authorizedDatabases = this.options.authorizedDatabases;
  6611. }
  6612. if ((0, utils_1.maxWireVersion)(server) >= 9 && this.options.comment !== void 0) {
  6613. cmd.comment = this.options.comment;
  6614. }
  6615. super.executeCommandCallback(server, session, cmd, callback);
  6616. }
  6617. };
  6618. __name(_ListDatabasesOperation, "ListDatabasesOperation");
  6619. var ListDatabasesOperation = _ListDatabasesOperation;
  6620. exports2.ListDatabasesOperation = ListDatabasesOperation;
  6621. (0, operation_1.defineAspects)(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]);
  6622. }
  6623. });
  6624. // node_modules/mongodb/lib/operations/remove_user.js
  6625. var require_remove_user = __commonJS({
  6626. "node_modules/mongodb/lib/operations/remove_user.js"(exports2) {
  6627. "use strict";
  6628. Object.defineProperty(exports2, "__esModule", { value: true });
  6629. exports2.RemoveUserOperation = void 0;
  6630. var command_1 = require_command();
  6631. var operation_1 = require_operation();
  6632. var _RemoveUserOperation = class _RemoveUserOperation extends command_1.CommandCallbackOperation {
  6633. constructor(db, username, options) {
  6634. super(db, options);
  6635. this.options = options;
  6636. this.username = username;
  6637. }
  6638. executeCallback(server, session, callback) {
  6639. super.executeCommandCallback(server, session, { dropUser: this.username }, (err) => {
  6640. callback(err, err ? false : true);
  6641. });
  6642. }
  6643. };
  6644. __name(_RemoveUserOperation, "RemoveUserOperation");
  6645. var RemoveUserOperation = _RemoveUserOperation;
  6646. exports2.RemoveUserOperation = RemoveUserOperation;
  6647. (0, operation_1.defineAspects)(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]);
  6648. }
  6649. });
  6650. // node_modules/mongodb/lib/operations/run_command.js
  6651. var require_run_command = __commonJS({
  6652. "node_modules/mongodb/lib/operations/run_command.js"(exports2) {
  6653. "use strict";
  6654. Object.defineProperty(exports2, "__esModule", { value: true });
  6655. exports2.RunAdminCommandOperation = exports2.RunCommandOperation = void 0;
  6656. var utils_1 = require_utils();
  6657. var command_1 = require_command();
  6658. var _RunCommandOperation = class _RunCommandOperation extends command_1.CommandCallbackOperation {
  6659. constructor(parent, command, options) {
  6660. super(parent, options);
  6661. this.options = options ?? {};
  6662. this.command = command;
  6663. }
  6664. executeCallback(server, session, callback) {
  6665. const command = this.command;
  6666. this.executeCommandCallback(server, session, command, callback);
  6667. }
  6668. };
  6669. __name(_RunCommandOperation, "RunCommandOperation");
  6670. var RunCommandOperation = _RunCommandOperation;
  6671. exports2.RunCommandOperation = RunCommandOperation;
  6672. var _RunAdminCommandOperation = class _RunAdminCommandOperation extends RunCommandOperation {
  6673. constructor(parent, command, options) {
  6674. super(parent, command, options);
  6675. this.ns = new utils_1.MongoDBNamespace("admin");
  6676. }
  6677. };
  6678. __name(_RunAdminCommandOperation, "RunAdminCommandOperation");
  6679. var RunAdminCommandOperation = _RunAdminCommandOperation;
  6680. exports2.RunAdminCommandOperation = RunAdminCommandOperation;
  6681. }
  6682. });
  6683. // node_modules/mongodb/lib/operations/validate_collection.js
  6684. var require_validate_collection = __commonJS({
  6685. "node_modules/mongodb/lib/operations/validate_collection.js"(exports2) {
  6686. "use strict";
  6687. Object.defineProperty(exports2, "__esModule", { value: true });
  6688. exports2.ValidateCollectionOperation = void 0;
  6689. var error_1 = require_error();
  6690. var command_1 = require_command();
  6691. var _ValidateCollectionOperation = class _ValidateCollectionOperation extends command_1.CommandCallbackOperation {
  6692. constructor(admin, collectionName, options) {
  6693. const command = { validate: collectionName };
  6694. const keys = Object.keys(options);
  6695. for (let i = 0; i < keys.length; i++) {
  6696. if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== "session") {
  6697. command[keys[i]] = options[keys[i]];
  6698. }
  6699. }
  6700. super(admin.s.db, options);
  6701. this.options = options;
  6702. this.command = command;
  6703. this.collectionName = collectionName;
  6704. }
  6705. executeCallback(server, session, callback) {
  6706. const collectionName = this.collectionName;
  6707. super.executeCommandCallback(server, session, this.command, (err, doc) => {
  6708. if (err != null)
  6709. return callback(err);
  6710. if (doc.ok === 0)
  6711. return callback(new error_1.MongoRuntimeError("Error with validate command"));
  6712. if (doc.result != null && typeof doc.result !== "string")
  6713. return callback(new error_1.MongoRuntimeError("Error with validation data"));
  6714. if (doc.result != null && doc.result.match(/exception|corrupt/) != null)
  6715. return callback(new error_1.MongoRuntimeError(`Invalid collection ${collectionName}`));
  6716. if (doc.valid != null && !doc.valid)
  6717. return callback(new error_1.MongoRuntimeError(`Invalid collection ${collectionName}`));
  6718. return callback(void 0, doc);
  6719. });
  6720. }
  6721. };
  6722. __name(_ValidateCollectionOperation, "ValidateCollectionOperation");
  6723. var ValidateCollectionOperation = _ValidateCollectionOperation;
  6724. exports2.ValidateCollectionOperation = ValidateCollectionOperation;
  6725. }
  6726. });
  6727. // node_modules/mongodb/lib/admin.js
  6728. var require_admin = __commonJS({
  6729. "node_modules/mongodb/lib/admin.js"(exports2) {
  6730. "use strict";
  6731. Object.defineProperty(exports2, "__esModule", { value: true });
  6732. exports2.Admin = void 0;
  6733. var add_user_1 = require_add_user();
  6734. var execute_operation_1 = require_execute_operation();
  6735. var list_databases_1 = require_list_databases();
  6736. var remove_user_1 = require_remove_user();
  6737. var run_command_1 = require_run_command();
  6738. var validate_collection_1 = require_validate_collection();
  6739. var _Admin = class _Admin {
  6740. /**
  6741. * Create a new Admin instance
  6742. * @internal
  6743. */
  6744. constructor(db) {
  6745. this.s = { db };
  6746. }
  6747. /**
  6748. * Execute a command
  6749. *
  6750. * The driver will ensure the following fields are attached to the command sent to the server:
  6751. * - `lsid` - sourced from an implicit session or options.session
  6752. * - `$readPreference` - defaults to primary or can be configured by options.readPreference
  6753. * - `$db` - sourced from the name of this database
  6754. *
  6755. * If the client has a serverApi setting:
  6756. * - `apiVersion`
  6757. * - `apiStrict`
  6758. * - `apiDeprecationErrors`
  6759. *
  6760. * When in a transaction:
  6761. * - `readConcern` - sourced from readConcern set on the TransactionOptions
  6762. * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
  6763. *
  6764. * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
  6765. *
  6766. * @param command - The command to execute
  6767. * @param options - Optional settings for the command
  6768. */
  6769. async command(command, options) {
  6770. return (0, execute_operation_1.executeOperation)(this.s.db.client, new run_command_1.RunCommandOperation(this.s.db, command, { dbName: "admin", ...options }));
  6771. }
  6772. /**
  6773. * Retrieve the server build information
  6774. *
  6775. * @param options - Optional settings for the command
  6776. */
  6777. async buildInfo(options) {
  6778. return this.command({ buildinfo: 1 }, options);
  6779. }
  6780. /**
  6781. * Retrieve the server build information
  6782. *
  6783. * @param options - Optional settings for the command
  6784. */
  6785. async serverInfo(options) {
  6786. return this.command({ buildinfo: 1 }, options);
  6787. }
  6788. /**
  6789. * Retrieve this db's server status.
  6790. *
  6791. * @param options - Optional settings for the command
  6792. */
  6793. async serverStatus(options) {
  6794. return this.command({ serverStatus: 1 }, options);
  6795. }
  6796. /**
  6797. * Ping the MongoDB server and retrieve results
  6798. *
  6799. * @param options - Optional settings for the command
  6800. */
  6801. async ping(options) {
  6802. return this.command({ ping: 1 }, options);
  6803. }
  6804. /**
  6805. * Add a user to the database
  6806. *
  6807. * @param username - The username for the new user
  6808. * @param passwordOrOptions - An optional password for the new user, or the options for the command
  6809. * @param options - Optional settings for the command
  6810. * @deprecated Use the createUser command in `db.command()` instead.
  6811. * @see https://www.mongodb.com/docs/manual/reference/command/createUser/
  6812. */
  6813. async addUser(username, passwordOrOptions, options) {
  6814. options = options != null && typeof options === "object" ? options : passwordOrOptions != null && typeof passwordOrOptions === "object" ? passwordOrOptions : void 0;
  6815. const password = typeof passwordOrOptions === "string" ? passwordOrOptions : void 0;
  6816. return (0, execute_operation_1.executeOperation)(this.s.db.client, new add_user_1.AddUserOperation(this.s.db, username, password, { dbName: "admin", ...options }));
  6817. }
  6818. /**
  6819. * Remove a user from a database
  6820. *
  6821. * @param username - The username to remove
  6822. * @param options - Optional settings for the command
  6823. */
  6824. async removeUser(username, options) {
  6825. return (0, execute_operation_1.executeOperation)(this.s.db.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: "admin", ...options }));
  6826. }
  6827. /**
  6828. * Validate an existing collection
  6829. *
  6830. * @param collectionName - The name of the collection to validate.
  6831. * @param options - Optional settings for the command
  6832. */
  6833. async validateCollection(collectionName, options = {}) {
  6834. return (0, execute_operation_1.executeOperation)(this.s.db.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options));
  6835. }
  6836. /**
  6837. * List the available databases
  6838. *
  6839. * @param options - Optional settings for the command
  6840. */
  6841. async listDatabases(options) {
  6842. return (0, execute_operation_1.executeOperation)(this.s.db.client, new list_databases_1.ListDatabasesOperation(this.s.db, options));
  6843. }
  6844. /**
  6845. * Get ReplicaSet status
  6846. *
  6847. * @param options - Optional settings for the command
  6848. */
  6849. async replSetGetStatus(options) {
  6850. return this.command({ replSetGetStatus: 1 }, options);
  6851. }
  6852. };
  6853. __name(_Admin, "Admin");
  6854. var Admin = _Admin;
  6855. exports2.Admin = Admin;
  6856. }
  6857. });
  6858. // node_modules/mongodb/lib/operations/delete.js
  6859. var require_delete = __commonJS({
  6860. "node_modules/mongodb/lib/operations/delete.js"(exports2) {
  6861. "use strict";
  6862. Object.defineProperty(exports2, "__esModule", { value: true });
  6863. exports2.makeDeleteStatement = exports2.DeleteManyOperation = exports2.DeleteOneOperation = exports2.DeleteOperation = void 0;
  6864. var error_1 = require_error();
  6865. var command_1 = require_command();
  6866. var operation_1 = require_operation();
  6867. var _DeleteOperation = class _DeleteOperation extends command_1.CommandCallbackOperation {
  6868. constructor(ns, statements, options) {
  6869. super(void 0, options);
  6870. this.options = options;
  6871. this.ns = ns;
  6872. this.statements = statements;
  6873. }
  6874. get canRetryWrite() {
  6875. if (super.canRetryWrite === false) {
  6876. return false;
  6877. }
  6878. return this.statements.every((op) => op.limit != null ? op.limit > 0 : true);
  6879. }
  6880. executeCallback(server, session, callback) {
  6881. const options = this.options ?? {};
  6882. const ordered = typeof options.ordered === "boolean" ? options.ordered : true;
  6883. const command = {
  6884. delete: this.ns.collection,
  6885. deletes: this.statements,
  6886. ordered
  6887. };
  6888. if (options.let) {
  6889. command.let = options.let;
  6890. }
  6891. if (options.comment !== void 0) {
  6892. command.comment = options.comment;
  6893. }
  6894. const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0;
  6895. if (unacknowledgedWrite) {
  6896. if (this.statements.find((o) => o.hint)) {
  6897. callback(new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`));
  6898. return;
  6899. }
  6900. }
  6901. super.executeCommandCallback(server, session, command, callback);
  6902. }
  6903. };
  6904. __name(_DeleteOperation, "DeleteOperation");
  6905. var DeleteOperation = _DeleteOperation;
  6906. exports2.DeleteOperation = DeleteOperation;
  6907. var _DeleteOneOperation = class _DeleteOneOperation extends DeleteOperation {
  6908. constructor(collection, filter, options) {
  6909. super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options);
  6910. }
  6911. executeCallback(server, session, callback) {
  6912. super.executeCallback(server, session, (err, res) => {
  6913. var _a;
  6914. if (err || res == null)
  6915. return callback(err);
  6916. if (res.code)
  6917. return callback(new error_1.MongoServerError(res));
  6918. if (res.writeErrors)
  6919. return callback(new error_1.MongoServerError(res.writeErrors[0]));
  6920. if (this.explain)
  6921. return callback(void 0, res);
  6922. callback(void 0, {
  6923. acknowledged: ((_a = this.writeConcern) == null ? void 0 : _a.w) !== 0,
  6924. deletedCount: res.n
  6925. });
  6926. });
  6927. }
  6928. };
  6929. __name(_DeleteOneOperation, "DeleteOneOperation");
  6930. var DeleteOneOperation = _DeleteOneOperation;
  6931. exports2.DeleteOneOperation = DeleteOneOperation;
  6932. var _DeleteManyOperation = class _DeleteManyOperation extends DeleteOperation {
  6933. constructor(collection, filter, options) {
  6934. super(collection.s.namespace, [makeDeleteStatement(filter, options)], options);
  6935. }
  6936. executeCallback(server, session, callback) {
  6937. super.executeCallback(server, session, (err, res) => {
  6938. var _a;
  6939. if (err || res == null)
  6940. return callback(err);
  6941. if (res.code)
  6942. return callback(new error_1.MongoServerError(res));
  6943. if (res.writeErrors)
  6944. return callback(new error_1.MongoServerError(res.writeErrors[0]));
  6945. if (this.explain)
  6946. return callback(void 0, res);
  6947. callback(void 0, {
  6948. acknowledged: ((_a = this.writeConcern) == null ? void 0 : _a.w) !== 0,
  6949. deletedCount: res.n
  6950. });
  6951. });
  6952. }
  6953. };
  6954. __name(_DeleteManyOperation, "DeleteManyOperation");
  6955. var DeleteManyOperation = _DeleteManyOperation;
  6956. exports2.DeleteManyOperation = DeleteManyOperation;
  6957. function makeDeleteStatement(filter, options) {
  6958. const op = {
  6959. q: filter,
  6960. limit: typeof options.limit === "number" ? options.limit : 0
  6961. };
  6962. if (options.collation) {
  6963. op.collation = options.collation;
  6964. }
  6965. if (options.hint) {
  6966. op.hint = options.hint;
  6967. }
  6968. return op;
  6969. }
  6970. __name(makeDeleteStatement, "makeDeleteStatement");
  6971. exports2.makeDeleteStatement = makeDeleteStatement;
  6972. (0, operation_1.defineAspects)(DeleteOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]);
  6973. (0, operation_1.defineAspects)(DeleteOneOperation, [
  6974. operation_1.Aspect.RETRYABLE,
  6975. operation_1.Aspect.WRITE_OPERATION,
  6976. operation_1.Aspect.EXPLAINABLE,
  6977. operation_1.Aspect.SKIP_COLLATION
  6978. ]);
  6979. (0, operation_1.defineAspects)(DeleteManyOperation, [
  6980. operation_1.Aspect.WRITE_OPERATION,
  6981. operation_1.Aspect.EXPLAINABLE,
  6982. operation_1.Aspect.SKIP_COLLATION
  6983. ]);
  6984. }
  6985. });
  6986. // node_modules/mongodb/lib/operations/bulk_write.js
  6987. var require_bulk_write = __commonJS({
  6988. "node_modules/mongodb/lib/operations/bulk_write.js"(exports2) {
  6989. "use strict";
  6990. Object.defineProperty(exports2, "__esModule", { value: true });
  6991. exports2.BulkWriteOperation = void 0;
  6992. var operation_1 = require_operation();
  6993. var _BulkWriteOperation = class _BulkWriteOperation extends operation_1.AbstractCallbackOperation {
  6994. constructor(collection, operations, options) {
  6995. super(options);
  6996. this.options = options;
  6997. this.collection = collection;
  6998. this.operations = operations;
  6999. }
  7000. executeCallback(server, session, callback) {
  7001. const coll = this.collection;
  7002. const operations = this.operations;
  7003. const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference };
  7004. const bulk = options.ordered === false ? coll.initializeUnorderedBulkOp(options) : coll.initializeOrderedBulkOp(options);
  7005. try {
  7006. for (let i = 0; i < operations.length; i++) {
  7007. bulk.raw(operations[i]);
  7008. }
  7009. } catch (err) {
  7010. return callback(err);
  7011. }
  7012. bulk.execute({ ...options, session }).then((result) => callback(void 0, result), (error) => callback(error));
  7013. }
  7014. };
  7015. __name(_BulkWriteOperation, "BulkWriteOperation");
  7016. var BulkWriteOperation = _BulkWriteOperation;
  7017. exports2.BulkWriteOperation = BulkWriteOperation;
  7018. (0, operation_1.defineAspects)(BulkWriteOperation, [operation_1.Aspect.WRITE_OPERATION]);
  7019. }
  7020. });
  7021. // node_modules/mongodb/lib/operations/common_functions.js
  7022. var require_common_functions = __commonJS({
  7023. "node_modules/mongodb/lib/operations/common_functions.js"(exports2) {
  7024. "use strict";
  7025. Object.defineProperty(exports2, "__esModule", { value: true });
  7026. exports2.prepareDocs = exports2.indexInformation = void 0;
  7027. var error_1 = require_error();
  7028. var utils_1 = require_utils();
  7029. function indexInformation(db, name, _optionsOrCallback, _callback) {
  7030. let options = _optionsOrCallback;
  7031. let callback = _callback;
  7032. if ("function" === typeof _optionsOrCallback) {
  7033. callback = _optionsOrCallback;
  7034. options = {};
  7035. }
  7036. const full = options.full == null ? false : options.full;
  7037. let topology;
  7038. try {
  7039. topology = (0, utils_1.getTopology)(db);
  7040. } catch (error) {
  7041. return callback(error);
  7042. }
  7043. if (topology.isDestroyed())
  7044. return callback(new error_1.MongoTopologyClosedError());
  7045. function processResults(indexes) {
  7046. const info = {};
  7047. for (let i = 0; i < indexes.length; i++) {
  7048. const index = indexes[i];
  7049. info[index.name] = [];
  7050. for (const name2 in index.key) {
  7051. info[index.name].push([name2, index.key[name2]]);
  7052. }
  7053. }
  7054. return info;
  7055. }
  7056. __name(processResults, "processResults");
  7057. db.collection(name).listIndexes(options).toArray().then((indexes) => {
  7058. if (!Array.isArray(indexes))
  7059. return callback(void 0, []);
  7060. if (full)
  7061. return callback(void 0, indexes);
  7062. callback(void 0, processResults(indexes));
  7063. }, (error) => callback(error));
  7064. }
  7065. __name(indexInformation, "indexInformation");
  7066. exports2.indexInformation = indexInformation;
  7067. function prepareDocs(coll, docs, options) {
  7068. var _a;
  7069. const forceServerObjectId = typeof options.forceServerObjectId === "boolean" ? options.forceServerObjectId : (_a = coll.s.db.options) == null ? void 0 : _a.forceServerObjectId;
  7070. if (forceServerObjectId === true) {
  7071. return docs;
  7072. }
  7073. return docs.map((doc) => {
  7074. if (doc._id == null) {
  7075. doc._id = coll.s.pkFactory.createPk();
  7076. }
  7077. return doc;
  7078. });
  7079. }
  7080. __name(prepareDocs, "prepareDocs");
  7081. exports2.prepareDocs = prepareDocs;
  7082. }
  7083. });
  7084. // node_modules/mongodb/lib/operations/insert.js
  7085. var require_insert = __commonJS({
  7086. "node_modules/mongodb/lib/operations/insert.js"(exports2) {
  7087. "use strict";
  7088. Object.defineProperty(exports2, "__esModule", { value: true });
  7089. exports2.InsertManyOperation = exports2.InsertOneOperation = exports2.InsertOperation = void 0;
  7090. var error_1 = require_error();
  7091. var write_concern_1 = require_write_concern();
  7092. var bulk_write_1 = require_bulk_write();
  7093. var command_1 = require_command();
  7094. var common_functions_1 = require_common_functions();
  7095. var operation_1 = require_operation();
  7096. var _InsertOperation = class _InsertOperation extends command_1.CommandCallbackOperation {
  7097. constructor(ns, documents, options) {
  7098. super(void 0, options);
  7099. this.options = { ...options, checkKeys: options.checkKeys ?? false };
  7100. this.ns = ns;
  7101. this.documents = documents;
  7102. }
  7103. executeCallback(server, session, callback) {
  7104. const options = this.options ?? {};
  7105. const ordered = typeof options.ordered === "boolean" ? options.ordered : true;
  7106. const command = {
  7107. insert: this.ns.collection,
  7108. documents: this.documents,
  7109. ordered
  7110. };
  7111. if (typeof options.bypassDocumentValidation === "boolean") {
  7112. command.bypassDocumentValidation = options.bypassDocumentValidation;
  7113. }
  7114. if (options.comment !== void 0) {
  7115. command.comment = options.comment;
  7116. }
  7117. super.executeCommandCallback(server, session, command, callback);
  7118. }
  7119. };
  7120. __name(_InsertOperation, "InsertOperation");
  7121. var InsertOperation = _InsertOperation;
  7122. exports2.InsertOperation = InsertOperation;
  7123. var _InsertOneOperation = class _InsertOneOperation extends InsertOperation {
  7124. constructor(collection, doc, options) {
  7125. super(collection.s.namespace, (0, common_functions_1.prepareDocs)(collection, [doc], options), options);
  7126. }
  7127. executeCallback(server, session, callback) {
  7128. super.executeCallback(server, session, (err, res) => {
  7129. var _a;
  7130. if (err || res == null)
  7131. return callback(err);
  7132. if (res.code)
  7133. return callback(new error_1.MongoServerError(res));
  7134. if (res.writeErrors) {
  7135. return callback(new error_1.MongoServerError(res.writeErrors[0]));
  7136. }
  7137. callback(void 0, {
  7138. acknowledged: ((_a = this.writeConcern) == null ? void 0 : _a.w) !== 0,
  7139. insertedId: this.documents[0]._id
  7140. });
  7141. });
  7142. }
  7143. };
  7144. __name(_InsertOneOperation, "InsertOneOperation");
  7145. var InsertOneOperation = _InsertOneOperation;
  7146. exports2.InsertOneOperation = InsertOneOperation;
  7147. var _InsertManyOperation = class _InsertManyOperation extends operation_1.AbstractCallbackOperation {
  7148. constructor(collection, docs, options) {
  7149. super(options);
  7150. if (!Array.isArray(docs)) {
  7151. throw new error_1.MongoInvalidArgumentError('Argument "docs" must be an array of documents');
  7152. }
  7153. this.options = options;
  7154. this.collection = collection;
  7155. this.docs = docs;
  7156. }
  7157. executeCallback(server, session, callback) {
  7158. const coll = this.collection;
  7159. const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference };
  7160. const writeConcern = write_concern_1.WriteConcern.fromOptions(options);
  7161. const bulkWriteOperation = new bulk_write_1.BulkWriteOperation(coll, (0, common_functions_1.prepareDocs)(coll, this.docs, options).map((document) => ({ insertOne: { document } })), options);
  7162. bulkWriteOperation.executeCallback(server, session, (err, res) => {
  7163. if (err || res == null) {
  7164. if (err && err.message === "Operation must be an object with an operation key") {
  7165. err = new error_1.MongoInvalidArgumentError("Collection.insertMany() cannot be called with an array that has null/undefined values");
  7166. }
  7167. return callback(err);
  7168. }
  7169. callback(void 0, {
  7170. acknowledged: (writeConcern == null ? void 0 : writeConcern.w) !== 0,
  7171. insertedCount: res.insertedCount,
  7172. insertedIds: res.insertedIds
  7173. });
  7174. });
  7175. }
  7176. };
  7177. __name(_InsertManyOperation, "InsertManyOperation");
  7178. var InsertManyOperation = _InsertManyOperation;
  7179. exports2.InsertManyOperation = InsertManyOperation;
  7180. (0, operation_1.defineAspects)(InsertOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]);
  7181. (0, operation_1.defineAspects)(InsertOneOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]);
  7182. (0, operation_1.defineAspects)(InsertManyOperation, [operation_1.Aspect.WRITE_OPERATION]);
  7183. }
  7184. });
  7185. // node_modules/mongodb/lib/operations/update.js
  7186. var require_update = __commonJS({
  7187. "node_modules/mongodb/lib/operations/update.js"(exports2) {
  7188. "use strict";
  7189. Object.defineProperty(exports2, "__esModule", { value: true });
  7190. exports2.makeUpdateStatement = exports2.ReplaceOneOperation = exports2.UpdateManyOperation = exports2.UpdateOneOperation = exports2.UpdateOperation = void 0;
  7191. var error_1 = require_error();
  7192. var utils_1 = require_utils();
  7193. var command_1 = require_command();
  7194. var operation_1 = require_operation();
  7195. var _UpdateOperation = class _UpdateOperation extends command_1.CommandCallbackOperation {
  7196. constructor(ns, statements, options) {
  7197. super(void 0, options);
  7198. this.options = options;
  7199. this.ns = ns;
  7200. this.statements = statements;
  7201. }
  7202. get canRetryWrite() {
  7203. if (super.canRetryWrite === false) {
  7204. return false;
  7205. }
  7206. return this.statements.every((op) => op.multi == null || op.multi === false);
  7207. }
  7208. executeCallback(server, session, callback) {
  7209. const options = this.options ?? {};
  7210. const ordered = typeof options.ordered === "boolean" ? options.ordered : true;
  7211. const command = {
  7212. update: this.ns.collection,
  7213. updates: this.statements,
  7214. ordered
  7215. };
  7216. if (typeof options.bypassDocumentValidation === "boolean") {
  7217. command.bypassDocumentValidation = options.bypassDocumentValidation;
  7218. }
  7219. if (options.let) {
  7220. command.let = options.let;
  7221. }
  7222. if (options.comment !== void 0) {
  7223. command.comment = options.comment;
  7224. }
  7225. const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0;
  7226. if (unacknowledgedWrite) {
  7227. if (this.statements.find((o) => o.hint)) {
  7228. callback(new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`));
  7229. return;
  7230. }
  7231. }
  7232. super.executeCommandCallback(server, session, command, callback);
  7233. }
  7234. };
  7235. __name(_UpdateOperation, "UpdateOperation");
  7236. var UpdateOperation = _UpdateOperation;
  7237. exports2.UpdateOperation = UpdateOperation;
  7238. var _UpdateOneOperation = class _UpdateOneOperation extends UpdateOperation {
  7239. constructor(collection, filter, update, options) {
  7240. super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: false })], options);
  7241. if (!(0, utils_1.hasAtomicOperators)(update)) {
  7242. throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
  7243. }
  7244. }
  7245. executeCallback(server, session, callback) {
  7246. super.executeCallback(server, session, (err, res) => {
  7247. var _a;
  7248. if (err || !res)
  7249. return callback(err);
  7250. if (this.explain != null)
  7251. return callback(void 0, res);
  7252. if (res.code)
  7253. return callback(new error_1.MongoServerError(res));
  7254. if (res.writeErrors)
  7255. return callback(new error_1.MongoServerError(res.writeErrors[0]));
  7256. callback(void 0, {
  7257. acknowledged: ((_a = this.writeConcern) == null ? void 0 : _a.w) !== 0,
  7258. modifiedCount: res.nModified != null ? res.nModified : res.n,
  7259. upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
  7260. upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
  7261. matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
  7262. });
  7263. });
  7264. }
  7265. };
  7266. __name(_UpdateOneOperation, "UpdateOneOperation");
  7267. var UpdateOneOperation = _UpdateOneOperation;
  7268. exports2.UpdateOneOperation = UpdateOneOperation;
  7269. var _UpdateManyOperation = class _UpdateManyOperation extends UpdateOperation {
  7270. constructor(collection, filter, update, options) {
  7271. super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: true })], options);
  7272. if (!(0, utils_1.hasAtomicOperators)(update)) {
  7273. throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
  7274. }
  7275. }
  7276. executeCallback(server, session, callback) {
  7277. super.executeCallback(server, session, (err, res) => {
  7278. var _a;
  7279. if (err || !res)
  7280. return callback(err);
  7281. if (this.explain != null)
  7282. return callback(void 0, res);
  7283. if (res.code)
  7284. return callback(new error_1.MongoServerError(res));
  7285. if (res.writeErrors)
  7286. return callback(new error_1.MongoServerError(res.writeErrors[0]));
  7287. callback(void 0, {
  7288. acknowledged: ((_a = this.writeConcern) == null ? void 0 : _a.w) !== 0,
  7289. modifiedCount: res.nModified != null ? res.nModified : res.n,
  7290. upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
  7291. upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
  7292. matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
  7293. });
  7294. });
  7295. }
  7296. };
  7297. __name(_UpdateManyOperation, "UpdateManyOperation");
  7298. var UpdateManyOperation = _UpdateManyOperation;
  7299. exports2.UpdateManyOperation = UpdateManyOperation;
  7300. var _ReplaceOneOperation = class _ReplaceOneOperation extends UpdateOperation {
  7301. constructor(collection, filter, replacement, options) {
  7302. super(collection.s.namespace, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options);
  7303. if ((0, utils_1.hasAtomicOperators)(replacement)) {
  7304. throw new error_1.MongoInvalidArgumentError("Replacement document must not contain atomic operators");
  7305. }
  7306. }
  7307. executeCallback(server, session, callback) {
  7308. super.executeCallback(server, session, (err, res) => {
  7309. var _a;
  7310. if (err || !res)
  7311. return callback(err);
  7312. if (this.explain != null)
  7313. return callback(void 0, res);
  7314. if (res.code)
  7315. return callback(new error_1.MongoServerError(res));
  7316. if (res.writeErrors)
  7317. return callback(new error_1.MongoServerError(res.writeErrors[0]));
  7318. callback(void 0, {
  7319. acknowledged: ((_a = this.writeConcern) == null ? void 0 : _a.w) !== 0,
  7320. modifiedCount: res.nModified != null ? res.nModified : res.n,
  7321. upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
  7322. upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
  7323. matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
  7324. });
  7325. });
  7326. }
  7327. };
  7328. __name(_ReplaceOneOperation, "ReplaceOneOperation");
  7329. var ReplaceOneOperation = _ReplaceOneOperation;
  7330. exports2.ReplaceOneOperation = ReplaceOneOperation;
  7331. function makeUpdateStatement(filter, update, options) {
  7332. if (filter == null || typeof filter !== "object") {
  7333. throw new error_1.MongoInvalidArgumentError("Selector must be a valid JavaScript object");
  7334. }
  7335. if (update == null || typeof update !== "object") {
  7336. throw new error_1.MongoInvalidArgumentError("Document must be a valid JavaScript object");
  7337. }
  7338. const op = { q: filter, u: update };
  7339. if (typeof options.upsert === "boolean") {
  7340. op.upsert = options.upsert;
  7341. }
  7342. if (options.multi) {
  7343. op.multi = options.multi;
  7344. }
  7345. if (options.hint) {
  7346. op.hint = options.hint;
  7347. }
  7348. if (options.arrayFilters) {
  7349. op.arrayFilters = options.arrayFilters;
  7350. }
  7351. if (options.collation) {
  7352. op.collation = options.collation;
  7353. }
  7354. return op;
  7355. }
  7356. __name(makeUpdateStatement, "makeUpdateStatement");
  7357. exports2.makeUpdateStatement = makeUpdateStatement;
  7358. (0, operation_1.defineAspects)(UpdateOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SKIP_COLLATION]);
  7359. (0, operation_1.defineAspects)(UpdateOneOperation, [
  7360. operation_1.Aspect.RETRYABLE,
  7361. operation_1.Aspect.WRITE_OPERATION,
  7362. operation_1.Aspect.EXPLAINABLE,
  7363. operation_1.Aspect.SKIP_COLLATION
  7364. ]);
  7365. (0, operation_1.defineAspects)(UpdateManyOperation, [
  7366. operation_1.Aspect.WRITE_OPERATION,
  7367. operation_1.Aspect.EXPLAINABLE,
  7368. operation_1.Aspect.SKIP_COLLATION
  7369. ]);
  7370. (0, operation_1.defineAspects)(ReplaceOneOperation, [
  7371. operation_1.Aspect.RETRYABLE,
  7372. operation_1.Aspect.WRITE_OPERATION,
  7373. operation_1.Aspect.SKIP_COLLATION
  7374. ]);
  7375. }
  7376. });
  7377. // node_modules/mongodb/lib/bulk/common.js
  7378. var require_common2 = __commonJS({
  7379. "node_modules/mongodb/lib/bulk/common.js"(exports2) {
  7380. "use strict";
  7381. Object.defineProperty(exports2, "__esModule", { value: true });
  7382. exports2.BulkOperationBase = exports2.FindOperators = exports2.MongoBulkWriteError = exports2.mergeBatchResults = exports2.WriteError = exports2.WriteConcernError = exports2.BulkWriteResult = exports2.Batch = exports2.BatchType = void 0;
  7383. var bson_1 = require_bson2();
  7384. var error_1 = require_error();
  7385. var delete_1 = require_delete();
  7386. var execute_operation_1 = require_execute_operation();
  7387. var insert_1 = require_insert();
  7388. var operation_1 = require_operation();
  7389. var update_1 = require_update();
  7390. var utils_1 = require_utils();
  7391. var write_concern_1 = require_write_concern();
  7392. var kServerError = Symbol("serverError");
  7393. exports2.BatchType = Object.freeze({
  7394. INSERT: 1,
  7395. UPDATE: 2,
  7396. DELETE: 3
  7397. });
  7398. var _Batch = class _Batch {
  7399. constructor(batchType, originalZeroIndex) {
  7400. this.originalZeroIndex = originalZeroIndex;
  7401. this.currentIndex = 0;
  7402. this.originalIndexes = [];
  7403. this.batchType = batchType;
  7404. this.operations = [];
  7405. this.size = 0;
  7406. this.sizeBytes = 0;
  7407. }
  7408. };
  7409. __name(_Batch, "Batch");
  7410. var Batch = _Batch;
  7411. exports2.Batch = Batch;
  7412. var _BulkWriteResult = class _BulkWriteResult {
  7413. static generateIdMap(ids) {
  7414. const idMap = {};
  7415. for (const doc of ids) {
  7416. idMap[doc.index] = doc._id;
  7417. }
  7418. return idMap;
  7419. }
  7420. /**
  7421. * Create a new BulkWriteResult instance
  7422. * @internal
  7423. */
  7424. constructor(bulkResult, isOrdered) {
  7425. this.result = bulkResult;
  7426. this.insertedCount = this.result.nInserted ?? 0;
  7427. this.matchedCount = this.result.nMatched ?? 0;
  7428. this.modifiedCount = this.result.nModified ?? 0;
  7429. this.deletedCount = this.result.nRemoved ?? 0;
  7430. this.upsertedCount = this.result.upserted.length ?? 0;
  7431. this.upsertedIds = _BulkWriteResult.generateIdMap(this.result.upserted);
  7432. this.insertedIds = _BulkWriteResult.generateIdMap(this.getSuccessfullyInsertedIds(bulkResult, isOrdered));
  7433. Object.defineProperty(this, "result", { value: this.result, enumerable: false });
  7434. }
  7435. /**
  7436. * Returns document_ids that were actually inserted
  7437. * @internal
  7438. */
  7439. getSuccessfullyInsertedIds(bulkResult, isOrdered) {
  7440. if (bulkResult.writeErrors.length === 0)
  7441. return bulkResult.insertedIds;
  7442. if (isOrdered) {
  7443. return bulkResult.insertedIds.slice(0, bulkResult.writeErrors[0].index);
  7444. }
  7445. return bulkResult.insertedIds.filter(({ index }) => !bulkResult.writeErrors.some((writeError) => index === writeError.index));
  7446. }
  7447. /** Evaluates to true if the bulk operation correctly executes */
  7448. get ok() {
  7449. return this.result.ok;
  7450. }
  7451. /**
  7452. * The number of inserted documents
  7453. * @deprecated Use insertedCount instead.
  7454. */
  7455. get nInserted() {
  7456. return this.result.nInserted;
  7457. }
  7458. /**
  7459. * Number of upserted documents
  7460. * @deprecated User upsertedCount instead.
  7461. */
  7462. get nUpserted() {
  7463. return this.result.nUpserted;
  7464. }
  7465. /**
  7466. * Number of matched documents
  7467. * @deprecated Use matchedCount instead.
  7468. */
  7469. get nMatched() {
  7470. return this.result.nMatched;
  7471. }
  7472. /**
  7473. * Number of documents updated physically on disk
  7474. * @deprecated Use modifiedCount instead.
  7475. */
  7476. get nModified() {
  7477. return this.result.nModified;
  7478. }
  7479. /**
  7480. * Number of removed documents
  7481. * @deprecated Use deletedCount instead.
  7482. */
  7483. get nRemoved() {
  7484. return this.result.nRemoved;
  7485. }
  7486. /**
  7487. * Returns an array of all inserted ids
  7488. * @deprecated Use insertedIds instead.
  7489. */
  7490. getInsertedIds() {
  7491. return this.result.insertedIds;
  7492. }
  7493. /**
  7494. * Returns an array of all upserted ids
  7495. * @deprecated Use upsertedIds instead.
  7496. */
  7497. getUpsertedIds() {
  7498. return this.result.upserted;
  7499. }
  7500. /** Returns the upserted id at the given index */
  7501. getUpsertedIdAt(index) {
  7502. return this.result.upserted[index];
  7503. }
  7504. /** Returns raw internal result */
  7505. getRawResponse() {
  7506. return this.result;
  7507. }
  7508. /** Returns true if the bulk operation contains a write error */
  7509. hasWriteErrors() {
  7510. return this.result.writeErrors.length > 0;
  7511. }
  7512. /** Returns the number of write errors off the bulk operation */
  7513. getWriteErrorCount() {
  7514. return this.result.writeErrors.length;
  7515. }
  7516. /** Returns a specific write error object */
  7517. getWriteErrorAt(index) {
  7518. return index < this.result.writeErrors.length ? this.result.writeErrors[index] : void 0;
  7519. }
  7520. /** Retrieve all write errors */
  7521. getWriteErrors() {
  7522. return this.result.writeErrors;
  7523. }
  7524. /** Retrieve the write concern error if one exists */
  7525. getWriteConcernError() {
  7526. if (this.result.writeConcernErrors.length === 0) {
  7527. return;
  7528. } else if (this.result.writeConcernErrors.length === 1) {
  7529. return this.result.writeConcernErrors[0];
  7530. } else {
  7531. let errmsg = "";
  7532. for (let i = 0; i < this.result.writeConcernErrors.length; i++) {
  7533. const err = this.result.writeConcernErrors[i];
  7534. errmsg = errmsg + err.errmsg;
  7535. if (i === 0)
  7536. errmsg = errmsg + " and ";
  7537. }
  7538. return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernFailed });
  7539. }
  7540. }
  7541. toString() {
  7542. return `BulkWriteResult(${this.result})`;
  7543. }
  7544. isOk() {
  7545. return this.result.ok === 1;
  7546. }
  7547. };
  7548. __name(_BulkWriteResult, "BulkWriteResult");
  7549. var BulkWriteResult = _BulkWriteResult;
  7550. exports2.BulkWriteResult = BulkWriteResult;
  7551. var _WriteConcernError = class _WriteConcernError {
  7552. constructor(error) {
  7553. this[kServerError] = error;
  7554. }
  7555. /** Write concern error code. */
  7556. get code() {
  7557. return this[kServerError].code;
  7558. }
  7559. /** Write concern error message. */
  7560. get errmsg() {
  7561. return this[kServerError].errmsg;
  7562. }
  7563. /** Write concern error info. */
  7564. get errInfo() {
  7565. return this[kServerError].errInfo;
  7566. }
  7567. toJSON() {
  7568. return this[kServerError];
  7569. }
  7570. toString() {
  7571. return `WriteConcernError(${this.errmsg})`;
  7572. }
  7573. };
  7574. __name(_WriteConcernError, "WriteConcernError");
  7575. var WriteConcernError = _WriteConcernError;
  7576. exports2.WriteConcernError = WriteConcernError;
  7577. var _WriteError = class _WriteError {
  7578. constructor(err) {
  7579. this.err = err;
  7580. }
  7581. /** WriteError code. */
  7582. get code() {
  7583. return this.err.code;
  7584. }
  7585. /** WriteError original bulk operation index. */
  7586. get index() {
  7587. return this.err.index;
  7588. }
  7589. /** WriteError message. */
  7590. get errmsg() {
  7591. return this.err.errmsg;
  7592. }
  7593. /** WriteError details. */
  7594. get errInfo() {
  7595. return this.err.errInfo;
  7596. }
  7597. /** Returns the underlying operation that caused the error */
  7598. getOperation() {
  7599. return this.err.op;
  7600. }
  7601. toJSON() {
  7602. return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op };
  7603. }
  7604. toString() {
  7605. return `WriteError(${JSON.stringify(this.toJSON())})`;
  7606. }
  7607. };
  7608. __name(_WriteError, "WriteError");
  7609. var WriteError = _WriteError;
  7610. exports2.WriteError = WriteError;
  7611. function mergeBatchResults(batch, bulkResult, err, result) {
  7612. if (err) {
  7613. result = err;
  7614. } else if (result && result.result) {
  7615. result = result.result;
  7616. }
  7617. if (result == null) {
  7618. return;
  7619. }
  7620. if (result.ok === 0 && bulkResult.ok === 1) {
  7621. bulkResult.ok = 0;
  7622. const writeError = {
  7623. index: 0,
  7624. code: result.code || 0,
  7625. errmsg: result.message,
  7626. errInfo: result.errInfo,
  7627. op: batch.operations[0]
  7628. };
  7629. bulkResult.writeErrors.push(new WriteError(writeError));
  7630. return;
  7631. } else if (result.ok === 0 && bulkResult.ok === 0) {
  7632. return;
  7633. }
  7634. if (isInsertBatch(batch) && result.n) {
  7635. bulkResult.nInserted = bulkResult.nInserted + result.n;
  7636. }
  7637. if (isDeleteBatch(batch) && result.n) {
  7638. bulkResult.nRemoved = bulkResult.nRemoved + result.n;
  7639. }
  7640. let nUpserted = 0;
  7641. if (Array.isArray(result.upserted)) {
  7642. nUpserted = result.upserted.length;
  7643. for (let i = 0; i < result.upserted.length; i++) {
  7644. bulkResult.upserted.push({
  7645. index: result.upserted[i].index + batch.originalZeroIndex,
  7646. _id: result.upserted[i]._id
  7647. });
  7648. }
  7649. } else if (result.upserted) {
  7650. nUpserted = 1;
  7651. bulkResult.upserted.push({
  7652. index: batch.originalZeroIndex,
  7653. _id: result.upserted
  7654. });
  7655. }
  7656. if (isUpdateBatch(batch) && result.n) {
  7657. const nModified = result.nModified;
  7658. bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;
  7659. bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);
  7660. if (typeof nModified === "number") {
  7661. bulkResult.nModified = bulkResult.nModified + nModified;
  7662. } else {
  7663. bulkResult.nModified = 0;
  7664. }
  7665. }
  7666. if (Array.isArray(result.writeErrors)) {
  7667. for (let i = 0; i < result.writeErrors.length; i++) {
  7668. const writeError = {
  7669. index: batch.originalIndexes[result.writeErrors[i].index],
  7670. code: result.writeErrors[i].code,
  7671. errmsg: result.writeErrors[i].errmsg,
  7672. errInfo: result.writeErrors[i].errInfo,
  7673. op: batch.operations[result.writeErrors[i].index]
  7674. };
  7675. bulkResult.writeErrors.push(new WriteError(writeError));
  7676. }
  7677. }
  7678. if (result.writeConcernError) {
  7679. bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
  7680. }
  7681. }
  7682. __name(mergeBatchResults, "mergeBatchResults");
  7683. exports2.mergeBatchResults = mergeBatchResults;
  7684. function executeCommands(bulkOperation, options, callback) {
  7685. if (bulkOperation.s.batches.length === 0) {
  7686. return callback(void 0, new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered));
  7687. }
  7688. const batch = bulkOperation.s.batches.shift();
  7689. function resultHandler(err, result) {
  7690. if (err && "message" in err && !(err instanceof error_1.MongoWriteConcernError)) {
  7691. return callback(new MongoBulkWriteError(err, new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered)));
  7692. }
  7693. if (err instanceof error_1.MongoWriteConcernError) {
  7694. return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, bulkOperation.isOrdered, err, callback);
  7695. }
  7696. mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result);
  7697. const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered);
  7698. if (bulkOperation.handleWriteError(callback, writeResult))
  7699. return;
  7700. executeCommands(bulkOperation, options, callback);
  7701. }
  7702. __name(resultHandler, "resultHandler");
  7703. const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, {
  7704. ...options,
  7705. ordered: bulkOperation.isOrdered
  7706. });
  7707. if (finalOptions.bypassDocumentValidation !== true) {
  7708. delete finalOptions.bypassDocumentValidation;
  7709. }
  7710. if (bulkOperation.operationId) {
  7711. resultHandler.operationId = bulkOperation.operationId;
  7712. }
  7713. if (bulkOperation.s.bypassDocumentValidation === true) {
  7714. finalOptions.bypassDocumentValidation = true;
  7715. }
  7716. if (bulkOperation.s.checkKeys === false) {
  7717. finalOptions.checkKeys = false;
  7718. }
  7719. if (finalOptions.retryWrites) {
  7720. if (isUpdateBatch(batch)) {
  7721. finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some((op) => op.multi);
  7722. }
  7723. if (isDeleteBatch(batch)) {
  7724. finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some((op) => op.limit === 0);
  7725. }
  7726. }
  7727. try {
  7728. if (isInsertBatch(batch)) {
  7729. (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.client, new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler);
  7730. } else if (isUpdateBatch(batch)) {
  7731. (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.client, new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler);
  7732. } else if (isDeleteBatch(batch)) {
  7733. (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.client, new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler);
  7734. }
  7735. } catch (err) {
  7736. err.ok = 0;
  7737. mergeBatchResults(batch, bulkOperation.s.bulkResult, err, void 0);
  7738. callback();
  7739. }
  7740. }
  7741. __name(executeCommands, "executeCommands");
  7742. function handleMongoWriteConcernError(batch, bulkResult, isOrdered, err, callback) {
  7743. var _a, _b;
  7744. mergeBatchResults(batch, bulkResult, void 0, err.result);
  7745. callback(new MongoBulkWriteError({
  7746. message: (_a = err.result) == null ? void 0 : _a.writeConcernError.errmsg,
  7747. code: (_b = err.result) == null ? void 0 : _b.writeConcernError.result
  7748. }, new BulkWriteResult(bulkResult, isOrdered)));
  7749. }
  7750. __name(handleMongoWriteConcernError, "handleMongoWriteConcernError");
  7751. var _MongoBulkWriteError = class _MongoBulkWriteError extends error_1.MongoServerError {
  7752. /** Creates a new MongoBulkWriteError */
  7753. constructor(error, result) {
  7754. super(error);
  7755. this.writeErrors = [];
  7756. if (error instanceof WriteConcernError)
  7757. this.err = error;
  7758. else if (!(error instanceof Error)) {
  7759. this.message = error.message;
  7760. this.code = error.code;
  7761. this.writeErrors = error.writeErrors ?? [];
  7762. }
  7763. this.result = result;
  7764. Object.assign(this, error);
  7765. }
  7766. get name() {
  7767. return "MongoBulkWriteError";
  7768. }
  7769. /** Number of documents inserted. */
  7770. get insertedCount() {
  7771. return this.result.insertedCount;
  7772. }
  7773. /** Number of documents matched for update. */
  7774. get matchedCount() {
  7775. return this.result.matchedCount;
  7776. }
  7777. /** Number of documents modified. */
  7778. get modifiedCount() {
  7779. return this.result.modifiedCount;
  7780. }
  7781. /** Number of documents deleted. */
  7782. get deletedCount() {
  7783. return this.result.deletedCount;
  7784. }
  7785. /** Number of documents upserted. */
  7786. get upsertedCount() {
  7787. return this.result.upsertedCount;
  7788. }
  7789. /** Inserted document generated Id's, hash key is the index of the originating operation */
  7790. get insertedIds() {
  7791. return this.result.insertedIds;
  7792. }
  7793. /** Upserted document generated Id's, hash key is the index of the originating operation */
  7794. get upsertedIds() {
  7795. return this.result.upsertedIds;
  7796. }
  7797. };
  7798. __name(_MongoBulkWriteError, "MongoBulkWriteError");
  7799. var MongoBulkWriteError = _MongoBulkWriteError;
  7800. exports2.MongoBulkWriteError = MongoBulkWriteError;
  7801. var _FindOperators = class _FindOperators {
  7802. /**
  7803. * Creates a new FindOperators object.
  7804. * @internal
  7805. */
  7806. constructor(bulkOperation) {
  7807. this.bulkOperation = bulkOperation;
  7808. }
  7809. /** Add a multiple update operation to the bulk operation */
  7810. update(updateDocument) {
  7811. const currentOp = buildCurrentOp(this.bulkOperation);
  7812. return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, {
  7813. ...currentOp,
  7814. multi: true
  7815. }));
  7816. }
  7817. /** Add a single update operation to the bulk operation */
  7818. updateOne(updateDocument) {
  7819. if (!(0, utils_1.hasAtomicOperators)(updateDocument)) {
  7820. throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
  7821. }
  7822. const currentOp = buildCurrentOp(this.bulkOperation);
  7823. return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false }));
  7824. }
  7825. /** Add a replace one operation to the bulk operation */
  7826. replaceOne(replacement) {
  7827. if ((0, utils_1.hasAtomicOperators)(replacement)) {
  7828. throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators");
  7829. }
  7830. const currentOp = buildCurrentOp(this.bulkOperation);
  7831. return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, replacement, { ...currentOp, multi: false }));
  7832. }
  7833. /** Add a delete one operation to the bulk operation */
  7834. deleteOne() {
  7835. const currentOp = buildCurrentOp(this.bulkOperation);
  7836. return this.bulkOperation.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 1 }));
  7837. }
  7838. /** Add a delete many operation to the bulk operation */
  7839. delete() {
  7840. const currentOp = buildCurrentOp(this.bulkOperation);
  7841. return this.bulkOperation.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 }));
  7842. }
  7843. /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */
  7844. upsert() {
  7845. if (!this.bulkOperation.s.currentOp) {
  7846. this.bulkOperation.s.currentOp = {};
  7847. }
  7848. this.bulkOperation.s.currentOp.upsert = true;
  7849. return this;
  7850. }
  7851. /** Specifies the collation for the query condition. */
  7852. collation(collation) {
  7853. if (!this.bulkOperation.s.currentOp) {
  7854. this.bulkOperation.s.currentOp = {};
  7855. }
  7856. this.bulkOperation.s.currentOp.collation = collation;
  7857. return this;
  7858. }
  7859. /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */
  7860. arrayFilters(arrayFilters) {
  7861. if (!this.bulkOperation.s.currentOp) {
  7862. this.bulkOperation.s.currentOp = {};
  7863. }
  7864. this.bulkOperation.s.currentOp.arrayFilters = arrayFilters;
  7865. return this;
  7866. }
  7867. /** Specifies hint for the bulk operation. */
  7868. hint(hint) {
  7869. if (!this.bulkOperation.s.currentOp) {
  7870. this.bulkOperation.s.currentOp = {};
  7871. }
  7872. this.bulkOperation.s.currentOp.hint = hint;
  7873. return this;
  7874. }
  7875. };
  7876. __name(_FindOperators, "FindOperators");
  7877. var FindOperators = _FindOperators;
  7878. exports2.FindOperators = FindOperators;
  7879. var _BulkWriteShimOperation = class _BulkWriteShimOperation extends operation_1.AbstractCallbackOperation {
  7880. constructor(bulkOperation, options) {
  7881. super(options);
  7882. this.bulkOperation = bulkOperation;
  7883. }
  7884. executeCallback(server, session, callback) {
  7885. if (this.options.session == null) {
  7886. this.options.session = session;
  7887. }
  7888. return executeCommands(this.bulkOperation, this.options, callback);
  7889. }
  7890. };
  7891. __name(_BulkWriteShimOperation, "BulkWriteShimOperation");
  7892. var BulkWriteShimOperation = _BulkWriteShimOperation;
  7893. var _BulkOperationBase = class _BulkOperationBase {
  7894. /**
  7895. * Create a new OrderedBulkOperation or UnorderedBulkOperation instance
  7896. * @internal
  7897. */
  7898. constructor(collection, options, isOrdered) {
  7899. this.isOrdered = isOrdered;
  7900. const topology = (0, utils_1.getTopology)(collection);
  7901. options = options == null ? {} : options;
  7902. const namespace = collection.s.namespace;
  7903. const executed = false;
  7904. const currentOp = void 0;
  7905. const hello = topology.lastHello();
  7906. const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter);
  7907. const maxBsonObjectSize = hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16;
  7908. const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize;
  7909. const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1e3;
  7910. const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2;
  7911. let finalOptions = Object.assign({}, options);
  7912. finalOptions = (0, utils_1.applyRetryableWrites)(finalOptions, collection.s.db);
  7913. const bulkResult = {
  7914. ok: 1,
  7915. writeErrors: [],
  7916. writeConcernErrors: [],
  7917. insertedIds: [],
  7918. nInserted: 0,
  7919. nUpserted: 0,
  7920. nMatched: 0,
  7921. nModified: 0,
  7922. nRemoved: 0,
  7923. upserted: []
  7924. };
  7925. this.s = {
  7926. // Final result
  7927. bulkResult,
  7928. // Current batch state
  7929. currentBatch: void 0,
  7930. currentIndex: 0,
  7931. // ordered specific
  7932. currentBatchSize: 0,
  7933. currentBatchSizeBytes: 0,
  7934. // unordered specific
  7935. currentInsertBatch: void 0,
  7936. currentUpdateBatch: void 0,
  7937. currentRemoveBatch: void 0,
  7938. batches: [],
  7939. // Write concern
  7940. writeConcern: write_concern_1.WriteConcern.fromOptions(options),
  7941. // Max batch size options
  7942. maxBsonObjectSize,
  7943. maxBatchSizeBytes,
  7944. maxWriteBatchSize,
  7945. maxKeySize,
  7946. // Namespace
  7947. namespace,
  7948. // Topology
  7949. topology,
  7950. // Options
  7951. options: finalOptions,
  7952. // BSON options
  7953. bsonOptions: (0, bson_1.resolveBSONOptions)(options),
  7954. // Current operation
  7955. currentOp,
  7956. // Executed
  7957. executed,
  7958. // Collection
  7959. collection,
  7960. // Fundamental error
  7961. err: void 0,
  7962. // check keys
  7963. checkKeys: typeof options.checkKeys === "boolean" ? options.checkKeys : false
  7964. };
  7965. if (options.bypassDocumentValidation === true) {
  7966. this.s.bypassDocumentValidation = true;
  7967. }
  7968. }
  7969. /**
  7970. * Add a single insert document to the bulk operation
  7971. *
  7972. * @example
  7973. * ```ts
  7974. * const bulkOp = collection.initializeOrderedBulkOp();
  7975. *
  7976. * // Adds three inserts to the bulkOp.
  7977. * bulkOp
  7978. * .insert({ a: 1 })
  7979. * .insert({ b: 2 })
  7980. * .insert({ c: 3 });
  7981. * await bulkOp.execute();
  7982. * ```
  7983. */
  7984. insert(document) {
  7985. if (document._id == null && !shouldForceServerObjectId(this)) {
  7986. document._id = new bson_1.ObjectId();
  7987. }
  7988. return this.addToOperationsList(exports2.BatchType.INSERT, document);
  7989. }
  7990. /**
  7991. * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
  7992. * Returns a builder object used to complete the definition of the operation.
  7993. *
  7994. * @example
  7995. * ```ts
  7996. * const bulkOp = collection.initializeOrderedBulkOp();
  7997. *
  7998. * // Add an updateOne to the bulkOp
  7999. * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
  8000. *
  8001. * // Add an updateMany to the bulkOp
  8002. * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
  8003. *
  8004. * // Add an upsert
  8005. * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
  8006. *
  8007. * // Add a deletion
  8008. * bulkOp.find({ g: 7 }).deleteOne();
  8009. *
  8010. * // Add a multi deletion
  8011. * bulkOp.find({ h: 8 }).delete();
  8012. *
  8013. * // Add a replaceOne
  8014. * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
  8015. *
  8016. * // Update using a pipeline (requires Mongodb 4.2 or higher)
  8017. * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
  8018. * { $set: { total: { $sum: [ '$y', '$z' ] } } }
  8019. * ]);
  8020. *
  8021. * // All of the ops will now be executed
  8022. * await bulkOp.execute();
  8023. * ```
  8024. */
  8025. find(selector) {
  8026. if (!selector) {
  8027. throw new error_1.MongoInvalidArgumentError("Bulk find operation must specify a selector");
  8028. }
  8029. this.s.currentOp = {
  8030. selector
  8031. };
  8032. return new FindOperators(this);
  8033. }
  8034. /** Specifies a raw operation to perform in the bulk write. */
  8035. raw(op) {
  8036. if (op == null || typeof op !== "object") {
  8037. throw new error_1.MongoInvalidArgumentError("Operation must be an object with an operation key");
  8038. }
  8039. if ("insertOne" in op) {
  8040. const forceServerObjectId = shouldForceServerObjectId(this);
  8041. if (op.insertOne && op.insertOne.document == null) {
  8042. if (forceServerObjectId !== true && op.insertOne._id == null) {
  8043. op.insertOne._id = new bson_1.ObjectId();
  8044. }
  8045. return this.addToOperationsList(exports2.BatchType.INSERT, op.insertOne);
  8046. }
  8047. if (forceServerObjectId !== true && op.insertOne.document._id == null) {
  8048. op.insertOne.document._id = new bson_1.ObjectId();
  8049. }
  8050. return this.addToOperationsList(exports2.BatchType.INSERT, op.insertOne.document);
  8051. }
  8052. if ("replaceOne" in op || "updateOne" in op || "updateMany" in op) {
  8053. if ("replaceOne" in op) {
  8054. if ("q" in op.replaceOne) {
  8055. throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
  8056. }
  8057. const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false });
  8058. if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) {
  8059. throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators");
  8060. }
  8061. return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement);
  8062. }
  8063. if ("updateOne" in op) {
  8064. if ("q" in op.updateOne) {
  8065. throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
  8066. }
  8067. const updateStatement = (0, update_1.makeUpdateStatement)(op.updateOne.filter, op.updateOne.update, {
  8068. ...op.updateOne,
  8069. multi: false
  8070. });
  8071. if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) {
  8072. throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
  8073. }
  8074. return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement);
  8075. }
  8076. if ("updateMany" in op) {
  8077. if ("q" in op.updateMany) {
  8078. throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
  8079. }
  8080. const updateStatement = (0, update_1.makeUpdateStatement)(op.updateMany.filter, op.updateMany.update, {
  8081. ...op.updateMany,
  8082. multi: true
  8083. });
  8084. if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) {
  8085. throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
  8086. }
  8087. return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement);
  8088. }
  8089. }
  8090. if ("deleteOne" in op) {
  8091. if ("q" in op.deleteOne) {
  8092. throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
  8093. }
  8094. return this.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteOne.filter, { ...op.deleteOne, limit: 1 }));
  8095. }
  8096. if ("deleteMany" in op) {
  8097. if ("q" in op.deleteMany) {
  8098. throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
  8099. }
  8100. return this.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteMany.filter, { ...op.deleteMany, limit: 0 }));
  8101. }
  8102. throw new error_1.MongoInvalidArgumentError("bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany");
  8103. }
  8104. get bsonOptions() {
  8105. return this.s.bsonOptions;
  8106. }
  8107. get writeConcern() {
  8108. return this.s.writeConcern;
  8109. }
  8110. get batches() {
  8111. const batches = [...this.s.batches];
  8112. if (this.isOrdered) {
  8113. if (this.s.currentBatch)
  8114. batches.push(this.s.currentBatch);
  8115. } else {
  8116. if (this.s.currentInsertBatch)
  8117. batches.push(this.s.currentInsertBatch);
  8118. if (this.s.currentUpdateBatch)
  8119. batches.push(this.s.currentUpdateBatch);
  8120. if (this.s.currentRemoveBatch)
  8121. batches.push(this.s.currentRemoveBatch);
  8122. }
  8123. return batches;
  8124. }
  8125. async execute(options = {}) {
  8126. if (this.s.executed) {
  8127. throw new error_1.MongoBatchReExecutionError();
  8128. }
  8129. const writeConcern = write_concern_1.WriteConcern.fromOptions(options);
  8130. if (writeConcern) {
  8131. this.s.writeConcern = writeConcern;
  8132. }
  8133. if (this.isOrdered) {
  8134. if (this.s.currentBatch)
  8135. this.s.batches.push(this.s.currentBatch);
  8136. } else {
  8137. if (this.s.currentInsertBatch)
  8138. this.s.batches.push(this.s.currentInsertBatch);
  8139. if (this.s.currentUpdateBatch)
  8140. this.s.batches.push(this.s.currentUpdateBatch);
  8141. if (this.s.currentRemoveBatch)
  8142. this.s.batches.push(this.s.currentRemoveBatch);
  8143. }
  8144. if (this.s.batches.length === 0) {
  8145. throw new error_1.MongoInvalidArgumentError("Invalid BulkOperation, Batch cannot be empty");
  8146. }
  8147. this.s.executed = true;
  8148. const finalOptions = { ...this.s.options, ...options };
  8149. const operation = new BulkWriteShimOperation(this, finalOptions);
  8150. return (0, execute_operation_1.executeOperation)(this.s.collection.client, operation);
  8151. }
  8152. /**
  8153. * Handles the write error before executing commands
  8154. * @internal
  8155. */
  8156. handleWriteError(callback, writeResult) {
  8157. if (this.s.bulkResult.writeErrors.length > 0) {
  8158. const msg = this.s.bulkResult.writeErrors[0].errmsg ? this.s.bulkResult.writeErrors[0].errmsg : "write operation failed";
  8159. callback(new MongoBulkWriteError({
  8160. message: msg,
  8161. code: this.s.bulkResult.writeErrors[0].code,
  8162. writeErrors: this.s.bulkResult.writeErrors
  8163. }, writeResult));
  8164. return true;
  8165. }
  8166. const writeConcernError = writeResult.getWriteConcernError();
  8167. if (writeConcernError) {
  8168. callback(new MongoBulkWriteError(writeConcernError, writeResult));
  8169. return true;
  8170. }
  8171. return false;
  8172. }
  8173. };
  8174. __name(_BulkOperationBase, "BulkOperationBase");
  8175. var BulkOperationBase = _BulkOperationBase;
  8176. exports2.BulkOperationBase = BulkOperationBase;
  8177. Object.defineProperty(BulkOperationBase.prototype, "length", {
  8178. enumerable: true,
  8179. get() {
  8180. return this.s.currentIndex;
  8181. }
  8182. });
  8183. function shouldForceServerObjectId(bulkOperation) {
  8184. var _a, _b;
  8185. if (typeof bulkOperation.s.options.forceServerObjectId === "boolean") {
  8186. return bulkOperation.s.options.forceServerObjectId;
  8187. }
  8188. if (typeof ((_a = bulkOperation.s.collection.s.db.options) == null ? void 0 : _a.forceServerObjectId) === "boolean") {
  8189. return (_b = bulkOperation.s.collection.s.db.options) == null ? void 0 : _b.forceServerObjectId;
  8190. }
  8191. return false;
  8192. }
  8193. __name(shouldForceServerObjectId, "shouldForceServerObjectId");
  8194. function isInsertBatch(batch) {
  8195. return batch.batchType === exports2.BatchType.INSERT;
  8196. }
  8197. __name(isInsertBatch, "isInsertBatch");
  8198. function isUpdateBatch(batch) {
  8199. return batch.batchType === exports2.BatchType.UPDATE;
  8200. }
  8201. __name(isUpdateBatch, "isUpdateBatch");
  8202. function isDeleteBatch(batch) {
  8203. return batch.batchType === exports2.BatchType.DELETE;
  8204. }
  8205. __name(isDeleteBatch, "isDeleteBatch");
  8206. function buildCurrentOp(bulkOp) {
  8207. let { currentOp } = bulkOp.s;
  8208. bulkOp.s.currentOp = void 0;
  8209. if (!currentOp)
  8210. currentOp = {};
  8211. return currentOp;
  8212. }
  8213. __name(buildCurrentOp, "buildCurrentOp");
  8214. }
  8215. });
  8216. // node_modules/mongodb/lib/bulk/ordered.js
  8217. var require_ordered = __commonJS({
  8218. "node_modules/mongodb/lib/bulk/ordered.js"(exports2) {
  8219. "use strict";
  8220. Object.defineProperty(exports2, "__esModule", { value: true });
  8221. exports2.OrderedBulkOperation = void 0;
  8222. var BSON = require_bson2();
  8223. var error_1 = require_error();
  8224. var common_1 = require_common2();
  8225. var _OrderedBulkOperation = class _OrderedBulkOperation extends common_1.BulkOperationBase {
  8226. /** @internal */
  8227. constructor(collection, options) {
  8228. super(collection, options, true);
  8229. }
  8230. addToOperationsList(batchType, document) {
  8231. const bsonSize = BSON.calculateObjectSize(document, {
  8232. checkKeys: false,
  8233. // Since we don't know what the user selected for BSON options here,
  8234. // err on the safe side, and check the size with ignoreUndefined: false.
  8235. ignoreUndefined: false
  8236. });
  8237. if (bsonSize >= this.s.maxBsonObjectSize)
  8238. throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`);
  8239. if (this.s.currentBatch == null) {
  8240. this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex);
  8241. }
  8242. const maxKeySize = this.s.maxKeySize;
  8243. if (
  8244. // New batch if we exceed the max batch op size
  8245. this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,
  8246. // since we can't sent an empty batch
  8247. this.s.currentBatchSize > 0 && this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || // New batch if the new op does not have the same op type as the current batch
  8248. this.s.currentBatch.batchType !== batchType
  8249. ) {
  8250. this.s.batches.push(this.s.currentBatch);
  8251. this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex);
  8252. this.s.currentBatchSize = 0;
  8253. this.s.currentBatchSizeBytes = 0;
  8254. }
  8255. if (batchType === common_1.BatchType.INSERT) {
  8256. this.s.bulkResult.insertedIds.push({
  8257. index: this.s.currentIndex,
  8258. _id: document._id
  8259. });
  8260. }
  8261. if (Array.isArray(document)) {
  8262. throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array");
  8263. }
  8264. this.s.currentBatch.originalIndexes.push(this.s.currentIndex);
  8265. this.s.currentBatch.operations.push(document);
  8266. this.s.currentBatchSize += 1;
  8267. this.s.currentBatchSizeBytes += maxKeySize + bsonSize;
  8268. this.s.currentIndex += 1;
  8269. return this;
  8270. }
  8271. };
  8272. __name(_OrderedBulkOperation, "OrderedBulkOperation");
  8273. var OrderedBulkOperation = _OrderedBulkOperation;
  8274. exports2.OrderedBulkOperation = OrderedBulkOperation;
  8275. }
  8276. });
  8277. // node_modules/mongodb/lib/bulk/unordered.js
  8278. var require_unordered = __commonJS({
  8279. "node_modules/mongodb/lib/bulk/unordered.js"(exports2) {
  8280. "use strict";
  8281. Object.defineProperty(exports2, "__esModule", { value: true });
  8282. exports2.UnorderedBulkOperation = void 0;
  8283. var BSON = require_bson2();
  8284. var error_1 = require_error();
  8285. var common_1 = require_common2();
  8286. var _UnorderedBulkOperation = class _UnorderedBulkOperation extends common_1.BulkOperationBase {
  8287. /** @internal */
  8288. constructor(collection, options) {
  8289. super(collection, options, false);
  8290. }
  8291. handleWriteError(callback, writeResult) {
  8292. if (this.s.batches.length) {
  8293. return false;
  8294. }
  8295. return super.handleWriteError(callback, writeResult);
  8296. }
  8297. addToOperationsList(batchType, document) {
  8298. const bsonSize = BSON.calculateObjectSize(document, {
  8299. checkKeys: false,
  8300. // Since we don't know what the user selected for BSON options here,
  8301. // err on the safe side, and check the size with ignoreUndefined: false.
  8302. ignoreUndefined: false
  8303. });
  8304. if (bsonSize >= this.s.maxBsonObjectSize) {
  8305. throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`);
  8306. }
  8307. this.s.currentBatch = void 0;
  8308. if (batchType === common_1.BatchType.INSERT) {
  8309. this.s.currentBatch = this.s.currentInsertBatch;
  8310. } else if (batchType === common_1.BatchType.UPDATE) {
  8311. this.s.currentBatch = this.s.currentUpdateBatch;
  8312. } else if (batchType === common_1.BatchType.DELETE) {
  8313. this.s.currentBatch = this.s.currentRemoveBatch;
  8314. }
  8315. const maxKeySize = this.s.maxKeySize;
  8316. if (this.s.currentBatch == null) {
  8317. this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex);
  8318. }
  8319. if (
  8320. // New batch if we exceed the max batch op size
  8321. this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,
  8322. // since we can't sent an empty batch
  8323. this.s.currentBatch.size > 0 && this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || // New batch if the new op does not have the same op type as the current batch
  8324. this.s.currentBatch.batchType !== batchType
  8325. ) {
  8326. this.s.batches.push(this.s.currentBatch);
  8327. this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex);
  8328. }
  8329. if (Array.isArray(document)) {
  8330. throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array");
  8331. }
  8332. this.s.currentBatch.operations.push(document);
  8333. this.s.currentBatch.originalIndexes.push(this.s.currentIndex);
  8334. this.s.currentIndex = this.s.currentIndex + 1;
  8335. if (batchType === common_1.BatchType.INSERT) {
  8336. this.s.currentInsertBatch = this.s.currentBatch;
  8337. this.s.bulkResult.insertedIds.push({
  8338. index: this.s.bulkResult.insertedIds.length,
  8339. _id: document._id
  8340. });
  8341. } else if (batchType === common_1.BatchType.UPDATE) {
  8342. this.s.currentUpdateBatch = this.s.currentBatch;
  8343. } else if (batchType === common_1.BatchType.DELETE) {
  8344. this.s.currentRemoveBatch = this.s.currentBatch;
  8345. }
  8346. this.s.currentBatch.size += 1;
  8347. this.s.currentBatch.sizeBytes += maxKeySize + bsonSize;
  8348. return this;
  8349. }
  8350. };
  8351. __name(_UnorderedBulkOperation, "UnorderedBulkOperation");
  8352. var UnorderedBulkOperation = _UnorderedBulkOperation;
  8353. exports2.UnorderedBulkOperation = UnorderedBulkOperation;
  8354. }
  8355. });
  8356. // node_modules/mongodb/lib/operations/aggregate.js
  8357. var require_aggregate = __commonJS({
  8358. "node_modules/mongodb/lib/operations/aggregate.js"(exports2) {
  8359. "use strict";
  8360. Object.defineProperty(exports2, "__esModule", { value: true });
  8361. exports2.AggregateOperation = exports2.DB_AGGREGATE_COLLECTION = void 0;
  8362. var error_1 = require_error();
  8363. var utils_1 = require_utils();
  8364. var write_concern_1 = require_write_concern();
  8365. var command_1 = require_command();
  8366. var operation_1 = require_operation();
  8367. exports2.DB_AGGREGATE_COLLECTION = 1;
  8368. var MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8;
  8369. var _AggregateOperation = class _AggregateOperation extends command_1.CommandCallbackOperation {
  8370. constructor(ns, pipeline, options) {
  8371. super(void 0, { ...options, dbName: ns.db });
  8372. this.options = { ...options };
  8373. this.target = ns.collection || exports2.DB_AGGREGATE_COLLECTION;
  8374. this.pipeline = pipeline;
  8375. this.hasWriteStage = false;
  8376. if (typeof (options == null ? void 0 : options.out) === "string") {
  8377. this.pipeline = this.pipeline.concat({ $out: options.out });
  8378. this.hasWriteStage = true;
  8379. } else if (pipeline.length > 0) {
  8380. const finalStage = pipeline[pipeline.length - 1];
  8381. if (finalStage.$out || finalStage.$merge) {
  8382. this.hasWriteStage = true;
  8383. }
  8384. }
  8385. if (this.hasWriteStage) {
  8386. this.trySecondaryWrite = true;
  8387. } else {
  8388. delete this.options.writeConcern;
  8389. }
  8390. if (this.explain && this.writeConcern) {
  8391. throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern');
  8392. }
  8393. if ((options == null ? void 0 : options.cursor) != null && typeof options.cursor !== "object") {
  8394. throw new error_1.MongoInvalidArgumentError("Cursor options must be an object");
  8395. }
  8396. }
  8397. get canRetryRead() {
  8398. return !this.hasWriteStage;
  8399. }
  8400. addToPipeline(stage) {
  8401. this.pipeline.push(stage);
  8402. }
  8403. executeCallback(server, session, callback) {
  8404. const options = this.options;
  8405. const serverWireVersion = (0, utils_1.maxWireVersion)(server);
  8406. const command = { aggregate: this.target, pipeline: this.pipeline };
  8407. if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) {
  8408. this.readConcern = void 0;
  8409. }
  8410. if (this.hasWriteStage && this.writeConcern) {
  8411. write_concern_1.WriteConcern.apply(command, this.writeConcern);
  8412. }
  8413. if (options.bypassDocumentValidation === true) {
  8414. command.bypassDocumentValidation = options.bypassDocumentValidation;
  8415. }
  8416. if (typeof options.allowDiskUse === "boolean") {
  8417. command.allowDiskUse = options.allowDiskUse;
  8418. }
  8419. if (options.hint) {
  8420. command.hint = options.hint;
  8421. }
  8422. if (options.let) {
  8423. command.let = options.let;
  8424. }
  8425. if (options.comment !== void 0) {
  8426. command.comment = options.comment;
  8427. }
  8428. command.cursor = options.cursor || {};
  8429. if (options.batchSize && !this.hasWriteStage) {
  8430. command.cursor.batchSize = options.batchSize;
  8431. }
  8432. super.executeCommandCallback(server, session, command, callback);
  8433. }
  8434. };
  8435. __name(_AggregateOperation, "AggregateOperation");
  8436. var AggregateOperation = _AggregateOperation;
  8437. exports2.AggregateOperation = AggregateOperation;
  8438. (0, operation_1.defineAspects)(AggregateOperation, [
  8439. operation_1.Aspect.READ_OPERATION,
  8440. operation_1.Aspect.RETRYABLE,
  8441. operation_1.Aspect.EXPLAINABLE,
  8442. operation_1.Aspect.CURSOR_CREATING
  8443. ]);
  8444. }
  8445. });
  8446. // node_modules/mongodb/lib/mongo_types.js
  8447. var require_mongo_types = __commonJS({
  8448. "node_modules/mongodb/lib/mongo_types.js"(exports2) {
  8449. "use strict";
  8450. Object.defineProperty(exports2, "__esModule", { value: true });
  8451. exports2.CancellationToken = exports2.TypedEventEmitter = void 0;
  8452. var events_1 = require("events");
  8453. var _TypedEventEmitter = class _TypedEventEmitter extends events_1.EventEmitter {
  8454. /** @internal */
  8455. emitAndLog(event, ...args) {
  8456. var _a;
  8457. this.emit(event, ...args);
  8458. if (this.component)
  8459. (_a = this.mongoLogger) == null ? void 0 : _a.debug(this.component, args[0]);
  8460. }
  8461. };
  8462. __name(_TypedEventEmitter, "TypedEventEmitter");
  8463. var TypedEventEmitter = _TypedEventEmitter;
  8464. exports2.TypedEventEmitter = TypedEventEmitter;
  8465. var _CancellationToken = class _CancellationToken extends TypedEventEmitter {
  8466. };
  8467. __name(_CancellationToken, "CancellationToken");
  8468. var CancellationToken = _CancellationToken;
  8469. exports2.CancellationToken = CancellationToken;
  8470. }
  8471. });
  8472. // node_modules/mongodb/lib/operations/get_more.js
  8473. var require_get_more = __commonJS({
  8474. "node_modules/mongodb/lib/operations/get_more.js"(exports2) {
  8475. "use strict";
  8476. Object.defineProperty(exports2, "__esModule", { value: true });
  8477. exports2.GetMoreOperation = void 0;
  8478. var error_1 = require_error();
  8479. var utils_1 = require_utils();
  8480. var operation_1 = require_operation();
  8481. var _GetMoreOperation = class _GetMoreOperation extends operation_1.AbstractCallbackOperation {
  8482. constructor(ns, cursorId, server, options) {
  8483. super(options);
  8484. this.options = options;
  8485. this.ns = ns;
  8486. this.cursorId = cursorId;
  8487. this.server = server;
  8488. }
  8489. /**
  8490. * Although there is a server already associated with the get more operation, the signature
  8491. * for execute passes a server so we will just use that one.
  8492. */
  8493. executeCallback(server, session, callback) {
  8494. if (server !== this.server) {
  8495. return callback(new error_1.MongoRuntimeError("Getmore must run on the same server operation began on"));
  8496. }
  8497. if (this.cursorId == null || this.cursorId.isZero()) {
  8498. return callback(new error_1.MongoRuntimeError("Unable to iterate cursor with no id"));
  8499. }
  8500. const collection = this.ns.collection;
  8501. if (collection == null) {
  8502. return callback(new error_1.MongoRuntimeError("A collection name must be determined before getMore"));
  8503. }
  8504. const getMoreCmd = {
  8505. getMore: this.cursorId,
  8506. collection
  8507. };
  8508. if (typeof this.options.batchSize === "number") {
  8509. getMoreCmd.batchSize = Math.abs(this.options.batchSize);
  8510. }
  8511. if (typeof this.options.maxAwaitTimeMS === "number") {
  8512. getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS;
  8513. }
  8514. if (this.options.comment !== void 0 && (0, utils_1.maxWireVersion)(server) >= 9) {
  8515. getMoreCmd.comment = this.options.comment;
  8516. }
  8517. const commandOptions = {
  8518. returnFieldSelector: null,
  8519. documentsReturnedIn: "nextBatch",
  8520. ...this.options
  8521. };
  8522. server.command(this.ns, getMoreCmd, commandOptions, callback);
  8523. }
  8524. };
  8525. __name(_GetMoreOperation, "GetMoreOperation");
  8526. var GetMoreOperation = _GetMoreOperation;
  8527. exports2.GetMoreOperation = GetMoreOperation;
  8528. (0, operation_1.defineAspects)(GetMoreOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.MUST_SELECT_SAME_SERVER]);
  8529. }
  8530. });
  8531. // node_modules/mongodb/lib/operations/kill_cursors.js
  8532. var require_kill_cursors = __commonJS({
  8533. "node_modules/mongodb/lib/operations/kill_cursors.js"(exports2) {
  8534. "use strict";
  8535. Object.defineProperty(exports2, "__esModule", { value: true });
  8536. exports2.KillCursorsOperation = void 0;
  8537. var error_1 = require_error();
  8538. var operation_1 = require_operation();
  8539. var _KillCursorsOperation = class _KillCursorsOperation extends operation_1.AbstractCallbackOperation {
  8540. constructor(cursorId, ns, server, options) {
  8541. super(options);
  8542. this.ns = ns;
  8543. this.cursorId = cursorId;
  8544. this.server = server;
  8545. }
  8546. executeCallback(server, session, callback) {
  8547. if (server !== this.server) {
  8548. return callback(new error_1.MongoRuntimeError("Killcursor must run on the same server operation began on"));
  8549. }
  8550. const killCursors = this.ns.collection;
  8551. if (killCursors == null) {
  8552. return callback(new error_1.MongoRuntimeError("A collection name must be determined before killCursors"));
  8553. }
  8554. const killCursorsCommand = {
  8555. killCursors,
  8556. cursors: [this.cursorId]
  8557. };
  8558. server.command(this.ns, killCursorsCommand, { session }, () => callback());
  8559. }
  8560. };
  8561. __name(_KillCursorsOperation, "KillCursorsOperation");
  8562. var KillCursorsOperation = _KillCursorsOperation;
  8563. exports2.KillCursorsOperation = KillCursorsOperation;
  8564. (0, operation_1.defineAspects)(KillCursorsOperation, [operation_1.Aspect.MUST_SELECT_SAME_SERVER]);
  8565. }
  8566. });
  8567. // node_modules/mongodb/lib/cmap/metrics.js
  8568. var require_metrics = __commonJS({
  8569. "node_modules/mongodb/lib/cmap/metrics.js"(exports2) {
  8570. "use strict";
  8571. Object.defineProperty(exports2, "__esModule", { value: true });
  8572. exports2.ConnectionPoolMetrics = void 0;
  8573. var _ConnectionPoolMetrics = class _ConnectionPoolMetrics {
  8574. constructor() {
  8575. this.txnConnections = 0;
  8576. this.cursorConnections = 0;
  8577. this.otherConnections = 0;
  8578. }
  8579. /**
  8580. * Mark a connection as pinned for a specific operation.
  8581. */
  8582. markPinned(pinType) {
  8583. if (pinType === _ConnectionPoolMetrics.TXN) {
  8584. this.txnConnections += 1;
  8585. } else if (pinType === _ConnectionPoolMetrics.CURSOR) {
  8586. this.cursorConnections += 1;
  8587. } else {
  8588. this.otherConnections += 1;
  8589. }
  8590. }
  8591. /**
  8592. * Unmark a connection as pinned for an operation.
  8593. */
  8594. markUnpinned(pinType) {
  8595. if (pinType === _ConnectionPoolMetrics.TXN) {
  8596. this.txnConnections -= 1;
  8597. } else if (pinType === _ConnectionPoolMetrics.CURSOR) {
  8598. this.cursorConnections -= 1;
  8599. } else {
  8600. this.otherConnections -= 1;
  8601. }
  8602. }
  8603. /**
  8604. * Return information about the cmap metrics as a string.
  8605. */
  8606. info(maxPoolSize) {
  8607. return `Timed out while checking out a connection from connection pool: maxPoolSize: ${maxPoolSize}, connections in use by cursors: ${this.cursorConnections}, connections in use by transactions: ${this.txnConnections}, connections in use by other operations: ${this.otherConnections}`;
  8608. }
  8609. /**
  8610. * Reset the metrics to the initial values.
  8611. */
  8612. reset() {
  8613. this.txnConnections = 0;
  8614. this.cursorConnections = 0;
  8615. this.otherConnections = 0;
  8616. }
  8617. };
  8618. __name(_ConnectionPoolMetrics, "ConnectionPoolMetrics");
  8619. var ConnectionPoolMetrics = _ConnectionPoolMetrics;
  8620. ConnectionPoolMetrics.TXN = "txn";
  8621. ConnectionPoolMetrics.CURSOR = "cursor";
  8622. ConnectionPoolMetrics.OTHER = "other";
  8623. exports2.ConnectionPoolMetrics = ConnectionPoolMetrics;
  8624. }
  8625. });
  8626. // node_modules/mongodb/lib/sdam/server_description.js
  8627. var require_server_description = __commonJS({
  8628. "node_modules/mongodb/lib/sdam/server_description.js"(exports2) {
  8629. "use strict";
  8630. Object.defineProperty(exports2, "__esModule", { value: true });
  8631. exports2.compareTopologyVersion = exports2.parseServerType = exports2.ServerDescription = void 0;
  8632. var bson_1 = require_bson2();
  8633. var error_1 = require_error();
  8634. var utils_1 = require_utils();
  8635. var common_1 = require_common();
  8636. var WRITABLE_SERVER_TYPES = /* @__PURE__ */ new Set([
  8637. common_1.ServerType.RSPrimary,
  8638. common_1.ServerType.Standalone,
  8639. common_1.ServerType.Mongos,
  8640. common_1.ServerType.LoadBalancer
  8641. ]);
  8642. var DATA_BEARING_SERVER_TYPES = /* @__PURE__ */ new Set([
  8643. common_1.ServerType.RSPrimary,
  8644. common_1.ServerType.RSSecondary,
  8645. common_1.ServerType.Mongos,
  8646. common_1.ServerType.Standalone,
  8647. common_1.ServerType.LoadBalancer
  8648. ]);
  8649. var _ServerDescription = class _ServerDescription {
  8650. /**
  8651. * Create a ServerDescription
  8652. * @internal
  8653. *
  8654. * @param address - The address of the server
  8655. * @param hello - An optional hello response for this server
  8656. */
  8657. constructor(address, hello, options = {}) {
  8658. var _a, _b, _c, _d, _e, _f;
  8659. if (address == null || address === "") {
  8660. throw new error_1.MongoRuntimeError("ServerDescription must be provided with a non-empty address");
  8661. }
  8662. this.address = typeof address === "string" ? utils_1.HostAddress.fromString(address).toString() : address.toString();
  8663. this.type = parseServerType(hello, options);
  8664. this.hosts = ((_a = hello == null ? void 0 : hello.hosts) == null ? void 0 : _a.map((host) => host.toLowerCase())) ?? [];
  8665. this.passives = ((_b = hello == null ? void 0 : hello.passives) == null ? void 0 : _b.map((host) => host.toLowerCase())) ?? [];
  8666. this.arbiters = ((_c = hello == null ? void 0 : hello.arbiters) == null ? void 0 : _c.map((host) => host.toLowerCase())) ?? [];
  8667. this.tags = (hello == null ? void 0 : hello.tags) ?? {};
  8668. this.minWireVersion = (hello == null ? void 0 : hello.minWireVersion) ?? 0;
  8669. this.maxWireVersion = (hello == null ? void 0 : hello.maxWireVersion) ?? 0;
  8670. this.roundTripTime = (options == null ? void 0 : options.roundTripTime) ?? -1;
  8671. this.lastUpdateTime = (0, utils_1.now)();
  8672. this.lastWriteDate = ((_d = hello == null ? void 0 : hello.lastWrite) == null ? void 0 : _d.lastWriteDate) ?? 0;
  8673. this.error = options.error ?? null;
  8674. this.topologyVersion = ((_e = this.error) == null ? void 0 : _e.topologyVersion) ?? (hello == null ? void 0 : hello.topologyVersion) ?? null;
  8675. this.setName = (hello == null ? void 0 : hello.setName) ?? null;
  8676. this.setVersion = (hello == null ? void 0 : hello.setVersion) ?? null;
  8677. this.electionId = (hello == null ? void 0 : hello.electionId) ?? null;
  8678. this.logicalSessionTimeoutMinutes = (hello == null ? void 0 : hello.logicalSessionTimeoutMinutes) ?? null;
  8679. this.primary = (hello == null ? void 0 : hello.primary) ?? null;
  8680. this.me = ((_f = hello == null ? void 0 : hello.me) == null ? void 0 : _f.toLowerCase()) ?? null;
  8681. this.$clusterTime = (hello == null ? void 0 : hello.$clusterTime) ?? null;
  8682. }
  8683. get hostAddress() {
  8684. return utils_1.HostAddress.fromString(this.address);
  8685. }
  8686. get allHosts() {
  8687. return this.hosts.concat(this.arbiters).concat(this.passives);
  8688. }
  8689. /** Is this server available for reads*/
  8690. get isReadable() {
  8691. return this.type === common_1.ServerType.RSSecondary || this.isWritable;
  8692. }
  8693. /** Is this server data bearing */
  8694. get isDataBearing() {
  8695. return DATA_BEARING_SERVER_TYPES.has(this.type);
  8696. }
  8697. /** Is this server available for writes */
  8698. get isWritable() {
  8699. return WRITABLE_SERVER_TYPES.has(this.type);
  8700. }
  8701. get host() {
  8702. const chopLength = `:${this.port}`.length;
  8703. return this.address.slice(0, -chopLength);
  8704. }
  8705. get port() {
  8706. const port = this.address.split(":").pop();
  8707. return port ? Number.parseInt(port, 10) : 27017;
  8708. }
  8709. /**
  8710. * Determines if another `ServerDescription` is equal to this one per the rules defined
  8711. * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec}
  8712. */
  8713. equals(other) {
  8714. const topologyVersionsEqual = this.topologyVersion === (other == null ? void 0 : other.topologyVersion) || compareTopologyVersion(this.topologyVersion, other == null ? void 0 : other.topologyVersion) === 0;
  8715. const electionIdsEqual = this.electionId != null && (other == null ? void 0 : other.electionId) != null ? (0, utils_1.compareObjectId)(this.electionId, other.electionId) === 0 : this.electionId === (other == null ? void 0 : other.electionId);
  8716. return other != null && (0, utils_1.errorStrictEqual)(this.error, other.error) && this.type === other.type && this.minWireVersion === other.minWireVersion && (0, utils_1.arrayStrictEqual)(this.hosts, other.hosts) && tagsStrictEqual(this.tags, other.tags) && this.setName === other.setName && this.setVersion === other.setVersion && electionIdsEqual && this.primary === other.primary && this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && topologyVersionsEqual;
  8717. }
  8718. };
  8719. __name(_ServerDescription, "ServerDescription");
  8720. var ServerDescription = _ServerDescription;
  8721. exports2.ServerDescription = ServerDescription;
  8722. function parseServerType(hello, options) {
  8723. if (options == null ? void 0 : options.loadBalanced) {
  8724. return common_1.ServerType.LoadBalancer;
  8725. }
  8726. if (!hello || !hello.ok) {
  8727. return common_1.ServerType.Unknown;
  8728. }
  8729. if (hello.isreplicaset) {
  8730. return common_1.ServerType.RSGhost;
  8731. }
  8732. if (hello.msg && hello.msg === "isdbgrid") {
  8733. return common_1.ServerType.Mongos;
  8734. }
  8735. if (hello.setName) {
  8736. if (hello.hidden) {
  8737. return common_1.ServerType.RSOther;
  8738. } else if (hello.isWritablePrimary) {
  8739. return common_1.ServerType.RSPrimary;
  8740. } else if (hello.secondary) {
  8741. return common_1.ServerType.RSSecondary;
  8742. } else if (hello.arbiterOnly) {
  8743. return common_1.ServerType.RSArbiter;
  8744. } else {
  8745. return common_1.ServerType.RSOther;
  8746. }
  8747. }
  8748. return common_1.ServerType.Standalone;
  8749. }
  8750. __name(parseServerType, "parseServerType");
  8751. exports2.parseServerType = parseServerType;
  8752. function tagsStrictEqual(tags, tags2) {
  8753. const tagsKeys = Object.keys(tags);
  8754. const tags2Keys = Object.keys(tags2);
  8755. return tagsKeys.length === tags2Keys.length && tagsKeys.every((key) => tags2[key] === tags[key]);
  8756. }
  8757. __name(tagsStrictEqual, "tagsStrictEqual");
  8758. function compareTopologyVersion(currentTv, newTv) {
  8759. if (currentTv == null || newTv == null) {
  8760. return -1;
  8761. }
  8762. if (!currentTv.processId.equals(newTv.processId)) {
  8763. return -1;
  8764. }
  8765. const currentCounter = bson_1.Long.isLong(currentTv.counter) ? currentTv.counter : bson_1.Long.fromNumber(currentTv.counter);
  8766. const newCounter = bson_1.Long.isLong(newTv.counter) ? newTv.counter : bson_1.Long.fromNumber(newTv.counter);
  8767. return currentCounter.compare(newCounter);
  8768. }
  8769. __name(compareTopologyVersion, "compareTopologyVersion");
  8770. exports2.compareTopologyVersion = compareTopologyVersion;
  8771. }
  8772. });
  8773. // node_modules/mongodb/lib/sdam/topology_description.js
  8774. var require_topology_description = __commonJS({
  8775. "node_modules/mongodb/lib/sdam/topology_description.js"(exports2) {
  8776. "use strict";
  8777. Object.defineProperty(exports2, "__esModule", { value: true });
  8778. exports2.TopologyDescription = void 0;
  8779. var WIRE_CONSTANTS = require_constants();
  8780. var error_1 = require_error();
  8781. var utils_1 = require_utils();
  8782. var common_1 = require_common();
  8783. var server_description_1 = require_server_description();
  8784. var MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;
  8785. var MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;
  8786. var MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;
  8787. var MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;
  8788. var MONGOS_OR_UNKNOWN = /* @__PURE__ */ new Set([common_1.ServerType.Mongos, common_1.ServerType.Unknown]);
  8789. var MONGOS_OR_STANDALONE = /* @__PURE__ */ new Set([common_1.ServerType.Mongos, common_1.ServerType.Standalone]);
  8790. var NON_PRIMARY_RS_MEMBERS = /* @__PURE__ */ new Set([
  8791. common_1.ServerType.RSSecondary,
  8792. common_1.ServerType.RSArbiter,
  8793. common_1.ServerType.RSOther
  8794. ]);
  8795. var _TopologyDescription = class _TopologyDescription {
  8796. /**
  8797. * Create a TopologyDescription
  8798. */
  8799. constructor(topologyType, serverDescriptions = null, setName = null, maxSetVersion = null, maxElectionId = null, commonWireVersion = null, options = null) {
  8800. options = options ?? {};
  8801. this.type = topologyType ?? common_1.TopologyType.Unknown;
  8802. this.servers = serverDescriptions ?? /* @__PURE__ */ new Map();
  8803. this.stale = false;
  8804. this.compatible = true;
  8805. this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0;
  8806. this.localThresholdMS = options.localThresholdMS ?? 15;
  8807. this.setName = setName ?? null;
  8808. this.maxElectionId = maxElectionId ?? null;
  8809. this.maxSetVersion = maxSetVersion ?? null;
  8810. this.commonWireVersion = commonWireVersion ?? 0;
  8811. for (const serverDescription of this.servers.values()) {
  8812. if (serverDescription.type === common_1.ServerType.Unknown || serverDescription.type === common_1.ServerType.LoadBalancer) {
  8813. continue;
  8814. }
  8815. if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) {
  8816. this.compatible = false;
  8817. this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`;
  8818. }
  8819. if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) {
  8820. this.compatible = false;
  8821. this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`;
  8822. break;
  8823. }
  8824. }
  8825. this.logicalSessionTimeoutMinutes = null;
  8826. for (const [, server] of this.servers) {
  8827. if (server.isReadable) {
  8828. if (server.logicalSessionTimeoutMinutes == null) {
  8829. this.logicalSessionTimeoutMinutes = null;
  8830. break;
  8831. }
  8832. if (this.logicalSessionTimeoutMinutes == null) {
  8833. this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes;
  8834. continue;
  8835. }
  8836. this.logicalSessionTimeoutMinutes = Math.min(this.logicalSessionTimeoutMinutes, server.logicalSessionTimeoutMinutes);
  8837. }
  8838. }
  8839. }
  8840. /**
  8841. * Returns a new TopologyDescription based on the SrvPollingEvent
  8842. * @internal
  8843. */
  8844. updateFromSrvPollingEvent(ev, srvMaxHosts = 0) {
  8845. const incomingHostnames = ev.hostnames();
  8846. const currentHostnames = new Set(this.servers.keys());
  8847. const hostnamesToAdd = new Set(incomingHostnames);
  8848. const hostnamesToRemove = /* @__PURE__ */ new Set();
  8849. for (const hostname of currentHostnames) {
  8850. hostnamesToAdd.delete(hostname);
  8851. if (!incomingHostnames.has(hostname)) {
  8852. hostnamesToRemove.add(hostname);
  8853. }
  8854. }
  8855. if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) {
  8856. return this;
  8857. }
  8858. const serverDescriptions = new Map(this.servers);
  8859. for (const removedHost of hostnamesToRemove) {
  8860. serverDescriptions.delete(removedHost);
  8861. }
  8862. if (hostnamesToAdd.size > 0) {
  8863. if (srvMaxHosts === 0) {
  8864. for (const hostToAdd of hostnamesToAdd) {
  8865. serverDescriptions.set(hostToAdd, new server_description_1.ServerDescription(hostToAdd));
  8866. }
  8867. } else if (serverDescriptions.size < srvMaxHosts) {
  8868. const selectedHosts = (0, utils_1.shuffle)(hostnamesToAdd, srvMaxHosts - serverDescriptions.size);
  8869. for (const selectedHostToAdd of selectedHosts) {
  8870. serverDescriptions.set(selectedHostToAdd, new server_description_1.ServerDescription(selectedHostToAdd));
  8871. }
  8872. }
  8873. }
  8874. return new _TopologyDescription(this.type, serverDescriptions, this.setName, this.maxSetVersion, this.maxElectionId, this.commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
  8875. }
  8876. /**
  8877. * Returns a copy of this description updated with a given ServerDescription
  8878. * @internal
  8879. */
  8880. update(serverDescription) {
  8881. const address = serverDescription.address;
  8882. let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this;
  8883. const serverType = serverDescription.type;
  8884. const serverDescriptions = new Map(this.servers);
  8885. if (serverDescription.maxWireVersion !== 0) {
  8886. if (commonWireVersion == null) {
  8887. commonWireVersion = serverDescription.maxWireVersion;
  8888. } else {
  8889. commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion);
  8890. }
  8891. }
  8892. if (typeof serverDescription.setName === "string" && typeof setName === "string" && serverDescription.setName !== setName) {
  8893. if (topologyType === common_1.TopologyType.Single) {
  8894. serverDescription = new server_description_1.ServerDescription(address);
  8895. } else {
  8896. serverDescriptions.delete(address);
  8897. }
  8898. }
  8899. serverDescriptions.set(address, serverDescription);
  8900. if (topologyType === common_1.TopologyType.Single) {
  8901. return new _TopologyDescription(common_1.TopologyType.Single, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
  8902. }
  8903. if (topologyType === common_1.TopologyType.Unknown) {
  8904. if (serverType === common_1.ServerType.Standalone && this.servers.size !== 1) {
  8905. serverDescriptions.delete(address);
  8906. } else {
  8907. topologyType = topologyTypeForServerType(serverType);
  8908. }
  8909. }
  8910. if (topologyType === common_1.TopologyType.Sharded) {
  8911. if (!MONGOS_OR_UNKNOWN.has(serverType)) {
  8912. serverDescriptions.delete(address);
  8913. }
  8914. }
  8915. if (topologyType === common_1.TopologyType.ReplicaSetNoPrimary) {
  8916. if (MONGOS_OR_STANDALONE.has(serverType)) {
  8917. serverDescriptions.delete(address);
  8918. }
  8919. if (serverType === common_1.ServerType.RSPrimary) {
  8920. const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId);
  8921. topologyType = result[0];
  8922. setName = result[1];
  8923. maxSetVersion = result[2];
  8924. maxElectionId = result[3];
  8925. } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) {
  8926. const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName);
  8927. topologyType = result[0];
  8928. setName = result[1];
  8929. }
  8930. }
  8931. if (topologyType === common_1.TopologyType.ReplicaSetWithPrimary) {
  8932. if (MONGOS_OR_STANDALONE.has(serverType)) {
  8933. serverDescriptions.delete(address);
  8934. topologyType = checkHasPrimary(serverDescriptions);
  8935. } else if (serverType === common_1.ServerType.RSPrimary) {
  8936. const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId);
  8937. topologyType = result[0];
  8938. setName = result[1];
  8939. maxSetVersion = result[2];
  8940. maxElectionId = result[3];
  8941. } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) {
  8942. topologyType = updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName);
  8943. } else {
  8944. topologyType = checkHasPrimary(serverDescriptions);
  8945. }
  8946. }
  8947. return new _TopologyDescription(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
  8948. }
  8949. get error() {
  8950. const descriptionsWithError = Array.from(this.servers.values()).filter((sd) => sd.error);
  8951. if (descriptionsWithError.length > 0) {
  8952. return descriptionsWithError[0].error;
  8953. }
  8954. return null;
  8955. }
  8956. /**
  8957. * Determines if the topology description has any known servers
  8958. */
  8959. get hasKnownServers() {
  8960. return Array.from(this.servers.values()).some((sd) => sd.type !== common_1.ServerType.Unknown);
  8961. }
  8962. /**
  8963. * Determines if this topology description has a data-bearing server available.
  8964. */
  8965. get hasDataBearingServers() {
  8966. return Array.from(this.servers.values()).some((sd) => sd.isDataBearing);
  8967. }
  8968. /**
  8969. * Determines if the topology has a definition for the provided address
  8970. * @internal
  8971. */
  8972. hasServer(address) {
  8973. return this.servers.has(address);
  8974. }
  8975. };
  8976. __name(_TopologyDescription, "TopologyDescription");
  8977. var TopologyDescription = _TopologyDescription;
  8978. exports2.TopologyDescription = TopologyDescription;
  8979. function topologyTypeForServerType(serverType) {
  8980. switch (serverType) {
  8981. case common_1.ServerType.Standalone:
  8982. return common_1.TopologyType.Single;
  8983. case common_1.ServerType.Mongos:
  8984. return common_1.TopologyType.Sharded;
  8985. case common_1.ServerType.RSPrimary:
  8986. return common_1.TopologyType.ReplicaSetWithPrimary;
  8987. case common_1.ServerType.RSOther:
  8988. case common_1.ServerType.RSSecondary:
  8989. return common_1.TopologyType.ReplicaSetNoPrimary;
  8990. default:
  8991. return common_1.TopologyType.Unknown;
  8992. }
  8993. }
  8994. __name(topologyTypeForServerType, "topologyTypeForServerType");
  8995. function updateRsFromPrimary(serverDescriptions, serverDescription, setName = null, maxSetVersion = null, maxElectionId = null) {
  8996. setName = setName || serverDescription.setName;
  8997. if (setName !== serverDescription.setName) {
  8998. serverDescriptions.delete(serverDescription.address);
  8999. return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  9000. }
  9001. if (serverDescription.maxWireVersion >= 17) {
  9002. const electionIdComparison = (0, utils_1.compareObjectId)(maxElectionId, serverDescription.electionId);
  9003. const maxElectionIdIsEqual = electionIdComparison === 0;
  9004. const maxElectionIdIsLess = electionIdComparison === -1;
  9005. const maxSetVersionIsLessOrEqual = (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1);
  9006. if (maxElectionIdIsLess || maxElectionIdIsEqual && maxSetVersionIsLessOrEqual) {
  9007. maxElectionId = serverDescription.electionId;
  9008. maxSetVersion = serverDescription.setVersion;
  9009. } else {
  9010. serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address));
  9011. return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  9012. }
  9013. } else {
  9014. const electionId = serverDescription.electionId ? serverDescription.electionId : null;
  9015. if (serverDescription.setVersion && electionId) {
  9016. if (maxSetVersion && maxElectionId) {
  9017. if (maxSetVersion > serverDescription.setVersion || (0, utils_1.compareObjectId)(maxElectionId, electionId) > 0) {
  9018. serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address));
  9019. return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  9020. }
  9021. }
  9022. maxElectionId = serverDescription.electionId;
  9023. }
  9024. if (serverDescription.setVersion != null && (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)) {
  9025. maxSetVersion = serverDescription.setVersion;
  9026. }
  9027. }
  9028. for (const [address, server] of serverDescriptions) {
  9029. if (server.type === common_1.ServerType.RSPrimary && server.address !== serverDescription.address) {
  9030. serverDescriptions.set(address, new server_description_1.ServerDescription(server.address));
  9031. break;
  9032. }
  9033. }
  9034. serverDescription.allHosts.forEach((address) => {
  9035. if (!serverDescriptions.has(address)) {
  9036. serverDescriptions.set(address, new server_description_1.ServerDescription(address));
  9037. }
  9038. });
  9039. const currentAddresses = Array.from(serverDescriptions.keys());
  9040. const responseAddresses = serverDescription.allHosts;
  9041. currentAddresses.filter((addr) => responseAddresses.indexOf(addr) === -1).forEach((address) => {
  9042. serverDescriptions.delete(address);
  9043. });
  9044. return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  9045. }
  9046. __name(updateRsFromPrimary, "updateRsFromPrimary");
  9047. function updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName = null) {
  9048. if (setName == null) {
  9049. throw new error_1.MongoRuntimeError('Argument "setName" is required if connected to a replica set');
  9050. }
  9051. if (setName !== serverDescription.setName || serverDescription.me && serverDescription.address !== serverDescription.me) {
  9052. serverDescriptions.delete(serverDescription.address);
  9053. }
  9054. return checkHasPrimary(serverDescriptions);
  9055. }
  9056. __name(updateRsWithPrimaryFromMember, "updateRsWithPrimaryFromMember");
  9057. function updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName = null) {
  9058. const topologyType = common_1.TopologyType.ReplicaSetNoPrimary;
  9059. setName = setName ?? serverDescription.setName;
  9060. if (setName !== serverDescription.setName) {
  9061. serverDescriptions.delete(serverDescription.address);
  9062. return [topologyType, setName];
  9063. }
  9064. serverDescription.allHosts.forEach((address) => {
  9065. if (!serverDescriptions.has(address)) {
  9066. serverDescriptions.set(address, new server_description_1.ServerDescription(address));
  9067. }
  9068. });
  9069. if (serverDescription.me && serverDescription.address !== serverDescription.me) {
  9070. serverDescriptions.delete(serverDescription.address);
  9071. }
  9072. return [topologyType, setName];
  9073. }
  9074. __name(updateRsNoPrimaryFromMember, "updateRsNoPrimaryFromMember");
  9075. function checkHasPrimary(serverDescriptions) {
  9076. for (const serverDescription of serverDescriptions.values()) {
  9077. if (serverDescription.type === common_1.ServerType.RSPrimary) {
  9078. return common_1.TopologyType.ReplicaSetWithPrimary;
  9079. }
  9080. }
  9081. return common_1.TopologyType.ReplicaSetNoPrimary;
  9082. }
  9083. __name(checkHasPrimary, "checkHasPrimary");
  9084. }
  9085. });
  9086. // node_modules/mongodb/lib/cmap/wire_protocol/shared.js
  9087. var require_shared = __commonJS({
  9088. "node_modules/mongodb/lib/cmap/wire_protocol/shared.js"(exports2) {
  9089. "use strict";
  9090. Object.defineProperty(exports2, "__esModule", { value: true });
  9091. exports2.isSharded = exports2.getReadPreference = void 0;
  9092. var error_1 = require_error();
  9093. var read_preference_1 = require_read_preference();
  9094. var common_1 = require_common();
  9095. var topology_description_1 = require_topology_description();
  9096. function getReadPreference(options) {
  9097. let readPreference = (options == null ? void 0 : options.readPreference) ?? read_preference_1.ReadPreference.primary;
  9098. if (options == null ? void 0 : options.readPreference) {
  9099. readPreference = options.readPreference;
  9100. }
  9101. if (typeof readPreference === "string") {
  9102. readPreference = read_preference_1.ReadPreference.fromString(readPreference);
  9103. }
  9104. if (!(readPreference instanceof read_preference_1.ReadPreference)) {
  9105. throw new error_1.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance');
  9106. }
  9107. return readPreference;
  9108. }
  9109. __name(getReadPreference, "getReadPreference");
  9110. exports2.getReadPreference = getReadPreference;
  9111. function isSharded(topologyOrServer) {
  9112. if (topologyOrServer == null) {
  9113. return false;
  9114. }
  9115. if (topologyOrServer.description && topologyOrServer.description.type === common_1.ServerType.Mongos) {
  9116. return true;
  9117. }
  9118. if (topologyOrServer.description && topologyOrServer.description instanceof topology_description_1.TopologyDescription) {
  9119. const servers = Array.from(topologyOrServer.description.servers.values());
  9120. return servers.some((server) => server.type === common_1.ServerType.Mongos);
  9121. }
  9122. return false;
  9123. }
  9124. __name(isSharded, "isSharded");
  9125. exports2.isSharded = isSharded;
  9126. }
  9127. });
  9128. // node_modules/mongodb/lib/transactions.js
  9129. var require_transactions = __commonJS({
  9130. "node_modules/mongodb/lib/transactions.js"(exports2) {
  9131. "use strict";
  9132. Object.defineProperty(exports2, "__esModule", { value: true });
  9133. exports2.isTransactionCommand = exports2.Transaction = exports2.TxnState = void 0;
  9134. var error_1 = require_error();
  9135. var read_concern_1 = require_read_concern();
  9136. var read_preference_1 = require_read_preference();
  9137. var write_concern_1 = require_write_concern();
  9138. exports2.TxnState = Object.freeze({
  9139. NO_TRANSACTION: "NO_TRANSACTION",
  9140. STARTING_TRANSACTION: "STARTING_TRANSACTION",
  9141. TRANSACTION_IN_PROGRESS: "TRANSACTION_IN_PROGRESS",
  9142. TRANSACTION_COMMITTED: "TRANSACTION_COMMITTED",
  9143. TRANSACTION_COMMITTED_EMPTY: "TRANSACTION_COMMITTED_EMPTY",
  9144. TRANSACTION_ABORTED: "TRANSACTION_ABORTED"
  9145. });
  9146. var stateMachine = {
  9147. [exports2.TxnState.NO_TRANSACTION]: [exports2.TxnState.NO_TRANSACTION, exports2.TxnState.STARTING_TRANSACTION],
  9148. [exports2.TxnState.STARTING_TRANSACTION]: [
  9149. exports2.TxnState.TRANSACTION_IN_PROGRESS,
  9150. exports2.TxnState.TRANSACTION_COMMITTED,
  9151. exports2.TxnState.TRANSACTION_COMMITTED_EMPTY,
  9152. exports2.TxnState.TRANSACTION_ABORTED
  9153. ],
  9154. [exports2.TxnState.TRANSACTION_IN_PROGRESS]: [
  9155. exports2.TxnState.TRANSACTION_IN_PROGRESS,
  9156. exports2.TxnState.TRANSACTION_COMMITTED,
  9157. exports2.TxnState.TRANSACTION_ABORTED
  9158. ],
  9159. [exports2.TxnState.TRANSACTION_COMMITTED]: [
  9160. exports2.TxnState.TRANSACTION_COMMITTED,
  9161. exports2.TxnState.TRANSACTION_COMMITTED_EMPTY,
  9162. exports2.TxnState.STARTING_TRANSACTION,
  9163. exports2.TxnState.NO_TRANSACTION
  9164. ],
  9165. [exports2.TxnState.TRANSACTION_ABORTED]: [exports2.TxnState.STARTING_TRANSACTION, exports2.TxnState.NO_TRANSACTION],
  9166. [exports2.TxnState.TRANSACTION_COMMITTED_EMPTY]: [
  9167. exports2.TxnState.TRANSACTION_COMMITTED_EMPTY,
  9168. exports2.TxnState.NO_TRANSACTION
  9169. ]
  9170. };
  9171. var ACTIVE_STATES = /* @__PURE__ */ new Set([
  9172. exports2.TxnState.STARTING_TRANSACTION,
  9173. exports2.TxnState.TRANSACTION_IN_PROGRESS
  9174. ]);
  9175. var COMMITTED_STATES = /* @__PURE__ */ new Set([
  9176. exports2.TxnState.TRANSACTION_COMMITTED,
  9177. exports2.TxnState.TRANSACTION_COMMITTED_EMPTY,
  9178. exports2.TxnState.TRANSACTION_ABORTED
  9179. ]);
  9180. var _Transaction = class _Transaction {
  9181. /** Create a transaction @internal */
  9182. constructor(options) {
  9183. options = options ?? {};
  9184. this.state = exports2.TxnState.NO_TRANSACTION;
  9185. this.options = {};
  9186. const writeConcern = write_concern_1.WriteConcern.fromOptions(options);
  9187. if (writeConcern) {
  9188. if (writeConcern.w === 0) {
  9189. throw new error_1.MongoTransactionError("Transactions do not support unacknowledged write concern");
  9190. }
  9191. this.options.writeConcern = writeConcern;
  9192. }
  9193. if (options.readConcern) {
  9194. this.options.readConcern = read_concern_1.ReadConcern.fromOptions(options);
  9195. }
  9196. if (options.readPreference) {
  9197. this.options.readPreference = read_preference_1.ReadPreference.fromOptions(options);
  9198. }
  9199. if (options.maxCommitTimeMS) {
  9200. this.options.maxTimeMS = options.maxCommitTimeMS;
  9201. }
  9202. this._pinnedServer = void 0;
  9203. this._recoveryToken = void 0;
  9204. }
  9205. /** @internal */
  9206. get server() {
  9207. return this._pinnedServer;
  9208. }
  9209. get recoveryToken() {
  9210. return this._recoveryToken;
  9211. }
  9212. get isPinned() {
  9213. return !!this.server;
  9214. }
  9215. /** @returns Whether the transaction has started */
  9216. get isStarting() {
  9217. return this.state === exports2.TxnState.STARTING_TRANSACTION;
  9218. }
  9219. /**
  9220. * @returns Whether this session is presently in a transaction
  9221. */
  9222. get isActive() {
  9223. return ACTIVE_STATES.has(this.state);
  9224. }
  9225. get isCommitted() {
  9226. return COMMITTED_STATES.has(this.state);
  9227. }
  9228. /**
  9229. * Transition the transaction in the state machine
  9230. * @internal
  9231. * @param nextState - The new state to transition to
  9232. */
  9233. transition(nextState) {
  9234. const nextStates = stateMachine[this.state];
  9235. if (nextStates && nextStates.includes(nextState)) {
  9236. this.state = nextState;
  9237. if (this.state === exports2.TxnState.NO_TRANSACTION || this.state === exports2.TxnState.STARTING_TRANSACTION || this.state === exports2.TxnState.TRANSACTION_ABORTED) {
  9238. this.unpinServer();
  9239. }
  9240. return;
  9241. }
  9242. throw new error_1.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${nextState}]`);
  9243. }
  9244. /** @internal */
  9245. pinServer(server) {
  9246. if (this.isActive) {
  9247. this._pinnedServer = server;
  9248. }
  9249. }
  9250. /** @internal */
  9251. unpinServer() {
  9252. this._pinnedServer = void 0;
  9253. }
  9254. };
  9255. __name(_Transaction, "Transaction");
  9256. var Transaction = _Transaction;
  9257. exports2.Transaction = Transaction;
  9258. function isTransactionCommand(command) {
  9259. return !!(command.commitTransaction || command.abortTransaction);
  9260. }
  9261. __name(isTransactionCommand, "isTransactionCommand");
  9262. exports2.isTransactionCommand = isTransactionCommand;
  9263. }
  9264. });
  9265. // node_modules/mongodb/lib/sessions.js
  9266. var require_sessions = __commonJS({
  9267. "node_modules/mongodb/lib/sessions.js"(exports2) {
  9268. "use strict";
  9269. var _a;
  9270. Object.defineProperty(exports2, "__esModule", { value: true });
  9271. exports2.updateSessionFromResponse = exports2.applySession = exports2.ServerSessionPool = exports2.ServerSession = exports2.maybeClearPinnedConnection = exports2.ClientSession = void 0;
  9272. var util_1 = require("util");
  9273. var bson_1 = require_bson2();
  9274. var metrics_1 = require_metrics();
  9275. var shared_1 = require_shared();
  9276. var constants_1 = require_constants2();
  9277. var error_1 = require_error();
  9278. var mongo_types_1 = require_mongo_types();
  9279. var execute_operation_1 = require_execute_operation();
  9280. var run_command_1 = require_run_command();
  9281. var read_concern_1 = require_read_concern();
  9282. var read_preference_1 = require_read_preference();
  9283. var common_1 = require_common();
  9284. var transactions_1 = require_transactions();
  9285. var utils_1 = require_utils();
  9286. var write_concern_1 = require_write_concern();
  9287. var minWireVersionForShardedTransactions = 8;
  9288. var kServerSession = Symbol("serverSession");
  9289. var kSnapshotTime = Symbol("snapshotTime");
  9290. var kSnapshotEnabled = Symbol("snapshotEnabled");
  9291. var kPinnedConnection = Symbol("pinnedConnection");
  9292. var kTxnNumberIncrement = Symbol("txnNumberIncrement");
  9293. var _ClientSession = class _ClientSession extends mongo_types_1.TypedEventEmitter {
  9294. /**
  9295. * Create a client session.
  9296. * @internal
  9297. * @param client - The current client
  9298. * @param sessionPool - The server session pool (Internal Class)
  9299. * @param options - Optional settings
  9300. * @param clientOptions - Optional settings provided when creating a MongoClient
  9301. */
  9302. constructor(client, sessionPool, options, clientOptions) {
  9303. super();
  9304. this[_a] = false;
  9305. if (client == null) {
  9306. throw new error_1.MongoRuntimeError("ClientSession requires a MongoClient");
  9307. }
  9308. if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) {
  9309. throw new error_1.MongoRuntimeError("ClientSession requires a ServerSessionPool");
  9310. }
  9311. options = options ?? {};
  9312. if (options.snapshot === true) {
  9313. this[kSnapshotEnabled] = true;
  9314. if (options.causalConsistency === true) {
  9315. throw new error_1.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive');
  9316. }
  9317. }
  9318. this.client = client;
  9319. this.sessionPool = sessionPool;
  9320. this.hasEnded = false;
  9321. this.clientOptions = clientOptions;
  9322. this.explicit = !!options.explicit;
  9323. this[kServerSession] = this.explicit ? this.sessionPool.acquire() : null;
  9324. this[kTxnNumberIncrement] = 0;
  9325. const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true;
  9326. this.supports = {
  9327. // if we can enable causal consistency, do so by default
  9328. causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue
  9329. };
  9330. this.clusterTime = options.initialClusterTime;
  9331. this.operationTime = void 0;
  9332. this.owner = options.owner;
  9333. this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions);
  9334. this.transaction = new transactions_1.Transaction();
  9335. }
  9336. /** The server id associated with this session */
  9337. get id() {
  9338. var _a2;
  9339. return (_a2 = this[kServerSession]) == null ? void 0 : _a2.id;
  9340. }
  9341. get serverSession() {
  9342. let serverSession = this[kServerSession];
  9343. if (serverSession == null) {
  9344. if (this.explicit) {
  9345. throw new error_1.MongoRuntimeError("Unexpected null serverSession for an explicit session");
  9346. }
  9347. if (this.hasEnded) {
  9348. throw new error_1.MongoRuntimeError("Unexpected null serverSession for an ended implicit session");
  9349. }
  9350. serverSession = this.sessionPool.acquire();
  9351. this[kServerSession] = serverSession;
  9352. }
  9353. return serverSession;
  9354. }
  9355. /** Whether or not this session is configured for snapshot reads */
  9356. get snapshotEnabled() {
  9357. return this[kSnapshotEnabled];
  9358. }
  9359. get loadBalanced() {
  9360. var _a2;
  9361. return ((_a2 = this.client.topology) == null ? void 0 : _a2.description.type) === common_1.TopologyType.LoadBalanced;
  9362. }
  9363. /** @internal */
  9364. get pinnedConnection() {
  9365. return this[kPinnedConnection];
  9366. }
  9367. /** @internal */
  9368. pin(conn) {
  9369. if (this[kPinnedConnection]) {
  9370. throw TypeError("Cannot pin multiple connections to the same session");
  9371. }
  9372. this[kPinnedConnection] = conn;
  9373. conn.emit(constants_1.PINNED, this.inTransaction() ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR);
  9374. }
  9375. /** @internal */
  9376. unpin(options) {
  9377. if (this.loadBalanced) {
  9378. return maybeClearPinnedConnection(this, options);
  9379. }
  9380. this.transaction.unpinServer();
  9381. }
  9382. get isPinned() {
  9383. return this.loadBalanced ? !!this[kPinnedConnection] : this.transaction.isPinned;
  9384. }
  9385. /**
  9386. * Ends this session on the server
  9387. *
  9388. * @param options - Optional settings. Currently reserved for future use
  9389. */
  9390. async endSession(options) {
  9391. try {
  9392. if (this.inTransaction()) {
  9393. await this.abortTransaction();
  9394. }
  9395. if (!this.hasEnded) {
  9396. const serverSession = this[kServerSession];
  9397. if (serverSession != null) {
  9398. this.sessionPool.release(serverSession);
  9399. Object.defineProperty(this, kServerSession, {
  9400. value: ServerSession.clone(serverSession),
  9401. writable: false
  9402. });
  9403. }
  9404. this.hasEnded = true;
  9405. this.emit("ended", this);
  9406. }
  9407. } catch {
  9408. } finally {
  9409. maybeClearPinnedConnection(this, { force: true, ...options });
  9410. }
  9411. }
  9412. /**
  9413. * Advances the operationTime for a ClientSession.
  9414. *
  9415. * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to
  9416. */
  9417. advanceOperationTime(operationTime) {
  9418. if (this.operationTime == null) {
  9419. this.operationTime = operationTime;
  9420. return;
  9421. }
  9422. if (operationTime.greaterThan(this.operationTime)) {
  9423. this.operationTime = operationTime;
  9424. }
  9425. }
  9426. /**
  9427. * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession
  9428. *
  9429. * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature
  9430. */
  9431. advanceClusterTime(clusterTime) {
  9432. var _a2, _b;
  9433. if (!clusterTime || typeof clusterTime !== "object") {
  9434. throw new error_1.MongoInvalidArgumentError("input cluster time must be an object");
  9435. }
  9436. if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== "Timestamp") {
  9437. throw new error_1.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp');
  9438. }
  9439. if (!clusterTime.signature || ((_a2 = clusterTime.signature.hash) == null ? void 0 : _a2._bsontype) !== "Binary" || typeof clusterTime.signature.keyId !== "bigint" && typeof clusterTime.signature.keyId !== "number" && ((_b = clusterTime.signature.keyId) == null ? void 0 : _b._bsontype) !== "Long") {
  9440. throw new error_1.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId');
  9441. }
  9442. (0, common_1._advanceClusterTime)(this, clusterTime);
  9443. }
  9444. /**
  9445. * Used to determine if this session equals another
  9446. *
  9447. * @param session - The session to compare to
  9448. */
  9449. equals(session) {
  9450. if (!(session instanceof _ClientSession)) {
  9451. return false;
  9452. }
  9453. if (this.id == null || session.id == null) {
  9454. return false;
  9455. }
  9456. return utils_1.ByteUtils.equals(this.id.id.buffer, session.id.id.buffer);
  9457. }
  9458. /**
  9459. * Increment the transaction number on the internal ServerSession
  9460. *
  9461. * @privateRemarks
  9462. * This helper increments a value stored on the client session that will be
  9463. * added to the serverSession's txnNumber upon applying it to a command.
  9464. * This is because the serverSession is lazily acquired after a connection is obtained
  9465. */
  9466. incrementTransactionNumber() {
  9467. this[kTxnNumberIncrement] += 1;
  9468. }
  9469. /** @returns whether this session is currently in a transaction or not */
  9470. inTransaction() {
  9471. return this.transaction.isActive;
  9472. }
  9473. /**
  9474. * Starts a new transaction with the given options.
  9475. *
  9476. * @param options - Options for the transaction
  9477. */
  9478. startTransaction(options) {
  9479. var _a2, _b, _c;
  9480. if (this[kSnapshotEnabled]) {
  9481. throw new error_1.MongoCompatibilityError("Transactions are not supported in snapshot sessions");
  9482. }
  9483. if (this.inTransaction()) {
  9484. throw new error_1.MongoTransactionError("Transaction already in progress");
  9485. }
  9486. if (this.isPinned && this.transaction.isCommitted) {
  9487. this.unpin();
  9488. }
  9489. const topologyMaxWireVersion = (0, utils_1.maxWireVersion)(this.client.topology);
  9490. if ((0, shared_1.isSharded)(this.client.topology) && topologyMaxWireVersion != null && topologyMaxWireVersion < minWireVersionForShardedTransactions) {
  9491. throw new error_1.MongoCompatibilityError("Transactions are not supported on sharded clusters in MongoDB < 4.2.");
  9492. }
  9493. this.incrementTransactionNumber();
  9494. this.transaction = new transactions_1.Transaction({
  9495. readConcern: (options == null ? void 0 : options.readConcern) ?? this.defaultTransactionOptions.readConcern ?? ((_a2 = this.clientOptions) == null ? void 0 : _a2.readConcern),
  9496. writeConcern: (options == null ? void 0 : options.writeConcern) ?? this.defaultTransactionOptions.writeConcern ?? ((_b = this.clientOptions) == null ? void 0 : _b.writeConcern),
  9497. readPreference: (options == null ? void 0 : options.readPreference) ?? this.defaultTransactionOptions.readPreference ?? ((_c = this.clientOptions) == null ? void 0 : _c.readPreference),
  9498. maxCommitTimeMS: (options == null ? void 0 : options.maxCommitTimeMS) ?? this.defaultTransactionOptions.maxCommitTimeMS
  9499. });
  9500. this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION);
  9501. }
  9502. /**
  9503. * Commits the currently active transaction in this session.
  9504. */
  9505. async commitTransaction() {
  9506. return endTransactionAsync(this, "commitTransaction");
  9507. }
  9508. /**
  9509. * Aborts the currently active transaction in this session.
  9510. */
  9511. async abortTransaction() {
  9512. return endTransactionAsync(this, "abortTransaction");
  9513. }
  9514. /**
  9515. * This is here to ensure that ClientSession is never serialized to BSON.
  9516. */
  9517. toBSON() {
  9518. throw new error_1.MongoRuntimeError("ClientSession cannot be serialized to BSON.");
  9519. }
  9520. /**
  9521. * Runs a provided callback within a transaction, retrying either the commitTransaction operation
  9522. * or entire transaction as needed (and when the error permits) to better ensure that
  9523. * the transaction can complete successfully.
  9524. *
  9525. * **IMPORTANT:** This method requires the user to return a Promise, and `await` all operations.
  9526. * Any callbacks that do not return a Promise will result in undefined behavior.
  9527. *
  9528. * @remarks
  9529. * This function:
  9530. * - Will return the command response from the final commitTransaction if every operation is successful (can be used as a truthy object)
  9531. * - Will return `undefined` if the transaction is explicitly aborted with `await session.abortTransaction()`
  9532. * - Will throw if one of the operations throws or `throw` statement is used inside the `withTransaction` callback
  9533. *
  9534. * Checkout a descriptive example here:
  9535. * @see https://www.mongodb.com/developer/quickstart/node-transactions/
  9536. *
  9537. * @param fn - callback to run within a transaction
  9538. * @param options - optional settings for the transaction
  9539. * @returns A raw command response or undefined
  9540. */
  9541. async withTransaction(fn, options) {
  9542. const startTime = (0, utils_1.now)();
  9543. return attemptTransaction(this, startTime, fn, options);
  9544. }
  9545. };
  9546. __name(_ClientSession, "ClientSession");
  9547. var ClientSession = _ClientSession;
  9548. exports2.ClientSession = ClientSession;
  9549. _a = kSnapshotEnabled;
  9550. var MAX_WITH_TRANSACTION_TIMEOUT = 12e4;
  9551. var NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = /* @__PURE__ */ new Set([
  9552. "CannotSatisfyWriteConcern",
  9553. "UnknownReplWriteConcern",
  9554. "UnsatisfiableWriteConcern"
  9555. ]);
  9556. function hasNotTimedOut(startTime, max) {
  9557. return (0, utils_1.calculateDurationInMs)(startTime) < max;
  9558. }
  9559. __name(hasNotTimedOut, "hasNotTimedOut");
  9560. function isUnknownTransactionCommitResult(err) {
  9561. const isNonDeterministicWriteConcernError = err instanceof error_1.MongoServerError && err.codeName && NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName);
  9562. return isMaxTimeMSExpiredError(err) || !isNonDeterministicWriteConcernError && err.code !== error_1.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && err.code !== error_1.MONGODB_ERROR_CODES.UnknownReplWriteConcern;
  9563. }
  9564. __name(isUnknownTransactionCommitResult, "isUnknownTransactionCommitResult");
  9565. function maybeClearPinnedConnection(session, options) {
  9566. const conn = session[kPinnedConnection];
  9567. const error = options == null ? void 0 : options.error;
  9568. if (session.inTransaction() && error && error instanceof error_1.MongoError && error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  9569. return;
  9570. }
  9571. const topology = session.client.topology;
  9572. if (conn && topology != null) {
  9573. const servers = Array.from(topology.s.servers.values());
  9574. const loadBalancer = servers[0];
  9575. if ((options == null ? void 0 : options.error) == null || (options == null ? void 0 : options.force)) {
  9576. loadBalancer.pool.checkIn(conn);
  9577. conn.emit(constants_1.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR);
  9578. if (options == null ? void 0 : options.forceClear) {
  9579. loadBalancer.pool.clear({ serviceId: conn.serviceId });
  9580. }
  9581. }
  9582. session[kPinnedConnection] = void 0;
  9583. }
  9584. }
  9585. __name(maybeClearPinnedConnection, "maybeClearPinnedConnection");
  9586. exports2.maybeClearPinnedConnection = maybeClearPinnedConnection;
  9587. function isMaxTimeMSExpiredError(err) {
  9588. if (err == null || !(err instanceof error_1.MongoServerError)) {
  9589. return false;
  9590. }
  9591. return err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired || err.writeConcernError && err.writeConcernError.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired;
  9592. }
  9593. __name(isMaxTimeMSExpiredError, "isMaxTimeMSExpiredError");
  9594. function attemptTransactionCommit(session, startTime, fn, options) {
  9595. return session.commitTransaction().catch((err) => {
  9596. if (err instanceof error_1.MongoError && hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && !isMaxTimeMSExpiredError(err)) {
  9597. if (err.hasErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult)) {
  9598. return attemptTransactionCommit(session, startTime, fn, options);
  9599. }
  9600. if (err.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  9601. return attemptTransaction(session, startTime, fn, options);
  9602. }
  9603. }
  9604. throw err;
  9605. });
  9606. }
  9607. __name(attemptTransactionCommit, "attemptTransactionCommit");
  9608. var USER_EXPLICIT_TXN_END_STATES = /* @__PURE__ */ new Set([
  9609. transactions_1.TxnState.NO_TRANSACTION,
  9610. transactions_1.TxnState.TRANSACTION_COMMITTED,
  9611. transactions_1.TxnState.TRANSACTION_ABORTED
  9612. ]);
  9613. function userExplicitlyEndedTransaction(session) {
  9614. return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state);
  9615. }
  9616. __name(userExplicitlyEndedTransaction, "userExplicitlyEndedTransaction");
  9617. function attemptTransaction(session, startTime, fn, options) {
  9618. session.startTransaction(options);
  9619. let promise;
  9620. try {
  9621. promise = fn(session);
  9622. } catch (err) {
  9623. promise = Promise.reject(err);
  9624. }
  9625. if (!(0, utils_1.isPromiseLike)(promise)) {
  9626. session.abortTransaction().catch(() => null);
  9627. throw new error_1.MongoInvalidArgumentError("Function provided to `withTransaction` must return a Promise");
  9628. }
  9629. return promise.then(() => {
  9630. if (userExplicitlyEndedTransaction(session)) {
  9631. return;
  9632. }
  9633. return attemptTransactionCommit(session, startTime, fn, options);
  9634. }, (err) => {
  9635. function maybeRetryOrThrow(err2) {
  9636. if (err2 instanceof error_1.MongoError && err2.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) && hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)) {
  9637. return attemptTransaction(session, startTime, fn, options);
  9638. }
  9639. if (isMaxTimeMSExpiredError(err2)) {
  9640. err2.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
  9641. }
  9642. throw err2;
  9643. }
  9644. __name(maybeRetryOrThrow, "maybeRetryOrThrow");
  9645. if (session.inTransaction()) {
  9646. return session.abortTransaction().then(() => maybeRetryOrThrow(err));
  9647. }
  9648. return maybeRetryOrThrow(err);
  9649. });
  9650. }
  9651. __name(attemptTransaction, "attemptTransaction");
  9652. var endTransactionAsync = (0, util_1.promisify)(endTransaction);
  9653. function endTransaction(session, commandName, callback) {
  9654. const txnState = session.transaction.state;
  9655. if (txnState === transactions_1.TxnState.NO_TRANSACTION) {
  9656. callback(new error_1.MongoTransactionError("No transaction started"));
  9657. return;
  9658. }
  9659. if (commandName === "commitTransaction") {
  9660. if (txnState === transactions_1.TxnState.STARTING_TRANSACTION || txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) {
  9661. session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY);
  9662. callback();
  9663. return;
  9664. }
  9665. if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) {
  9666. callback(new error_1.MongoTransactionError("Cannot call commitTransaction after calling abortTransaction"));
  9667. return;
  9668. }
  9669. } else {
  9670. if (txnState === transactions_1.TxnState.STARTING_TRANSACTION) {
  9671. session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
  9672. callback();
  9673. return;
  9674. }
  9675. if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) {
  9676. callback(new error_1.MongoTransactionError("Cannot call abortTransaction twice"));
  9677. return;
  9678. }
  9679. if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED || txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) {
  9680. callback(new error_1.MongoTransactionError("Cannot call abortTransaction after calling commitTransaction"));
  9681. return;
  9682. }
  9683. }
  9684. const command = { [commandName]: 1 };
  9685. let writeConcern;
  9686. if (session.transaction.options.writeConcern) {
  9687. writeConcern = Object.assign({}, session.transaction.options.writeConcern);
  9688. } else if (session.clientOptions && session.clientOptions.writeConcern) {
  9689. writeConcern = { w: session.clientOptions.writeConcern.w };
  9690. }
  9691. if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED) {
  9692. writeConcern = Object.assign({ wtimeoutMS: 1e4 }, writeConcern, { w: "majority" });
  9693. }
  9694. if (writeConcern) {
  9695. write_concern_1.WriteConcern.apply(command, writeConcern);
  9696. }
  9697. if (commandName === "commitTransaction" && session.transaction.options.maxTimeMS) {
  9698. Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS });
  9699. }
  9700. function commandHandler(error, result) {
  9701. if (commandName !== "commitTransaction") {
  9702. session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
  9703. if (session.loadBalanced) {
  9704. maybeClearPinnedConnection(session, { force: false });
  9705. }
  9706. return callback();
  9707. }
  9708. session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED);
  9709. if (error instanceof error_1.MongoError) {
  9710. if (error.hasErrorLabel(error_1.MongoErrorLabel.RetryableWriteError) || error instanceof error_1.MongoWriteConcernError || isMaxTimeMSExpiredError(error)) {
  9711. if (isUnknownTransactionCommitResult(error)) {
  9712. error.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
  9713. session.unpin({ error });
  9714. }
  9715. } else if (error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  9716. session.unpin({ error });
  9717. }
  9718. }
  9719. callback(error, result);
  9720. }
  9721. __name(commandHandler, "commandHandler");
  9722. if (session.transaction.recoveryToken) {
  9723. command.recoveryToken = session.transaction.recoveryToken;
  9724. }
  9725. (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(void 0, command, {
  9726. session,
  9727. readPreference: read_preference_1.ReadPreference.primary,
  9728. bypassPinningCheck: true
  9729. }), (error, result) => {
  9730. if (command.abortTransaction) {
  9731. session.unpin();
  9732. }
  9733. if (error instanceof error_1.MongoError && error.hasErrorLabel(error_1.MongoErrorLabel.RetryableWriteError)) {
  9734. if (command.commitTransaction) {
  9735. session.unpin({ force: true });
  9736. command.writeConcern = Object.assign({ wtimeout: 1e4 }, command.writeConcern, {
  9737. w: "majority"
  9738. });
  9739. }
  9740. return (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(void 0, command, {
  9741. session,
  9742. readPreference: read_preference_1.ReadPreference.primary,
  9743. bypassPinningCheck: true
  9744. }), commandHandler);
  9745. }
  9746. commandHandler(error, result);
  9747. });
  9748. }
  9749. __name(endTransaction, "endTransaction");
  9750. var _ServerSession = class _ServerSession {
  9751. /** @internal */
  9752. constructor() {
  9753. this.id = { id: new bson_1.Binary((0, utils_1.uuidV4)(), bson_1.Binary.SUBTYPE_UUID) };
  9754. this.lastUse = (0, utils_1.now)();
  9755. this.txnNumber = 0;
  9756. this.isDirty = false;
  9757. }
  9758. /**
  9759. * Determines if the server session has timed out.
  9760. *
  9761. * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes"
  9762. */
  9763. hasTimedOut(sessionTimeoutMinutes) {
  9764. const idleTimeMinutes = Math.round((0, utils_1.calculateDurationInMs)(this.lastUse) % 864e5 % 36e5 / 6e4);
  9765. return idleTimeMinutes > sessionTimeoutMinutes - 1;
  9766. }
  9767. /**
  9768. * @internal
  9769. * Cloning meant to keep a readable reference to the server session data
  9770. * after ClientSession has ended
  9771. */
  9772. static clone(serverSession) {
  9773. const arrayBuffer = new ArrayBuffer(16);
  9774. const idBytes = Buffer.from(arrayBuffer);
  9775. idBytes.set(serverSession.id.id.buffer);
  9776. const id = new bson_1.Binary(idBytes, serverSession.id.id.sub_type);
  9777. return Object.setPrototypeOf({
  9778. id: { id },
  9779. lastUse: serverSession.lastUse,
  9780. txnNumber: serverSession.txnNumber,
  9781. isDirty: serverSession.isDirty
  9782. }, _ServerSession.prototype);
  9783. }
  9784. };
  9785. __name(_ServerSession, "ServerSession");
  9786. var ServerSession = _ServerSession;
  9787. exports2.ServerSession = ServerSession;
  9788. var _ServerSessionPool = class _ServerSessionPool {
  9789. constructor(client) {
  9790. if (client == null) {
  9791. throw new error_1.MongoRuntimeError("ServerSessionPool requires a MongoClient");
  9792. }
  9793. this.client = client;
  9794. this.sessions = new utils_1.List();
  9795. }
  9796. /**
  9797. * Acquire a Server Session from the pool.
  9798. * Iterates through each session in the pool, removing any stale sessions
  9799. * along the way. The first non-stale session found is removed from the
  9800. * pool and returned. If no non-stale session is found, a new ServerSession is created.
  9801. */
  9802. acquire() {
  9803. var _a2, _b;
  9804. const sessionTimeoutMinutes = ((_a2 = this.client.topology) == null ? void 0 : _a2.logicalSessionTimeoutMinutes) ?? 10;
  9805. let session = null;
  9806. while (this.sessions.length > 0) {
  9807. const potentialSession = this.sessions.shift();
  9808. if (potentialSession != null && (!!((_b = this.client.topology) == null ? void 0 : _b.loadBalanced) || !potentialSession.hasTimedOut(sessionTimeoutMinutes))) {
  9809. session = potentialSession;
  9810. break;
  9811. }
  9812. }
  9813. if (session == null) {
  9814. session = new ServerSession();
  9815. }
  9816. return session;
  9817. }
  9818. /**
  9819. * Release a session to the session pool
  9820. * Adds the session back to the session pool if the session has not timed out yet.
  9821. * This method also removes any stale sessions from the pool.
  9822. *
  9823. * @param session - The session to release to the pool
  9824. */
  9825. release(session) {
  9826. var _a2, _b;
  9827. const sessionTimeoutMinutes = ((_a2 = this.client.topology) == null ? void 0 : _a2.logicalSessionTimeoutMinutes) ?? 10;
  9828. if (((_b = this.client.topology) == null ? void 0 : _b.loadBalanced) && !sessionTimeoutMinutes) {
  9829. this.sessions.unshift(session);
  9830. }
  9831. if (!sessionTimeoutMinutes) {
  9832. return;
  9833. }
  9834. this.sessions.prune((session2) => session2.hasTimedOut(sessionTimeoutMinutes));
  9835. if (!session.hasTimedOut(sessionTimeoutMinutes)) {
  9836. if (session.isDirty) {
  9837. return;
  9838. }
  9839. this.sessions.unshift(session);
  9840. }
  9841. }
  9842. };
  9843. __name(_ServerSessionPool, "ServerSessionPool");
  9844. var ServerSessionPool = _ServerSessionPool;
  9845. exports2.ServerSessionPool = ServerSessionPool;
  9846. function applySession(session, command, options) {
  9847. var _a2, _b;
  9848. if (session.hasEnded) {
  9849. return new error_1.MongoExpiredSessionError();
  9850. }
  9851. const serverSession = session.serverSession;
  9852. if (serverSession == null) {
  9853. return new error_1.MongoRuntimeError("Unable to acquire server session");
  9854. }
  9855. if (((_a2 = options.writeConcern) == null ? void 0 : _a2.w) === 0) {
  9856. if (session && session.explicit) {
  9857. return new error_1.MongoAPIError("Cannot have explicit session with unacknowledged writes");
  9858. }
  9859. return;
  9860. }
  9861. serverSession.lastUse = (0, utils_1.now)();
  9862. command.lsid = serverSession.id;
  9863. const inTxnOrTxnCommand = session.inTransaction() || (0, transactions_1.isTransactionCommand)(command);
  9864. const isRetryableWrite = !!options.willRetryWrite;
  9865. if (isRetryableWrite || inTxnOrTxnCommand) {
  9866. serverSession.txnNumber += session[kTxnNumberIncrement];
  9867. session[kTxnNumberIncrement] = 0;
  9868. command.txnNumber = bson_1.Long.fromNumber(serverSession.txnNumber);
  9869. }
  9870. if (!inTxnOrTxnCommand) {
  9871. if (session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION) {
  9872. session.transaction.transition(transactions_1.TxnState.NO_TRANSACTION);
  9873. }
  9874. if (session.supports.causalConsistency && session.operationTime && (0, utils_1.commandSupportsReadConcern)(command, options)) {
  9875. command.readConcern = command.readConcern || {};
  9876. Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
  9877. } else if (session[kSnapshotEnabled]) {
  9878. command.readConcern = command.readConcern || { level: read_concern_1.ReadConcernLevel.snapshot };
  9879. if (session[kSnapshotTime] != null) {
  9880. Object.assign(command.readConcern, { atClusterTime: session[kSnapshotTime] });
  9881. }
  9882. }
  9883. return;
  9884. }
  9885. command.autocommit = false;
  9886. if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) {
  9887. session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS);
  9888. command.startTransaction = true;
  9889. const readConcern = session.transaction.options.readConcern || ((_b = session == null ? void 0 : session.clientOptions) == null ? void 0 : _b.readConcern);
  9890. if (readConcern) {
  9891. command.readConcern = readConcern;
  9892. }
  9893. if (session.supports.causalConsistency && session.operationTime) {
  9894. command.readConcern = command.readConcern || {};
  9895. Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
  9896. }
  9897. }
  9898. return;
  9899. }
  9900. __name(applySession, "applySession");
  9901. exports2.applySession = applySession;
  9902. function updateSessionFromResponse(session, document) {
  9903. var _a2;
  9904. if (document.$clusterTime) {
  9905. (0, common_1._advanceClusterTime)(session, document.$clusterTime);
  9906. }
  9907. if (document.operationTime && session && session.supports.causalConsistency) {
  9908. session.advanceOperationTime(document.operationTime);
  9909. }
  9910. if (document.recoveryToken && session && session.inTransaction()) {
  9911. session.transaction._recoveryToken = document.recoveryToken;
  9912. }
  9913. if ((session == null ? void 0 : session[kSnapshotEnabled]) && session[kSnapshotTime] == null) {
  9914. const atClusterTime = ((_a2 = document.cursor) == null ? void 0 : _a2.atClusterTime) || document.atClusterTime;
  9915. if (atClusterTime) {
  9916. session[kSnapshotTime] = atClusterTime;
  9917. }
  9918. }
  9919. }
  9920. __name(updateSessionFromResponse, "updateSessionFromResponse");
  9921. exports2.updateSessionFromResponse = updateSessionFromResponse;
  9922. }
  9923. });
  9924. // node_modules/mongodb/lib/cursor/abstract_cursor.js
  9925. var require_abstract_cursor = __commonJS({
  9926. "node_modules/mongodb/lib/cursor/abstract_cursor.js"(exports2) {
  9927. "use strict";
  9928. Object.defineProperty(exports2, "__esModule", { value: true });
  9929. exports2.assertUninitialized = exports2.AbstractCursor = exports2.CURSOR_FLAGS = void 0;
  9930. var stream_1 = require("stream");
  9931. var util_1 = require("util");
  9932. var bson_1 = require_bson2();
  9933. var error_1 = require_error();
  9934. var mongo_types_1 = require_mongo_types();
  9935. var execute_operation_1 = require_execute_operation();
  9936. var get_more_1 = require_get_more();
  9937. var kill_cursors_1 = require_kill_cursors();
  9938. var read_concern_1 = require_read_concern();
  9939. var read_preference_1 = require_read_preference();
  9940. var sessions_1 = require_sessions();
  9941. var utils_1 = require_utils();
  9942. var kId = Symbol("id");
  9943. var kDocuments = Symbol("documents");
  9944. var kServer = Symbol("server");
  9945. var kNamespace = Symbol("namespace");
  9946. var kClient = Symbol("client");
  9947. var kSession = Symbol("session");
  9948. var kOptions = Symbol("options");
  9949. var kTransform = Symbol("transform");
  9950. var kInitialized = Symbol("initialized");
  9951. var kClosed = Symbol("closed");
  9952. var kKilled = Symbol("killed");
  9953. var kInit = Symbol("kInit");
  9954. exports2.CURSOR_FLAGS = [
  9955. "tailable",
  9956. "oplogReplay",
  9957. "noCursorTimeout",
  9958. "awaitData",
  9959. "exhaust",
  9960. "partial"
  9961. ];
  9962. var _AbstractCursor = class _AbstractCursor extends mongo_types_1.TypedEventEmitter {
  9963. /** @internal */
  9964. constructor(client, namespace, options = {}) {
  9965. super();
  9966. if (!client.s.isMongoClient) {
  9967. throw new error_1.MongoRuntimeError("Cursor must be constructed with MongoClient");
  9968. }
  9969. this[kClient] = client;
  9970. this[kNamespace] = namespace;
  9971. this[kId] = null;
  9972. this[kDocuments] = new utils_1.List();
  9973. this[kInitialized] = false;
  9974. this[kClosed] = false;
  9975. this[kKilled] = false;
  9976. this[kOptions] = {
  9977. readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference ? options.readPreference : read_preference_1.ReadPreference.primary,
  9978. ...(0, bson_1.pluckBSONSerializeOptions)(options)
  9979. };
  9980. const readConcern = read_concern_1.ReadConcern.fromOptions(options);
  9981. if (readConcern) {
  9982. this[kOptions].readConcern = readConcern;
  9983. }
  9984. if (typeof options.batchSize === "number") {
  9985. this[kOptions].batchSize = options.batchSize;
  9986. }
  9987. if (options.comment !== void 0) {
  9988. this[kOptions].comment = options.comment;
  9989. }
  9990. if (typeof options.maxTimeMS === "number") {
  9991. this[kOptions].maxTimeMS = options.maxTimeMS;
  9992. }
  9993. if (typeof options.maxAwaitTimeMS === "number") {
  9994. this[kOptions].maxAwaitTimeMS = options.maxAwaitTimeMS;
  9995. }
  9996. if (options.session instanceof sessions_1.ClientSession) {
  9997. this[kSession] = options.session;
  9998. } else {
  9999. this[kSession] = this[kClient].startSession({ owner: this, explicit: false });
  10000. }
  10001. }
  10002. get id() {
  10003. return this[kId] ?? void 0;
  10004. }
  10005. /** @internal */
  10006. get isDead() {
  10007. var _a;
  10008. return (((_a = this[kId]) == null ? void 0 : _a.isZero()) ?? false) || this[kClosed] || this[kKilled];
  10009. }
  10010. /** @internal */
  10011. get client() {
  10012. return this[kClient];
  10013. }
  10014. /** @internal */
  10015. get server() {
  10016. return this[kServer];
  10017. }
  10018. get namespace() {
  10019. return this[kNamespace];
  10020. }
  10021. get readPreference() {
  10022. return this[kOptions].readPreference;
  10023. }
  10024. get readConcern() {
  10025. return this[kOptions].readConcern;
  10026. }
  10027. /** @internal */
  10028. get session() {
  10029. return this[kSession];
  10030. }
  10031. set session(clientSession) {
  10032. this[kSession] = clientSession;
  10033. }
  10034. /** @internal */
  10035. get cursorOptions() {
  10036. return this[kOptions];
  10037. }
  10038. get closed() {
  10039. return this[kClosed];
  10040. }
  10041. get killed() {
  10042. return this[kKilled];
  10043. }
  10044. get loadBalanced() {
  10045. var _a;
  10046. return !!((_a = this[kClient].topology) == null ? void 0 : _a.loadBalanced);
  10047. }
  10048. /** Returns current buffered documents length */
  10049. bufferedCount() {
  10050. return this[kDocuments].length;
  10051. }
  10052. /** Returns current buffered documents */
  10053. readBufferedDocuments(number) {
  10054. const bufferedDocs = [];
  10055. const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length);
  10056. for (let count = 0; count < documentsToRead; count++) {
  10057. const document = this[kDocuments].shift();
  10058. if (document != null) {
  10059. bufferedDocs.push(document);
  10060. }
  10061. }
  10062. return bufferedDocs;
  10063. }
  10064. async *[Symbol.asyncIterator]() {
  10065. if (this.closed) {
  10066. return;
  10067. }
  10068. try {
  10069. while (true) {
  10070. const document = await this.next();
  10071. if (document === null) {
  10072. if (!this.closed) {
  10073. const message = "Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.";
  10074. await cleanupCursorAsync(this, { needsToEmitClosed: true }).catch(() => null);
  10075. throw new error_1.MongoAPIError(message);
  10076. }
  10077. break;
  10078. }
  10079. yield document;
  10080. if (this[kId] === bson_1.Long.ZERO) {
  10081. break;
  10082. }
  10083. }
  10084. } finally {
  10085. if (!this.closed) {
  10086. await this.close().catch(() => null);
  10087. }
  10088. }
  10089. }
  10090. stream(options) {
  10091. if (options == null ? void 0 : options.transform) {
  10092. const transform = options.transform;
  10093. const readable = new ReadableCursorStream(this);
  10094. return readable.pipe(new stream_1.Transform({
  10095. objectMode: true,
  10096. highWaterMark: 1,
  10097. transform(chunk, _, callback) {
  10098. try {
  10099. const transformed = transform(chunk);
  10100. callback(void 0, transformed);
  10101. } catch (err) {
  10102. callback(err);
  10103. }
  10104. }
  10105. }));
  10106. }
  10107. return new ReadableCursorStream(this);
  10108. }
  10109. async hasNext() {
  10110. if (this[kId] === bson_1.Long.ZERO) {
  10111. return false;
  10112. }
  10113. if (this[kDocuments].length !== 0) {
  10114. return true;
  10115. }
  10116. const doc = await next(this, { blocking: true, transform: false });
  10117. if (doc) {
  10118. this[kDocuments].unshift(doc);
  10119. return true;
  10120. }
  10121. return false;
  10122. }
  10123. /** Get the next available document from the cursor, returns null if no more documents are available. */
  10124. async next() {
  10125. if (this[kId] === bson_1.Long.ZERO) {
  10126. throw new error_1.MongoCursorExhaustedError();
  10127. }
  10128. return next(this, { blocking: true, transform: true });
  10129. }
  10130. /**
  10131. * Try to get the next available document from the cursor or `null` if an empty batch is returned
  10132. */
  10133. async tryNext() {
  10134. if (this[kId] === bson_1.Long.ZERO) {
  10135. throw new error_1.MongoCursorExhaustedError();
  10136. }
  10137. return next(this, { blocking: false, transform: true });
  10138. }
  10139. /**
  10140. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  10141. *
  10142. * If the iterator returns `false`, iteration will stop.
  10143. *
  10144. * @param iterator - The iteration callback.
  10145. * @deprecated - Will be removed in a future release. Use for await...of instead.
  10146. */
  10147. async forEach(iterator) {
  10148. if (typeof iterator !== "function") {
  10149. throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function');
  10150. }
  10151. for await (const document of this) {
  10152. const result = iterator(document);
  10153. if (result === false) {
  10154. break;
  10155. }
  10156. }
  10157. }
  10158. async close() {
  10159. const needsToEmitClosed = !this[kClosed];
  10160. this[kClosed] = true;
  10161. await cleanupCursorAsync(this, { needsToEmitClosed });
  10162. }
  10163. /**
  10164. * Returns an array of documents. The caller is responsible for making sure that there
  10165. * is enough memory to store the results. Note that the array only contains partial
  10166. * results when this cursor had been previously accessed. In that case,
  10167. * cursor.rewind() can be used to reset the cursor.
  10168. */
  10169. async toArray() {
  10170. const array = [];
  10171. for await (const document of this) {
  10172. array.push(document);
  10173. }
  10174. return array;
  10175. }
  10176. /**
  10177. * Add a cursor flag to the cursor
  10178. *
  10179. * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
  10180. * @param value - The flag boolean value.
  10181. */
  10182. addCursorFlag(flag, value) {
  10183. assertUninitialized(this);
  10184. if (!exports2.CURSOR_FLAGS.includes(flag)) {
  10185. throw new error_1.MongoInvalidArgumentError(`Flag ${flag} is not one of ${exports2.CURSOR_FLAGS}`);
  10186. }
  10187. if (typeof value !== "boolean") {
  10188. throw new error_1.MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`);
  10189. }
  10190. this[kOptions][flag] = value;
  10191. return this;
  10192. }
  10193. /**
  10194. * Map all documents using the provided function
  10195. * If there is a transform set on the cursor, that will be called first and the result passed to
  10196. * this function's transform.
  10197. *
  10198. * @remarks
  10199. *
  10200. * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping
  10201. * function that maps values to `null` will result in the cursor closing itself before it has finished iterating
  10202. * all documents. This will **not** result in a memory leak, just surprising behavior. For example:
  10203. *
  10204. * ```typescript
  10205. * const cursor = collection.find({});
  10206. * cursor.map(() => null);
  10207. *
  10208. * const documents = await cursor.toArray();
  10209. * // documents is always [], regardless of how many documents are in the collection.
  10210. * ```
  10211. *
  10212. * Other falsey values are allowed:
  10213. *
  10214. * ```typescript
  10215. * const cursor = collection.find({});
  10216. * cursor.map(() => '');
  10217. *
  10218. * const documents = await cursor.toArray();
  10219. * // documents is now an array of empty strings
  10220. * ```
  10221. *
  10222. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  10223. * it **does not** return a new instance of a cursor. This means when calling map,
  10224. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  10225. * Take note of the following example:
  10226. *
  10227. * @example
  10228. * ```typescript
  10229. * const cursor: FindCursor<Document> = coll.find();
  10230. * const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
  10231. * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
  10232. * ```
  10233. * @param transform - The mapping transformation method.
  10234. */
  10235. map(transform) {
  10236. assertUninitialized(this);
  10237. const oldTransform = this[kTransform];
  10238. if (oldTransform) {
  10239. this[kTransform] = (doc) => {
  10240. return transform(oldTransform(doc));
  10241. };
  10242. } else {
  10243. this[kTransform] = transform;
  10244. }
  10245. return this;
  10246. }
  10247. /**
  10248. * Set the ReadPreference for the cursor.
  10249. *
  10250. * @param readPreference - The new read preference for the cursor.
  10251. */
  10252. withReadPreference(readPreference) {
  10253. assertUninitialized(this);
  10254. if (readPreference instanceof read_preference_1.ReadPreference) {
  10255. this[kOptions].readPreference = readPreference;
  10256. } else if (typeof readPreference === "string") {
  10257. this[kOptions].readPreference = read_preference_1.ReadPreference.fromString(readPreference);
  10258. } else {
  10259. throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`);
  10260. }
  10261. return this;
  10262. }
  10263. /**
  10264. * Set the ReadPreference for the cursor.
  10265. *
  10266. * @param readPreference - The new read preference for the cursor.
  10267. */
  10268. withReadConcern(readConcern) {
  10269. assertUninitialized(this);
  10270. const resolvedReadConcern = read_concern_1.ReadConcern.fromOptions({ readConcern });
  10271. if (resolvedReadConcern) {
  10272. this[kOptions].readConcern = resolvedReadConcern;
  10273. }
  10274. return this;
  10275. }
  10276. /**
  10277. * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
  10278. *
  10279. * @param value - Number of milliseconds to wait before aborting the query.
  10280. */
  10281. maxTimeMS(value) {
  10282. assertUninitialized(this);
  10283. if (typeof value !== "number") {
  10284. throw new error_1.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");
  10285. }
  10286. this[kOptions].maxTimeMS = value;
  10287. return this;
  10288. }
  10289. /**
  10290. * Set the batch size for the cursor.
  10291. *
  10292. * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}.
  10293. */
  10294. batchSize(value) {
  10295. assertUninitialized(this);
  10296. if (this[kOptions].tailable) {
  10297. throw new error_1.MongoTailableCursorError("Tailable cursor does not support batchSize");
  10298. }
  10299. if (typeof value !== "number") {
  10300. throw new error_1.MongoInvalidArgumentError('Operation "batchSize" requires an integer');
  10301. }
  10302. this[kOptions].batchSize = value;
  10303. return this;
  10304. }
  10305. /**
  10306. * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
  10307. * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
  10308. * if the resultant data has already been retrieved by this cursor.
  10309. */
  10310. rewind() {
  10311. if (!this[kInitialized]) {
  10312. return;
  10313. }
  10314. this[kId] = null;
  10315. this[kDocuments].clear();
  10316. this[kClosed] = false;
  10317. this[kKilled] = false;
  10318. this[kInitialized] = false;
  10319. const session = this[kSession];
  10320. if (session) {
  10321. if (session.explicit === false) {
  10322. if (!session.hasEnded) {
  10323. session.endSession().catch(() => null);
  10324. }
  10325. this[kSession] = this.client.startSession({ owner: this, explicit: false });
  10326. }
  10327. }
  10328. }
  10329. /** @internal */
  10330. _getMore(batchSize, callback) {
  10331. const getMoreOperation = new get_more_1.GetMoreOperation(this[kNamespace], this[kId], this[kServer], {
  10332. ...this[kOptions],
  10333. session: this[kSession],
  10334. batchSize
  10335. });
  10336. (0, execute_operation_1.executeOperation)(this[kClient], getMoreOperation, callback);
  10337. }
  10338. /**
  10339. * @internal
  10340. *
  10341. * This function is exposed for the unified test runner's createChangeStream
  10342. * operation. We cannot refactor to use the abstract _initialize method without
  10343. * a significant refactor.
  10344. */
  10345. [kInit](callback) {
  10346. this._initialize(this[kSession], (error, state) => {
  10347. if (state) {
  10348. const response = state.response;
  10349. this[kServer] = state.server;
  10350. if (response.cursor) {
  10351. this[kId] = typeof response.cursor.id === "number" ? bson_1.Long.fromNumber(response.cursor.id) : typeof response.cursor.id === "bigint" ? bson_1.Long.fromBigInt(response.cursor.id) : response.cursor.id;
  10352. if (response.cursor.ns) {
  10353. this[kNamespace] = (0, utils_1.ns)(response.cursor.ns);
  10354. }
  10355. this[kDocuments].pushMany(response.cursor.firstBatch);
  10356. }
  10357. if (this[kId] == null) {
  10358. this[kId] = bson_1.Long.ZERO;
  10359. this[kDocuments].push(state.response);
  10360. }
  10361. }
  10362. this[kInitialized] = true;
  10363. if (error) {
  10364. return cleanupCursor(this, { error }, () => callback(error, void 0));
  10365. }
  10366. if (this.isDead) {
  10367. return cleanupCursor(this, void 0, () => callback());
  10368. }
  10369. callback();
  10370. });
  10371. }
  10372. };
  10373. __name(_AbstractCursor, "AbstractCursor");
  10374. var AbstractCursor = _AbstractCursor;
  10375. AbstractCursor.CLOSE = "close";
  10376. exports2.AbstractCursor = AbstractCursor;
  10377. async function next(cursor, { blocking, transform }) {
  10378. if (cursor.closed) {
  10379. return null;
  10380. }
  10381. do {
  10382. if (cursor[kId] == null) {
  10383. await (0, util_1.promisify)(cursor[kInit].bind(cursor))();
  10384. }
  10385. if (cursor[kDocuments].length !== 0) {
  10386. const doc = cursor[kDocuments].shift();
  10387. if (doc != null && transform && cursor[kTransform]) {
  10388. try {
  10389. return cursor[kTransform](doc);
  10390. } catch (error) {
  10391. await cleanupCursorAsync(cursor, { error, needsToEmitClosed: true }).catch(() => null);
  10392. throw error;
  10393. }
  10394. }
  10395. return doc;
  10396. }
  10397. if (cursor.isDead) {
  10398. await cleanupCursorAsync(cursor, {});
  10399. return null;
  10400. }
  10401. const batchSize = cursor[kOptions].batchSize || 1e3;
  10402. try {
  10403. const response = await (0, util_1.promisify)(cursor._getMore.bind(cursor))(batchSize);
  10404. if (response) {
  10405. const cursorId = typeof response.cursor.id === "number" ? bson_1.Long.fromNumber(response.cursor.id) : typeof response.cursor.id === "bigint" ? bson_1.Long.fromBigInt(response.cursor.id) : response.cursor.id;
  10406. cursor[kDocuments].pushMany(response.cursor.nextBatch);
  10407. cursor[kId] = cursorId;
  10408. }
  10409. } catch (error) {
  10410. await cleanupCursorAsync(cursor, { error }).catch(() => null);
  10411. throw error;
  10412. }
  10413. if (cursor.isDead) {
  10414. await cleanupCursorAsync(cursor, {});
  10415. }
  10416. if (cursor[kDocuments].length === 0 && blocking === false) {
  10417. return null;
  10418. }
  10419. } while (!cursor.isDead || cursor[kDocuments].length !== 0);
  10420. return null;
  10421. }
  10422. __name(next, "next");
  10423. var cleanupCursorAsync = (0, util_1.promisify)(cleanupCursor);
  10424. function cleanupCursor(cursor, options, callback) {
  10425. const cursorId = cursor[kId];
  10426. const cursorNs = cursor[kNamespace];
  10427. const server = cursor[kServer];
  10428. const session = cursor[kSession];
  10429. const error = options == null ? void 0 : options.error;
  10430. const needsToEmitClosed = (options == null ? void 0 : options.needsToEmitClosed) ?? cursor[kDocuments].length === 0;
  10431. if (error) {
  10432. if (cursor.loadBalanced && error instanceof error_1.MongoNetworkError) {
  10433. return completeCleanup();
  10434. }
  10435. }
  10436. if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) {
  10437. if (needsToEmitClosed) {
  10438. cursor[kClosed] = true;
  10439. cursor[kId] = bson_1.Long.ZERO;
  10440. cursor.emit(AbstractCursor.CLOSE);
  10441. }
  10442. if (session) {
  10443. if (session.owner === cursor) {
  10444. session.endSession({ error }).finally(() => {
  10445. callback();
  10446. });
  10447. return;
  10448. }
  10449. if (!session.inTransaction()) {
  10450. (0, sessions_1.maybeClearPinnedConnection)(session, { error });
  10451. }
  10452. }
  10453. return callback();
  10454. }
  10455. function completeCleanup() {
  10456. if (session) {
  10457. if (session.owner === cursor) {
  10458. session.endSession({ error }).finally(() => {
  10459. cursor.emit(AbstractCursor.CLOSE);
  10460. callback();
  10461. });
  10462. return;
  10463. }
  10464. if (!session.inTransaction()) {
  10465. (0, sessions_1.maybeClearPinnedConnection)(session, { error });
  10466. }
  10467. }
  10468. cursor.emit(AbstractCursor.CLOSE);
  10469. return callback();
  10470. }
  10471. __name(completeCleanup, "completeCleanup");
  10472. cursor[kKilled] = true;
  10473. if (session.hasEnded) {
  10474. return completeCleanup();
  10475. }
  10476. (0, execute_operation_1.executeOperation)(cursor[kClient], new kill_cursors_1.KillCursorsOperation(cursorId, cursorNs, server, { session })).catch(() => null).finally(completeCleanup);
  10477. }
  10478. __name(cleanupCursor, "cleanupCursor");
  10479. function assertUninitialized(cursor) {
  10480. if (cursor[kInitialized]) {
  10481. throw new error_1.MongoCursorInUseError();
  10482. }
  10483. }
  10484. __name(assertUninitialized, "assertUninitialized");
  10485. exports2.assertUninitialized = assertUninitialized;
  10486. var _ReadableCursorStream = class _ReadableCursorStream extends stream_1.Readable {
  10487. constructor(cursor) {
  10488. super({
  10489. objectMode: true,
  10490. autoDestroy: false,
  10491. highWaterMark: 1
  10492. });
  10493. this._readInProgress = false;
  10494. this._cursor = cursor;
  10495. }
  10496. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  10497. _read(size) {
  10498. if (!this._readInProgress) {
  10499. this._readInProgress = true;
  10500. this._readNext();
  10501. }
  10502. }
  10503. _destroy(error, callback) {
  10504. this._cursor.close().then(() => callback(error), (closeError) => callback(closeError));
  10505. }
  10506. _readNext() {
  10507. next(this._cursor, { blocking: true, transform: true }).then((result) => {
  10508. if (result == null) {
  10509. this.push(null);
  10510. } else if (this.destroyed) {
  10511. this._cursor.close().catch(() => null);
  10512. } else {
  10513. if (this.push(result)) {
  10514. return this._readNext();
  10515. }
  10516. this._readInProgress = false;
  10517. }
  10518. }, (err) => {
  10519. if (err.message.match(/server is closed/)) {
  10520. this._cursor.close().catch(() => null);
  10521. return this.push(null);
  10522. }
  10523. if (err.message.match(/operation was interrupted/)) {
  10524. return this.push(null);
  10525. }
  10526. return this.destroy(err);
  10527. });
  10528. }
  10529. };
  10530. __name(_ReadableCursorStream, "ReadableCursorStream");
  10531. var ReadableCursorStream = _ReadableCursorStream;
  10532. }
  10533. });
  10534. // node_modules/mongodb/lib/cursor/aggregation_cursor.js
  10535. var require_aggregation_cursor = __commonJS({
  10536. "node_modules/mongodb/lib/cursor/aggregation_cursor.js"(exports2) {
  10537. "use strict";
  10538. Object.defineProperty(exports2, "__esModule", { value: true });
  10539. exports2.AggregationCursor = void 0;
  10540. var aggregate_1 = require_aggregate();
  10541. var execute_operation_1 = require_execute_operation();
  10542. var utils_1 = require_utils();
  10543. var abstract_cursor_1 = require_abstract_cursor();
  10544. var kPipeline = Symbol("pipeline");
  10545. var kOptions = Symbol("options");
  10546. var _AggregationCursor = class _AggregationCursor extends abstract_cursor_1.AbstractCursor {
  10547. /** @internal */
  10548. constructor(client, namespace, pipeline = [], options = {}) {
  10549. super(client, namespace, options);
  10550. this[kPipeline] = pipeline;
  10551. this[kOptions] = options;
  10552. }
  10553. get pipeline() {
  10554. return this[kPipeline];
  10555. }
  10556. clone() {
  10557. const clonedOptions = (0, utils_1.mergeOptions)({}, this[kOptions]);
  10558. delete clonedOptions.session;
  10559. return new _AggregationCursor(this.client, this.namespace, this[kPipeline], {
  10560. ...clonedOptions
  10561. });
  10562. }
  10563. map(transform) {
  10564. return super.map(transform);
  10565. }
  10566. /** @internal */
  10567. _initialize(session, callback) {
  10568. const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], {
  10569. ...this[kOptions],
  10570. ...this.cursorOptions,
  10571. session
  10572. });
  10573. (0, execute_operation_1.executeOperation)(this.client, aggregateOperation, (err, response) => {
  10574. if (err || response == null)
  10575. return callback(err);
  10576. callback(void 0, { server: aggregateOperation.server, session, response });
  10577. });
  10578. }
  10579. /** Execute the explain for the cursor */
  10580. async explain(verbosity) {
  10581. return (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], {
  10582. ...this[kOptions],
  10583. ...this.cursorOptions,
  10584. explain: verbosity ?? true
  10585. }));
  10586. }
  10587. group($group) {
  10588. (0, abstract_cursor_1.assertUninitialized)(this);
  10589. this[kPipeline].push({ $group });
  10590. return this;
  10591. }
  10592. /** Add a limit stage to the aggregation pipeline */
  10593. limit($limit) {
  10594. (0, abstract_cursor_1.assertUninitialized)(this);
  10595. this[kPipeline].push({ $limit });
  10596. return this;
  10597. }
  10598. /** Add a match stage to the aggregation pipeline */
  10599. match($match) {
  10600. (0, abstract_cursor_1.assertUninitialized)(this);
  10601. this[kPipeline].push({ $match });
  10602. return this;
  10603. }
  10604. /** Add an out stage to the aggregation pipeline */
  10605. out($out) {
  10606. (0, abstract_cursor_1.assertUninitialized)(this);
  10607. this[kPipeline].push({ $out });
  10608. return this;
  10609. }
  10610. /**
  10611. * Add a project stage to the aggregation pipeline
  10612. *
  10613. * @remarks
  10614. * In order to strictly type this function you must provide an interface
  10615. * that represents the effect of your projection on the result documents.
  10616. *
  10617. * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type.
  10618. * You should specify a parameterized type to have assertions on your final results.
  10619. *
  10620. * @example
  10621. * ```typescript
  10622. * // Best way
  10623. * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
  10624. * // Flexible way
  10625. * const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });
  10626. * ```
  10627. *
  10628. * @remarks
  10629. * In order to strictly type this function you must provide an interface
  10630. * that represents the effect of your projection on the result documents.
  10631. *
  10632. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  10633. * it **does not** return a new instance of a cursor. This means when calling project,
  10634. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  10635. * Take note of the following example:
  10636. *
  10637. * @example
  10638. * ```typescript
  10639. * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);
  10640. * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
  10641. * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
  10642. *
  10643. * // or always use chaining and save the final cursor
  10644. *
  10645. * const cursor = coll.aggregate().project<{ a: string }>({
  10646. * _id: 0,
  10647. * a: { $convert: { input: '$a', to: 'string' }
  10648. * }});
  10649. * ```
  10650. */
  10651. project($project) {
  10652. (0, abstract_cursor_1.assertUninitialized)(this);
  10653. this[kPipeline].push({ $project });
  10654. return this;
  10655. }
  10656. /** Add a lookup stage to the aggregation pipeline */
  10657. lookup($lookup) {
  10658. (0, abstract_cursor_1.assertUninitialized)(this);
  10659. this[kPipeline].push({ $lookup });
  10660. return this;
  10661. }
  10662. /** Add a redact stage to the aggregation pipeline */
  10663. redact($redact) {
  10664. (0, abstract_cursor_1.assertUninitialized)(this);
  10665. this[kPipeline].push({ $redact });
  10666. return this;
  10667. }
  10668. /** Add a skip stage to the aggregation pipeline */
  10669. skip($skip) {
  10670. (0, abstract_cursor_1.assertUninitialized)(this);
  10671. this[kPipeline].push({ $skip });
  10672. return this;
  10673. }
  10674. /** Add a sort stage to the aggregation pipeline */
  10675. sort($sort) {
  10676. (0, abstract_cursor_1.assertUninitialized)(this);
  10677. this[kPipeline].push({ $sort });
  10678. return this;
  10679. }
  10680. /** Add a unwind stage to the aggregation pipeline */
  10681. unwind($unwind) {
  10682. (0, abstract_cursor_1.assertUninitialized)(this);
  10683. this[kPipeline].push({ $unwind });
  10684. return this;
  10685. }
  10686. /** Add a geoNear stage to the aggregation pipeline */
  10687. geoNear($geoNear) {
  10688. (0, abstract_cursor_1.assertUninitialized)(this);
  10689. this[kPipeline].push({ $geoNear });
  10690. return this;
  10691. }
  10692. };
  10693. __name(_AggregationCursor, "AggregationCursor");
  10694. var AggregationCursor = _AggregationCursor;
  10695. exports2.AggregationCursor = AggregationCursor;
  10696. }
  10697. });
  10698. // node_modules/mongodb/lib/operations/count.js
  10699. var require_count = __commonJS({
  10700. "node_modules/mongodb/lib/operations/count.js"(exports2) {
  10701. "use strict";
  10702. Object.defineProperty(exports2, "__esModule", { value: true });
  10703. exports2.CountOperation = void 0;
  10704. var command_1 = require_command();
  10705. var operation_1 = require_operation();
  10706. var _CountOperation = class _CountOperation extends command_1.CommandCallbackOperation {
  10707. constructor(namespace, filter, options) {
  10708. super({ s: { namespace } }, options);
  10709. this.options = options;
  10710. this.collectionName = namespace.collection;
  10711. this.query = filter;
  10712. }
  10713. executeCallback(server, session, callback) {
  10714. const options = this.options;
  10715. const cmd = {
  10716. count: this.collectionName,
  10717. query: this.query
  10718. };
  10719. if (typeof options.limit === "number") {
  10720. cmd.limit = options.limit;
  10721. }
  10722. if (typeof options.skip === "number") {
  10723. cmd.skip = options.skip;
  10724. }
  10725. if (options.hint != null) {
  10726. cmd.hint = options.hint;
  10727. }
  10728. if (typeof options.maxTimeMS === "number") {
  10729. cmd.maxTimeMS = options.maxTimeMS;
  10730. }
  10731. super.executeCommandCallback(server, session, cmd, (err, result) => {
  10732. callback(err, result ? result.n : 0);
  10733. });
  10734. }
  10735. };
  10736. __name(_CountOperation, "CountOperation");
  10737. var CountOperation = _CountOperation;
  10738. exports2.CountOperation = CountOperation;
  10739. (0, operation_1.defineAspects)(CountOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]);
  10740. }
  10741. });
  10742. // node_modules/mongodb/lib/sort.js
  10743. var require_sort = __commonJS({
  10744. "node_modules/mongodb/lib/sort.js"(exports2) {
  10745. "use strict";
  10746. Object.defineProperty(exports2, "__esModule", { value: true });
  10747. exports2.formatSort = void 0;
  10748. var error_1 = require_error();
  10749. function prepareDirection(direction = 1) {
  10750. const value = `${direction}`.toLowerCase();
  10751. if (isMeta(direction))
  10752. return direction;
  10753. switch (value) {
  10754. case "ascending":
  10755. case "asc":
  10756. case "1":
  10757. return 1;
  10758. case "descending":
  10759. case "desc":
  10760. case "-1":
  10761. return -1;
  10762. default:
  10763. throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`);
  10764. }
  10765. }
  10766. __name(prepareDirection, "prepareDirection");
  10767. function isMeta(t) {
  10768. return typeof t === "object" && t != null && "$meta" in t && typeof t.$meta === "string";
  10769. }
  10770. __name(isMeta, "isMeta");
  10771. function isPair(t) {
  10772. if (Array.isArray(t) && t.length === 2) {
  10773. try {
  10774. prepareDirection(t[1]);
  10775. return true;
  10776. } catch (e) {
  10777. return false;
  10778. }
  10779. }
  10780. return false;
  10781. }
  10782. __name(isPair, "isPair");
  10783. function isDeep(t) {
  10784. return Array.isArray(t) && Array.isArray(t[0]);
  10785. }
  10786. __name(isDeep, "isDeep");
  10787. function isMap(t) {
  10788. return t instanceof Map && t.size > 0;
  10789. }
  10790. __name(isMap, "isMap");
  10791. function pairToMap(v) {
  10792. return /* @__PURE__ */ new Map([[`${v[0]}`, prepareDirection([v[1]])]]);
  10793. }
  10794. __name(pairToMap, "pairToMap");
  10795. function deepToMap(t) {
  10796. const sortEntries = t.map(([k, v]) => [`${k}`, prepareDirection(v)]);
  10797. return new Map(sortEntries);
  10798. }
  10799. __name(deepToMap, "deepToMap");
  10800. function stringsToMap(t) {
  10801. const sortEntries = t.map((key) => [`${key}`, 1]);
  10802. return new Map(sortEntries);
  10803. }
  10804. __name(stringsToMap, "stringsToMap");
  10805. function objectToMap(t) {
  10806. const sortEntries = Object.entries(t).map(([k, v]) => [
  10807. `${k}`,
  10808. prepareDirection(v)
  10809. ]);
  10810. return new Map(sortEntries);
  10811. }
  10812. __name(objectToMap, "objectToMap");
  10813. function mapToMap(t) {
  10814. const sortEntries = Array.from(t).map(([k, v]) => [
  10815. `${k}`,
  10816. prepareDirection(v)
  10817. ]);
  10818. return new Map(sortEntries);
  10819. }
  10820. __name(mapToMap, "mapToMap");
  10821. function formatSort(sort, direction) {
  10822. if (sort == null)
  10823. return void 0;
  10824. if (typeof sort === "string")
  10825. return /* @__PURE__ */ new Map([[sort, prepareDirection(direction)]]);
  10826. if (typeof sort !== "object") {
  10827. throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`);
  10828. }
  10829. if (!Array.isArray(sort)) {
  10830. return isMap(sort) ? mapToMap(sort) : Object.keys(sort).length ? objectToMap(sort) : void 0;
  10831. }
  10832. if (!sort.length)
  10833. return void 0;
  10834. if (isDeep(sort))
  10835. return deepToMap(sort);
  10836. if (isPair(sort))
  10837. return pairToMap(sort);
  10838. return stringsToMap(sort);
  10839. }
  10840. __name(formatSort, "formatSort");
  10841. exports2.formatSort = formatSort;
  10842. }
  10843. });
  10844. // node_modules/mongodb/lib/operations/find.js
  10845. var require_find = __commonJS({
  10846. "node_modules/mongodb/lib/operations/find.js"(exports2) {
  10847. "use strict";
  10848. Object.defineProperty(exports2, "__esModule", { value: true });
  10849. exports2.FindOperation = void 0;
  10850. var error_1 = require_error();
  10851. var read_concern_1 = require_read_concern();
  10852. var sort_1 = require_sort();
  10853. var utils_1 = require_utils();
  10854. var command_1 = require_command();
  10855. var operation_1 = require_operation();
  10856. var _FindOperation = class _FindOperation extends command_1.CommandCallbackOperation {
  10857. constructor(collection, ns, filter = {}, options = {}) {
  10858. super(collection, options);
  10859. this.options = { ...options };
  10860. delete this.options.writeConcern;
  10861. this.ns = ns;
  10862. if (typeof filter !== "object" || Array.isArray(filter)) {
  10863. throw new error_1.MongoInvalidArgumentError("Query filter must be a plain object or ObjectId");
  10864. }
  10865. this.filter = filter != null && filter._bsontype === "ObjectId" ? { _id: filter } : filter;
  10866. }
  10867. executeCallback(server, session, callback) {
  10868. this.server = server;
  10869. const options = this.options;
  10870. let findCommand = makeFindCommand(this.ns, this.filter, options);
  10871. if (this.explain) {
  10872. findCommand = (0, utils_1.decorateWithExplain)(findCommand, this.explain);
  10873. }
  10874. server.command(this.ns, findCommand, {
  10875. ...this.options,
  10876. ...this.bsonOptions,
  10877. documentsReturnedIn: "firstBatch",
  10878. session
  10879. }, callback);
  10880. }
  10881. };
  10882. __name(_FindOperation, "FindOperation");
  10883. var FindOperation = _FindOperation;
  10884. exports2.FindOperation = FindOperation;
  10885. function makeFindCommand(ns, filter, options) {
  10886. const findCommand = {
  10887. find: ns.collection,
  10888. filter
  10889. };
  10890. if (options.sort) {
  10891. findCommand.sort = (0, sort_1.formatSort)(options.sort);
  10892. }
  10893. if (options.projection) {
  10894. let projection = options.projection;
  10895. if (projection && Array.isArray(projection)) {
  10896. projection = projection.length ? projection.reduce((result, field) => {
  10897. result[field] = 1;
  10898. return result;
  10899. }, {}) : { _id: 1 };
  10900. }
  10901. findCommand.projection = projection;
  10902. }
  10903. if (options.hint) {
  10904. findCommand.hint = (0, utils_1.normalizeHintField)(options.hint);
  10905. }
  10906. if (typeof options.skip === "number") {
  10907. findCommand.skip = options.skip;
  10908. }
  10909. if (typeof options.limit === "number") {
  10910. if (options.limit < 0) {
  10911. findCommand.limit = -options.limit;
  10912. findCommand.singleBatch = true;
  10913. } else {
  10914. findCommand.limit = options.limit;
  10915. }
  10916. }
  10917. if (typeof options.batchSize === "number") {
  10918. if (options.batchSize < 0) {
  10919. if (options.limit && options.limit !== 0 && Math.abs(options.batchSize) < Math.abs(options.limit)) {
  10920. findCommand.limit = -options.batchSize;
  10921. }
  10922. findCommand.singleBatch = true;
  10923. } else {
  10924. findCommand.batchSize = options.batchSize;
  10925. }
  10926. }
  10927. if (typeof options.singleBatch === "boolean") {
  10928. findCommand.singleBatch = options.singleBatch;
  10929. }
  10930. if (options.comment !== void 0) {
  10931. findCommand.comment = options.comment;
  10932. }
  10933. if (typeof options.maxTimeMS === "number") {
  10934. findCommand.maxTimeMS = options.maxTimeMS;
  10935. }
  10936. const readConcern = read_concern_1.ReadConcern.fromOptions(options);
  10937. if (readConcern) {
  10938. findCommand.readConcern = readConcern.toJSON();
  10939. }
  10940. if (options.max) {
  10941. findCommand.max = options.max;
  10942. }
  10943. if (options.min) {
  10944. findCommand.min = options.min;
  10945. }
  10946. if (typeof options.returnKey === "boolean") {
  10947. findCommand.returnKey = options.returnKey;
  10948. }
  10949. if (typeof options.showRecordId === "boolean") {
  10950. findCommand.showRecordId = options.showRecordId;
  10951. }
  10952. if (typeof options.tailable === "boolean") {
  10953. findCommand.tailable = options.tailable;
  10954. }
  10955. if (typeof options.oplogReplay === "boolean") {
  10956. findCommand.oplogReplay = options.oplogReplay;
  10957. }
  10958. if (typeof options.timeout === "boolean") {
  10959. findCommand.noCursorTimeout = !options.timeout;
  10960. } else if (typeof options.noCursorTimeout === "boolean") {
  10961. findCommand.noCursorTimeout = options.noCursorTimeout;
  10962. }
  10963. if (typeof options.awaitData === "boolean") {
  10964. findCommand.awaitData = options.awaitData;
  10965. }
  10966. if (typeof options.allowPartialResults === "boolean") {
  10967. findCommand.allowPartialResults = options.allowPartialResults;
  10968. }
  10969. if (options.collation) {
  10970. findCommand.collation = options.collation;
  10971. }
  10972. if (typeof options.allowDiskUse === "boolean") {
  10973. findCommand.allowDiskUse = options.allowDiskUse;
  10974. }
  10975. if (options.let) {
  10976. findCommand.let = options.let;
  10977. }
  10978. return findCommand;
  10979. }
  10980. __name(makeFindCommand, "makeFindCommand");
  10981. (0, operation_1.defineAspects)(FindOperation, [
  10982. operation_1.Aspect.READ_OPERATION,
  10983. operation_1.Aspect.RETRYABLE,
  10984. operation_1.Aspect.EXPLAINABLE,
  10985. operation_1.Aspect.CURSOR_CREATING
  10986. ]);
  10987. }
  10988. });
  10989. // node_modules/mongodb/lib/cursor/find_cursor.js
  10990. var require_find_cursor = __commonJS({
  10991. "node_modules/mongodb/lib/cursor/find_cursor.js"(exports2) {
  10992. "use strict";
  10993. Object.defineProperty(exports2, "__esModule", { value: true });
  10994. exports2.FindCursor = exports2.FLAGS = void 0;
  10995. var bson_1 = require_bson2();
  10996. var error_1 = require_error();
  10997. var count_1 = require_count();
  10998. var execute_operation_1 = require_execute_operation();
  10999. var find_1 = require_find();
  11000. var sort_1 = require_sort();
  11001. var utils_1 = require_utils();
  11002. var abstract_cursor_1 = require_abstract_cursor();
  11003. var kFilter = Symbol("filter");
  11004. var kNumReturned = Symbol("numReturned");
  11005. var kBuiltOptions = Symbol("builtOptions");
  11006. exports2.FLAGS = [
  11007. "tailable",
  11008. "oplogReplay",
  11009. "noCursorTimeout",
  11010. "awaitData",
  11011. "exhaust",
  11012. "partial"
  11013. ];
  11014. var _FindCursor = class _FindCursor extends abstract_cursor_1.AbstractCursor {
  11015. /** @internal */
  11016. constructor(client, namespace, filter = {}, options = {}) {
  11017. super(client, namespace, options);
  11018. this[kFilter] = filter;
  11019. this[kBuiltOptions] = options;
  11020. if (options.sort != null) {
  11021. this[kBuiltOptions].sort = (0, sort_1.formatSort)(options.sort);
  11022. }
  11023. }
  11024. clone() {
  11025. const clonedOptions = (0, utils_1.mergeOptions)({}, this[kBuiltOptions]);
  11026. delete clonedOptions.session;
  11027. return new _FindCursor(this.client, this.namespace, this[kFilter], {
  11028. ...clonedOptions
  11029. });
  11030. }
  11031. map(transform) {
  11032. return super.map(transform);
  11033. }
  11034. /** @internal */
  11035. _initialize(session, callback) {
  11036. const findOperation = new find_1.FindOperation(void 0, this.namespace, this[kFilter], {
  11037. ...this[kBuiltOptions],
  11038. ...this.cursorOptions,
  11039. session
  11040. });
  11041. (0, execute_operation_1.executeOperation)(this.client, findOperation, (err, response) => {
  11042. if (err || response == null)
  11043. return callback(err);
  11044. if (response.cursor) {
  11045. this[kNumReturned] = response.cursor.firstBatch.length;
  11046. } else {
  11047. this[kNumReturned] = response.documents ? response.documents.length : 0;
  11048. }
  11049. callback(void 0, { server: findOperation.server, session, response });
  11050. });
  11051. }
  11052. /** @internal */
  11053. _getMore(batchSize, callback) {
  11054. const numReturned = this[kNumReturned];
  11055. if (numReturned) {
  11056. const limit = this[kBuiltOptions].limit;
  11057. batchSize = limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize;
  11058. if (batchSize <= 0) {
  11059. this.close().finally(() => callback(void 0, { cursor: { id: bson_1.Long.ZERO, nextBatch: [] } }));
  11060. return;
  11061. }
  11062. }
  11063. super._getMore(batchSize, (err, response) => {
  11064. if (err)
  11065. return callback(err);
  11066. if (response) {
  11067. this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length;
  11068. }
  11069. callback(void 0, response);
  11070. });
  11071. }
  11072. /**
  11073. * Get the count of documents for this cursor
  11074. * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead
  11075. */
  11076. async count(options) {
  11077. (0, utils_1.emitWarningOnce)("cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead ");
  11078. if (typeof options === "boolean") {
  11079. throw new error_1.MongoInvalidArgumentError("Invalid first parameter to count");
  11080. }
  11081. return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this[kFilter], {
  11082. ...this[kBuiltOptions],
  11083. ...this.cursorOptions,
  11084. ...options
  11085. }));
  11086. }
  11087. /** Execute the explain for the cursor */
  11088. async explain(verbosity) {
  11089. return (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(void 0, this.namespace, this[kFilter], {
  11090. ...this[kBuiltOptions],
  11091. ...this.cursorOptions,
  11092. explain: verbosity ?? true
  11093. }));
  11094. }
  11095. /** Set the cursor query */
  11096. filter(filter) {
  11097. (0, abstract_cursor_1.assertUninitialized)(this);
  11098. this[kFilter] = filter;
  11099. return this;
  11100. }
  11101. /**
  11102. * Set the cursor hint
  11103. *
  11104. * @param hint - If specified, then the query system will only consider plans using the hinted index.
  11105. */
  11106. hint(hint) {
  11107. (0, abstract_cursor_1.assertUninitialized)(this);
  11108. this[kBuiltOptions].hint = hint;
  11109. return this;
  11110. }
  11111. /**
  11112. * Set the cursor min
  11113. *
  11114. * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.
  11115. */
  11116. min(min) {
  11117. (0, abstract_cursor_1.assertUninitialized)(this);
  11118. this[kBuiltOptions].min = min;
  11119. return this;
  11120. }
  11121. /**
  11122. * Set the cursor max
  11123. *
  11124. * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.
  11125. */
  11126. max(max) {
  11127. (0, abstract_cursor_1.assertUninitialized)(this);
  11128. this[kBuiltOptions].max = max;
  11129. return this;
  11130. }
  11131. /**
  11132. * Set the cursor returnKey.
  11133. * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents.
  11134. * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields.
  11135. *
  11136. * @param value - the returnKey value.
  11137. */
  11138. returnKey(value) {
  11139. (0, abstract_cursor_1.assertUninitialized)(this);
  11140. this[kBuiltOptions].returnKey = value;
  11141. return this;
  11142. }
  11143. /**
  11144. * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection.
  11145. *
  11146. * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.
  11147. */
  11148. showRecordId(value) {
  11149. (0, abstract_cursor_1.assertUninitialized)(this);
  11150. this[kBuiltOptions].showRecordId = value;
  11151. return this;
  11152. }
  11153. /**
  11154. * Add a query modifier to the cursor query
  11155. *
  11156. * @param name - The query modifier (must start with $, such as $orderby etc)
  11157. * @param value - The modifier value.
  11158. */
  11159. addQueryModifier(name, value) {
  11160. (0, abstract_cursor_1.assertUninitialized)(this);
  11161. if (name[0] !== "$") {
  11162. throw new error_1.MongoInvalidArgumentError(`${name} is not a valid query modifier`);
  11163. }
  11164. const field = name.substr(1);
  11165. switch (field) {
  11166. case "comment":
  11167. this[kBuiltOptions].comment = value;
  11168. break;
  11169. case "explain":
  11170. this[kBuiltOptions].explain = value;
  11171. break;
  11172. case "hint":
  11173. this[kBuiltOptions].hint = value;
  11174. break;
  11175. case "max":
  11176. this[kBuiltOptions].max = value;
  11177. break;
  11178. case "maxTimeMS":
  11179. this[kBuiltOptions].maxTimeMS = value;
  11180. break;
  11181. case "min":
  11182. this[kBuiltOptions].min = value;
  11183. break;
  11184. case "orderby":
  11185. this[kBuiltOptions].sort = (0, sort_1.formatSort)(value);
  11186. break;
  11187. case "query":
  11188. this[kFilter] = value;
  11189. break;
  11190. case "returnKey":
  11191. this[kBuiltOptions].returnKey = value;
  11192. break;
  11193. case "showDiskLoc":
  11194. this[kBuiltOptions].showRecordId = value;
  11195. break;
  11196. default:
  11197. throw new error_1.MongoInvalidArgumentError(`Invalid query modifier: ${name}`);
  11198. }
  11199. return this;
  11200. }
  11201. /**
  11202. * Add a comment to the cursor query allowing for tracking the comment in the log.
  11203. *
  11204. * @param value - The comment attached to this query.
  11205. */
  11206. comment(value) {
  11207. (0, abstract_cursor_1.assertUninitialized)(this);
  11208. this[kBuiltOptions].comment = value;
  11209. return this;
  11210. }
  11211. /**
  11212. * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
  11213. *
  11214. * @param value - Number of milliseconds to wait before aborting the tailed query.
  11215. */
  11216. maxAwaitTimeMS(value) {
  11217. (0, abstract_cursor_1.assertUninitialized)(this);
  11218. if (typeof value !== "number") {
  11219. throw new error_1.MongoInvalidArgumentError("Argument for maxAwaitTimeMS must be a number");
  11220. }
  11221. this[kBuiltOptions].maxAwaitTimeMS = value;
  11222. return this;
  11223. }
  11224. /**
  11225. * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
  11226. *
  11227. * @param value - Number of milliseconds to wait before aborting the query.
  11228. */
  11229. maxTimeMS(value) {
  11230. (0, abstract_cursor_1.assertUninitialized)(this);
  11231. if (typeof value !== "number") {
  11232. throw new error_1.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");
  11233. }
  11234. this[kBuiltOptions].maxTimeMS = value;
  11235. return this;
  11236. }
  11237. /**
  11238. * Add a project stage to the aggregation pipeline
  11239. *
  11240. * @remarks
  11241. * In order to strictly type this function you must provide an interface
  11242. * that represents the effect of your projection on the result documents.
  11243. *
  11244. * By default chaining a projection to your cursor changes the returned type to the generic
  11245. * {@link Document} type.
  11246. * You should specify a parameterized type to have assertions on your final results.
  11247. *
  11248. * @example
  11249. * ```typescript
  11250. * // Best way
  11251. * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
  11252. * // Flexible way
  11253. * const docs: FindCursor<Document> = cursor.project({ _id: 0, a: true });
  11254. * ```
  11255. *
  11256. * @remarks
  11257. *
  11258. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  11259. * it **does not** return a new instance of a cursor. This means when calling project,
  11260. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  11261. * Take note of the following example:
  11262. *
  11263. * @example
  11264. * ```typescript
  11265. * const cursor: FindCursor<{ a: number; b: string }> = coll.find();
  11266. * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
  11267. * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
  11268. *
  11269. * // or always use chaining and save the final cursor
  11270. *
  11271. * const cursor = coll.find().project<{ a: string }>({
  11272. * _id: 0,
  11273. * a: { $convert: { input: '$a', to: 'string' }
  11274. * }});
  11275. * ```
  11276. */
  11277. project(value) {
  11278. (0, abstract_cursor_1.assertUninitialized)(this);
  11279. this[kBuiltOptions].projection = value;
  11280. return this;
  11281. }
  11282. /**
  11283. * Sets the sort order of the cursor query.
  11284. *
  11285. * @param sort - The key or keys set for the sort.
  11286. * @param direction - The direction of the sorting (1 or -1).
  11287. */
  11288. sort(sort, direction) {
  11289. (0, abstract_cursor_1.assertUninitialized)(this);
  11290. if (this[kBuiltOptions].tailable) {
  11291. throw new error_1.MongoTailableCursorError("Tailable cursor does not support sorting");
  11292. }
  11293. this[kBuiltOptions].sort = (0, sort_1.formatSort)(sort, direction);
  11294. return this;
  11295. }
  11296. /**
  11297. * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher)
  11298. *
  11299. * @remarks
  11300. * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation}
  11301. */
  11302. allowDiskUse(allow = true) {
  11303. (0, abstract_cursor_1.assertUninitialized)(this);
  11304. if (!this[kBuiltOptions].sort) {
  11305. throw new error_1.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification');
  11306. }
  11307. if (!allow) {
  11308. this[kBuiltOptions].allowDiskUse = false;
  11309. return this;
  11310. }
  11311. this[kBuiltOptions].allowDiskUse = true;
  11312. return this;
  11313. }
  11314. /**
  11315. * Set the collation options for the cursor.
  11316. *
  11317. * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  11318. */
  11319. collation(value) {
  11320. (0, abstract_cursor_1.assertUninitialized)(this);
  11321. this[kBuiltOptions].collation = value;
  11322. return this;
  11323. }
  11324. /**
  11325. * Set the limit for the cursor.
  11326. *
  11327. * @param value - The limit for the cursor query.
  11328. */
  11329. limit(value) {
  11330. (0, abstract_cursor_1.assertUninitialized)(this);
  11331. if (this[kBuiltOptions].tailable) {
  11332. throw new error_1.MongoTailableCursorError("Tailable cursor does not support limit");
  11333. }
  11334. if (typeof value !== "number") {
  11335. throw new error_1.MongoInvalidArgumentError('Operation "limit" requires an integer');
  11336. }
  11337. this[kBuiltOptions].limit = value;
  11338. return this;
  11339. }
  11340. /**
  11341. * Set the skip for the cursor.
  11342. *
  11343. * @param value - The skip for the cursor query.
  11344. */
  11345. skip(value) {
  11346. (0, abstract_cursor_1.assertUninitialized)(this);
  11347. if (this[kBuiltOptions].tailable) {
  11348. throw new error_1.MongoTailableCursorError("Tailable cursor does not support skip");
  11349. }
  11350. if (typeof value !== "number") {
  11351. throw new error_1.MongoInvalidArgumentError('Operation "skip" requires an integer');
  11352. }
  11353. this[kBuiltOptions].skip = value;
  11354. return this;
  11355. }
  11356. };
  11357. __name(_FindCursor, "FindCursor");
  11358. var FindCursor = _FindCursor;
  11359. exports2.FindCursor = FindCursor;
  11360. }
  11361. });
  11362. // node_modules/mongodb/lib/operations/indexes.js
  11363. var require_indexes = __commonJS({
  11364. "node_modules/mongodb/lib/operations/indexes.js"(exports2) {
  11365. "use strict";
  11366. Object.defineProperty(exports2, "__esModule", { value: true });
  11367. exports2.IndexInformationOperation = exports2.IndexExistsOperation = exports2.ListIndexesOperation = exports2.DropIndexesOperation = exports2.DropIndexOperation = exports2.EnsureIndexOperation = exports2.CreateIndexOperation = exports2.CreateIndexesOperation = exports2.IndexesOperation = void 0;
  11368. var error_1 = require_error();
  11369. var read_preference_1 = require_read_preference();
  11370. var utils_1 = require_utils();
  11371. var command_1 = require_command();
  11372. var common_functions_1 = require_common_functions();
  11373. var operation_1 = require_operation();
  11374. var VALID_INDEX_OPTIONS = /* @__PURE__ */ new Set([
  11375. "background",
  11376. "unique",
  11377. "name",
  11378. "partialFilterExpression",
  11379. "sparse",
  11380. "hidden",
  11381. "expireAfterSeconds",
  11382. "storageEngine",
  11383. "collation",
  11384. "version",
  11385. // text indexes
  11386. "weights",
  11387. "default_language",
  11388. "language_override",
  11389. "textIndexVersion",
  11390. // 2d-sphere indexes
  11391. "2dsphereIndexVersion",
  11392. // 2d indexes
  11393. "bits",
  11394. "min",
  11395. "max",
  11396. // geoHaystack Indexes
  11397. "bucketSize",
  11398. // wildcard indexes
  11399. "wildcardProjection"
  11400. ]);
  11401. function isIndexDirection(x) {
  11402. return typeof x === "number" || x === "2d" || x === "2dsphere" || x === "text" || x === "geoHaystack";
  11403. }
  11404. __name(isIndexDirection, "isIndexDirection");
  11405. function isSingleIndexTuple(t) {
  11406. return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]);
  11407. }
  11408. __name(isSingleIndexTuple, "isSingleIndexTuple");
  11409. function makeIndexSpec(indexSpec, options) {
  11410. const key = /* @__PURE__ */ new Map();
  11411. const indexSpecs = !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec;
  11412. for (const spec of indexSpecs) {
  11413. if (typeof spec === "string") {
  11414. key.set(spec, 1);
  11415. } else if (Array.isArray(spec)) {
  11416. key.set(spec[0], spec[1] ?? 1);
  11417. } else if (spec instanceof Map) {
  11418. for (const [property, value] of spec) {
  11419. key.set(property, value);
  11420. }
  11421. } else if ((0, utils_1.isObject)(spec)) {
  11422. for (const [property, value] of Object.entries(spec)) {
  11423. key.set(property, value);
  11424. }
  11425. }
  11426. }
  11427. return { ...options, key };
  11428. }
  11429. __name(makeIndexSpec, "makeIndexSpec");
  11430. var _IndexesOperation = class _IndexesOperation extends operation_1.AbstractCallbackOperation {
  11431. constructor(collection, options) {
  11432. super(options);
  11433. this.options = options;
  11434. this.collection = collection;
  11435. }
  11436. executeCallback(server, session, callback) {
  11437. const coll = this.collection;
  11438. const options = this.options;
  11439. (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, { full: true, ...options, readPreference: this.readPreference, session }, callback);
  11440. }
  11441. };
  11442. __name(_IndexesOperation, "IndexesOperation");
  11443. var IndexesOperation = _IndexesOperation;
  11444. exports2.IndexesOperation = IndexesOperation;
  11445. var _CreateIndexesOperation = class _CreateIndexesOperation extends command_1.CommandCallbackOperation {
  11446. constructor(parent, collectionName, indexes, options) {
  11447. super(parent, options);
  11448. this.options = options ?? {};
  11449. this.collectionName = collectionName;
  11450. this.indexes = indexes.map((userIndex) => {
  11451. const key = userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key));
  11452. const name = userIndex.name != null ? userIndex.name : Array.from(key).flat().join("_");
  11453. const validIndexOptions = Object.fromEntries(Object.entries({ ...userIndex }).filter(([optionName]) => VALID_INDEX_OPTIONS.has(optionName)));
  11454. return {
  11455. ...validIndexOptions,
  11456. name,
  11457. key
  11458. };
  11459. });
  11460. }
  11461. executeCallback(server, session, callback) {
  11462. const options = this.options;
  11463. const indexes = this.indexes;
  11464. const serverWireVersion = (0, utils_1.maxWireVersion)(server);
  11465. const cmd = { createIndexes: this.collectionName, indexes };
  11466. if (options.commitQuorum != null) {
  11467. if (serverWireVersion < 9) {
  11468. callback(new error_1.MongoCompatibilityError("Option `commitQuorum` for `createIndexes` not supported on servers < 4.4"));
  11469. return;
  11470. }
  11471. cmd.commitQuorum = options.commitQuorum;
  11472. }
  11473. this.options.collation = void 0;
  11474. super.executeCommandCallback(server, session, cmd, (err) => {
  11475. if (err) {
  11476. callback(err);
  11477. return;
  11478. }
  11479. const indexNames = indexes.map((index) => index.name || "");
  11480. callback(void 0, indexNames);
  11481. });
  11482. }
  11483. };
  11484. __name(_CreateIndexesOperation, "CreateIndexesOperation");
  11485. var CreateIndexesOperation = _CreateIndexesOperation;
  11486. exports2.CreateIndexesOperation = CreateIndexesOperation;
  11487. var _CreateIndexOperation = class _CreateIndexOperation extends CreateIndexesOperation {
  11488. constructor(parent, collectionName, indexSpec, options) {
  11489. super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options);
  11490. }
  11491. executeCallback(server, session, callback) {
  11492. super.executeCallback(server, session, (err, indexNames) => {
  11493. if (err || !indexNames)
  11494. return callback(err);
  11495. return callback(void 0, indexNames[0]);
  11496. });
  11497. }
  11498. };
  11499. __name(_CreateIndexOperation, "CreateIndexOperation");
  11500. var CreateIndexOperation = _CreateIndexOperation;
  11501. exports2.CreateIndexOperation = CreateIndexOperation;
  11502. var _EnsureIndexOperation = class _EnsureIndexOperation extends CreateIndexOperation {
  11503. constructor(db, collectionName, indexSpec, options) {
  11504. super(db, collectionName, indexSpec, options);
  11505. this.readPreference = read_preference_1.ReadPreference.primary;
  11506. this.db = db;
  11507. this.collectionName = collectionName;
  11508. }
  11509. executeCallback(server, session, callback) {
  11510. const indexName = this.indexes[0].name;
  11511. const cursor = this.db.collection(this.collectionName).listIndexes({ session });
  11512. cursor.toArray().then((indexes) => {
  11513. indexes = Array.isArray(indexes) ? indexes : [indexes];
  11514. if (indexes.some((index) => index.name === indexName)) {
  11515. callback(void 0, indexName);
  11516. return;
  11517. }
  11518. super.executeCallback(server, session, callback);
  11519. }, (error) => {
  11520. if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
  11521. return super.executeCallback(server, session, callback);
  11522. }
  11523. return callback(error);
  11524. });
  11525. }
  11526. };
  11527. __name(_EnsureIndexOperation, "EnsureIndexOperation");
  11528. var EnsureIndexOperation = _EnsureIndexOperation;
  11529. exports2.EnsureIndexOperation = EnsureIndexOperation;
  11530. var _DropIndexOperation = class _DropIndexOperation extends command_1.CommandCallbackOperation {
  11531. constructor(collection, indexName, options) {
  11532. super(collection, options);
  11533. this.options = options ?? {};
  11534. this.collection = collection;
  11535. this.indexName = indexName;
  11536. }
  11537. executeCallback(server, session, callback) {
  11538. const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName };
  11539. super.executeCommandCallback(server, session, cmd, callback);
  11540. }
  11541. };
  11542. __name(_DropIndexOperation, "DropIndexOperation");
  11543. var DropIndexOperation = _DropIndexOperation;
  11544. exports2.DropIndexOperation = DropIndexOperation;
  11545. var _DropIndexesOperation = class _DropIndexesOperation extends DropIndexOperation {
  11546. constructor(collection, options) {
  11547. super(collection, "*", options);
  11548. }
  11549. executeCallback(server, session, callback) {
  11550. super.executeCallback(server, session, (err) => {
  11551. if (err)
  11552. return callback(err, false);
  11553. callback(void 0, true);
  11554. });
  11555. }
  11556. };
  11557. __name(_DropIndexesOperation, "DropIndexesOperation");
  11558. var DropIndexesOperation = _DropIndexesOperation;
  11559. exports2.DropIndexesOperation = DropIndexesOperation;
  11560. var _ListIndexesOperation = class _ListIndexesOperation extends command_1.CommandCallbackOperation {
  11561. constructor(collection, options) {
  11562. super(collection, options);
  11563. this.options = { ...options };
  11564. delete this.options.writeConcern;
  11565. this.collectionNamespace = collection.s.namespace;
  11566. }
  11567. executeCallback(server, session, callback) {
  11568. const serverWireVersion = (0, utils_1.maxWireVersion)(server);
  11569. const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {};
  11570. const command = { listIndexes: this.collectionNamespace.collection, cursor };
  11571. if (serverWireVersion >= 9 && this.options.comment !== void 0) {
  11572. command.comment = this.options.comment;
  11573. }
  11574. super.executeCommandCallback(server, session, command, callback);
  11575. }
  11576. };
  11577. __name(_ListIndexesOperation, "ListIndexesOperation");
  11578. var ListIndexesOperation = _ListIndexesOperation;
  11579. exports2.ListIndexesOperation = ListIndexesOperation;
  11580. var _IndexExistsOperation = class _IndexExistsOperation extends operation_1.AbstractCallbackOperation {
  11581. constructor(collection, indexes, options) {
  11582. super(options);
  11583. this.options = options;
  11584. this.collection = collection;
  11585. this.indexes = indexes;
  11586. }
  11587. executeCallback(server, session, callback) {
  11588. const coll = this.collection;
  11589. const indexes = this.indexes;
  11590. (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, { ...this.options, readPreference: this.readPreference, session }, (err, indexInformation) => {
  11591. if (err != null)
  11592. return callback(err);
  11593. if (!Array.isArray(indexes))
  11594. return callback(void 0, indexInformation[indexes] != null);
  11595. for (let i = 0; i < indexes.length; i++) {
  11596. if (indexInformation[indexes[i]] == null) {
  11597. return callback(void 0, false);
  11598. }
  11599. }
  11600. return callback(void 0, true);
  11601. });
  11602. }
  11603. };
  11604. __name(_IndexExistsOperation, "IndexExistsOperation");
  11605. var IndexExistsOperation = _IndexExistsOperation;
  11606. exports2.IndexExistsOperation = IndexExistsOperation;
  11607. var _IndexInformationOperation = class _IndexInformationOperation extends operation_1.AbstractCallbackOperation {
  11608. constructor(db, name, options) {
  11609. super(options);
  11610. this.options = options ?? {};
  11611. this.db = db;
  11612. this.name = name;
  11613. }
  11614. executeCallback(server, session, callback) {
  11615. const db = this.db;
  11616. const name = this.name;
  11617. (0, common_functions_1.indexInformation)(db, name, { ...this.options, readPreference: this.readPreference, session }, callback);
  11618. }
  11619. };
  11620. __name(_IndexInformationOperation, "IndexInformationOperation");
  11621. var IndexInformationOperation = _IndexInformationOperation;
  11622. exports2.IndexInformationOperation = IndexInformationOperation;
  11623. (0, operation_1.defineAspects)(ListIndexesOperation, [
  11624. operation_1.Aspect.READ_OPERATION,
  11625. operation_1.Aspect.RETRYABLE,
  11626. operation_1.Aspect.CURSOR_CREATING
  11627. ]);
  11628. (0, operation_1.defineAspects)(CreateIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]);
  11629. (0, operation_1.defineAspects)(CreateIndexOperation, [operation_1.Aspect.WRITE_OPERATION]);
  11630. (0, operation_1.defineAspects)(EnsureIndexOperation, [operation_1.Aspect.WRITE_OPERATION]);
  11631. (0, operation_1.defineAspects)(DropIndexOperation, [operation_1.Aspect.WRITE_OPERATION]);
  11632. (0, operation_1.defineAspects)(DropIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]);
  11633. }
  11634. });
  11635. // node_modules/mongodb/lib/cursor/list_indexes_cursor.js
  11636. var require_list_indexes_cursor = __commonJS({
  11637. "node_modules/mongodb/lib/cursor/list_indexes_cursor.js"(exports2) {
  11638. "use strict";
  11639. Object.defineProperty(exports2, "__esModule", { value: true });
  11640. exports2.ListIndexesCursor = void 0;
  11641. var execute_operation_1 = require_execute_operation();
  11642. var indexes_1 = require_indexes();
  11643. var abstract_cursor_1 = require_abstract_cursor();
  11644. var _ListIndexesCursor = class _ListIndexesCursor extends abstract_cursor_1.AbstractCursor {
  11645. constructor(collection, options) {
  11646. super(collection.client, collection.s.namespace, options);
  11647. this.parent = collection;
  11648. this.options = options;
  11649. }
  11650. clone() {
  11651. return new _ListIndexesCursor(this.parent, {
  11652. ...this.options,
  11653. ...this.cursorOptions
  11654. });
  11655. }
  11656. /** @internal */
  11657. _initialize(session, callback) {
  11658. const operation = new indexes_1.ListIndexesOperation(this.parent, {
  11659. ...this.cursorOptions,
  11660. ...this.options,
  11661. session
  11662. });
  11663. (0, execute_operation_1.executeOperation)(this.parent.client, operation, (err, response) => {
  11664. if (err || response == null)
  11665. return callback(err);
  11666. callback(void 0, { server: operation.server, session, response });
  11667. });
  11668. }
  11669. };
  11670. __name(_ListIndexesCursor, "ListIndexesCursor");
  11671. var ListIndexesCursor = _ListIndexesCursor;
  11672. exports2.ListIndexesCursor = ListIndexesCursor;
  11673. }
  11674. });
  11675. // node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js
  11676. var require_list_search_indexes_cursor = __commonJS({
  11677. "node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js"(exports2) {
  11678. "use strict";
  11679. Object.defineProperty(exports2, "__esModule", { value: true });
  11680. exports2.ListSearchIndexesCursor = void 0;
  11681. var aggregation_cursor_1 = require_aggregation_cursor();
  11682. var _ListSearchIndexesCursor = class _ListSearchIndexesCursor extends aggregation_cursor_1.AggregationCursor {
  11683. /** @internal */
  11684. constructor({ fullNamespace: ns, client }, name, options = {}) {
  11685. const pipeline = name == null ? [{ $listSearchIndexes: {} }] : [{ $listSearchIndexes: { name } }];
  11686. super(client, ns, pipeline, options);
  11687. }
  11688. };
  11689. __name(_ListSearchIndexesCursor, "ListSearchIndexesCursor");
  11690. var ListSearchIndexesCursor = _ListSearchIndexesCursor;
  11691. exports2.ListSearchIndexesCursor = ListSearchIndexesCursor;
  11692. }
  11693. });
  11694. // node_modules/mongodb/lib/operations/count_documents.js
  11695. var require_count_documents = __commonJS({
  11696. "node_modules/mongodb/lib/operations/count_documents.js"(exports2) {
  11697. "use strict";
  11698. Object.defineProperty(exports2, "__esModule", { value: true });
  11699. exports2.CountDocumentsOperation = void 0;
  11700. var aggregate_1 = require_aggregate();
  11701. var _CountDocumentsOperation = class _CountDocumentsOperation extends aggregate_1.AggregateOperation {
  11702. constructor(collection, query, options) {
  11703. const pipeline = [];
  11704. pipeline.push({ $match: query });
  11705. if (typeof options.skip === "number") {
  11706. pipeline.push({ $skip: options.skip });
  11707. }
  11708. if (typeof options.limit === "number") {
  11709. pipeline.push({ $limit: options.limit });
  11710. }
  11711. pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });
  11712. super(collection.s.namespace, pipeline, options);
  11713. }
  11714. executeCallback(server, session, callback) {
  11715. super.executeCallback(server, session, (err, result) => {
  11716. if (err || !result) {
  11717. callback(err);
  11718. return;
  11719. }
  11720. const response = result;
  11721. if (response.cursor == null || response.cursor.firstBatch == null) {
  11722. callback(void 0, 0);
  11723. return;
  11724. }
  11725. const docs = response.cursor.firstBatch;
  11726. callback(void 0, docs.length ? docs[0].n : 0);
  11727. });
  11728. }
  11729. };
  11730. __name(_CountDocumentsOperation, "CountDocumentsOperation");
  11731. var CountDocumentsOperation = _CountDocumentsOperation;
  11732. exports2.CountDocumentsOperation = CountDocumentsOperation;
  11733. }
  11734. });
  11735. // node_modules/mongodb/lib/operations/distinct.js
  11736. var require_distinct = __commonJS({
  11737. "node_modules/mongodb/lib/operations/distinct.js"(exports2) {
  11738. "use strict";
  11739. Object.defineProperty(exports2, "__esModule", { value: true });
  11740. exports2.DistinctOperation = void 0;
  11741. var utils_1 = require_utils();
  11742. var command_1 = require_command();
  11743. var operation_1 = require_operation();
  11744. var _DistinctOperation = class _DistinctOperation extends command_1.CommandCallbackOperation {
  11745. /**
  11746. * Construct a Distinct operation.
  11747. *
  11748. * @param collection - Collection instance.
  11749. * @param key - Field of the document to find distinct values for.
  11750. * @param query - The query for filtering the set of documents to which we apply the distinct filter.
  11751. * @param options - Optional settings. See Collection.prototype.distinct for a list of options.
  11752. */
  11753. constructor(collection, key, query, options) {
  11754. super(collection, options);
  11755. this.options = options ?? {};
  11756. this.collection = collection;
  11757. this.key = key;
  11758. this.query = query;
  11759. }
  11760. executeCallback(server, session, callback) {
  11761. const coll = this.collection;
  11762. const key = this.key;
  11763. const query = this.query;
  11764. const options = this.options;
  11765. const cmd = {
  11766. distinct: coll.collectionName,
  11767. key,
  11768. query
  11769. };
  11770. if (typeof options.maxTimeMS === "number") {
  11771. cmd.maxTimeMS = options.maxTimeMS;
  11772. }
  11773. if (typeof options.comment !== "undefined") {
  11774. cmd.comment = options.comment;
  11775. }
  11776. (0, utils_1.decorateWithReadConcern)(cmd, coll, options);
  11777. try {
  11778. (0, utils_1.decorateWithCollation)(cmd, coll, options);
  11779. } catch (err) {
  11780. return callback(err);
  11781. }
  11782. super.executeCommandCallback(server, session, cmd, (err, result) => {
  11783. if (err) {
  11784. callback(err);
  11785. return;
  11786. }
  11787. callback(void 0, this.explain ? result : result.values);
  11788. });
  11789. }
  11790. };
  11791. __name(_DistinctOperation, "DistinctOperation");
  11792. var DistinctOperation = _DistinctOperation;
  11793. exports2.DistinctOperation = DistinctOperation;
  11794. (0, operation_1.defineAspects)(DistinctOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE]);
  11795. }
  11796. });
  11797. // node_modules/mongodb/lib/operations/drop.js
  11798. var require_drop = __commonJS({
  11799. "node_modules/mongodb/lib/operations/drop.js"(exports2) {
  11800. "use strict";
  11801. Object.defineProperty(exports2, "__esModule", { value: true });
  11802. exports2.DropDatabaseOperation = exports2.DropCollectionOperation = void 0;
  11803. var error_1 = require_error();
  11804. var command_1 = require_command();
  11805. var operation_1 = require_operation();
  11806. var _DropCollectionOperation = class _DropCollectionOperation extends command_1.CommandCallbackOperation {
  11807. constructor(db, name, options = {}) {
  11808. super(db, options);
  11809. this.db = db;
  11810. this.options = options;
  11811. this.name = name;
  11812. }
  11813. executeCallback(server, session, callback) {
  11814. (async () => {
  11815. var _a, _b, _c;
  11816. const db = this.db;
  11817. const options = this.options;
  11818. const name = this.name;
  11819. const encryptedFieldsMap = (_a = db.client.options.autoEncryption) == null ? void 0 : _a.encryptedFieldsMap;
  11820. let encryptedFields = options.encryptedFields ?? (encryptedFieldsMap == null ? void 0 : encryptedFieldsMap[`${db.databaseName}.${name}`]);
  11821. if (!encryptedFields && encryptedFieldsMap) {
  11822. const listCollectionsResult = await db.listCollections({ name }, { nameOnly: false }).toArray();
  11823. encryptedFields = (_c = (_b = listCollectionsResult == null ? void 0 : listCollectionsResult[0]) == null ? void 0 : _b.options) == null ? void 0 : _c.encryptedFields;
  11824. }
  11825. if (encryptedFields) {
  11826. const escCollection = encryptedFields.escCollection || `enxcol_.${name}.esc`;
  11827. const ecocCollection = encryptedFields.ecocCollection || `enxcol_.${name}.ecoc`;
  11828. for (const collectionName of [escCollection, ecocCollection]) {
  11829. const dropOp = new _DropCollectionOperation(db, collectionName);
  11830. try {
  11831. await dropOp.executeWithoutEncryptedFieldsCheck(server, session);
  11832. } catch (err) {
  11833. if (!(err instanceof error_1.MongoServerError) || err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
  11834. throw err;
  11835. }
  11836. }
  11837. }
  11838. }
  11839. return this.executeWithoutEncryptedFieldsCheck(server, session);
  11840. })().then((result) => callback(void 0, result), (err) => callback(err));
  11841. }
  11842. executeWithoutEncryptedFieldsCheck(server, session) {
  11843. return new Promise((resolve, reject) => {
  11844. super.executeCommandCallback(server, session, { drop: this.name }, (err, result) => {
  11845. if (err)
  11846. return reject(err);
  11847. resolve(!!result.ok);
  11848. });
  11849. });
  11850. }
  11851. };
  11852. __name(_DropCollectionOperation, "DropCollectionOperation");
  11853. var DropCollectionOperation = _DropCollectionOperation;
  11854. exports2.DropCollectionOperation = DropCollectionOperation;
  11855. var _DropDatabaseOperation = class _DropDatabaseOperation extends command_1.CommandCallbackOperation {
  11856. constructor(db, options) {
  11857. super(db, options);
  11858. this.options = options;
  11859. }
  11860. executeCallback(server, session, callback) {
  11861. super.executeCommandCallback(server, session, { dropDatabase: 1 }, (err, result) => {
  11862. if (err)
  11863. return callback(err);
  11864. if (result.ok)
  11865. return callback(void 0, true);
  11866. callback(void 0, false);
  11867. });
  11868. }
  11869. };
  11870. __name(_DropDatabaseOperation, "DropDatabaseOperation");
  11871. var DropDatabaseOperation = _DropDatabaseOperation;
  11872. exports2.DropDatabaseOperation = DropDatabaseOperation;
  11873. (0, operation_1.defineAspects)(DropCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]);
  11874. (0, operation_1.defineAspects)(DropDatabaseOperation, [operation_1.Aspect.WRITE_OPERATION]);
  11875. }
  11876. });
  11877. // node_modules/mongodb/lib/operations/estimated_document_count.js
  11878. var require_estimated_document_count = __commonJS({
  11879. "node_modules/mongodb/lib/operations/estimated_document_count.js"(exports2) {
  11880. "use strict";
  11881. Object.defineProperty(exports2, "__esModule", { value: true });
  11882. exports2.EstimatedDocumentCountOperation = void 0;
  11883. var command_1 = require_command();
  11884. var operation_1 = require_operation();
  11885. var _EstimatedDocumentCountOperation = class _EstimatedDocumentCountOperation extends command_1.CommandCallbackOperation {
  11886. constructor(collection, options = {}) {
  11887. super(collection, options);
  11888. this.options = options;
  11889. this.collectionName = collection.collectionName;
  11890. }
  11891. executeCallback(server, session, callback) {
  11892. const cmd = { count: this.collectionName };
  11893. if (typeof this.options.maxTimeMS === "number") {
  11894. cmd.maxTimeMS = this.options.maxTimeMS;
  11895. }
  11896. if (this.options.comment !== void 0) {
  11897. cmd.comment = this.options.comment;
  11898. }
  11899. super.executeCommandCallback(server, session, cmd, (err, response) => {
  11900. if (err) {
  11901. callback(err);
  11902. return;
  11903. }
  11904. callback(void 0, (response == null ? void 0 : response.n) || 0);
  11905. });
  11906. }
  11907. };
  11908. __name(_EstimatedDocumentCountOperation, "EstimatedDocumentCountOperation");
  11909. var EstimatedDocumentCountOperation = _EstimatedDocumentCountOperation;
  11910. exports2.EstimatedDocumentCountOperation = EstimatedDocumentCountOperation;
  11911. (0, operation_1.defineAspects)(EstimatedDocumentCountOperation, [
  11912. operation_1.Aspect.READ_OPERATION,
  11913. operation_1.Aspect.RETRYABLE,
  11914. operation_1.Aspect.CURSOR_CREATING
  11915. ]);
  11916. }
  11917. });
  11918. // node_modules/mongodb/lib/operations/find_and_modify.js
  11919. var require_find_and_modify = __commonJS({
  11920. "node_modules/mongodb/lib/operations/find_and_modify.js"(exports2) {
  11921. "use strict";
  11922. Object.defineProperty(exports2, "__esModule", { value: true });
  11923. exports2.FindOneAndUpdateOperation = exports2.FindOneAndReplaceOperation = exports2.FindOneAndDeleteOperation = exports2.ReturnDocument = void 0;
  11924. var error_1 = require_error();
  11925. var read_preference_1 = require_read_preference();
  11926. var sort_1 = require_sort();
  11927. var utils_1 = require_utils();
  11928. var command_1 = require_command();
  11929. var operation_1 = require_operation();
  11930. exports2.ReturnDocument = Object.freeze({
  11931. BEFORE: "before",
  11932. AFTER: "after"
  11933. });
  11934. function configureFindAndModifyCmdBaseUpdateOpts(cmdBase, options) {
  11935. cmdBase.new = options.returnDocument === exports2.ReturnDocument.AFTER;
  11936. cmdBase.upsert = options.upsert === true;
  11937. if (options.bypassDocumentValidation === true) {
  11938. cmdBase.bypassDocumentValidation = options.bypassDocumentValidation;
  11939. }
  11940. return cmdBase;
  11941. }
  11942. __name(configureFindAndModifyCmdBaseUpdateOpts, "configureFindAndModifyCmdBaseUpdateOpts");
  11943. var _FindAndModifyOperation = class _FindAndModifyOperation extends command_1.CommandCallbackOperation {
  11944. constructor(collection, query, options) {
  11945. super(collection, options);
  11946. this.options = options ?? {};
  11947. this.cmdBase = {
  11948. remove: false,
  11949. new: false,
  11950. upsert: false
  11951. };
  11952. options.includeResultMetadata ?? (options.includeResultMetadata = true);
  11953. const sort = (0, sort_1.formatSort)(options.sort);
  11954. if (sort) {
  11955. this.cmdBase.sort = sort;
  11956. }
  11957. if (options.projection) {
  11958. this.cmdBase.fields = options.projection;
  11959. }
  11960. if (options.maxTimeMS) {
  11961. this.cmdBase.maxTimeMS = options.maxTimeMS;
  11962. }
  11963. if (options.writeConcern) {
  11964. this.cmdBase.writeConcern = options.writeConcern;
  11965. }
  11966. if (options.let) {
  11967. this.cmdBase.let = options.let;
  11968. }
  11969. if (options.comment !== void 0) {
  11970. this.cmdBase.comment = options.comment;
  11971. }
  11972. this.readPreference = read_preference_1.ReadPreference.primary;
  11973. this.collection = collection;
  11974. this.query = query;
  11975. }
  11976. executeCallback(server, session, callback) {
  11977. var _a;
  11978. const coll = this.collection;
  11979. const query = this.query;
  11980. const options = { ...this.options, ...this.bsonOptions };
  11981. const cmd = {
  11982. findAndModify: coll.collectionName,
  11983. query,
  11984. ...this.cmdBase
  11985. };
  11986. try {
  11987. (0, utils_1.decorateWithCollation)(cmd, coll, options);
  11988. } catch (err) {
  11989. return callback(err);
  11990. }
  11991. if (options.hint) {
  11992. const unacknowledgedWrite = ((_a = this.writeConcern) == null ? void 0 : _a.w) === 0;
  11993. if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 8) {
  11994. callback(new error_1.MongoCompatibilityError("The current topology does not support a hint on findAndModify commands"));
  11995. return;
  11996. }
  11997. cmd.hint = options.hint;
  11998. }
  11999. super.executeCommandCallback(server, session, cmd, (err, result) => {
  12000. if (err)
  12001. return callback(err);
  12002. return callback(void 0, options.includeResultMetadata ? result : result.value ?? null);
  12003. });
  12004. }
  12005. };
  12006. __name(_FindAndModifyOperation, "FindAndModifyOperation");
  12007. var FindAndModifyOperation = _FindAndModifyOperation;
  12008. var _FindOneAndDeleteOperation = class _FindOneAndDeleteOperation extends FindAndModifyOperation {
  12009. constructor(collection, filter, options) {
  12010. if (filter == null || typeof filter !== "object") {
  12011. throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object');
  12012. }
  12013. super(collection, filter, options);
  12014. this.cmdBase.remove = true;
  12015. }
  12016. };
  12017. __name(_FindOneAndDeleteOperation, "FindOneAndDeleteOperation");
  12018. var FindOneAndDeleteOperation = _FindOneAndDeleteOperation;
  12019. exports2.FindOneAndDeleteOperation = FindOneAndDeleteOperation;
  12020. var _FindOneAndReplaceOperation = class _FindOneAndReplaceOperation extends FindAndModifyOperation {
  12021. constructor(collection, filter, replacement, options) {
  12022. if (filter == null || typeof filter !== "object") {
  12023. throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object');
  12024. }
  12025. if (replacement == null || typeof replacement !== "object") {
  12026. throw new error_1.MongoInvalidArgumentError('Argument "replacement" must be an object');
  12027. }
  12028. if ((0, utils_1.hasAtomicOperators)(replacement)) {
  12029. throw new error_1.MongoInvalidArgumentError("Replacement document must not contain atomic operators");
  12030. }
  12031. super(collection, filter, options);
  12032. this.cmdBase.update = replacement;
  12033. configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options);
  12034. }
  12035. };
  12036. __name(_FindOneAndReplaceOperation, "FindOneAndReplaceOperation");
  12037. var FindOneAndReplaceOperation = _FindOneAndReplaceOperation;
  12038. exports2.FindOneAndReplaceOperation = FindOneAndReplaceOperation;
  12039. var _FindOneAndUpdateOperation = class _FindOneAndUpdateOperation extends FindAndModifyOperation {
  12040. constructor(collection, filter, update, options) {
  12041. if (filter == null || typeof filter !== "object") {
  12042. throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object');
  12043. }
  12044. if (update == null || typeof update !== "object") {
  12045. throw new error_1.MongoInvalidArgumentError('Argument "update" must be an object');
  12046. }
  12047. if (!(0, utils_1.hasAtomicOperators)(update)) {
  12048. throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
  12049. }
  12050. super(collection, filter, options);
  12051. this.cmdBase.update = update;
  12052. configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options);
  12053. if (options.arrayFilters) {
  12054. this.cmdBase.arrayFilters = options.arrayFilters;
  12055. }
  12056. }
  12057. };
  12058. __name(_FindOneAndUpdateOperation, "FindOneAndUpdateOperation");
  12059. var FindOneAndUpdateOperation = _FindOneAndUpdateOperation;
  12060. exports2.FindOneAndUpdateOperation = FindOneAndUpdateOperation;
  12061. (0, operation_1.defineAspects)(FindAndModifyOperation, [
  12062. operation_1.Aspect.WRITE_OPERATION,
  12063. operation_1.Aspect.RETRYABLE,
  12064. operation_1.Aspect.EXPLAINABLE
  12065. ]);
  12066. }
  12067. });
  12068. // node_modules/mongodb/lib/operations/is_capped.js
  12069. var require_is_capped = __commonJS({
  12070. "node_modules/mongodb/lib/operations/is_capped.js"(exports2) {
  12071. "use strict";
  12072. Object.defineProperty(exports2, "__esModule", { value: true });
  12073. exports2.IsCappedOperation = void 0;
  12074. var error_1 = require_error();
  12075. var operation_1 = require_operation();
  12076. var _IsCappedOperation = class _IsCappedOperation extends operation_1.AbstractCallbackOperation {
  12077. constructor(collection, options) {
  12078. super(options);
  12079. this.options = options;
  12080. this.collection = collection;
  12081. }
  12082. executeCallback(server, session, callback) {
  12083. const coll = this.collection;
  12084. coll.s.db.listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }).toArray().then((collections) => {
  12085. var _a;
  12086. if (collections.length === 0) {
  12087. return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`));
  12088. }
  12089. callback(void 0, !!((_a = collections[0].options) == null ? void 0 : _a.capped));
  12090. }, (error) => callback(error));
  12091. }
  12092. };
  12093. __name(_IsCappedOperation, "IsCappedOperation");
  12094. var IsCappedOperation = _IsCappedOperation;
  12095. exports2.IsCappedOperation = IsCappedOperation;
  12096. }
  12097. });
  12098. // node_modules/mongodb/lib/operations/options_operation.js
  12099. var require_options_operation = __commonJS({
  12100. "node_modules/mongodb/lib/operations/options_operation.js"(exports2) {
  12101. "use strict";
  12102. Object.defineProperty(exports2, "__esModule", { value: true });
  12103. exports2.OptionsOperation = void 0;
  12104. var error_1 = require_error();
  12105. var operation_1 = require_operation();
  12106. var _OptionsOperation = class _OptionsOperation extends operation_1.AbstractCallbackOperation {
  12107. constructor(collection, options) {
  12108. super(options);
  12109. this.options = options;
  12110. this.collection = collection;
  12111. }
  12112. executeCallback(server, session, callback) {
  12113. const coll = this.collection;
  12114. coll.s.db.listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }).toArray().then((collections) => {
  12115. if (collections.length === 0) {
  12116. return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`));
  12117. }
  12118. callback(void 0, collections[0].options);
  12119. }, (error) => callback(error));
  12120. }
  12121. };
  12122. __name(_OptionsOperation, "OptionsOperation");
  12123. var OptionsOperation = _OptionsOperation;
  12124. exports2.OptionsOperation = OptionsOperation;
  12125. }
  12126. });
  12127. // node_modules/mongodb/lib/operations/rename.js
  12128. var require_rename = __commonJS({
  12129. "node_modules/mongodb/lib/operations/rename.js"(exports2) {
  12130. "use strict";
  12131. Object.defineProperty(exports2, "__esModule", { value: true });
  12132. exports2.RenameOperation = void 0;
  12133. var collection_1 = require_collection();
  12134. var error_1 = require_error();
  12135. var utils_1 = require_utils();
  12136. var operation_1 = require_operation();
  12137. var run_command_1 = require_run_command();
  12138. var _RenameOperation = class _RenameOperation extends run_command_1.RunAdminCommandOperation {
  12139. constructor(collection, newName, options) {
  12140. (0, utils_1.checkCollectionName)(newName);
  12141. const renameCollection = collection.namespace;
  12142. const toCollection = collection.s.namespace.withCollection(newName).toString();
  12143. const dropTarget = typeof options.dropTarget === "boolean" ? options.dropTarget : false;
  12144. const cmd = { renameCollection, to: toCollection, dropTarget };
  12145. super(collection, cmd, options);
  12146. this.options = options;
  12147. this.collection = collection;
  12148. this.newName = newName;
  12149. }
  12150. executeCallback(server, session, callback) {
  12151. const coll = this.collection;
  12152. super.executeCallback(server, session, (err, doc) => {
  12153. if (err)
  12154. return callback(err);
  12155. if (doc == null ? void 0 : doc.errmsg) {
  12156. return callback(new error_1.MongoServerError(doc));
  12157. }
  12158. let newColl;
  12159. try {
  12160. newColl = new collection_1.Collection(coll.s.db, this.newName, coll.s.options);
  12161. } catch (err2) {
  12162. return callback(err2);
  12163. }
  12164. return callback(void 0, newColl);
  12165. });
  12166. }
  12167. };
  12168. __name(_RenameOperation, "RenameOperation");
  12169. var RenameOperation = _RenameOperation;
  12170. exports2.RenameOperation = RenameOperation;
  12171. (0, operation_1.defineAspects)(RenameOperation, [operation_1.Aspect.WRITE_OPERATION]);
  12172. }
  12173. });
  12174. // node_modules/mongodb/lib/operations/search_indexes/create.js
  12175. var require_create = __commonJS({
  12176. "node_modules/mongodb/lib/operations/search_indexes/create.js"(exports2) {
  12177. "use strict";
  12178. Object.defineProperty(exports2, "__esModule", { value: true });
  12179. exports2.CreateSearchIndexesOperation = void 0;
  12180. var operation_1 = require_operation();
  12181. var _CreateSearchIndexesOperation = class _CreateSearchIndexesOperation extends operation_1.AbstractCallbackOperation {
  12182. constructor(collection, descriptions) {
  12183. super();
  12184. this.collection = collection;
  12185. this.descriptions = descriptions;
  12186. }
  12187. executeCallback(server, session, callback) {
  12188. const namespace = this.collection.fullNamespace;
  12189. const command = {
  12190. createSearchIndexes: namespace.collection,
  12191. indexes: this.descriptions
  12192. };
  12193. server.command(namespace, command, { session }, (err, res) => {
  12194. if (err || !res) {
  12195. callback(err);
  12196. return;
  12197. }
  12198. const indexesCreated = (res == null ? void 0 : res.indexesCreated) ?? [];
  12199. callback(void 0, indexesCreated.map(({ name }) => name));
  12200. });
  12201. }
  12202. };
  12203. __name(_CreateSearchIndexesOperation, "CreateSearchIndexesOperation");
  12204. var CreateSearchIndexesOperation = _CreateSearchIndexesOperation;
  12205. exports2.CreateSearchIndexesOperation = CreateSearchIndexesOperation;
  12206. }
  12207. });
  12208. // node_modules/mongodb/lib/operations/search_indexes/drop.js
  12209. var require_drop2 = __commonJS({
  12210. "node_modules/mongodb/lib/operations/search_indexes/drop.js"(exports2) {
  12211. "use strict";
  12212. Object.defineProperty(exports2, "__esModule", { value: true });
  12213. exports2.DropSearchIndexOperation = void 0;
  12214. var operation_1 = require_operation();
  12215. var _DropSearchIndexOperation = class _DropSearchIndexOperation extends operation_1.AbstractCallbackOperation {
  12216. constructor(collection, name) {
  12217. super();
  12218. this.collection = collection;
  12219. this.name = name;
  12220. }
  12221. executeCallback(server, session, callback) {
  12222. const namespace = this.collection.fullNamespace;
  12223. const command = {
  12224. dropSearchIndex: namespace.collection
  12225. };
  12226. if (typeof this.name === "string") {
  12227. command.name = this.name;
  12228. }
  12229. server.command(namespace, command, { session }, (err) => {
  12230. if (err) {
  12231. callback(err);
  12232. return;
  12233. }
  12234. callback();
  12235. });
  12236. }
  12237. };
  12238. __name(_DropSearchIndexOperation, "DropSearchIndexOperation");
  12239. var DropSearchIndexOperation = _DropSearchIndexOperation;
  12240. exports2.DropSearchIndexOperation = DropSearchIndexOperation;
  12241. }
  12242. });
  12243. // node_modules/mongodb/lib/operations/search_indexes/update.js
  12244. var require_update2 = __commonJS({
  12245. "node_modules/mongodb/lib/operations/search_indexes/update.js"(exports2) {
  12246. "use strict";
  12247. Object.defineProperty(exports2, "__esModule", { value: true });
  12248. exports2.UpdateSearchIndexOperation = void 0;
  12249. var operation_1 = require_operation();
  12250. var _UpdateSearchIndexOperation = class _UpdateSearchIndexOperation extends operation_1.AbstractCallbackOperation {
  12251. constructor(collection, name, definition) {
  12252. super();
  12253. this.collection = collection;
  12254. this.name = name;
  12255. this.definition = definition;
  12256. }
  12257. executeCallback(server, session, callback) {
  12258. const namespace = this.collection.fullNamespace;
  12259. const command = {
  12260. updateSearchIndex: namespace.collection,
  12261. name: this.name,
  12262. definition: this.definition
  12263. };
  12264. server.command(namespace, command, { session }, (err) => {
  12265. if (err) {
  12266. callback(err);
  12267. return;
  12268. }
  12269. callback();
  12270. });
  12271. }
  12272. };
  12273. __name(_UpdateSearchIndexOperation, "UpdateSearchIndexOperation");
  12274. var UpdateSearchIndexOperation = _UpdateSearchIndexOperation;
  12275. exports2.UpdateSearchIndexOperation = UpdateSearchIndexOperation;
  12276. }
  12277. });
  12278. // node_modules/mongodb/lib/operations/stats.js
  12279. var require_stats = __commonJS({
  12280. "node_modules/mongodb/lib/operations/stats.js"(exports2) {
  12281. "use strict";
  12282. Object.defineProperty(exports2, "__esModule", { value: true });
  12283. exports2.DbStatsOperation = exports2.CollStatsOperation = void 0;
  12284. var command_1 = require_command();
  12285. var operation_1 = require_operation();
  12286. var _CollStatsOperation = class _CollStatsOperation extends command_1.CommandCallbackOperation {
  12287. /**
  12288. * Construct a Stats operation.
  12289. *
  12290. * @param collection - Collection instance
  12291. * @param options - Optional settings. See Collection.prototype.stats for a list of options.
  12292. */
  12293. constructor(collection, options) {
  12294. super(collection, options);
  12295. this.options = options ?? {};
  12296. this.collectionName = collection.collectionName;
  12297. }
  12298. executeCallback(server, session, callback) {
  12299. const command = { collStats: this.collectionName };
  12300. if (this.options.scale != null) {
  12301. command.scale = this.options.scale;
  12302. }
  12303. super.executeCommandCallback(server, session, command, callback);
  12304. }
  12305. };
  12306. __name(_CollStatsOperation, "CollStatsOperation");
  12307. var CollStatsOperation = _CollStatsOperation;
  12308. exports2.CollStatsOperation = CollStatsOperation;
  12309. var _DbStatsOperation = class _DbStatsOperation extends command_1.CommandCallbackOperation {
  12310. constructor(db, options) {
  12311. super(db, options);
  12312. this.options = options;
  12313. }
  12314. executeCallback(server, session, callback) {
  12315. const command = { dbStats: true };
  12316. if (this.options.scale != null) {
  12317. command.scale = this.options.scale;
  12318. }
  12319. super.executeCommandCallback(server, session, command, callback);
  12320. }
  12321. };
  12322. __name(_DbStatsOperation, "DbStatsOperation");
  12323. var DbStatsOperation = _DbStatsOperation;
  12324. exports2.DbStatsOperation = DbStatsOperation;
  12325. (0, operation_1.defineAspects)(CollStatsOperation, [operation_1.Aspect.READ_OPERATION]);
  12326. (0, operation_1.defineAspects)(DbStatsOperation, [operation_1.Aspect.READ_OPERATION]);
  12327. }
  12328. });
  12329. // node_modules/mongodb/lib/collection.js
  12330. var require_collection = __commonJS({
  12331. "node_modules/mongodb/lib/collection.js"(exports2) {
  12332. "use strict";
  12333. Object.defineProperty(exports2, "__esModule", { value: true });
  12334. exports2.Collection = void 0;
  12335. var bson_1 = require_bson2();
  12336. var ordered_1 = require_ordered();
  12337. var unordered_1 = require_unordered();
  12338. var change_stream_1 = require_change_stream();
  12339. var aggregation_cursor_1 = require_aggregation_cursor();
  12340. var find_cursor_1 = require_find_cursor();
  12341. var list_indexes_cursor_1 = require_list_indexes_cursor();
  12342. var list_search_indexes_cursor_1 = require_list_search_indexes_cursor();
  12343. var error_1 = require_error();
  12344. var bulk_write_1 = require_bulk_write();
  12345. var count_1 = require_count();
  12346. var count_documents_1 = require_count_documents();
  12347. var delete_1 = require_delete();
  12348. var distinct_1 = require_distinct();
  12349. var drop_1 = require_drop();
  12350. var estimated_document_count_1 = require_estimated_document_count();
  12351. var execute_operation_1 = require_execute_operation();
  12352. var find_and_modify_1 = require_find_and_modify();
  12353. var indexes_1 = require_indexes();
  12354. var insert_1 = require_insert();
  12355. var is_capped_1 = require_is_capped();
  12356. var options_operation_1 = require_options_operation();
  12357. var rename_1 = require_rename();
  12358. var create_1 = require_create();
  12359. var drop_2 = require_drop2();
  12360. var update_1 = require_update2();
  12361. var stats_1 = require_stats();
  12362. var update_2 = require_update();
  12363. var read_concern_1 = require_read_concern();
  12364. var read_preference_1 = require_read_preference();
  12365. var utils_1 = require_utils();
  12366. var write_concern_1 = require_write_concern();
  12367. var _Collection = class _Collection {
  12368. /**
  12369. * Create a new Collection instance
  12370. * @internal
  12371. */
  12372. constructor(db, name, options) {
  12373. var _a;
  12374. (0, utils_1.checkCollectionName)(name);
  12375. this.s = {
  12376. db,
  12377. options,
  12378. namespace: new utils_1.MongoDBCollectionNamespace(db.databaseName, name),
  12379. pkFactory: ((_a = db.options) == null ? void 0 : _a.pkFactory) ?? utils_1.DEFAULT_PK_FACTORY,
  12380. readPreference: read_preference_1.ReadPreference.fromOptions(options),
  12381. bsonOptions: (0, bson_1.resolveBSONOptions)(options, db),
  12382. readConcern: read_concern_1.ReadConcern.fromOptions(options),
  12383. writeConcern: write_concern_1.WriteConcern.fromOptions(options)
  12384. };
  12385. this.client = db.client;
  12386. }
  12387. /**
  12388. * The name of the database this collection belongs to
  12389. */
  12390. get dbName() {
  12391. return this.s.namespace.db;
  12392. }
  12393. /**
  12394. * The name of this collection
  12395. */
  12396. get collectionName() {
  12397. return this.s.namespace.collection;
  12398. }
  12399. /**
  12400. * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`
  12401. */
  12402. get namespace() {
  12403. return this.fullNamespace.toString();
  12404. }
  12405. /**
  12406. * @internal
  12407. *
  12408. * The `MongoDBNamespace` for the collection.
  12409. */
  12410. get fullNamespace() {
  12411. return this.s.namespace;
  12412. }
  12413. /**
  12414. * The current readConcern of the collection. If not explicitly defined for
  12415. * this collection, will be inherited from the parent DB
  12416. */
  12417. get readConcern() {
  12418. if (this.s.readConcern == null) {
  12419. return this.s.db.readConcern;
  12420. }
  12421. return this.s.readConcern;
  12422. }
  12423. /**
  12424. * The current readPreference of the collection. If not explicitly defined for
  12425. * this collection, will be inherited from the parent DB
  12426. */
  12427. get readPreference() {
  12428. if (this.s.readPreference == null) {
  12429. return this.s.db.readPreference;
  12430. }
  12431. return this.s.readPreference;
  12432. }
  12433. get bsonOptions() {
  12434. return this.s.bsonOptions;
  12435. }
  12436. /**
  12437. * The current writeConcern of the collection. If not explicitly defined for
  12438. * this collection, will be inherited from the parent DB
  12439. */
  12440. get writeConcern() {
  12441. if (this.s.writeConcern == null) {
  12442. return this.s.db.writeConcern;
  12443. }
  12444. return this.s.writeConcern;
  12445. }
  12446. /** The current index hint for the collection */
  12447. get hint() {
  12448. return this.s.collectionHint;
  12449. }
  12450. set hint(v) {
  12451. this.s.collectionHint = (0, utils_1.normalizeHintField)(v);
  12452. }
  12453. /**
  12454. * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
  12455. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  12456. * can be overridden by setting the **forceServerObjectId** flag.
  12457. *
  12458. * @param doc - The document to insert
  12459. * @param options - Optional settings for the command
  12460. */
  12461. async insertOne(doc, options) {
  12462. return (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options)));
  12463. }
  12464. /**
  12465. * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  12466. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  12467. * can be overridden by setting the **forceServerObjectId** flag.
  12468. *
  12469. * @param docs - The documents to insert
  12470. * @param options - Optional settings for the command
  12471. */
  12472. async insertMany(docs, options) {
  12473. return (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options ?? { ordered: true })));
  12474. }
  12475. /**
  12476. * Perform a bulkWrite operation without a fluent API
  12477. *
  12478. * Legal operation types are
  12479. * - `insertOne`
  12480. * - `replaceOne`
  12481. * - `updateOne`
  12482. * - `updateMany`
  12483. * - `deleteOne`
  12484. * - `deleteMany`
  12485. *
  12486. * If documents passed in do not contain the **_id** field,
  12487. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  12488. * can be overridden by setting the **forceServerObjectId** flag.
  12489. *
  12490. * @param operations - Bulk operations to perform
  12491. * @param options - Optional settings for the command
  12492. * @throws MongoDriverError if operations is not an array
  12493. */
  12494. async bulkWrite(operations, options) {
  12495. if (!Array.isArray(operations)) {
  12496. throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents');
  12497. }
  12498. return (0, execute_operation_1.executeOperation)(this.client, new bulk_write_1.BulkWriteOperation(this, operations, (0, utils_1.resolveOptions)(this, options ?? { ordered: true })));
  12499. }
  12500. /**
  12501. * Update a single document in a collection
  12502. *
  12503. * @param filter - The filter used to select the document to update
  12504. * @param update - The update operations to be applied to the document
  12505. * @param options - Optional settings for the command
  12506. */
  12507. async updateOne(filter, update, options) {
  12508. return (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateOneOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
  12509. }
  12510. /**
  12511. * Replace a document in a collection with another document
  12512. *
  12513. * @param filter - The filter used to select the document to replace
  12514. * @param replacement - The Document that replaces the matching document
  12515. * @param options - Optional settings for the command
  12516. */
  12517. async replaceOne(filter, replacement, options) {
  12518. return (0, execute_operation_1.executeOperation)(this.client, new update_2.ReplaceOneOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
  12519. }
  12520. /**
  12521. * Update multiple documents in a collection
  12522. *
  12523. * @param filter - The filter used to select the documents to update
  12524. * @param update - The update operations to be applied to the documents
  12525. * @param options - Optional settings for the command
  12526. */
  12527. async updateMany(filter, update, options) {
  12528. return (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateManyOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
  12529. }
  12530. /**
  12531. * Delete a document from a collection
  12532. *
  12533. * @param filter - The filter used to select the document to remove
  12534. * @param options - Optional settings for the command
  12535. */
  12536. async deleteOne(filter = {}, options = {}) {
  12537. return (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
  12538. }
  12539. /**
  12540. * Delete multiple documents from a collection
  12541. *
  12542. * @param filter - The filter used to select the documents to remove
  12543. * @param options - Optional settings for the command
  12544. */
  12545. async deleteMany(filter = {}, options = {}) {
  12546. return (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
  12547. }
  12548. /**
  12549. * Rename the collection.
  12550. *
  12551. * @remarks
  12552. * This operation does not inherit options from the Db or MongoClient.
  12553. *
  12554. * @param newName - New name of of the collection.
  12555. * @param options - Optional settings for the command
  12556. */
  12557. async rename(newName, options) {
  12558. return (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this, newName, {
  12559. ...options,
  12560. readPreference: read_preference_1.ReadPreference.PRIMARY
  12561. }));
  12562. }
  12563. /**
  12564. * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
  12565. *
  12566. * @param options - Optional settings for the command
  12567. */
  12568. async drop(options) {
  12569. return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options));
  12570. }
  12571. async findOne(filter = {}, options = {}) {
  12572. const cursor = this.find(filter, options).limit(-1).batchSize(1);
  12573. const res = await cursor.next();
  12574. await cursor.close();
  12575. return res;
  12576. }
  12577. find(filter = {}, options = {}) {
  12578. return new find_cursor_1.FindCursor(this.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options));
  12579. }
  12580. /**
  12581. * Returns the options of the collection.
  12582. *
  12583. * @param options - Optional settings for the command
  12584. */
  12585. async options(options) {
  12586. return (0, execute_operation_1.executeOperation)(this.client, new options_operation_1.OptionsOperation(this, (0, utils_1.resolveOptions)(this, options)));
  12587. }
  12588. /**
  12589. * Returns if the collection is a capped collection
  12590. *
  12591. * @param options - Optional settings for the command
  12592. */
  12593. async isCapped(options) {
  12594. return (0, execute_operation_1.executeOperation)(this.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options)));
  12595. }
  12596. /**
  12597. * Creates an index on the db and collection collection.
  12598. *
  12599. * @param indexSpec - The field name or index specification to create an index for
  12600. * @param options - Optional settings for the command
  12601. *
  12602. * @example
  12603. * ```ts
  12604. * const collection = client.db('foo').collection('bar');
  12605. *
  12606. * await collection.createIndex({ a: 1, b: -1 });
  12607. *
  12608. * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
  12609. * await collection.createIndex([ [c, 1], [d, -1] ]);
  12610. *
  12611. * // Equivalent to { e: 1 }
  12612. * await collection.createIndex('e');
  12613. *
  12614. * // Equivalent to { f: 1, g: 1 }
  12615. * await collection.createIndex(['f', 'g'])
  12616. *
  12617. * // Equivalent to { h: 1, i: -1 }
  12618. * await collection.createIndex([ { h: 1 }, { i: -1 } ]);
  12619. *
  12620. * // Equivalent to { j: 1, k: -1, l: 2d }
  12621. * await collection.createIndex(['j', ['k', -1], { l: '2d' }])
  12622. * ```
  12623. */
  12624. async createIndex(indexSpec, options) {
  12625. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexOperation(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options)));
  12626. }
  12627. /**
  12628. * Creates multiple indexes in the collection, this method is only supported for
  12629. * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
  12630. * error.
  12631. *
  12632. * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications.
  12633. * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}.
  12634. *
  12635. * @param indexSpecs - An array of index specifications to be created
  12636. * @param options - Optional settings for the command
  12637. *
  12638. * @example
  12639. * ```ts
  12640. * const collection = client.db('foo').collection('bar');
  12641. * await collection.createIndexes([
  12642. * // Simple index on field fizz
  12643. * {
  12644. * key: { fizz: 1 },
  12645. * }
  12646. * // wildcard index
  12647. * {
  12648. * key: { '$**': 1 }
  12649. * },
  12650. * // named index on darmok and jalad
  12651. * {
  12652. * key: { darmok: 1, jalad: -1 }
  12653. * name: 'tanagra'
  12654. * }
  12655. * ]);
  12656. * ```
  12657. */
  12658. async createIndexes(indexSpecs, options) {
  12659. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexesOperation(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, { ...options, maxTimeMS: void 0 })));
  12660. }
  12661. /**
  12662. * Drops an index from this collection.
  12663. *
  12664. * @param indexName - Name of the index to drop.
  12665. * @param options - Optional settings for the command
  12666. */
  12667. async dropIndex(indexName, options) {
  12668. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, indexName, {
  12669. ...(0, utils_1.resolveOptions)(this, options),
  12670. readPreference: read_preference_1.ReadPreference.primary
  12671. }));
  12672. }
  12673. /**
  12674. * Drops all indexes from this collection.
  12675. *
  12676. * @param options - Optional settings for the command
  12677. */
  12678. async dropIndexes(options) {
  12679. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexesOperation(this, (0, utils_1.resolveOptions)(this, options)));
  12680. }
  12681. /**
  12682. * Get the list of all indexes information for the collection.
  12683. *
  12684. * @param options - Optional settings for the command
  12685. */
  12686. listIndexes(options) {
  12687. return new list_indexes_cursor_1.ListIndexesCursor(this, (0, utils_1.resolveOptions)(this, options));
  12688. }
  12689. /**
  12690. * Checks if one or more indexes exist on the collection, fails on first non-existing index
  12691. *
  12692. * @param indexes - One or more index names to check.
  12693. * @param options - Optional settings for the command
  12694. */
  12695. async indexExists(indexes, options) {
  12696. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexExistsOperation(this, indexes, (0, utils_1.resolveOptions)(this, options)));
  12697. }
  12698. /**
  12699. * Retrieves this collections index info.
  12700. *
  12701. * @param options - Optional settings for the command
  12702. */
  12703. async indexInformation(options) {
  12704. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexInformationOperation(this.s.db, this.collectionName, (0, utils_1.resolveOptions)(this, options)));
  12705. }
  12706. /**
  12707. * Gets an estimate of the count of documents in a collection using collection metadata.
  12708. * This will always run a count command on all server versions.
  12709. *
  12710. * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command,
  12711. * which estimatedDocumentCount uses in its implementation, was not included in v1 of
  12712. * the Stable API, and so users of the Stable API with estimatedDocumentCount are
  12713. * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid
  12714. * encountering errors.
  12715. *
  12716. * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior}
  12717. * @param options - Optional settings for the command
  12718. */
  12719. async estimatedDocumentCount(options) {
  12720. return (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options)));
  12721. }
  12722. /**
  12723. * Gets the number of documents matching the filter.
  12724. * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
  12725. * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments}
  12726. * the following query operators must be replaced:
  12727. *
  12728. * | Operator | Replacement |
  12729. * | -------- | ----------- |
  12730. * | `$where` | [`$expr`][1] |
  12731. * | `$near` | [`$geoWithin`][2] with [`$center`][3] |
  12732. * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] |
  12733. *
  12734. * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/
  12735. * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  12736. * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
  12737. * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  12738. *
  12739. * @param filter - The filter for the count
  12740. * @param options - Optional settings for the command
  12741. *
  12742. * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/
  12743. * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  12744. * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
  12745. * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  12746. */
  12747. async countDocuments(filter = {}, options = {}) {
  12748. return (0, execute_operation_1.executeOperation)(this.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
  12749. }
  12750. async distinct(key, filter = {}, options = {}) {
  12751. return (0, execute_operation_1.executeOperation)(this.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options)));
  12752. }
  12753. /**
  12754. * Retrieve all the indexes on the collection.
  12755. *
  12756. * @param options - Optional settings for the command
  12757. */
  12758. async indexes(options) {
  12759. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexesOperation(this, (0, utils_1.resolveOptions)(this, options)));
  12760. }
  12761. /**
  12762. * Get all the collection statistics.
  12763. *
  12764. * @deprecated the `collStats` operation will be removed in the next major release. Please
  12765. * use an aggregation pipeline with the [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/) stage instead
  12766. *
  12767. * @param options - Optional settings for the command
  12768. */
  12769. async stats(options) {
  12770. return (0, execute_operation_1.executeOperation)(this.client, new stats_1.CollStatsOperation(this, options));
  12771. }
  12772. async findOneAndDelete(filter, options) {
  12773. return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
  12774. }
  12775. async findOneAndReplace(filter, replacement, options) {
  12776. return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
  12777. }
  12778. async findOneAndUpdate(filter, update, options) {
  12779. return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
  12780. }
  12781. /**
  12782. * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2
  12783. *
  12784. * @param pipeline - An array of aggregation pipelines to execute
  12785. * @param options - Optional settings for the command
  12786. */
  12787. aggregate(pipeline = [], options) {
  12788. if (!Array.isArray(pipeline)) {
  12789. throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages');
  12790. }
  12791. return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options));
  12792. }
  12793. /**
  12794. * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
  12795. *
  12796. * @remarks
  12797. * watch() accepts two generic arguments for distinct use cases:
  12798. * - The first is to override the schema that may be defined for this specific collection
  12799. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  12800. * @example
  12801. * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>`
  12802. * ```ts
  12803. * collection.watch<{ _id: number }>()
  12804. * .on('change', change => console.log(change._id.toFixed(4)));
  12805. * ```
  12806. *
  12807. * @example
  12808. * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline.
  12809. * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment.
  12810. * No need start from scratch on the ChangeStreamInsertDocument type!
  12811. * By using an intersection we can save time and ensure defaults remain the same type!
  12812. * ```ts
  12813. * collection
  12814. * .watch<Schema, ChangeStreamInsertDocument<Schema> & { comment: string }>([
  12815. * { $addFields: { comment: 'big changes' } },
  12816. * { $match: { operationType: 'insert' } }
  12817. * ])
  12818. * .on('change', change => {
  12819. * change.comment.startsWith('big');
  12820. * change.operationType === 'insert';
  12821. * // No need to narrow in code because the generics did that for us!
  12822. * expectType<Schema>(change.fullDocument);
  12823. * });
  12824. * ```
  12825. *
  12826. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  12827. * @param options - Optional settings for the command
  12828. * @typeParam TLocal - Type of the data being detected by the change stream
  12829. * @typeParam TChange - Type of the whole change stream document emitted
  12830. */
  12831. watch(pipeline = [], options = {}) {
  12832. if (!Array.isArray(pipeline)) {
  12833. options = pipeline;
  12834. pipeline = [];
  12835. }
  12836. return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options));
  12837. }
  12838. /**
  12839. * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
  12840. *
  12841. * @throws MongoNotConnectedError
  12842. * @remarks
  12843. * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
  12844. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
  12845. */
  12846. initializeUnorderedBulkOp(options) {
  12847. return new unordered_1.UnorderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options));
  12848. }
  12849. /**
  12850. * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types.
  12851. *
  12852. * @throws MongoNotConnectedError
  12853. * @remarks
  12854. * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
  12855. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
  12856. */
  12857. initializeOrderedBulkOp(options) {
  12858. return new ordered_1.OrderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options));
  12859. }
  12860. /**
  12861. * An estimated count of matching documents in the db to a filter.
  12862. *
  12863. * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents
  12864. * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}.
  12865. * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
  12866. *
  12867. * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead
  12868. *
  12869. * @param filter - The filter for the count.
  12870. * @param options - Optional settings for the command
  12871. */
  12872. async count(filter = {}, options = {}) {
  12873. return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.fullNamespace, filter, (0, utils_1.resolveOptions)(this, options)));
  12874. }
  12875. listSearchIndexes(indexNameOrOptions, options) {
  12876. options = typeof indexNameOrOptions === "object" ? indexNameOrOptions : options == null ? {} : options;
  12877. const indexName = indexNameOrOptions == null ? null : typeof indexNameOrOptions === "object" ? null : indexNameOrOptions;
  12878. return new list_search_indexes_cursor_1.ListSearchIndexesCursor(this, indexName, options);
  12879. }
  12880. /**
  12881. * Creates a single search index for the collection.
  12882. *
  12883. * @param description - The index description for the new search index.
  12884. * @returns A promise that resolves to the name of the new search index.
  12885. *
  12886. * @remarks Only available when used against a 7.0+ Atlas cluster.
  12887. */
  12888. async createSearchIndex(description) {
  12889. const [index] = await this.createSearchIndexes([description]);
  12890. return index;
  12891. }
  12892. /**
  12893. * Creates multiple search indexes for the current collection.
  12894. *
  12895. * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes.
  12896. * @returns A promise that resolves to an array of the newly created search index names.
  12897. *
  12898. * @remarks Only available when used against a 7.0+ Atlas cluster.
  12899. * @returns
  12900. */
  12901. async createSearchIndexes(descriptions) {
  12902. return (0, execute_operation_1.executeOperation)(this.client, new create_1.CreateSearchIndexesOperation(this, descriptions));
  12903. }
  12904. /**
  12905. * Deletes a search index by index name.
  12906. *
  12907. * @param name - The name of the search index to be deleted.
  12908. *
  12909. * @remarks Only available when used against a 7.0+ Atlas cluster.
  12910. */
  12911. async dropSearchIndex(name) {
  12912. return (0, execute_operation_1.executeOperation)(this.client, new drop_2.DropSearchIndexOperation(this, name));
  12913. }
  12914. /**
  12915. * Updates a search index by replacing the existing index definition with the provided definition.
  12916. *
  12917. * @param name - The name of the search index to update.
  12918. * @param definition - The new search index definition.
  12919. *
  12920. * @remarks Only available when used against a 7.0+ Atlas cluster.
  12921. */
  12922. async updateSearchIndex(name, definition) {
  12923. return (0, execute_operation_1.executeOperation)(this.client, new update_1.UpdateSearchIndexOperation(this, name, definition));
  12924. }
  12925. };
  12926. __name(_Collection, "Collection");
  12927. var Collection = _Collection;
  12928. exports2.Collection = Collection;
  12929. }
  12930. });
  12931. // node_modules/mongodb/lib/cursor/change_stream_cursor.js
  12932. var require_change_stream_cursor = __commonJS({
  12933. "node_modules/mongodb/lib/cursor/change_stream_cursor.js"(exports2) {
  12934. "use strict";
  12935. Object.defineProperty(exports2, "__esModule", { value: true });
  12936. exports2.ChangeStreamCursor = void 0;
  12937. var change_stream_1 = require_change_stream();
  12938. var constants_1 = require_constants2();
  12939. var aggregate_1 = require_aggregate();
  12940. var execute_operation_1 = require_execute_operation();
  12941. var utils_1 = require_utils();
  12942. var abstract_cursor_1 = require_abstract_cursor();
  12943. var _ChangeStreamCursor = class _ChangeStreamCursor extends abstract_cursor_1.AbstractCursor {
  12944. constructor(client, namespace, pipeline = [], options = {}) {
  12945. super(client, namespace, options);
  12946. this.pipeline = pipeline;
  12947. this.options = options;
  12948. this._resumeToken = null;
  12949. this.startAtOperationTime = options.startAtOperationTime;
  12950. if (options.startAfter) {
  12951. this.resumeToken = options.startAfter;
  12952. } else if (options.resumeAfter) {
  12953. this.resumeToken = options.resumeAfter;
  12954. }
  12955. }
  12956. set resumeToken(token) {
  12957. this._resumeToken = token;
  12958. this.emit(change_stream_1.ChangeStream.RESUME_TOKEN_CHANGED, token);
  12959. }
  12960. get resumeToken() {
  12961. return this._resumeToken;
  12962. }
  12963. get resumeOptions() {
  12964. const options = {
  12965. ...this.options
  12966. };
  12967. for (const key of ["resumeAfter", "startAfter", "startAtOperationTime"]) {
  12968. delete options[key];
  12969. }
  12970. if (this.resumeToken != null) {
  12971. if (this.options.startAfter && !this.hasReceived) {
  12972. options.startAfter = this.resumeToken;
  12973. } else {
  12974. options.resumeAfter = this.resumeToken;
  12975. }
  12976. } else if (this.startAtOperationTime != null && (0, utils_1.maxWireVersion)(this.server) >= 7) {
  12977. options.startAtOperationTime = this.startAtOperationTime;
  12978. }
  12979. return options;
  12980. }
  12981. cacheResumeToken(resumeToken) {
  12982. if (this.bufferedCount() === 0 && this.postBatchResumeToken) {
  12983. this.resumeToken = this.postBatchResumeToken;
  12984. } else {
  12985. this.resumeToken = resumeToken;
  12986. }
  12987. this.hasReceived = true;
  12988. }
  12989. _processBatch(response) {
  12990. const cursor = response.cursor;
  12991. if (cursor.postBatchResumeToken) {
  12992. this.postBatchResumeToken = response.cursor.postBatchResumeToken;
  12993. const batch = "firstBatch" in response.cursor ? response.cursor.firstBatch : response.cursor.nextBatch;
  12994. if (batch.length === 0) {
  12995. this.resumeToken = cursor.postBatchResumeToken;
  12996. }
  12997. }
  12998. }
  12999. clone() {
  13000. return new _ChangeStreamCursor(this.client, this.namespace, this.pipeline, {
  13001. ...this.cursorOptions
  13002. });
  13003. }
  13004. _initialize(session, callback) {
  13005. const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, {
  13006. ...this.cursorOptions,
  13007. ...this.options,
  13008. session
  13009. });
  13010. (0, execute_operation_1.executeOperation)(session.client, aggregateOperation, (err, response) => {
  13011. if (err || response == null) {
  13012. return callback(err);
  13013. }
  13014. const server = aggregateOperation.server;
  13015. this.maxWireVersion = (0, utils_1.maxWireVersion)(server);
  13016. if (this.startAtOperationTime == null && this.resumeAfter == null && this.startAfter == null && this.maxWireVersion >= 7) {
  13017. this.startAtOperationTime = response.operationTime;
  13018. }
  13019. this._processBatch(response);
  13020. this.emit(constants_1.INIT, response);
  13021. this.emit(constants_1.RESPONSE);
  13022. callback(void 0, { server, session, response });
  13023. });
  13024. }
  13025. _getMore(batchSize, callback) {
  13026. super._getMore(batchSize, (err, response) => {
  13027. if (err) {
  13028. return callback(err);
  13029. }
  13030. this.maxWireVersion = (0, utils_1.maxWireVersion)(this.server);
  13031. this._processBatch(response);
  13032. this.emit(change_stream_1.ChangeStream.MORE, response);
  13033. this.emit(change_stream_1.ChangeStream.RESPONSE);
  13034. callback(err, response);
  13035. });
  13036. }
  13037. };
  13038. __name(_ChangeStreamCursor, "ChangeStreamCursor");
  13039. var ChangeStreamCursor = _ChangeStreamCursor;
  13040. exports2.ChangeStreamCursor = ChangeStreamCursor;
  13041. }
  13042. });
  13043. // node_modules/mongodb/lib/operations/list_collections.js
  13044. var require_list_collections = __commonJS({
  13045. "node_modules/mongodb/lib/operations/list_collections.js"(exports2) {
  13046. "use strict";
  13047. Object.defineProperty(exports2, "__esModule", { value: true });
  13048. exports2.ListCollectionsOperation = void 0;
  13049. var utils_1 = require_utils();
  13050. var command_1 = require_command();
  13051. var operation_1 = require_operation();
  13052. var _ListCollectionsOperation = class _ListCollectionsOperation extends command_1.CommandCallbackOperation {
  13053. constructor(db, filter, options) {
  13054. super(db, options);
  13055. this.options = { ...options };
  13056. delete this.options.writeConcern;
  13057. this.db = db;
  13058. this.filter = filter;
  13059. this.nameOnly = !!this.options.nameOnly;
  13060. this.authorizedCollections = !!this.options.authorizedCollections;
  13061. if (typeof this.options.batchSize === "number") {
  13062. this.batchSize = this.options.batchSize;
  13063. }
  13064. }
  13065. executeCallback(server, session, callback) {
  13066. return super.executeCommandCallback(server, session, this.generateCommand((0, utils_1.maxWireVersion)(server)), callback);
  13067. }
  13068. /* This is here for the purpose of unit testing the final command that gets sent. */
  13069. generateCommand(wireVersion) {
  13070. const command = {
  13071. listCollections: 1,
  13072. filter: this.filter,
  13073. cursor: this.batchSize ? { batchSize: this.batchSize } : {},
  13074. nameOnly: this.nameOnly,
  13075. authorizedCollections: this.authorizedCollections
  13076. };
  13077. if (wireVersion >= 9 && this.options.comment !== void 0) {
  13078. command.comment = this.options.comment;
  13079. }
  13080. return command;
  13081. }
  13082. };
  13083. __name(_ListCollectionsOperation, "ListCollectionsOperation");
  13084. var ListCollectionsOperation = _ListCollectionsOperation;
  13085. exports2.ListCollectionsOperation = ListCollectionsOperation;
  13086. (0, operation_1.defineAspects)(ListCollectionsOperation, [
  13087. operation_1.Aspect.READ_OPERATION,
  13088. operation_1.Aspect.RETRYABLE,
  13089. operation_1.Aspect.CURSOR_CREATING
  13090. ]);
  13091. }
  13092. });
  13093. // node_modules/mongodb/lib/cursor/list_collections_cursor.js
  13094. var require_list_collections_cursor = __commonJS({
  13095. "node_modules/mongodb/lib/cursor/list_collections_cursor.js"(exports2) {
  13096. "use strict";
  13097. Object.defineProperty(exports2, "__esModule", { value: true });
  13098. exports2.ListCollectionsCursor = void 0;
  13099. var execute_operation_1 = require_execute_operation();
  13100. var list_collections_1 = require_list_collections();
  13101. var abstract_cursor_1 = require_abstract_cursor();
  13102. var _ListCollectionsCursor = class _ListCollectionsCursor extends abstract_cursor_1.AbstractCursor {
  13103. constructor(db, filter, options) {
  13104. super(db.client, db.s.namespace, options);
  13105. this.parent = db;
  13106. this.filter = filter;
  13107. this.options = options;
  13108. }
  13109. clone() {
  13110. return new _ListCollectionsCursor(this.parent, this.filter, {
  13111. ...this.options,
  13112. ...this.cursorOptions
  13113. });
  13114. }
  13115. /** @internal */
  13116. _initialize(session, callback) {
  13117. const operation = new list_collections_1.ListCollectionsOperation(this.parent, this.filter, {
  13118. ...this.cursorOptions,
  13119. ...this.options,
  13120. session
  13121. });
  13122. (0, execute_operation_1.executeOperation)(this.parent.client, operation, (err, response) => {
  13123. if (err || response == null)
  13124. return callback(err);
  13125. callback(void 0, { server: operation.server, session, response });
  13126. });
  13127. }
  13128. };
  13129. __name(_ListCollectionsCursor, "ListCollectionsCursor");
  13130. var ListCollectionsCursor = _ListCollectionsCursor;
  13131. exports2.ListCollectionsCursor = ListCollectionsCursor;
  13132. }
  13133. });
  13134. // node_modules/mongodb/lib/cursor/run_command_cursor.js
  13135. var require_run_command_cursor = __commonJS({
  13136. "node_modules/mongodb/lib/cursor/run_command_cursor.js"(exports2) {
  13137. "use strict";
  13138. Object.defineProperty(exports2, "__esModule", { value: true });
  13139. exports2.RunCommandCursor = void 0;
  13140. var error_1 = require_error();
  13141. var execute_operation_1 = require_execute_operation();
  13142. var get_more_1 = require_get_more();
  13143. var run_command_1 = require_run_command();
  13144. var utils_1 = require_utils();
  13145. var abstract_cursor_1 = require_abstract_cursor();
  13146. var _RunCommandCursor = class _RunCommandCursor extends abstract_cursor_1.AbstractCursor {
  13147. /**
  13148. * Controls the `getMore.comment` field
  13149. * @param comment - any BSON value
  13150. */
  13151. setComment(comment) {
  13152. this.getMoreOptions.comment = comment;
  13153. return this;
  13154. }
  13155. /**
  13156. * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await
  13157. * @param maxTimeMS - the number of milliseconds to wait for new data
  13158. */
  13159. setMaxTimeMS(maxTimeMS) {
  13160. this.getMoreOptions.maxAwaitTimeMS = maxTimeMS;
  13161. return this;
  13162. }
  13163. /**
  13164. * Controls the `getMore.batchSize` field
  13165. * @param maxTimeMS - the number documents to return in the `nextBatch`
  13166. */
  13167. setBatchSize(batchSize) {
  13168. this.getMoreOptions.batchSize = batchSize;
  13169. return this;
  13170. }
  13171. /** Unsupported for RunCommandCursor */
  13172. clone() {
  13173. throw new error_1.MongoAPIError("Clone not supported, create a new cursor with db.runCursorCommand");
  13174. }
  13175. /** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */
  13176. withReadConcern(_) {
  13177. throw new error_1.MongoAPIError("RunCommandCursor does not support readConcern it must be attached to the command being run");
  13178. }
  13179. /** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */
  13180. addCursorFlag(_, __) {
  13181. throw new error_1.MongoAPIError("RunCommandCursor does not support cursor flags, they must be attached to the command being run");
  13182. }
  13183. /** Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document */
  13184. maxTimeMS(_) {
  13185. throw new error_1.MongoAPIError("maxTimeMS must be configured on the command document directly, to configure getMore.maxTimeMS use cursor.setMaxTimeMS()");
  13186. }
  13187. /** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */
  13188. batchSize(_) {
  13189. throw new error_1.MongoAPIError("batchSize must be configured on the command document directly, to configure getMore.batchSize use cursor.setBatchSize()");
  13190. }
  13191. /** @internal */
  13192. constructor(db, command, options = {}) {
  13193. super(db.client, (0, utils_1.ns)(db.namespace), options);
  13194. this.getMoreOptions = {};
  13195. this.db = db;
  13196. this.command = Object.freeze({ ...command });
  13197. }
  13198. /** @internal */
  13199. _initialize(session, callback) {
  13200. const operation = new run_command_1.RunCommandOperation(this.db, this.command, {
  13201. ...this.cursorOptions,
  13202. session,
  13203. readPreference: this.cursorOptions.readPreference
  13204. });
  13205. (0, execute_operation_1.executeOperation)(this.client, operation).then((response) => {
  13206. if (response.cursor == null) {
  13207. callback(new error_1.MongoUnexpectedServerResponseError("Expected server to respond with cursor"));
  13208. return;
  13209. }
  13210. callback(void 0, {
  13211. server: operation.server,
  13212. session,
  13213. response
  13214. });
  13215. }, (err) => callback(err));
  13216. }
  13217. /** @internal */
  13218. _getMore(_batchSize, callback) {
  13219. const getMoreOperation = new get_more_1.GetMoreOperation(this.namespace, this.id, this.server, {
  13220. ...this.cursorOptions,
  13221. session: this.session,
  13222. ...this.getMoreOptions
  13223. });
  13224. (0, execute_operation_1.executeOperation)(this.client, getMoreOperation, callback);
  13225. }
  13226. };
  13227. __name(_RunCommandCursor, "RunCommandCursor");
  13228. var RunCommandCursor = _RunCommandCursor;
  13229. exports2.RunCommandCursor = RunCommandCursor;
  13230. }
  13231. });
  13232. // node_modules/mongodb/lib/operations/collections.js
  13233. var require_collections = __commonJS({
  13234. "node_modules/mongodb/lib/operations/collections.js"(exports2) {
  13235. "use strict";
  13236. Object.defineProperty(exports2, "__esModule", { value: true });
  13237. exports2.CollectionsOperation = void 0;
  13238. var collection_1 = require_collection();
  13239. var operation_1 = require_operation();
  13240. var _CollectionsOperation = class _CollectionsOperation extends operation_1.AbstractCallbackOperation {
  13241. constructor(db, options) {
  13242. super(options);
  13243. this.options = options;
  13244. this.db = db;
  13245. }
  13246. executeCallback(server, session, callback) {
  13247. this.db.listCollections({}, { ...this.options, nameOnly: true, readPreference: this.readPreference, session }).toArray().then((documents) => {
  13248. const collections = [];
  13249. for (const { name } of documents) {
  13250. if (!name.includes("$")) {
  13251. collections.push(new collection_1.Collection(this.db, name, this.db.s.options));
  13252. }
  13253. }
  13254. callback(void 0, collections);
  13255. }, (error) => callback(error));
  13256. }
  13257. };
  13258. __name(_CollectionsOperation, "CollectionsOperation");
  13259. var CollectionsOperation = _CollectionsOperation;
  13260. exports2.CollectionsOperation = CollectionsOperation;
  13261. }
  13262. });
  13263. // node_modules/mongodb/lib/operations/create_collection.js
  13264. var require_create_collection = __commonJS({
  13265. "node_modules/mongodb/lib/operations/create_collection.js"(exports2) {
  13266. "use strict";
  13267. Object.defineProperty(exports2, "__esModule", { value: true });
  13268. exports2.CreateCollectionOperation = void 0;
  13269. var constants_1 = require_constants();
  13270. var collection_1 = require_collection();
  13271. var error_1 = require_error();
  13272. var command_1 = require_command();
  13273. var indexes_1 = require_indexes();
  13274. var operation_1 = require_operation();
  13275. var ILLEGAL_COMMAND_FIELDS = /* @__PURE__ */ new Set([
  13276. "w",
  13277. "wtimeout",
  13278. "j",
  13279. "fsync",
  13280. "autoIndexId",
  13281. "pkFactory",
  13282. "raw",
  13283. "readPreference",
  13284. "session",
  13285. "readConcern",
  13286. "writeConcern",
  13287. "raw",
  13288. "fieldsAsRaw",
  13289. "useBigInt64",
  13290. "promoteLongs",
  13291. "promoteValues",
  13292. "promoteBuffers",
  13293. "bsonRegExp",
  13294. "serializeFunctions",
  13295. "ignoreUndefined",
  13296. "enableUtf8Validation"
  13297. ]);
  13298. var INVALID_QE_VERSION = "Driver support of Queryable Encryption is incompatible with server. Upgrade server to use Queryable Encryption.";
  13299. var _CreateCollectionOperation = class _CreateCollectionOperation extends command_1.CommandCallbackOperation {
  13300. constructor(db, name, options = {}) {
  13301. super(db, options);
  13302. this.options = options;
  13303. this.db = db;
  13304. this.name = name;
  13305. }
  13306. executeCallback(server, session, callback) {
  13307. (async () => {
  13308. var _a, _b;
  13309. const db = this.db;
  13310. const name = this.name;
  13311. const options = this.options;
  13312. const encryptedFields = options.encryptedFields ?? ((_b = (_a = db.client.options.autoEncryption) == null ? void 0 : _a.encryptedFieldsMap) == null ? void 0 : _b[`${db.databaseName}.${name}`]);
  13313. if (encryptedFields) {
  13314. if (!server.loadBalanced && server.description.maxWireVersion < constants_1.MIN_SUPPORTED_QE_WIRE_VERSION) {
  13315. throw new error_1.MongoCompatibilityError(`${INVALID_QE_VERSION} The minimum server version required is ${constants_1.MIN_SUPPORTED_QE_SERVER_VERSION}`);
  13316. }
  13317. const escCollection = encryptedFields.escCollection ?? `enxcol_.${name}.esc`;
  13318. const ecocCollection = encryptedFields.ecocCollection ?? `enxcol_.${name}.ecoc`;
  13319. for (const collectionName of [escCollection, ecocCollection]) {
  13320. const createOp = new _CreateCollectionOperation(db, collectionName, {
  13321. clusteredIndex: {
  13322. key: { _id: 1 },
  13323. unique: true
  13324. }
  13325. });
  13326. await createOp.executeWithoutEncryptedFieldsCheck(server, session);
  13327. }
  13328. if (!options.encryptedFields) {
  13329. this.options = { ...this.options, encryptedFields };
  13330. }
  13331. }
  13332. const coll = await this.executeWithoutEncryptedFieldsCheck(server, session);
  13333. if (encryptedFields) {
  13334. const createIndexOp = new indexes_1.CreateIndexOperation(db, name, { __safeContent__: 1 }, {});
  13335. await createIndexOp.execute(server, session);
  13336. }
  13337. return coll;
  13338. })().then((coll) => callback(void 0, coll), (err) => callback(err));
  13339. }
  13340. executeWithoutEncryptedFieldsCheck(server, session) {
  13341. return new Promise((resolve, reject) => {
  13342. const db = this.db;
  13343. const name = this.name;
  13344. const options = this.options;
  13345. const done = /* @__PURE__ */ __name((err) => {
  13346. if (err) {
  13347. return reject(err);
  13348. }
  13349. resolve(new collection_1.Collection(db, name, options));
  13350. }, "done");
  13351. const cmd = { create: name };
  13352. for (const n in options) {
  13353. if (options[n] != null && typeof options[n] !== "function" && !ILLEGAL_COMMAND_FIELDS.has(n)) {
  13354. cmd[n] = options[n];
  13355. }
  13356. }
  13357. super.executeCommandCallback(server, session, cmd, done);
  13358. });
  13359. }
  13360. };
  13361. __name(_CreateCollectionOperation, "CreateCollectionOperation");
  13362. var CreateCollectionOperation = _CreateCollectionOperation;
  13363. exports2.CreateCollectionOperation = CreateCollectionOperation;
  13364. (0, operation_1.defineAspects)(CreateCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]);
  13365. }
  13366. });
  13367. // node_modules/mongodb/lib/operations/profiling_level.js
  13368. var require_profiling_level = __commonJS({
  13369. "node_modules/mongodb/lib/operations/profiling_level.js"(exports2) {
  13370. "use strict";
  13371. Object.defineProperty(exports2, "__esModule", { value: true });
  13372. exports2.ProfilingLevelOperation = void 0;
  13373. var error_1 = require_error();
  13374. var command_1 = require_command();
  13375. var _ProfilingLevelOperation = class _ProfilingLevelOperation extends command_1.CommandCallbackOperation {
  13376. constructor(db, options) {
  13377. super(db, options);
  13378. this.options = options;
  13379. }
  13380. executeCallback(server, session, callback) {
  13381. super.executeCommandCallback(server, session, { profile: -1 }, (err, doc) => {
  13382. if (err == null && doc.ok === 1) {
  13383. const was = doc.was;
  13384. if (was === 0)
  13385. return callback(void 0, "off");
  13386. if (was === 1)
  13387. return callback(void 0, "slow_only");
  13388. if (was === 2)
  13389. return callback(void 0, "all");
  13390. return callback(new error_1.MongoRuntimeError(`Illegal profiling level value ${was}`));
  13391. } else {
  13392. err != null ? callback(err) : callback(new error_1.MongoRuntimeError("Error with profile command"));
  13393. }
  13394. });
  13395. }
  13396. };
  13397. __name(_ProfilingLevelOperation, "ProfilingLevelOperation");
  13398. var ProfilingLevelOperation = _ProfilingLevelOperation;
  13399. exports2.ProfilingLevelOperation = ProfilingLevelOperation;
  13400. }
  13401. });
  13402. // node_modules/mongodb/lib/operations/set_profiling_level.js
  13403. var require_set_profiling_level = __commonJS({
  13404. "node_modules/mongodb/lib/operations/set_profiling_level.js"(exports2) {
  13405. "use strict";
  13406. Object.defineProperty(exports2, "__esModule", { value: true });
  13407. exports2.SetProfilingLevelOperation = exports2.ProfilingLevel = void 0;
  13408. var error_1 = require_error();
  13409. var utils_1 = require_utils();
  13410. var command_1 = require_command();
  13411. var levelValues = /* @__PURE__ */ new Set(["off", "slow_only", "all"]);
  13412. exports2.ProfilingLevel = Object.freeze({
  13413. off: "off",
  13414. slowOnly: "slow_only",
  13415. all: "all"
  13416. });
  13417. var _SetProfilingLevelOperation = class _SetProfilingLevelOperation extends command_1.CommandCallbackOperation {
  13418. constructor(db, level, options) {
  13419. super(db, options);
  13420. this.options = options;
  13421. switch (level) {
  13422. case exports2.ProfilingLevel.off:
  13423. this.profile = 0;
  13424. break;
  13425. case exports2.ProfilingLevel.slowOnly:
  13426. this.profile = 1;
  13427. break;
  13428. case exports2.ProfilingLevel.all:
  13429. this.profile = 2;
  13430. break;
  13431. default:
  13432. this.profile = 0;
  13433. break;
  13434. }
  13435. this.level = level;
  13436. }
  13437. executeCallback(server, session, callback) {
  13438. const level = this.level;
  13439. if (!levelValues.has(level)) {
  13440. return callback(new error_1.MongoInvalidArgumentError(`Profiling level must be one of "${(0, utils_1.enumToString)(exports2.ProfilingLevel)}"`));
  13441. }
  13442. super.executeCommandCallback(server, session, { profile: this.profile }, (err, doc) => {
  13443. if (err == null && doc.ok === 1)
  13444. return callback(void 0, level);
  13445. return err != null ? callback(err) : callback(new error_1.MongoRuntimeError("Error with profile command"));
  13446. });
  13447. }
  13448. };
  13449. __name(_SetProfilingLevelOperation, "SetProfilingLevelOperation");
  13450. var SetProfilingLevelOperation = _SetProfilingLevelOperation;
  13451. exports2.SetProfilingLevelOperation = SetProfilingLevelOperation;
  13452. }
  13453. });
  13454. // node_modules/mongodb/lib/db.js
  13455. var require_db = __commonJS({
  13456. "node_modules/mongodb/lib/db.js"(exports2) {
  13457. "use strict";
  13458. Object.defineProperty(exports2, "__esModule", { value: true });
  13459. exports2.Db = void 0;
  13460. var admin_1 = require_admin();
  13461. var bson_1 = require_bson2();
  13462. var change_stream_1 = require_change_stream();
  13463. var collection_1 = require_collection();
  13464. var CONSTANTS = require_constants2();
  13465. var aggregation_cursor_1 = require_aggregation_cursor();
  13466. var list_collections_cursor_1 = require_list_collections_cursor();
  13467. var run_command_cursor_1 = require_run_command_cursor();
  13468. var error_1 = require_error();
  13469. var add_user_1 = require_add_user();
  13470. var collections_1 = require_collections();
  13471. var create_collection_1 = require_create_collection();
  13472. var drop_1 = require_drop();
  13473. var execute_operation_1 = require_execute_operation();
  13474. var indexes_1 = require_indexes();
  13475. var profiling_level_1 = require_profiling_level();
  13476. var remove_user_1 = require_remove_user();
  13477. var rename_1 = require_rename();
  13478. var run_command_1 = require_run_command();
  13479. var set_profiling_level_1 = require_set_profiling_level();
  13480. var stats_1 = require_stats();
  13481. var read_concern_1 = require_read_concern();
  13482. var read_preference_1 = require_read_preference();
  13483. var utils_1 = require_utils();
  13484. var write_concern_1 = require_write_concern();
  13485. var DB_OPTIONS_ALLOW_LIST = [
  13486. "writeConcern",
  13487. "readPreference",
  13488. "readPreferenceTags",
  13489. "native_parser",
  13490. "forceServerObjectId",
  13491. "pkFactory",
  13492. "serializeFunctions",
  13493. "raw",
  13494. "authSource",
  13495. "ignoreUndefined",
  13496. "readConcern",
  13497. "retryMiliSeconds",
  13498. "numberOfRetries",
  13499. "useBigInt64",
  13500. "promoteBuffers",
  13501. "promoteLongs",
  13502. "bsonRegExp",
  13503. "enableUtf8Validation",
  13504. "promoteValues",
  13505. "compression",
  13506. "retryWrites"
  13507. ];
  13508. var _Db = class _Db {
  13509. /**
  13510. * Creates a new Db instance
  13511. *
  13512. * @param client - The MongoClient for the database.
  13513. * @param databaseName - The name of the database this instance represents.
  13514. * @param options - Optional settings for Db construction
  13515. */
  13516. constructor(client, databaseName, options) {
  13517. options = options ?? {};
  13518. options = (0, utils_1.filterOptions)(options, DB_OPTIONS_ALLOW_LIST);
  13519. validateDatabaseName(databaseName);
  13520. this.s = {
  13521. // Options
  13522. options,
  13523. // Unpack read preference
  13524. readPreference: read_preference_1.ReadPreference.fromOptions(options),
  13525. // Merge bson options
  13526. bsonOptions: (0, bson_1.resolveBSONOptions)(options, client),
  13527. // Set up the primary key factory or fallback to ObjectId
  13528. pkFactory: (options == null ? void 0 : options.pkFactory) ?? utils_1.DEFAULT_PK_FACTORY,
  13529. // ReadConcern
  13530. readConcern: read_concern_1.ReadConcern.fromOptions(options),
  13531. writeConcern: write_concern_1.WriteConcern.fromOptions(options),
  13532. // Namespace
  13533. namespace: new utils_1.MongoDBNamespace(databaseName)
  13534. };
  13535. this.client = client;
  13536. }
  13537. get databaseName() {
  13538. return this.s.namespace.db;
  13539. }
  13540. // Options
  13541. get options() {
  13542. return this.s.options;
  13543. }
  13544. /**
  13545. * Check if a secondary can be used (because the read preference is *not* set to primary)
  13546. */
  13547. get secondaryOk() {
  13548. var _a;
  13549. return ((_a = this.s.readPreference) == null ? void 0 : _a.preference) !== "primary" || false;
  13550. }
  13551. get readConcern() {
  13552. return this.s.readConcern;
  13553. }
  13554. /**
  13555. * The current readPreference of the Db. If not explicitly defined for
  13556. * this Db, will be inherited from the parent MongoClient
  13557. */
  13558. get readPreference() {
  13559. if (this.s.readPreference == null) {
  13560. return this.client.readPreference;
  13561. }
  13562. return this.s.readPreference;
  13563. }
  13564. get bsonOptions() {
  13565. return this.s.bsonOptions;
  13566. }
  13567. // get the write Concern
  13568. get writeConcern() {
  13569. return this.s.writeConcern;
  13570. }
  13571. get namespace() {
  13572. return this.s.namespace.toString();
  13573. }
  13574. /**
  13575. * Create a new collection on a server with the specified options. Use this to create capped collections.
  13576. * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
  13577. *
  13578. * @param name - The name of the collection to create
  13579. * @param options - Optional settings for the command
  13580. */
  13581. async createCollection(name, options) {
  13582. return (0, execute_operation_1.executeOperation)(this.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
  13583. }
  13584. /**
  13585. * Execute a command
  13586. *
  13587. * @remarks
  13588. * This command does not inherit options from the MongoClient.
  13589. *
  13590. * The driver will ensure the following fields are attached to the command sent to the server:
  13591. * - `lsid` - sourced from an implicit session or options.session
  13592. * - `$readPreference` - defaults to primary or can be configured by options.readPreference
  13593. * - `$db` - sourced from the name of this database
  13594. *
  13595. * If the client has a serverApi setting:
  13596. * - `apiVersion`
  13597. * - `apiStrict`
  13598. * - `apiDeprecationErrors`
  13599. *
  13600. * When in a transaction:
  13601. * - `readConcern` - sourced from readConcern set on the TransactionOptions
  13602. * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
  13603. *
  13604. * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
  13605. *
  13606. * @param command - The command to run
  13607. * @param options - Optional settings for the command
  13608. */
  13609. async command(command, options) {
  13610. return (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(this, command, options));
  13611. }
  13612. /**
  13613. * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6
  13614. *
  13615. * @param pipeline - An array of aggregation stages to be executed
  13616. * @param options - Optional settings for the command
  13617. */
  13618. aggregate(pipeline = [], options) {
  13619. return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options));
  13620. }
  13621. /** Return the Admin db instance */
  13622. admin() {
  13623. return new admin_1.Admin(this);
  13624. }
  13625. /**
  13626. * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
  13627. *
  13628. * @param name - the collection name we wish to access.
  13629. * @returns return the new Collection instance
  13630. */
  13631. collection(name, options = {}) {
  13632. if (typeof options === "function") {
  13633. throw new error_1.MongoInvalidArgumentError("The callback form of this helper has been removed.");
  13634. }
  13635. return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options));
  13636. }
  13637. /**
  13638. * Get all the db statistics.
  13639. *
  13640. * @param options - Optional settings for the command
  13641. */
  13642. async stats(options) {
  13643. return (0, execute_operation_1.executeOperation)(this.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)));
  13644. }
  13645. listCollections(filter = {}, options = {}) {
  13646. return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options));
  13647. }
  13648. /**
  13649. * Rename a collection.
  13650. *
  13651. * @remarks
  13652. * This operation does not inherit options from the MongoClient.
  13653. *
  13654. * @param fromCollection - Name of current collection to rename
  13655. * @param toCollection - New name of of the collection
  13656. * @param options - Optional settings for the command
  13657. */
  13658. async renameCollection(fromCollection, toCollection, options) {
  13659. return (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, { ...options, new_collection: true, readPreference: read_preference_1.ReadPreference.primary }));
  13660. }
  13661. /**
  13662. * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
  13663. *
  13664. * @param name - Name of collection to drop
  13665. * @param options - Optional settings for the command
  13666. */
  13667. async dropCollection(name, options) {
  13668. return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
  13669. }
  13670. /**
  13671. * Drop a database, removing it permanently from the server.
  13672. *
  13673. * @param options - Optional settings for the command
  13674. */
  13675. async dropDatabase(options) {
  13676. return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)));
  13677. }
  13678. /**
  13679. * Fetch all collections for the current db.
  13680. *
  13681. * @param options - Optional settings for the command
  13682. */
  13683. async collections(options) {
  13684. return (0, execute_operation_1.executeOperation)(this.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options)));
  13685. }
  13686. /**
  13687. * Creates an index on the db and collection.
  13688. *
  13689. * @param name - Name of the collection to create the index on.
  13690. * @param indexSpec - Specify the field to index, or an index specification
  13691. * @param options - Optional settings for the command
  13692. */
  13693. async createIndex(name, indexSpec, options) {
  13694. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options)));
  13695. }
  13696. /**
  13697. * Add a user to the database
  13698. *
  13699. * @param username - The username for the new user
  13700. * @param passwordOrOptions - An optional password for the new user, or the options for the command
  13701. * @param options - Optional settings for the command
  13702. * @deprecated Use the createUser command in `db.command()` instead.
  13703. * @see https://www.mongodb.com/docs/manual/reference/command/createUser/
  13704. */
  13705. async addUser(username, passwordOrOptions, options) {
  13706. options = options != null && typeof options === "object" ? options : passwordOrOptions != null && typeof passwordOrOptions === "object" ? passwordOrOptions : void 0;
  13707. const password = typeof passwordOrOptions === "string" ? passwordOrOptions : void 0;
  13708. return (0, execute_operation_1.executeOperation)(this.client, new add_user_1.AddUserOperation(this, username, password, (0, utils_1.resolveOptions)(this, options)));
  13709. }
  13710. /**
  13711. * Remove a user from a database
  13712. *
  13713. * @param username - The username to remove
  13714. * @param options - Optional settings for the command
  13715. */
  13716. async removeUser(username, options) {
  13717. return (0, execute_operation_1.executeOperation)(this.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)));
  13718. }
  13719. /**
  13720. * Set the current profiling level of MongoDB
  13721. *
  13722. * @param level - The new profiling level (off, slow_only, all).
  13723. * @param options - Optional settings for the command
  13724. */
  13725. async setProfilingLevel(level, options) {
  13726. return (0, execute_operation_1.executeOperation)(this.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)));
  13727. }
  13728. /**
  13729. * Retrieve the current profiling Level for MongoDB
  13730. *
  13731. * @param options - Optional settings for the command
  13732. */
  13733. async profilingLevel(options) {
  13734. return (0, execute_operation_1.executeOperation)(this.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)));
  13735. }
  13736. /**
  13737. * Retrieves this collections index info.
  13738. *
  13739. * @param name - The name of the collection.
  13740. * @param options - Optional settings for the command
  13741. */
  13742. async indexInformation(name, options) {
  13743. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
  13744. }
  13745. /**
  13746. * Create a new Change Stream, watching for new changes (insertions, updates,
  13747. * replacements, deletions, and invalidations) in this database. Will ignore all
  13748. * changes to system collections.
  13749. *
  13750. * @remarks
  13751. * watch() accepts two generic arguments for distinct use cases:
  13752. * - The first is to provide the schema that may be defined for all the collections within this database
  13753. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  13754. *
  13755. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  13756. * @param options - Optional settings for the command
  13757. * @typeParam TSchema - Type of the data being detected by the change stream
  13758. * @typeParam TChange - Type of the whole change stream document emitted
  13759. */
  13760. watch(pipeline = [], options = {}) {
  13761. if (!Array.isArray(pipeline)) {
  13762. options = pipeline;
  13763. pipeline = [];
  13764. }
  13765. return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options));
  13766. }
  13767. /**
  13768. * A low level cursor API providing basic driver functionality:
  13769. * - ClientSession management
  13770. * - ReadPreference for server selection
  13771. * - Running getMores automatically when a local batch is exhausted
  13772. *
  13773. * @param command - The command that will start a cursor on the server.
  13774. * @param options - Configurations for running the command, bson options will apply to getMores
  13775. */
  13776. runCursorCommand(command, options) {
  13777. return new run_command_cursor_1.RunCommandCursor(this, command, options);
  13778. }
  13779. };
  13780. __name(_Db, "Db");
  13781. var Db = _Db;
  13782. Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;
  13783. Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;
  13784. Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;
  13785. Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;
  13786. Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;
  13787. Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;
  13788. exports2.Db = Db;
  13789. function validateDatabaseName(databaseName) {
  13790. if (typeof databaseName !== "string")
  13791. throw new error_1.MongoInvalidArgumentError("Database name must be a string");
  13792. if (databaseName.length === 0)
  13793. throw new error_1.MongoInvalidArgumentError("Database name cannot be the empty string");
  13794. if (databaseName === "$external")
  13795. return;
  13796. const invalidChars = [" ", ".", "$", "/", "\\"];
  13797. for (let i = 0; i < invalidChars.length; i++) {
  13798. if (databaseName.indexOf(invalidChars[i]) !== -1)
  13799. throw new error_1.MongoAPIError(`database names cannot contain the character '${invalidChars[i]}'`);
  13800. }
  13801. }
  13802. __name(validateDatabaseName, "validateDatabaseName");
  13803. }
  13804. });
  13805. // node_modules/@mongodb-js/saslprep/dist/index.js
  13806. var require_dist = __commonJS({
  13807. "node_modules/@mongodb-js/saslprep/dist/index.js"(exports2, module2) {
  13808. "use strict";
  13809. var getCodePoint = /* @__PURE__ */ __name((character) => character.codePointAt(0), "getCodePoint");
  13810. var first = /* @__PURE__ */ __name((x) => x[0], "first");
  13811. var last = /* @__PURE__ */ __name((x) => x[x.length - 1], "last");
  13812. function toCodePoints(input) {
  13813. const codepoints = [];
  13814. const size = input.length;
  13815. for (let i = 0; i < size; i += 1) {
  13816. const before = input.charCodeAt(i);
  13817. if (before >= 55296 && before <= 56319 && size > i + 1) {
  13818. const next = input.charCodeAt(i + 1);
  13819. if (next >= 56320 && next <= 57343) {
  13820. codepoints.push((before - 55296) * 1024 + next - 56320 + 65536);
  13821. i += 1;
  13822. continue;
  13823. }
  13824. }
  13825. codepoints.push(before);
  13826. }
  13827. return codepoints;
  13828. }
  13829. __name(toCodePoints, "toCodePoints");
  13830. function saslprep({ unassigned_code_points, commonly_mapped_to_nothing, non_ASCII_space_characters, prohibited_characters, bidirectional_r_al, bidirectional_l }, input, opts = {}) {
  13831. const mapping2space = non_ASCII_space_characters;
  13832. const mapping2nothing = commonly_mapped_to_nothing;
  13833. if (typeof input !== "string") {
  13834. throw new TypeError("Expected string.");
  13835. }
  13836. if (input.length === 0) {
  13837. return "";
  13838. }
  13839. const mapped_input = toCodePoints(input).map((character) => mapping2space.get(character) ? 32 : character).filter((character) => !mapping2nothing.get(character));
  13840. const normalized_input = String.fromCodePoint.apply(null, mapped_input).normalize("NFKC");
  13841. const normalized_map = toCodePoints(normalized_input);
  13842. const hasProhibited = normalized_map.some((character) => prohibited_characters.get(character));
  13843. if (hasProhibited) {
  13844. throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");
  13845. }
  13846. if (opts.allowUnassigned !== true) {
  13847. const hasUnassigned = normalized_map.some((character) => unassigned_code_points.get(character));
  13848. if (hasUnassigned) {
  13849. throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5");
  13850. }
  13851. }
  13852. const hasBidiRAL = normalized_map.some((character) => bidirectional_r_al.get(character));
  13853. const hasBidiL = normalized_map.some((character) => bidirectional_l.get(character));
  13854. if (hasBidiRAL && hasBidiL) {
  13855. throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");
  13856. }
  13857. const isFirstBidiRAL = bidirectional_r_al.get(getCodePoint(first(normalized_input)));
  13858. const isLastBidiRAL = bidirectional_r_al.get(getCodePoint(last(normalized_input)));
  13859. if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) {
  13860. throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");
  13861. }
  13862. return normalized_input;
  13863. }
  13864. __name(saslprep, "saslprep");
  13865. saslprep.saslprep = saslprep;
  13866. saslprep.default = saslprep;
  13867. module2.exports = saslprep;
  13868. }
  13869. });
  13870. // node_modules/memory-pager/index.js
  13871. var require_memory_pager = __commonJS({
  13872. "node_modules/memory-pager/index.js"(exports2, module2) {
  13873. module2.exports = Pager;
  13874. function Pager(pageSize, opts) {
  13875. if (!(this instanceof Pager)) return new Pager(pageSize, opts);
  13876. this.length = 0;
  13877. this.updates = [];
  13878. this.path = new Uint16Array(4);
  13879. this.pages = new Array(32768);
  13880. this.maxPages = this.pages.length;
  13881. this.level = 0;
  13882. this.pageSize = pageSize || 1024;
  13883. this.deduplicate = opts ? opts.deduplicate : null;
  13884. this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null;
  13885. }
  13886. __name(Pager, "Pager");
  13887. Pager.prototype.updated = function(page) {
  13888. while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) {
  13889. page.deduplicate++;
  13890. if (page.deduplicate === this.deduplicate.length) {
  13891. page.deduplicate = 0;
  13892. if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate;
  13893. break;
  13894. }
  13895. }
  13896. if (page.updated || !this.updates) return;
  13897. page.updated = true;
  13898. this.updates.push(page);
  13899. };
  13900. Pager.prototype.lastUpdate = function() {
  13901. if (!this.updates || !this.updates.length) return null;
  13902. var page = this.updates.pop();
  13903. page.updated = false;
  13904. return page;
  13905. };
  13906. Pager.prototype._array = function(i, noAllocate) {
  13907. if (i >= this.maxPages) {
  13908. if (noAllocate) return;
  13909. grow(this, i);
  13910. }
  13911. factor(i, this.path);
  13912. var arr = this.pages;
  13913. for (var j = this.level; j > 0; j--) {
  13914. var p = this.path[j];
  13915. var next = arr[p];
  13916. if (!next) {
  13917. if (noAllocate) return;
  13918. next = arr[p] = new Array(32768);
  13919. }
  13920. arr = next;
  13921. }
  13922. return arr;
  13923. };
  13924. Pager.prototype.get = function(i, noAllocate) {
  13925. var arr = this._array(i, noAllocate);
  13926. var first = this.path[0];
  13927. var page = arr && arr[first];
  13928. if (!page && !noAllocate) {
  13929. page = arr[first] = new Page(i, alloc(this.pageSize));
  13930. if (i >= this.length) this.length = i + 1;
  13931. }
  13932. if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) {
  13933. page.buffer = copy(page.buffer);
  13934. page.deduplicate = 0;
  13935. }
  13936. return page;
  13937. };
  13938. Pager.prototype.set = function(i, buf) {
  13939. var arr = this._array(i, false);
  13940. var first = this.path[0];
  13941. if (i >= this.length) this.length = i + 1;
  13942. if (!buf || this.zeros && buf.equals && buf.equals(this.zeros)) {
  13943. arr[first] = void 0;
  13944. return;
  13945. }
  13946. if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) {
  13947. buf = this.deduplicate;
  13948. }
  13949. var page = arr[first];
  13950. var b = truncate(buf, this.pageSize);
  13951. if (page) page.buffer = b;
  13952. else arr[first] = new Page(i, b);
  13953. };
  13954. Pager.prototype.toBuffer = function() {
  13955. var list = new Array(this.length);
  13956. var empty = alloc(this.pageSize);
  13957. var ptr = 0;
  13958. while (ptr < list.length) {
  13959. var arr = this._array(ptr, true);
  13960. for (var i = 0; i < 32768 && ptr < list.length; i++) {
  13961. list[ptr++] = arr && arr[i] ? arr[i].buffer : empty;
  13962. }
  13963. }
  13964. return Buffer.concat(list);
  13965. };
  13966. function grow(pager, index) {
  13967. while (pager.maxPages < index) {
  13968. var old = pager.pages;
  13969. pager.pages = new Array(32768);
  13970. pager.pages[0] = old;
  13971. pager.level++;
  13972. pager.maxPages *= 32768;
  13973. }
  13974. }
  13975. __name(grow, "grow");
  13976. function truncate(buf, len) {
  13977. if (buf.length === len) return buf;
  13978. if (buf.length > len) return buf.slice(0, len);
  13979. var cpy = alloc(len);
  13980. buf.copy(cpy);
  13981. return cpy;
  13982. }
  13983. __name(truncate, "truncate");
  13984. function alloc(size) {
  13985. if (Buffer.alloc) return Buffer.alloc(size);
  13986. var buf = new Buffer(size);
  13987. buf.fill(0);
  13988. return buf;
  13989. }
  13990. __name(alloc, "alloc");
  13991. function copy(buf) {
  13992. var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length);
  13993. buf.copy(cpy);
  13994. return cpy;
  13995. }
  13996. __name(copy, "copy");
  13997. function Page(i, buf) {
  13998. this.offset = i * buf.length;
  13999. this.buffer = buf;
  14000. this.updated = false;
  14001. this.deduplicate = 0;
  14002. }
  14003. __name(Page, "Page");
  14004. function factor(n, out) {
  14005. n = (n - (out[0] = n & 32767)) / 32768;
  14006. n = (n - (out[1] = n & 32767)) / 32768;
  14007. out[3] = (n - (out[2] = n & 32767)) / 32768 & 32767;
  14008. }
  14009. __name(factor, "factor");
  14010. }
  14011. });
  14012. // node_modules/sparse-bitfield/index.js
  14013. var require_sparse_bitfield = __commonJS({
  14014. "node_modules/sparse-bitfield/index.js"(exports2, module2) {
  14015. var pager = require_memory_pager();
  14016. module2.exports = Bitfield;
  14017. function Bitfield(opts) {
  14018. if (!(this instanceof Bitfield)) return new Bitfield(opts);
  14019. if (!opts) opts = {};
  14020. if (Buffer.isBuffer(opts)) opts = { buffer: opts };
  14021. this.pageOffset = opts.pageOffset || 0;
  14022. this.pageSize = opts.pageSize || 1024;
  14023. this.pages = opts.pages || pager(this.pageSize);
  14024. this.byteLength = this.pages.length * this.pageSize;
  14025. this.length = 8 * this.byteLength;
  14026. if (!powerOfTwo(this.pageSize)) throw new Error("The page size should be a power of two");
  14027. this._trackUpdates = !!opts.trackUpdates;
  14028. this._pageMask = this.pageSize - 1;
  14029. if (opts.buffer) {
  14030. for (var i = 0; i < opts.buffer.length; i += this.pageSize) {
  14031. this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize));
  14032. }
  14033. this.byteLength = opts.buffer.length;
  14034. this.length = 8 * this.byteLength;
  14035. }
  14036. }
  14037. __name(Bitfield, "Bitfield");
  14038. Bitfield.prototype.get = function(i) {
  14039. var o = i & 7;
  14040. var j = (i - o) / 8;
  14041. return !!(this.getByte(j) & 128 >> o);
  14042. };
  14043. Bitfield.prototype.getByte = function(i) {
  14044. var o = i & this._pageMask;
  14045. var j = (i - o) / this.pageSize;
  14046. var page = this.pages.get(j, true);
  14047. return page ? page.buffer[o + this.pageOffset] : 0;
  14048. };
  14049. Bitfield.prototype.set = function(i, v) {
  14050. var o = i & 7;
  14051. var j = (i - o) / 8;
  14052. var b = this.getByte(j);
  14053. return this.setByte(j, v ? b | 128 >> o : b & (255 ^ 128 >> o));
  14054. };
  14055. Bitfield.prototype.toBuffer = function() {
  14056. var all = alloc(this.pages.length * this.pageSize);
  14057. for (var i = 0; i < this.pages.length; i++) {
  14058. var next = this.pages.get(i, true);
  14059. var allOffset = i * this.pageSize;
  14060. if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize);
  14061. }
  14062. return all;
  14063. };
  14064. Bitfield.prototype.setByte = function(i, b) {
  14065. var o = i & this._pageMask;
  14066. var j = (i - o) / this.pageSize;
  14067. var page = this.pages.get(j, false);
  14068. o += this.pageOffset;
  14069. if (page.buffer[o] === b) return false;
  14070. page.buffer[o] = b;
  14071. if (i >= this.byteLength) {
  14072. this.byteLength = i + 1;
  14073. this.length = this.byteLength * 8;
  14074. }
  14075. if (this._trackUpdates) this.pages.updated(page);
  14076. return true;
  14077. };
  14078. function alloc(n) {
  14079. if (Buffer.alloc) return Buffer.alloc(n);
  14080. var b = new Buffer(n);
  14081. b.fill(0);
  14082. return b;
  14083. }
  14084. __name(alloc, "alloc");
  14085. function powerOfTwo(x) {
  14086. return !(x & x - 1);
  14087. }
  14088. __name(powerOfTwo, "powerOfTwo");
  14089. }
  14090. });
  14091. // node_modules/@mongodb-js/saslprep/dist/memory-code-points.js
  14092. var require_memory_code_points = __commonJS({
  14093. "node_modules/@mongodb-js/saslprep/dist/memory-code-points.js"(exports2) {
  14094. "use strict";
  14095. var __importDefault = exports2 && exports2.__importDefault || function(mod) {
  14096. return mod && mod.__esModule ? mod : { "default": mod };
  14097. };
  14098. Object.defineProperty(exports2, "__esModule", { value: true });
  14099. exports2.createMemoryCodePoints = void 0;
  14100. var sparse_bitfield_1 = __importDefault(require_sparse_bitfield());
  14101. function createMemoryCodePoints(data) {
  14102. let offset = 0;
  14103. function read() {
  14104. const size = data.readUInt32BE(offset);
  14105. offset += 4;
  14106. const codepoints = data.slice(offset, offset + size);
  14107. offset += size;
  14108. return (0, sparse_bitfield_1.default)({ buffer: codepoints });
  14109. }
  14110. __name(read, "read");
  14111. const unassigned_code_points = read();
  14112. const commonly_mapped_to_nothing = read();
  14113. const non_ASCII_space_characters = read();
  14114. const prohibited_characters = read();
  14115. const bidirectional_r_al = read();
  14116. const bidirectional_l = read();
  14117. return {
  14118. unassigned_code_points,
  14119. commonly_mapped_to_nothing,
  14120. non_ASCII_space_characters,
  14121. prohibited_characters,
  14122. bidirectional_r_al,
  14123. bidirectional_l
  14124. };
  14125. }
  14126. __name(createMemoryCodePoints, "createMemoryCodePoints");
  14127. exports2.createMemoryCodePoints = createMemoryCodePoints;
  14128. }
  14129. });
  14130. // node_modules/@mongodb-js/saslprep/dist/code-points-data.js
  14131. var require_code_points_data = __commonJS({
  14132. "node_modules/@mongodb-js/saslprep/dist/code-points-data.js"(exports2) {
  14133. "use strict";
  14134. Object.defineProperty(exports2, "__esModule", { value: true });
  14135. var zlib_1 = require("zlib");
  14136. exports2.default = (0, zlib_1.gunzipSync)(Buffer.from("H4sIAAAAAAACA+3dTYgcaRkA4LemO9Mhxm0FITnE9Cwr4jHgwgZ22B6YywqCJ0HQg5CL4sGTuOjCtGSF4CkHEW856MlTQHD3EJnWkU0Owh5VxE3LHlYQdNxd2U6mU59UV/d09fw4M2EySSXPAzNdP1/9fX/99bzVNZEN4jisRDulVFnQmLxm1aXF9Id/2/xMxNJ4XZlg576yuYlGt9gupV6xoFf8jhu9YvulVrFlp5XSx+lfvYhORGPXvqIRWSxERKtIm8bKFd10WNfKDS5Fo9jJWrq2+M2IlW+8uHgl/+BsROfPF4v5L7148Ur68Sha6dqZpYiVVy8tvLCWXo80Sf/lS89dGX2wHGvpzoXVn75/YWH5wmqe8uika82ViJXTy83Ve2k5Urozm38wm4/ls6t5uT6yfsTSJ7J3T0VKt8c5ExEXI8aFkH729c3eT+7EC6ca8cVULZUiYacX0R5PNWNxlh9L1y90q5kyzrpyy+9WcvOV6URntqw7La9sNVstXyczWVaWYbaaTYqzOHpr7pyiNT3/YzKuT63Z/FqKZlFTiuXtFM2vVOtIq7jiyKJbWZaOWD0euz0yoV2Z7kY0xq2x0YhfzVpmM5px9nTEH7JZ0ot5u39p0ma75Z472/s/H+2yr2inYyuq7fMvJivH2rM72N/Z3lyL31F2b1ya1P0zn816k2KP6JU9UzseucdQH5YqVeH/lFajSN2udg+TLJ9rksNxlvV2lki19rXKI43TPLejFu4ov7k3nMbhyhfY3Xb37f8BAGCf0eMTOH5szf154KmnNgKcnLb+Fzi2AfXktbN7fJelwTAiO/W5uQ2KINXRYu+znqo/WTAdLadURHmy3qciazd3bra4T3w16/f7t7Ms9U5gfJu10955sx1r3vmhBAAAAAAAgId20J1iZbDowNvIjuH427Gr5l/eiC+8OplZON8sVjx/qr9y+Pj+YRItT+NqAM+kkZs3AAAAAID6yfx1FwCAI97/dCh1/ub6SA0AAAAAAAAAgNoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hutp5SiQpYAAAAAAAAAQO2MIpZiT804flnAE2fhwjOeAZXr76kOAAAAAAAA8FjNf4N/l0NE3U/vuVQskLpSd4/Yh2xu9xTu0tFeeNYsLI2f/VMdNxTzj6Je9E/+6pp6Nn3awW3A54goe4Bss6v+PGsjQGMAAAAAAOBp5XEgwH6e7J7rwEQHRb/XvAMAAAAAAAA8yzoDeQDwVGjIAgAAAAAAAACoPfF/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqL/GSkSkClkCAAAAAAAAALXTSAAAAAAAAABA3Y1kAQAAAAAAAADUX8RSXZ9dsHC9+M8Fg2Ex/em1lAZpEBGttcrVjZqLEa+k0XpKw9mG4zWx4ukPUMhkAQAAAAAAABzBqbSe3//rXOS9HxGdo4TqR2XkutCdBu+LaPZw/lBbO7cbHnh2C7N7AIo4evEznllqLqWUp/LnYOtpM2bnOH66wI1+9GO4sOuISwv/TOlumu56FDv3NZhc4mR9v7zYIrafr40j/Cccvj9Xns3t3mu99E7qxUv3bqS0/ouNH/08++RGemfQ+nsx/5uNXsQPGulynPvv3ZTW37zd+1ovrqaYpP/122X6Xpx779Z3zr/3YOPKW1lkaRDf31pPaf3j/msRsVGkL+d/f+/m4sJsPm1cfSsr16e8m9Ldj/KsnyIuR3nXw83Is3EhxLd/2V773ks3m/cj/THKUummdP9qKhIOImuOU0Xjwb3y+oqt735rpTetVbF9n8R4x9crRfO77TKqVOZpDclv5bfK18lMnk+q0K18UpxF/RrGXE0Zxtqx3tWSj+vxbL4XaasfKb0dRbtLW73JsfPGg177H+OmGKlfvS1msllt7JEJm9XOJqXR+Fkfo1H66uy5H1v3Xx5+uJmGLw9jro2u7Loj4PnuR6+f+e3d261+eazNhzrL7X83MohoHpS4PddV8ki1it61//pw1g7z6p1U/26Nm2llST57B5rUvuG0XqSU/rPd7jYrqWcbd+beJQ77BgPMDwn37/8BAGCf0eMTOH4cPlufv9VGgJOzqf8Fjm1APXkd7B7f5dF57GPMaWy/MTvjvNvtXj6h8W2+GXvnzXaseeeHEgAAAAAAAB7aQXeKlcGiadBoEOeLb2dtpGOL2MyOtf391a3P/zD96c3JzIP3t4oV797vrh8+vn+YRL5bBuj/AQAAAABqJvfHXQAAHkX82zfXAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACeAgkAAAAAAAAAqLuRLAAAAAAAAACA2hv9D1iu/VAYaAYA", "base64"));
  14137. }
  14138. });
  14139. // node_modules/@mongodb-js/saslprep/dist/node.js
  14140. var require_node = __commonJS({
  14141. "node_modules/@mongodb-js/saslprep/dist/node.js"(exports2, module2) {
  14142. "use strict";
  14143. var __importDefault = exports2 && exports2.__importDefault || function(mod) {
  14144. return mod && mod.__esModule ? mod : { "default": mod };
  14145. };
  14146. var index_1 = __importDefault(require_dist());
  14147. var memory_code_points_1 = require_memory_code_points();
  14148. var code_points_data_1 = __importDefault(require_code_points_data());
  14149. var codePoints = (0, memory_code_points_1.createMemoryCodePoints)(code_points_data_1.default);
  14150. function saslprep(input, opts) {
  14151. return (0, index_1.default)(codePoints, input, opts);
  14152. }
  14153. __name(saslprep, "saslprep");
  14154. saslprep.saslprep = saslprep;
  14155. saslprep.default = saslprep;
  14156. module2.exports = saslprep;
  14157. }
  14158. });
  14159. // node_modules/mongodb/lib/deps.js
  14160. var require_deps = __commonJS({
  14161. "node_modules/mongodb/lib/deps.js"(exports2) {
  14162. "use strict";
  14163. Object.defineProperty(exports2, "__esModule", { value: true });
  14164. exports2.AutoEncryptionLoggerLevel = exports2.aws4 = exports2.saslprep = exports2.getSnappy = exports2.getAwsCredentialProvider = exports2.getZstdLibrary = exports2.ZStandard = exports2.getKerberos = exports2.Kerberos = void 0;
  14165. var error_1 = require_error();
  14166. function makeErrorModule(error) {
  14167. const props = error ? { kModuleError: error } : {};
  14168. return new Proxy(props, {
  14169. get: /* @__PURE__ */ __name((_, key) => {
  14170. if (key === "kModuleError") {
  14171. return error;
  14172. }
  14173. throw error;
  14174. }, "get"),
  14175. set: /* @__PURE__ */ __name(() => {
  14176. throw error;
  14177. }, "set")
  14178. });
  14179. }
  14180. __name(makeErrorModule, "makeErrorModule");
  14181. exports2.Kerberos = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `kerberos` not found. Please install it to enable kerberos authentication"));
  14182. function getKerberos() {
  14183. try {
  14184. exports2.Kerberos = require("kerberos");
  14185. return exports2.Kerberos;
  14186. } catch {
  14187. return exports2.Kerberos;
  14188. }
  14189. }
  14190. __name(getKerberos, "getKerberos");
  14191. exports2.getKerberos = getKerberos;
  14192. exports2.ZStandard = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression"));
  14193. function getZstdLibrary() {
  14194. try {
  14195. exports2.ZStandard = require("@mongodb-js/zstd");
  14196. return exports2.ZStandard;
  14197. } catch {
  14198. return exports2.ZStandard;
  14199. }
  14200. }
  14201. __name(getZstdLibrary, "getZstdLibrary");
  14202. exports2.getZstdLibrary = getZstdLibrary;
  14203. function getAwsCredentialProvider() {
  14204. try {
  14205. const credentialProvider = require("@aws-sdk/credential-providers");
  14206. return credentialProvider;
  14207. } catch {
  14208. return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@aws-sdk/credential-providers` not found. Please install it to enable getting aws credentials via the official sdk."));
  14209. }
  14210. }
  14211. __name(getAwsCredentialProvider, "getAwsCredentialProvider");
  14212. exports2.getAwsCredentialProvider = getAwsCredentialProvider;
  14213. function getSnappy() {
  14214. try {
  14215. const value = require("snappy");
  14216. return value;
  14217. } catch (cause) {
  14218. const kModuleError = new error_1.MongoMissingDependencyError("Optional module `snappy` not found. Please install it to enable snappy compression", { cause });
  14219. return { kModuleError };
  14220. }
  14221. }
  14222. __name(getSnappy, "getSnappy");
  14223. exports2.getSnappy = getSnappy;
  14224. exports2.saslprep = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `saslprep` not found. Please install it to enable Stringprep Profile for User Names and Passwords"));
  14225. try {
  14226. exports2.saslprep = require_node();
  14227. } catch {
  14228. }
  14229. exports2.aws4 = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `aws4` not found. Please install it to enable AWS authentication"));
  14230. try {
  14231. exports2.aws4 = require("aws4");
  14232. } catch {
  14233. }
  14234. exports2.AutoEncryptionLoggerLevel = Object.freeze({
  14235. FatalError: 0,
  14236. Error: 1,
  14237. Warning: 2,
  14238. Info: 3,
  14239. Trace: 4
  14240. });
  14241. }
  14242. });
  14243. // node_modules/mongodb/lib/cmap/auth/auth_provider.js
  14244. var require_auth_provider = __commonJS({
  14245. "node_modules/mongodb/lib/cmap/auth/auth_provider.js"(exports2) {
  14246. "use strict";
  14247. Object.defineProperty(exports2, "__esModule", { value: true });
  14248. exports2.AuthProvider = exports2.AuthContext = void 0;
  14249. var error_1 = require_error();
  14250. var _AuthContext = class _AuthContext {
  14251. constructor(connection, credentials, options) {
  14252. this.reauthenticating = false;
  14253. this.connection = connection;
  14254. this.credentials = credentials;
  14255. this.options = options;
  14256. }
  14257. };
  14258. __name(_AuthContext, "AuthContext");
  14259. var AuthContext = _AuthContext;
  14260. exports2.AuthContext = AuthContext;
  14261. var _AuthProvider = class _AuthProvider {
  14262. /**
  14263. * Prepare the handshake document before the initial handshake.
  14264. *
  14265. * @param handshakeDoc - The document used for the initial handshake on a connection
  14266. * @param authContext - Context for authentication flow
  14267. */
  14268. async prepare(handshakeDoc, _authContext) {
  14269. return handshakeDoc;
  14270. }
  14271. /**
  14272. * Reauthenticate.
  14273. * @param context - The shared auth context.
  14274. */
  14275. async reauth(context) {
  14276. if (context.reauthenticating) {
  14277. throw new error_1.MongoRuntimeError("Reauthentication already in progress.");
  14278. }
  14279. try {
  14280. context.reauthenticating = true;
  14281. await this.auth(context);
  14282. } finally {
  14283. context.reauthenticating = false;
  14284. }
  14285. }
  14286. };
  14287. __name(_AuthProvider, "AuthProvider");
  14288. var AuthProvider = _AuthProvider;
  14289. exports2.AuthProvider = AuthProvider;
  14290. }
  14291. });
  14292. // node_modules/mongodb/lib/cmap/auth/gssapi.js
  14293. var require_gssapi = __commonJS({
  14294. "node_modules/mongodb/lib/cmap/auth/gssapi.js"(exports2) {
  14295. "use strict";
  14296. Object.defineProperty(exports2, "__esModule", { value: true });
  14297. exports2.resolveCname = exports2.performGSSAPICanonicalizeHostName = exports2.GSSAPI = exports2.GSSAPICanonicalizationValue = void 0;
  14298. var dns = require("dns");
  14299. var deps_1 = require_deps();
  14300. var error_1 = require_error();
  14301. var utils_1 = require_utils();
  14302. var auth_provider_1 = require_auth_provider();
  14303. exports2.GSSAPICanonicalizationValue = Object.freeze({
  14304. on: true,
  14305. off: false,
  14306. none: "none",
  14307. forward: "forward",
  14308. forwardAndReverse: "forwardAndReverse"
  14309. });
  14310. async function externalCommand(connection, command) {
  14311. return connection.commandAsync((0, utils_1.ns)("$external.$cmd"), command, void 0);
  14312. }
  14313. __name(externalCommand, "externalCommand");
  14314. var krb;
  14315. var _GSSAPI = class _GSSAPI extends auth_provider_1.AuthProvider {
  14316. async auth(authContext) {
  14317. const { connection, credentials } = authContext;
  14318. if (credentials == null) {
  14319. throw new error_1.MongoMissingCredentialsError("Credentials required for GSSAPI authentication");
  14320. }
  14321. const { username } = credentials;
  14322. const client = await makeKerberosClient(authContext);
  14323. const payload = await client.step("");
  14324. const saslStartResponse = await externalCommand(connection, saslStart(payload));
  14325. const negotiatedPayload = await negotiate(client, 10, saslStartResponse.payload);
  14326. const saslContinueResponse = await externalCommand(connection, saslContinue(negotiatedPayload, saslStartResponse.conversationId));
  14327. const finalizePayload = await finalize(client, username, saslContinueResponse.payload);
  14328. await externalCommand(connection, {
  14329. saslContinue: 1,
  14330. conversationId: saslContinueResponse.conversationId,
  14331. payload: finalizePayload
  14332. });
  14333. }
  14334. };
  14335. __name(_GSSAPI, "GSSAPI");
  14336. var GSSAPI = _GSSAPI;
  14337. exports2.GSSAPI = GSSAPI;
  14338. async function makeKerberosClient(authContext) {
  14339. const { hostAddress } = authContext.options;
  14340. const { credentials } = authContext;
  14341. if (!hostAddress || typeof hostAddress.host !== "string" || !credentials) {
  14342. throw new error_1.MongoInvalidArgumentError("Connection must have host and port and credentials defined.");
  14343. }
  14344. loadKrb();
  14345. if ("kModuleError" in krb) {
  14346. throw krb["kModuleError"];
  14347. }
  14348. const { initializeClient } = krb;
  14349. const { username, password } = credentials;
  14350. const mechanismProperties = credentials.mechanismProperties;
  14351. const serviceName = mechanismProperties.SERVICE_NAME ?? "mongodb";
  14352. const host = await performGSSAPICanonicalizeHostName(hostAddress.host, mechanismProperties);
  14353. const initOptions = {};
  14354. if (password != null) {
  14355. Object.assign(initOptions, { user: username, password });
  14356. }
  14357. const spnHost = mechanismProperties.SERVICE_HOST ?? host;
  14358. let spn = `${serviceName}${process.platform === "win32" ? "/" : "@"}${spnHost}`;
  14359. if ("SERVICE_REALM" in mechanismProperties) {
  14360. spn = `${spn}@${mechanismProperties.SERVICE_REALM}`;
  14361. }
  14362. return initializeClient(spn, initOptions);
  14363. }
  14364. __name(makeKerberosClient, "makeKerberosClient");
  14365. function saslStart(payload) {
  14366. return {
  14367. saslStart: 1,
  14368. mechanism: "GSSAPI",
  14369. payload,
  14370. autoAuthorize: 1
  14371. };
  14372. }
  14373. __name(saslStart, "saslStart");
  14374. function saslContinue(payload, conversationId) {
  14375. return {
  14376. saslContinue: 1,
  14377. conversationId,
  14378. payload
  14379. };
  14380. }
  14381. __name(saslContinue, "saslContinue");
  14382. async function negotiate(client, retries, payload) {
  14383. try {
  14384. const response = await client.step(payload);
  14385. return response || "";
  14386. } catch (error) {
  14387. if (retries === 0) {
  14388. throw error;
  14389. }
  14390. return negotiate(client, retries - 1, payload);
  14391. }
  14392. }
  14393. __name(negotiate, "negotiate");
  14394. async function finalize(client, user, payload) {
  14395. const response = await client.unwrap(payload);
  14396. return client.wrap(response || "", { user });
  14397. }
  14398. __name(finalize, "finalize");
  14399. async function performGSSAPICanonicalizeHostName(host, mechanismProperties) {
  14400. const mode = mechanismProperties.CANONICALIZE_HOST_NAME;
  14401. if (!mode || mode === exports2.GSSAPICanonicalizationValue.none) {
  14402. return host;
  14403. }
  14404. if (mode === exports2.GSSAPICanonicalizationValue.on || mode === exports2.GSSAPICanonicalizationValue.forwardAndReverse) {
  14405. const { address } = await dns.promises.lookup(host);
  14406. try {
  14407. const results = await dns.promises.resolvePtr(address);
  14408. return results.length > 0 ? results[0] : host;
  14409. } catch (error) {
  14410. return resolveCname(host);
  14411. }
  14412. } else {
  14413. return resolveCname(host);
  14414. }
  14415. }
  14416. __name(performGSSAPICanonicalizeHostName, "performGSSAPICanonicalizeHostName");
  14417. exports2.performGSSAPICanonicalizeHostName = performGSSAPICanonicalizeHostName;
  14418. async function resolveCname(host) {
  14419. try {
  14420. const results = await dns.promises.resolveCname(host);
  14421. return results.length > 0 ? results[0] : host;
  14422. } catch {
  14423. return host;
  14424. }
  14425. }
  14426. __name(resolveCname, "resolveCname");
  14427. exports2.resolveCname = resolveCname;
  14428. function loadKrb() {
  14429. if (!krb) {
  14430. krb = (0, deps_1.getKerberos)();
  14431. }
  14432. }
  14433. __name(loadKrb, "loadKrb");
  14434. }
  14435. });
  14436. // node_modules/mongodb/lib/cmap/auth/providers.js
  14437. var require_providers = __commonJS({
  14438. "node_modules/mongodb/lib/cmap/auth/providers.js"(exports2) {
  14439. "use strict";
  14440. Object.defineProperty(exports2, "__esModule", { value: true });
  14441. exports2.AUTH_MECHS_AUTH_SRC_EXTERNAL = exports2.AuthMechanism = void 0;
  14442. exports2.AuthMechanism = Object.freeze({
  14443. MONGODB_AWS: "MONGODB-AWS",
  14444. MONGODB_CR: "MONGODB-CR",
  14445. MONGODB_DEFAULT: "DEFAULT",
  14446. MONGODB_GSSAPI: "GSSAPI",
  14447. MONGODB_PLAIN: "PLAIN",
  14448. MONGODB_SCRAM_SHA1: "SCRAM-SHA-1",
  14449. MONGODB_SCRAM_SHA256: "SCRAM-SHA-256",
  14450. MONGODB_X509: "MONGODB-X509",
  14451. /** @experimental */
  14452. MONGODB_OIDC: "MONGODB-OIDC"
  14453. });
  14454. exports2.AUTH_MECHS_AUTH_SRC_EXTERNAL = /* @__PURE__ */ new Set([
  14455. exports2.AuthMechanism.MONGODB_GSSAPI,
  14456. exports2.AuthMechanism.MONGODB_AWS,
  14457. exports2.AuthMechanism.MONGODB_OIDC,
  14458. exports2.AuthMechanism.MONGODB_X509
  14459. ]);
  14460. }
  14461. });
  14462. // node_modules/mongodb/lib/cmap/auth/mongo_credentials.js
  14463. var require_mongo_credentials = __commonJS({
  14464. "node_modules/mongodb/lib/cmap/auth/mongo_credentials.js"(exports2) {
  14465. "use strict";
  14466. Object.defineProperty(exports2, "__esModule", { value: true });
  14467. exports2.MongoCredentials = exports2.DEFAULT_ALLOWED_HOSTS = void 0;
  14468. var error_1 = require_error();
  14469. var gssapi_1 = require_gssapi();
  14470. var providers_1 = require_providers();
  14471. function getDefaultAuthMechanism(hello) {
  14472. if (hello) {
  14473. if (Array.isArray(hello.saslSupportedMechs)) {
  14474. return hello.saslSupportedMechs.includes(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA256 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA1;
  14475. }
  14476. if (hello.maxWireVersion >= 3) {
  14477. return providers_1.AuthMechanism.MONGODB_SCRAM_SHA1;
  14478. }
  14479. }
  14480. return providers_1.AuthMechanism.MONGODB_CR;
  14481. }
  14482. __name(getDefaultAuthMechanism, "getDefaultAuthMechanism");
  14483. var ALLOWED_PROVIDER_NAMES = ["aws", "azure"];
  14484. var ALLOWED_HOSTS_ERROR = "Auth mechanism property ALLOWED_HOSTS must be an array of strings.";
  14485. exports2.DEFAULT_ALLOWED_HOSTS = [
  14486. "*.mongodb.net",
  14487. "*.mongodb-dev.net",
  14488. "*.mongodbgov.net",
  14489. "localhost",
  14490. "127.0.0.1",
  14491. "::1"
  14492. ];
  14493. var TOKEN_AUDIENCE_MISSING_ERROR = "TOKEN_AUDIENCE must be set in the auth mechanism properties when PROVIDER_NAME is azure.";
  14494. var _MongoCredentials = class _MongoCredentials {
  14495. constructor(options) {
  14496. this.username = options.username ?? "";
  14497. this.password = options.password;
  14498. this.source = options.source;
  14499. if (!this.source && options.db) {
  14500. this.source = options.db;
  14501. }
  14502. this.mechanism = options.mechanism || providers_1.AuthMechanism.MONGODB_DEFAULT;
  14503. this.mechanismProperties = options.mechanismProperties || {};
  14504. if (this.mechanism.match(/MONGODB-AWS/i)) {
  14505. if (!this.username && process.env.AWS_ACCESS_KEY_ID) {
  14506. this.username = process.env.AWS_ACCESS_KEY_ID;
  14507. }
  14508. if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) {
  14509. this.password = process.env.AWS_SECRET_ACCESS_KEY;
  14510. }
  14511. if (this.mechanismProperties.AWS_SESSION_TOKEN == null && process.env.AWS_SESSION_TOKEN != null) {
  14512. this.mechanismProperties = {
  14513. ...this.mechanismProperties,
  14514. AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN
  14515. };
  14516. }
  14517. }
  14518. if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC && !this.mechanismProperties.ALLOWED_HOSTS) {
  14519. this.mechanismProperties = {
  14520. ...this.mechanismProperties,
  14521. ALLOWED_HOSTS: exports2.DEFAULT_ALLOWED_HOSTS
  14522. };
  14523. }
  14524. Object.freeze(this.mechanismProperties);
  14525. Object.freeze(this);
  14526. }
  14527. /** Determines if two MongoCredentials objects are equivalent */
  14528. equals(other) {
  14529. return this.mechanism === other.mechanism && this.username === other.username && this.password === other.password && this.source === other.source;
  14530. }
  14531. /**
  14532. * If the authentication mechanism is set to "default", resolves the authMechanism
  14533. * based on the server version and server supported sasl mechanisms.
  14534. *
  14535. * @param hello - A hello response from the server
  14536. */
  14537. resolveAuthMechanism(hello) {
  14538. if (this.mechanism.match(/DEFAULT/i)) {
  14539. return new _MongoCredentials({
  14540. username: this.username,
  14541. password: this.password,
  14542. source: this.source,
  14543. mechanism: getDefaultAuthMechanism(hello),
  14544. mechanismProperties: this.mechanismProperties
  14545. });
  14546. }
  14547. return this;
  14548. }
  14549. validate() {
  14550. if ((this.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI || this.mechanism === providers_1.AuthMechanism.MONGODB_CR || this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 || this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) && !this.username) {
  14551. throw new error_1.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`);
  14552. }
  14553. if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) {
  14554. if (this.username && this.mechanismProperties.PROVIDER_NAME) {
  14555. throw new error_1.MongoInvalidArgumentError(`username and PROVIDER_NAME may not be used together for mechanism '${this.mechanism}'.`);
  14556. }
  14557. if (this.mechanismProperties.PROVIDER_NAME === "azure" && !this.mechanismProperties.TOKEN_AUDIENCE) {
  14558. throw new error_1.MongoAzureError(TOKEN_AUDIENCE_MISSING_ERROR);
  14559. }
  14560. if (this.mechanismProperties.PROVIDER_NAME && !ALLOWED_PROVIDER_NAMES.includes(this.mechanismProperties.PROVIDER_NAME)) {
  14561. throw new error_1.MongoInvalidArgumentError(`Currently only a PROVIDER_NAME in ${ALLOWED_PROVIDER_NAMES.join(",")} is supported for mechanism '${this.mechanism}'.`);
  14562. }
  14563. if (this.mechanismProperties.REFRESH_TOKEN_CALLBACK && !this.mechanismProperties.REQUEST_TOKEN_CALLBACK) {
  14564. throw new error_1.MongoInvalidArgumentError(`A REQUEST_TOKEN_CALLBACK must be provided when using a REFRESH_TOKEN_CALLBACK for mechanism '${this.mechanism}'`);
  14565. }
  14566. if (!this.mechanismProperties.PROVIDER_NAME && !this.mechanismProperties.REQUEST_TOKEN_CALLBACK) {
  14567. throw new error_1.MongoInvalidArgumentError(`Either a PROVIDER_NAME or a REQUEST_TOKEN_CALLBACK must be specified for mechanism '${this.mechanism}'.`);
  14568. }
  14569. if (this.mechanismProperties.ALLOWED_HOSTS) {
  14570. const hosts = this.mechanismProperties.ALLOWED_HOSTS;
  14571. if (!Array.isArray(hosts)) {
  14572. throw new error_1.MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR);
  14573. }
  14574. for (const host of hosts) {
  14575. if (typeof host !== "string") {
  14576. throw new error_1.MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR);
  14577. }
  14578. }
  14579. }
  14580. }
  14581. if (providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)) {
  14582. if (this.source != null && this.source !== "$external") {
  14583. throw new error_1.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`);
  14584. }
  14585. }
  14586. if (this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN && this.source == null) {
  14587. throw new error_1.MongoAPIError("PLAIN Authentication Mechanism needs an auth source");
  14588. }
  14589. if (this.mechanism === providers_1.AuthMechanism.MONGODB_X509 && this.password != null) {
  14590. if (this.password === "") {
  14591. Reflect.set(this, "password", void 0);
  14592. return;
  14593. }
  14594. throw new error_1.MongoAPIError(`Password not allowed for mechanism MONGODB-X509`);
  14595. }
  14596. const canonicalization = this.mechanismProperties.CANONICALIZE_HOST_NAME ?? false;
  14597. if (!Object.values(gssapi_1.GSSAPICanonicalizationValue).includes(canonicalization)) {
  14598. throw new error_1.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`);
  14599. }
  14600. }
  14601. static merge(creds, options) {
  14602. return new _MongoCredentials({
  14603. username: options.username ?? (creds == null ? void 0 : creds.username) ?? "",
  14604. password: options.password ?? (creds == null ? void 0 : creds.password) ?? "",
  14605. mechanism: options.mechanism ?? (creds == null ? void 0 : creds.mechanism) ?? providers_1.AuthMechanism.MONGODB_DEFAULT,
  14606. mechanismProperties: options.mechanismProperties ?? (creds == null ? void 0 : creds.mechanismProperties) ?? {},
  14607. source: options.source ?? options.db ?? (creds == null ? void 0 : creds.source) ?? "admin"
  14608. });
  14609. }
  14610. };
  14611. __name(_MongoCredentials, "MongoCredentials");
  14612. var MongoCredentials = _MongoCredentials;
  14613. exports2.MongoCredentials = MongoCredentials;
  14614. }
  14615. });
  14616. // node_modules/webidl-conversions/lib/index.js
  14617. var require_lib = __commonJS({
  14618. "node_modules/webidl-conversions/lib/index.js"(exports2) {
  14619. "use strict";
  14620. function makeException(ErrorType, message, options) {
  14621. if (options.globals) {
  14622. ErrorType = options.globals[ErrorType.name];
  14623. }
  14624. return new ErrorType(`${options.context ? options.context : "Value"} ${message}.`);
  14625. }
  14626. __name(makeException, "makeException");
  14627. function toNumber(value, options) {
  14628. if (typeof value === "bigint") {
  14629. throw makeException(TypeError, "is a BigInt which cannot be converted to a number", options);
  14630. }
  14631. if (!options.globals) {
  14632. return Number(value);
  14633. }
  14634. return options.globals.Number(value);
  14635. }
  14636. __name(toNumber, "toNumber");
  14637. function evenRound(x) {
  14638. if (x > 0 && x % 1 === 0.5 && (x & 1) === 0 || x < 0 && x % 1 === -0.5 && (x & 1) === 1) {
  14639. return censorNegativeZero(Math.floor(x));
  14640. }
  14641. return censorNegativeZero(Math.round(x));
  14642. }
  14643. __name(evenRound, "evenRound");
  14644. function integerPart(n) {
  14645. return censorNegativeZero(Math.trunc(n));
  14646. }
  14647. __name(integerPart, "integerPart");
  14648. function sign(x) {
  14649. return x < 0 ? -1 : 1;
  14650. }
  14651. __name(sign, "sign");
  14652. function modulo(x, y) {
  14653. const signMightNotMatch = x % y;
  14654. if (sign(y) !== sign(signMightNotMatch)) {
  14655. return signMightNotMatch + y;
  14656. }
  14657. return signMightNotMatch;
  14658. }
  14659. __name(modulo, "modulo");
  14660. function censorNegativeZero(x) {
  14661. return x === 0 ? 0 : x;
  14662. }
  14663. __name(censorNegativeZero, "censorNegativeZero");
  14664. function createIntegerConversion(bitLength, { unsigned }) {
  14665. let lowerBound, upperBound;
  14666. if (unsigned) {
  14667. lowerBound = 0;
  14668. upperBound = 2 ** bitLength - 1;
  14669. } else {
  14670. lowerBound = -(2 ** (bitLength - 1));
  14671. upperBound = 2 ** (bitLength - 1) - 1;
  14672. }
  14673. const twoToTheBitLength = 2 ** bitLength;
  14674. const twoToOneLessThanTheBitLength = 2 ** (bitLength - 1);
  14675. return (value, options = {}) => {
  14676. let x = toNumber(value, options);
  14677. x = censorNegativeZero(x);
  14678. if (options.enforceRange) {
  14679. if (!Number.isFinite(x)) {
  14680. throw makeException(TypeError, "is not a finite number", options);
  14681. }
  14682. x = integerPart(x);
  14683. if (x < lowerBound || x > upperBound) {
  14684. throw makeException(
  14685. TypeError,
  14686. `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,
  14687. options
  14688. );
  14689. }
  14690. return x;
  14691. }
  14692. if (!Number.isNaN(x) && options.clamp) {
  14693. x = Math.min(Math.max(x, lowerBound), upperBound);
  14694. x = evenRound(x);
  14695. return x;
  14696. }
  14697. if (!Number.isFinite(x) || x === 0) {
  14698. return 0;
  14699. }
  14700. x = integerPart(x);
  14701. if (x >= lowerBound && x <= upperBound) {
  14702. return x;
  14703. }
  14704. x = modulo(x, twoToTheBitLength);
  14705. if (!unsigned && x >= twoToOneLessThanTheBitLength) {
  14706. return x - twoToTheBitLength;
  14707. }
  14708. return x;
  14709. };
  14710. }
  14711. __name(createIntegerConversion, "createIntegerConversion");
  14712. function createLongLongConversion(bitLength, { unsigned }) {
  14713. const upperBound = Number.MAX_SAFE_INTEGER;
  14714. const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
  14715. const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN;
  14716. return (value, options = {}) => {
  14717. let x = toNumber(value, options);
  14718. x = censorNegativeZero(x);
  14719. if (options.enforceRange) {
  14720. if (!Number.isFinite(x)) {
  14721. throw makeException(TypeError, "is not a finite number", options);
  14722. }
  14723. x = integerPart(x);
  14724. if (x < lowerBound || x > upperBound) {
  14725. throw makeException(
  14726. TypeError,
  14727. `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,
  14728. options
  14729. );
  14730. }
  14731. return x;
  14732. }
  14733. if (!Number.isNaN(x) && options.clamp) {
  14734. x = Math.min(Math.max(x, lowerBound), upperBound);
  14735. x = evenRound(x);
  14736. return x;
  14737. }
  14738. if (!Number.isFinite(x) || x === 0) {
  14739. return 0;
  14740. }
  14741. let xBigInt = BigInt(integerPart(x));
  14742. xBigInt = asBigIntN(bitLength, xBigInt);
  14743. return Number(xBigInt);
  14744. };
  14745. }
  14746. __name(createLongLongConversion, "createLongLongConversion");
  14747. exports2.any = (value) => {
  14748. return value;
  14749. };
  14750. exports2.undefined = () => {
  14751. return void 0;
  14752. };
  14753. exports2.boolean = (value) => {
  14754. return Boolean(value);
  14755. };
  14756. exports2.byte = createIntegerConversion(8, { unsigned: false });
  14757. exports2.octet = createIntegerConversion(8, { unsigned: true });
  14758. exports2.short = createIntegerConversion(16, { unsigned: false });
  14759. exports2["unsigned short"] = createIntegerConversion(16, { unsigned: true });
  14760. exports2.long = createIntegerConversion(32, { unsigned: false });
  14761. exports2["unsigned long"] = createIntegerConversion(32, { unsigned: true });
  14762. exports2["long long"] = createLongLongConversion(64, { unsigned: false });
  14763. exports2["unsigned long long"] = createLongLongConversion(64, { unsigned: true });
  14764. exports2.double = (value, options = {}) => {
  14765. const x = toNumber(value, options);
  14766. if (!Number.isFinite(x)) {
  14767. throw makeException(TypeError, "is not a finite floating-point value", options);
  14768. }
  14769. return x;
  14770. };
  14771. exports2["unrestricted double"] = (value, options = {}) => {
  14772. const x = toNumber(value, options);
  14773. return x;
  14774. };
  14775. exports2.float = (value, options = {}) => {
  14776. const x = toNumber(value, options);
  14777. if (!Number.isFinite(x)) {
  14778. throw makeException(TypeError, "is not a finite floating-point value", options);
  14779. }
  14780. if (Object.is(x, -0)) {
  14781. return x;
  14782. }
  14783. const y = Math.fround(x);
  14784. if (!Number.isFinite(y)) {
  14785. throw makeException(TypeError, "is outside the range of a single-precision floating-point value", options);
  14786. }
  14787. return y;
  14788. };
  14789. exports2["unrestricted float"] = (value, options = {}) => {
  14790. const x = toNumber(value, options);
  14791. if (isNaN(x)) {
  14792. return x;
  14793. }
  14794. if (Object.is(x, -0)) {
  14795. return x;
  14796. }
  14797. return Math.fround(x);
  14798. };
  14799. exports2.DOMString = (value, options = {}) => {
  14800. if (options.treatNullAsEmptyString && value === null) {
  14801. return "";
  14802. }
  14803. if (typeof value === "symbol") {
  14804. throw makeException(TypeError, "is a symbol, which cannot be converted to a string", options);
  14805. }
  14806. const StringCtor = options.globals ? options.globals.String : String;
  14807. return StringCtor(value);
  14808. };
  14809. exports2.ByteString = (value, options = {}) => {
  14810. const x = exports2.DOMString(value, options);
  14811. let c;
  14812. for (let i = 0; (c = x.codePointAt(i)) !== void 0; ++i) {
  14813. if (c > 255) {
  14814. throw makeException(TypeError, "is not a valid ByteString", options);
  14815. }
  14816. }
  14817. return x;
  14818. };
  14819. exports2.USVString = (value, options = {}) => {
  14820. const S = exports2.DOMString(value, options);
  14821. const n = S.length;
  14822. const U = [];
  14823. for (let i = 0; i < n; ++i) {
  14824. const c = S.charCodeAt(i);
  14825. if (c < 55296 || c > 57343) {
  14826. U.push(String.fromCodePoint(c));
  14827. } else if (56320 <= c && c <= 57343) {
  14828. U.push(String.fromCodePoint(65533));
  14829. } else if (i === n - 1) {
  14830. U.push(String.fromCodePoint(65533));
  14831. } else {
  14832. const d = S.charCodeAt(i + 1);
  14833. if (56320 <= d && d <= 57343) {
  14834. const a = c & 1023;
  14835. const b = d & 1023;
  14836. U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
  14837. ++i;
  14838. } else {
  14839. U.push(String.fromCodePoint(65533));
  14840. }
  14841. }
  14842. }
  14843. return U.join("");
  14844. };
  14845. exports2.object = (value, options = {}) => {
  14846. if (value === null || typeof value !== "object" && typeof value !== "function") {
  14847. throw makeException(TypeError, "is not an object", options);
  14848. }
  14849. return value;
  14850. };
  14851. var abByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
  14852. var sabByteLengthGetter = typeof SharedArrayBuffer === "function" ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get : null;
  14853. function isNonSharedArrayBuffer(value) {
  14854. try {
  14855. abByteLengthGetter.call(value);
  14856. return true;
  14857. } catch {
  14858. return false;
  14859. }
  14860. }
  14861. __name(isNonSharedArrayBuffer, "isNonSharedArrayBuffer");
  14862. function isSharedArrayBuffer(value) {
  14863. try {
  14864. sabByteLengthGetter.call(value);
  14865. return true;
  14866. } catch {
  14867. return false;
  14868. }
  14869. }
  14870. __name(isSharedArrayBuffer, "isSharedArrayBuffer");
  14871. function isArrayBufferDetached(value) {
  14872. try {
  14873. new Uint8Array(value);
  14874. return false;
  14875. } catch {
  14876. return true;
  14877. }
  14878. }
  14879. __name(isArrayBufferDetached, "isArrayBufferDetached");
  14880. exports2.ArrayBuffer = (value, options = {}) => {
  14881. if (!isNonSharedArrayBuffer(value)) {
  14882. if (options.allowShared && !isSharedArrayBuffer(value)) {
  14883. throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", options);
  14884. }
  14885. throw makeException(TypeError, "is not an ArrayBuffer", options);
  14886. }
  14887. if (isArrayBufferDetached(value)) {
  14888. throw makeException(TypeError, "is a detached ArrayBuffer", options);
  14889. }
  14890. return value;
  14891. };
  14892. var dvByteLengthGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
  14893. exports2.DataView = (value, options = {}) => {
  14894. try {
  14895. dvByteLengthGetter.call(value);
  14896. } catch (e) {
  14897. throw makeException(TypeError, "is not a DataView", options);
  14898. }
  14899. if (!options.allowShared && isSharedArrayBuffer(value.buffer)) {
  14900. throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", options);
  14901. }
  14902. if (isArrayBufferDetached(value.buffer)) {
  14903. throw makeException(TypeError, "is backed by a detached ArrayBuffer", options);
  14904. }
  14905. return value;
  14906. };
  14907. var typedArrayNameGetter = Object.getOwnPropertyDescriptor(
  14908. Object.getPrototypeOf(Uint8Array).prototype,
  14909. Symbol.toStringTag
  14910. ).get;
  14911. [
  14912. Int8Array,
  14913. Int16Array,
  14914. Int32Array,
  14915. Uint8Array,
  14916. Uint16Array,
  14917. Uint32Array,
  14918. Uint8ClampedArray,
  14919. Float32Array,
  14920. Float64Array
  14921. ].forEach((func) => {
  14922. const { name } = func;
  14923. const article = /^[AEIOU]/u.test(name) ? "an" : "a";
  14924. exports2[name] = (value, options = {}) => {
  14925. if (!ArrayBuffer.isView(value) || typedArrayNameGetter.call(value) !== name) {
  14926. throw makeException(TypeError, `is not ${article} ${name} object`, options);
  14927. }
  14928. if (!options.allowShared && isSharedArrayBuffer(value.buffer)) {
  14929. throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options);
  14930. }
  14931. if (isArrayBufferDetached(value.buffer)) {
  14932. throw makeException(TypeError, "is a view on a detached ArrayBuffer", options);
  14933. }
  14934. return value;
  14935. };
  14936. });
  14937. exports2.ArrayBufferView = (value, options = {}) => {
  14938. if (!ArrayBuffer.isView(value)) {
  14939. throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", options);
  14940. }
  14941. if (!options.allowShared && isSharedArrayBuffer(value.buffer)) {
  14942. throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options);
  14943. }
  14944. if (isArrayBufferDetached(value.buffer)) {
  14945. throw makeException(TypeError, "is a view on a detached ArrayBuffer", options);
  14946. }
  14947. return value;
  14948. };
  14949. exports2.BufferSource = (value, options = {}) => {
  14950. if (ArrayBuffer.isView(value)) {
  14951. if (!options.allowShared && isSharedArrayBuffer(value.buffer)) {
  14952. throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options);
  14953. }
  14954. if (isArrayBufferDetached(value.buffer)) {
  14955. throw makeException(TypeError, "is a view on a detached ArrayBuffer", options);
  14956. }
  14957. return value;
  14958. }
  14959. if (!options.allowShared && !isNonSharedArrayBuffer(value)) {
  14960. throw makeException(TypeError, "is not an ArrayBuffer or a view on one", options);
  14961. }
  14962. if (options.allowShared && !isSharedArrayBuffer(value) && !isNonSharedArrayBuffer(value)) {
  14963. throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBuffer, or a view on one", options);
  14964. }
  14965. if (isArrayBufferDetached(value)) {
  14966. throw makeException(TypeError, "is a detached ArrayBuffer", options);
  14967. }
  14968. return value;
  14969. };
  14970. exports2.DOMTimeStamp = exports2["unsigned long long"];
  14971. }
  14972. });
  14973. // node_modules/whatwg-url/lib/utils.js
  14974. var require_utils2 = __commonJS({
  14975. "node_modules/whatwg-url/lib/utils.js"(exports2, module2) {
  14976. "use strict";
  14977. function isObject(value) {
  14978. return typeof value === "object" && value !== null || typeof value === "function";
  14979. }
  14980. __name(isObject, "isObject");
  14981. var hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
  14982. function define2(target, source) {
  14983. for (const key of Reflect.ownKeys(source)) {
  14984. const descriptor = Reflect.getOwnPropertyDescriptor(source, key);
  14985. if (descriptor && !Reflect.defineProperty(target, key, descriptor)) {
  14986. throw new TypeError(`Cannot redefine property: ${String(key)}`);
  14987. }
  14988. }
  14989. }
  14990. __name(define2, "define");
  14991. function newObjectInRealm(globalObject, object) {
  14992. const ctorRegistry = initCtorRegistry(globalObject);
  14993. return Object.defineProperties(
  14994. Object.create(ctorRegistry["%Object.prototype%"]),
  14995. Object.getOwnPropertyDescriptors(object)
  14996. );
  14997. }
  14998. __name(newObjectInRealm, "newObjectInRealm");
  14999. var wrapperSymbol = Symbol("wrapper");
  15000. var implSymbol = Symbol("impl");
  15001. var sameObjectCaches = Symbol("SameObject caches");
  15002. var ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry");
  15003. var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {
  15004. }).prototype);
  15005. function initCtorRegistry(globalObject) {
  15006. if (hasOwn(globalObject, ctorRegistrySymbol)) {
  15007. return globalObject[ctorRegistrySymbol];
  15008. }
  15009. const ctorRegistry = /* @__PURE__ */ Object.create(null);
  15010. ctorRegistry["%Object.prototype%"] = globalObject.Object.prototype;
  15011. ctorRegistry["%IteratorPrototype%"] = Object.getPrototypeOf(
  15012. Object.getPrototypeOf(new globalObject.Array()[Symbol.iterator]())
  15013. );
  15014. try {
  15015. ctorRegistry["%AsyncIteratorPrototype%"] = Object.getPrototypeOf(
  15016. Object.getPrototypeOf(
  15017. globalObject.eval("(async function* () {})").prototype
  15018. )
  15019. );
  15020. } catch {
  15021. ctorRegistry["%AsyncIteratorPrototype%"] = AsyncIteratorPrototype;
  15022. }
  15023. globalObject[ctorRegistrySymbol] = ctorRegistry;
  15024. return ctorRegistry;
  15025. }
  15026. __name(initCtorRegistry, "initCtorRegistry");
  15027. function getSameObject(wrapper, prop, creator) {
  15028. if (!wrapper[sameObjectCaches]) {
  15029. wrapper[sameObjectCaches] = /* @__PURE__ */ Object.create(null);
  15030. }
  15031. if (prop in wrapper[sameObjectCaches]) {
  15032. return wrapper[sameObjectCaches][prop];
  15033. }
  15034. wrapper[sameObjectCaches][prop] = creator();
  15035. return wrapper[sameObjectCaches][prop];
  15036. }
  15037. __name(getSameObject, "getSameObject");
  15038. function wrapperForImpl(impl) {
  15039. return impl ? impl[wrapperSymbol] : null;
  15040. }
  15041. __name(wrapperForImpl, "wrapperForImpl");
  15042. function implForWrapper(wrapper) {
  15043. return wrapper ? wrapper[implSymbol] : null;
  15044. }
  15045. __name(implForWrapper, "implForWrapper");
  15046. function tryWrapperForImpl(impl) {
  15047. const wrapper = wrapperForImpl(impl);
  15048. return wrapper ? wrapper : impl;
  15049. }
  15050. __name(tryWrapperForImpl, "tryWrapperForImpl");
  15051. function tryImplForWrapper(wrapper) {
  15052. const impl = implForWrapper(wrapper);
  15053. return impl ? impl : wrapper;
  15054. }
  15055. __name(tryImplForWrapper, "tryImplForWrapper");
  15056. var iterInternalSymbol = Symbol("internal");
  15057. function isArrayIndexPropName(P) {
  15058. if (typeof P !== "string") {
  15059. return false;
  15060. }
  15061. const i = P >>> 0;
  15062. if (i === 2 ** 32 - 1) {
  15063. return false;
  15064. }
  15065. const s = `${i}`;
  15066. if (P !== s) {
  15067. return false;
  15068. }
  15069. return true;
  15070. }
  15071. __name(isArrayIndexPropName, "isArrayIndexPropName");
  15072. var byteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
  15073. function isArrayBuffer(value) {
  15074. try {
  15075. byteLengthGetter.call(value);
  15076. return true;
  15077. } catch (e) {
  15078. return false;
  15079. }
  15080. }
  15081. __name(isArrayBuffer, "isArrayBuffer");
  15082. function iteratorResult([key, value], kind) {
  15083. let result;
  15084. switch (kind) {
  15085. case "key":
  15086. result = key;
  15087. break;
  15088. case "value":
  15089. result = value;
  15090. break;
  15091. case "key+value":
  15092. result = [key, value];
  15093. break;
  15094. }
  15095. return { value: result, done: false };
  15096. }
  15097. __name(iteratorResult, "iteratorResult");
  15098. var supportsPropertyIndex = Symbol("supports property index");
  15099. var supportedPropertyIndices = Symbol("supported property indices");
  15100. var supportsPropertyName = Symbol("supports property name");
  15101. var supportedPropertyNames = Symbol("supported property names");
  15102. var indexedGet = Symbol("indexed property get");
  15103. var indexedSetNew = Symbol("indexed property set new");
  15104. var indexedSetExisting = Symbol("indexed property set existing");
  15105. var namedGet = Symbol("named property get");
  15106. var namedSetNew = Symbol("named property set new");
  15107. var namedSetExisting = Symbol("named property set existing");
  15108. var namedDelete = Symbol("named property delete");
  15109. var asyncIteratorNext = Symbol("async iterator get the next iteration result");
  15110. var asyncIteratorReturn = Symbol("async iterator return steps");
  15111. var asyncIteratorInit = Symbol("async iterator initialization steps");
  15112. var asyncIteratorEOI = Symbol("async iterator end of iteration");
  15113. module2.exports = exports2 = {
  15114. isObject,
  15115. hasOwn,
  15116. define: define2,
  15117. newObjectInRealm,
  15118. wrapperSymbol,
  15119. implSymbol,
  15120. getSameObject,
  15121. ctorRegistrySymbol,
  15122. initCtorRegistry,
  15123. wrapperForImpl,
  15124. implForWrapper,
  15125. tryWrapperForImpl,
  15126. tryImplForWrapper,
  15127. iterInternalSymbol,
  15128. isArrayBuffer,
  15129. isArrayIndexPropName,
  15130. supportsPropertyIndex,
  15131. supportedPropertyIndices,
  15132. supportsPropertyName,
  15133. supportedPropertyNames,
  15134. indexedGet,
  15135. indexedSetNew,
  15136. indexedSetExisting,
  15137. namedGet,
  15138. namedSetNew,
  15139. namedSetExisting,
  15140. namedDelete,
  15141. asyncIteratorNext,
  15142. asyncIteratorReturn,
  15143. asyncIteratorInit,
  15144. asyncIteratorEOI,
  15145. iteratorResult
  15146. };
  15147. }
  15148. });
  15149. // node_modules/tr46/lib/regexes.js
  15150. var require_regexes = __commonJS({
  15151. "node_modules/tr46/lib/regexes.js"(exports2, module2) {
  15152. "use strict";
  15153. var combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{111CE}\u{111CF}\u{1122C}-\u{11237}\u{1123E}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{11930}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{1193E}\u{11940}\u{11942}\u{11943}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{16FE4}\u{16FF0}\u{16FF1}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u;
  15154. var combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0EBA\u0F84\u1039\u103A\u1714\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11839}\u{119E0}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}\u{11D97}]/u;
  15155. var validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u08A0-\u08A9\u08AF\u08B0\u08B3\u08B4\u08B6-\u08B8\u08BA-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0855\u0860\u0862-\u0865\u0867-\u086A\u08A0-\u08AC\u08AE-\u08B4\u08B6-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{1E900}-\u{1E943}]/u;
  15156. var bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u;
  15157. var bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B50-\u1B6A\u1B74-\u1B7E\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u;
  15158. var bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u;
  15159. var bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u0898-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20C0\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2426\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82C\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uAB6A\uAB6B\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD8F\uFD92-\uFDC7\uFDCF\uFDF0-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019C}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D27}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAB}-\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F59}\u{10F70}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11FD5}-\u{11FF1}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE2}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D1E9}\u{1D1EA}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6DB}\u{1D715}\u{1D74F}\u{1D789}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E2FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8D6}\u{1E900}-\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10F}\u{1F12F}\u{1F16A}-\u{1F16F}\u{1F1AD}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DD}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7C}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAAC}\u{1FAB0}-\u{1FABA}\u{1FAC0}-\u{1FAC5}\u{1FAD0}-\u{1FAD9}\u{1FAE0}-\u{1FAE7}\u{1FAF0}-\u{1FAF6}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u;
  15160. var bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u;
  15161. var bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}]/u;
  15162. var bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u0890\u0891\u08E2\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}]/u;
  15163. var bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FE\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A76\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BFA\u0C00-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3C-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C5D\u0C60-\u0C63\u0C66-\u0C6F\u0C77-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D81-\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u1715\u171F-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ACE\u1B00-\u1B4C\u1B50-\u1B7E\u1B80-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD0-\u1CFA\u1D00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20C0\u20D0-\u20F0\u2100-\u218B\u2190-\u2426\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B97-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31E3\u31F0-\u321E\u3220-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA82C\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB6B\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E-\uFD4F\uFDCF\uFDFD-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019C}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{1104D}\u{11052}-\u{11075}\u{1107F}-\u{110C2}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11147}\u{11150}-\u{11176}\u{11180}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1123E}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133B}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11400}-\u{1145B}\u{1145D}-\u{11461}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{1171D}-\u{1172B}\u{11730}-\u{11746}\u{11800}-\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D7}\u{119DA}-\u{119E4}\u{11A00}-\u{11A47}\u{11A50}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FF1}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F4F}-\u{16F87}\u{16F8F}-\u{16F9F}\u{16FE0}-\u{16FE4}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1EA}\u{1D200}-\u{1D245}\u{1D2E0}-\u{1D2F3}\u{1D300}-\u{1D356}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1DF00}-\u{1DF1E}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E100}-\u{1E12C}\u{1E130}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AE}\u{1E2C0}-\u{1E2F9}\u{1E2FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F1AD}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DD}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7C}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAAC}\u{1FAB0}-\u{1FABA}\u{1FAC0}-\u{1FAC5}\u{1FAD0}-\u{1FAD9}\u{1FAE0}-\u{1FAE7}\u{1FAF0}-\u{1FAF6}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u;
  15164. var bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B50-\u1B6A\u1B74-\u1B7E\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u;
  15165. module2.exports = {
  15166. combiningMarks,
  15167. combiningClassVirama,
  15168. validZWNJ,
  15169. bidiDomain,
  15170. bidiS1LTR,
  15171. bidiS1RTL,
  15172. bidiS2,
  15173. bidiS3,
  15174. bidiS4EN,
  15175. bidiS4AN,
  15176. bidiS5,
  15177. bidiS6
  15178. };
  15179. }
  15180. });
  15181. // node_modules/tr46/lib/mappingTable.json
  15182. var require_mappingTable = __commonJS({
  15183. "node_modules/tr46/lib/mappingTable.json"(exports2, module2) {
  15184. module2.exports = [[[0, 44], 4], [[45, 46], 2], [47, 4], [[48, 57], 2], [[58, 64], 4], [65, 1, "a"], [66, 1, "b"], [67, 1, "c"], [68, 1, "d"], [69, 1, "e"], [70, 1, "f"], [71, 1, "g"], [72, 1, "h"], [73, 1, "i"], [74, 1, "j"], [75, 1, "k"], [76, 1, "l"], [77, 1, "m"], [78, 1, "n"], [79, 1, "o"], [80, 1, "p"], [81, 1, "q"], [82, 1, "r"], [83, 1, "s"], [84, 1, "t"], [85, 1, "u"], [86, 1, "v"], [87, 1, "w"], [88, 1, "x"], [89, 1, "y"], [90, 1, "z"], [[91, 96], 4], [[97, 122], 2], [[123, 127], 4], [[128, 159], 3], [160, 5, " "], [[161, 167], 2], [168, 5, " \u0308"], [169, 2], [170, 1, "a"], [[171, 172], 2], [173, 7], [174, 2], [175, 5, " \u0304"], [[176, 177], 2], [178, 1, "2"], [179, 1, "3"], [180, 5, " \u0301"], [181, 1, "\u03BC"], [182, 2], [183, 2], [184, 5, " \u0327"], [185, 1, "1"], [186, 1, "o"], [187, 2], [188, 1, "1\u20444"], [189, 1, "1\u20442"], [190, 1, "3\u20444"], [191, 2], [192, 1, "\xE0"], [193, 1, "\xE1"], [194, 1, "\xE2"], [195, 1, "\xE3"], [196, 1, "\xE4"], [197, 1, "\xE5"], [198, 1, "\xE6"], [199, 1, "\xE7"], [200, 1, "\xE8"], [201, 1, "\xE9"], [202, 1, "\xEA"], [203, 1, "\xEB"], [204, 1, "\xEC"], [205, 1, "\xED"], [206, 1, "\xEE"], [207, 1, "\xEF"], [208, 1, "\xF0"], [209, 1, "\xF1"], [210, 1, "\xF2"], [211, 1, "\xF3"], [212, 1, "\xF4"], [213, 1, "\xF5"], [214, 1, "\xF6"], [215, 2], [216, 1, "\xF8"], [217, 1, "\xF9"], [218, 1, "\xFA"], [219, 1, "\xFB"], [220, 1, "\xFC"], [221, 1, "\xFD"], [222, 1, "\xFE"], [223, 6, "ss"], [[224, 246], 2], [247, 2], [[248, 255], 2], [256, 1, "\u0101"], [257, 2], [258, 1, "\u0103"], [259, 2], [260, 1, "\u0105"], [261, 2], [262, 1, "\u0107"], [263, 2], [264, 1, "\u0109"], [265, 2], [266, 1, "\u010B"], [267, 2], [268, 1, "\u010D"], [269, 2], [270, 1, "\u010F"], [271, 2], [272, 1, "\u0111"], [273, 2], [274, 1, "\u0113"], [275, 2], [276, 1, "\u0115"], [277, 2], [278, 1, "\u0117"], [279, 2], [280, 1, "\u0119"], [281, 2], [282, 1, "\u011B"], [283, 2], [284, 1, "\u011D"], [285, 2], [286, 1, "\u011F"], [287, 2], [288, 1, "\u0121"], [289, 2], [290, 1, "\u0123"], [291, 2], [292, 1, "\u0125"], [293, 2], [294, 1, "\u0127"], [295, 2], [296, 1, "\u0129"], [297, 2], [298, 1, "\u012B"], [299, 2], [300, 1, "\u012D"], [301, 2], [302, 1, "\u012F"], [303, 2], [304, 1, "i\u0307"], [305, 2], [[306, 307], 1, "ij"], [308, 1, "\u0135"], [309, 2], [310, 1, "\u0137"], [[311, 312], 2], [313, 1, "\u013A"], [314, 2], [315, 1, "\u013C"], [316, 2], [317, 1, "\u013E"], [318, 2], [[319, 320], 1, "l\xB7"], [321, 1, "\u0142"], [322, 2], [323, 1, "\u0144"], [324, 2], [325, 1, "\u0146"], [326, 2], [327, 1, "\u0148"], [328, 2], [329, 1, "\u02BCn"], [330, 1, "\u014B"], [331, 2], [332, 1, "\u014D"], [333, 2], [334, 1, "\u014F"], [335, 2], [336, 1, "\u0151"], [337, 2], [338, 1, "\u0153"], [339, 2], [340, 1, "\u0155"], [341, 2], [342, 1, "\u0157"], [343, 2], [344, 1, "\u0159"], [345, 2], [346, 1, "\u015B"], [347, 2], [348, 1, "\u015D"], [349, 2], [350, 1, "\u015F"], [351, 2], [352, 1, "\u0161"], [353, 2], [354, 1, "\u0163"], [355, 2], [356, 1, "\u0165"], [357, 2], [358, 1, "\u0167"], [359, 2], [360, 1, "\u0169"], [361, 2], [362, 1, "\u016B"], [363, 2], [364, 1, "\u016D"], [365, 2], [366, 1, "\u016F"], [367, 2], [368, 1, "\u0171"], [369, 2], [370, 1, "\u0173"], [371, 2], [372, 1, "\u0175"], [373, 2], [374, 1, "\u0177"], [375, 2], [376, 1, "\xFF"], [377, 1, "\u017A"], [378, 2], [379, 1, "\u017C"], [380, 2], [381, 1, "\u017E"], [382, 2], [383, 1, "s"], [384, 2], [385, 1, "\u0253"], [386, 1, "\u0183"], [387, 2], [388, 1, "\u0185"], [389, 2], [390, 1, "\u0254"], [391, 1, "\u0188"], [392, 2], [393, 1, "\u0256"], [394, 1, "\u0257"], [395, 1, "\u018C"], [[396, 397], 2], [398, 1, "\u01DD"], [399, 1, "\u0259"], [400, 1, "\u025B"], [401, 1, "\u0192"], [402, 2], [403, 1, "\u0260"], [404, 1, "\u0263"], [405, 2], [406, 1, "\u0269"], [407, 1, "\u0268"], [408, 1, "\u0199"], [[409, 411], 2], [412, 1, "\u026F"], [413, 1, "\u0272"], [414, 2], [415, 1, "\u0275"], [416, 1, "\u01A1"], [417, 2], [418, 1, "\u01A3"], [419, 2], [420, 1, "\u01A5"], [421, 2], [422, 1, "\u0280"], [423, 1, "\u01A8"], [424, 2], [425, 1, "\u0283"], [[426, 427], 2], [428, 1, "\u01AD"], [429, 2], [430, 1, "\u0288"], [431, 1, "\u01B0"], [432, 2], [433, 1, "\u028A"], [434, 1, "\u028B"], [435, 1, "\u01B4"], [436, 2], [437, 1, "\u01B6"], [438, 2], [439, 1, "\u0292"], [440, 1, "\u01B9"], [[441, 443], 2], [444, 1, "\u01BD"], [[445, 451], 2], [[452, 454], 1, "d\u017E"], [[455, 457], 1, "lj"], [[458, 460], 1, "nj"], [461, 1, "\u01CE"], [462, 2], [463, 1, "\u01D0"], [464, 2], [465, 1, "\u01D2"], [466, 2], [467, 1, "\u01D4"], [468, 2], [469, 1, "\u01D6"], [470, 2], [471, 1, "\u01D8"], [472, 2], [473, 1, "\u01DA"], [474, 2], [475, 1, "\u01DC"], [[476, 477], 2], [478, 1, "\u01DF"], [479, 2], [480, 1, "\u01E1"], [481, 2], [482, 1, "\u01E3"], [483, 2], [484, 1, "\u01E5"], [485, 2], [486, 1, "\u01E7"], [487, 2], [488, 1, "\u01E9"], [489, 2], [490, 1, "\u01EB"], [491, 2], [492, 1, "\u01ED"], [493, 2], [494, 1, "\u01EF"], [[495, 496], 2], [[497, 499], 1, "dz"], [500, 1, "\u01F5"], [501, 2], [502, 1, "\u0195"], [503, 1, "\u01BF"], [504, 1, "\u01F9"], [505, 2], [506, 1, "\u01FB"], [507, 2], [508, 1, "\u01FD"], [509, 2], [510, 1, "\u01FF"], [511, 2], [512, 1, "\u0201"], [513, 2], [514, 1, "\u0203"], [515, 2], [516, 1, "\u0205"], [517, 2], [518, 1, "\u0207"], [519, 2], [520, 1, "\u0209"], [521, 2], [522, 1, "\u020B"], [523, 2], [524, 1, "\u020D"], [525, 2], [526, 1, "\u020F"], [527, 2], [528, 1, "\u0211"], [529, 2], [530, 1, "\u0213"], [531, 2], [532, 1, "\u0215"], [533, 2], [534, 1, "\u0217"], [535, 2], [536, 1, "\u0219"], [537, 2], [538, 1, "\u021B"], [539, 2], [540, 1, "\u021D"], [541, 2], [542, 1, "\u021F"], [543, 2], [544, 1, "\u019E"], [545, 2], [546, 1, "\u0223"], [547, 2], [548, 1, "\u0225"], [549, 2], [550, 1, "\u0227"], [551, 2], [552, 1, "\u0229"], [553, 2], [554, 1, "\u022B"], [555, 2], [556, 1, "\u022D"], [557, 2], [558, 1, "\u022F"], [559, 2], [560, 1, "\u0231"], [561, 2], [562, 1, "\u0233"], [563, 2], [[564, 566], 2], [[567, 569], 2], [570, 1, "\u2C65"], [571, 1, "\u023C"], [572, 2], [573, 1, "\u019A"], [574, 1, "\u2C66"], [[575, 576], 2], [577, 1, "\u0242"], [578, 2], [579, 1, "\u0180"], [580, 1, "\u0289"], [581, 1, "\u028C"], [582, 1, "\u0247"], [583, 2], [584, 1, "\u0249"], [585, 2], [586, 1, "\u024B"], [587, 2], [588, 1, "\u024D"], [589, 2], [590, 1, "\u024F"], [591, 2], [[592, 680], 2], [[681, 685], 2], [[686, 687], 2], [688, 1, "h"], [689, 1, "\u0266"], [690, 1, "j"], [691, 1, "r"], [692, 1, "\u0279"], [693, 1, "\u027B"], [694, 1, "\u0281"], [695, 1, "w"], [696, 1, "y"], [[697, 705], 2], [[706, 709], 2], [[710, 721], 2], [[722, 727], 2], [728, 5, " \u0306"], [729, 5, " \u0307"], [730, 5, " \u030A"], [731, 5, " \u0328"], [732, 5, " \u0303"], [733, 5, " \u030B"], [734, 2], [735, 2], [736, 1, "\u0263"], [737, 1, "l"], [738, 1, "s"], [739, 1, "x"], [740, 1, "\u0295"], [[741, 745], 2], [[746, 747], 2], [748, 2], [749, 2], [750, 2], [[751, 767], 2], [[768, 831], 2], [832, 1, "\u0300"], [833, 1, "\u0301"], [834, 2], [835, 1, "\u0313"], [836, 1, "\u0308\u0301"], [837, 1, "\u03B9"], [[838, 846], 2], [847, 7], [[848, 855], 2], [[856, 860], 2], [[861, 863], 2], [[864, 865], 2], [866, 2], [[867, 879], 2], [880, 1, "\u0371"], [881, 2], [882, 1, "\u0373"], [883, 2], [884, 1, "\u02B9"], [885, 2], [886, 1, "\u0377"], [887, 2], [[888, 889], 3], [890, 5, " \u03B9"], [[891, 893], 2], [894, 5, ";"], [895, 1, "\u03F3"], [[896, 899], 3], [900, 5, " \u0301"], [901, 5, " \u0308\u0301"], [902, 1, "\u03AC"], [903, 1, "\xB7"], [904, 1, "\u03AD"], [905, 1, "\u03AE"], [906, 1, "\u03AF"], [907, 3], [908, 1, "\u03CC"], [909, 3], [910, 1, "\u03CD"], [911, 1, "\u03CE"], [912, 2], [913, 1, "\u03B1"], [914, 1, "\u03B2"], [915, 1, "\u03B3"], [916, 1, "\u03B4"], [917, 1, "\u03B5"], [918, 1, "\u03B6"], [919, 1, "\u03B7"], [920, 1, "\u03B8"], [921, 1, "\u03B9"], [922, 1, "\u03BA"], [923, 1, "\u03BB"], [924, 1, "\u03BC"], [925, 1, "\u03BD"], [926, 1, "\u03BE"], [927, 1, "\u03BF"], [928, 1, "\u03C0"], [929, 1, "\u03C1"], [930, 3], [931, 1, "\u03C3"], [932, 1, "\u03C4"], [933, 1, "\u03C5"], [934, 1, "\u03C6"], [935, 1, "\u03C7"], [936, 1, "\u03C8"], [937, 1, "\u03C9"], [938, 1, "\u03CA"], [939, 1, "\u03CB"], [[940, 961], 2], [962, 6, "\u03C3"], [[963, 974], 2], [975, 1, "\u03D7"], [976, 1, "\u03B2"], [977, 1, "\u03B8"], [978, 1, "\u03C5"], [979, 1, "\u03CD"], [980, 1, "\u03CB"], [981, 1, "\u03C6"], [982, 1, "\u03C0"], [983, 2], [984, 1, "\u03D9"], [985, 2], [986, 1, "\u03DB"], [987, 2], [988, 1, "\u03DD"], [989, 2], [990, 1, "\u03DF"], [991, 2], [992, 1, "\u03E1"], [993, 2], [994, 1, "\u03E3"], [995, 2], [996, 1, "\u03E5"], [997, 2], [998, 1, "\u03E7"], [999, 2], [1e3, 1, "\u03E9"], [1001, 2], [1002, 1, "\u03EB"], [1003, 2], [1004, 1, "\u03ED"], [1005, 2], [1006, 1, "\u03EF"], [1007, 2], [1008, 1, "\u03BA"], [1009, 1, "\u03C1"], [1010, 1, "\u03C3"], [1011, 2], [1012, 1, "\u03B8"], [1013, 1, "\u03B5"], [1014, 2], [1015, 1, "\u03F8"], [1016, 2], [1017, 1, "\u03C3"], [1018, 1, "\u03FB"], [1019, 2], [1020, 2], [1021, 1, "\u037B"], [1022, 1, "\u037C"], [1023, 1, "\u037D"], [1024, 1, "\u0450"], [1025, 1, "\u0451"], [1026, 1, "\u0452"], [1027, 1, "\u0453"], [1028, 1, "\u0454"], [1029, 1, "\u0455"], [1030, 1, "\u0456"], [1031, 1, "\u0457"], [1032, 1, "\u0458"], [1033, 1, "\u0459"], [1034, 1, "\u045A"], [1035, 1, "\u045B"], [1036, 1, "\u045C"], [1037, 1, "\u045D"], [1038, 1, "\u045E"], [1039, 1, "\u045F"], [1040, 1, "\u0430"], [1041, 1, "\u0431"], [1042, 1, "\u0432"], [1043, 1, "\u0433"], [1044, 1, "\u0434"], [1045, 1, "\u0435"], [1046, 1, "\u0436"], [1047, 1, "\u0437"], [1048, 1, "\u0438"], [1049, 1, "\u0439"], [1050, 1, "\u043A"], [1051, 1, "\u043B"], [1052, 1, "\u043C"], [1053, 1, "\u043D"], [1054, 1, "\u043E"], [1055, 1, "\u043F"], [1056, 1, "\u0440"], [1057, 1, "\u0441"], [1058, 1, "\u0442"], [1059, 1, "\u0443"], [1060, 1, "\u0444"], [1061, 1, "\u0445"], [1062, 1, "\u0446"], [1063, 1, "\u0447"], [1064, 1, "\u0448"], [1065, 1, "\u0449"], [1066, 1, "\u044A"], [1067, 1, "\u044B"], [1068, 1, "\u044C"], [1069, 1, "\u044D"], [1070, 1, "\u044E"], [1071, 1, "\u044F"], [[1072, 1103], 2], [1104, 2], [[1105, 1116], 2], [1117, 2], [[1118, 1119], 2], [1120, 1, "\u0461"], [1121, 2], [1122, 1, "\u0463"], [1123, 2], [1124, 1, "\u0465"], [1125, 2], [1126, 1, "\u0467"], [1127, 2], [1128, 1, "\u0469"], [1129, 2], [1130, 1, "\u046B"], [1131, 2], [1132, 1, "\u046D"], [1133, 2], [1134, 1, "\u046F"], [1135, 2], [1136, 1, "\u0471"], [1137, 2], [1138, 1, "\u0473"], [1139, 2], [1140, 1, "\u0475"], [1141, 2], [1142, 1, "\u0477"], [1143, 2], [1144, 1, "\u0479"], [1145, 2], [1146, 1, "\u047B"], [1147, 2], [1148, 1, "\u047D"], [1149, 2], [1150, 1, "\u047F"], [1151, 2], [1152, 1, "\u0481"], [1153, 2], [1154, 2], [[1155, 1158], 2], [1159, 2], [[1160, 1161], 2], [1162, 1, "\u048B"], [1163, 2], [1164, 1, "\u048D"], [1165, 2], [1166, 1, "\u048F"], [1167, 2], [1168, 1, "\u0491"], [1169, 2], [1170, 1, "\u0493"], [1171, 2], [1172, 1, "\u0495"], [1173, 2], [1174, 1, "\u0497"], [1175, 2], [1176, 1, "\u0499"], [1177, 2], [1178, 1, "\u049B"], [1179, 2], [1180, 1, "\u049D"], [1181, 2], [1182, 1, "\u049F"], [1183, 2], [1184, 1, "\u04A1"], [1185, 2], [1186, 1, "\u04A3"], [1187, 2], [1188, 1, "\u04A5"], [1189, 2], [1190, 1, "\u04A7"], [1191, 2], [1192, 1, "\u04A9"], [1193, 2], [1194, 1, "\u04AB"], [1195, 2], [1196, 1, "\u04AD"], [1197, 2], [1198, 1, "\u04AF"], [1199, 2], [1200, 1, "\u04B1"], [1201, 2], [1202, 1, "\u04B3"], [1203, 2], [1204, 1, "\u04B5"], [1205, 2], [1206, 1, "\u04B7"], [1207, 2], [1208, 1, "\u04B9"], [1209, 2], [1210, 1, "\u04BB"], [1211, 2], [1212, 1, "\u04BD"], [1213, 2], [1214, 1, "\u04BF"], [1215, 2], [1216, 3], [1217, 1, "\u04C2"], [1218, 2], [1219, 1, "\u04C4"], [1220, 2], [1221, 1, "\u04C6"], [1222, 2], [1223, 1, "\u04C8"], [1224, 2], [1225, 1, "\u04CA"], [1226, 2], [1227, 1, "\u04CC"], [1228, 2], [1229, 1, "\u04CE"], [1230, 2], [1231, 2], [1232, 1, "\u04D1"], [1233, 2], [1234, 1, "\u04D3"], [1235, 2], [1236, 1, "\u04D5"], [1237, 2], [1238, 1, "\u04D7"], [1239, 2], [1240, 1, "\u04D9"], [1241, 2], [1242, 1, "\u04DB"], [1243, 2], [1244, 1, "\u04DD"], [1245, 2], [1246, 1, "\u04DF"], [1247, 2], [1248, 1, "\u04E1"], [1249, 2], [1250, 1, "\u04E3"], [1251, 2], [1252, 1, "\u04E5"], [1253, 2], [1254, 1, "\u04E7"], [1255, 2], [1256, 1, "\u04E9"], [1257, 2], [1258, 1, "\u04EB"], [1259, 2], [1260, 1, "\u04ED"], [1261, 2], [1262, 1, "\u04EF"], [1263, 2], [1264, 1, "\u04F1"], [1265, 2], [1266, 1, "\u04F3"], [1267, 2], [1268, 1, "\u04F5"], [1269, 2], [1270, 1, "\u04F7"], [1271, 2], [1272, 1, "\u04F9"], [1273, 2], [1274, 1, "\u04FB"], [1275, 2], [1276, 1, "\u04FD"], [1277, 2], [1278, 1, "\u04FF"], [1279, 2], [1280, 1, "\u0501"], [1281, 2], [1282, 1, "\u0503"], [1283, 2], [1284, 1, "\u0505"], [1285, 2], [1286, 1, "\u0507"], [1287, 2], [1288, 1, "\u0509"], [1289, 2], [1290, 1, "\u050B"], [1291, 2], [1292, 1, "\u050D"], [1293, 2], [1294, 1, "\u050F"], [1295, 2], [1296, 1, "\u0511"], [1297, 2], [1298, 1, "\u0513"], [1299, 2], [1300, 1, "\u0515"], [1301, 2], [1302, 1, "\u0517"], [1303, 2], [1304, 1, "\u0519"], [1305, 2], [1306, 1, "\u051B"], [1307, 2], [1308, 1, "\u051D"], [1309, 2], [1310, 1, "\u051F"], [1311, 2], [1312, 1, "\u0521"], [1313, 2], [1314, 1, "\u0523"], [1315, 2], [1316, 1, "\u0525"], [1317, 2], [1318, 1, "\u0527"], [1319, 2], [1320, 1, "\u0529"], [1321, 2], [1322, 1, "\u052B"], [1323, 2], [1324, 1, "\u052D"], [1325, 2], [1326, 1, "\u052F"], [1327, 2], [1328, 3], [1329, 1, "\u0561"], [1330, 1, "\u0562"], [1331, 1, "\u0563"], [1332, 1, "\u0564"], [1333, 1, "\u0565"], [1334, 1, "\u0566"], [1335, 1, "\u0567"], [1336, 1, "\u0568"], [1337, 1, "\u0569"], [1338, 1, "\u056A"], [1339, 1, "\u056B"], [1340, 1, "\u056C"], [1341, 1, "\u056D"], [1342, 1, "\u056E"], [1343, 1, "\u056F"], [1344, 1, "\u0570"], [1345, 1, "\u0571"], [1346, 1, "\u0572"], [1347, 1, "\u0573"], [1348, 1, "\u0574"], [1349, 1, "\u0575"], [1350, 1, "\u0576"], [1351, 1, "\u0577"], [1352, 1, "\u0578"], [1353, 1, "\u0579"], [1354, 1, "\u057A"], [1355, 1, "\u057B"], [1356, 1, "\u057C"], [1357, 1, "\u057D"], [1358, 1, "\u057E"], [1359, 1, "\u057F"], [1360, 1, "\u0580"], [1361, 1, "\u0581"], [1362, 1, "\u0582"], [1363, 1, "\u0583"], [1364, 1, "\u0584"], [1365, 1, "\u0585"], [1366, 1, "\u0586"], [[1367, 1368], 3], [1369, 2], [[1370, 1375], 2], [1376, 2], [[1377, 1414], 2], [1415, 1, "\u0565\u0582"], [1416, 2], [1417, 2], [1418, 2], [[1419, 1420], 3], [[1421, 1422], 2], [1423, 2], [1424, 3], [[1425, 1441], 2], [1442, 2], [[1443, 1455], 2], [[1456, 1465], 2], [1466, 2], [[1467, 1469], 2], [1470, 2], [1471, 2], [1472, 2], [[1473, 1474], 2], [1475, 2], [1476, 2], [1477, 2], [1478, 2], [1479, 2], [[1480, 1487], 3], [[1488, 1514], 2], [[1515, 1518], 3], [1519, 2], [[1520, 1524], 2], [[1525, 1535], 3], [[1536, 1539], 3], [1540, 3], [1541, 3], [[1542, 1546], 2], [1547, 2], [1548, 2], [[1549, 1551], 2], [[1552, 1557], 2], [[1558, 1562], 2], [1563, 2], [1564, 3], [1565, 2], [1566, 2], [1567, 2], [1568, 2], [[1569, 1594], 2], [[1595, 1599], 2], [1600, 2], [[1601, 1618], 2], [[1619, 1621], 2], [[1622, 1624], 2], [[1625, 1630], 2], [1631, 2], [[1632, 1641], 2], [[1642, 1645], 2], [[1646, 1647], 2], [[1648, 1652], 2], [1653, 1, "\u0627\u0674"], [1654, 1, "\u0648\u0674"], [1655, 1, "\u06C7\u0674"], [1656, 1, "\u064A\u0674"], [[1657, 1719], 2], [[1720, 1721], 2], [[1722, 1726], 2], [1727, 2], [[1728, 1742], 2], [1743, 2], [[1744, 1747], 2], [1748, 2], [[1749, 1756], 2], [1757, 3], [1758, 2], [[1759, 1768], 2], [1769, 2], [[1770, 1773], 2], [[1774, 1775], 2], [[1776, 1785], 2], [[1786, 1790], 2], [1791, 2], [[1792, 1805], 2], [1806, 3], [1807, 3], [[1808, 1836], 2], [[1837, 1839], 2], [[1840, 1866], 2], [[1867, 1868], 3], [[1869, 1871], 2], [[1872, 1901], 2], [[1902, 1919], 2], [[1920, 1968], 2], [1969, 2], [[1970, 1983], 3], [[1984, 2037], 2], [[2038, 2042], 2], [[2043, 2044], 3], [2045, 2], [[2046, 2047], 2], [[2048, 2093], 2], [[2094, 2095], 3], [[2096, 2110], 2], [2111, 3], [[2112, 2139], 2], [[2140, 2141], 3], [2142, 2], [2143, 3], [[2144, 2154], 2], [[2155, 2159], 3], [[2160, 2183], 2], [2184, 2], [[2185, 2190], 2], [2191, 3], [[2192, 2193], 3], [[2194, 2199], 3], [[2200, 2207], 2], [2208, 2], [2209, 2], [[2210, 2220], 2], [[2221, 2226], 2], [[2227, 2228], 2], [2229, 2], [[2230, 2237], 2], [[2238, 2247], 2], [[2248, 2258], 2], [2259, 2], [[2260, 2273], 2], [2274, 3], [2275, 2], [[2276, 2302], 2], [2303, 2], [2304, 2], [[2305, 2307], 2], [2308, 2], [[2309, 2361], 2], [[2362, 2363], 2], [[2364, 2381], 2], [2382, 2], [2383, 2], [[2384, 2388], 2], [2389, 2], [[2390, 2391], 2], [2392, 1, "\u0915\u093C"], [2393, 1, "\u0916\u093C"], [2394, 1, "\u0917\u093C"], [2395, 1, "\u091C\u093C"], [2396, 1, "\u0921\u093C"], [2397, 1, "\u0922\u093C"], [2398, 1, "\u092B\u093C"], [2399, 1, "\u092F\u093C"], [[2400, 2403], 2], [[2404, 2405], 2], [[2406, 2415], 2], [2416, 2], [[2417, 2418], 2], [[2419, 2423], 2], [2424, 2], [[2425, 2426], 2], [[2427, 2428], 2], [2429, 2], [[2430, 2431], 2], [2432, 2], [[2433, 2435], 2], [2436, 3], [[2437, 2444], 2], [[2445, 2446], 3], [[2447, 2448], 2], [[2449, 2450], 3], [[2451, 2472], 2], [2473, 3], [[2474, 2480], 2], [2481, 3], [2482, 2], [[2483, 2485], 3], [[2486, 2489], 2], [[2490, 2491], 3], [2492, 2], [2493, 2], [[2494, 2500], 2], [[2501, 2502], 3], [[2503, 2504], 2], [[2505, 2506], 3], [[2507, 2509], 2], [2510, 2], [[2511, 2518], 3], [2519, 2], [[2520, 2523], 3], [2524, 1, "\u09A1\u09BC"], [2525, 1, "\u09A2\u09BC"], [2526, 3], [2527, 1, "\u09AF\u09BC"], [[2528, 2531], 2], [[2532, 2533], 3], [[2534, 2545], 2], [[2546, 2554], 2], [2555, 2], [2556, 2], [2557, 2], [2558, 2], [[2559, 2560], 3], [2561, 2], [2562, 2], [2563, 2], [2564, 3], [[2565, 2570], 2], [[2571, 2574], 3], [[2575, 2576], 2], [[2577, 2578], 3], [[2579, 2600], 2], [2601, 3], [[2602, 2608], 2], [2609, 3], [2610, 2], [2611, 1, "\u0A32\u0A3C"], [2612, 3], [2613, 2], [2614, 1, "\u0A38\u0A3C"], [2615, 3], [[2616, 2617], 2], [[2618, 2619], 3], [2620, 2], [2621, 3], [[2622, 2626], 2], [[2627, 2630], 3], [[2631, 2632], 2], [[2633, 2634], 3], [[2635, 2637], 2], [[2638, 2640], 3], [2641, 2], [[2642, 2648], 3], [2649, 1, "\u0A16\u0A3C"], [2650, 1, "\u0A17\u0A3C"], [2651, 1, "\u0A1C\u0A3C"], [2652, 2], [2653, 3], [2654, 1, "\u0A2B\u0A3C"], [[2655, 2661], 3], [[2662, 2676], 2], [2677, 2], [2678, 2], [[2679, 2688], 3], [[2689, 2691], 2], [2692, 3], [[2693, 2699], 2], [2700, 2], [2701, 2], [2702, 3], [[2703, 2705], 2], [2706, 3], [[2707, 2728], 2], [2729, 3], [[2730, 2736], 2], [2737, 3], [[2738, 2739], 2], [2740, 3], [[2741, 2745], 2], [[2746, 2747], 3], [[2748, 2757], 2], [2758, 3], [[2759, 2761], 2], [2762, 3], [[2763, 2765], 2], [[2766, 2767], 3], [2768, 2], [[2769, 2783], 3], [2784, 2], [[2785, 2787], 2], [[2788, 2789], 3], [[2790, 2799], 2], [2800, 2], [2801, 2], [[2802, 2808], 3], [2809, 2], [[2810, 2815], 2], [2816, 3], [[2817, 2819], 2], [2820, 3], [[2821, 2828], 2], [[2829, 2830], 3], [[2831, 2832], 2], [[2833, 2834], 3], [[2835, 2856], 2], [2857, 3], [[2858, 2864], 2], [2865, 3], [[2866, 2867], 2], [2868, 3], [2869, 2], [[2870, 2873], 2], [[2874, 2875], 3], [[2876, 2883], 2], [2884, 2], [[2885, 2886], 3], [[2887, 2888], 2], [[2889, 2890], 3], [[2891, 2893], 2], [[2894, 2900], 3], [2901, 2], [[2902, 2903], 2], [[2904, 2907], 3], [2908, 1, "\u0B21\u0B3C"], [2909, 1, "\u0B22\u0B3C"], [2910, 3], [[2911, 2913], 2], [[2914, 2915], 2], [[2916, 2917], 3], [[2918, 2927], 2], [2928, 2], [2929, 2], [[2930, 2935], 2], [[2936, 2945], 3], [[2946, 2947], 2], [2948, 3], [[2949, 2954], 2], [[2955, 2957], 3], [[2958, 2960], 2], [2961, 3], [[2962, 2965], 2], [[2966, 2968], 3], [[2969, 2970], 2], [2971, 3], [2972, 2], [2973, 3], [[2974, 2975], 2], [[2976, 2978], 3], [[2979, 2980], 2], [[2981, 2983], 3], [[2984, 2986], 2], [[2987, 2989], 3], [[2990, 2997], 2], [2998, 2], [[2999, 3001], 2], [[3002, 3005], 3], [[3006, 3010], 2], [[3011, 3013], 3], [[3014, 3016], 2], [3017, 3], [[3018, 3021], 2], [[3022, 3023], 3], [3024, 2], [[3025, 3030], 3], [3031, 2], [[3032, 3045], 3], [3046, 2], [[3047, 3055], 2], [[3056, 3058], 2], [[3059, 3066], 2], [[3067, 3071], 3], [3072, 2], [[3073, 3075], 2], [3076, 2], [[3077, 3084], 2], [3085, 3], [[3086, 3088], 2], [3089, 3], [[3090, 3112], 2], [3113, 3], [[3114, 3123], 2], [3124, 2], [[3125, 3129], 2], [[3130, 3131], 3], [3132, 2], [3133, 2], [[3134, 3140], 2], [3141, 3], [[3142, 3144], 2], [3145, 3], [[3146, 3149], 2], [[3150, 3156], 3], [[3157, 3158], 2], [3159, 3], [[3160, 3161], 2], [3162, 2], [[3163, 3164], 3], [3165, 2], [[3166, 3167], 3], [[3168, 3169], 2], [[3170, 3171], 2], [[3172, 3173], 3], [[3174, 3183], 2], [[3184, 3190], 3], [3191, 2], [[3192, 3199], 2], [3200, 2], [3201, 2], [[3202, 3203], 2], [3204, 2], [[3205, 3212], 2], [3213, 3], [[3214, 3216], 2], [3217, 3], [[3218, 3240], 2], [3241, 3], [[3242, 3251], 2], [3252, 3], [[3253, 3257], 2], [[3258, 3259], 3], [[3260, 3261], 2], [[3262, 3268], 2], [3269, 3], [[3270, 3272], 2], [3273, 3], [[3274, 3277], 2], [[3278, 3284], 3], [[3285, 3286], 2], [[3287, 3292], 3], [3293, 2], [3294, 2], [3295, 3], [[3296, 3297], 2], [[3298, 3299], 2], [[3300, 3301], 3], [[3302, 3311], 2], [3312, 3], [[3313, 3314], 2], [[3315, 3327], 3], [3328, 2], [3329, 2], [[3330, 3331], 2], [3332, 2], [[3333, 3340], 2], [3341, 3], [[3342, 3344], 2], [3345, 3], [[3346, 3368], 2], [3369, 2], [[3370, 3385], 2], [3386, 2], [[3387, 3388], 2], [3389, 2], [[3390, 3395], 2], [3396, 2], [3397, 3], [[3398, 3400], 2], [3401, 3], [[3402, 3405], 2], [3406, 2], [3407, 2], [[3408, 3411], 3], [[3412, 3414], 2], [3415, 2], [[3416, 3422], 2], [3423, 2], [[3424, 3425], 2], [[3426, 3427], 2], [[3428, 3429], 3], [[3430, 3439], 2], [[3440, 3445], 2], [[3446, 3448], 2], [3449, 2], [[3450, 3455], 2], [3456, 3], [3457, 2], [[3458, 3459], 2], [3460, 3], [[3461, 3478], 2], [[3479, 3481], 3], [[3482, 3505], 2], [3506, 3], [[3507, 3515], 2], [3516, 3], [3517, 2], [[3518, 3519], 3], [[3520, 3526], 2], [[3527, 3529], 3], [3530, 2], [[3531, 3534], 3], [[3535, 3540], 2], [3541, 3], [3542, 2], [3543, 3], [[3544, 3551], 2], [[3552, 3557], 3], [[3558, 3567], 2], [[3568, 3569], 3], [[3570, 3571], 2], [3572, 2], [[3573, 3584], 3], [[3585, 3634], 2], [3635, 1, "\u0E4D\u0E32"], [[3636, 3642], 2], [[3643, 3646], 3], [3647, 2], [[3648, 3662], 2], [3663, 2], [[3664, 3673], 2], [[3674, 3675], 2], [[3676, 3712], 3], [[3713, 3714], 2], [3715, 3], [3716, 2], [3717, 3], [3718, 2], [[3719, 3720], 2], [3721, 2], [3722, 2], [3723, 3], [3724, 2], [3725, 2], [[3726, 3731], 2], [[3732, 3735], 2], [3736, 2], [[3737, 3743], 2], [3744, 2], [[3745, 3747], 2], [3748, 3], [3749, 2], [3750, 3], [3751, 2], [[3752, 3753], 2], [[3754, 3755], 2], [3756, 2], [[3757, 3762], 2], [3763, 1, "\u0ECD\u0EB2"], [[3764, 3769], 2], [3770, 2], [[3771, 3773], 2], [[3774, 3775], 3], [[3776, 3780], 2], [3781, 3], [3782, 2], [3783, 3], [[3784, 3789], 2], [[3790, 3791], 3], [[3792, 3801], 2], [[3802, 3803], 3], [3804, 1, "\u0EAB\u0E99"], [3805, 1, "\u0EAB\u0EA1"], [[3806, 3807], 2], [[3808, 3839], 3], [3840, 2], [[3841, 3850], 2], [3851, 2], [3852, 1, "\u0F0B"], [[3853, 3863], 2], [[3864, 3865], 2], [[3866, 3871], 2], [[3872, 3881], 2], [[3882, 3892], 2], [3893, 2], [3894, 2], [3895, 2], [3896, 2], [3897, 2], [[3898, 3901], 2], [[3902, 3906], 2], [3907, 1, "\u0F42\u0FB7"], [[3908, 3911], 2], [3912, 3], [[3913, 3916], 2], [3917, 1, "\u0F4C\u0FB7"], [[3918, 3921], 2], [3922, 1, "\u0F51\u0FB7"], [[3923, 3926], 2], [3927, 1, "\u0F56\u0FB7"], [[3928, 3931], 2], [3932, 1, "\u0F5B\u0FB7"], [[3933, 3944], 2], [3945, 1, "\u0F40\u0FB5"], [3946, 2], [[3947, 3948], 2], [[3949, 3952], 3], [[3953, 3954], 2], [3955, 1, "\u0F71\u0F72"], [3956, 2], [3957, 1, "\u0F71\u0F74"], [3958, 1, "\u0FB2\u0F80"], [3959, 1, "\u0FB2\u0F71\u0F80"], [3960, 1, "\u0FB3\u0F80"], [3961, 1, "\u0FB3\u0F71\u0F80"], [[3962, 3968], 2], [3969, 1, "\u0F71\u0F80"], [[3970, 3972], 2], [3973, 2], [[3974, 3979], 2], [[3980, 3983], 2], [[3984, 3986], 2], [3987, 1, "\u0F92\u0FB7"], [[3988, 3989], 2], [3990, 2], [3991, 2], [3992, 3], [[3993, 3996], 2], [3997, 1, "\u0F9C\u0FB7"], [[3998, 4001], 2], [4002, 1, "\u0FA1\u0FB7"], [[4003, 4006], 2], [4007, 1, "\u0FA6\u0FB7"], [[4008, 4011], 2], [4012, 1, "\u0FAB\u0FB7"], [4013, 2], [[4014, 4016], 2], [[4017, 4023], 2], [4024, 2], [4025, 1, "\u0F90\u0FB5"], [[4026, 4028], 2], [4029, 3], [[4030, 4037], 2], [4038, 2], [[4039, 4044], 2], [4045, 3], [4046, 2], [4047, 2], [[4048, 4049], 2], [[4050, 4052], 2], [[4053, 4056], 2], [[4057, 4058], 2], [[4059, 4095], 3], [[4096, 4129], 2], [4130, 2], [[4131, 4135], 2], [4136, 2], [[4137, 4138], 2], [4139, 2], [[4140, 4146], 2], [[4147, 4149], 2], [[4150, 4153], 2], [[4154, 4159], 2], [[4160, 4169], 2], [[4170, 4175], 2], [[4176, 4185], 2], [[4186, 4249], 2], [[4250, 4253], 2], [[4254, 4255], 2], [[4256, 4293], 3], [4294, 3], [4295, 1, "\u2D27"], [[4296, 4300], 3], [4301, 1, "\u2D2D"], [[4302, 4303], 3], [[4304, 4342], 2], [[4343, 4344], 2], [[4345, 4346], 2], [4347, 2], [4348, 1, "\u10DC"], [[4349, 4351], 2], [[4352, 4441], 2], [[4442, 4446], 2], [[4447, 4448], 3], [[4449, 4514], 2], [[4515, 4519], 2], [[4520, 4601], 2], [[4602, 4607], 2], [[4608, 4614], 2], [4615, 2], [[4616, 4678], 2], [4679, 2], [4680, 2], [4681, 3], [[4682, 4685], 2], [[4686, 4687], 3], [[4688, 4694], 2], [4695, 3], [4696, 2], [4697, 3], [[4698, 4701], 2], [[4702, 4703], 3], [[4704, 4742], 2], [4743, 2], [4744, 2], [4745, 3], [[4746, 4749], 2], [[4750, 4751], 3], [[4752, 4782], 2], [4783, 2], [4784, 2], [4785, 3], [[4786, 4789], 2], [[4790, 4791], 3], [[4792, 4798], 2], [4799, 3], [4800, 2], [4801, 3], [[4802, 4805], 2], [[4806, 4807], 3], [[4808, 4814], 2], [4815, 2], [[4816, 4822], 2], [4823, 3], [[4824, 4846], 2], [4847, 2], [[4848, 4878], 2], [4879, 2], [4880, 2], [4881, 3], [[4882, 4885], 2], [[4886, 4887], 3], [[4888, 4894], 2], [4895, 2], [[4896, 4934], 2], [4935, 2], [[4936, 4954], 2], [[4955, 4956], 3], [[4957, 4958], 2], [4959, 2], [4960, 2], [[4961, 4988], 2], [[4989, 4991], 3], [[4992, 5007], 2], [[5008, 5017], 2], [[5018, 5023], 3], [[5024, 5108], 2], [5109, 2], [[5110, 5111], 3], [5112, 1, "\u13F0"], [5113, 1, "\u13F1"], [5114, 1, "\u13F2"], [5115, 1, "\u13F3"], [5116, 1, "\u13F4"], [5117, 1, "\u13F5"], [[5118, 5119], 3], [5120, 2], [[5121, 5740], 2], [[5741, 5742], 2], [[5743, 5750], 2], [[5751, 5759], 2], [5760, 3], [[5761, 5786], 2], [[5787, 5788], 2], [[5789, 5791], 3], [[5792, 5866], 2], [[5867, 5872], 2], [[5873, 5880], 2], [[5881, 5887], 3], [[5888, 5900], 2], [5901, 2], [[5902, 5908], 2], [5909, 2], [[5910, 5918], 3], [5919, 2], [[5920, 5940], 2], [[5941, 5942], 2], [[5943, 5951], 3], [[5952, 5971], 2], [[5972, 5983], 3], [[5984, 5996], 2], [5997, 3], [[5998, 6e3], 2], [6001, 3], [[6002, 6003], 2], [[6004, 6015], 3], [[6016, 6067], 2], [[6068, 6069], 3], [[6070, 6099], 2], [[6100, 6102], 2], [6103, 2], [[6104, 6107], 2], [6108, 2], [6109, 2], [[6110, 6111], 3], [[6112, 6121], 2], [[6122, 6127], 3], [[6128, 6137], 2], [[6138, 6143], 3], [[6144, 6149], 2], [6150, 3], [[6151, 6154], 2], [[6155, 6157], 7], [6158, 3], [6159, 7], [[6160, 6169], 2], [[6170, 6175], 3], [[6176, 6263], 2], [6264, 2], [[6265, 6271], 3], [[6272, 6313], 2], [6314, 2], [[6315, 6319], 3], [[6320, 6389], 2], [[6390, 6399], 3], [[6400, 6428], 2], [[6429, 6430], 2], [6431, 3], [[6432, 6443], 2], [[6444, 6447], 3], [[6448, 6459], 2], [[6460, 6463], 3], [6464, 2], [[6465, 6467], 3], [[6468, 6469], 2], [[6470, 6509], 2], [[6510, 6511], 3], [[6512, 6516], 2], [[6517, 6527], 3], [[6528, 6569], 2], [[6570, 6571], 2], [[6572, 6575], 3], [[6576, 6601], 2], [[6602, 6607], 3], [[6608, 6617], 2], [6618, 2], [[6619, 6621], 3], [[6622, 6623], 2], [[6624, 6655], 2], [[6656, 6683], 2], [[6684, 6685], 3], [[6686, 6687], 2], [[6688, 6750], 2], [6751, 3], [[6752, 6780], 2], [[6781, 6782], 3], [[6783, 6793], 2], [[6794, 6799], 3], [[6800, 6809], 2], [[6810, 6815], 3], [[6816, 6822], 2], [6823, 2], [[6824, 6829], 2], [[6830, 6831], 3], [[6832, 6845], 2], [6846, 2], [[6847, 6848], 2], [[6849, 6862], 2], [[6863, 6911], 3], [[6912, 6987], 2], [6988, 2], [[6989, 6991], 3], [[6992, 7001], 2], [[7002, 7018], 2], [[7019, 7027], 2], [[7028, 7036], 2], [[7037, 7038], 2], [7039, 3], [[7040, 7082], 2], [[7083, 7085], 2], [[7086, 7097], 2], [[7098, 7103], 2], [[7104, 7155], 2], [[7156, 7163], 3], [[7164, 7167], 2], [[7168, 7223], 2], [[7224, 7226], 3], [[7227, 7231], 2], [[7232, 7241], 2], [[7242, 7244], 3], [[7245, 7293], 2], [[7294, 7295], 2], [7296, 1, "\u0432"], [7297, 1, "\u0434"], [7298, 1, "\u043E"], [7299, 1, "\u0441"], [[7300, 7301], 1, "\u0442"], [7302, 1, "\u044A"], [7303, 1, "\u0463"], [7304, 1, "\uA64B"], [[7305, 7311], 3], [7312, 1, "\u10D0"], [7313, 1, "\u10D1"], [7314, 1, "\u10D2"], [7315, 1, "\u10D3"], [7316, 1, "\u10D4"], [7317, 1, "\u10D5"], [7318, 1, "\u10D6"], [7319, 1, "\u10D7"], [7320, 1, "\u10D8"], [7321, 1, "\u10D9"], [7322, 1, "\u10DA"], [7323, 1, "\u10DB"], [7324, 1, "\u10DC"], [7325, 1, "\u10DD"], [7326, 1, "\u10DE"], [7327, 1, "\u10DF"], [7328, 1, "\u10E0"], [7329, 1, "\u10E1"], [7330, 1, "\u10E2"], [7331, 1, "\u10E3"], [7332, 1, "\u10E4"], [7333, 1, "\u10E5"], [7334, 1, "\u10E6"], [7335, 1, "\u10E7"], [7336, 1, "\u10E8"], [7337, 1, "\u10E9"], [7338, 1, "\u10EA"], [7339, 1, "\u10EB"], [7340, 1, "\u10EC"], [7341, 1, "\u10ED"], [7342, 1, "\u10EE"], [7343, 1, "\u10EF"], [7344, 1, "\u10F0"], [7345, 1, "\u10F1"], [7346, 1, "\u10F2"], [7347, 1, "\u10F3"], [7348, 1, "\u10F4"], [7349, 1, "\u10F5"], [7350, 1, "\u10F6"], [7351, 1, "\u10F7"], [7352, 1, "\u10F8"], [7353, 1, "\u10F9"], [7354, 1, "\u10FA"], [[7355, 7356], 3], [7357, 1, "\u10FD"], [7358, 1, "\u10FE"], [7359, 1, "\u10FF"], [[7360, 7367], 2], [[7368, 7375], 3], [[7376, 7378], 2], [7379, 2], [[7380, 7410], 2], [[7411, 7414], 2], [7415, 2], [[7416, 7417], 2], [7418, 2], [[7419, 7423], 3], [[7424, 7467], 2], [7468, 1, "a"], [7469, 1, "\xE6"], [7470, 1, "b"], [7471, 2], [7472, 1, "d"], [7473, 1, "e"], [7474, 1, "\u01DD"], [7475, 1, "g"], [7476, 1, "h"], [7477, 1, "i"], [7478, 1, "j"], [7479, 1, "k"], [7480, 1, "l"], [7481, 1, "m"], [7482, 1, "n"], [7483, 2], [7484, 1, "o"], [7485, 1, "\u0223"], [7486, 1, "p"], [7487, 1, "r"], [7488, 1, "t"], [7489, 1, "u"], [7490, 1, "w"], [7491, 1, "a"], [7492, 1, "\u0250"], [7493, 1, "\u0251"], [7494, 1, "\u1D02"], [7495, 1, "b"], [7496, 1, "d"], [7497, 1, "e"], [7498, 1, "\u0259"], [7499, 1, "\u025B"], [7500, 1, "\u025C"], [7501, 1, "g"], [7502, 2], [7503, 1, "k"], [7504, 1, "m"], [7505, 1, "\u014B"], [7506, 1, "o"], [7507, 1, "\u0254"], [7508, 1, "\u1D16"], [7509, 1, "\u1D17"], [7510, 1, "p"], [7511, 1, "t"], [7512, 1, "u"], [7513, 1, "\u1D1D"], [7514, 1, "\u026F"], [7515, 1, "v"], [7516, 1, "\u1D25"], [7517, 1, "\u03B2"], [7518, 1, "\u03B3"], [7519, 1, "\u03B4"], [7520, 1, "\u03C6"], [7521, 1, "\u03C7"], [7522, 1, "i"], [7523, 1, "r"], [7524, 1, "u"], [7525, 1, "v"], [7526, 1, "\u03B2"], [7527, 1, "\u03B3"], [7528, 1, "\u03C1"], [7529, 1, "\u03C6"], [7530, 1, "\u03C7"], [7531, 2], [[7532, 7543], 2], [7544, 1, "\u043D"], [[7545, 7578], 2], [7579, 1, "\u0252"], [7580, 1, "c"], [7581, 1, "\u0255"], [7582, 1, "\xF0"], [7583, 1, "\u025C"], [7584, 1, "f"], [7585, 1, "\u025F"], [7586, 1, "\u0261"], [7587, 1, "\u0265"], [7588, 1, "\u0268"], [7589, 1, "\u0269"], [7590, 1, "\u026A"], [7591, 1, "\u1D7B"], [7592, 1, "\u029D"], [7593, 1, "\u026D"], [7594, 1, "\u1D85"], [7595, 1, "\u029F"], [7596, 1, "\u0271"], [7597, 1, "\u0270"], [7598, 1, "\u0272"], [7599, 1, "\u0273"], [7600, 1, "\u0274"], [7601, 1, "\u0275"], [7602, 1, "\u0278"], [7603, 1, "\u0282"], [7604, 1, "\u0283"], [7605, 1, "\u01AB"], [7606, 1, "\u0289"], [7607, 1, "\u028A"], [7608, 1, "\u1D1C"], [7609, 1, "\u028B"], [7610, 1, "\u028C"], [7611, 1, "z"], [7612, 1, "\u0290"], [7613, 1, "\u0291"], [7614, 1, "\u0292"], [7615, 1, "\u03B8"], [[7616, 7619], 2], [[7620, 7626], 2], [[7627, 7654], 2], [[7655, 7669], 2], [[7670, 7673], 2], [7674, 2], [7675, 2], [7676, 2], [7677, 2], [[7678, 7679], 2], [7680, 1, "\u1E01"], [7681, 2], [7682, 1, "\u1E03"], [7683, 2], [7684, 1, "\u1E05"], [7685, 2], [7686, 1, "\u1E07"], [7687, 2], [7688, 1, "\u1E09"], [7689, 2], [7690, 1, "\u1E0B"], [7691, 2], [7692, 1, "\u1E0D"], [7693, 2], [7694, 1, "\u1E0F"], [7695, 2], [7696, 1, "\u1E11"], [7697, 2], [7698, 1, "\u1E13"], [7699, 2], [7700, 1, "\u1E15"], [7701, 2], [7702, 1, "\u1E17"], [7703, 2], [7704, 1, "\u1E19"], [7705, 2], [7706, 1, "\u1E1B"], [7707, 2], [7708, 1, "\u1E1D"], [7709, 2], [7710, 1, "\u1E1F"], [7711, 2], [7712, 1, "\u1E21"], [7713, 2], [7714, 1, "\u1E23"], [7715, 2], [7716, 1, "\u1E25"], [7717, 2], [7718, 1, "\u1E27"], [7719, 2], [7720, 1, "\u1E29"], [7721, 2], [7722, 1, "\u1E2B"], [7723, 2], [7724, 1, "\u1E2D"], [7725, 2], [7726, 1, "\u1E2F"], [7727, 2], [7728, 1, "\u1E31"], [7729, 2], [7730, 1, "\u1E33"], [7731, 2], [7732, 1, "\u1E35"], [7733, 2], [7734, 1, "\u1E37"], [7735, 2], [7736, 1, "\u1E39"], [7737, 2], [7738, 1, "\u1E3B"], [7739, 2], [7740, 1, "\u1E3D"], [7741, 2], [7742, 1, "\u1E3F"], [7743, 2], [7744, 1, "\u1E41"], [7745, 2], [7746, 1, "\u1E43"], [7747, 2], [7748, 1, "\u1E45"], [7749, 2], [7750, 1, "\u1E47"], [7751, 2], [7752, 1, "\u1E49"], [7753, 2], [7754, 1, "\u1E4B"], [7755, 2], [7756, 1, "\u1E4D"], [7757, 2], [7758, 1, "\u1E4F"], [7759, 2], [7760, 1, "\u1E51"], [7761, 2], [7762, 1, "\u1E53"], [7763, 2], [7764, 1, "\u1E55"], [7765, 2], [7766, 1, "\u1E57"], [7767, 2], [7768, 1, "\u1E59"], [7769, 2], [7770, 1, "\u1E5B"], [7771, 2], [7772, 1, "\u1E5D"], [7773, 2], [7774, 1, "\u1E5F"], [7775, 2], [7776, 1, "\u1E61"], [7777, 2], [7778, 1, "\u1E63"], [7779, 2], [7780, 1, "\u1E65"], [7781, 2], [7782, 1, "\u1E67"], [7783, 2], [7784, 1, "\u1E69"], [7785, 2], [7786, 1, "\u1E6B"], [7787, 2], [7788, 1, "\u1E6D"], [7789, 2], [7790, 1, "\u1E6F"], [7791, 2], [7792, 1, "\u1E71"], [7793, 2], [7794, 1, "\u1E73"], [7795, 2], [7796, 1, "\u1E75"], [7797, 2], [7798, 1, "\u1E77"], [7799, 2], [7800, 1, "\u1E79"], [7801, 2], [7802, 1, "\u1E7B"], [7803, 2], [7804, 1, "\u1E7D"], [7805, 2], [7806, 1, "\u1E7F"], [7807, 2], [7808, 1, "\u1E81"], [7809, 2], [7810, 1, "\u1E83"], [7811, 2], [7812, 1, "\u1E85"], [7813, 2], [7814, 1, "\u1E87"], [7815, 2], [7816, 1, "\u1E89"], [7817, 2], [7818, 1, "\u1E8B"], [7819, 2], [7820, 1, "\u1E8D"], [7821, 2], [7822, 1, "\u1E8F"], [7823, 2], [7824, 1, "\u1E91"], [7825, 2], [7826, 1, "\u1E93"], [7827, 2], [7828, 1, "\u1E95"], [[7829, 7833], 2], [7834, 1, "a\u02BE"], [7835, 1, "\u1E61"], [[7836, 7837], 2], [7838, 1, "ss"], [7839, 2], [7840, 1, "\u1EA1"], [7841, 2], [7842, 1, "\u1EA3"], [7843, 2], [7844, 1, "\u1EA5"], [7845, 2], [7846, 1, "\u1EA7"], [7847, 2], [7848, 1, "\u1EA9"], [7849, 2], [7850, 1, "\u1EAB"], [7851, 2], [7852, 1, "\u1EAD"], [7853, 2], [7854, 1, "\u1EAF"], [7855, 2], [7856, 1, "\u1EB1"], [7857, 2], [7858, 1, "\u1EB3"], [7859, 2], [7860, 1, "\u1EB5"], [7861, 2], [7862, 1, "\u1EB7"], [7863, 2], [7864, 1, "\u1EB9"], [7865, 2], [7866, 1, "\u1EBB"], [7867, 2], [7868, 1, "\u1EBD"], [7869, 2], [7870, 1, "\u1EBF"], [7871, 2], [7872, 1, "\u1EC1"], [7873, 2], [7874, 1, "\u1EC3"], [7875, 2], [7876, 1, "\u1EC5"], [7877, 2], [7878, 1, "\u1EC7"], [7879, 2], [7880, 1, "\u1EC9"], [7881, 2], [7882, 1, "\u1ECB"], [7883, 2], [7884, 1, "\u1ECD"], [7885, 2], [7886, 1, "\u1ECF"], [7887, 2], [7888, 1, "\u1ED1"], [7889, 2], [7890, 1, "\u1ED3"], [7891, 2], [7892, 1, "\u1ED5"], [7893, 2], [7894, 1, "\u1ED7"], [7895, 2], [7896, 1, "\u1ED9"], [7897, 2], [7898, 1, "\u1EDB"], [7899, 2], [7900, 1, "\u1EDD"], [7901, 2], [7902, 1, "\u1EDF"], [7903, 2], [7904, 1, "\u1EE1"], [7905, 2], [7906, 1, "\u1EE3"], [7907, 2], [7908, 1, "\u1EE5"], [7909, 2], [7910, 1, "\u1EE7"], [7911, 2], [7912, 1, "\u1EE9"], [7913, 2], [7914, 1, "\u1EEB"], [7915, 2], [7916, 1, "\u1EED"], [7917, 2], [7918, 1, "\u1EEF"], [7919, 2], [7920, 1, "\u1EF1"], [7921, 2], [7922, 1, "\u1EF3"], [7923, 2], [7924, 1, "\u1EF5"], [7925, 2], [7926, 1, "\u1EF7"], [7927, 2], [7928, 1, "\u1EF9"], [7929, 2], [7930, 1, "\u1EFB"], [7931, 2], [7932, 1, "\u1EFD"], [7933, 2], [7934, 1, "\u1EFF"], [7935, 2], [[7936, 7943], 2], [7944, 1, "\u1F00"], [7945, 1, "\u1F01"], [7946, 1, "\u1F02"], [7947, 1, "\u1F03"], [7948, 1, "\u1F04"], [7949, 1, "\u1F05"], [7950, 1, "\u1F06"], [7951, 1, "\u1F07"], [[7952, 7957], 2], [[7958, 7959], 3], [7960, 1, "\u1F10"], [7961, 1, "\u1F11"], [7962, 1, "\u1F12"], [7963, 1, "\u1F13"], [7964, 1, "\u1F14"], [7965, 1, "\u1F15"], [[7966, 7967], 3], [[7968, 7975], 2], [7976, 1, "\u1F20"], [7977, 1, "\u1F21"], [7978, 1, "\u1F22"], [7979, 1, "\u1F23"], [7980, 1, "\u1F24"], [7981, 1, "\u1F25"], [7982, 1, "\u1F26"], [7983, 1, "\u1F27"], [[7984, 7991], 2], [7992, 1, "\u1F30"], [7993, 1, "\u1F31"], [7994, 1, "\u1F32"], [7995, 1, "\u1F33"], [7996, 1, "\u1F34"], [7997, 1, "\u1F35"], [7998, 1, "\u1F36"], [7999, 1, "\u1F37"], [[8e3, 8005], 2], [[8006, 8007], 3], [8008, 1, "\u1F40"], [8009, 1, "\u1F41"], [8010, 1, "\u1F42"], [8011, 1, "\u1F43"], [8012, 1, "\u1F44"], [8013, 1, "\u1F45"], [[8014, 8015], 3], [[8016, 8023], 2], [8024, 3], [8025, 1, "\u1F51"], [8026, 3], [8027, 1, "\u1F53"], [8028, 3], [8029, 1, "\u1F55"], [8030, 3], [8031, 1, "\u1F57"], [[8032, 8039], 2], [8040, 1, "\u1F60"], [8041, 1, "\u1F61"], [8042, 1, "\u1F62"], [8043, 1, "\u1F63"], [8044, 1, "\u1F64"], [8045, 1, "\u1F65"], [8046, 1, "\u1F66"], [8047, 1, "\u1F67"], [8048, 2], [8049, 1, "\u03AC"], [8050, 2], [8051, 1, "\u03AD"], [8052, 2], [8053, 1, "\u03AE"], [8054, 2], [8055, 1, "\u03AF"], [8056, 2], [8057, 1, "\u03CC"], [8058, 2], [8059, 1, "\u03CD"], [8060, 2], [8061, 1, "\u03CE"], [[8062, 8063], 3], [8064, 1, "\u1F00\u03B9"], [8065, 1, "\u1F01\u03B9"], [8066, 1, "\u1F02\u03B9"], [8067, 1, "\u1F03\u03B9"], [8068, 1, "\u1F04\u03B9"], [8069, 1, "\u1F05\u03B9"], [8070, 1, "\u1F06\u03B9"], [8071, 1, "\u1F07\u03B9"], [8072, 1, "\u1F00\u03B9"], [8073, 1, "\u1F01\u03B9"], [8074, 1, "\u1F02\u03B9"], [8075, 1, "\u1F03\u03B9"], [8076, 1, "\u1F04\u03B9"], [8077, 1, "\u1F05\u03B9"], [8078, 1, "\u1F06\u03B9"], [8079, 1, "\u1F07\u03B9"], [8080, 1, "\u1F20\u03B9"], [8081, 1, "\u1F21\u03B9"], [8082, 1, "\u1F22\u03B9"], [8083, 1, "\u1F23\u03B9"], [8084, 1, "\u1F24\u03B9"], [8085, 1, "\u1F25\u03B9"], [8086, 1, "\u1F26\u03B9"], [8087, 1, "\u1F27\u03B9"], [8088, 1, "\u1F20\u03B9"], [8089, 1, "\u1F21\u03B9"], [8090, 1, "\u1F22\u03B9"], [8091, 1, "\u1F23\u03B9"], [8092, 1, "\u1F24\u03B9"], [8093, 1, "\u1F25\u03B9"], [8094, 1, "\u1F26\u03B9"], [8095, 1, "\u1F27\u03B9"], [8096, 1, "\u1F60\u03B9"], [8097, 1, "\u1F61\u03B9"], [8098, 1, "\u1F62\u03B9"], [8099, 1, "\u1F63\u03B9"], [8100, 1, "\u1F64\u03B9"], [8101, 1, "\u1F65\u03B9"], [8102, 1, "\u1F66\u03B9"], [8103, 1, "\u1F67\u03B9"], [8104, 1, "\u1F60\u03B9"], [8105, 1, "\u1F61\u03B9"], [8106, 1, "\u1F62\u03B9"], [8107, 1, "\u1F63\u03B9"], [8108, 1, "\u1F64\u03B9"], [8109, 1, "\u1F65\u03B9"], [8110, 1, "\u1F66\u03B9"], [8111, 1, "\u1F67\u03B9"], [[8112, 8113], 2], [8114, 1, "\u1F70\u03B9"], [8115, 1, "\u03B1\u03B9"], [8116, 1, "\u03AC\u03B9"], [8117, 3], [8118, 2], [8119, 1, "\u1FB6\u03B9"], [8120, 1, "\u1FB0"], [8121, 1, "\u1FB1"], [8122, 1, "\u1F70"], [8123, 1, "\u03AC"], [8124, 1, "\u03B1\u03B9"], [8125, 5, " \u0313"], [8126, 1, "\u03B9"], [8127, 5, " \u0313"], [8128, 5, " \u0342"], [8129, 5, " \u0308\u0342"], [8130, 1, "\u1F74\u03B9"], [8131, 1, "\u03B7\u03B9"], [8132, 1, "\u03AE\u03B9"], [8133, 3], [8134, 2], [8135, 1, "\u1FC6\u03B9"], [8136, 1, "\u1F72"], [8137, 1, "\u03AD"], [8138, 1, "\u1F74"], [8139, 1, "\u03AE"], [8140, 1, "\u03B7\u03B9"], [8141, 5, " \u0313\u0300"], [8142, 5, " \u0313\u0301"], [8143, 5, " \u0313\u0342"], [[8144, 8146], 2], [8147, 1, "\u0390"], [[8148, 8149], 3], [[8150, 8151], 2], [8152, 1, "\u1FD0"], [8153, 1, "\u1FD1"], [8154, 1, "\u1F76"], [8155, 1, "\u03AF"], [8156, 3], [8157, 5, " \u0314\u0300"], [8158, 5, " \u0314\u0301"], [8159, 5, " \u0314\u0342"], [[8160, 8162], 2], [8163, 1, "\u03B0"], [[8164, 8167], 2], [8168, 1, "\u1FE0"], [8169, 1, "\u1FE1"], [8170, 1, "\u1F7A"], [8171, 1, "\u03CD"], [8172, 1, "\u1FE5"], [8173, 5, " \u0308\u0300"], [8174, 5, " \u0308\u0301"], [8175, 5, "`"], [[8176, 8177], 3], [8178, 1, "\u1F7C\u03B9"], [8179, 1, "\u03C9\u03B9"], [8180, 1, "\u03CE\u03B9"], [8181, 3], [8182, 2], [8183, 1, "\u1FF6\u03B9"], [8184, 1, "\u1F78"], [8185, 1, "\u03CC"], [8186, 1, "\u1F7C"], [8187, 1, "\u03CE"], [8188, 1, "\u03C9\u03B9"], [8189, 5, " \u0301"], [8190, 5, " \u0314"], [8191, 3], [[8192, 8202], 5, " "], [8203, 7], [[8204, 8205], 6, ""], [[8206, 8207], 3], [8208, 2], [8209, 1, "\u2010"], [[8210, 8214], 2], [8215, 5, " \u0333"], [[8216, 8227], 2], [[8228, 8230], 3], [8231, 2], [[8232, 8238], 3], [8239, 5, " "], [[8240, 8242], 2], [8243, 1, "\u2032\u2032"], [8244, 1, "\u2032\u2032\u2032"], [8245, 2], [8246, 1, "\u2035\u2035"], [8247, 1, "\u2035\u2035\u2035"], [[8248, 8251], 2], [8252, 5, "!!"], [8253, 2], [8254, 5, " \u0305"], [[8255, 8262], 2], [8263, 5, "??"], [8264, 5, "?!"], [8265, 5, "!?"], [[8266, 8269], 2], [[8270, 8274], 2], [[8275, 8276], 2], [[8277, 8278], 2], [8279, 1, "\u2032\u2032\u2032\u2032"], [[8280, 8286], 2], [8287, 5, " "], [8288, 7], [[8289, 8291], 3], [8292, 7], [8293, 3], [[8294, 8297], 3], [[8298, 8303], 3], [8304, 1, "0"], [8305, 1, "i"], [[8306, 8307], 3], [8308, 1, "4"], [8309, 1, "5"], [8310, 1, "6"], [8311, 1, "7"], [8312, 1, "8"], [8313, 1, "9"], [8314, 5, "+"], [8315, 1, "\u2212"], [8316, 5, "="], [8317, 5, "("], [8318, 5, ")"], [8319, 1, "n"], [8320, 1, "0"], [8321, 1, "1"], [8322, 1, "2"], [8323, 1, "3"], [8324, 1, "4"], [8325, 1, "5"], [8326, 1, "6"], [8327, 1, "7"], [8328, 1, "8"], [8329, 1, "9"], [8330, 5, "+"], [8331, 1, "\u2212"], [8332, 5, "="], [8333, 5, "("], [8334, 5, ")"], [8335, 3], [8336, 1, "a"], [8337, 1, "e"], [8338, 1, "o"], [8339, 1, "x"], [8340, 1, "\u0259"], [8341, 1, "h"], [8342, 1, "k"], [8343, 1, "l"], [8344, 1, "m"], [8345, 1, "n"], [8346, 1, "p"], [8347, 1, "s"], [8348, 1, "t"], [[8349, 8351], 3], [[8352, 8359], 2], [8360, 1, "rs"], [[8361, 8362], 2], [8363, 2], [8364, 2], [[8365, 8367], 2], [[8368, 8369], 2], [[8370, 8373], 2], [[8374, 8376], 2], [8377, 2], [8378, 2], [[8379, 8381], 2], [8382, 2], [8383, 2], [8384, 2], [[8385, 8399], 3], [[8400, 8417], 2], [[8418, 8419], 2], [[8420, 8426], 2], [8427, 2], [[8428, 8431], 2], [8432, 2], [[8433, 8447], 3], [8448, 5, "a/c"], [8449, 5, "a/s"], [8450, 1, "c"], [8451, 1, "\xB0c"], [8452, 2], [8453, 5, "c/o"], [8454, 5, "c/u"], [8455, 1, "\u025B"], [8456, 2], [8457, 1, "\xB0f"], [8458, 1, "g"], [[8459, 8462], 1, "h"], [8463, 1, "\u0127"], [[8464, 8465], 1, "i"], [[8466, 8467], 1, "l"], [8468, 2], [8469, 1, "n"], [8470, 1, "no"], [[8471, 8472], 2], [8473, 1, "p"], [8474, 1, "q"], [[8475, 8477], 1, "r"], [[8478, 8479], 2], [8480, 1, "sm"], [8481, 1, "tel"], [8482, 1, "tm"], [8483, 2], [8484, 1, "z"], [8485, 2], [8486, 1, "\u03C9"], [8487, 2], [8488, 1, "z"], [8489, 2], [8490, 1, "k"], [8491, 1, "\xE5"], [8492, 1, "b"], [8493, 1, "c"], [8494, 2], [[8495, 8496], 1, "e"], [8497, 1, "f"], [8498, 3], [8499, 1, "m"], [8500, 1, "o"], [8501, 1, "\u05D0"], [8502, 1, "\u05D1"], [8503, 1, "\u05D2"], [8504, 1, "\u05D3"], [8505, 1, "i"], [8506, 2], [8507, 1, "fax"], [8508, 1, "\u03C0"], [[8509, 8510], 1, "\u03B3"], [8511, 1, "\u03C0"], [8512, 1, "\u2211"], [[8513, 8516], 2], [[8517, 8518], 1, "d"], [8519, 1, "e"], [8520, 1, "i"], [8521, 1, "j"], [[8522, 8523], 2], [8524, 2], [8525, 2], [8526, 2], [8527, 2], [8528, 1, "1\u20447"], [8529, 1, "1\u20449"], [8530, 1, "1\u204410"], [8531, 1, "1\u20443"], [8532, 1, "2\u20443"], [8533, 1, "1\u20445"], [8534, 1, "2\u20445"], [8535, 1, "3\u20445"], [8536, 1, "4\u20445"], [8537, 1, "1\u20446"], [8538, 1, "5\u20446"], [8539, 1, "1\u20448"], [8540, 1, "3\u20448"], [8541, 1, "5\u20448"], [8542, 1, "7\u20448"], [8543, 1, "1\u2044"], [8544, 1, "i"], [8545, 1, "ii"], [8546, 1, "iii"], [8547, 1, "iv"], [8548, 1, "v"], [8549, 1, "vi"], [8550, 1, "vii"], [8551, 1, "viii"], [8552, 1, "ix"], [8553, 1, "x"], [8554, 1, "xi"], [8555, 1, "xii"], [8556, 1, "l"], [8557, 1, "c"], [8558, 1, "d"], [8559, 1, "m"], [8560, 1, "i"], [8561, 1, "ii"], [8562, 1, "iii"], [8563, 1, "iv"], [8564, 1, "v"], [8565, 1, "vi"], [8566, 1, "vii"], [8567, 1, "viii"], [8568, 1, "ix"], [8569, 1, "x"], [8570, 1, "xi"], [8571, 1, "xii"], [8572, 1, "l"], [8573, 1, "c"], [8574, 1, "d"], [8575, 1, "m"], [[8576, 8578], 2], [8579, 3], [8580, 2], [[8581, 8584], 2], [8585, 1, "0\u20443"], [[8586, 8587], 2], [[8588, 8591], 3], [[8592, 8682], 2], [[8683, 8691], 2], [[8692, 8703], 2], [[8704, 8747], 2], [8748, 1, "\u222B\u222B"], [8749, 1, "\u222B\u222B\u222B"], [8750, 2], [8751, 1, "\u222E\u222E"], [8752, 1, "\u222E\u222E\u222E"], [[8753, 8799], 2], [8800, 4], [[8801, 8813], 2], [[8814, 8815], 4], [[8816, 8945], 2], [[8946, 8959], 2], [8960, 2], [8961, 2], [[8962, 9e3], 2], [9001, 1, "\u3008"], [9002, 1, "\u3009"], [[9003, 9082], 2], [9083, 2], [9084, 2], [[9085, 9114], 2], [[9115, 9166], 2], [[9167, 9168], 2], [[9169, 9179], 2], [[9180, 9191], 2], [9192, 2], [[9193, 9203], 2], [[9204, 9210], 2], [[9211, 9214], 2], [9215, 2], [[9216, 9252], 2], [[9253, 9254], 2], [[9255, 9279], 3], [[9280, 9290], 2], [[9291, 9311], 3], [9312, 1, "1"], [9313, 1, "2"], [9314, 1, "3"], [9315, 1, "4"], [9316, 1, "5"], [9317, 1, "6"], [9318, 1, "7"], [9319, 1, "8"], [9320, 1, "9"], [9321, 1, "10"], [9322, 1, "11"], [9323, 1, "12"], [9324, 1, "13"], [9325, 1, "14"], [9326, 1, "15"], [9327, 1, "16"], [9328, 1, "17"], [9329, 1, "18"], [9330, 1, "19"], [9331, 1, "20"], [9332, 5, "(1)"], [9333, 5, "(2)"], [9334, 5, "(3)"], [9335, 5, "(4)"], [9336, 5, "(5)"], [9337, 5, "(6)"], [9338, 5, "(7)"], [9339, 5, "(8)"], [9340, 5, "(9)"], [9341, 5, "(10)"], [9342, 5, "(11)"], [9343, 5, "(12)"], [9344, 5, "(13)"], [9345, 5, "(14)"], [9346, 5, "(15)"], [9347, 5, "(16)"], [9348, 5, "(17)"], [9349, 5, "(18)"], [9350, 5, "(19)"], [9351, 5, "(20)"], [[9352, 9371], 3], [9372, 5, "(a)"], [9373, 5, "(b)"], [9374, 5, "(c)"], [9375, 5, "(d)"], [9376, 5, "(e)"], [9377, 5, "(f)"], [9378, 5, "(g)"], [9379, 5, "(h)"], [9380, 5, "(i)"], [9381, 5, "(j)"], [9382, 5, "(k)"], [9383, 5, "(l)"], [9384, 5, "(m)"], [9385, 5, "(n)"], [9386, 5, "(o)"], [9387, 5, "(p)"], [9388, 5, "(q)"], [9389, 5, "(r)"], [9390, 5, "(s)"], [9391, 5, "(t)"], [9392, 5, "(u)"], [9393, 5, "(v)"], [9394, 5, "(w)"], [9395, 5, "(x)"], [9396, 5, "(y)"], [9397, 5, "(z)"], [9398, 1, "a"], [9399, 1, "b"], [9400, 1, "c"], [9401, 1, "d"], [9402, 1, "e"], [9403, 1, "f"], [9404, 1, "g"], [9405, 1, "h"], [9406, 1, "i"], [9407, 1, "j"], [9408, 1, "k"], [9409, 1, "l"], [9410, 1, "m"], [9411, 1, "n"], [9412, 1, "o"], [9413, 1, "p"], [9414, 1, "q"], [9415, 1, "r"], [9416, 1, "s"], [9417, 1, "t"], [9418, 1, "u"], [9419, 1, "v"], [9420, 1, "w"], [9421, 1, "x"], [9422, 1, "y"], [9423, 1, "z"], [9424, 1, "a"], [9425, 1, "b"], [9426, 1, "c"], [9427, 1, "d"], [9428, 1, "e"], [9429, 1, "f"], [9430, 1, "g"], [9431, 1, "h"], [9432, 1, "i"], [9433, 1, "j"], [9434, 1, "k"], [9435, 1, "l"], [9436, 1, "m"], [9437, 1, "n"], [9438, 1, "o"], [9439, 1, "p"], [9440, 1, "q"], [9441, 1, "r"], [9442, 1, "s"], [9443, 1, "t"], [9444, 1, "u"], [9445, 1, "v"], [9446, 1, "w"], [9447, 1, "x"], [9448, 1, "y"], [9449, 1, "z"], [9450, 1, "0"], [[9451, 9470], 2], [9471, 2], [[9472, 9621], 2], [[9622, 9631], 2], [[9632, 9711], 2], [[9712, 9719], 2], [[9720, 9727], 2], [[9728, 9747], 2], [[9748, 9749], 2], [[9750, 9751], 2], [9752, 2], [9753, 2], [[9754, 9839], 2], [[9840, 9841], 2], [[9842, 9853], 2], [[9854, 9855], 2], [[9856, 9865], 2], [[9866, 9873], 2], [[9874, 9884], 2], [9885, 2], [[9886, 9887], 2], [[9888, 9889], 2], [[9890, 9905], 2], [9906, 2], [[9907, 9916], 2], [[9917, 9919], 2], [[9920, 9923], 2], [[9924, 9933], 2], [9934, 2], [[9935, 9953], 2], [9954, 2], [9955, 2], [[9956, 9959], 2], [[9960, 9983], 2], [9984, 2], [[9985, 9988], 2], [9989, 2], [[9990, 9993], 2], [[9994, 9995], 2], [[9996, 10023], 2], [10024, 2], [[10025, 10059], 2], [10060, 2], [10061, 2], [10062, 2], [[10063, 10066], 2], [[10067, 10069], 2], [10070, 2], [10071, 2], [[10072, 10078], 2], [[10079, 10080], 2], [[10081, 10087], 2], [[10088, 10101], 2], [[10102, 10132], 2], [[10133, 10135], 2], [[10136, 10159], 2], [10160, 2], [[10161, 10174], 2], [10175, 2], [[10176, 10182], 2], [[10183, 10186], 2], [10187, 2], [10188, 2], [10189, 2], [[10190, 10191], 2], [[10192, 10219], 2], [[10220, 10223], 2], [[10224, 10239], 2], [[10240, 10495], 2], [[10496, 10763], 2], [10764, 1, "\u222B\u222B\u222B\u222B"], [[10765, 10867], 2], [10868, 5, "::="], [10869, 5, "=="], [10870, 5, "==="], [[10871, 10971], 2], [10972, 1, "\u2ADD\u0338"], [[10973, 11007], 2], [[11008, 11021], 2], [[11022, 11027], 2], [[11028, 11034], 2], [[11035, 11039], 2], [[11040, 11043], 2], [[11044, 11084], 2], [[11085, 11087], 2], [[11088, 11092], 2], [[11093, 11097], 2], [[11098, 11123], 2], [[11124, 11125], 3], [[11126, 11157], 2], [11158, 3], [11159, 2], [[11160, 11193], 2], [[11194, 11196], 2], [[11197, 11208], 2], [11209, 2], [[11210, 11217], 2], [11218, 2], [[11219, 11243], 2], [[11244, 11247], 2], [[11248, 11262], 2], [11263, 2], [11264, 1, "\u2C30"], [11265, 1, "\u2C31"], [11266, 1, "\u2C32"], [11267, 1, "\u2C33"], [11268, 1, "\u2C34"], [11269, 1, "\u2C35"], [11270, 1, "\u2C36"], [11271, 1, "\u2C37"], [11272, 1, "\u2C38"], [11273, 1, "\u2C39"], [11274, 1, "\u2C3A"], [11275, 1, "\u2C3B"], [11276, 1, "\u2C3C"], [11277, 1, "\u2C3D"], [11278, 1, "\u2C3E"], [11279, 1, "\u2C3F"], [11280, 1, "\u2C40"], [11281, 1, "\u2C41"], [11282, 1, "\u2C42"], [11283, 1, "\u2C43"], [11284, 1, "\u2C44"], [11285, 1, "\u2C45"], [11286, 1, "\u2C46"], [11287, 1, "\u2C47"], [11288, 1, "\u2C48"], [11289, 1, "\u2C49"], [11290, 1, "\u2C4A"], [11291, 1, "\u2C4B"], [11292, 1, "\u2C4C"], [11293, 1, "\u2C4D"], [11294, 1, "\u2C4E"], [11295, 1, "\u2C4F"], [11296, 1, "\u2C50"], [11297, 1, "\u2C51"], [11298, 1, "\u2C52"], [11299, 1, "\u2C53"], [11300, 1, "\u2C54"], [11301, 1, "\u2C55"], [11302, 1, "\u2C56"], [11303, 1, "\u2C57"], [11304, 1, "\u2C58"], [11305, 1, "\u2C59"], [11306, 1, "\u2C5A"], [11307, 1, "\u2C5B"], [11308, 1, "\u2C5C"], [11309, 1, "\u2C5D"], [11310, 1, "\u2C5E"], [11311, 1, "\u2C5F"], [[11312, 11358], 2], [11359, 2], [11360, 1, "\u2C61"], [11361, 2], [11362, 1, "\u026B"], [11363, 1, "\u1D7D"], [11364, 1, "\u027D"], [[11365, 11366], 2], [11367, 1, "\u2C68"], [11368, 2], [11369, 1, "\u2C6A"], [11370, 2], [11371, 1, "\u2C6C"], [11372, 2], [11373, 1, "\u0251"], [11374, 1, "\u0271"], [11375, 1, "\u0250"], [11376, 1, "\u0252"], [11377, 2], [11378, 1, "\u2C73"], [11379, 2], [11380, 2], [11381, 1, "\u2C76"], [[11382, 11383], 2], [[11384, 11387], 2], [11388, 1, "j"], [11389, 1, "v"], [11390, 1, "\u023F"], [11391, 1, "\u0240"], [11392, 1, "\u2C81"], [11393, 2], [11394, 1, "\u2C83"], [11395, 2], [11396, 1, "\u2C85"], [11397, 2], [11398, 1, "\u2C87"], [11399, 2], [11400, 1, "\u2C89"], [11401, 2], [11402, 1, "\u2C8B"], [11403, 2], [11404, 1, "\u2C8D"], [11405, 2], [11406, 1, "\u2C8F"], [11407, 2], [11408, 1, "\u2C91"], [11409, 2], [11410, 1, "\u2C93"], [11411, 2], [11412, 1, "\u2C95"], [11413, 2], [11414, 1, "\u2C97"], [11415, 2], [11416, 1, "\u2C99"], [11417, 2], [11418, 1, "\u2C9B"], [11419, 2], [11420, 1, "\u2C9D"], [11421, 2], [11422, 1, "\u2C9F"], [11423, 2], [11424, 1, "\u2CA1"], [11425, 2], [11426, 1, "\u2CA3"], [11427, 2], [11428, 1, "\u2CA5"], [11429, 2], [11430, 1, "\u2CA7"], [11431, 2], [11432, 1, "\u2CA9"], [11433, 2], [11434, 1, "\u2CAB"], [11435, 2], [11436, 1, "\u2CAD"], [11437, 2], [11438, 1, "\u2CAF"], [11439, 2], [11440, 1, "\u2CB1"], [11441, 2], [11442, 1, "\u2CB3"], [11443, 2], [11444, 1, "\u2CB5"], [11445, 2], [11446, 1, "\u2CB7"], [11447, 2], [11448, 1, "\u2CB9"], [11449, 2], [11450, 1, "\u2CBB"], [11451, 2], [11452, 1, "\u2CBD"], [11453, 2], [11454, 1, "\u2CBF"], [11455, 2], [11456, 1, "\u2CC1"], [11457, 2], [11458, 1, "\u2CC3"], [11459, 2], [11460, 1, "\u2CC5"], [11461, 2], [11462, 1, "\u2CC7"], [11463, 2], [11464, 1, "\u2CC9"], [11465, 2], [11466, 1, "\u2CCB"], [11467, 2], [11468, 1, "\u2CCD"], [11469, 2], [11470, 1, "\u2CCF"], [11471, 2], [11472, 1, "\u2CD1"], [11473, 2], [11474, 1, "\u2CD3"], [11475, 2], [11476, 1, "\u2CD5"], [11477, 2], [11478, 1, "\u2CD7"], [11479, 2], [11480, 1, "\u2CD9"], [11481, 2], [11482, 1, "\u2CDB"], [11483, 2], [11484, 1, "\u2CDD"], [11485, 2], [11486, 1, "\u2CDF"], [11487, 2], [11488, 1, "\u2CE1"], [11489, 2], [11490, 1, "\u2CE3"], [[11491, 11492], 2], [[11493, 11498], 2], [11499, 1, "\u2CEC"], [11500, 2], [11501, 1, "\u2CEE"], [[11502, 11505], 2], [11506, 1, "\u2CF3"], [11507, 2], [[11508, 11512], 3], [[11513, 11519], 2], [[11520, 11557], 2], [11558, 3], [11559, 2], [[11560, 11564], 3], [11565, 2], [[11566, 11567], 3], [[11568, 11621], 2], [[11622, 11623], 2], [[11624, 11630], 3], [11631, 1, "\u2D61"], [11632, 2], [[11633, 11646], 3], [11647, 2], [[11648, 11670], 2], [[11671, 11679], 3], [[11680, 11686], 2], [11687, 3], [[11688, 11694], 2], [11695, 3], [[11696, 11702], 2], [11703, 3], [[11704, 11710], 2], [11711, 3], [[11712, 11718], 2], [11719, 3], [[11720, 11726], 2], [11727, 3], [[11728, 11734], 2], [11735, 3], [[11736, 11742], 2], [11743, 3], [[11744, 11775], 2], [[11776, 11799], 2], [[11800, 11803], 2], [[11804, 11805], 2], [[11806, 11822], 2], [11823, 2], [11824, 2], [11825, 2], [[11826, 11835], 2], [[11836, 11842], 2], [[11843, 11844], 2], [[11845, 11849], 2], [[11850, 11854], 2], [11855, 2], [[11856, 11858], 2], [[11859, 11869], 2], [[11870, 11903], 3], [[11904, 11929], 2], [11930, 3], [[11931, 11934], 2], [11935, 1, "\u6BCD"], [[11936, 12018], 2], [12019, 1, "\u9F9F"], [[12020, 12031], 3], [12032, 1, "\u4E00"], [12033, 1, "\u4E28"], [12034, 1, "\u4E36"], [12035, 1, "\u4E3F"], [12036, 1, "\u4E59"], [12037, 1, "\u4E85"], [12038, 1, "\u4E8C"], [12039, 1, "\u4EA0"], [12040, 1, "\u4EBA"], [12041, 1, "\u513F"], [12042, 1, "\u5165"], [12043, 1, "\u516B"], [12044, 1, "\u5182"], [12045, 1, "\u5196"], [12046, 1, "\u51AB"], [12047, 1, "\u51E0"], [12048, 1, "\u51F5"], [12049, 1, "\u5200"], [12050, 1, "\u529B"], [12051, 1, "\u52F9"], [12052, 1, "\u5315"], [12053, 1, "\u531A"], [12054, 1, "\u5338"], [12055, 1, "\u5341"], [12056, 1, "\u535C"], [12057, 1, "\u5369"], [12058, 1, "\u5382"], [12059, 1, "\u53B6"], [12060, 1, "\u53C8"], [12061, 1, "\u53E3"], [12062, 1, "\u56D7"], [12063, 1, "\u571F"], [12064, 1, "\u58EB"], [12065, 1, "\u5902"], [12066, 1, "\u590A"], [12067, 1, "\u5915"], [12068, 1, "\u5927"], [12069, 1, "\u5973"], [12070, 1, "\u5B50"], [12071, 1, "\u5B80"], [12072, 1, "\u5BF8"], [12073, 1, "\u5C0F"], [12074, 1, "\u5C22"], [12075, 1, "\u5C38"], [12076, 1, "\u5C6E"], [12077, 1, "\u5C71"], [12078, 1, "\u5DDB"], [12079, 1, "\u5DE5"], [12080, 1, "\u5DF1"], [12081, 1, "\u5DFE"], [12082, 1, "\u5E72"], [12083, 1, "\u5E7A"], [12084, 1, "\u5E7F"], [12085, 1, "\u5EF4"], [12086, 1, "\u5EFE"], [12087, 1, "\u5F0B"], [12088, 1, "\u5F13"], [12089, 1, "\u5F50"], [12090, 1, "\u5F61"], [12091, 1, "\u5F73"], [12092, 1, "\u5FC3"], [12093, 1, "\u6208"], [12094, 1, "\u6236"], [12095, 1, "\u624B"], [12096, 1, "\u652F"], [12097, 1, "\u6534"], [12098, 1, "\u6587"], [12099, 1, "\u6597"], [12100, 1, "\u65A4"], [12101, 1, "\u65B9"], [12102, 1, "\u65E0"], [12103, 1, "\u65E5"], [12104, 1, "\u66F0"], [12105, 1, "\u6708"], [12106, 1, "\u6728"], [12107, 1, "\u6B20"], [12108, 1, "\u6B62"], [12109, 1, "\u6B79"], [12110, 1, "\u6BB3"], [12111, 1, "\u6BCB"], [12112, 1, "\u6BD4"], [12113, 1, "\u6BDB"], [12114, 1, "\u6C0F"], [12115, 1, "\u6C14"], [12116, 1, "\u6C34"], [12117, 1, "\u706B"], [12118, 1, "\u722A"], [12119, 1, "\u7236"], [12120, 1, "\u723B"], [12121, 1, "\u723F"], [12122, 1, "\u7247"], [12123, 1, "\u7259"], [12124, 1, "\u725B"], [12125, 1, "\u72AC"], [12126, 1, "\u7384"], [12127, 1, "\u7389"], [12128, 1, "\u74DC"], [12129, 1, "\u74E6"], [12130, 1, "\u7518"], [12131, 1, "\u751F"], [12132, 1, "\u7528"], [12133, 1, "\u7530"], [12134, 1, "\u758B"], [12135, 1, "\u7592"], [12136, 1, "\u7676"], [12137, 1, "\u767D"], [12138, 1, "\u76AE"], [12139, 1, "\u76BF"], [12140, 1, "\u76EE"], [12141, 1, "\u77DB"], [12142, 1, "\u77E2"], [12143, 1, "\u77F3"], [12144, 1, "\u793A"], [12145, 1, "\u79B8"], [12146, 1, "\u79BE"], [12147, 1, "\u7A74"], [12148, 1, "\u7ACB"], [12149, 1, "\u7AF9"], [12150, 1, "\u7C73"], [12151, 1, "\u7CF8"], [12152, 1, "\u7F36"], [12153, 1, "\u7F51"], [12154, 1, "\u7F8A"], [12155, 1, "\u7FBD"], [12156, 1, "\u8001"], [12157, 1, "\u800C"], [12158, 1, "\u8012"], [12159, 1, "\u8033"], [12160, 1, "\u807F"], [12161, 1, "\u8089"], [12162, 1, "\u81E3"], [12163, 1, "\u81EA"], [12164, 1, "\u81F3"], [12165, 1, "\u81FC"], [12166, 1, "\u820C"], [12167, 1, "\u821B"], [12168, 1, "\u821F"], [12169, 1, "\u826E"], [12170, 1, "\u8272"], [12171, 1, "\u8278"], [12172, 1, "\u864D"], [12173, 1, "\u866B"], [12174, 1, "\u8840"], [12175, 1, "\u884C"], [12176, 1, "\u8863"], [12177, 1, "\u897E"], [12178, 1, "\u898B"], [12179, 1, "\u89D2"], [12180, 1, "\u8A00"], [12181, 1, "\u8C37"], [12182, 1, "\u8C46"], [12183, 1, "\u8C55"], [12184, 1, "\u8C78"], [12185, 1, "\u8C9D"], [12186, 1, "\u8D64"], [12187, 1, "\u8D70"], [12188, 1, "\u8DB3"], [12189, 1, "\u8EAB"], [12190, 1, "\u8ECA"], [12191, 1, "\u8F9B"], [12192, 1, "\u8FB0"], [12193, 1, "\u8FB5"], [12194, 1, "\u9091"], [12195, 1, "\u9149"], [12196, 1, "\u91C6"], [12197, 1, "\u91CC"], [12198, 1, "\u91D1"], [12199, 1, "\u9577"], [12200, 1, "\u9580"], [12201, 1, "\u961C"], [12202, 1, "\u96B6"], [12203, 1, "\u96B9"], [12204, 1, "\u96E8"], [12205, 1, "\u9751"], [12206, 1, "\u975E"], [12207, 1, "\u9762"], [12208, 1, "\u9769"], [12209, 1, "\u97CB"], [12210, 1, "\u97ED"], [12211, 1, "\u97F3"], [12212, 1, "\u9801"], [12213, 1, "\u98A8"], [12214, 1, "\u98DB"], [12215, 1, "\u98DF"], [12216, 1, "\u9996"], [12217, 1, "\u9999"], [12218, 1, "\u99AC"], [12219, 1, "\u9AA8"], [12220, 1, "\u9AD8"], [12221, 1, "\u9ADF"], [12222, 1, "\u9B25"], [12223, 1, "\u9B2F"], [12224, 1, "\u9B32"], [12225, 1, "\u9B3C"], [12226, 1, "\u9B5A"], [12227, 1, "\u9CE5"], [12228, 1, "\u9E75"], [12229, 1, "\u9E7F"], [12230, 1, "\u9EA5"], [12231, 1, "\u9EBB"], [12232, 1, "\u9EC3"], [12233, 1, "\u9ECD"], [12234, 1, "\u9ED1"], [12235, 1, "\u9EF9"], [12236, 1, "\u9EFD"], [12237, 1, "\u9F0E"], [12238, 1, "\u9F13"], [12239, 1, "\u9F20"], [12240, 1, "\u9F3B"], [12241, 1, "\u9F4A"], [12242, 1, "\u9F52"], [12243, 1, "\u9F8D"], [12244, 1, "\u9F9C"], [12245, 1, "\u9FA0"], [[12246, 12271], 3], [[12272, 12283], 3], [[12284, 12287], 3], [12288, 5, " "], [12289, 2], [12290, 1, "."], [[12291, 12292], 2], [[12293, 12295], 2], [[12296, 12329], 2], [[12330, 12333], 2], [[12334, 12341], 2], [12342, 1, "\u3012"], [12343, 2], [12344, 1, "\u5341"], [12345, 1, "\u5344"], [12346, 1, "\u5345"], [12347, 2], [12348, 2], [12349, 2], [12350, 2], [12351, 2], [12352, 3], [[12353, 12436], 2], [[12437, 12438], 2], [[12439, 12440], 3], [[12441, 12442], 2], [12443, 5, " \u3099"], [12444, 5, " \u309A"], [[12445, 12446], 2], [12447, 1, "\u3088\u308A"], [12448, 2], [[12449, 12542], 2], [12543, 1, "\u30B3\u30C8"], [[12544, 12548], 3], [[12549, 12588], 2], [12589, 2], [12590, 2], [12591, 2], [12592, 3], [12593, 1, "\u1100"], [12594, 1, "\u1101"], [12595, 1, "\u11AA"], [12596, 1, "\u1102"], [12597, 1, "\u11AC"], [12598, 1, "\u11AD"], [12599, 1, "\u1103"], [12600, 1, "\u1104"], [12601, 1, "\u1105"], [12602, 1, "\u11B0"], [12603, 1, "\u11B1"], [12604, 1, "\u11B2"], [12605, 1, "\u11B3"], [12606, 1, "\u11B4"], [12607, 1, "\u11B5"], [12608, 1, "\u111A"], [12609, 1, "\u1106"], [12610, 1, "\u1107"], [12611, 1, "\u1108"], [12612, 1, "\u1121"], [12613, 1, "\u1109"], [12614, 1, "\u110A"], [12615, 1, "\u110B"], [12616, 1, "\u110C"], [12617, 1, "\u110D"], [12618, 1, "\u110E"], [12619, 1, "\u110F"], [12620, 1, "\u1110"], [12621, 1, "\u1111"], [12622, 1, "\u1112"], [12623, 1, "\u1161"], [12624, 1, "\u1162"], [12625, 1, "\u1163"], [12626, 1, "\u1164"], [12627, 1, "\u1165"], [12628, 1, "\u1166"], [12629, 1, "\u1167"], [12630, 1, "\u1168"], [12631, 1, "\u1169"], [12632, 1, "\u116A"], [12633, 1, "\u116B"], [12634, 1, "\u116C"], [12635, 1, "\u116D"], [12636, 1, "\u116E"], [12637, 1, "\u116F"], [12638, 1, "\u1170"], [12639, 1, "\u1171"], [12640, 1, "\u1172"], [12641, 1, "\u1173"], [12642, 1, "\u1174"], [12643, 1, "\u1175"], [12644, 3], [12645, 1, "\u1114"], [12646, 1, "\u1115"], [12647, 1, "\u11C7"], [12648, 1, "\u11C8"], [12649, 1, "\u11CC"], [12650, 1, "\u11CE"], [12651, 1, "\u11D3"], [12652, 1, "\u11D7"], [12653, 1, "\u11D9"], [12654, 1, "\u111C"], [12655, 1, "\u11DD"], [12656, 1, "\u11DF"], [12657, 1, "\u111D"], [12658, 1, "\u111E"], [12659, 1, "\u1120"], [12660, 1, "\u1122"], [12661, 1, "\u1123"], [12662, 1, "\u1127"], [12663, 1, "\u1129"], [12664, 1, "\u112B"], [12665, 1, "\u112C"], [12666, 1, "\u112D"], [12667, 1, "\u112E"], [12668, 1, "\u112F"], [12669, 1, "\u1132"], [12670, 1, "\u1136"], [12671, 1, "\u1140"], [12672, 1, "\u1147"], [12673, 1, "\u114C"], [12674, 1, "\u11F1"], [12675, 1, "\u11F2"], [12676, 1, "\u1157"], [12677, 1, "\u1158"], [12678, 1, "\u1159"], [12679, 1, "\u1184"], [12680, 1, "\u1185"], [12681, 1, "\u1188"], [12682, 1, "\u1191"], [12683, 1, "\u1192"], [12684, 1, "\u1194"], [12685, 1, "\u119E"], [12686, 1, "\u11A1"], [12687, 3], [[12688, 12689], 2], [12690, 1, "\u4E00"], [12691, 1, "\u4E8C"], [12692, 1, "\u4E09"], [12693, 1, "\u56DB"], [12694, 1, "\u4E0A"], [12695, 1, "\u4E2D"], [12696, 1, "\u4E0B"], [12697, 1, "\u7532"], [12698, 1, "\u4E59"], [12699, 1, "\u4E19"], [12700, 1, "\u4E01"], [12701, 1, "\u5929"], [12702, 1, "\u5730"], [12703, 1, "\u4EBA"], [[12704, 12727], 2], [[12728, 12730], 2], [[12731, 12735], 2], [[12736, 12751], 2], [[12752, 12771], 2], [[12772, 12783], 3], [[12784, 12799], 2], [12800, 5, "(\u1100)"], [12801, 5, "(\u1102)"], [12802, 5, "(\u1103)"], [12803, 5, "(\u1105)"], [12804, 5, "(\u1106)"], [12805, 5, "(\u1107)"], [12806, 5, "(\u1109)"], [12807, 5, "(\u110B)"], [12808, 5, "(\u110C)"], [12809, 5, "(\u110E)"], [12810, 5, "(\u110F)"], [12811, 5, "(\u1110)"], [12812, 5, "(\u1111)"], [12813, 5, "(\u1112)"], [12814, 5, "(\uAC00)"], [12815, 5, "(\uB098)"], [12816, 5, "(\uB2E4)"], [12817, 5, "(\uB77C)"], [12818, 5, "(\uB9C8)"], [12819, 5, "(\uBC14)"], [12820, 5, "(\uC0AC)"], [12821, 5, "(\uC544)"], [12822, 5, "(\uC790)"], [12823, 5, "(\uCC28)"], [12824, 5, "(\uCE74)"], [12825, 5, "(\uD0C0)"], [12826, 5, "(\uD30C)"], [12827, 5, "(\uD558)"], [12828, 5, "(\uC8FC)"], [12829, 5, "(\uC624\uC804)"], [12830, 5, "(\uC624\uD6C4)"], [12831, 3], [12832, 5, "(\u4E00)"], [12833, 5, "(\u4E8C)"], [12834, 5, "(\u4E09)"], [12835, 5, "(\u56DB)"], [12836, 5, "(\u4E94)"], [12837, 5, "(\u516D)"], [12838, 5, "(\u4E03)"], [12839, 5, "(\u516B)"], [12840, 5, "(\u4E5D)"], [12841, 5, "(\u5341)"], [12842, 5, "(\u6708)"], [12843, 5, "(\u706B)"], [12844, 5, "(\u6C34)"], [12845, 5, "(\u6728)"], [12846, 5, "(\u91D1)"], [12847, 5, "(\u571F)"], [12848, 5, "(\u65E5)"], [12849, 5, "(\u682A)"], [12850, 5, "(\u6709)"], [12851, 5, "(\u793E)"], [12852, 5, "(\u540D)"], [12853, 5, "(\u7279)"], [12854, 5, "(\u8CA1)"], [12855, 5, "(\u795D)"], [12856, 5, "(\u52B4)"], [12857, 5, "(\u4EE3)"], [12858, 5, "(\u547C)"], [12859, 5, "(\u5B66)"], [12860, 5, "(\u76E3)"], [12861, 5, "(\u4F01)"], [12862, 5, "(\u8CC7)"], [12863, 5, "(\u5354)"], [12864, 5, "(\u796D)"], [12865, 5, "(\u4F11)"], [12866, 5, "(\u81EA)"], [12867, 5, "(\u81F3)"], [12868, 1, "\u554F"], [12869, 1, "\u5E7C"], [12870, 1, "\u6587"], [12871, 1, "\u7B8F"], [[12872, 12879], 2], [12880, 1, "pte"], [12881, 1, "21"], [12882, 1, "22"], [12883, 1, "23"], [12884, 1, "24"], [12885, 1, "25"], [12886, 1, "26"], [12887, 1, "27"], [12888, 1, "28"], [12889, 1, "29"], [12890, 1, "30"], [12891, 1, "31"], [12892, 1, "32"], [12893, 1, "33"], [12894, 1, "34"], [12895, 1, "35"], [12896, 1, "\u1100"], [12897, 1, "\u1102"], [12898, 1, "\u1103"], [12899, 1, "\u1105"], [12900, 1, "\u1106"], [12901, 1, "\u1107"], [12902, 1, "\u1109"], [12903, 1, "\u110B"], [12904, 1, "\u110C"], [12905, 1, "\u110E"], [12906, 1, "\u110F"], [12907, 1, "\u1110"], [12908, 1, "\u1111"], [12909, 1, "\u1112"], [12910, 1, "\uAC00"], [12911, 1, "\uB098"], [12912, 1, "\uB2E4"], [12913, 1, "\uB77C"], [12914, 1, "\uB9C8"], [12915, 1, "\uBC14"], [12916, 1, "\uC0AC"], [12917, 1, "\uC544"], [12918, 1, "\uC790"], [12919, 1, "\uCC28"], [12920, 1, "\uCE74"], [12921, 1, "\uD0C0"], [12922, 1, "\uD30C"], [12923, 1, "\uD558"], [12924, 1, "\uCC38\uACE0"], [12925, 1, "\uC8FC\uC758"], [12926, 1, "\uC6B0"], [12927, 2], [12928, 1, "\u4E00"], [12929, 1, "\u4E8C"], [12930, 1, "\u4E09"], [12931, 1, "\u56DB"], [12932, 1, "\u4E94"], [12933, 1, "\u516D"], [12934, 1, "\u4E03"], [12935, 1, "\u516B"], [12936, 1, "\u4E5D"], [12937, 1, "\u5341"], [12938, 1, "\u6708"], [12939, 1, "\u706B"], [12940, 1, "\u6C34"], [12941, 1, "\u6728"], [12942, 1, "\u91D1"], [12943, 1, "\u571F"], [12944, 1, "\u65E5"], [12945, 1, "\u682A"], [12946, 1, "\u6709"], [12947, 1, "\u793E"], [12948, 1, "\u540D"], [12949, 1, "\u7279"], [12950, 1, "\u8CA1"], [12951, 1, "\u795D"], [12952, 1, "\u52B4"], [12953, 1, "\u79D8"], [12954, 1, "\u7537"], [12955, 1, "\u5973"], [12956, 1, "\u9069"], [12957, 1, "\u512A"], [12958, 1, "\u5370"], [12959, 1, "\u6CE8"], [12960, 1, "\u9805"], [12961, 1, "\u4F11"], [12962, 1, "\u5199"], [12963, 1, "\u6B63"], [12964, 1, "\u4E0A"], [12965, 1, "\u4E2D"], [12966, 1, "\u4E0B"], [12967, 1, "\u5DE6"], [12968, 1, "\u53F3"], [12969, 1, "\u533B"], [12970, 1, "\u5B97"], [12971, 1, "\u5B66"], [12972, 1, "\u76E3"], [12973, 1, "\u4F01"], [12974, 1, "\u8CC7"], [12975, 1, "\u5354"], [12976, 1, "\u591C"], [12977, 1, "36"], [12978, 1, "37"], [12979, 1, "38"], [12980, 1, "39"], [12981, 1, "40"], [12982, 1, "41"], [12983, 1, "42"], [12984, 1, "43"], [12985, 1, "44"], [12986, 1, "45"], [12987, 1, "46"], [12988, 1, "47"], [12989, 1, "48"], [12990, 1, "49"], [12991, 1, "50"], [12992, 1, "1\u6708"], [12993, 1, "2\u6708"], [12994, 1, "3\u6708"], [12995, 1, "4\u6708"], [12996, 1, "5\u6708"], [12997, 1, "6\u6708"], [12998, 1, "7\u6708"], [12999, 1, "8\u6708"], [13e3, 1, "9\u6708"], [13001, 1, "10\u6708"], [13002, 1, "11\u6708"], [13003, 1, "12\u6708"], [13004, 1, "hg"], [13005, 1, "erg"], [13006, 1, "ev"], [13007, 1, "ltd"], [13008, 1, "\u30A2"], [13009, 1, "\u30A4"], [13010, 1, "\u30A6"], [13011, 1, "\u30A8"], [13012, 1, "\u30AA"], [13013, 1, "\u30AB"], [13014, 1, "\u30AD"], [13015, 1, "\u30AF"], [13016, 1, "\u30B1"], [13017, 1, "\u30B3"], [13018, 1, "\u30B5"], [13019, 1, "\u30B7"], [13020, 1, "\u30B9"], [13021, 1, "\u30BB"], [13022, 1, "\u30BD"], [13023, 1, "\u30BF"], [13024, 1, "\u30C1"], [13025, 1, "\u30C4"], [13026, 1, "\u30C6"], [13027, 1, "\u30C8"], [13028, 1, "\u30CA"], [13029, 1, "\u30CB"], [13030, 1, "\u30CC"], [13031, 1, "\u30CD"], [13032, 1, "\u30CE"], [13033, 1, "\u30CF"], [13034, 1, "\u30D2"], [13035, 1, "\u30D5"], [13036, 1, "\u30D8"], [13037, 1, "\u30DB"], [13038, 1, "\u30DE"], [13039, 1, "\u30DF"], [13040, 1, "\u30E0"], [13041, 1, "\u30E1"], [13042, 1, "\u30E2"], [13043, 1, "\u30E4"], [13044, 1, "\u30E6"], [13045, 1, "\u30E8"], [13046, 1, "\u30E9"], [13047, 1, "\u30EA"], [13048, 1, "\u30EB"], [13049, 1, "\u30EC"], [13050, 1, "\u30ED"], [13051, 1, "\u30EF"], [13052, 1, "\u30F0"], [13053, 1, "\u30F1"], [13054, 1, "\u30F2"], [13055, 1, "\u4EE4\u548C"], [13056, 1, "\u30A2\u30D1\u30FC\u30C8"], [13057, 1, "\u30A2\u30EB\u30D5\u30A1"], [13058, 1, "\u30A2\u30F3\u30DA\u30A2"], [13059, 1, "\u30A2\u30FC\u30EB"], [13060, 1, "\u30A4\u30CB\u30F3\u30B0"], [13061, 1, "\u30A4\u30F3\u30C1"], [13062, 1, "\u30A6\u30A9\u30F3"], [13063, 1, "\u30A8\u30B9\u30AF\u30FC\u30C9"], [13064, 1, "\u30A8\u30FC\u30AB\u30FC"], [13065, 1, "\u30AA\u30F3\u30B9"], [13066, 1, "\u30AA\u30FC\u30E0"], [13067, 1, "\u30AB\u30A4\u30EA"], [13068, 1, "\u30AB\u30E9\u30C3\u30C8"], [13069, 1, "\u30AB\u30ED\u30EA\u30FC"], [13070, 1, "\u30AC\u30ED\u30F3"], [13071, 1, "\u30AC\u30F3\u30DE"], [13072, 1, "\u30AE\u30AC"], [13073, 1, "\u30AE\u30CB\u30FC"], [13074, 1, "\u30AD\u30E5\u30EA\u30FC"], [13075, 1, "\u30AE\u30EB\u30C0\u30FC"], [13076, 1, "\u30AD\u30ED"], [13077, 1, "\u30AD\u30ED\u30B0\u30E9\u30E0"], [13078, 1, "\u30AD\u30ED\u30E1\u30FC\u30C8\u30EB"], [13079, 1, "\u30AD\u30ED\u30EF\u30C3\u30C8"], [13080, 1, "\u30B0\u30E9\u30E0"], [13081, 1, "\u30B0\u30E9\u30E0\u30C8\u30F3"], [13082, 1, "\u30AF\u30EB\u30BC\u30A4\u30ED"], [13083, 1, "\u30AF\u30ED\u30FC\u30CD"], [13084, 1, "\u30B1\u30FC\u30B9"], [13085, 1, "\u30B3\u30EB\u30CA"], [13086, 1, "\u30B3\u30FC\u30DD"], [13087, 1, "\u30B5\u30A4\u30AF\u30EB"], [13088, 1, "\u30B5\u30F3\u30C1\u30FC\u30E0"], [13089, 1, "\u30B7\u30EA\u30F3\u30B0"], [13090, 1, "\u30BB\u30F3\u30C1"], [13091, 1, "\u30BB\u30F3\u30C8"], [13092, 1, "\u30C0\u30FC\u30B9"], [13093, 1, "\u30C7\u30B7"], [13094, 1, "\u30C9\u30EB"], [13095, 1, "\u30C8\u30F3"], [13096, 1, "\u30CA\u30CE"], [13097, 1, "\u30CE\u30C3\u30C8"], [13098, 1, "\u30CF\u30A4\u30C4"], [13099, 1, "\u30D1\u30FC\u30BB\u30F3\u30C8"], [13100, 1, "\u30D1\u30FC\u30C4"], [13101, 1, "\u30D0\u30FC\u30EC\u30EB"], [13102, 1, "\u30D4\u30A2\u30B9\u30C8\u30EB"], [13103, 1, "\u30D4\u30AF\u30EB"], [13104, 1, "\u30D4\u30B3"], [13105, 1, "\u30D3\u30EB"], [13106, 1, "\u30D5\u30A1\u30E9\u30C3\u30C9"], [13107, 1, "\u30D5\u30A3\u30FC\u30C8"], [13108, 1, "\u30D6\u30C3\u30B7\u30A7\u30EB"], [13109, 1, "\u30D5\u30E9\u30F3"], [13110, 1, "\u30D8\u30AF\u30BF\u30FC\u30EB"], [13111, 1, "\u30DA\u30BD"], [13112, 1, "\u30DA\u30CB\u30D2"], [13113, 1, "\u30D8\u30EB\u30C4"], [13114, 1, "\u30DA\u30F3\u30B9"], [13115, 1, "\u30DA\u30FC\u30B8"], [13116, 1, "\u30D9\u30FC\u30BF"], [13117, 1, "\u30DD\u30A4\u30F3\u30C8"], [13118, 1, "\u30DC\u30EB\u30C8"], [13119, 1, "\u30DB\u30F3"], [13120, 1, "\u30DD\u30F3\u30C9"], [13121, 1, "\u30DB\u30FC\u30EB"], [13122, 1, "\u30DB\u30FC\u30F3"], [13123, 1, "\u30DE\u30A4\u30AF\u30ED"], [13124, 1, "\u30DE\u30A4\u30EB"], [13125, 1, "\u30DE\u30C3\u30CF"], [13126, 1, "\u30DE\u30EB\u30AF"], [13127, 1, "\u30DE\u30F3\u30B7\u30E7\u30F3"], [13128, 1, "\u30DF\u30AF\u30ED\u30F3"], [13129, 1, "\u30DF\u30EA"], [13130, 1, "\u30DF\u30EA\u30D0\u30FC\u30EB"], [13131, 1, "\u30E1\u30AC"], [13132, 1, "\u30E1\u30AC\u30C8\u30F3"], [13133, 1, "\u30E1\u30FC\u30C8\u30EB"], [13134, 1, "\u30E4\u30FC\u30C9"], [13135, 1, "\u30E4\u30FC\u30EB"], [13136, 1, "\u30E6\u30A2\u30F3"], [13137, 1, "\u30EA\u30C3\u30C8\u30EB"], [13138, 1, "\u30EA\u30E9"], [13139, 1, "\u30EB\u30D4\u30FC"], [13140, 1, "\u30EB\u30FC\u30D6\u30EB"], [13141, 1, "\u30EC\u30E0"], [13142, 1, "\u30EC\u30F3\u30C8\u30B2\u30F3"], [13143, 1, "\u30EF\u30C3\u30C8"], [13144, 1, "0\u70B9"], [13145, 1, "1\u70B9"], [13146, 1, "2\u70B9"], [13147, 1, "3\u70B9"], [13148, 1, "4\u70B9"], [13149, 1, "5\u70B9"], [13150, 1, "6\u70B9"], [13151, 1, "7\u70B9"], [13152, 1, "8\u70B9"], [13153, 1, "9\u70B9"], [13154, 1, "10\u70B9"], [13155, 1, "11\u70B9"], [13156, 1, "12\u70B9"], [13157, 1, "13\u70B9"], [13158, 1, "14\u70B9"], [13159, 1, "15\u70B9"], [13160, 1, "16\u70B9"], [13161, 1, "17\u70B9"], [13162, 1, "18\u70B9"], [13163, 1, "19\u70B9"], [13164, 1, "20\u70B9"], [13165, 1, "21\u70B9"], [13166, 1, "22\u70B9"], [13167, 1, "23\u70B9"], [13168, 1, "24\u70B9"], [13169, 1, "hpa"], [13170, 1, "da"], [13171, 1, "au"], [13172, 1, "bar"], [13173, 1, "ov"], [13174, 1, "pc"], [13175, 1, "dm"], [13176, 1, "dm2"], [13177, 1, "dm3"], [13178, 1, "iu"], [13179, 1, "\u5E73\u6210"], [13180, 1, "\u662D\u548C"], [13181, 1, "\u5927\u6B63"], [13182, 1, "\u660E\u6CBB"], [13183, 1, "\u682A\u5F0F\u4F1A\u793E"], [13184, 1, "pa"], [13185, 1, "na"], [13186, 1, "\u03BCa"], [13187, 1, "ma"], [13188, 1, "ka"], [13189, 1, "kb"], [13190, 1, "mb"], [13191, 1, "gb"], [13192, 1, "cal"], [13193, 1, "kcal"], [13194, 1, "pf"], [13195, 1, "nf"], [13196, 1, "\u03BCf"], [13197, 1, "\u03BCg"], [13198, 1, "mg"], [13199, 1, "kg"], [13200, 1, "hz"], [13201, 1, "khz"], [13202, 1, "mhz"], [13203, 1, "ghz"], [13204, 1, "thz"], [13205, 1, "\u03BCl"], [13206, 1, "ml"], [13207, 1, "dl"], [13208, 1, "kl"], [13209, 1, "fm"], [13210, 1, "nm"], [13211, 1, "\u03BCm"], [13212, 1, "mm"], [13213, 1, "cm"], [13214, 1, "km"], [13215, 1, "mm2"], [13216, 1, "cm2"], [13217, 1, "m2"], [13218, 1, "km2"], [13219, 1, "mm3"], [13220, 1, "cm3"], [13221, 1, "m3"], [13222, 1, "km3"], [13223, 1, "m\u2215s"], [13224, 1, "m\u2215s2"], [13225, 1, "pa"], [13226, 1, "kpa"], [13227, 1, "mpa"], [13228, 1, "gpa"], [13229, 1, "rad"], [13230, 1, "rad\u2215s"], [13231, 1, "rad\u2215s2"], [13232, 1, "ps"], [13233, 1, "ns"], [13234, 1, "\u03BCs"], [13235, 1, "ms"], [13236, 1, "pv"], [13237, 1, "nv"], [13238, 1, "\u03BCv"], [13239, 1, "mv"], [13240, 1, "kv"], [13241, 1, "mv"], [13242, 1, "pw"], [13243, 1, "nw"], [13244, 1, "\u03BCw"], [13245, 1, "mw"], [13246, 1, "kw"], [13247, 1, "mw"], [13248, 1, "k\u03C9"], [13249, 1, "m\u03C9"], [13250, 3], [13251, 1, "bq"], [13252, 1, "cc"], [13253, 1, "cd"], [13254, 1, "c\u2215kg"], [13255, 3], [13256, 1, "db"], [13257, 1, "gy"], [13258, 1, "ha"], [13259, 1, "hp"], [13260, 1, "in"], [13261, 1, "kk"], [13262, 1, "km"], [13263, 1, "kt"], [13264, 1, "lm"], [13265, 1, "ln"], [13266, 1, "log"], [13267, 1, "lx"], [13268, 1, "mb"], [13269, 1, "mil"], [13270, 1, "mol"], [13271, 1, "ph"], [13272, 3], [13273, 1, "ppm"], [13274, 1, "pr"], [13275, 1, "sr"], [13276, 1, "sv"], [13277, 1, "wb"], [13278, 1, "v\u2215m"], [13279, 1, "a\u2215m"], [13280, 1, "1\u65E5"], [13281, 1, "2\u65E5"], [13282, 1, "3\u65E5"], [13283, 1, "4\u65E5"], [13284, 1, "5\u65E5"], [13285, 1, "6\u65E5"], [13286, 1, "7\u65E5"], [13287, 1, "8\u65E5"], [13288, 1, "9\u65E5"], [13289, 1, "10\u65E5"], [13290, 1, "11\u65E5"], [13291, 1, "12\u65E5"], [13292, 1, "13\u65E5"], [13293, 1, "14\u65E5"], [13294, 1, "15\u65E5"], [13295, 1, "16\u65E5"], [13296, 1, "17\u65E5"], [13297, 1, "18\u65E5"], [13298, 1, "19\u65E5"], [13299, 1, "20\u65E5"], [13300, 1, "21\u65E5"], [13301, 1, "22\u65E5"], [13302, 1, "23\u65E5"], [13303, 1, "24\u65E5"], [13304, 1, "25\u65E5"], [13305, 1, "26\u65E5"], [13306, 1, "27\u65E5"], [13307, 1, "28\u65E5"], [13308, 1, "29\u65E5"], [13309, 1, "30\u65E5"], [13310, 1, "31\u65E5"], [13311, 1, "gal"], [[13312, 19893], 2], [[19894, 19903], 2], [[19904, 19967], 2], [[19968, 40869], 2], [[40870, 40891], 2], [[40892, 40899], 2], [[40900, 40907], 2], [40908, 2], [[40909, 40917], 2], [[40918, 40938], 2], [[40939, 40943], 2], [[40944, 40956], 2], [[40957, 40959], 2], [[40960, 42124], 2], [[42125, 42127], 3], [[42128, 42145], 2], [[42146, 42147], 2], [[42148, 42163], 2], [42164, 2], [[42165, 42176], 2], [42177, 2], [[42178, 42180], 2], [42181, 2], [42182, 2], [[42183, 42191], 3], [[42192, 42237], 2], [[42238, 42239], 2], [[42240, 42508], 2], [[42509, 42511], 2], [[42512, 42539], 2], [[42540, 42559], 3], [42560, 1, "\uA641"], [42561, 2], [42562, 1, "\uA643"], [42563, 2], [42564, 1, "\uA645"], [42565, 2], [42566, 1, "\uA647"], [42567, 2], [42568, 1, "\uA649"], [42569, 2], [42570, 1, "\uA64B"], [42571, 2], [42572, 1, "\uA64D"], [42573, 2], [42574, 1, "\uA64F"], [42575, 2], [42576, 1, "\uA651"], [42577, 2], [42578, 1, "\uA653"], [42579, 2], [42580, 1, "\uA655"], [42581, 2], [42582, 1, "\uA657"], [42583, 2], [42584, 1, "\uA659"], [42585, 2], [42586, 1, "\uA65B"], [42587, 2], [42588, 1, "\uA65D"], [42589, 2], [42590, 1, "\uA65F"], [42591, 2], [42592, 1, "\uA661"], [42593, 2], [42594, 1, "\uA663"], [42595, 2], [42596, 1, "\uA665"], [42597, 2], [42598, 1, "\uA667"], [42599, 2], [42600, 1, "\uA669"], [42601, 2], [42602, 1, "\uA66B"], [42603, 2], [42604, 1, "\uA66D"], [[42605, 42607], 2], [[42608, 42611], 2], [[42612, 42619], 2], [[42620, 42621], 2], [42622, 2], [42623, 2], [42624, 1, "\uA681"], [42625, 2], [42626, 1, "\uA683"], [42627, 2], [42628, 1, "\uA685"], [42629, 2], [42630, 1, "\uA687"], [42631, 2], [42632, 1, "\uA689"], [42633, 2], [42634, 1, "\uA68B"], [42635, 2], [42636, 1, "\uA68D"], [42637, 2], [42638, 1, "\uA68F"], [42639, 2], [42640, 1, "\uA691"], [42641, 2], [42642, 1, "\uA693"], [42643, 2], [42644, 1, "\uA695"], [42645, 2], [42646, 1, "\uA697"], [42647, 2], [42648, 1, "\uA699"], [42649, 2], [42650, 1, "\uA69B"], [42651, 2], [42652, 1, "\u044A"], [42653, 1, "\u044C"], [42654, 2], [42655, 2], [[42656, 42725], 2], [[42726, 42735], 2], [[42736, 42737], 2], [[42738, 42743], 2], [[42744, 42751], 3], [[42752, 42774], 2], [[42775, 42778], 2], [[42779, 42783], 2], [[42784, 42785], 2], [42786, 1, "\uA723"], [42787, 2], [42788, 1, "\uA725"], [42789, 2], [42790, 1, "\uA727"], [42791, 2], [42792, 1, "\uA729"], [42793, 2], [42794, 1, "\uA72B"], [42795, 2], [42796, 1, "\uA72D"], [42797, 2], [42798, 1, "\uA72F"], [[42799, 42801], 2], [42802, 1, "\uA733"], [42803, 2], [42804, 1, "\uA735"], [42805, 2], [42806, 1, "\uA737"], [42807, 2], [42808, 1, "\uA739"], [42809, 2], [42810, 1, "\uA73B"], [42811, 2], [42812, 1, "\uA73D"], [42813, 2], [42814, 1, "\uA73F"], [42815, 2], [42816, 1, "\uA741"], [42817, 2], [42818, 1, "\uA743"], [42819, 2], [42820, 1, "\uA745"], [42821, 2], [42822, 1, "\uA747"], [42823, 2], [42824, 1, "\uA749"], [42825, 2], [42826, 1, "\uA74B"], [42827, 2], [42828, 1, "\uA74D"], [42829, 2], [42830, 1, "\uA74F"], [42831, 2], [42832, 1, "\uA751"], [42833, 2], [42834, 1, "\uA753"], [42835, 2], [42836, 1, "\uA755"], [42837, 2], [42838, 1, "\uA757"], [42839, 2], [42840, 1, "\uA759"], [42841, 2], [42842, 1, "\uA75B"], [42843, 2], [42844, 1, "\uA75D"], [42845, 2], [42846, 1, "\uA75F"], [42847, 2], [42848, 1, "\uA761"], [42849, 2], [42850, 1, "\uA763"], [42851, 2], [42852, 1, "\uA765"], [42853, 2], [42854, 1, "\uA767"], [42855, 2], [42856, 1, "\uA769"], [42857, 2], [42858, 1, "\uA76B"], [42859, 2], [42860, 1, "\uA76D"], [42861, 2], [42862, 1, "\uA76F"], [42863, 2], [42864, 1, "\uA76F"], [[42865, 42872], 2], [42873, 1, "\uA77A"], [42874, 2], [42875, 1, "\uA77C"], [42876, 2], [42877, 1, "\u1D79"], [42878, 1, "\uA77F"], [42879, 2], [42880, 1, "\uA781"], [42881, 2], [42882, 1, "\uA783"], [42883, 2], [42884, 1, "\uA785"], [42885, 2], [42886, 1, "\uA787"], [[42887, 42888], 2], [[42889, 42890], 2], [42891, 1, "\uA78C"], [42892, 2], [42893, 1, "\u0265"], [42894, 2], [42895, 2], [42896, 1, "\uA791"], [42897, 2], [42898, 1, "\uA793"], [42899, 2], [[42900, 42901], 2], [42902, 1, "\uA797"], [42903, 2], [42904, 1, "\uA799"], [42905, 2], [42906, 1, "\uA79B"], [42907, 2], [42908, 1, "\uA79D"], [42909, 2], [42910, 1, "\uA79F"], [42911, 2], [42912, 1, "\uA7A1"], [42913, 2], [42914, 1, "\uA7A3"], [42915, 2], [42916, 1, "\uA7A5"], [42917, 2], [42918, 1, "\uA7A7"], [42919, 2], [42920, 1, "\uA7A9"], [42921, 2], [42922, 1, "\u0266"], [42923, 1, "\u025C"], [42924, 1, "\u0261"], [42925, 1, "\u026C"], [42926, 1, "\u026A"], [42927, 2], [42928, 1, "\u029E"], [42929, 1, "\u0287"], [42930, 1, "\u029D"], [42931, 1, "\uAB53"], [42932, 1, "\uA7B5"], [42933, 2], [42934, 1, "\uA7B7"], [42935, 2], [42936, 1, "\uA7B9"], [42937, 2], [42938, 1, "\uA7BB"], [42939, 2], [42940, 1, "\uA7BD"], [42941, 2], [42942, 1, "\uA7BF"], [42943, 2], [42944, 1, "\uA7C1"], [42945, 2], [42946, 1, "\uA7C3"], [42947, 2], [42948, 1, "\uA794"], [42949, 1, "\u0282"], [42950, 1, "\u1D8E"], [42951, 1, "\uA7C8"], [42952, 2], [42953, 1, "\uA7CA"], [42954, 2], [[42955, 42959], 3], [42960, 1, "\uA7D1"], [42961, 2], [42962, 3], [42963, 2], [42964, 3], [42965, 2], [42966, 1, "\uA7D7"], [42967, 2], [42968, 1, "\uA7D9"], [42969, 2], [[42970, 42993], 3], [42994, 1, "c"], [42995, 1, "f"], [42996, 1, "q"], [42997, 1, "\uA7F6"], [42998, 2], [42999, 2], [43e3, 1, "\u0127"], [43001, 1, "\u0153"], [43002, 2], [[43003, 43007], 2], [[43008, 43047], 2], [[43048, 43051], 2], [43052, 2], [[43053, 43055], 3], [[43056, 43065], 2], [[43066, 43071], 3], [[43072, 43123], 2], [[43124, 43127], 2], [[43128, 43135], 3], [[43136, 43204], 2], [43205, 2], [[43206, 43213], 3], [[43214, 43215], 2], [[43216, 43225], 2], [[43226, 43231], 3], [[43232, 43255], 2], [[43256, 43258], 2], [43259, 2], [43260, 2], [43261, 2], [[43262, 43263], 2], [[43264, 43309], 2], [[43310, 43311], 2], [[43312, 43347], 2], [[43348, 43358], 3], [43359, 2], [[43360, 43388], 2], [[43389, 43391], 3], [[43392, 43456], 2], [[43457, 43469], 2], [43470, 3], [[43471, 43481], 2], [[43482, 43485], 3], [[43486, 43487], 2], [[43488, 43518], 2], [43519, 3], [[43520, 43574], 2], [[43575, 43583], 3], [[43584, 43597], 2], [[43598, 43599], 3], [[43600, 43609], 2], [[43610, 43611], 3], [[43612, 43615], 2], [[43616, 43638], 2], [[43639, 43641], 2], [[43642, 43643], 2], [[43644, 43647], 2], [[43648, 43714], 2], [[43715, 43738], 3], [[43739, 43741], 2], [[43742, 43743], 2], [[43744, 43759], 2], [[43760, 43761], 2], [[43762, 43766], 2], [[43767, 43776], 3], [[43777, 43782], 2], [[43783, 43784], 3], [[43785, 43790], 2], [[43791, 43792], 3], [[43793, 43798], 2], [[43799, 43807], 3], [[43808, 43814], 2], [43815, 3], [[43816, 43822], 2], [43823, 3], [[43824, 43866], 2], [43867, 2], [43868, 1, "\uA727"], [43869, 1, "\uAB37"], [43870, 1, "\u026B"], [43871, 1, "\uAB52"], [[43872, 43875], 2], [[43876, 43877], 2], [[43878, 43879], 2], [43880, 2], [43881, 1, "\u028D"], [[43882, 43883], 2], [[43884, 43887], 3], [43888, 1, "\u13A0"], [43889, 1, "\u13A1"], [43890, 1, "\u13A2"], [43891, 1, "\u13A3"], [43892, 1, "\u13A4"], [43893, 1, "\u13A5"], [43894, 1, "\u13A6"], [43895, 1, "\u13A7"], [43896, 1, "\u13A8"], [43897, 1, "\u13A9"], [43898, 1, "\u13AA"], [43899, 1, "\u13AB"], [43900, 1, "\u13AC"], [43901, 1, "\u13AD"], [43902, 1, "\u13AE"], [43903, 1, "\u13AF"], [43904, 1, "\u13B0"], [43905, 1, "\u13B1"], [43906, 1, "\u13B2"], [43907, 1, "\u13B3"], [43908, 1, "\u13B4"], [43909, 1, "\u13B5"], [43910, 1, "\u13B6"], [43911, 1, "\u13B7"], [43912, 1, "\u13B8"], [43913, 1, "\u13B9"], [43914, 1, "\u13BA"], [43915, 1, "\u13BB"], [43916, 1, "\u13BC"], [43917, 1, "\u13BD"], [43918, 1, "\u13BE"], [43919, 1, "\u13BF"], [43920, 1, "\u13C0"], [43921, 1, "\u13C1"], [43922, 1, "\u13C2"], [43923, 1, "\u13C3"], [43924, 1, "\u13C4"], [43925, 1, "\u13C5"], [43926, 1, "\u13C6"], [43927, 1, "\u13C7"], [43928, 1, "\u13C8"], [43929, 1, "\u13C9"], [43930, 1, "\u13CA"], [43931, 1, "\u13CB"], [43932, 1, "\u13CC"], [43933, 1, "\u13CD"], [43934, 1, "\u13CE"], [43935, 1, "\u13CF"], [43936, 1, "\u13D0"], [43937, 1, "\u13D1"], [43938, 1, "\u13D2"], [43939, 1, "\u13D3"], [43940, 1, "\u13D4"], [43941, 1, "\u13D5"], [43942, 1, "\u13D6"], [43943, 1, "\u13D7"], [43944, 1, "\u13D8"], [43945, 1, "\u13D9"], [43946, 1, "\u13DA"], [43947, 1, "\u13DB"], [43948, 1, "\u13DC"], [43949, 1, "\u13DD"], [43950, 1, "\u13DE"], [43951, 1, "\u13DF"], [43952, 1, "\u13E0"], [43953, 1, "\u13E1"], [43954, 1, "\u13E2"], [43955, 1, "\u13E3"], [43956, 1, "\u13E4"], [43957, 1, "\u13E5"], [43958, 1, "\u13E6"], [43959, 1, "\u13E7"], [43960, 1, "\u13E8"], [43961, 1, "\u13E9"], [43962, 1, "\u13EA"], [43963, 1, "\u13EB"], [43964, 1, "\u13EC"], [43965, 1, "\u13ED"], [43966, 1, "\u13EE"], [43967, 1, "\u13EF"], [[43968, 44010], 2], [44011, 2], [[44012, 44013], 2], [[44014, 44015], 3], [[44016, 44025], 2], [[44026, 44031], 3], [[44032, 55203], 2], [[55204, 55215], 3], [[55216, 55238], 2], [[55239, 55242], 3], [[55243, 55291], 2], [[55292, 55295], 3], [[55296, 57343], 3], [[57344, 63743], 3], [63744, 1, "\u8C48"], [63745, 1, "\u66F4"], [63746, 1, "\u8ECA"], [63747, 1, "\u8CC8"], [63748, 1, "\u6ED1"], [63749, 1, "\u4E32"], [63750, 1, "\u53E5"], [[63751, 63752], 1, "\u9F9C"], [63753, 1, "\u5951"], [63754, 1, "\u91D1"], [63755, 1, "\u5587"], [63756, 1, "\u5948"], [63757, 1, "\u61F6"], [63758, 1, "\u7669"], [63759, 1, "\u7F85"], [63760, 1, "\u863F"], [63761, 1, "\u87BA"], [63762, 1, "\u88F8"], [63763, 1, "\u908F"], [63764, 1, "\u6A02"], [63765, 1, "\u6D1B"], [63766, 1, "\u70D9"], [63767, 1, "\u73DE"], [63768, 1, "\u843D"], [63769, 1, "\u916A"], [63770, 1, "\u99F1"], [63771, 1, "\u4E82"], [63772, 1, "\u5375"], [63773, 1, "\u6B04"], [63774, 1, "\u721B"], [63775, 1, "\u862D"], [63776, 1, "\u9E1E"], [63777, 1, "\u5D50"], [63778, 1, "\u6FEB"], [63779, 1, "\u85CD"], [63780, 1, "\u8964"], [63781, 1, "\u62C9"], [63782, 1, "\u81D8"], [63783, 1, "\u881F"], [63784, 1, "\u5ECA"], [63785, 1, "\u6717"], [63786, 1, "\u6D6A"], [63787, 1, "\u72FC"], [63788, 1, "\u90CE"], [63789, 1, "\u4F86"], [63790, 1, "\u51B7"], [63791, 1, "\u52DE"], [63792, 1, "\u64C4"], [63793, 1, "\u6AD3"], [63794, 1, "\u7210"], [63795, 1, "\u76E7"], [63796, 1, "\u8001"], [63797, 1, "\u8606"], [63798, 1, "\u865C"], [63799, 1, "\u8DEF"], [63800, 1, "\u9732"], [63801, 1, "\u9B6F"], [63802, 1, "\u9DFA"], [63803, 1, "\u788C"], [63804, 1, "\u797F"], [63805, 1, "\u7DA0"], [63806, 1, "\u83C9"], [63807, 1, "\u9304"], [63808, 1, "\u9E7F"], [63809, 1, "\u8AD6"], [63810, 1, "\u58DF"], [63811, 1, "\u5F04"], [63812, 1, "\u7C60"], [63813, 1, "\u807E"], [63814, 1, "\u7262"], [63815, 1, "\u78CA"], [63816, 1, "\u8CC2"], [63817, 1, "\u96F7"], [63818, 1, "\u58D8"], [63819, 1, "\u5C62"], [63820, 1, "\u6A13"], [63821, 1, "\u6DDA"], [63822, 1, "\u6F0F"], [63823, 1, "\u7D2F"], [63824, 1, "\u7E37"], [63825, 1, "\u964B"], [63826, 1, "\u52D2"], [63827, 1, "\u808B"], [63828, 1, "\u51DC"], [63829, 1, "\u51CC"], [63830, 1, "\u7A1C"], [63831, 1, "\u7DBE"], [63832, 1, "\u83F1"], [63833, 1, "\u9675"], [63834, 1, "\u8B80"], [63835, 1, "\u62CF"], [63836, 1, "\u6A02"], [63837, 1, "\u8AFE"], [63838, 1, "\u4E39"], [63839, 1, "\u5BE7"], [63840, 1, "\u6012"], [63841, 1, "\u7387"], [63842, 1, "\u7570"], [63843, 1, "\u5317"], [63844, 1, "\u78FB"], [63845, 1, "\u4FBF"], [63846, 1, "\u5FA9"], [63847, 1, "\u4E0D"], [63848, 1, "\u6CCC"], [63849, 1, "\u6578"], [63850, 1, "\u7D22"], [63851, 1, "\u53C3"], [63852, 1, "\u585E"], [63853, 1, "\u7701"], [63854, 1, "\u8449"], [63855, 1, "\u8AAA"], [63856, 1, "\u6BBA"], [63857, 1, "\u8FB0"], [63858, 1, "\u6C88"], [63859, 1, "\u62FE"], [63860, 1, "\u82E5"], [63861, 1, "\u63A0"], [63862, 1, "\u7565"], [63863, 1, "\u4EAE"], [63864, 1, "\u5169"], [63865, 1, "\u51C9"], [63866, 1, "\u6881"], [63867, 1, "\u7CE7"], [63868, 1, "\u826F"], [63869, 1, "\u8AD2"], [63870, 1, "\u91CF"], [63871, 1, "\u52F5"], [63872, 1, "\u5442"], [63873, 1, "\u5973"], [63874, 1, "\u5EEC"], [63875, 1, "\u65C5"], [63876, 1, "\u6FFE"], [63877, 1, "\u792A"], [63878, 1, "\u95AD"], [63879, 1, "\u9A6A"], [63880, 1, "\u9E97"], [63881, 1, "\u9ECE"], [63882, 1, "\u529B"], [63883, 1, "\u66C6"], [63884, 1, "\u6B77"], [63885, 1, "\u8F62"], [63886, 1, "\u5E74"], [63887, 1, "\u6190"], [63888, 1, "\u6200"], [63889, 1, "\u649A"], [63890, 1, "\u6F23"], [63891, 1, "\u7149"], [63892, 1, "\u7489"], [63893, 1, "\u79CA"], [63894, 1, "\u7DF4"], [63895, 1, "\u806F"], [63896, 1, "\u8F26"], [63897, 1, "\u84EE"], [63898, 1, "\u9023"], [63899, 1, "\u934A"], [63900, 1, "\u5217"], [63901, 1, "\u52A3"], [63902, 1, "\u54BD"], [63903, 1, "\u70C8"], [63904, 1, "\u88C2"], [63905, 1, "\u8AAA"], [63906, 1, "\u5EC9"], [63907, 1, "\u5FF5"], [63908, 1, "\u637B"], [63909, 1, "\u6BAE"], [63910, 1, "\u7C3E"], [63911, 1, "\u7375"], [63912, 1, "\u4EE4"], [63913, 1, "\u56F9"], [63914, 1, "\u5BE7"], [63915, 1, "\u5DBA"], [63916, 1, "\u601C"], [63917, 1, "\u73B2"], [63918, 1, "\u7469"], [63919, 1, "\u7F9A"], [63920, 1, "\u8046"], [63921, 1, "\u9234"], [63922, 1, "\u96F6"], [63923, 1, "\u9748"], [63924, 1, "\u9818"], [63925, 1, "\u4F8B"], [63926, 1, "\u79AE"], [63927, 1, "\u91B4"], [63928, 1, "\u96B8"], [63929, 1, "\u60E1"], [63930, 1, "\u4E86"], [63931, 1, "\u50DA"], [63932, 1, "\u5BEE"], [63933, 1, "\u5C3F"], [63934, 1, "\u6599"], [63935, 1, "\u6A02"], [63936, 1, "\u71CE"], [63937, 1, "\u7642"], [63938, 1, "\u84FC"], [63939, 1, "\u907C"], [63940, 1, "\u9F8D"], [63941, 1, "\u6688"], [63942, 1, "\u962E"], [63943, 1, "\u5289"], [63944, 1, "\u677B"], [63945, 1, "\u67F3"], [63946, 1, "\u6D41"], [63947, 1, "\u6E9C"], [63948, 1, "\u7409"], [63949, 1, "\u7559"], [63950, 1, "\u786B"], [63951, 1, "\u7D10"], [63952, 1, "\u985E"], [63953, 1, "\u516D"], [63954, 1, "\u622E"], [63955, 1, "\u9678"], [63956, 1, "\u502B"], [63957, 1, "\u5D19"], [63958, 1, "\u6DEA"], [63959, 1, "\u8F2A"], [63960, 1, "\u5F8B"], [63961, 1, "\u6144"], [63962, 1, "\u6817"], [63963, 1, "\u7387"], [63964, 1, "\u9686"], [63965, 1, "\u5229"], [63966, 1, "\u540F"], [63967, 1, "\u5C65"], [63968, 1, "\u6613"], [63969, 1, "\u674E"], [63970, 1, "\u68A8"], [63971, 1, "\u6CE5"], [63972, 1, "\u7406"], [63973, 1, "\u75E2"], [63974, 1, "\u7F79"], [63975, 1, "\u88CF"], [63976, 1, "\u88E1"], [63977, 1, "\u91CC"], [63978, 1, "\u96E2"], [63979, 1, "\u533F"], [63980, 1, "\u6EBA"], [63981, 1, "\u541D"], [63982, 1, "\u71D0"], [63983, 1, "\u7498"], [63984, 1, "\u85FA"], [63985, 1, "\u96A3"], [63986, 1, "\u9C57"], [63987, 1, "\u9E9F"], [63988, 1, "\u6797"], [63989, 1, "\u6DCB"], [63990, 1, "\u81E8"], [63991, 1, "\u7ACB"], [63992, 1, "\u7B20"], [63993, 1, "\u7C92"], [63994, 1, "\u72C0"], [63995, 1, "\u7099"], [63996, 1, "\u8B58"], [63997, 1, "\u4EC0"], [63998, 1, "\u8336"], [63999, 1, "\u523A"], [64e3, 1, "\u5207"], [64001, 1, "\u5EA6"], [64002, 1, "\u62D3"], [64003, 1, "\u7CD6"], [64004, 1, "\u5B85"], [64005, 1, "\u6D1E"], [64006, 1, "\u66B4"], [64007, 1, "\u8F3B"], [64008, 1, "\u884C"], [64009, 1, "\u964D"], [64010, 1, "\u898B"], [64011, 1, "\u5ED3"], [64012, 1, "\u5140"], [64013, 1, "\u55C0"], [[64014, 64015], 2], [64016, 1, "\u585A"], [64017, 2], [64018, 1, "\u6674"], [[64019, 64020], 2], [64021, 1, "\u51DE"], [64022, 1, "\u732A"], [64023, 1, "\u76CA"], [64024, 1, "\u793C"], [64025, 1, "\u795E"], [64026, 1, "\u7965"], [64027, 1, "\u798F"], [64028, 1, "\u9756"], [64029, 1, "\u7CBE"], [64030, 1, "\u7FBD"], [64031, 2], [64032, 1, "\u8612"], [64033, 2], [64034, 1, "\u8AF8"], [[64035, 64036], 2], [64037, 1, "\u9038"], [64038, 1, "\u90FD"], [[64039, 64041], 2], [64042, 1, "\u98EF"], [64043, 1, "\u98FC"], [64044, 1, "\u9928"], [64045, 1, "\u9DB4"], [64046, 1, "\u90DE"], [64047, 1, "\u96B7"], [64048, 1, "\u4FAE"], [64049, 1, "\u50E7"], [64050, 1, "\u514D"], [64051, 1, "\u52C9"], [64052, 1, "\u52E4"], [64053, 1, "\u5351"], [64054, 1, "\u559D"], [64055, 1, "\u5606"], [64056, 1, "\u5668"], [64057, 1, "\u5840"], [64058, 1, "\u58A8"], [64059, 1, "\u5C64"], [64060, 1, "\u5C6E"], [64061, 1, "\u6094"], [64062, 1, "\u6168"], [64063, 1, "\u618E"], [64064, 1, "\u61F2"], [64065, 1, "\u654F"], [64066, 1, "\u65E2"], [64067, 1, "\u6691"], [64068, 1, "\u6885"], [64069, 1, "\u6D77"], [64070, 1, "\u6E1A"], [64071, 1, "\u6F22"], [64072, 1, "\u716E"], [64073, 1, "\u722B"], [64074, 1, "\u7422"], [64075, 1, "\u7891"], [64076, 1, "\u793E"], [64077, 1, "\u7949"], [64078, 1, "\u7948"], [64079, 1, "\u7950"], [64080, 1, "\u7956"], [64081, 1, "\u795D"], [64082, 1, "\u798D"], [64083, 1, "\u798E"], [64084, 1, "\u7A40"], [64085, 1, "\u7A81"], [64086, 1, "\u7BC0"], [64087, 1, "\u7DF4"], [64088, 1, "\u7E09"], [64089, 1, "\u7E41"], [64090, 1, "\u7F72"], [64091, 1, "\u8005"], [64092, 1, "\u81ED"], [[64093, 64094], 1, "\u8279"], [64095, 1, "\u8457"], [64096, 1, "\u8910"], [64097, 1, "\u8996"], [64098, 1, "\u8B01"], [64099, 1, "\u8B39"], [64100, 1, "\u8CD3"], [64101, 1, "\u8D08"], [64102, 1, "\u8FB6"], [64103, 1, "\u9038"], [64104, 1, "\u96E3"], [64105, 1, "\u97FF"], [64106, 1, "\u983B"], [64107, 1, "\u6075"], [64108, 1, "\u{242EE}"], [64109, 1, "\u8218"], [[64110, 64111], 3], [64112, 1, "\u4E26"], [64113, 1, "\u51B5"], [64114, 1, "\u5168"], [64115, 1, "\u4F80"], [64116, 1, "\u5145"], [64117, 1, "\u5180"], [64118, 1, "\u52C7"], [64119, 1, "\u52FA"], [64120, 1, "\u559D"], [64121, 1, "\u5555"], [64122, 1, "\u5599"], [64123, 1, "\u55E2"], [64124, 1, "\u585A"], [64125, 1, "\u58B3"], [64126, 1, "\u5944"], [64127, 1, "\u5954"], [64128, 1, "\u5A62"], [64129, 1, "\u5B28"], [64130, 1, "\u5ED2"], [64131, 1, "\u5ED9"], [64132, 1, "\u5F69"], [64133, 1, "\u5FAD"], [64134, 1, "\u60D8"], [64135, 1, "\u614E"], [64136, 1, "\u6108"], [64137, 1, "\u618E"], [64138, 1, "\u6160"], [64139, 1, "\u61F2"], [64140, 1, "\u6234"], [64141, 1, "\u63C4"], [64142, 1, "\u641C"], [64143, 1, "\u6452"], [64144, 1, "\u6556"], [64145, 1, "\u6674"], [64146, 1, "\u6717"], [64147, 1, "\u671B"], [64148, 1, "\u6756"], [64149, 1, "\u6B79"], [64150, 1, "\u6BBA"], [64151, 1, "\u6D41"], [64152, 1, "\u6EDB"], [64153, 1, "\u6ECB"], [64154, 1, "\u6F22"], [64155, 1, "\u701E"], [64156, 1, "\u716E"], [64157, 1, "\u77A7"], [64158, 1, "\u7235"], [64159, 1, "\u72AF"], [64160, 1, "\u732A"], [64161, 1, "\u7471"], [64162, 1, "\u7506"], [64163, 1, "\u753B"], [64164, 1, "\u761D"], [64165, 1, "\u761F"], [64166, 1, "\u76CA"], [64167, 1, "\u76DB"], [64168, 1, "\u76F4"], [64169, 1, "\u774A"], [64170, 1, "\u7740"], [64171, 1, "\u78CC"], [64172, 1, "\u7AB1"], [64173, 1, "\u7BC0"], [64174, 1, "\u7C7B"], [64175, 1, "\u7D5B"], [64176, 1, "\u7DF4"], [64177, 1, "\u7F3E"], [64178, 1, "\u8005"], [64179, 1, "\u8352"], [64180, 1, "\u83EF"], [64181, 1, "\u8779"], [64182, 1, "\u8941"], [64183, 1, "\u8986"], [64184, 1, "\u8996"], [64185, 1, "\u8ABF"], [64186, 1, "\u8AF8"], [64187, 1, "\u8ACB"], [64188, 1, "\u8B01"], [64189, 1, "\u8AFE"], [64190, 1, "\u8AED"], [64191, 1, "\u8B39"], [64192, 1, "\u8B8A"], [64193, 1, "\u8D08"], [64194, 1, "\u8F38"], [64195, 1, "\u9072"], [64196, 1, "\u9199"], [64197, 1, "\u9276"], [64198, 1, "\u967C"], [64199, 1, "\u96E3"], [64200, 1, "\u9756"], [64201, 1, "\u97DB"], [64202, 1, "\u97FF"], [64203, 1, "\u980B"], [64204, 1, "\u983B"], [64205, 1, "\u9B12"], [64206, 1, "\u9F9C"], [64207, 1, "\u{2284A}"], [64208, 1, "\u{22844}"], [64209, 1, "\u{233D5}"], [64210, 1, "\u3B9D"], [64211, 1, "\u4018"], [64212, 1, "\u4039"], [64213, 1, "\u{25249}"], [64214, 1, "\u{25CD0}"], [64215, 1, "\u{27ED3}"], [64216, 1, "\u9F43"], [64217, 1, "\u9F8E"], [[64218, 64255], 3], [64256, 1, "ff"], [64257, 1, "fi"], [64258, 1, "fl"], [64259, 1, "ffi"], [64260, 1, "ffl"], [[64261, 64262], 1, "st"], [[64263, 64274], 3], [64275, 1, "\u0574\u0576"], [64276, 1, "\u0574\u0565"], [64277, 1, "\u0574\u056B"], [64278, 1, "\u057E\u0576"], [64279, 1, "\u0574\u056D"], [[64280, 64284], 3], [64285, 1, "\u05D9\u05B4"], [64286, 2], [64287, 1, "\u05F2\u05B7"], [64288, 1, "\u05E2"], [64289, 1, "\u05D0"], [64290, 1, "\u05D3"], [64291, 1, "\u05D4"], [64292, 1, "\u05DB"], [64293, 1, "\u05DC"], [64294, 1, "\u05DD"], [64295, 1, "\u05E8"], [64296, 1, "\u05EA"], [64297, 5, "+"], [64298, 1, "\u05E9\u05C1"], [64299, 1, "\u05E9\u05C2"], [64300, 1, "\u05E9\u05BC\u05C1"], [64301, 1, "\u05E9\u05BC\u05C2"], [64302, 1, "\u05D0\u05B7"], [64303, 1, "\u05D0\u05B8"], [64304, 1, "\u05D0\u05BC"], [64305, 1, "\u05D1\u05BC"], [64306, 1, "\u05D2\u05BC"], [64307, 1, "\u05D3\u05BC"], [64308, 1, "\u05D4\u05BC"], [64309, 1, "\u05D5\u05BC"], [64310, 1, "\u05D6\u05BC"], [64311, 3], [64312, 1, "\u05D8\u05BC"], [64313, 1, "\u05D9\u05BC"], [64314, 1, "\u05DA\u05BC"], [64315, 1, "\u05DB\u05BC"], [64316, 1, "\u05DC\u05BC"], [64317, 3], [64318, 1, "\u05DE\u05BC"], [64319, 3], [64320, 1, "\u05E0\u05BC"], [64321, 1, "\u05E1\u05BC"], [64322, 3], [64323, 1, "\u05E3\u05BC"], [64324, 1, "\u05E4\u05BC"], [64325, 3], [64326, 1, "\u05E6\u05BC"], [64327, 1, "\u05E7\u05BC"], [64328, 1, "\u05E8\u05BC"], [64329, 1, "\u05E9\u05BC"], [64330, 1, "\u05EA\u05BC"], [64331, 1, "\u05D5\u05B9"], [64332, 1, "\u05D1\u05BF"], [64333, 1, "\u05DB\u05BF"], [64334, 1, "\u05E4\u05BF"], [64335, 1, "\u05D0\u05DC"], [[64336, 64337], 1, "\u0671"], [[64338, 64341], 1, "\u067B"], [[64342, 64345], 1, "\u067E"], [[64346, 64349], 1, "\u0680"], [[64350, 64353], 1, "\u067A"], [[64354, 64357], 1, "\u067F"], [[64358, 64361], 1, "\u0679"], [[64362, 64365], 1, "\u06A4"], [[64366, 64369], 1, "\u06A6"], [[64370, 64373], 1, "\u0684"], [[64374, 64377], 1, "\u0683"], [[64378, 64381], 1, "\u0686"], [[64382, 64385], 1, "\u0687"], [[64386, 64387], 1, "\u068D"], [[64388, 64389], 1, "\u068C"], [[64390, 64391], 1, "\u068E"], [[64392, 64393], 1, "\u0688"], [[64394, 64395], 1, "\u0698"], [[64396, 64397], 1, "\u0691"], [[64398, 64401], 1, "\u06A9"], [[64402, 64405], 1, "\u06AF"], [[64406, 64409], 1, "\u06B3"], [[64410, 64413], 1, "\u06B1"], [[64414, 64415], 1, "\u06BA"], [[64416, 64419], 1, "\u06BB"], [[64420, 64421], 1, "\u06C0"], [[64422, 64425], 1, "\u06C1"], [[64426, 64429], 1, "\u06BE"], [[64430, 64431], 1, "\u06D2"], [[64432, 64433], 1, "\u06D3"], [[64434, 64449], 2], [64450, 2], [[64451, 64466], 3], [[64467, 64470], 1, "\u06AD"], [[64471, 64472], 1, "\u06C7"], [[64473, 64474], 1, "\u06C6"], [[64475, 64476], 1, "\u06C8"], [64477, 1, "\u06C7\u0674"], [[64478, 64479], 1, "\u06CB"], [[64480, 64481], 1, "\u06C5"], [[64482, 64483], 1, "\u06C9"], [[64484, 64487], 1, "\u06D0"], [[64488, 64489], 1, "\u0649"], [[64490, 64491], 1, "\u0626\u0627"], [[64492, 64493], 1, "\u0626\u06D5"], [[64494, 64495], 1, "\u0626\u0648"], [[64496, 64497], 1, "\u0626\u06C7"], [[64498, 64499], 1, "\u0626\u06C6"], [[64500, 64501], 1, "\u0626\u06C8"], [[64502, 64504], 1, "\u0626\u06D0"], [[64505, 64507], 1, "\u0626\u0649"], [[64508, 64511], 1, "\u06CC"], [64512, 1, "\u0626\u062C"], [64513, 1, "\u0626\u062D"], [64514, 1, "\u0626\u0645"], [64515, 1, "\u0626\u0649"], [64516, 1, "\u0626\u064A"], [64517, 1, "\u0628\u062C"], [64518, 1, "\u0628\u062D"], [64519, 1, "\u0628\u062E"], [64520, 1, "\u0628\u0645"], [64521, 1, "\u0628\u0649"], [64522, 1, "\u0628\u064A"], [64523, 1, "\u062A\u062C"], [64524, 1, "\u062A\u062D"], [64525, 1, "\u062A\u062E"], [64526, 1, "\u062A\u0645"], [64527, 1, "\u062A\u0649"], [64528, 1, "\u062A\u064A"], [64529, 1, "\u062B\u062C"], [64530, 1, "\u062B\u0645"], [64531, 1, "\u062B\u0649"], [64532, 1, "\u062B\u064A"], [64533, 1, "\u062C\u062D"], [64534, 1, "\u062C\u0645"], [64535, 1, "\u062D\u062C"], [64536, 1, "\u062D\u0645"], [64537, 1, "\u062E\u062C"], [64538, 1, "\u062E\u062D"], [64539, 1, "\u062E\u0645"], [64540, 1, "\u0633\u062C"], [64541, 1, "\u0633\u062D"], [64542, 1, "\u0633\u062E"], [64543, 1, "\u0633\u0645"], [64544, 1, "\u0635\u062D"], [64545, 1, "\u0635\u0645"], [64546, 1, "\u0636\u062C"], [64547, 1, "\u0636\u062D"], [64548, 1, "\u0636\u062E"], [64549, 1, "\u0636\u0645"], [64550, 1, "\u0637\u062D"], [64551, 1, "\u0637\u0645"], [64552, 1, "\u0638\u0645"], [64553, 1, "\u0639\u062C"], [64554, 1, "\u0639\u0645"], [64555, 1, "\u063A\u062C"], [64556, 1, "\u063A\u0645"], [64557, 1, "\u0641\u062C"], [64558, 1, "\u0641\u062D"], [64559, 1, "\u0641\u062E"], [64560, 1, "\u0641\u0645"], [64561, 1, "\u0641\u0649"], [64562, 1, "\u0641\u064A"], [64563, 1, "\u0642\u062D"], [64564, 1, "\u0642\u0645"], [64565, 1, "\u0642\u0649"], [64566, 1, "\u0642\u064A"], [64567, 1, "\u0643\u0627"], [64568, 1, "\u0643\u062C"], [64569, 1, "\u0643\u062D"], [64570, 1, "\u0643\u062E"], [64571, 1, "\u0643\u0644"], [64572, 1, "\u0643\u0645"], [64573, 1, "\u0643\u0649"], [64574, 1, "\u0643\u064A"], [64575, 1, "\u0644\u062C"], [64576, 1, "\u0644\u062D"], [64577, 1, "\u0644\u062E"], [64578, 1, "\u0644\u0645"], [64579, 1, "\u0644\u0649"], [64580, 1, "\u0644\u064A"], [64581, 1, "\u0645\u062C"], [64582, 1, "\u0645\u062D"], [64583, 1, "\u0645\u062E"], [64584, 1, "\u0645\u0645"], [64585, 1, "\u0645\u0649"], [64586, 1, "\u0645\u064A"], [64587, 1, "\u0646\u062C"], [64588, 1, "\u0646\u062D"], [64589, 1, "\u0646\u062E"], [64590, 1, "\u0646\u0645"], [64591, 1, "\u0646\u0649"], [64592, 1, "\u0646\u064A"], [64593, 1, "\u0647\u062C"], [64594, 1, "\u0647\u0645"], [64595, 1, "\u0647\u0649"], [64596, 1, "\u0647\u064A"], [64597, 1, "\u064A\u062C"], [64598, 1, "\u064A\u062D"], [64599, 1, "\u064A\u062E"], [64600, 1, "\u064A\u0645"], [64601, 1, "\u064A\u0649"], [64602, 1, "\u064A\u064A"], [64603, 1, "\u0630\u0670"], [64604, 1, "\u0631\u0670"], [64605, 1, "\u0649\u0670"], [64606, 5, " \u064C\u0651"], [64607, 5, " \u064D\u0651"], [64608, 5, " \u064E\u0651"], [64609, 5, " \u064F\u0651"], [64610, 5, " \u0650\u0651"], [64611, 5, " \u0651\u0670"], [64612, 1, "\u0626\u0631"], [64613, 1, "\u0626\u0632"], [64614, 1, "\u0626\u0645"], [64615, 1, "\u0626\u0646"], [64616, 1, "\u0626\u0649"], [64617, 1, "\u0626\u064A"], [64618, 1, "\u0628\u0631"], [64619, 1, "\u0628\u0632"], [64620, 1, "\u0628\u0645"], [64621, 1, "\u0628\u0646"], [64622, 1, "\u0628\u0649"], [64623, 1, "\u0628\u064A"], [64624, 1, "\u062A\u0631"], [64625, 1, "\u062A\u0632"], [64626, 1, "\u062A\u0645"], [64627, 1, "\u062A\u0646"], [64628, 1, "\u062A\u0649"], [64629, 1, "\u062A\u064A"], [64630, 1, "\u062B\u0631"], [64631, 1, "\u062B\u0632"], [64632, 1, "\u062B\u0645"], [64633, 1, "\u062B\u0646"], [64634, 1, "\u062B\u0649"], [64635, 1, "\u062B\u064A"], [64636, 1, "\u0641\u0649"], [64637, 1, "\u0641\u064A"], [64638, 1, "\u0642\u0649"], [64639, 1, "\u0642\u064A"], [64640, 1, "\u0643\u0627"], [64641, 1, "\u0643\u0644"], [64642, 1, "\u0643\u0645"], [64643, 1, "\u0643\u0649"], [64644, 1, "\u0643\u064A"], [64645, 1, "\u0644\u0645"], [64646, 1, "\u0644\u0649"], [64647, 1, "\u0644\u064A"], [64648, 1, "\u0645\u0627"], [64649, 1, "\u0645\u0645"], [64650, 1, "\u0646\u0631"], [64651, 1, "\u0646\u0632"], [64652, 1, "\u0646\u0645"], [64653, 1, "\u0646\u0646"], [64654, 1, "\u0646\u0649"], [64655, 1, "\u0646\u064A"], [64656, 1, "\u0649\u0670"], [64657, 1, "\u064A\u0631"], [64658, 1, "\u064A\u0632"], [64659, 1, "\u064A\u0645"], [64660, 1, "\u064A\u0646"], [64661, 1, "\u064A\u0649"], [64662, 1, "\u064A\u064A"], [64663, 1, "\u0626\u062C"], [64664, 1, "\u0626\u062D"], [64665, 1, "\u0626\u062E"], [64666, 1, "\u0626\u0645"], [64667, 1, "\u0626\u0647"], [64668, 1, "\u0628\u062C"], [64669, 1, "\u0628\u062D"], [64670, 1, "\u0628\u062E"], [64671, 1, "\u0628\u0645"], [64672, 1, "\u0628\u0647"], [64673, 1, "\u062A\u062C"], [64674, 1, "\u062A\u062D"], [64675, 1, "\u062A\u062E"], [64676, 1, "\u062A\u0645"], [64677, 1, "\u062A\u0647"], [64678, 1, "\u062B\u0645"], [64679, 1, "\u062C\u062D"], [64680, 1, "\u062C\u0645"], [64681, 1, "\u062D\u062C"], [64682, 1, "\u062D\u0645"], [64683, 1, "\u062E\u062C"], [64684, 1, "\u062E\u0645"], [64685, 1, "\u0633\u062C"], [64686, 1, "\u0633\u062D"], [64687, 1, "\u0633\u062E"], [64688, 1, "\u0633\u0645"], [64689, 1, "\u0635\u062D"], [64690, 1, "\u0635\u062E"], [64691, 1, "\u0635\u0645"], [64692, 1, "\u0636\u062C"], [64693, 1, "\u0636\u062D"], [64694, 1, "\u0636\u062E"], [64695, 1, "\u0636\u0645"], [64696, 1, "\u0637\u062D"], [64697, 1, "\u0638\u0645"], [64698, 1, "\u0639\u062C"], [64699, 1, "\u0639\u0645"], [64700, 1, "\u063A\u062C"], [64701, 1, "\u063A\u0645"], [64702, 1, "\u0641\u062C"], [64703, 1, "\u0641\u062D"], [64704, 1, "\u0641\u062E"], [64705, 1, "\u0641\u0645"], [64706, 1, "\u0642\u062D"], [64707, 1, "\u0642\u0645"], [64708, 1, "\u0643\u062C"], [64709, 1, "\u0643\u062D"], [64710, 1, "\u0643\u062E"], [64711, 1, "\u0643\u0644"], [64712, 1, "\u0643\u0645"], [64713, 1, "\u0644\u062C"], [64714, 1, "\u0644\u062D"], [64715, 1, "\u0644\u062E"], [64716, 1, "\u0644\u0645"], [64717, 1, "\u0644\u0647"], [64718, 1, "\u0645\u062C"], [64719, 1, "\u0645\u062D"], [64720, 1, "\u0645\u062E"], [64721, 1, "\u0645\u0645"], [64722, 1, "\u0646\u062C"], [64723, 1, "\u0646\u062D"], [64724, 1, "\u0646\u062E"], [64725, 1, "\u0646\u0645"], [64726, 1, "\u0646\u0647"], [64727, 1, "\u0647\u062C"], [64728, 1, "\u0647\u0645"], [64729, 1, "\u0647\u0670"], [64730, 1, "\u064A\u062C"], [64731, 1, "\u064A\u062D"], [64732, 1, "\u064A\u062E"], [64733, 1, "\u064A\u0645"], [64734, 1, "\u064A\u0647"], [64735, 1, "\u0626\u0645"], [64736, 1, "\u0626\u0647"], [64737, 1, "\u0628\u0645"], [64738, 1, "\u0628\u0647"], [64739, 1, "\u062A\u0645"], [64740, 1, "\u062A\u0647"], [64741, 1, "\u062B\u0645"], [64742, 1, "\u062B\u0647"], [64743, 1, "\u0633\u0645"], [64744, 1, "\u0633\u0647"], [64745, 1, "\u0634\u0645"], [64746, 1, "\u0634\u0647"], [64747, 1, "\u0643\u0644"], [64748, 1, "\u0643\u0645"], [64749, 1, "\u0644\u0645"], [64750, 1, "\u0646\u0645"], [64751, 1, "\u0646\u0647"], [64752, 1, "\u064A\u0645"], [64753, 1, "\u064A\u0647"], [64754, 1, "\u0640\u064E\u0651"], [64755, 1, "\u0640\u064F\u0651"], [64756, 1, "\u0640\u0650\u0651"], [64757, 1, "\u0637\u0649"], [64758, 1, "\u0637\u064A"], [64759, 1, "\u0639\u0649"], [64760, 1, "\u0639\u064A"], [64761, 1, "\u063A\u0649"], [64762, 1, "\u063A\u064A"], [64763, 1, "\u0633\u0649"], [64764, 1, "\u0633\u064A"], [64765, 1, "\u0634\u0649"], [64766, 1, "\u0634\u064A"], [64767, 1, "\u062D\u0649"], [64768, 1, "\u062D\u064A"], [64769, 1, "\u062C\u0649"], [64770, 1, "\u062C\u064A"], [64771, 1, "\u062E\u0649"], [64772, 1, "\u062E\u064A"], [64773, 1, "\u0635\u0649"], [64774, 1, "\u0635\u064A"], [64775, 1, "\u0636\u0649"], [64776, 1, "\u0636\u064A"], [64777, 1, "\u0634\u062C"], [64778, 1, "\u0634\u062D"], [64779, 1, "\u0634\u062E"], [64780, 1, "\u0634\u0645"], [64781, 1, "\u0634\u0631"], [64782, 1, "\u0633\u0631"], [64783, 1, "\u0635\u0631"], [64784, 1, "\u0636\u0631"], [64785, 1, "\u0637\u0649"], [64786, 1, "\u0637\u064A"], [64787, 1, "\u0639\u0649"], [64788, 1, "\u0639\u064A"], [64789, 1, "\u063A\u0649"], [64790, 1, "\u063A\u064A"], [64791, 1, "\u0633\u0649"], [64792, 1, "\u0633\u064A"], [64793, 1, "\u0634\u0649"], [64794, 1, "\u0634\u064A"], [64795, 1, "\u062D\u0649"], [64796, 1, "\u062D\u064A"], [64797, 1, "\u062C\u0649"], [64798, 1, "\u062C\u064A"], [64799, 1, "\u062E\u0649"], [64800, 1, "\u062E\u064A"], [64801, 1, "\u0635\u0649"], [64802, 1, "\u0635\u064A"], [64803, 1, "\u0636\u0649"], [64804, 1, "\u0636\u064A"], [64805, 1, "\u0634\u062C"], [64806, 1, "\u0634\u062D"], [64807, 1, "\u0634\u062E"], [64808, 1, "\u0634\u0645"], [64809, 1, "\u0634\u0631"], [64810, 1, "\u0633\u0631"], [64811, 1, "\u0635\u0631"], [64812, 1, "\u0636\u0631"], [64813, 1, "\u0634\u062C"], [64814, 1, "\u0634\u062D"], [64815, 1, "\u0634\u062E"], [64816, 1, "\u0634\u0645"], [64817, 1, "\u0633\u0647"], [64818, 1, "\u0634\u0647"], [64819, 1, "\u0637\u0645"], [64820, 1, "\u0633\u062C"], [64821, 1, "\u0633\u062D"], [64822, 1, "\u0633\u062E"], [64823, 1, "\u0634\u062C"], [64824, 1, "\u0634\u062D"], [64825, 1, "\u0634\u062E"], [64826, 1, "\u0637\u0645"], [64827, 1, "\u0638\u0645"], [[64828, 64829], 1, "\u0627\u064B"], [[64830, 64831], 2], [[64832, 64847], 2], [64848, 1, "\u062A\u062C\u0645"], [[64849, 64850], 1, "\u062A\u062D\u062C"], [64851, 1, "\u062A\u062D\u0645"], [64852, 1, "\u062A\u062E\u0645"], [64853, 1, "\u062A\u0645\u062C"], [64854, 1, "\u062A\u0645\u062D"], [64855, 1, "\u062A\u0645\u062E"], [[64856, 64857], 1, "\u062C\u0645\u062D"], [64858, 1, "\u062D\u0645\u064A"], [64859, 1, "\u062D\u0645\u0649"], [64860, 1, "\u0633\u062D\u062C"], [64861, 1, "\u0633\u062C\u062D"], [64862, 1, "\u0633\u062C\u0649"], [[64863, 64864], 1, "\u0633\u0645\u062D"], [64865, 1, "\u0633\u0645\u062C"], [[64866, 64867], 1, "\u0633\u0645\u0645"], [[64868, 64869], 1, "\u0635\u062D\u062D"], [64870, 1, "\u0635\u0645\u0645"], [[64871, 64872], 1, "\u0634\u062D\u0645"], [64873, 1, "\u0634\u062C\u064A"], [[64874, 64875], 1, "\u0634\u0645\u062E"], [[64876, 64877], 1, "\u0634\u0645\u0645"], [64878, 1, "\u0636\u062D\u0649"], [[64879, 64880], 1, "\u0636\u062E\u0645"], [[64881, 64882], 1, "\u0637\u0645\u062D"], [64883, 1, "\u0637\u0645\u0645"], [64884, 1, "\u0637\u0645\u064A"], [64885, 1, "\u0639\u062C\u0645"], [[64886, 64887], 1, "\u0639\u0645\u0645"], [64888, 1, "\u0639\u0645\u0649"], [64889, 1, "\u063A\u0645\u0645"], [64890, 1, "\u063A\u0645\u064A"], [64891, 1, "\u063A\u0645\u0649"], [[64892, 64893], 1, "\u0641\u062E\u0645"], [64894, 1, "\u0642\u0645\u062D"], [64895, 1, "\u0642\u0645\u0645"], [64896, 1, "\u0644\u062D\u0645"], [64897, 1, "\u0644\u062D\u064A"], [64898, 1, "\u0644\u062D\u0649"], [[64899, 64900], 1, "\u0644\u062C\u062C"], [[64901, 64902], 1, "\u0644\u062E\u0645"], [[64903, 64904], 1, "\u0644\u0645\u062D"], [64905, 1, "\u0645\u062D\u062C"], [64906, 1, "\u0645\u062D\u0645"], [64907, 1, "\u0645\u062D\u064A"], [64908, 1, "\u0645\u062C\u062D"], [64909, 1, "\u0645\u062C\u0645"], [64910, 1, "\u0645\u062E\u062C"], [64911, 1, "\u0645\u062E\u0645"], [[64912, 64913], 3], [64914, 1, "\u0645\u062C\u062E"], [64915, 1, "\u0647\u0645\u062C"], [64916, 1, "\u0647\u0645\u0645"], [64917, 1, "\u0646\u062D\u0645"], [64918, 1, "\u0646\u062D\u0649"], [[64919, 64920], 1, "\u0646\u062C\u0645"], [64921, 1, "\u0646\u062C\u0649"], [64922, 1, "\u0646\u0645\u064A"], [64923, 1, "\u0646\u0645\u0649"], [[64924, 64925], 1, "\u064A\u0645\u0645"], [64926, 1, "\u0628\u062E\u064A"], [64927, 1, "\u062A\u062C\u064A"], [64928, 1, "\u062A\u062C\u0649"], [64929, 1, "\u062A\u062E\u064A"], [64930, 1, "\u062A\u062E\u0649"], [64931, 1, "\u062A\u0645\u064A"], [64932, 1, "\u062A\u0645\u0649"], [64933, 1, "\u062C\u0645\u064A"], [64934, 1, "\u062C\u062D\u0649"], [64935, 1, "\u062C\u0645\u0649"], [64936, 1, "\u0633\u062E\u0649"], [64937, 1, "\u0635\u062D\u064A"], [64938, 1, "\u0634\u062D\u064A"], [64939, 1, "\u0636\u062D\u064A"], [64940, 1, "\u0644\u062C\u064A"], [64941, 1, "\u0644\u0645\u064A"], [64942, 1, "\u064A\u062D\u064A"], [64943, 1, "\u064A\u062C\u064A"], [64944, 1, "\u064A\u0645\u064A"], [64945, 1, "\u0645\u0645\u064A"], [64946, 1, "\u0642\u0645\u064A"], [64947, 1, "\u0646\u062D\u064A"], [64948, 1, "\u0642\u0645\u062D"], [64949, 1, "\u0644\u062D\u0645"], [64950, 1, "\u0639\u0645\u064A"], [64951, 1, "\u0643\u0645\u064A"], [64952, 1, "\u0646\u062C\u062D"], [64953, 1, "\u0645\u062E\u064A"], [64954, 1, "\u0644\u062C\u0645"], [64955, 1, "\u0643\u0645\u0645"], [64956, 1, "\u0644\u062C\u0645"], [64957, 1, "\u0646\u062C\u062D"], [64958, 1, "\u062C\u062D\u064A"], [64959, 1, "\u062D\u062C\u064A"], [64960, 1, "\u0645\u062C\u064A"], [64961, 1, "\u0641\u0645\u064A"], [64962, 1, "\u0628\u062D\u064A"], [64963, 1, "\u0643\u0645\u0645"], [64964, 1, "\u0639\u062C\u0645"], [64965, 1, "\u0635\u0645\u0645"], [64966, 1, "\u0633\u062E\u064A"], [64967, 1, "\u0646\u062C\u064A"], [[64968, 64974], 3], [64975, 2], [[64976, 65007], 3], [65008, 1, "\u0635\u0644\u06D2"], [65009, 1, "\u0642\u0644\u06D2"], [65010, 1, "\u0627\u0644\u0644\u0647"], [65011, 1, "\u0627\u0643\u0628\u0631"], [65012, 1, "\u0645\u062D\u0645\u062F"], [65013, 1, "\u0635\u0644\u0639\u0645"], [65014, 1, "\u0631\u0633\u0648\u0644"], [65015, 1, "\u0639\u0644\u064A\u0647"], [65016, 1, "\u0648\u0633\u0644\u0645"], [65017, 1, "\u0635\u0644\u0649"], [65018, 5, "\u0635\u0644\u0649 \u0627\u0644\u0644\u0647 \u0639\u0644\u064A\u0647 \u0648\u0633\u0644\u0645"], [65019, 5, "\u062C\u0644 \u062C\u0644\u0627\u0644\u0647"], [65020, 1, "\u0631\u06CC\u0627\u0644"], [65021, 2], [[65022, 65023], 2], [[65024, 65039], 7], [65040, 5, ","], [65041, 1, "\u3001"], [65042, 3], [65043, 5, ":"], [65044, 5, ";"], [65045, 5, "!"], [65046, 5, "?"], [65047, 1, "\u3016"], [65048, 1, "\u3017"], [65049, 3], [[65050, 65055], 3], [[65056, 65059], 2], [[65060, 65062], 2], [[65063, 65069], 2], [[65070, 65071], 2], [65072, 3], [65073, 1, "\u2014"], [65074, 1, "\u2013"], [[65075, 65076], 5, "_"], [65077, 5, "("], [65078, 5, ")"], [65079, 5, "{"], [65080, 5, "}"], [65081, 1, "\u3014"], [65082, 1, "\u3015"], [65083, 1, "\u3010"], [65084, 1, "\u3011"], [65085, 1, "\u300A"], [65086, 1, "\u300B"], [65087, 1, "\u3008"], [65088, 1, "\u3009"], [65089, 1, "\u300C"], [65090, 1, "\u300D"], [65091, 1, "\u300E"], [65092, 1, "\u300F"], [[65093, 65094], 2], [65095, 5, "["], [65096, 5, "]"], [[65097, 65100], 5, " \u0305"], [[65101, 65103], 5, "_"], [65104, 5, ","], [65105, 1, "\u3001"], [65106, 3], [65107, 3], [65108, 5, ";"], [65109, 5, ":"], [65110, 5, "?"], [65111, 5, "!"], [65112, 1, "\u2014"], [65113, 5, "("], [65114, 5, ")"], [65115, 5, "{"], [65116, 5, "}"], [65117, 1, "\u3014"], [65118, 1, "\u3015"], [65119, 5, "#"], [65120, 5, "&"], [65121, 5, "*"], [65122, 5, "+"], [65123, 1, "-"], [65124, 5, "<"], [65125, 5, ">"], [65126, 5, "="], [65127, 3], [65128, 5, "\\"], [65129, 5, "$"], [65130, 5, "%"], [65131, 5, "@"], [[65132, 65135], 3], [65136, 5, " \u064B"], [65137, 1, "\u0640\u064B"], [65138, 5, " \u064C"], [65139, 2], [65140, 5, " \u064D"], [65141, 3], [65142, 5, " \u064E"], [65143, 1, "\u0640\u064E"], [65144, 5, " \u064F"], [65145, 1, "\u0640\u064F"], [65146, 5, " \u0650"], [65147, 1, "\u0640\u0650"], [65148, 5, " \u0651"], [65149, 1, "\u0640\u0651"], [65150, 5, " \u0652"], [65151, 1, "\u0640\u0652"], [65152, 1, "\u0621"], [[65153, 65154], 1, "\u0622"], [[65155, 65156], 1, "\u0623"], [[65157, 65158], 1, "\u0624"], [[65159, 65160], 1, "\u0625"], [[65161, 65164], 1, "\u0626"], [[65165, 65166], 1, "\u0627"], [[65167, 65170], 1, "\u0628"], [[65171, 65172], 1, "\u0629"], [[65173, 65176], 1, "\u062A"], [[65177, 65180], 1, "\u062B"], [[65181, 65184], 1, "\u062C"], [[65185, 65188], 1, "\u062D"], [[65189, 65192], 1, "\u062E"], [[65193, 65194], 1, "\u062F"], [[65195, 65196], 1, "\u0630"], [[65197, 65198], 1, "\u0631"], [[65199, 65200], 1, "\u0632"], [[65201, 65204], 1, "\u0633"], [[65205, 65208], 1, "\u0634"], [[65209, 65212], 1, "\u0635"], [[65213, 65216], 1, "\u0636"], [[65217, 65220], 1, "\u0637"], [[65221, 65224], 1, "\u0638"], [[65225, 65228], 1, "\u0639"], [[65229, 65232], 1, "\u063A"], [[65233, 65236], 1, "\u0641"], [[65237, 65240], 1, "\u0642"], [[65241, 65244], 1, "\u0643"], [[65245, 65248], 1, "\u0644"], [[65249, 65252], 1, "\u0645"], [[65253, 65256], 1, "\u0646"], [[65257, 65260], 1, "\u0647"], [[65261, 65262], 1, "\u0648"], [[65263, 65264], 1, "\u0649"], [[65265, 65268], 1, "\u064A"], [[65269, 65270], 1, "\u0644\u0622"], [[65271, 65272], 1, "\u0644\u0623"], [[65273, 65274], 1, "\u0644\u0625"], [[65275, 65276], 1, "\u0644\u0627"], [[65277, 65278], 3], [65279, 7], [65280, 3], [65281, 5, "!"], [65282, 5, '"'], [65283, 5, "#"], [65284, 5, "$"], [65285, 5, "%"], [65286, 5, "&"], [65287, 5, "'"], [65288, 5, "("], [65289, 5, ")"], [65290, 5, "*"], [65291, 5, "+"], [65292, 5, ","], [65293, 1, "-"], [65294, 1, "."], [65295, 5, "/"], [65296, 1, "0"], [65297, 1, "1"], [65298, 1, "2"], [65299, 1, "3"], [65300, 1, "4"], [65301, 1, "5"], [65302, 1, "6"], [65303, 1, "7"], [65304, 1, "8"], [65305, 1, "9"], [65306, 5, ":"], [65307, 5, ";"], [65308, 5, "<"], [65309, 5, "="], [65310, 5, ">"], [65311, 5, "?"], [65312, 5, "@"], [65313, 1, "a"], [65314, 1, "b"], [65315, 1, "c"], [65316, 1, "d"], [65317, 1, "e"], [65318, 1, "f"], [65319, 1, "g"], [65320, 1, "h"], [65321, 1, "i"], [65322, 1, "j"], [65323, 1, "k"], [65324, 1, "l"], [65325, 1, "m"], [65326, 1, "n"], [65327, 1, "o"], [65328, 1, "p"], [65329, 1, "q"], [65330, 1, "r"], [65331, 1, "s"], [65332, 1, "t"], [65333, 1, "u"], [65334, 1, "v"], [65335, 1, "w"], [65336, 1, "x"], [65337, 1, "y"], [65338, 1, "z"], [65339, 5, "["], [65340, 5, "\\"], [65341, 5, "]"], [65342, 5, "^"], [65343, 5, "_"], [65344, 5, "`"], [65345, 1, "a"], [65346, 1, "b"], [65347, 1, "c"], [65348, 1, "d"], [65349, 1, "e"], [65350, 1, "f"], [65351, 1, "g"], [65352, 1, "h"], [65353, 1, "i"], [65354, 1, "j"], [65355, 1, "k"], [65356, 1, "l"], [65357, 1, "m"], [65358, 1, "n"], [65359, 1, "o"], [65360, 1, "p"], [65361, 1, "q"], [65362, 1, "r"], [65363, 1, "s"], [65364, 1, "t"], [65365, 1, "u"], [65366, 1, "v"], [65367, 1, "w"], [65368, 1, "x"], [65369, 1, "y"], [65370, 1, "z"], [65371, 5, "{"], [65372, 5, "|"], [65373, 5, "}"], [65374, 5, "~"], [65375, 1, "\u2985"], [65376, 1, "\u2986"], [65377, 1, "."], [65378, 1, "\u300C"], [65379, 1, "\u300D"], [65380, 1, "\u3001"], [65381, 1, "\u30FB"], [65382, 1, "\u30F2"], [65383, 1, "\u30A1"], [65384, 1, "\u30A3"], [65385, 1, "\u30A5"], [65386, 1, "\u30A7"], [65387, 1, "\u30A9"], [65388, 1, "\u30E3"], [65389, 1, "\u30E5"], [65390, 1, "\u30E7"], [65391, 1, "\u30C3"], [65392, 1, "\u30FC"], [65393, 1, "\u30A2"], [65394, 1, "\u30A4"], [65395, 1, "\u30A6"], [65396, 1, "\u30A8"], [65397, 1, "\u30AA"], [65398, 1, "\u30AB"], [65399, 1, "\u30AD"], [65400, 1, "\u30AF"], [65401, 1, "\u30B1"], [65402, 1, "\u30B3"], [65403, 1, "\u30B5"], [65404, 1, "\u30B7"], [65405, 1, "\u30B9"], [65406, 1, "\u30BB"], [65407, 1, "\u30BD"], [65408, 1, "\u30BF"], [65409, 1, "\u30C1"], [65410, 1, "\u30C4"], [65411, 1, "\u30C6"], [65412, 1, "\u30C8"], [65413, 1, "\u30CA"], [65414, 1, "\u30CB"], [65415, 1, "\u30CC"], [65416, 1, "\u30CD"], [65417, 1, "\u30CE"], [65418, 1, "\u30CF"], [65419, 1, "\u30D2"], [65420, 1, "\u30D5"], [65421, 1, "\u30D8"], [65422, 1, "\u30DB"], [65423, 1, "\u30DE"], [65424, 1, "\u30DF"], [65425, 1, "\u30E0"], [65426, 1, "\u30E1"], [65427, 1, "\u30E2"], [65428, 1, "\u30E4"], [65429, 1, "\u30E6"], [65430, 1, "\u30E8"], [65431, 1, "\u30E9"], [65432, 1, "\u30EA"], [65433, 1, "\u30EB"], [65434, 1, "\u30EC"], [65435, 1, "\u30ED"], [65436, 1, "\u30EF"], [65437, 1, "\u30F3"], [65438, 1, "\u3099"], [65439, 1, "\u309A"], [65440, 3], [65441, 1, "\u1100"], [65442, 1, "\u1101"], [65443, 1, "\u11AA"], [65444, 1, "\u1102"], [65445, 1, "\u11AC"], [65446, 1, "\u11AD"], [65447, 1, "\u1103"], [65448, 1, "\u1104"], [65449, 1, "\u1105"], [65450, 1, "\u11B0"], [65451, 1, "\u11B1"], [65452, 1, "\u11B2"], [65453, 1, "\u11B3"], [65454, 1, "\u11B4"], [65455, 1, "\u11B5"], [65456, 1, "\u111A"], [65457, 1, "\u1106"], [65458, 1, "\u1107"], [65459, 1, "\u1108"], [65460, 1, "\u1121"], [65461, 1, "\u1109"], [65462, 1, "\u110A"], [65463, 1, "\u110B"], [65464, 1, "\u110C"], [65465, 1, "\u110D"], [65466, 1, "\u110E"], [65467, 1, "\u110F"], [65468, 1, "\u1110"], [65469, 1, "\u1111"], [65470, 1, "\u1112"], [[65471, 65473], 3], [65474, 1, "\u1161"], [65475, 1, "\u1162"], [65476, 1, "\u1163"], [65477, 1, "\u1164"], [65478, 1, "\u1165"], [65479, 1, "\u1166"], [[65480, 65481], 3], [65482, 1, "\u1167"], [65483, 1, "\u1168"], [65484, 1, "\u1169"], [65485, 1, "\u116A"], [65486, 1, "\u116B"], [65487, 1, "\u116C"], [[65488, 65489], 3], [65490, 1, "\u116D"], [65491, 1, "\u116E"], [65492, 1, "\u116F"], [65493, 1, "\u1170"], [65494, 1, "\u1171"], [65495, 1, "\u1172"], [[65496, 65497], 3], [65498, 1, "\u1173"], [65499, 1, "\u1174"], [65500, 1, "\u1175"], [[65501, 65503], 3], [65504, 1, "\xA2"], [65505, 1, "\xA3"], [65506, 1, "\xAC"], [65507, 5, " \u0304"], [65508, 1, "\xA6"], [65509, 1, "\xA5"], [65510, 1, "\u20A9"], [65511, 3], [65512, 1, "\u2502"], [65513, 1, "\u2190"], [65514, 1, "\u2191"], [65515, 1, "\u2192"], [65516, 1, "\u2193"], [65517, 1, "\u25A0"], [65518, 1, "\u25CB"], [[65519, 65528], 3], [[65529, 65531], 3], [65532, 3], [65533, 3], [[65534, 65535], 3], [[65536, 65547], 2], [65548, 3], [[65549, 65574], 2], [65575, 3], [[65576, 65594], 2], [65595, 3], [[65596, 65597], 2], [65598, 3], [[65599, 65613], 2], [[65614, 65615], 3], [[65616, 65629], 2], [[65630, 65663], 3], [[65664, 65786], 2], [[65787, 65791], 3], [[65792, 65794], 2], [[65795, 65798], 3], [[65799, 65843], 2], [[65844, 65846], 3], [[65847, 65855], 2], [[65856, 65930], 2], [[65931, 65932], 2], [[65933, 65934], 2], [65935, 3], [[65936, 65947], 2], [65948, 2], [[65949, 65951], 3], [65952, 2], [[65953, 65999], 3], [[66e3, 66044], 2], [66045, 2], [[66046, 66175], 3], [[66176, 66204], 2], [[66205, 66207], 3], [[66208, 66256], 2], [[66257, 66271], 3], [66272, 2], [[66273, 66299], 2], [[66300, 66303], 3], [[66304, 66334], 2], [66335, 2], [[66336, 66339], 2], [[66340, 66348], 3], [[66349, 66351], 2], [[66352, 66368], 2], [66369, 2], [[66370, 66377], 2], [66378, 2], [[66379, 66383], 3], [[66384, 66426], 2], [[66427, 66431], 3], [[66432, 66461], 2], [66462, 3], [66463, 2], [[66464, 66499], 2], [[66500, 66503], 3], [[66504, 66511], 2], [[66512, 66517], 2], [[66518, 66559], 3], [66560, 1, "\u{10428}"], [66561, 1, "\u{10429}"], [66562, 1, "\u{1042A}"], [66563, 1, "\u{1042B}"], [66564, 1, "\u{1042C}"], [66565, 1, "\u{1042D}"], [66566, 1, "\u{1042E}"], [66567, 1, "\u{1042F}"], [66568, 1, "\u{10430}"], [66569, 1, "\u{10431}"], [66570, 1, "\u{10432}"], [66571, 1, "\u{10433}"], [66572, 1, "\u{10434}"], [66573, 1, "\u{10435}"], [66574, 1, "\u{10436}"], [66575, 1, "\u{10437}"], [66576, 1, "\u{10438}"], [66577, 1, "\u{10439}"], [66578, 1, "\u{1043A}"], [66579, 1, "\u{1043B}"], [66580, 1, "\u{1043C}"], [66581, 1, "\u{1043D}"], [66582, 1, "\u{1043E}"], [66583, 1, "\u{1043F}"], [66584, 1, "\u{10440}"], [66585, 1, "\u{10441}"], [66586, 1, "\u{10442}"], [66587, 1, "\u{10443}"], [66588, 1, "\u{10444}"], [66589, 1, "\u{10445}"], [66590, 1, "\u{10446}"], [66591, 1, "\u{10447}"], [66592, 1, "\u{10448}"], [66593, 1, "\u{10449}"], [66594, 1, "\u{1044A}"], [66595, 1, "\u{1044B}"], [66596, 1, "\u{1044C}"], [66597, 1, "\u{1044D}"], [66598, 1, "\u{1044E}"], [66599, 1, "\u{1044F}"], [[66600, 66637], 2], [[66638, 66717], 2], [[66718, 66719], 3], [[66720, 66729], 2], [[66730, 66735], 3], [66736, 1, "\u{104D8}"], [66737, 1, "\u{104D9}"], [66738, 1, "\u{104DA}"], [66739, 1, "\u{104DB}"], [66740, 1, "\u{104DC}"], [66741, 1, "\u{104DD}"], [66742, 1, "\u{104DE}"], [66743, 1, "\u{104DF}"], [66744, 1, "\u{104E0}"], [66745, 1, "\u{104E1}"], [66746, 1, "\u{104E2}"], [66747, 1, "\u{104E3}"], [66748, 1, "\u{104E4}"], [66749, 1, "\u{104E5}"], [66750, 1, "\u{104E6}"], [66751, 1, "\u{104E7}"], [66752, 1, "\u{104E8}"], [66753, 1, "\u{104E9}"], [66754, 1, "\u{104EA}"], [66755, 1, "\u{104EB}"], [66756, 1, "\u{104EC}"], [66757, 1, "\u{104ED}"], [66758, 1, "\u{104EE}"], [66759, 1, "\u{104EF}"], [66760, 1, "\u{104F0}"], [66761, 1, "\u{104F1}"], [66762, 1, "\u{104F2}"], [66763, 1, "\u{104F3}"], [66764, 1, "\u{104F4}"], [66765, 1, "\u{104F5}"], [66766, 1, "\u{104F6}"], [66767, 1, "\u{104F7}"], [66768, 1, "\u{104F8}"], [66769, 1, "\u{104F9}"], [66770, 1, "\u{104FA}"], [66771, 1, "\u{104FB}"], [[66772, 66775], 3], [[66776, 66811], 2], [[66812, 66815], 3], [[66816, 66855], 2], [[66856, 66863], 3], [[66864, 66915], 2], [[66916, 66926], 3], [66927, 2], [66928, 1, "\u{10597}"], [66929, 1, "\u{10598}"], [66930, 1, "\u{10599}"], [66931, 1, "\u{1059A}"], [66932, 1, "\u{1059B}"], [66933, 1, "\u{1059C}"], [66934, 1, "\u{1059D}"], [66935, 1, "\u{1059E}"], [66936, 1, "\u{1059F}"], [66937, 1, "\u{105A0}"], [66938, 1, "\u{105A1}"], [66939, 3], [66940, 1, "\u{105A3}"], [66941, 1, "\u{105A4}"], [66942, 1, "\u{105A5}"], [66943, 1, "\u{105A6}"], [66944, 1, "\u{105A7}"], [66945, 1, "\u{105A8}"], [66946, 1, "\u{105A9}"], [66947, 1, "\u{105AA}"], [66948, 1, "\u{105AB}"], [66949, 1, "\u{105AC}"], [66950, 1, "\u{105AD}"], [66951, 1, "\u{105AE}"], [66952, 1, "\u{105AF}"], [66953, 1, "\u{105B0}"], [66954, 1, "\u{105B1}"], [66955, 3], [66956, 1, "\u{105B3}"], [66957, 1, "\u{105B4}"], [66958, 1, "\u{105B5}"], [66959, 1, "\u{105B6}"], [66960, 1, "\u{105B7}"], [66961, 1, "\u{105B8}"], [66962, 1, "\u{105B9}"], [66963, 3], [66964, 1, "\u{105BB}"], [66965, 1, "\u{105BC}"], [66966, 3], [[66967, 66977], 2], [66978, 3], [[66979, 66993], 2], [66994, 3], [[66995, 67001], 2], [67002, 3], [[67003, 67004], 2], [[67005, 67071], 3], [[67072, 67382], 2], [[67383, 67391], 3], [[67392, 67413], 2], [[67414, 67423], 3], [[67424, 67431], 2], [[67432, 67455], 3], [67456, 2], [67457, 1, "\u02D0"], [67458, 1, "\u02D1"], [67459, 1, "\xE6"], [67460, 1, "\u0299"], [67461, 1, "\u0253"], [67462, 3], [67463, 1, "\u02A3"], [67464, 1, "\uAB66"], [67465, 1, "\u02A5"], [67466, 1, "\u02A4"], [67467, 1, "\u0256"], [67468, 1, "\u0257"], [67469, 1, "\u1D91"], [67470, 1, "\u0258"], [67471, 1, "\u025E"], [67472, 1, "\u02A9"], [67473, 1, "\u0264"], [67474, 1, "\u0262"], [67475, 1, "\u0260"], [67476, 1, "\u029B"], [67477, 1, "\u0127"], [67478, 1, "\u029C"], [67479, 1, "\u0267"], [67480, 1, "\u0284"], [67481, 1, "\u02AA"], [67482, 1, "\u02AB"], [67483, 1, "\u026C"], [67484, 1, "\u{1DF04}"], [67485, 1, "\uA78E"], [67486, 1, "\u026E"], [67487, 1, "\u{1DF05}"], [67488, 1, "\u028E"], [67489, 1, "\u{1DF06}"], [67490, 1, "\xF8"], [67491, 1, "\u0276"], [67492, 1, "\u0277"], [67493, 1, "q"], [67494, 1, "\u027A"], [67495, 1, "\u{1DF08}"], [67496, 1, "\u027D"], [67497, 1, "\u027E"], [67498, 1, "\u0280"], [67499, 1, "\u02A8"], [67500, 1, "\u02A6"], [67501, 1, "\uAB67"], [67502, 1, "\u02A7"], [67503, 1, "\u0288"], [67504, 1, "\u2C71"], [67505, 3], [67506, 1, "\u028F"], [67507, 1, "\u02A1"], [67508, 1, "\u02A2"], [67509, 1, "\u0298"], [67510, 1, "\u01C0"], [67511, 1, "\u01C1"], [67512, 1, "\u01C2"], [67513, 1, "\u{1DF0A}"], [67514, 1, "\u{1DF1E}"], [[67515, 67583], 3], [[67584, 67589], 2], [[67590, 67591], 3], [67592, 2], [67593, 3], [[67594, 67637], 2], [67638, 3], [[67639, 67640], 2], [[67641, 67643], 3], [67644, 2], [[67645, 67646], 3], [67647, 2], [[67648, 67669], 2], [67670, 3], [[67671, 67679], 2], [[67680, 67702], 2], [[67703, 67711], 2], [[67712, 67742], 2], [[67743, 67750], 3], [[67751, 67759], 2], [[67760, 67807], 3], [[67808, 67826], 2], [67827, 3], [[67828, 67829], 2], [[67830, 67834], 3], [[67835, 67839], 2], [[67840, 67861], 2], [[67862, 67865], 2], [[67866, 67867], 2], [[67868, 67870], 3], [67871, 2], [[67872, 67897], 2], [[67898, 67902], 3], [67903, 2], [[67904, 67967], 3], [[67968, 68023], 2], [[68024, 68027], 3], [[68028, 68029], 2], [[68030, 68031], 2], [[68032, 68047], 2], [[68048, 68049], 3], [[68050, 68095], 2], [[68096, 68099], 2], [68100, 3], [[68101, 68102], 2], [[68103, 68107], 3], [[68108, 68115], 2], [68116, 3], [[68117, 68119], 2], [68120, 3], [[68121, 68147], 2], [[68148, 68149], 2], [[68150, 68151], 3], [[68152, 68154], 2], [[68155, 68158], 3], [68159, 2], [[68160, 68167], 2], [68168, 2], [[68169, 68175], 3], [[68176, 68184], 2], [[68185, 68191], 3], [[68192, 68220], 2], [[68221, 68223], 2], [[68224, 68252], 2], [[68253, 68255], 2], [[68256, 68287], 3], [[68288, 68295], 2], [68296, 2], [[68297, 68326], 2], [[68327, 68330], 3], [[68331, 68342], 2], [[68343, 68351], 3], [[68352, 68405], 2], [[68406, 68408], 3], [[68409, 68415], 2], [[68416, 68437], 2], [[68438, 68439], 3], [[68440, 68447], 2], [[68448, 68466], 2], [[68467, 68471], 3], [[68472, 68479], 2], [[68480, 68497], 2], [[68498, 68504], 3], [[68505, 68508], 2], [[68509, 68520], 3], [[68521, 68527], 2], [[68528, 68607], 3], [[68608, 68680], 2], [[68681, 68735], 3], [68736, 1, "\u{10CC0}"], [68737, 1, "\u{10CC1}"], [68738, 1, "\u{10CC2}"], [68739, 1, "\u{10CC3}"], [68740, 1, "\u{10CC4}"], [68741, 1, "\u{10CC5}"], [68742, 1, "\u{10CC6}"], [68743, 1, "\u{10CC7}"], [68744, 1, "\u{10CC8}"], [68745, 1, "\u{10CC9}"], [68746, 1, "\u{10CCA}"], [68747, 1, "\u{10CCB}"], [68748, 1, "\u{10CCC}"], [68749, 1, "\u{10CCD}"], [68750, 1, "\u{10CCE}"], [68751, 1, "\u{10CCF}"], [68752, 1, "\u{10CD0}"], [68753, 1, "\u{10CD1}"], [68754, 1, "\u{10CD2}"], [68755, 1, "\u{10CD3}"], [68756, 1, "\u{10CD4}"], [68757, 1, "\u{10CD5}"], [68758, 1, "\u{10CD6}"], [68759, 1, "\u{10CD7}"], [68760, 1, "\u{10CD8}"], [68761, 1, "\u{10CD9}"], [68762, 1, "\u{10CDA}"], [68763, 1, "\u{10CDB}"], [68764, 1, "\u{10CDC}"], [68765, 1, "\u{10CDD}"], [68766, 1, "\u{10CDE}"], [68767, 1, "\u{10CDF}"], [68768, 1, "\u{10CE0}"], [68769, 1, "\u{10CE1}"], [68770, 1, "\u{10CE2}"], [68771, 1, "\u{10CE3}"], [68772, 1, "\u{10CE4}"], [68773, 1, "\u{10CE5}"], [68774, 1, "\u{10CE6}"], [68775, 1, "\u{10CE7}"], [68776, 1, "\u{10CE8}"], [68777, 1, "\u{10CE9}"], [68778, 1, "\u{10CEA}"], [68779, 1, "\u{10CEB}"], [68780, 1, "\u{10CEC}"], [68781, 1, "\u{10CED}"], [68782, 1, "\u{10CEE}"], [68783, 1, "\u{10CEF}"], [68784, 1, "\u{10CF0}"], [68785, 1, "\u{10CF1}"], [68786, 1, "\u{10CF2}"], [[68787, 68799], 3], [[68800, 68850], 2], [[68851, 68857], 3], [[68858, 68863], 2], [[68864, 68903], 2], [[68904, 68911], 3], [[68912, 68921], 2], [[68922, 69215], 3], [[69216, 69246], 2], [69247, 3], [[69248, 69289], 2], [69290, 3], [[69291, 69292], 2], [69293, 2], [[69294, 69295], 3], [[69296, 69297], 2], [[69298, 69375], 3], [[69376, 69404], 2], [[69405, 69414], 2], [69415, 2], [[69416, 69423], 3], [[69424, 69456], 2], [[69457, 69465], 2], [[69466, 69487], 3], [[69488, 69509], 2], [[69510, 69513], 2], [[69514, 69551], 3], [[69552, 69572], 2], [[69573, 69579], 2], [[69580, 69599], 3], [[69600, 69622], 2], [[69623, 69631], 3], [[69632, 69702], 2], [[69703, 69709], 2], [[69710, 69713], 3], [[69714, 69733], 2], [[69734, 69743], 2], [[69744, 69749], 2], [[69750, 69758], 3], [69759, 2], [[69760, 69818], 2], [[69819, 69820], 2], [69821, 3], [[69822, 69825], 2], [69826, 2], [[69827, 69836], 3], [69837, 3], [[69838, 69839], 3], [[69840, 69864], 2], [[69865, 69871], 3], [[69872, 69881], 2], [[69882, 69887], 3], [[69888, 69940], 2], [69941, 3], [[69942, 69951], 2], [[69952, 69955], 2], [[69956, 69958], 2], [69959, 2], [[69960, 69967], 3], [[69968, 70003], 2], [[70004, 70005], 2], [70006, 2], [[70007, 70015], 3], [[70016, 70084], 2], [[70085, 70088], 2], [[70089, 70092], 2], [70093, 2], [[70094, 70095], 2], [[70096, 70105], 2], [70106, 2], [70107, 2], [70108, 2], [[70109, 70111], 2], [70112, 3], [[70113, 70132], 2], [[70133, 70143], 3], [[70144, 70161], 2], [70162, 3], [[70163, 70199], 2], [[70200, 70205], 2], [70206, 2], [[70207, 70271], 3], [[70272, 70278], 2], [70279, 3], [70280, 2], [70281, 3], [[70282, 70285], 2], [70286, 3], [[70287, 70301], 2], [70302, 3], [[70303, 70312], 2], [70313, 2], [[70314, 70319], 3], [[70320, 70378], 2], [[70379, 70383], 3], [[70384, 70393], 2], [[70394, 70399], 3], [70400, 2], [[70401, 70403], 2], [70404, 3], [[70405, 70412], 2], [[70413, 70414], 3], [[70415, 70416], 2], [[70417, 70418], 3], [[70419, 70440], 2], [70441, 3], [[70442, 70448], 2], [70449, 3], [[70450, 70451], 2], [70452, 3], [[70453, 70457], 2], [70458, 3], [70459, 2], [[70460, 70468], 2], [[70469, 70470], 3], [[70471, 70472], 2], [[70473, 70474], 3], [[70475, 70477], 2], [[70478, 70479], 3], [70480, 2], [[70481, 70486], 3], [70487, 2], [[70488, 70492], 3], [[70493, 70499], 2], [[70500, 70501], 3], [[70502, 70508], 2], [[70509, 70511], 3], [[70512, 70516], 2], [[70517, 70655], 3], [[70656, 70730], 2], [[70731, 70735], 2], [[70736, 70745], 2], [70746, 2], [70747, 2], [70748, 3], [70749, 2], [70750, 2], [70751, 2], [[70752, 70753], 2], [[70754, 70783], 3], [[70784, 70853], 2], [70854, 2], [70855, 2], [[70856, 70863], 3], [[70864, 70873], 2], [[70874, 71039], 3], [[71040, 71093], 2], [[71094, 71095], 3], [[71096, 71104], 2], [[71105, 71113], 2], [[71114, 71127], 2], [[71128, 71133], 2], [[71134, 71167], 3], [[71168, 71232], 2], [[71233, 71235], 2], [71236, 2], [[71237, 71247], 3], [[71248, 71257], 2], [[71258, 71263], 3], [[71264, 71276], 2], [[71277, 71295], 3], [[71296, 71351], 2], [71352, 2], [71353, 2], [[71354, 71359], 3], [[71360, 71369], 2], [[71370, 71423], 3], [[71424, 71449], 2], [71450, 2], [[71451, 71452], 3], [[71453, 71467], 2], [[71468, 71471], 3], [[71472, 71481], 2], [[71482, 71487], 2], [[71488, 71494], 2], [[71495, 71679], 3], [[71680, 71738], 2], [71739, 2], [[71740, 71839], 3], [71840, 1, "\u{118C0}"], [71841, 1, "\u{118C1}"], [71842, 1, "\u{118C2}"], [71843, 1, "\u{118C3}"], [71844, 1, "\u{118C4}"], [71845, 1, "\u{118C5}"], [71846, 1, "\u{118C6}"], [71847, 1, "\u{118C7}"], [71848, 1, "\u{118C8}"], [71849, 1, "\u{118C9}"], [71850, 1, "\u{118CA}"], [71851, 1, "\u{118CB}"], [71852, 1, "\u{118CC}"], [71853, 1, "\u{118CD}"], [71854, 1, "\u{118CE}"], [71855, 1, "\u{118CF}"], [71856, 1, "\u{118D0}"], [71857, 1, "\u{118D1}"], [71858, 1, "\u{118D2}"], [71859, 1, "\u{118D3}"], [71860, 1, "\u{118D4}"], [71861, 1, "\u{118D5}"], [71862, 1, "\u{118D6}"], [71863, 1, "\u{118D7}"], [71864, 1, "\u{118D8}"], [71865, 1, "\u{118D9}"], [71866, 1, "\u{118DA}"], [71867, 1, "\u{118DB}"], [71868, 1, "\u{118DC}"], [71869, 1, "\u{118DD}"], [71870, 1, "\u{118DE}"], [71871, 1, "\u{118DF}"], [[71872, 71913], 2], [[71914, 71922], 2], [[71923, 71934], 3], [71935, 2], [[71936, 71942], 2], [[71943, 71944], 3], [71945, 2], [[71946, 71947], 3], [[71948, 71955], 2], [71956, 3], [[71957, 71958], 2], [71959, 3], [[71960, 71989], 2], [71990, 3], [[71991, 71992], 2], [[71993, 71994], 3], [[71995, 72003], 2], [[72004, 72006], 2], [[72007, 72015], 3], [[72016, 72025], 2], [[72026, 72095], 3], [[72096, 72103], 2], [[72104, 72105], 3], [[72106, 72151], 2], [[72152, 72153], 3], [[72154, 72161], 2], [72162, 2], [[72163, 72164], 2], [[72165, 72191], 3], [[72192, 72254], 2], [[72255, 72262], 2], [72263, 2], [[72264, 72271], 3], [[72272, 72323], 2], [[72324, 72325], 2], [[72326, 72345], 2], [[72346, 72348], 2], [72349, 2], [[72350, 72354], 2], [[72355, 72367], 3], [[72368, 72383], 2], [[72384, 72440], 2], [[72441, 72703], 3], [[72704, 72712], 2], [72713, 3], [[72714, 72758], 2], [72759, 3], [[72760, 72768], 2], [[72769, 72773], 2], [[72774, 72783], 3], [[72784, 72793], 2], [[72794, 72812], 2], [[72813, 72815], 3], [[72816, 72817], 2], [[72818, 72847], 2], [[72848, 72849], 3], [[72850, 72871], 2], [72872, 3], [[72873, 72886], 2], [[72887, 72959], 3], [[72960, 72966], 2], [72967, 3], [[72968, 72969], 2], [72970, 3], [[72971, 73014], 2], [[73015, 73017], 3], [73018, 2], [73019, 3], [[73020, 73021], 2], [73022, 3], [[73023, 73031], 2], [[73032, 73039], 3], [[73040, 73049], 2], [[73050, 73055], 3], [[73056, 73061], 2], [73062, 3], [[73063, 73064], 2], [73065, 3], [[73066, 73102], 2], [73103, 3], [[73104, 73105], 2], [73106, 3], [[73107, 73112], 2], [[73113, 73119], 3], [[73120, 73129], 2], [[73130, 73439], 3], [[73440, 73462], 2], [[73463, 73464], 2], [[73465, 73647], 3], [73648, 2], [[73649, 73663], 3], [[73664, 73713], 2], [[73714, 73726], 3], [73727, 2], [[73728, 74606], 2], [[74607, 74648], 2], [74649, 2], [[74650, 74751], 3], [[74752, 74850], 2], [[74851, 74862], 2], [74863, 3], [[74864, 74867], 2], [74868, 2], [[74869, 74879], 3], [[74880, 75075], 2], [[75076, 77711], 3], [[77712, 77808], 2], [[77809, 77810], 2], [[77811, 77823], 3], [[77824, 78894], 2], [78895, 3], [[78896, 78904], 3], [[78905, 82943], 3], [[82944, 83526], 2], [[83527, 92159], 3], [[92160, 92728], 2], [[92729, 92735], 3], [[92736, 92766], 2], [92767, 3], [[92768, 92777], 2], [[92778, 92781], 3], [[92782, 92783], 2], [[92784, 92862], 2], [92863, 3], [[92864, 92873], 2], [[92874, 92879], 3], [[92880, 92909], 2], [[92910, 92911], 3], [[92912, 92916], 2], [92917, 2], [[92918, 92927], 3], [[92928, 92982], 2], [[92983, 92991], 2], [[92992, 92995], 2], [[92996, 92997], 2], [[92998, 93007], 3], [[93008, 93017], 2], [93018, 3], [[93019, 93025], 2], [93026, 3], [[93027, 93047], 2], [[93048, 93052], 3], [[93053, 93071], 2], [[93072, 93759], 3], [93760, 1, "\u{16E60}"], [93761, 1, "\u{16E61}"], [93762, 1, "\u{16E62}"], [93763, 1, "\u{16E63}"], [93764, 1, "\u{16E64}"], [93765, 1, "\u{16E65}"], [93766, 1, "\u{16E66}"], [93767, 1, "\u{16E67}"], [93768, 1, "\u{16E68}"], [93769, 1, "\u{16E69}"], [93770, 1, "\u{16E6A}"], [93771, 1, "\u{16E6B}"], [93772, 1, "\u{16E6C}"], [93773, 1, "\u{16E6D}"], [93774, 1, "\u{16E6E}"], [93775, 1, "\u{16E6F}"], [93776, 1, "\u{16E70}"], [93777, 1, "\u{16E71}"], [93778, 1, "\u{16E72}"], [93779, 1, "\u{16E73}"], [93780, 1, "\u{16E74}"], [93781, 1, "\u{16E75}"], [93782, 1, "\u{16E76}"], [93783, 1, "\u{16E77}"], [93784, 1, "\u{16E78}"], [93785, 1, "\u{16E79}"], [93786, 1, "\u{16E7A}"], [93787, 1, "\u{16E7B}"], [93788, 1, "\u{16E7C}"], [93789, 1, "\u{16E7D}"], [93790, 1, "\u{16E7E}"], [93791, 1, "\u{16E7F}"], [[93792, 93823], 2], [[93824, 93850], 2], [[93851, 93951], 3], [[93952, 94020], 2], [[94021, 94026], 2], [[94027, 94030], 3], [94031, 2], [[94032, 94078], 2], [[94079, 94087], 2], [[94088, 94094], 3], [[94095, 94111], 2], [[94112, 94175], 3], [94176, 2], [94177, 2], [94178, 2], [94179, 2], [94180, 2], [[94181, 94191], 3], [[94192, 94193], 2], [[94194, 94207], 3], [[94208, 100332], 2], [[100333, 100337], 2], [[100338, 100343], 2], [[100344, 100351], 3], [[100352, 101106], 2], [[101107, 101589], 2], [[101590, 101631], 3], [[101632, 101640], 2], [[101641, 110575], 3], [[110576, 110579], 2], [110580, 3], [[110581, 110587], 2], [110588, 3], [[110589, 110590], 2], [110591, 3], [[110592, 110593], 2], [[110594, 110878], 2], [[110879, 110882], 2], [[110883, 110927], 3], [[110928, 110930], 2], [[110931, 110947], 3], [[110948, 110951], 2], [[110952, 110959], 3], [[110960, 111355], 2], [[111356, 113663], 3], [[113664, 113770], 2], [[113771, 113775], 3], [[113776, 113788], 2], [[113789, 113791], 3], [[113792, 113800], 2], [[113801, 113807], 3], [[113808, 113817], 2], [[113818, 113819], 3], [113820, 2], [[113821, 113822], 2], [113823, 2], [[113824, 113827], 7], [[113828, 118527], 3], [[118528, 118573], 2], [[118574, 118575], 3], [[118576, 118598], 2], [[118599, 118607], 3], [[118608, 118723], 2], [[118724, 118783], 3], [[118784, 119029], 2], [[119030, 119039], 3], [[119040, 119078], 2], [[119079, 119080], 3], [119081, 2], [[119082, 119133], 2], [119134, 1, "\u{1D157}\u{1D165}"], [119135, 1, "\u{1D158}\u{1D165}"], [119136, 1, "\u{1D158}\u{1D165}\u{1D16E}"], [119137, 1, "\u{1D158}\u{1D165}\u{1D16F}"], [119138, 1, "\u{1D158}\u{1D165}\u{1D170}"], [119139, 1, "\u{1D158}\u{1D165}\u{1D171}"], [119140, 1, "\u{1D158}\u{1D165}\u{1D172}"], [[119141, 119154], 2], [[119155, 119162], 3], [[119163, 119226], 2], [119227, 1, "\u{1D1B9}\u{1D165}"], [119228, 1, "\u{1D1BA}\u{1D165}"], [119229, 1, "\u{1D1B9}\u{1D165}\u{1D16E}"], [119230, 1, "\u{1D1BA}\u{1D165}\u{1D16E}"], [119231, 1, "\u{1D1B9}\u{1D165}\u{1D16F}"], [119232, 1, "\u{1D1BA}\u{1D165}\u{1D16F}"], [[119233, 119261], 2], [[119262, 119272], 2], [[119273, 119274], 2], [[119275, 119295], 3], [[119296, 119365], 2], [[119366, 119519], 3], [[119520, 119539], 2], [[119540, 119551], 3], [[119552, 119638], 2], [[119639, 119647], 3], [[119648, 119665], 2], [[119666, 119672], 2], [[119673, 119807], 3], [119808, 1, "a"], [119809, 1, "b"], [119810, 1, "c"], [119811, 1, "d"], [119812, 1, "e"], [119813, 1, "f"], [119814, 1, "g"], [119815, 1, "h"], [119816, 1, "i"], [119817, 1, "j"], [119818, 1, "k"], [119819, 1, "l"], [119820, 1, "m"], [119821, 1, "n"], [119822, 1, "o"], [119823, 1, "p"], [119824, 1, "q"], [119825, 1, "r"], [119826, 1, "s"], [119827, 1, "t"], [119828, 1, "u"], [119829, 1, "v"], [119830, 1, "w"], [119831, 1, "x"], [119832, 1, "y"], [119833, 1, "z"], [119834, 1, "a"], [119835, 1, "b"], [119836, 1, "c"], [119837, 1, "d"], [119838, 1, "e"], [119839, 1, "f"], [119840, 1, "g"], [119841, 1, "h"], [119842, 1, "i"], [119843, 1, "j"], [119844, 1, "k"], [119845, 1, "l"], [119846, 1, "m"], [119847, 1, "n"], [119848, 1, "o"], [119849, 1, "p"], [119850, 1, "q"], [119851, 1, "r"], [119852, 1, "s"], [119853, 1, "t"], [119854, 1, "u"], [119855, 1, "v"], [119856, 1, "w"], [119857, 1, "x"], [119858, 1, "y"], [119859, 1, "z"], [119860, 1, "a"], [119861, 1, "b"], [119862, 1, "c"], [119863, 1, "d"], [119864, 1, "e"], [119865, 1, "f"], [119866, 1, "g"], [119867, 1, "h"], [119868, 1, "i"], [119869, 1, "j"], [119870, 1, "k"], [119871, 1, "l"], [119872, 1, "m"], [119873, 1, "n"], [119874, 1, "o"], [119875, 1, "p"], [119876, 1, "q"], [119877, 1, "r"], [119878, 1, "s"], [119879, 1, "t"], [119880, 1, "u"], [119881, 1, "v"], [119882, 1, "w"], [119883, 1, "x"], [119884, 1, "y"], [119885, 1, "z"], [119886, 1, "a"], [119887, 1, "b"], [119888, 1, "c"], [119889, 1, "d"], [119890, 1, "e"], [119891, 1, "f"], [119892, 1, "g"], [119893, 3], [119894, 1, "i"], [119895, 1, "j"], [119896, 1, "k"], [119897, 1, "l"], [119898, 1, "m"], [119899, 1, "n"], [119900, 1, "o"], [119901, 1, "p"], [119902, 1, "q"], [119903, 1, "r"], [119904, 1, "s"], [119905, 1, "t"], [119906, 1, "u"], [119907, 1, "v"], [119908, 1, "w"], [119909, 1, "x"], [119910, 1, "y"], [119911, 1, "z"], [119912, 1, "a"], [119913, 1, "b"], [119914, 1, "c"], [119915, 1, "d"], [119916, 1, "e"], [119917, 1, "f"], [119918, 1, "g"], [119919, 1, "h"], [119920, 1, "i"], [119921, 1, "j"], [119922, 1, "k"], [119923, 1, "l"], [119924, 1, "m"], [119925, 1, "n"], [119926, 1, "o"], [119927, 1, "p"], [119928, 1, "q"], [119929, 1, "r"], [119930, 1, "s"], [119931, 1, "t"], [119932, 1, "u"], [119933, 1, "v"], [119934, 1, "w"], [119935, 1, "x"], [119936, 1, "y"], [119937, 1, "z"], [119938, 1, "a"], [119939, 1, "b"], [119940, 1, "c"], [119941, 1, "d"], [119942, 1, "e"], [119943, 1, "f"], [119944, 1, "g"], [119945, 1, "h"], [119946, 1, "i"], [119947, 1, "j"], [119948, 1, "k"], [119949, 1, "l"], [119950, 1, "m"], [119951, 1, "n"], [119952, 1, "o"], [119953, 1, "p"], [119954, 1, "q"], [119955, 1, "r"], [119956, 1, "s"], [119957, 1, "t"], [119958, 1, "u"], [119959, 1, "v"], [119960, 1, "w"], [119961, 1, "x"], [119962, 1, "y"], [119963, 1, "z"], [119964, 1, "a"], [119965, 3], [119966, 1, "c"], [119967, 1, "d"], [[119968, 119969], 3], [119970, 1, "g"], [[119971, 119972], 3], [119973, 1, "j"], [119974, 1, "k"], [[119975, 119976], 3], [119977, 1, "n"], [119978, 1, "o"], [119979, 1, "p"], [119980, 1, "q"], [119981, 3], [119982, 1, "s"], [119983, 1, "t"], [119984, 1, "u"], [119985, 1, "v"], [119986, 1, "w"], [119987, 1, "x"], [119988, 1, "y"], [119989, 1, "z"], [119990, 1, "a"], [119991, 1, "b"], [119992, 1, "c"], [119993, 1, "d"], [119994, 3], [119995, 1, "f"], [119996, 3], [119997, 1, "h"], [119998, 1, "i"], [119999, 1, "j"], [12e4, 1, "k"], [120001, 1, "l"], [120002, 1, "m"], [120003, 1, "n"], [120004, 3], [120005, 1, "p"], [120006, 1, "q"], [120007, 1, "r"], [120008, 1, "s"], [120009, 1, "t"], [120010, 1, "u"], [120011, 1, "v"], [120012, 1, "w"], [120013, 1, "x"], [120014, 1, "y"], [120015, 1, "z"], [120016, 1, "a"], [120017, 1, "b"], [120018, 1, "c"], [120019, 1, "d"], [120020, 1, "e"], [120021, 1, "f"], [120022, 1, "g"], [120023, 1, "h"], [120024, 1, "i"], [120025, 1, "j"], [120026, 1, "k"], [120027, 1, "l"], [120028, 1, "m"], [120029, 1, "n"], [120030, 1, "o"], [120031, 1, "p"], [120032, 1, "q"], [120033, 1, "r"], [120034, 1, "s"], [120035, 1, "t"], [120036, 1, "u"], [120037, 1, "v"], [120038, 1, "w"], [120039, 1, "x"], [120040, 1, "y"], [120041, 1, "z"], [120042, 1, "a"], [120043, 1, "b"], [120044, 1, "c"], [120045, 1, "d"], [120046, 1, "e"], [120047, 1, "f"], [120048, 1, "g"], [120049, 1, "h"], [120050, 1, "i"], [120051, 1, "j"], [120052, 1, "k"], [120053, 1, "l"], [120054, 1, "m"], [120055, 1, "n"], [120056, 1, "o"], [120057, 1, "p"], [120058, 1, "q"], [120059, 1, "r"], [120060, 1, "s"], [120061, 1, "t"], [120062, 1, "u"], [120063, 1, "v"], [120064, 1, "w"], [120065, 1, "x"], [120066, 1, "y"], [120067, 1, "z"], [120068, 1, "a"], [120069, 1, "b"], [120070, 3], [120071, 1, "d"], [120072, 1, "e"], [120073, 1, "f"], [120074, 1, "g"], [[120075, 120076], 3], [120077, 1, "j"], [120078, 1, "k"], [120079, 1, "l"], [120080, 1, "m"], [120081, 1, "n"], [120082, 1, "o"], [120083, 1, "p"], [120084, 1, "q"], [120085, 3], [120086, 1, "s"], [120087, 1, "t"], [120088, 1, "u"], [120089, 1, "v"], [120090, 1, "w"], [120091, 1, "x"], [120092, 1, "y"], [120093, 3], [120094, 1, "a"], [120095, 1, "b"], [120096, 1, "c"], [120097, 1, "d"], [120098, 1, "e"], [120099, 1, "f"], [120100, 1, "g"], [120101, 1, "h"], [120102, 1, "i"], [120103, 1, "j"], [120104, 1, "k"], [120105, 1, "l"], [120106, 1, "m"], [120107, 1, "n"], [120108, 1, "o"], [120109, 1, "p"], [120110, 1, "q"], [120111, 1, "r"], [120112, 1, "s"], [120113, 1, "t"], [120114, 1, "u"], [120115, 1, "v"], [120116, 1, "w"], [120117, 1, "x"], [120118, 1, "y"], [120119, 1, "z"], [120120, 1, "a"], [120121, 1, "b"], [120122, 3], [120123, 1, "d"], [120124, 1, "e"], [120125, 1, "f"], [120126, 1, "g"], [120127, 3], [120128, 1, "i"], [120129, 1, "j"], [120130, 1, "k"], [120131, 1, "l"], [120132, 1, "m"], [120133, 3], [120134, 1, "o"], [[120135, 120137], 3], [120138, 1, "s"], [120139, 1, "t"], [120140, 1, "u"], [120141, 1, "v"], [120142, 1, "w"], [120143, 1, "x"], [120144, 1, "y"], [120145, 3], [120146, 1, "a"], [120147, 1, "b"], [120148, 1, "c"], [120149, 1, "d"], [120150, 1, "e"], [120151, 1, "f"], [120152, 1, "g"], [120153, 1, "h"], [120154, 1, "i"], [120155, 1, "j"], [120156, 1, "k"], [120157, 1, "l"], [120158, 1, "m"], [120159, 1, "n"], [120160, 1, "o"], [120161, 1, "p"], [120162, 1, "q"], [120163, 1, "r"], [120164, 1, "s"], [120165, 1, "t"], [120166, 1, "u"], [120167, 1, "v"], [120168, 1, "w"], [120169, 1, "x"], [120170, 1, "y"], [120171, 1, "z"], [120172, 1, "a"], [120173, 1, "b"], [120174, 1, "c"], [120175, 1, "d"], [120176, 1, "e"], [120177, 1, "f"], [120178, 1, "g"], [120179, 1, "h"], [120180, 1, "i"], [120181, 1, "j"], [120182, 1, "k"], [120183, 1, "l"], [120184, 1, "m"], [120185, 1, "n"], [120186, 1, "o"], [120187, 1, "p"], [120188, 1, "q"], [120189, 1, "r"], [120190, 1, "s"], [120191, 1, "t"], [120192, 1, "u"], [120193, 1, "v"], [120194, 1, "w"], [120195, 1, "x"], [120196, 1, "y"], [120197, 1, "z"], [120198, 1, "a"], [120199, 1, "b"], [120200, 1, "c"], [120201, 1, "d"], [120202, 1, "e"], [120203, 1, "f"], [120204, 1, "g"], [120205, 1, "h"], [120206, 1, "i"], [120207, 1, "j"], [120208, 1, "k"], [120209, 1, "l"], [120210, 1, "m"], [120211, 1, "n"], [120212, 1, "o"], [120213, 1, "p"], [120214, 1, "q"], [120215, 1, "r"], [120216, 1, "s"], [120217, 1, "t"], [120218, 1, "u"], [120219, 1, "v"], [120220, 1, "w"], [120221, 1, "x"], [120222, 1, "y"], [120223, 1, "z"], [120224, 1, "a"], [120225, 1, "b"], [120226, 1, "c"], [120227, 1, "d"], [120228, 1, "e"], [120229, 1, "f"], [120230, 1, "g"], [120231, 1, "h"], [120232, 1, "i"], [120233, 1, "j"], [120234, 1, "k"], [120235, 1, "l"], [120236, 1, "m"], [120237, 1, "n"], [120238, 1, "o"], [120239, 1, "p"], [120240, 1, "q"], [120241, 1, "r"], [120242, 1, "s"], [120243, 1, "t"], [120244, 1, "u"], [120245, 1, "v"], [120246, 1, "w"], [120247, 1, "x"], [120248, 1, "y"], [120249, 1, "z"], [120250, 1, "a"], [120251, 1, "b"], [120252, 1, "c"], [120253, 1, "d"], [120254, 1, "e"], [120255, 1, "f"], [120256, 1, "g"], [120257, 1, "h"], [120258, 1, "i"], [120259, 1, "j"], [120260, 1, "k"], [120261, 1, "l"], [120262, 1, "m"], [120263, 1, "n"], [120264, 1, "o"], [120265, 1, "p"], [120266, 1, "q"], [120267, 1, "r"], [120268, 1, "s"], [120269, 1, "t"], [120270, 1, "u"], [120271, 1, "v"], [120272, 1, "w"], [120273, 1, "x"], [120274, 1, "y"], [120275, 1, "z"], [120276, 1, "a"], [120277, 1, "b"], [120278, 1, "c"], [120279, 1, "d"], [120280, 1, "e"], [120281, 1, "f"], [120282, 1, "g"], [120283, 1, "h"], [120284, 1, "i"], [120285, 1, "j"], [120286, 1, "k"], [120287, 1, "l"], [120288, 1, "m"], [120289, 1, "n"], [120290, 1, "o"], [120291, 1, "p"], [120292, 1, "q"], [120293, 1, "r"], [120294, 1, "s"], [120295, 1, "t"], [120296, 1, "u"], [120297, 1, "v"], [120298, 1, "w"], [120299, 1, "x"], [120300, 1, "y"], [120301, 1, "z"], [120302, 1, "a"], [120303, 1, "b"], [120304, 1, "c"], [120305, 1, "d"], [120306, 1, "e"], [120307, 1, "f"], [120308, 1, "g"], [120309, 1, "h"], [120310, 1, "i"], [120311, 1, "j"], [120312, 1, "k"], [120313, 1, "l"], [120314, 1, "m"], [120315, 1, "n"], [120316, 1, "o"], [120317, 1, "p"], [120318, 1, "q"], [120319, 1, "r"], [120320, 1, "s"], [120321, 1, "t"], [120322, 1, "u"], [120323, 1, "v"], [120324, 1, "w"], [120325, 1, "x"], [120326, 1, "y"], [120327, 1, "z"], [120328, 1, "a"], [120329, 1, "b"], [120330, 1, "c"], [120331, 1, "d"], [120332, 1, "e"], [120333, 1, "f"], [120334, 1, "g"], [120335, 1, "h"], [120336, 1, "i"], [120337, 1, "j"], [120338, 1, "k"], [120339, 1, "l"], [120340, 1, "m"], [120341, 1, "n"], [120342, 1, "o"], [120343, 1, "p"], [120344, 1, "q"], [120345, 1, "r"], [120346, 1, "s"], [120347, 1, "t"], [120348, 1, "u"], [120349, 1, "v"], [120350, 1, "w"], [120351, 1, "x"], [120352, 1, "y"], [120353, 1, "z"], [120354, 1, "a"], [120355, 1, "b"], [120356, 1, "c"], [120357, 1, "d"], [120358, 1, "e"], [120359, 1, "f"], [120360, 1, "g"], [120361, 1, "h"], [120362, 1, "i"], [120363, 1, "j"], [120364, 1, "k"], [120365, 1, "l"], [120366, 1, "m"], [120367, 1, "n"], [120368, 1, "o"], [120369, 1, "p"], [120370, 1, "q"], [120371, 1, "r"], [120372, 1, "s"], [120373, 1, "t"], [120374, 1, "u"], [120375, 1, "v"], [120376, 1, "w"], [120377, 1, "x"], [120378, 1, "y"], [120379, 1, "z"], [120380, 1, "a"], [120381, 1, "b"], [120382, 1, "c"], [120383, 1, "d"], [120384, 1, "e"], [120385, 1, "f"], [120386, 1, "g"], [120387, 1, "h"], [120388, 1, "i"], [120389, 1, "j"], [120390, 1, "k"], [120391, 1, "l"], [120392, 1, "m"], [120393, 1, "n"], [120394, 1, "o"], [120395, 1, "p"], [120396, 1, "q"], [120397, 1, "r"], [120398, 1, "s"], [120399, 1, "t"], [120400, 1, "u"], [120401, 1, "v"], [120402, 1, "w"], [120403, 1, "x"], [120404, 1, "y"], [120405, 1, "z"], [120406, 1, "a"], [120407, 1, "b"], [120408, 1, "c"], [120409, 1, "d"], [120410, 1, "e"], [120411, 1, "f"], [120412, 1, "g"], [120413, 1, "h"], [120414, 1, "i"], [120415, 1, "j"], [120416, 1, "k"], [120417, 1, "l"], [120418, 1, "m"], [120419, 1, "n"], [120420, 1, "o"], [120421, 1, "p"], [120422, 1, "q"], [120423, 1, "r"], [120424, 1, "s"], [120425, 1, "t"], [120426, 1, "u"], [120427, 1, "v"], [120428, 1, "w"], [120429, 1, "x"], [120430, 1, "y"], [120431, 1, "z"], [120432, 1, "a"], [120433, 1, "b"], [120434, 1, "c"], [120435, 1, "d"], [120436, 1, "e"], [120437, 1, "f"], [120438, 1, "g"], [120439, 1, "h"], [120440, 1, "i"], [120441, 1, "j"], [120442, 1, "k"], [120443, 1, "l"], [120444, 1, "m"], [120445, 1, "n"], [120446, 1, "o"], [120447, 1, "p"], [120448, 1, "q"], [120449, 1, "r"], [120450, 1, "s"], [120451, 1, "t"], [120452, 1, "u"], [120453, 1, "v"], [120454, 1, "w"], [120455, 1, "x"], [120456, 1, "y"], [120457, 1, "z"], [120458, 1, "a"], [120459, 1, "b"], [120460, 1, "c"], [120461, 1, "d"], [120462, 1, "e"], [120463, 1, "f"], [120464, 1, "g"], [120465, 1, "h"], [120466, 1, "i"], [120467, 1, "j"], [120468, 1, "k"], [120469, 1, "l"], [120470, 1, "m"], [120471, 1, "n"], [120472, 1, "o"], [120473, 1, "p"], [120474, 1, "q"], [120475, 1, "r"], [120476, 1, "s"], [120477, 1, "t"], [120478, 1, "u"], [120479, 1, "v"], [120480, 1, "w"], [120481, 1, "x"], [120482, 1, "y"], [120483, 1, "z"], [120484, 1, "\u0131"], [120485, 1, "\u0237"], [[120486, 120487], 3], [120488, 1, "\u03B1"], [120489, 1, "\u03B2"], [120490, 1, "\u03B3"], [120491, 1, "\u03B4"], [120492, 1, "\u03B5"], [120493, 1, "\u03B6"], [120494, 1, "\u03B7"], [120495, 1, "\u03B8"], [120496, 1, "\u03B9"], [120497, 1, "\u03BA"], [120498, 1, "\u03BB"], [120499, 1, "\u03BC"], [120500, 1, "\u03BD"], [120501, 1, "\u03BE"], [120502, 1, "\u03BF"], [120503, 1, "\u03C0"], [120504, 1, "\u03C1"], [120505, 1, "\u03B8"], [120506, 1, "\u03C3"], [120507, 1, "\u03C4"], [120508, 1, "\u03C5"], [120509, 1, "\u03C6"], [120510, 1, "\u03C7"], [120511, 1, "\u03C8"], [120512, 1, "\u03C9"], [120513, 1, "\u2207"], [120514, 1, "\u03B1"], [120515, 1, "\u03B2"], [120516, 1, "\u03B3"], [120517, 1, "\u03B4"], [120518, 1, "\u03B5"], [120519, 1, "\u03B6"], [120520, 1, "\u03B7"], [120521, 1, "\u03B8"], [120522, 1, "\u03B9"], [120523, 1, "\u03BA"], [120524, 1, "\u03BB"], [120525, 1, "\u03BC"], [120526, 1, "\u03BD"], [120527, 1, "\u03BE"], [120528, 1, "\u03BF"], [120529, 1, "\u03C0"], [120530, 1, "\u03C1"], [[120531, 120532], 1, "\u03C3"], [120533, 1, "\u03C4"], [120534, 1, "\u03C5"], [120535, 1, "\u03C6"], [120536, 1, "\u03C7"], [120537, 1, "\u03C8"], [120538, 1, "\u03C9"], [120539, 1, "\u2202"], [120540, 1, "\u03B5"], [120541, 1, "\u03B8"], [120542, 1, "\u03BA"], [120543, 1, "\u03C6"], [120544, 1, "\u03C1"], [120545, 1, "\u03C0"], [120546, 1, "\u03B1"], [120547, 1, "\u03B2"], [120548, 1, "\u03B3"], [120549, 1, "\u03B4"], [120550, 1, "\u03B5"], [120551, 1, "\u03B6"], [120552, 1, "\u03B7"], [120553, 1, "\u03B8"], [120554, 1, "\u03B9"], [120555, 1, "\u03BA"], [120556, 1, "\u03BB"], [120557, 1, "\u03BC"], [120558, 1, "\u03BD"], [120559, 1, "\u03BE"], [120560, 1, "\u03BF"], [120561, 1, "\u03C0"], [120562, 1, "\u03C1"], [120563, 1, "\u03B8"], [120564, 1, "\u03C3"], [120565, 1, "\u03C4"], [120566, 1, "\u03C5"], [120567, 1, "\u03C6"], [120568, 1, "\u03C7"], [120569, 1, "\u03C8"], [120570, 1, "\u03C9"], [120571, 1, "\u2207"], [120572, 1, "\u03B1"], [120573, 1, "\u03B2"], [120574, 1, "\u03B3"], [120575, 1, "\u03B4"], [120576, 1, "\u03B5"], [120577, 1, "\u03B6"], [120578, 1, "\u03B7"], [120579, 1, "\u03B8"], [120580, 1, "\u03B9"], [120581, 1, "\u03BA"], [120582, 1, "\u03BB"], [120583, 1, "\u03BC"], [120584, 1, "\u03BD"], [120585, 1, "\u03BE"], [120586, 1, "\u03BF"], [120587, 1, "\u03C0"], [120588, 1, "\u03C1"], [[120589, 120590], 1, "\u03C3"], [120591, 1, "\u03C4"], [120592, 1, "\u03C5"], [120593, 1, "\u03C6"], [120594, 1, "\u03C7"], [120595, 1, "\u03C8"], [120596, 1, "\u03C9"], [120597, 1, "\u2202"], [120598, 1, "\u03B5"], [120599, 1, "\u03B8"], [120600, 1, "\u03BA"], [120601, 1, "\u03C6"], [120602, 1, "\u03C1"], [120603, 1, "\u03C0"], [120604, 1, "\u03B1"], [120605, 1, "\u03B2"], [120606, 1, "\u03B3"], [120607, 1, "\u03B4"], [120608, 1, "\u03B5"], [120609, 1, "\u03B6"], [120610, 1, "\u03B7"], [120611, 1, "\u03B8"], [120612, 1, "\u03B9"], [120613, 1, "\u03BA"], [120614, 1, "\u03BB"], [120615, 1, "\u03BC"], [120616, 1, "\u03BD"], [120617, 1, "\u03BE"], [120618, 1, "\u03BF"], [120619, 1, "\u03C0"], [120620, 1, "\u03C1"], [120621, 1, "\u03B8"], [120622, 1, "\u03C3"], [120623, 1, "\u03C4"], [120624, 1, "\u03C5"], [120625, 1, "\u03C6"], [120626, 1, "\u03C7"], [120627, 1, "\u03C8"], [120628, 1, "\u03C9"], [120629, 1, "\u2207"], [120630, 1, "\u03B1"], [120631, 1, "\u03B2"], [120632, 1, "\u03B3"], [120633, 1, "\u03B4"], [120634, 1, "\u03B5"], [120635, 1, "\u03B6"], [120636, 1, "\u03B7"], [120637, 1, "\u03B8"], [120638, 1, "\u03B9"], [120639, 1, "\u03BA"], [120640, 1, "\u03BB"], [120641, 1, "\u03BC"], [120642, 1, "\u03BD"], [120643, 1, "\u03BE"], [120644, 1, "\u03BF"], [120645, 1, "\u03C0"], [120646, 1, "\u03C1"], [[120647, 120648], 1, "\u03C3"], [120649, 1, "\u03C4"], [120650, 1, "\u03C5"], [120651, 1, "\u03C6"], [120652, 1, "\u03C7"], [120653, 1, "\u03C8"], [120654, 1, "\u03C9"], [120655, 1, "\u2202"], [120656, 1, "\u03B5"], [120657, 1, "\u03B8"], [120658, 1, "\u03BA"], [120659, 1, "\u03C6"], [120660, 1, "\u03C1"], [120661, 1, "\u03C0"], [120662, 1, "\u03B1"], [120663, 1, "\u03B2"], [120664, 1, "\u03B3"], [120665, 1, "\u03B4"], [120666, 1, "\u03B5"], [120667, 1, "\u03B6"], [120668, 1, "\u03B7"], [120669, 1, "\u03B8"], [120670, 1, "\u03B9"], [120671, 1, "\u03BA"], [120672, 1, "\u03BB"], [120673, 1, "\u03BC"], [120674, 1, "\u03BD"], [120675, 1, "\u03BE"], [120676, 1, "\u03BF"], [120677, 1, "\u03C0"], [120678, 1, "\u03C1"], [120679, 1, "\u03B8"], [120680, 1, "\u03C3"], [120681, 1, "\u03C4"], [120682, 1, "\u03C5"], [120683, 1, "\u03C6"], [120684, 1, "\u03C7"], [120685, 1, "\u03C8"], [120686, 1, "\u03C9"], [120687, 1, "\u2207"], [120688, 1, "\u03B1"], [120689, 1, "\u03B2"], [120690, 1, "\u03B3"], [120691, 1, "\u03B4"], [120692, 1, "\u03B5"], [120693, 1, "\u03B6"], [120694, 1, "\u03B7"], [120695, 1, "\u03B8"], [120696, 1, "\u03B9"], [120697, 1, "\u03BA"], [120698, 1, "\u03BB"], [120699, 1, "\u03BC"], [120700, 1, "\u03BD"], [120701, 1, "\u03BE"], [120702, 1, "\u03BF"], [120703, 1, "\u03C0"], [120704, 1, "\u03C1"], [[120705, 120706], 1, "\u03C3"], [120707, 1, "\u03C4"], [120708, 1, "\u03C5"], [120709, 1, "\u03C6"], [120710, 1, "\u03C7"], [120711, 1, "\u03C8"], [120712, 1, "\u03C9"], [120713, 1, "\u2202"], [120714, 1, "\u03B5"], [120715, 1, "\u03B8"], [120716, 1, "\u03BA"], [120717, 1, "\u03C6"], [120718, 1, "\u03C1"], [120719, 1, "\u03C0"], [120720, 1, "\u03B1"], [120721, 1, "\u03B2"], [120722, 1, "\u03B3"], [120723, 1, "\u03B4"], [120724, 1, "\u03B5"], [120725, 1, "\u03B6"], [120726, 1, "\u03B7"], [120727, 1, "\u03B8"], [120728, 1, "\u03B9"], [120729, 1, "\u03BA"], [120730, 1, "\u03BB"], [120731, 1, "\u03BC"], [120732, 1, "\u03BD"], [120733, 1, "\u03BE"], [120734, 1, "\u03BF"], [120735, 1, "\u03C0"], [120736, 1, "\u03C1"], [120737, 1, "\u03B8"], [120738, 1, "\u03C3"], [120739, 1, "\u03C4"], [120740, 1, "\u03C5"], [120741, 1, "\u03C6"], [120742, 1, "\u03C7"], [120743, 1, "\u03C8"], [120744, 1, "\u03C9"], [120745, 1, "\u2207"], [120746, 1, "\u03B1"], [120747, 1, "\u03B2"], [120748, 1, "\u03B3"], [120749, 1, "\u03B4"], [120750, 1, "\u03B5"], [120751, 1, "\u03B6"], [120752, 1, "\u03B7"], [120753, 1, "\u03B8"], [120754, 1, "\u03B9"], [120755, 1, "\u03BA"], [120756, 1, "\u03BB"], [120757, 1, "\u03BC"], [120758, 1, "\u03BD"], [120759, 1, "\u03BE"], [120760, 1, "\u03BF"], [120761, 1, "\u03C0"], [120762, 1, "\u03C1"], [[120763, 120764], 1, "\u03C3"], [120765, 1, "\u03C4"], [120766, 1, "\u03C5"], [120767, 1, "\u03C6"], [120768, 1, "\u03C7"], [120769, 1, "\u03C8"], [120770, 1, "\u03C9"], [120771, 1, "\u2202"], [120772, 1, "\u03B5"], [120773, 1, "\u03B8"], [120774, 1, "\u03BA"], [120775, 1, "\u03C6"], [120776, 1, "\u03C1"], [120777, 1, "\u03C0"], [[120778, 120779], 1, "\u03DD"], [[120780, 120781], 3], [120782, 1, "0"], [120783, 1, "1"], [120784, 1, "2"], [120785, 1, "3"], [120786, 1, "4"], [120787, 1, "5"], [120788, 1, "6"], [120789, 1, "7"], [120790, 1, "8"], [120791, 1, "9"], [120792, 1, "0"], [120793, 1, "1"], [120794, 1, "2"], [120795, 1, "3"], [120796, 1, "4"], [120797, 1, "5"], [120798, 1, "6"], [120799, 1, "7"], [120800, 1, "8"], [120801, 1, "9"], [120802, 1, "0"], [120803, 1, "1"], [120804, 1, "2"], [120805, 1, "3"], [120806, 1, "4"], [120807, 1, "5"], [120808, 1, "6"], [120809, 1, "7"], [120810, 1, "8"], [120811, 1, "9"], [120812, 1, "0"], [120813, 1, "1"], [120814, 1, "2"], [120815, 1, "3"], [120816, 1, "4"], [120817, 1, "5"], [120818, 1, "6"], [120819, 1, "7"], [120820, 1, "8"], [120821, 1, "9"], [120822, 1, "0"], [120823, 1, "1"], [120824, 1, "2"], [120825, 1, "3"], [120826, 1, "4"], [120827, 1, "5"], [120828, 1, "6"], [120829, 1, "7"], [120830, 1, "8"], [120831, 1, "9"], [[120832, 121343], 2], [[121344, 121398], 2], [[121399, 121402], 2], [[121403, 121452], 2], [[121453, 121460], 2], [121461, 2], [[121462, 121475], 2], [121476, 2], [[121477, 121483], 2], [[121484, 121498], 3], [[121499, 121503], 2], [121504, 3], [[121505, 121519], 2], [[121520, 122623], 3], [[122624, 122654], 2], [[122655, 122879], 3], [[122880, 122886], 2], [122887, 3], [[122888, 122904], 2], [[122905, 122906], 3], [[122907, 122913], 2], [122914, 3], [[122915, 122916], 2], [122917, 3], [[122918, 122922], 2], [[122923, 123135], 3], [[123136, 123180], 2], [[123181, 123183], 3], [[123184, 123197], 2], [[123198, 123199], 3], [[123200, 123209], 2], [[123210, 123213], 3], [123214, 2], [123215, 2], [[123216, 123535], 3], [[123536, 123566], 2], [[123567, 123583], 3], [[123584, 123641], 2], [[123642, 123646], 3], [123647, 2], [[123648, 124895], 3], [[124896, 124902], 2], [124903, 3], [[124904, 124907], 2], [124908, 3], [[124909, 124910], 2], [124911, 3], [[124912, 124926], 2], [124927, 3], [[124928, 125124], 2], [[125125, 125126], 3], [[125127, 125135], 2], [[125136, 125142], 2], [[125143, 125183], 3], [125184, 1, "\u{1E922}"], [125185, 1, "\u{1E923}"], [125186, 1, "\u{1E924}"], [125187, 1, "\u{1E925}"], [125188, 1, "\u{1E926}"], [125189, 1, "\u{1E927}"], [125190, 1, "\u{1E928}"], [125191, 1, "\u{1E929}"], [125192, 1, "\u{1E92A}"], [125193, 1, "\u{1E92B}"], [125194, 1, "\u{1E92C}"], [125195, 1, "\u{1E92D}"], [125196, 1, "\u{1E92E}"], [125197, 1, "\u{1E92F}"], [125198, 1, "\u{1E930}"], [125199, 1, "\u{1E931}"], [125200, 1, "\u{1E932}"], [125201, 1, "\u{1E933}"], [125202, 1, "\u{1E934}"], [125203, 1, "\u{1E935}"], [125204, 1, "\u{1E936}"], [125205, 1, "\u{1E937}"], [125206, 1, "\u{1E938}"], [125207, 1, "\u{1E939}"], [125208, 1, "\u{1E93A}"], [125209, 1, "\u{1E93B}"], [125210, 1, "\u{1E93C}"], [125211, 1, "\u{1E93D}"], [125212, 1, "\u{1E93E}"], [125213, 1, "\u{1E93F}"], [125214, 1, "\u{1E940}"], [125215, 1, "\u{1E941}"], [125216, 1, "\u{1E942}"], [125217, 1, "\u{1E943}"], [[125218, 125258], 2], [125259, 2], [[125260, 125263], 3], [[125264, 125273], 2], [[125274, 125277], 3], [[125278, 125279], 2], [[125280, 126064], 3], [[126065, 126132], 2], [[126133, 126208], 3], [[126209, 126269], 2], [[126270, 126463], 3], [126464, 1, "\u0627"], [126465, 1, "\u0628"], [126466, 1, "\u062C"], [126467, 1, "\u062F"], [126468, 3], [126469, 1, "\u0648"], [126470, 1, "\u0632"], [126471, 1, "\u062D"], [126472, 1, "\u0637"], [126473, 1, "\u064A"], [126474, 1, "\u0643"], [126475, 1, "\u0644"], [126476, 1, "\u0645"], [126477, 1, "\u0646"], [126478, 1, "\u0633"], [126479, 1, "\u0639"], [126480, 1, "\u0641"], [126481, 1, "\u0635"], [126482, 1, "\u0642"], [126483, 1, "\u0631"], [126484, 1, "\u0634"], [126485, 1, "\u062A"], [126486, 1, "\u062B"], [126487, 1, "\u062E"], [126488, 1, "\u0630"], [126489, 1, "\u0636"], [126490, 1, "\u0638"], [126491, 1, "\u063A"], [126492, 1, "\u066E"], [126493, 1, "\u06BA"], [126494, 1, "\u06A1"], [126495, 1, "\u066F"], [126496, 3], [126497, 1, "\u0628"], [126498, 1, "\u062C"], [126499, 3], [126500, 1, "\u0647"], [[126501, 126502], 3], [126503, 1, "\u062D"], [126504, 3], [126505, 1, "\u064A"], [126506, 1, "\u0643"], [126507, 1, "\u0644"], [126508, 1, "\u0645"], [126509, 1, "\u0646"], [126510, 1, "\u0633"], [126511, 1, "\u0639"], [126512, 1, "\u0641"], [126513, 1, "\u0635"], [126514, 1, "\u0642"], [126515, 3], [126516, 1, "\u0634"], [126517, 1, "\u062A"], [126518, 1, "\u062B"], [126519, 1, "\u062E"], [126520, 3], [126521, 1, "\u0636"], [126522, 3], [126523, 1, "\u063A"], [[126524, 126529], 3], [126530, 1, "\u062C"], [[126531, 126534], 3], [126535, 1, "\u062D"], [126536, 3], [126537, 1, "\u064A"], [126538, 3], [126539, 1, "\u0644"], [126540, 3], [126541, 1, "\u0646"], [126542, 1, "\u0633"], [126543, 1, "\u0639"], [126544, 3], [126545, 1, "\u0635"], [126546, 1, "\u0642"], [126547, 3], [126548, 1, "\u0634"], [[126549, 126550], 3], [126551, 1, "\u062E"], [126552, 3], [126553, 1, "\u0636"], [126554, 3], [126555, 1, "\u063A"], [126556, 3], [126557, 1, "\u06BA"], [126558, 3], [126559, 1, "\u066F"], [126560, 3], [126561, 1, "\u0628"], [126562, 1, "\u062C"], [126563, 3], [126564, 1, "\u0647"], [[126565, 126566], 3], [126567, 1, "\u062D"], [126568, 1, "\u0637"], [126569, 1, "\u064A"], [126570, 1, "\u0643"], [126571, 3], [126572, 1, "\u0645"], [126573, 1, "\u0646"], [126574, 1, "\u0633"], [126575, 1, "\u0639"], [126576, 1, "\u0641"], [126577, 1, "\u0635"], [126578, 1, "\u0642"], [126579, 3], [126580, 1, "\u0634"], [126581, 1, "\u062A"], [126582, 1, "\u062B"], [126583, 1, "\u062E"], [126584, 3], [126585, 1, "\u0636"], [126586, 1, "\u0638"], [126587, 1, "\u063A"], [126588, 1, "\u066E"], [126589, 3], [126590, 1, "\u06A1"], [126591, 3], [126592, 1, "\u0627"], [126593, 1, "\u0628"], [126594, 1, "\u062C"], [126595, 1, "\u062F"], [126596, 1, "\u0647"], [126597, 1, "\u0648"], [126598, 1, "\u0632"], [126599, 1, "\u062D"], [126600, 1, "\u0637"], [126601, 1, "\u064A"], [126602, 3], [126603, 1, "\u0644"], [126604, 1, "\u0645"], [126605, 1, "\u0646"], [126606, 1, "\u0633"], [126607, 1, "\u0639"], [126608, 1, "\u0641"], [126609, 1, "\u0635"], [126610, 1, "\u0642"], [126611, 1, "\u0631"], [126612, 1, "\u0634"], [126613, 1, "\u062A"], [126614, 1, "\u062B"], [126615, 1, "\u062E"], [126616, 1, "\u0630"], [126617, 1, "\u0636"], [126618, 1, "\u0638"], [126619, 1, "\u063A"], [[126620, 126624], 3], [126625, 1, "\u0628"], [126626, 1, "\u062C"], [126627, 1, "\u062F"], [126628, 3], [126629, 1, "\u0648"], [126630, 1, "\u0632"], [126631, 1, "\u062D"], [126632, 1, "\u0637"], [126633, 1, "\u064A"], [126634, 3], [126635, 1, "\u0644"], [126636, 1, "\u0645"], [126637, 1, "\u0646"], [126638, 1, "\u0633"], [126639, 1, "\u0639"], [126640, 1, "\u0641"], [126641, 1, "\u0635"], [126642, 1, "\u0642"], [126643, 1, "\u0631"], [126644, 1, "\u0634"], [126645, 1, "\u062A"], [126646, 1, "\u062B"], [126647, 1, "\u062E"], [126648, 1, "\u0630"], [126649, 1, "\u0636"], [126650, 1, "\u0638"], [126651, 1, "\u063A"], [[126652, 126703], 3], [[126704, 126705], 2], [[126706, 126975], 3], [[126976, 127019], 2], [[127020, 127023], 3], [[127024, 127123], 2], [[127124, 127135], 3], [[127136, 127150], 2], [[127151, 127152], 3], [[127153, 127166], 2], [127167, 2], [127168, 3], [[127169, 127183], 2], [127184, 3], [[127185, 127199], 2], [[127200, 127221], 2], [[127222, 127231], 3], [127232, 3], [127233, 5, "0,"], [127234, 5, "1,"], [127235, 5, "2,"], [127236, 5, "3,"], [127237, 5, "4,"], [127238, 5, "5,"], [127239, 5, "6,"], [127240, 5, "7,"], [127241, 5, "8,"], [127242, 5, "9,"], [[127243, 127244], 2], [[127245, 127247], 2], [127248, 5, "(a)"], [127249, 5, "(b)"], [127250, 5, "(c)"], [127251, 5, "(d)"], [127252, 5, "(e)"], [127253, 5, "(f)"], [127254, 5, "(g)"], [127255, 5, "(h)"], [127256, 5, "(i)"], [127257, 5, "(j)"], [127258, 5, "(k)"], [127259, 5, "(l)"], [127260, 5, "(m)"], [127261, 5, "(n)"], [127262, 5, "(o)"], [127263, 5, "(p)"], [127264, 5, "(q)"], [127265, 5, "(r)"], [127266, 5, "(s)"], [127267, 5, "(t)"], [127268, 5, "(u)"], [127269, 5, "(v)"], [127270, 5, "(w)"], [127271, 5, "(x)"], [127272, 5, "(y)"], [127273, 5, "(z)"], [127274, 1, "\u3014s\u3015"], [127275, 1, "c"], [127276, 1, "r"], [127277, 1, "cd"], [127278, 1, "wz"], [127279, 2], [127280, 1, "a"], [127281, 1, "b"], [127282, 1, "c"], [127283, 1, "d"], [127284, 1, "e"], [127285, 1, "f"], [127286, 1, "g"], [127287, 1, "h"], [127288, 1, "i"], [127289, 1, "j"], [127290, 1, "k"], [127291, 1, "l"], [127292, 1, "m"], [127293, 1, "n"], [127294, 1, "o"], [127295, 1, "p"], [127296, 1, "q"], [127297, 1, "r"], [127298, 1, "s"], [127299, 1, "t"], [127300, 1, "u"], [127301, 1, "v"], [127302, 1, "w"], [127303, 1, "x"], [127304, 1, "y"], [127305, 1, "z"], [127306, 1, "hv"], [127307, 1, "mv"], [127308, 1, "sd"], [127309, 1, "ss"], [127310, 1, "ppv"], [127311, 1, "wc"], [[127312, 127318], 2], [127319, 2], [[127320, 127326], 2], [127327, 2], [[127328, 127337], 2], [127338, 1, "mc"], [127339, 1, "md"], [127340, 1, "mr"], [[127341, 127343], 2], [[127344, 127352], 2], [127353, 2], [127354, 2], [[127355, 127356], 2], [[127357, 127358], 2], [127359, 2], [[127360, 127369], 2], [[127370, 127373], 2], [[127374, 127375], 2], [127376, 1, "dj"], [[127377, 127386], 2], [[127387, 127404], 2], [127405, 2], [[127406, 127461], 3], [[127462, 127487], 2], [127488, 1, "\u307B\u304B"], [127489, 1, "\u30B3\u30B3"], [127490, 1, "\u30B5"], [[127491, 127503], 3], [127504, 1, "\u624B"], [127505, 1, "\u5B57"], [127506, 1, "\u53CC"], [127507, 1, "\u30C7"], [127508, 1, "\u4E8C"], [127509, 1, "\u591A"], [127510, 1, "\u89E3"], [127511, 1, "\u5929"], [127512, 1, "\u4EA4"], [127513, 1, "\u6620"], [127514, 1, "\u7121"], [127515, 1, "\u6599"], [127516, 1, "\u524D"], [127517, 1, "\u5F8C"], [127518, 1, "\u518D"], [127519, 1, "\u65B0"], [127520, 1, "\u521D"], [127521, 1, "\u7D42"], [127522, 1, "\u751F"], [127523, 1, "\u8CA9"], [127524, 1, "\u58F0"], [127525, 1, "\u5439"], [127526, 1, "\u6F14"], [127527, 1, "\u6295"], [127528, 1, "\u6355"], [127529, 1, "\u4E00"], [127530, 1, "\u4E09"], [127531, 1, "\u904A"], [127532, 1, "\u5DE6"], [127533, 1, "\u4E2D"], [127534, 1, "\u53F3"], [127535, 1, "\u6307"], [127536, 1, "\u8D70"], [127537, 1, "\u6253"], [127538, 1, "\u7981"], [127539, 1, "\u7A7A"], [127540, 1, "\u5408"], [127541, 1, "\u6E80"], [127542, 1, "\u6709"], [127543, 1, "\u6708"], [127544, 1, "\u7533"], [127545, 1, "\u5272"], [127546, 1, "\u55B6"], [127547, 1, "\u914D"], [[127548, 127551], 3], [127552, 1, "\u3014\u672C\u3015"], [127553, 1, "\u3014\u4E09\u3015"], [127554, 1, "\u3014\u4E8C\u3015"], [127555, 1, "\u3014\u5B89\u3015"], [127556, 1, "\u3014\u70B9\u3015"], [127557, 1, "\u3014\u6253\u3015"], [127558, 1, "\u3014\u76D7\u3015"], [127559, 1, "\u3014\u52DD\u3015"], [127560, 1, "\u3014\u6557\u3015"], [[127561, 127567], 3], [127568, 1, "\u5F97"], [127569, 1, "\u53EF"], [[127570, 127583], 3], [[127584, 127589], 2], [[127590, 127743], 3], [[127744, 127776], 2], [[127777, 127788], 2], [[127789, 127791], 2], [[127792, 127797], 2], [127798, 2], [[127799, 127868], 2], [127869, 2], [[127870, 127871], 2], [[127872, 127891], 2], [[127892, 127903], 2], [[127904, 127940], 2], [127941, 2], [[127942, 127946], 2], [[127947, 127950], 2], [[127951, 127955], 2], [[127956, 127967], 2], [[127968, 127984], 2], [[127985, 127991], 2], [[127992, 127999], 2], [[128e3, 128062], 2], [128063, 2], [128064, 2], [128065, 2], [[128066, 128247], 2], [128248, 2], [[128249, 128252], 2], [[128253, 128254], 2], [128255, 2], [[128256, 128317], 2], [[128318, 128319], 2], [[128320, 128323], 2], [[128324, 128330], 2], [[128331, 128335], 2], [[128336, 128359], 2], [[128360, 128377], 2], [128378, 2], [[128379, 128419], 2], [128420, 2], [[128421, 128506], 2], [[128507, 128511], 2], [128512, 2], [[128513, 128528], 2], [128529, 2], [[128530, 128532], 2], [128533, 2], [128534, 2], [128535, 2], [128536, 2], [128537, 2], [128538, 2], [128539, 2], [[128540, 128542], 2], [128543, 2], [[128544, 128549], 2], [[128550, 128551], 2], [[128552, 128555], 2], [128556, 2], [128557, 2], [[128558, 128559], 2], [[128560, 128563], 2], [128564, 2], [[128565, 128576], 2], [[128577, 128578], 2], [[128579, 128580], 2], [[128581, 128591], 2], [[128592, 128639], 2], [[128640, 128709], 2], [[128710, 128719], 2], [128720, 2], [[128721, 128722], 2], [[128723, 128724], 2], [128725, 2], [[128726, 128727], 2], [[128728, 128732], 3], [[128733, 128735], 2], [[128736, 128748], 2], [[128749, 128751], 3], [[128752, 128755], 2], [[128756, 128758], 2], [[128759, 128760], 2], [128761, 2], [128762, 2], [[128763, 128764], 2], [[128765, 128767], 3], [[128768, 128883], 2], [[128884, 128895], 3], [[128896, 128980], 2], [[128981, 128984], 2], [[128985, 128991], 3], [[128992, 129003], 2], [[129004, 129007], 3], [129008, 2], [[129009, 129023], 3], [[129024, 129035], 2], [[129036, 129039], 3], [[129040, 129095], 2], [[129096, 129103], 3], [[129104, 129113], 2], [[129114, 129119], 3], [[129120, 129159], 2], [[129160, 129167], 3], [[129168, 129197], 2], [[129198, 129199], 3], [[129200, 129201], 2], [[129202, 129279], 3], [[129280, 129291], 2], [129292, 2], [[129293, 129295], 2], [[129296, 129304], 2], [[129305, 129310], 2], [129311, 2], [[129312, 129319], 2], [[129320, 129327], 2], [129328, 2], [[129329, 129330], 2], [[129331, 129342], 2], [129343, 2], [[129344, 129355], 2], [129356, 2], [[129357, 129359], 2], [[129360, 129374], 2], [[129375, 129387], 2], [[129388, 129392], 2], [129393, 2], [129394, 2], [[129395, 129398], 2], [[129399, 129400], 2], [129401, 2], [129402, 2], [129403, 2], [[129404, 129407], 2], [[129408, 129412], 2], [[129413, 129425], 2], [[129426, 129431], 2], [[129432, 129442], 2], [[129443, 129444], 2], [[129445, 129450], 2], [[129451, 129453], 2], [[129454, 129455], 2], [[129456, 129465], 2], [[129466, 129471], 2], [129472, 2], [[129473, 129474], 2], [[129475, 129482], 2], [129483, 2], [129484, 2], [[129485, 129487], 2], [[129488, 129510], 2], [[129511, 129535], 2], [[129536, 129619], 2], [[129620, 129631], 3], [[129632, 129645], 2], [[129646, 129647], 3], [[129648, 129651], 2], [129652, 2], [[129653, 129655], 3], [[129656, 129658], 2], [[129659, 129660], 2], [[129661, 129663], 3], [[129664, 129666], 2], [[129667, 129670], 2], [[129671, 129679], 3], [[129680, 129685], 2], [[129686, 129704], 2], [[129705, 129708], 2], [[129709, 129711], 3], [[129712, 129718], 2], [[129719, 129722], 2], [[129723, 129727], 3], [[129728, 129730], 2], [[129731, 129733], 2], [[129734, 129743], 3], [[129744, 129750], 2], [[129751, 129753], 2], [[129754, 129759], 3], [[129760, 129767], 2], [[129768, 129775], 3], [[129776, 129782], 2], [[129783, 129791], 3], [[129792, 129938], 2], [129939, 3], [[129940, 129994], 2], [[129995, 130031], 3], [130032, 1, "0"], [130033, 1, "1"], [130034, 1, "2"], [130035, 1, "3"], [130036, 1, "4"], [130037, 1, "5"], [130038, 1, "6"], [130039, 1, "7"], [130040, 1, "8"], [130041, 1, "9"], [[130042, 131069], 3], [[131070, 131071], 3], [[131072, 173782], 2], [[173783, 173789], 2], [[173790, 173791], 2], [[173792, 173823], 3], [[173824, 177972], 2], [[177973, 177976], 2], [[177977, 177983], 3], [[177984, 178205], 2], [[178206, 178207], 3], [[178208, 183969], 2], [[183970, 183983], 3], [[183984, 191456], 2], [[191457, 194559], 3], [194560, 1, "\u4E3D"], [194561, 1, "\u4E38"], [194562, 1, "\u4E41"], [194563, 1, "\u{20122}"], [194564, 1, "\u4F60"], [194565, 1, "\u4FAE"], [194566, 1, "\u4FBB"], [194567, 1, "\u5002"], [194568, 1, "\u507A"], [194569, 1, "\u5099"], [194570, 1, "\u50E7"], [194571, 1, "\u50CF"], [194572, 1, "\u349E"], [194573, 1, "\u{2063A}"], [194574, 1, "\u514D"], [194575, 1, "\u5154"], [194576, 1, "\u5164"], [194577, 1, "\u5177"], [194578, 1, "\u{2051C}"], [194579, 1, "\u34B9"], [194580, 1, "\u5167"], [194581, 1, "\u518D"], [194582, 1, "\u{2054B}"], [194583, 1, "\u5197"], [194584, 1, "\u51A4"], [194585, 1, "\u4ECC"], [194586, 1, "\u51AC"], [194587, 1, "\u51B5"], [194588, 1, "\u{291DF}"], [194589, 1, "\u51F5"], [194590, 1, "\u5203"], [194591, 1, "\u34DF"], [194592, 1, "\u523B"], [194593, 1, "\u5246"], [194594, 1, "\u5272"], [194595, 1, "\u5277"], [194596, 1, "\u3515"], [194597, 1, "\u52C7"], [194598, 1, "\u52C9"], [194599, 1, "\u52E4"], [194600, 1, "\u52FA"], [194601, 1, "\u5305"], [194602, 1, "\u5306"], [194603, 1, "\u5317"], [194604, 1, "\u5349"], [194605, 1, "\u5351"], [194606, 1, "\u535A"], [194607, 1, "\u5373"], [194608, 1, "\u537D"], [[194609, 194611], 1, "\u537F"], [194612, 1, "\u{20A2C}"], [194613, 1, "\u7070"], [194614, 1, "\u53CA"], [194615, 1, "\u53DF"], [194616, 1, "\u{20B63}"], [194617, 1, "\u53EB"], [194618, 1, "\u53F1"], [194619, 1, "\u5406"], [194620, 1, "\u549E"], [194621, 1, "\u5438"], [194622, 1, "\u5448"], [194623, 1, "\u5468"], [194624, 1, "\u54A2"], [194625, 1, "\u54F6"], [194626, 1, "\u5510"], [194627, 1, "\u5553"], [194628, 1, "\u5563"], [[194629, 194630], 1, "\u5584"], [194631, 1, "\u5599"], [194632, 1, "\u55AB"], [194633, 1, "\u55B3"], [194634, 1, "\u55C2"], [194635, 1, "\u5716"], [194636, 1, "\u5606"], [194637, 1, "\u5717"], [194638, 1, "\u5651"], [194639, 1, "\u5674"], [194640, 1, "\u5207"], [194641, 1, "\u58EE"], [194642, 1, "\u57CE"], [194643, 1, "\u57F4"], [194644, 1, "\u580D"], [194645, 1, "\u578B"], [194646, 1, "\u5832"], [194647, 1, "\u5831"], [194648, 1, "\u58AC"], [194649, 1, "\u{214E4}"], [194650, 1, "\u58F2"], [194651, 1, "\u58F7"], [194652, 1, "\u5906"], [194653, 1, "\u591A"], [194654, 1, "\u5922"], [194655, 1, "\u5962"], [194656, 1, "\u{216A8}"], [194657, 1, "\u{216EA}"], [194658, 1, "\u59EC"], [194659, 1, "\u5A1B"], [194660, 1, "\u5A27"], [194661, 1, "\u59D8"], [194662, 1, "\u5A66"], [194663, 1, "\u36EE"], [194664, 3], [194665, 1, "\u5B08"], [[194666, 194667], 1, "\u5B3E"], [194668, 1, "\u{219C8}"], [194669, 1, "\u5BC3"], [194670, 1, "\u5BD8"], [194671, 1, "\u5BE7"], [194672, 1, "\u5BF3"], [194673, 1, "\u{21B18}"], [194674, 1, "\u5BFF"], [194675, 1, "\u5C06"], [194676, 3], [194677, 1, "\u5C22"], [194678, 1, "\u3781"], [194679, 1, "\u5C60"], [194680, 1, "\u5C6E"], [194681, 1, "\u5CC0"], [194682, 1, "\u5C8D"], [194683, 1, "\u{21DE4}"], [194684, 1, "\u5D43"], [194685, 1, "\u{21DE6}"], [194686, 1, "\u5D6E"], [194687, 1, "\u5D6B"], [194688, 1, "\u5D7C"], [194689, 1, "\u5DE1"], [194690, 1, "\u5DE2"], [194691, 1, "\u382F"], [194692, 1, "\u5DFD"], [194693, 1, "\u5E28"], [194694, 1, "\u5E3D"], [194695, 1, "\u5E69"], [194696, 1, "\u3862"], [194697, 1, "\u{22183}"], [194698, 1, "\u387C"], [194699, 1, "\u5EB0"], [194700, 1, "\u5EB3"], [194701, 1, "\u5EB6"], [194702, 1, "\u5ECA"], [194703, 1, "\u{2A392}"], [194704, 1, "\u5EFE"], [[194705, 194706], 1, "\u{22331}"], [194707, 1, "\u8201"], [[194708, 194709], 1, "\u5F22"], [194710, 1, "\u38C7"], [194711, 1, "\u{232B8}"], [194712, 1, "\u{261DA}"], [194713, 1, "\u5F62"], [194714, 1, "\u5F6B"], [194715, 1, "\u38E3"], [194716, 1, "\u5F9A"], [194717, 1, "\u5FCD"], [194718, 1, "\u5FD7"], [194719, 1, "\u5FF9"], [194720, 1, "\u6081"], [194721, 1, "\u393A"], [194722, 1, "\u391C"], [194723, 1, "\u6094"], [194724, 1, "\u{226D4}"], [194725, 1, "\u60C7"], [194726, 1, "\u6148"], [194727, 1, "\u614C"], [194728, 1, "\u614E"], [194729, 1, "\u614C"], [194730, 1, "\u617A"], [194731, 1, "\u618E"], [194732, 1, "\u61B2"], [194733, 1, "\u61A4"], [194734, 1, "\u61AF"], [194735, 1, "\u61DE"], [194736, 1, "\u61F2"], [194737, 1, "\u61F6"], [194738, 1, "\u6210"], [194739, 1, "\u621B"], [194740, 1, "\u625D"], [194741, 1, "\u62B1"], [194742, 1, "\u62D4"], [194743, 1, "\u6350"], [194744, 1, "\u{22B0C}"], [194745, 1, "\u633D"], [194746, 1, "\u62FC"], [194747, 1, "\u6368"], [194748, 1, "\u6383"], [194749, 1, "\u63E4"], [194750, 1, "\u{22BF1}"], [194751, 1, "\u6422"], [194752, 1, "\u63C5"], [194753, 1, "\u63A9"], [194754, 1, "\u3A2E"], [194755, 1, "\u6469"], [194756, 1, "\u647E"], [194757, 1, "\u649D"], [194758, 1, "\u6477"], [194759, 1, "\u3A6C"], [194760, 1, "\u654F"], [194761, 1, "\u656C"], [194762, 1, "\u{2300A}"], [194763, 1, "\u65E3"], [194764, 1, "\u66F8"], [194765, 1, "\u6649"], [194766, 1, "\u3B19"], [194767, 1, "\u6691"], [194768, 1, "\u3B08"], [194769, 1, "\u3AE4"], [194770, 1, "\u5192"], [194771, 1, "\u5195"], [194772, 1, "\u6700"], [194773, 1, "\u669C"], [194774, 1, "\u80AD"], [194775, 1, "\u43D9"], [194776, 1, "\u6717"], [194777, 1, "\u671B"], [194778, 1, "\u6721"], [194779, 1, "\u675E"], [194780, 1, "\u6753"], [194781, 1, "\u{233C3}"], [194782, 1, "\u3B49"], [194783, 1, "\u67FA"], [194784, 1, "\u6785"], [194785, 1, "\u6852"], [194786, 1, "\u6885"], [194787, 1, "\u{2346D}"], [194788, 1, "\u688E"], [194789, 1, "\u681F"], [194790, 1, "\u6914"], [194791, 1, "\u3B9D"], [194792, 1, "\u6942"], [194793, 1, "\u69A3"], [194794, 1, "\u69EA"], [194795, 1, "\u6AA8"], [194796, 1, "\u{236A3}"], [194797, 1, "\u6ADB"], [194798, 1, "\u3C18"], [194799, 1, "\u6B21"], [194800, 1, "\u{238A7}"], [194801, 1, "\u6B54"], [194802, 1, "\u3C4E"], [194803, 1, "\u6B72"], [194804, 1, "\u6B9F"], [194805, 1, "\u6BBA"], [194806, 1, "\u6BBB"], [194807, 1, "\u{23A8D}"], [194808, 1, "\u{21D0B}"], [194809, 1, "\u{23AFA}"], [194810, 1, "\u6C4E"], [194811, 1, "\u{23CBC}"], [194812, 1, "\u6CBF"], [194813, 1, "\u6CCD"], [194814, 1, "\u6C67"], [194815, 1, "\u6D16"], [194816, 1, "\u6D3E"], [194817, 1, "\u6D77"], [194818, 1, "\u6D41"], [194819, 1, "\u6D69"], [194820, 1, "\u6D78"], [194821, 1, "\u6D85"], [194822, 1, "\u{23D1E}"], [194823, 1, "\u6D34"], [194824, 1, "\u6E2F"], [194825, 1, "\u6E6E"], [194826, 1, "\u3D33"], [194827, 1, "\u6ECB"], [194828, 1, "\u6EC7"], [194829, 1, "\u{23ED1}"], [194830, 1, "\u6DF9"], [194831, 1, "\u6F6E"], [194832, 1, "\u{23F5E}"], [194833, 1, "\u{23F8E}"], [194834, 1, "\u6FC6"], [194835, 1, "\u7039"], [194836, 1, "\u701E"], [194837, 1, "\u701B"], [194838, 1, "\u3D96"], [194839, 1, "\u704A"], [194840, 1, "\u707D"], [194841, 1, "\u7077"], [194842, 1, "\u70AD"], [194843, 1, "\u{20525}"], [194844, 1, "\u7145"], [194845, 1, "\u{24263}"], [194846, 1, "\u719C"], [194847, 3], [194848, 1, "\u7228"], [194849, 1, "\u7235"], [194850, 1, "\u7250"], [194851, 1, "\u{24608}"], [194852, 1, "\u7280"], [194853, 1, "\u7295"], [194854, 1, "\u{24735}"], [194855, 1, "\u{24814}"], [194856, 1, "\u737A"], [194857, 1, "\u738B"], [194858, 1, "\u3EAC"], [194859, 1, "\u73A5"], [[194860, 194861], 1, "\u3EB8"], [194862, 1, "\u7447"], [194863, 1, "\u745C"], [194864, 1, "\u7471"], [194865, 1, "\u7485"], [194866, 1, "\u74CA"], [194867, 1, "\u3F1B"], [194868, 1, "\u7524"], [194869, 1, "\u{24C36}"], [194870, 1, "\u753E"], [194871, 1, "\u{24C92}"], [194872, 1, "\u7570"], [194873, 1, "\u{2219F}"], [194874, 1, "\u7610"], [194875, 1, "\u{24FA1}"], [194876, 1, "\u{24FB8}"], [194877, 1, "\u{25044}"], [194878, 1, "\u3FFC"], [194879, 1, "\u4008"], [194880, 1, "\u76F4"], [194881, 1, "\u{250F3}"], [194882, 1, "\u{250F2}"], [194883, 1, "\u{25119}"], [194884, 1, "\u{25133}"], [194885, 1, "\u771E"], [[194886, 194887], 1, "\u771F"], [194888, 1, "\u774A"], [194889, 1, "\u4039"], [194890, 1, "\u778B"], [194891, 1, "\u4046"], [194892, 1, "\u4096"], [194893, 1, "\u{2541D}"], [194894, 1, "\u784E"], [194895, 1, "\u788C"], [194896, 1, "\u78CC"], [194897, 1, "\u40E3"], [194898, 1, "\u{25626}"], [194899, 1, "\u7956"], [194900, 1, "\u{2569A}"], [194901, 1, "\u{256C5}"], [194902, 1, "\u798F"], [194903, 1, "\u79EB"], [194904, 1, "\u412F"], [194905, 1, "\u7A40"], [194906, 1, "\u7A4A"], [194907, 1, "\u7A4F"], [194908, 1, "\u{2597C}"], [[194909, 194910], 1, "\u{25AA7}"], [194911, 3], [194912, 1, "\u4202"], [194913, 1, "\u{25BAB}"], [194914, 1, "\u7BC6"], [194915, 1, "\u7BC9"], [194916, 1, "\u4227"], [194917, 1, "\u{25C80}"], [194918, 1, "\u7CD2"], [194919, 1, "\u42A0"], [194920, 1, "\u7CE8"], [194921, 1, "\u7CE3"], [194922, 1, "\u7D00"], [194923, 1, "\u{25F86}"], [194924, 1, "\u7D63"], [194925, 1, "\u4301"], [194926, 1, "\u7DC7"], [194927, 1, "\u7E02"], [194928, 1, "\u7E45"], [194929, 1, "\u4334"], [194930, 1, "\u{26228}"], [194931, 1, "\u{26247}"], [194932, 1, "\u4359"], [194933, 1, "\u{262D9}"], [194934, 1, "\u7F7A"], [194935, 1, "\u{2633E}"], [194936, 1, "\u7F95"], [194937, 1, "\u7FFA"], [194938, 1, "\u8005"], [194939, 1, "\u{264DA}"], [194940, 1, "\u{26523}"], [194941, 1, "\u8060"], [194942, 1, "\u{265A8}"], [194943, 1, "\u8070"], [194944, 1, "\u{2335F}"], [194945, 1, "\u43D5"], [194946, 1, "\u80B2"], [194947, 1, "\u8103"], [194948, 1, "\u440B"], [194949, 1, "\u813E"], [194950, 1, "\u5AB5"], [194951, 1, "\u{267A7}"], [194952, 1, "\u{267B5}"], [194953, 1, "\u{23393}"], [194954, 1, "\u{2339C}"], [194955, 1, "\u8201"], [194956, 1, "\u8204"], [194957, 1, "\u8F9E"], [194958, 1, "\u446B"], [194959, 1, "\u8291"], [194960, 1, "\u828B"], [194961, 1, "\u829D"], [194962, 1, "\u52B3"], [194963, 1, "\u82B1"], [194964, 1, "\u82B3"], [194965, 1, "\u82BD"], [194966, 1, "\u82E6"], [194967, 1, "\u{26B3C}"], [194968, 1, "\u82E5"], [194969, 1, "\u831D"], [194970, 1, "\u8363"], [194971, 1, "\u83AD"], [194972, 1, "\u8323"], [194973, 1, "\u83BD"], [194974, 1, "\u83E7"], [194975, 1, "\u8457"], [194976, 1, "\u8353"], [194977, 1, "\u83CA"], [194978, 1, "\u83CC"], [194979, 1, "\u83DC"], [194980, 1, "\u{26C36}"], [194981, 1, "\u{26D6B}"], [194982, 1, "\u{26CD5}"], [194983, 1, "\u452B"], [194984, 1, "\u84F1"], [194985, 1, "\u84F3"], [194986, 1, "\u8516"], [194987, 1, "\u{273CA}"], [194988, 1, "\u8564"], [194989, 1, "\u{26F2C}"], [194990, 1, "\u455D"], [194991, 1, "\u4561"], [194992, 1, "\u{26FB1}"], [194993, 1, "\u{270D2}"], [194994, 1, "\u456B"], [194995, 1, "\u8650"], [194996, 1, "\u865C"], [194997, 1, "\u8667"], [194998, 1, "\u8669"], [194999, 1, "\u86A9"], [195e3, 1, "\u8688"], [195001, 1, "\u870E"], [195002, 1, "\u86E2"], [195003, 1, "\u8779"], [195004, 1, "\u8728"], [195005, 1, "\u876B"], [195006, 1, "\u8786"], [195007, 3], [195008, 1, "\u87E1"], [195009, 1, "\u8801"], [195010, 1, "\u45F9"], [195011, 1, "\u8860"], [195012, 1, "\u8863"], [195013, 1, "\u{27667}"], [195014, 1, "\u88D7"], [195015, 1, "\u88DE"], [195016, 1, "\u4635"], [195017, 1, "\u88FA"], [195018, 1, "\u34BB"], [195019, 1, "\u{278AE}"], [195020, 1, "\u{27966}"], [195021, 1, "\u46BE"], [195022, 1, "\u46C7"], [195023, 1, "\u8AA0"], [195024, 1, "\u8AED"], [195025, 1, "\u8B8A"], [195026, 1, "\u8C55"], [195027, 1, "\u{27CA8}"], [195028, 1, "\u8CAB"], [195029, 1, "\u8CC1"], [195030, 1, "\u8D1B"], [195031, 1, "\u8D77"], [195032, 1, "\u{27F2F}"], [195033, 1, "\u{20804}"], [195034, 1, "\u8DCB"], [195035, 1, "\u8DBC"], [195036, 1, "\u8DF0"], [195037, 1, "\u{208DE}"], [195038, 1, "\u8ED4"], [195039, 1, "\u8F38"], [195040, 1, "\u{285D2}"], [195041, 1, "\u{285ED}"], [195042, 1, "\u9094"], [195043, 1, "\u90F1"], [195044, 1, "\u9111"], [195045, 1, "\u{2872E}"], [195046, 1, "\u911B"], [195047, 1, "\u9238"], [195048, 1, "\u92D7"], [195049, 1, "\u92D8"], [195050, 1, "\u927C"], [195051, 1, "\u93F9"], [195052, 1, "\u9415"], [195053, 1, "\u{28BFA}"], [195054, 1, "\u958B"], [195055, 1, "\u4995"], [195056, 1, "\u95B7"], [195057, 1, "\u{28D77}"], [195058, 1, "\u49E6"], [195059, 1, "\u96C3"], [195060, 1, "\u5DB2"], [195061, 1, "\u9723"], [195062, 1, "\u{29145}"], [195063, 1, "\u{2921A}"], [195064, 1, "\u4A6E"], [195065, 1, "\u4A76"], [195066, 1, "\u97E0"], [195067, 1, "\u{2940A}"], [195068, 1, "\u4AB2"], [195069, 1, "\u{29496}"], [[195070, 195071], 1, "\u980B"], [195072, 1, "\u9829"], [195073, 1, "\u{295B6}"], [195074, 1, "\u98E2"], [195075, 1, "\u4B33"], [195076, 1, "\u9929"], [195077, 1, "\u99A7"], [195078, 1, "\u99C2"], [195079, 1, "\u99FE"], [195080, 1, "\u4BCE"], [195081, 1, "\u{29B30}"], [195082, 1, "\u9B12"], [195083, 1, "\u9C40"], [195084, 1, "\u9CFD"], [195085, 1, "\u4CCE"], [195086, 1, "\u4CED"], [195087, 1, "\u9D67"], [195088, 1, "\u{2A0CE}"], [195089, 1, "\u4CF8"], [195090, 1, "\u{2A105}"], [195091, 1, "\u{2A20E}"], [195092, 1, "\u{2A291}"], [195093, 1, "\u9EBB"], [195094, 1, "\u4D56"], [195095, 1, "\u9EF9"], [195096, 1, "\u9EFE"], [195097, 1, "\u9F05"], [195098, 1, "\u9F0F"], [195099, 1, "\u9F16"], [195100, 1, "\u9F3B"], [195101, 1, "\u{2A600}"], [[195102, 196605], 3], [[196606, 196607], 3], [[196608, 201546], 2], [[201547, 262141], 3], [[262142, 262143], 3], [[262144, 327677], 3], [[327678, 327679], 3], [[327680, 393213], 3], [[393214, 393215], 3], [[393216, 458749], 3], [[458750, 458751], 3], [[458752, 524285], 3], [[524286, 524287], 3], [[524288, 589821], 3], [[589822, 589823], 3], [[589824, 655357], 3], [[655358, 655359], 3], [[655360, 720893], 3], [[720894, 720895], 3], [[720896, 786429], 3], [[786430, 786431], 3], [[786432, 851965], 3], [[851966, 851967], 3], [[851968, 917501], 3], [[917502, 917503], 3], [917504, 3], [917505, 3], [[917506, 917535], 3], [[917536, 917631], 3], [[917632, 917759], 3], [[917760, 917999], 7], [[918e3, 983037], 3], [[983038, 983039], 3], [[983040, 1048573], 3], [[1048574, 1048575], 3], [[1048576, 1114109], 3], [[1114110, 1114111], 3]];
  15185. }
  15186. });
  15187. // node_modules/tr46/lib/statusMapping.js
  15188. var require_statusMapping = __commonJS({
  15189. "node_modules/tr46/lib/statusMapping.js"(exports2, module2) {
  15190. "use strict";
  15191. module2.exports.STATUS_MAPPING = {
  15192. mapped: 1,
  15193. valid: 2,
  15194. disallowed: 3,
  15195. disallowed_STD3_valid: 4,
  15196. disallowed_STD3_mapped: 5,
  15197. deviation: 6,
  15198. ignored: 7
  15199. };
  15200. }
  15201. });
  15202. // node_modules/tr46/index.js
  15203. var require_tr46 = __commonJS({
  15204. "node_modules/tr46/index.js"(exports2, module2) {
  15205. "use strict";
  15206. var punycode = require("punycode");
  15207. var regexes = require_regexes();
  15208. var mappingTable = require_mappingTable();
  15209. var { STATUS_MAPPING } = require_statusMapping();
  15210. function containsNonASCII(str) {
  15211. return /[^\x00-\x7F]/u.test(str);
  15212. }
  15213. __name(containsNonASCII, "containsNonASCII");
  15214. function findStatus(val, { useSTD3ASCIIRules }) {
  15215. let start = 0;
  15216. let end = mappingTable.length - 1;
  15217. while (start <= end) {
  15218. const mid = Math.floor((start + end) / 2);
  15219. const target = mappingTable[mid];
  15220. const min = Array.isArray(target[0]) ? target[0][0] : target[0];
  15221. const max = Array.isArray(target[0]) ? target[0][1] : target[0];
  15222. if (min <= val && max >= val) {
  15223. if (useSTD3ASCIIRules && (target[1] === STATUS_MAPPING.disallowed_STD3_valid || target[1] === STATUS_MAPPING.disallowed_STD3_mapped)) {
  15224. return [STATUS_MAPPING.disallowed, ...target.slice(2)];
  15225. } else if (target[1] === STATUS_MAPPING.disallowed_STD3_valid) {
  15226. return [STATUS_MAPPING.valid, ...target.slice(2)];
  15227. } else if (target[1] === STATUS_MAPPING.disallowed_STD3_mapped) {
  15228. return [STATUS_MAPPING.mapped, ...target.slice(2)];
  15229. }
  15230. return target.slice(1);
  15231. } else if (min > val) {
  15232. end = mid - 1;
  15233. } else {
  15234. start = mid + 1;
  15235. }
  15236. }
  15237. return null;
  15238. }
  15239. __name(findStatus, "findStatus");
  15240. function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) {
  15241. let hasError = false;
  15242. let processed = "";
  15243. for (const ch of domainName) {
  15244. const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules });
  15245. switch (status) {
  15246. case STATUS_MAPPING.disallowed:
  15247. hasError = true;
  15248. processed += ch;
  15249. break;
  15250. case STATUS_MAPPING.ignored:
  15251. break;
  15252. case STATUS_MAPPING.mapped:
  15253. processed += mapping;
  15254. break;
  15255. case STATUS_MAPPING.deviation:
  15256. if (processingOption === "transitional") {
  15257. processed += mapping;
  15258. } else {
  15259. processed += ch;
  15260. }
  15261. break;
  15262. case STATUS_MAPPING.valid:
  15263. processed += ch;
  15264. break;
  15265. }
  15266. }
  15267. return {
  15268. string: processed,
  15269. error: hasError
  15270. };
  15271. }
  15272. __name(mapChars, "mapChars");
  15273. function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) {
  15274. if (label.normalize("NFC") !== label) {
  15275. return false;
  15276. }
  15277. const codePoints = Array.from(label);
  15278. if (checkHyphens) {
  15279. if (codePoints[2] === "-" && codePoints[3] === "-" || (label.startsWith("-") || label.endsWith("-"))) {
  15280. return false;
  15281. }
  15282. }
  15283. if (label.includes(".") || codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0])) {
  15284. return false;
  15285. }
  15286. for (const ch of codePoints) {
  15287. const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules });
  15288. if (processingOption === "transitional" && status !== STATUS_MAPPING.valid || processingOption === "nontransitional" && status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation) {
  15289. return false;
  15290. }
  15291. }
  15292. if (checkJoiners) {
  15293. let last = 0;
  15294. for (const [i, ch] of codePoints.entries()) {
  15295. if (ch === "\u200C" || ch === "\u200D") {
  15296. if (i > 0) {
  15297. if (regexes.combiningClassVirama.test(codePoints[i - 1])) {
  15298. continue;
  15299. }
  15300. if (ch === "\u200C") {
  15301. const next = codePoints.indexOf("\u200C", i + 1);
  15302. const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next);
  15303. if (regexes.validZWNJ.test(test.join(""))) {
  15304. last = i + 1;
  15305. continue;
  15306. }
  15307. }
  15308. }
  15309. return false;
  15310. }
  15311. }
  15312. }
  15313. if (checkBidi) {
  15314. let rtl;
  15315. if (regexes.bidiS1LTR.test(codePoints[0])) {
  15316. rtl = false;
  15317. } else if (regexes.bidiS1RTL.test(codePoints[0])) {
  15318. rtl = true;
  15319. } else {
  15320. return false;
  15321. }
  15322. if (rtl) {
  15323. if (!regexes.bidiS2.test(label) || !regexes.bidiS3.test(label) || regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label)) {
  15324. return false;
  15325. }
  15326. } else if (!regexes.bidiS5.test(label) || !regexes.bidiS6.test(label)) {
  15327. return false;
  15328. }
  15329. }
  15330. return true;
  15331. }
  15332. __name(validateLabel, "validateLabel");
  15333. function isBidiDomain(labels) {
  15334. const domain = labels.map((label) => {
  15335. if (label.startsWith("xn--")) {
  15336. try {
  15337. return punycode.decode(label.substring(4));
  15338. } catch (err) {
  15339. return "";
  15340. }
  15341. }
  15342. return label;
  15343. }).join(".");
  15344. return regexes.bidiDomain.test(domain);
  15345. }
  15346. __name(isBidiDomain, "isBidiDomain");
  15347. function processing(domainName, options) {
  15348. const { processingOption } = options;
  15349. let { string, error } = mapChars(domainName, options);
  15350. string = string.normalize("NFC");
  15351. const labels = string.split(".");
  15352. const isBidi = isBidiDomain(labels);
  15353. for (const [i, origLabel] of labels.entries()) {
  15354. let label = origLabel;
  15355. let curProcessing = processingOption;
  15356. if (label.startsWith("xn--")) {
  15357. try {
  15358. label = punycode.decode(label.substring(4));
  15359. labels[i] = label;
  15360. } catch (err) {
  15361. error = true;
  15362. continue;
  15363. }
  15364. curProcessing = "nontransitional";
  15365. }
  15366. if (error) {
  15367. continue;
  15368. }
  15369. const validation = validateLabel(label, {
  15370. ...options,
  15371. processingOption: curProcessing,
  15372. checkBidi: options.checkBidi && isBidi
  15373. });
  15374. if (!validation) {
  15375. error = true;
  15376. }
  15377. }
  15378. return {
  15379. string: labels.join("."),
  15380. error
  15381. };
  15382. }
  15383. __name(processing, "processing");
  15384. function toASCII(domainName, {
  15385. checkHyphens = false,
  15386. checkBidi = false,
  15387. checkJoiners = false,
  15388. useSTD3ASCIIRules = false,
  15389. processingOption = "nontransitional",
  15390. verifyDNSLength = false
  15391. } = {}) {
  15392. if (processingOption !== "transitional" && processingOption !== "nontransitional") {
  15393. throw new RangeError("processingOption must be either transitional or nontransitional");
  15394. }
  15395. const result = processing(domainName, {
  15396. processingOption,
  15397. checkHyphens,
  15398. checkBidi,
  15399. checkJoiners,
  15400. useSTD3ASCIIRules
  15401. });
  15402. let labels = result.string.split(".");
  15403. labels = labels.map((l) => {
  15404. if (containsNonASCII(l)) {
  15405. try {
  15406. return `xn--${punycode.encode(l)}`;
  15407. } catch (e) {
  15408. result.error = true;
  15409. }
  15410. }
  15411. return l;
  15412. });
  15413. if (verifyDNSLength) {
  15414. const total = labels.join(".").length;
  15415. if (total > 253 || total === 0) {
  15416. result.error = true;
  15417. }
  15418. for (let i = 0; i < labels.length; ++i) {
  15419. if (labels[i].length > 63 || labels[i].length === 0) {
  15420. result.error = true;
  15421. break;
  15422. }
  15423. }
  15424. }
  15425. if (result.error) {
  15426. return null;
  15427. }
  15428. return labels.join(".");
  15429. }
  15430. __name(toASCII, "toASCII");
  15431. function toUnicode(domainName, {
  15432. checkHyphens = false,
  15433. checkBidi = false,
  15434. checkJoiners = false,
  15435. useSTD3ASCIIRules = false,
  15436. processingOption = "nontransitional"
  15437. } = {}) {
  15438. const result = processing(domainName, {
  15439. processingOption,
  15440. checkHyphens,
  15441. checkBidi,
  15442. checkJoiners,
  15443. useSTD3ASCIIRules
  15444. });
  15445. return {
  15446. domain: result.string,
  15447. error: result.error
  15448. };
  15449. }
  15450. __name(toUnicode, "toUnicode");
  15451. module2.exports = {
  15452. toASCII,
  15453. toUnicode
  15454. };
  15455. }
  15456. });
  15457. // node_modules/whatwg-url/lib/infra.js
  15458. var require_infra = __commonJS({
  15459. "node_modules/whatwg-url/lib/infra.js"(exports2, module2) {
  15460. "use strict";
  15461. function isASCIIDigit(c) {
  15462. return c >= 48 && c <= 57;
  15463. }
  15464. __name(isASCIIDigit, "isASCIIDigit");
  15465. function isASCIIAlpha(c) {
  15466. return c >= 65 && c <= 90 || c >= 97 && c <= 122;
  15467. }
  15468. __name(isASCIIAlpha, "isASCIIAlpha");
  15469. function isASCIIAlphanumeric(c) {
  15470. return isASCIIAlpha(c) || isASCIIDigit(c);
  15471. }
  15472. __name(isASCIIAlphanumeric, "isASCIIAlphanumeric");
  15473. function isASCIIHex(c) {
  15474. return isASCIIDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102;
  15475. }
  15476. __name(isASCIIHex, "isASCIIHex");
  15477. module2.exports = {
  15478. isASCIIDigit,
  15479. isASCIIAlpha,
  15480. isASCIIAlphanumeric,
  15481. isASCIIHex
  15482. };
  15483. }
  15484. });
  15485. // node_modules/whatwg-url/lib/encoding.js
  15486. var require_encoding = __commonJS({
  15487. "node_modules/whatwg-url/lib/encoding.js"(exports2, module2) {
  15488. "use strict";
  15489. var utf8Encoder = new TextEncoder();
  15490. var utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
  15491. function utf8Encode(string) {
  15492. return utf8Encoder.encode(string);
  15493. }
  15494. __name(utf8Encode, "utf8Encode");
  15495. function utf8DecodeWithoutBOM(bytes) {
  15496. return utf8Decoder.decode(bytes);
  15497. }
  15498. __name(utf8DecodeWithoutBOM, "utf8DecodeWithoutBOM");
  15499. module2.exports = {
  15500. utf8Encode,
  15501. utf8DecodeWithoutBOM
  15502. };
  15503. }
  15504. });
  15505. // node_modules/whatwg-url/lib/percent-encoding.js
  15506. var require_percent_encoding = __commonJS({
  15507. "node_modules/whatwg-url/lib/percent-encoding.js"(exports2, module2) {
  15508. "use strict";
  15509. var { isASCIIHex } = require_infra();
  15510. var { utf8Encode } = require_encoding();
  15511. function p(char) {
  15512. return char.codePointAt(0);
  15513. }
  15514. __name(p, "p");
  15515. function percentEncode(c) {
  15516. let hex = c.toString(16).toUpperCase();
  15517. if (hex.length === 1) {
  15518. hex = `0${hex}`;
  15519. }
  15520. return `%${hex}`;
  15521. }
  15522. __name(percentEncode, "percentEncode");
  15523. function percentDecodeBytes(input) {
  15524. const output = new Uint8Array(input.byteLength);
  15525. let outputIndex = 0;
  15526. for (let i = 0; i < input.byteLength; ++i) {
  15527. const byte = input[i];
  15528. if (byte !== 37) {
  15529. output[outputIndex++] = byte;
  15530. } else if (byte === 37 && (!isASCIIHex(input[i + 1]) || !isASCIIHex(input[i + 2]))) {
  15531. output[outputIndex++] = byte;
  15532. } else {
  15533. const bytePoint = parseInt(String.fromCodePoint(input[i + 1], input[i + 2]), 16);
  15534. output[outputIndex++] = bytePoint;
  15535. i += 2;
  15536. }
  15537. }
  15538. return output.slice(0, outputIndex);
  15539. }
  15540. __name(percentDecodeBytes, "percentDecodeBytes");
  15541. function percentDecodeString(input) {
  15542. const bytes = utf8Encode(input);
  15543. return percentDecodeBytes(bytes);
  15544. }
  15545. __name(percentDecodeString, "percentDecodeString");
  15546. function isC0ControlPercentEncode(c) {
  15547. return c <= 31 || c > 126;
  15548. }
  15549. __name(isC0ControlPercentEncode, "isC0ControlPercentEncode");
  15550. var extraFragmentPercentEncodeSet = /* @__PURE__ */ new Set([p(" "), p('"'), p("<"), p(">"), p("`")]);
  15551. function isFragmentPercentEncode(c) {
  15552. return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c);
  15553. }
  15554. __name(isFragmentPercentEncode, "isFragmentPercentEncode");
  15555. var extraQueryPercentEncodeSet = /* @__PURE__ */ new Set([p(" "), p('"'), p("#"), p("<"), p(">")]);
  15556. function isQueryPercentEncode(c) {
  15557. return isC0ControlPercentEncode(c) || extraQueryPercentEncodeSet.has(c);
  15558. }
  15559. __name(isQueryPercentEncode, "isQueryPercentEncode");
  15560. function isSpecialQueryPercentEncode(c) {
  15561. return isQueryPercentEncode(c) || c === p("'");
  15562. }
  15563. __name(isSpecialQueryPercentEncode, "isSpecialQueryPercentEncode");
  15564. var extraPathPercentEncodeSet = /* @__PURE__ */ new Set([p("?"), p("`"), p("{"), p("}")]);
  15565. function isPathPercentEncode(c) {
  15566. return isQueryPercentEncode(c) || extraPathPercentEncodeSet.has(c);
  15567. }
  15568. __name(isPathPercentEncode, "isPathPercentEncode");
  15569. var extraUserinfoPercentEncodeSet = /* @__PURE__ */ new Set([p("/"), p(":"), p(";"), p("="), p("@"), p("["), p("\\"), p("]"), p("^"), p("|")]);
  15570. function isUserinfoPercentEncode(c) {
  15571. return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);
  15572. }
  15573. __name(isUserinfoPercentEncode, "isUserinfoPercentEncode");
  15574. var extraComponentPercentEncodeSet = /* @__PURE__ */ new Set([p("$"), p("%"), p("&"), p("+"), p(",")]);
  15575. function isComponentPercentEncode(c) {
  15576. return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c);
  15577. }
  15578. __name(isComponentPercentEncode, "isComponentPercentEncode");
  15579. var extraURLEncodedPercentEncodeSet = /* @__PURE__ */ new Set([p("!"), p("'"), p("("), p(")"), p("~")]);
  15580. function isURLEncodedPercentEncode(c) {
  15581. return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c);
  15582. }
  15583. __name(isURLEncodedPercentEncode, "isURLEncodedPercentEncode");
  15584. function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) {
  15585. const bytes = utf8Encode(codePoint);
  15586. let output = "";
  15587. for (const byte of bytes) {
  15588. if (!percentEncodePredicate(byte)) {
  15589. output += String.fromCharCode(byte);
  15590. } else {
  15591. output += percentEncode(byte);
  15592. }
  15593. }
  15594. return output;
  15595. }
  15596. __name(utf8PercentEncodeCodePointInternal, "utf8PercentEncodeCodePointInternal");
  15597. function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) {
  15598. return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate);
  15599. }
  15600. __name(utf8PercentEncodeCodePoint, "utf8PercentEncodeCodePoint");
  15601. function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) {
  15602. let output = "";
  15603. for (const codePoint of input) {
  15604. if (spaceAsPlus && codePoint === " ") {
  15605. output += "+";
  15606. } else {
  15607. output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate);
  15608. }
  15609. }
  15610. return output;
  15611. }
  15612. __name(utf8PercentEncodeString, "utf8PercentEncodeString");
  15613. module2.exports = {
  15614. isC0ControlPercentEncode,
  15615. isFragmentPercentEncode,
  15616. isQueryPercentEncode,
  15617. isSpecialQueryPercentEncode,
  15618. isPathPercentEncode,
  15619. isUserinfoPercentEncode,
  15620. isURLEncodedPercentEncode,
  15621. percentDecodeString,
  15622. percentDecodeBytes,
  15623. utf8PercentEncodeString,
  15624. utf8PercentEncodeCodePoint
  15625. };
  15626. }
  15627. });
  15628. // node_modules/whatwg-url/lib/url-state-machine.js
  15629. var require_url_state_machine = __commonJS({
  15630. "node_modules/whatwg-url/lib/url-state-machine.js"(exports2, module2) {
  15631. "use strict";
  15632. var tr46 = require_tr46();
  15633. var infra = require_infra();
  15634. var { utf8DecodeWithoutBOM } = require_encoding();
  15635. var {
  15636. percentDecodeString,
  15637. utf8PercentEncodeCodePoint,
  15638. utf8PercentEncodeString,
  15639. isC0ControlPercentEncode,
  15640. isFragmentPercentEncode,
  15641. isQueryPercentEncode,
  15642. isSpecialQueryPercentEncode,
  15643. isPathPercentEncode,
  15644. isUserinfoPercentEncode
  15645. } = require_percent_encoding();
  15646. function p(char) {
  15647. return char.codePointAt(0);
  15648. }
  15649. __name(p, "p");
  15650. var specialSchemes = {
  15651. ftp: 21,
  15652. file: null,
  15653. http: 80,
  15654. https: 443,
  15655. ws: 80,
  15656. wss: 443
  15657. };
  15658. var failure = Symbol("failure");
  15659. function countSymbols(str) {
  15660. return [...str].length;
  15661. }
  15662. __name(countSymbols, "countSymbols");
  15663. function at(input, idx) {
  15664. const c = input[idx];
  15665. return isNaN(c) ? void 0 : String.fromCodePoint(c);
  15666. }
  15667. __name(at, "at");
  15668. function isSingleDot(buffer) {
  15669. return buffer === "." || buffer.toLowerCase() === "%2e";
  15670. }
  15671. __name(isSingleDot, "isSingleDot");
  15672. function isDoubleDot(buffer) {
  15673. buffer = buffer.toLowerCase();
  15674. return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
  15675. }
  15676. __name(isDoubleDot, "isDoubleDot");
  15677. function isWindowsDriveLetterCodePoints(cp1, cp2) {
  15678. return infra.isASCIIAlpha(cp1) && (cp2 === p(":") || cp2 === p("|"));
  15679. }
  15680. __name(isWindowsDriveLetterCodePoints, "isWindowsDriveLetterCodePoints");
  15681. function isWindowsDriveLetterString(string) {
  15682. return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
  15683. }
  15684. __name(isWindowsDriveLetterString, "isWindowsDriveLetterString");
  15685. function isNormalizedWindowsDriveLetterString(string) {
  15686. return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";
  15687. }
  15688. __name(isNormalizedWindowsDriveLetterString, "isNormalizedWindowsDriveLetterString");
  15689. function containsForbiddenHostCodePoint(string) {
  15690. return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1;
  15691. }
  15692. __name(containsForbiddenHostCodePoint, "containsForbiddenHostCodePoint");
  15693. function containsForbiddenHostCodePointExcludingPercent(string) {
  15694. return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1;
  15695. }
  15696. __name(containsForbiddenHostCodePointExcludingPercent, "containsForbiddenHostCodePointExcludingPercent");
  15697. function isSpecialScheme(scheme) {
  15698. return specialSchemes[scheme] !== void 0;
  15699. }
  15700. __name(isSpecialScheme, "isSpecialScheme");
  15701. function isSpecial(url) {
  15702. return isSpecialScheme(url.scheme);
  15703. }
  15704. __name(isSpecial, "isSpecial");
  15705. function isNotSpecial(url) {
  15706. return !isSpecialScheme(url.scheme);
  15707. }
  15708. __name(isNotSpecial, "isNotSpecial");
  15709. function defaultPort(scheme) {
  15710. return specialSchemes[scheme];
  15711. }
  15712. __name(defaultPort, "defaultPort");
  15713. function parseIPv4Number(input) {
  15714. if (input === "") {
  15715. return failure;
  15716. }
  15717. let R = 10;
  15718. if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
  15719. input = input.substring(2);
  15720. R = 16;
  15721. } else if (input.length >= 2 && input.charAt(0) === "0") {
  15722. input = input.substring(1);
  15723. R = 8;
  15724. }
  15725. if (input === "") {
  15726. return 0;
  15727. }
  15728. let regex = /[^0-7]/u;
  15729. if (R === 10) {
  15730. regex = /[^0-9]/u;
  15731. }
  15732. if (R === 16) {
  15733. regex = /[^0-9A-Fa-f]/u;
  15734. }
  15735. if (regex.test(input)) {
  15736. return failure;
  15737. }
  15738. return parseInt(input, R);
  15739. }
  15740. __name(parseIPv4Number, "parseIPv4Number");
  15741. function parseIPv4(input) {
  15742. const parts = input.split(".");
  15743. if (parts[parts.length - 1] === "") {
  15744. if (parts.length > 1) {
  15745. parts.pop();
  15746. }
  15747. }
  15748. if (parts.length > 4) {
  15749. return failure;
  15750. }
  15751. const numbers = [];
  15752. for (const part of parts) {
  15753. const n = parseIPv4Number(part);
  15754. if (n === failure) {
  15755. return failure;
  15756. }
  15757. numbers.push(n);
  15758. }
  15759. for (let i = 0; i < numbers.length - 1; ++i) {
  15760. if (numbers[i] > 255) {
  15761. return failure;
  15762. }
  15763. }
  15764. if (numbers[numbers.length - 1] >= 256 ** (5 - numbers.length)) {
  15765. return failure;
  15766. }
  15767. let ipv4 = numbers.pop();
  15768. let counter = 0;
  15769. for (const n of numbers) {
  15770. ipv4 += n * 256 ** (3 - counter);
  15771. ++counter;
  15772. }
  15773. return ipv4;
  15774. }
  15775. __name(parseIPv4, "parseIPv4");
  15776. function serializeIPv4(address) {
  15777. let output = "";
  15778. let n = address;
  15779. for (let i = 1; i <= 4; ++i) {
  15780. output = String(n % 256) + output;
  15781. if (i !== 4) {
  15782. output = `.${output}`;
  15783. }
  15784. n = Math.floor(n / 256);
  15785. }
  15786. return output;
  15787. }
  15788. __name(serializeIPv4, "serializeIPv4");
  15789. function parseIPv6(input) {
  15790. const address = [0, 0, 0, 0, 0, 0, 0, 0];
  15791. let pieceIndex = 0;
  15792. let compress = null;
  15793. let pointer = 0;
  15794. input = Array.from(input, (c) => c.codePointAt(0));
  15795. if (input[pointer] === p(":")) {
  15796. if (input[pointer + 1] !== p(":")) {
  15797. return failure;
  15798. }
  15799. pointer += 2;
  15800. ++pieceIndex;
  15801. compress = pieceIndex;
  15802. }
  15803. while (pointer < input.length) {
  15804. if (pieceIndex === 8) {
  15805. return failure;
  15806. }
  15807. if (input[pointer] === p(":")) {
  15808. if (compress !== null) {
  15809. return failure;
  15810. }
  15811. ++pointer;
  15812. ++pieceIndex;
  15813. compress = pieceIndex;
  15814. continue;
  15815. }
  15816. let value = 0;
  15817. let length = 0;
  15818. while (length < 4 && infra.isASCIIHex(input[pointer])) {
  15819. value = value * 16 + parseInt(at(input, pointer), 16);
  15820. ++pointer;
  15821. ++length;
  15822. }
  15823. if (input[pointer] === p(".")) {
  15824. if (length === 0) {
  15825. return failure;
  15826. }
  15827. pointer -= length;
  15828. if (pieceIndex > 6) {
  15829. return failure;
  15830. }
  15831. let numbersSeen = 0;
  15832. while (input[pointer] !== void 0) {
  15833. let ipv4Piece = null;
  15834. if (numbersSeen > 0) {
  15835. if (input[pointer] === p(".") && numbersSeen < 4) {
  15836. ++pointer;
  15837. } else {
  15838. return failure;
  15839. }
  15840. }
  15841. if (!infra.isASCIIDigit(input[pointer])) {
  15842. return failure;
  15843. }
  15844. while (infra.isASCIIDigit(input[pointer])) {
  15845. const number = parseInt(at(input, pointer));
  15846. if (ipv4Piece === null) {
  15847. ipv4Piece = number;
  15848. } else if (ipv4Piece === 0) {
  15849. return failure;
  15850. } else {
  15851. ipv4Piece = ipv4Piece * 10 + number;
  15852. }
  15853. if (ipv4Piece > 255) {
  15854. return failure;
  15855. }
  15856. ++pointer;
  15857. }
  15858. address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
  15859. ++numbersSeen;
  15860. if (numbersSeen === 2 || numbersSeen === 4) {
  15861. ++pieceIndex;
  15862. }
  15863. }
  15864. if (numbersSeen !== 4) {
  15865. return failure;
  15866. }
  15867. break;
  15868. } else if (input[pointer] === p(":")) {
  15869. ++pointer;
  15870. if (input[pointer] === void 0) {
  15871. return failure;
  15872. }
  15873. } else if (input[pointer] !== void 0) {
  15874. return failure;
  15875. }
  15876. address[pieceIndex] = value;
  15877. ++pieceIndex;
  15878. }
  15879. if (compress !== null) {
  15880. let swaps = pieceIndex - compress;
  15881. pieceIndex = 7;
  15882. while (pieceIndex !== 0 && swaps > 0) {
  15883. const temp = address[compress + swaps - 1];
  15884. address[compress + swaps - 1] = address[pieceIndex];
  15885. address[pieceIndex] = temp;
  15886. --pieceIndex;
  15887. --swaps;
  15888. }
  15889. } else if (compress === null && pieceIndex !== 8) {
  15890. return failure;
  15891. }
  15892. return address;
  15893. }
  15894. __name(parseIPv6, "parseIPv6");
  15895. function serializeIPv6(address) {
  15896. let output = "";
  15897. const compress = findLongestZeroSequence(address);
  15898. let ignore0 = false;
  15899. for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
  15900. if (ignore0 && address[pieceIndex] === 0) {
  15901. continue;
  15902. } else if (ignore0) {
  15903. ignore0 = false;
  15904. }
  15905. if (compress === pieceIndex) {
  15906. const separator = pieceIndex === 0 ? "::" : ":";
  15907. output += separator;
  15908. ignore0 = true;
  15909. continue;
  15910. }
  15911. output += address[pieceIndex].toString(16);
  15912. if (pieceIndex !== 7) {
  15913. output += ":";
  15914. }
  15915. }
  15916. return output;
  15917. }
  15918. __name(serializeIPv6, "serializeIPv6");
  15919. function parseHost(input, isNotSpecialArg = false) {
  15920. if (input[0] === "[") {
  15921. if (input[input.length - 1] !== "]") {
  15922. return failure;
  15923. }
  15924. return parseIPv6(input.substring(1, input.length - 1));
  15925. }
  15926. if (isNotSpecialArg) {
  15927. return parseOpaqueHost(input);
  15928. }
  15929. const domain = utf8DecodeWithoutBOM(percentDecodeString(input));
  15930. const asciiDomain = domainToASCII(domain);
  15931. if (asciiDomain === failure) {
  15932. return failure;
  15933. }
  15934. if (containsForbiddenHostCodePoint(asciiDomain)) {
  15935. return failure;
  15936. }
  15937. if (endsInANumber(asciiDomain)) {
  15938. return parseIPv4(asciiDomain);
  15939. }
  15940. return asciiDomain;
  15941. }
  15942. __name(parseHost, "parseHost");
  15943. function endsInANumber(input) {
  15944. const parts = input.split(".");
  15945. if (parts[parts.length - 1] === "") {
  15946. if (parts.length === 1) {
  15947. return false;
  15948. }
  15949. parts.pop();
  15950. }
  15951. const last = parts[parts.length - 1];
  15952. if (parseIPv4Number(last) !== failure) {
  15953. return true;
  15954. }
  15955. if (/^[0-9]+$/u.test(last)) {
  15956. return true;
  15957. }
  15958. return false;
  15959. }
  15960. __name(endsInANumber, "endsInANumber");
  15961. function parseOpaqueHost(input) {
  15962. if (containsForbiddenHostCodePointExcludingPercent(input)) {
  15963. return failure;
  15964. }
  15965. return utf8PercentEncodeString(input, isC0ControlPercentEncode);
  15966. }
  15967. __name(parseOpaqueHost, "parseOpaqueHost");
  15968. function findLongestZeroSequence(arr) {
  15969. let maxIdx = null;
  15970. let maxLen = 1;
  15971. let currStart = null;
  15972. let currLen = 0;
  15973. for (let i = 0; i < arr.length; ++i) {
  15974. if (arr[i] !== 0) {
  15975. if (currLen > maxLen) {
  15976. maxIdx = currStart;
  15977. maxLen = currLen;
  15978. }
  15979. currStart = null;
  15980. currLen = 0;
  15981. } else {
  15982. if (currStart === null) {
  15983. currStart = i;
  15984. }
  15985. ++currLen;
  15986. }
  15987. }
  15988. if (currLen > maxLen) {
  15989. return currStart;
  15990. }
  15991. return maxIdx;
  15992. }
  15993. __name(findLongestZeroSequence, "findLongestZeroSequence");
  15994. function serializeHost(host) {
  15995. if (typeof host === "number") {
  15996. return serializeIPv4(host);
  15997. }
  15998. if (host instanceof Array) {
  15999. return `[${serializeIPv6(host)}]`;
  16000. }
  16001. return host;
  16002. }
  16003. __name(serializeHost, "serializeHost");
  16004. function domainToASCII(domain, beStrict = false) {
  16005. const result = tr46.toASCII(domain, {
  16006. checkBidi: true,
  16007. checkHyphens: false,
  16008. checkJoiners: true,
  16009. useSTD3ASCIIRules: beStrict,
  16010. verifyDNSLength: beStrict
  16011. });
  16012. if (result === null || result === "") {
  16013. return failure;
  16014. }
  16015. return result;
  16016. }
  16017. __name(domainToASCII, "domainToASCII");
  16018. function trimControlChars(url) {
  16019. return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/ug, "");
  16020. }
  16021. __name(trimControlChars, "trimControlChars");
  16022. function trimTabAndNewline(url) {
  16023. return url.replace(/\u0009|\u000A|\u000D/ug, "");
  16024. }
  16025. __name(trimTabAndNewline, "trimTabAndNewline");
  16026. function shortenPath(url) {
  16027. const { path } = url;
  16028. if (path.length === 0) {
  16029. return;
  16030. }
  16031. if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {
  16032. return;
  16033. }
  16034. path.pop();
  16035. }
  16036. __name(shortenPath, "shortenPath");
  16037. function includesCredentials(url) {
  16038. return url.username !== "" || url.password !== "";
  16039. }
  16040. __name(includesCredentials, "includesCredentials");
  16041. function cannotHaveAUsernamePasswordPort(url) {
  16042. return url.host === null || url.host === "" || hasAnOpaquePath(url) || url.scheme === "file";
  16043. }
  16044. __name(cannotHaveAUsernamePasswordPort, "cannotHaveAUsernamePasswordPort");
  16045. function hasAnOpaquePath(url) {
  16046. return typeof url.path === "string";
  16047. }
  16048. __name(hasAnOpaquePath, "hasAnOpaquePath");
  16049. function isNormalizedWindowsDriveLetter(string) {
  16050. return /^[A-Za-z]:$/u.test(string);
  16051. }
  16052. __name(isNormalizedWindowsDriveLetter, "isNormalizedWindowsDriveLetter");
  16053. function URLStateMachine(input, base, encodingOverride, url, stateOverride) {
  16054. this.pointer = 0;
  16055. this.input = input;
  16056. this.base = base || null;
  16057. this.encodingOverride = encodingOverride || "utf-8";
  16058. this.stateOverride = stateOverride;
  16059. this.url = url;
  16060. this.failure = false;
  16061. this.parseError = false;
  16062. if (!this.url) {
  16063. this.url = {
  16064. scheme: "",
  16065. username: "",
  16066. password: "",
  16067. host: null,
  16068. port: null,
  16069. path: [],
  16070. query: null,
  16071. fragment: null
  16072. };
  16073. const res2 = trimControlChars(this.input);
  16074. if (res2 !== this.input) {
  16075. this.parseError = true;
  16076. }
  16077. this.input = res2;
  16078. }
  16079. const res = trimTabAndNewline(this.input);
  16080. if (res !== this.input) {
  16081. this.parseError = true;
  16082. }
  16083. this.input = res;
  16084. this.state = stateOverride || "scheme start";
  16085. this.buffer = "";
  16086. this.atFlag = false;
  16087. this.arrFlag = false;
  16088. this.passwordTokenSeenFlag = false;
  16089. this.input = Array.from(this.input, (c) => c.codePointAt(0));
  16090. for (; this.pointer <= this.input.length; ++this.pointer) {
  16091. const c = this.input[this.pointer];
  16092. const cStr = isNaN(c) ? void 0 : String.fromCodePoint(c);
  16093. const ret = this[`parse ${this.state}`](c, cStr);
  16094. if (!ret) {
  16095. break;
  16096. } else if (ret === failure) {
  16097. this.failure = true;
  16098. break;
  16099. }
  16100. }
  16101. }
  16102. __name(URLStateMachine, "URLStateMachine");
  16103. URLStateMachine.prototype["parse scheme start"] = /* @__PURE__ */ __name(function parseSchemeStart(c, cStr) {
  16104. if (infra.isASCIIAlpha(c)) {
  16105. this.buffer += cStr.toLowerCase();
  16106. this.state = "scheme";
  16107. } else if (!this.stateOverride) {
  16108. this.state = "no scheme";
  16109. --this.pointer;
  16110. } else {
  16111. this.parseError = true;
  16112. return failure;
  16113. }
  16114. return true;
  16115. }, "parseSchemeStart");
  16116. URLStateMachine.prototype["parse scheme"] = /* @__PURE__ */ __name(function parseScheme(c, cStr) {
  16117. if (infra.isASCIIAlphanumeric(c) || c === p("+") || c === p("-") || c === p(".")) {
  16118. this.buffer += cStr.toLowerCase();
  16119. } else if (c === p(":")) {
  16120. if (this.stateOverride) {
  16121. if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
  16122. return false;
  16123. }
  16124. if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
  16125. return false;
  16126. }
  16127. if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
  16128. return false;
  16129. }
  16130. if (this.url.scheme === "file" && this.url.host === "") {
  16131. return false;
  16132. }
  16133. }
  16134. this.url.scheme = this.buffer;
  16135. if (this.stateOverride) {
  16136. if (this.url.port === defaultPort(this.url.scheme)) {
  16137. this.url.port = null;
  16138. }
  16139. return false;
  16140. }
  16141. this.buffer = "";
  16142. if (this.url.scheme === "file") {
  16143. if (this.input[this.pointer + 1] !== p("/") || this.input[this.pointer + 2] !== p("/")) {
  16144. this.parseError = true;
  16145. }
  16146. this.state = "file";
  16147. } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
  16148. this.state = "special relative or authority";
  16149. } else if (isSpecial(this.url)) {
  16150. this.state = "special authority slashes";
  16151. } else if (this.input[this.pointer + 1] === p("/")) {
  16152. this.state = "path or authority";
  16153. ++this.pointer;
  16154. } else {
  16155. this.url.path = "";
  16156. this.state = "opaque path";
  16157. }
  16158. } else if (!this.stateOverride) {
  16159. this.buffer = "";
  16160. this.state = "no scheme";
  16161. this.pointer = -1;
  16162. } else {
  16163. this.parseError = true;
  16164. return failure;
  16165. }
  16166. return true;
  16167. }, "parseScheme");
  16168. URLStateMachine.prototype["parse no scheme"] = /* @__PURE__ */ __name(function parseNoScheme(c) {
  16169. if (this.base === null || hasAnOpaquePath(this.base) && c !== p("#")) {
  16170. return failure;
  16171. } else if (hasAnOpaquePath(this.base) && c === p("#")) {
  16172. this.url.scheme = this.base.scheme;
  16173. this.url.path = this.base.path;
  16174. this.url.query = this.base.query;
  16175. this.url.fragment = "";
  16176. this.state = "fragment";
  16177. } else if (this.base.scheme === "file") {
  16178. this.state = "file";
  16179. --this.pointer;
  16180. } else {
  16181. this.state = "relative";
  16182. --this.pointer;
  16183. }
  16184. return true;
  16185. }, "parseNoScheme");
  16186. URLStateMachine.prototype["parse special relative or authority"] = /* @__PURE__ */ __name(function parseSpecialRelativeOrAuthority(c) {
  16187. if (c === p("/") && this.input[this.pointer + 1] === p("/")) {
  16188. this.state = "special authority ignore slashes";
  16189. ++this.pointer;
  16190. } else {
  16191. this.parseError = true;
  16192. this.state = "relative";
  16193. --this.pointer;
  16194. }
  16195. return true;
  16196. }, "parseSpecialRelativeOrAuthority");
  16197. URLStateMachine.prototype["parse path or authority"] = /* @__PURE__ */ __name(function parsePathOrAuthority(c) {
  16198. if (c === p("/")) {
  16199. this.state = "authority";
  16200. } else {
  16201. this.state = "path";
  16202. --this.pointer;
  16203. }
  16204. return true;
  16205. }, "parsePathOrAuthority");
  16206. URLStateMachine.prototype["parse relative"] = /* @__PURE__ */ __name(function parseRelative(c) {
  16207. this.url.scheme = this.base.scheme;
  16208. if (c === p("/")) {
  16209. this.state = "relative slash";
  16210. } else if (isSpecial(this.url) && c === p("\\")) {
  16211. this.parseError = true;
  16212. this.state = "relative slash";
  16213. } else {
  16214. this.url.username = this.base.username;
  16215. this.url.password = this.base.password;
  16216. this.url.host = this.base.host;
  16217. this.url.port = this.base.port;
  16218. this.url.path = this.base.path.slice();
  16219. this.url.query = this.base.query;
  16220. if (c === p("?")) {
  16221. this.url.query = "";
  16222. this.state = "query";
  16223. } else if (c === p("#")) {
  16224. this.url.fragment = "";
  16225. this.state = "fragment";
  16226. } else if (!isNaN(c)) {
  16227. this.url.query = null;
  16228. this.url.path.pop();
  16229. this.state = "path";
  16230. --this.pointer;
  16231. }
  16232. }
  16233. return true;
  16234. }, "parseRelative");
  16235. URLStateMachine.prototype["parse relative slash"] = /* @__PURE__ */ __name(function parseRelativeSlash(c) {
  16236. if (isSpecial(this.url) && (c === p("/") || c === p("\\"))) {
  16237. if (c === p("\\")) {
  16238. this.parseError = true;
  16239. }
  16240. this.state = "special authority ignore slashes";
  16241. } else if (c === p("/")) {
  16242. this.state = "authority";
  16243. } else {
  16244. this.url.username = this.base.username;
  16245. this.url.password = this.base.password;
  16246. this.url.host = this.base.host;
  16247. this.url.port = this.base.port;
  16248. this.state = "path";
  16249. --this.pointer;
  16250. }
  16251. return true;
  16252. }, "parseRelativeSlash");
  16253. URLStateMachine.prototype["parse special authority slashes"] = /* @__PURE__ */ __name(function parseSpecialAuthoritySlashes(c) {
  16254. if (c === p("/") && this.input[this.pointer + 1] === p("/")) {
  16255. this.state = "special authority ignore slashes";
  16256. ++this.pointer;
  16257. } else {
  16258. this.parseError = true;
  16259. this.state = "special authority ignore slashes";
  16260. --this.pointer;
  16261. }
  16262. return true;
  16263. }, "parseSpecialAuthoritySlashes");
  16264. URLStateMachine.prototype["parse special authority ignore slashes"] = /* @__PURE__ */ __name(function parseSpecialAuthorityIgnoreSlashes(c) {
  16265. if (c !== p("/") && c !== p("\\")) {
  16266. this.state = "authority";
  16267. --this.pointer;
  16268. } else {
  16269. this.parseError = true;
  16270. }
  16271. return true;
  16272. }, "parseSpecialAuthorityIgnoreSlashes");
  16273. URLStateMachine.prototype["parse authority"] = /* @__PURE__ */ __name(function parseAuthority(c, cStr) {
  16274. if (c === p("@")) {
  16275. this.parseError = true;
  16276. if (this.atFlag) {
  16277. this.buffer = `%40${this.buffer}`;
  16278. }
  16279. this.atFlag = true;
  16280. const len = countSymbols(this.buffer);
  16281. for (let pointer = 0; pointer < len; ++pointer) {
  16282. const codePoint = this.buffer.codePointAt(pointer);
  16283. if (codePoint === p(":") && !this.passwordTokenSeenFlag) {
  16284. this.passwordTokenSeenFlag = true;
  16285. continue;
  16286. }
  16287. const encodedCodePoints = utf8PercentEncodeCodePoint(codePoint, isUserinfoPercentEncode);
  16288. if (this.passwordTokenSeenFlag) {
  16289. this.url.password += encodedCodePoints;
  16290. } else {
  16291. this.url.username += encodedCodePoints;
  16292. }
  16293. }
  16294. this.buffer = "";
  16295. } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\")) {
  16296. if (this.atFlag && this.buffer === "") {
  16297. this.parseError = true;
  16298. return failure;
  16299. }
  16300. this.pointer -= countSymbols(this.buffer) + 1;
  16301. this.buffer = "";
  16302. this.state = "host";
  16303. } else {
  16304. this.buffer += cStr;
  16305. }
  16306. return true;
  16307. }, "parseAuthority");
  16308. URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = /* @__PURE__ */ __name(function parseHostName(c, cStr) {
  16309. if (this.stateOverride && this.url.scheme === "file") {
  16310. --this.pointer;
  16311. this.state = "file host";
  16312. } else if (c === p(":") && !this.arrFlag) {
  16313. if (this.buffer === "") {
  16314. this.parseError = true;
  16315. return failure;
  16316. }
  16317. if (this.stateOverride === "hostname") {
  16318. return false;
  16319. }
  16320. const host = parseHost(this.buffer, isNotSpecial(this.url));
  16321. if (host === failure) {
  16322. return failure;
  16323. }
  16324. this.url.host = host;
  16325. this.buffer = "";
  16326. this.state = "port";
  16327. } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\")) {
  16328. --this.pointer;
  16329. if (isSpecial(this.url) && this.buffer === "") {
  16330. this.parseError = true;
  16331. return failure;
  16332. } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) {
  16333. this.parseError = true;
  16334. return false;
  16335. }
  16336. const host = parseHost(this.buffer, isNotSpecial(this.url));
  16337. if (host === failure) {
  16338. return failure;
  16339. }
  16340. this.url.host = host;
  16341. this.buffer = "";
  16342. this.state = "path start";
  16343. if (this.stateOverride) {
  16344. return false;
  16345. }
  16346. } else {
  16347. if (c === p("[")) {
  16348. this.arrFlag = true;
  16349. } else if (c === p("]")) {
  16350. this.arrFlag = false;
  16351. }
  16352. this.buffer += cStr;
  16353. }
  16354. return true;
  16355. }, "parseHostName");
  16356. URLStateMachine.prototype["parse port"] = /* @__PURE__ */ __name(function parsePort(c, cStr) {
  16357. if (infra.isASCIIDigit(c)) {
  16358. this.buffer += cStr;
  16359. } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\") || this.stateOverride) {
  16360. if (this.buffer !== "") {
  16361. const port = parseInt(this.buffer);
  16362. if (port > 2 ** 16 - 1) {
  16363. this.parseError = true;
  16364. return failure;
  16365. }
  16366. this.url.port = port === defaultPort(this.url.scheme) ? null : port;
  16367. this.buffer = "";
  16368. }
  16369. if (this.stateOverride) {
  16370. return false;
  16371. }
  16372. this.state = "path start";
  16373. --this.pointer;
  16374. } else {
  16375. this.parseError = true;
  16376. return failure;
  16377. }
  16378. return true;
  16379. }, "parsePort");
  16380. var fileOtherwiseCodePoints = /* @__PURE__ */ new Set([p("/"), p("\\"), p("?"), p("#")]);
  16381. function startsWithWindowsDriveLetter(input, pointer) {
  16382. const length = input.length - pointer;
  16383. return length >= 2 && isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2]));
  16384. }
  16385. __name(startsWithWindowsDriveLetter, "startsWithWindowsDriveLetter");
  16386. URLStateMachine.prototype["parse file"] = /* @__PURE__ */ __name(function parseFile(c) {
  16387. this.url.scheme = "file";
  16388. this.url.host = "";
  16389. if (c === p("/") || c === p("\\")) {
  16390. if (c === p("\\")) {
  16391. this.parseError = true;
  16392. }
  16393. this.state = "file slash";
  16394. } else if (this.base !== null && this.base.scheme === "file") {
  16395. this.url.host = this.base.host;
  16396. this.url.path = this.base.path.slice();
  16397. this.url.query = this.base.query;
  16398. if (c === p("?")) {
  16399. this.url.query = "";
  16400. this.state = "query";
  16401. } else if (c === p("#")) {
  16402. this.url.fragment = "";
  16403. this.state = "fragment";
  16404. } else if (!isNaN(c)) {
  16405. this.url.query = null;
  16406. if (!startsWithWindowsDriveLetter(this.input, this.pointer)) {
  16407. shortenPath(this.url);
  16408. } else {
  16409. this.parseError = true;
  16410. this.url.path = [];
  16411. }
  16412. this.state = "path";
  16413. --this.pointer;
  16414. }
  16415. } else {
  16416. this.state = "path";
  16417. --this.pointer;
  16418. }
  16419. return true;
  16420. }, "parseFile");
  16421. URLStateMachine.prototype["parse file slash"] = /* @__PURE__ */ __name(function parseFileSlash(c) {
  16422. if (c === p("/") || c === p("\\")) {
  16423. if (c === p("\\")) {
  16424. this.parseError = true;
  16425. }
  16426. this.state = "file host";
  16427. } else {
  16428. if (this.base !== null && this.base.scheme === "file") {
  16429. if (!startsWithWindowsDriveLetter(this.input, this.pointer) && isNormalizedWindowsDriveLetterString(this.base.path[0])) {
  16430. this.url.path.push(this.base.path[0]);
  16431. }
  16432. this.url.host = this.base.host;
  16433. }
  16434. this.state = "path";
  16435. --this.pointer;
  16436. }
  16437. return true;
  16438. }, "parseFileSlash");
  16439. URLStateMachine.prototype["parse file host"] = /* @__PURE__ */ __name(function parseFileHost(c, cStr) {
  16440. if (isNaN(c) || c === p("/") || c === p("\\") || c === p("?") || c === p("#")) {
  16441. --this.pointer;
  16442. if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
  16443. this.parseError = true;
  16444. this.state = "path";
  16445. } else if (this.buffer === "") {
  16446. this.url.host = "";
  16447. if (this.stateOverride) {
  16448. return false;
  16449. }
  16450. this.state = "path start";
  16451. } else {
  16452. let host = parseHost(this.buffer, isNotSpecial(this.url));
  16453. if (host === failure) {
  16454. return failure;
  16455. }
  16456. if (host === "localhost") {
  16457. host = "";
  16458. }
  16459. this.url.host = host;
  16460. if (this.stateOverride) {
  16461. return false;
  16462. }
  16463. this.buffer = "";
  16464. this.state = "path start";
  16465. }
  16466. } else {
  16467. this.buffer += cStr;
  16468. }
  16469. return true;
  16470. }, "parseFileHost");
  16471. URLStateMachine.prototype["parse path start"] = /* @__PURE__ */ __name(function parsePathStart(c) {
  16472. if (isSpecial(this.url)) {
  16473. if (c === p("\\")) {
  16474. this.parseError = true;
  16475. }
  16476. this.state = "path";
  16477. if (c !== p("/") && c !== p("\\")) {
  16478. --this.pointer;
  16479. }
  16480. } else if (!this.stateOverride && c === p("?")) {
  16481. this.url.query = "";
  16482. this.state = "query";
  16483. } else if (!this.stateOverride && c === p("#")) {
  16484. this.url.fragment = "";
  16485. this.state = "fragment";
  16486. } else if (c !== void 0) {
  16487. this.state = "path";
  16488. if (c !== p("/")) {
  16489. --this.pointer;
  16490. }
  16491. } else if (this.stateOverride && this.url.host === null) {
  16492. this.url.path.push("");
  16493. }
  16494. return true;
  16495. }, "parsePathStart");
  16496. URLStateMachine.prototype["parse path"] = /* @__PURE__ */ __name(function parsePath(c) {
  16497. if (isNaN(c) || c === p("/") || isSpecial(this.url) && c === p("\\") || !this.stateOverride && (c === p("?") || c === p("#"))) {
  16498. if (isSpecial(this.url) && c === p("\\")) {
  16499. this.parseError = true;
  16500. }
  16501. if (isDoubleDot(this.buffer)) {
  16502. shortenPath(this.url);
  16503. if (c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) {
  16504. this.url.path.push("");
  16505. }
  16506. } else if (isSingleDot(this.buffer) && c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) {
  16507. this.url.path.push("");
  16508. } else if (!isSingleDot(this.buffer)) {
  16509. if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
  16510. this.buffer = `${this.buffer[0]}:`;
  16511. }
  16512. this.url.path.push(this.buffer);
  16513. }
  16514. this.buffer = "";
  16515. if (c === p("?")) {
  16516. this.url.query = "";
  16517. this.state = "query";
  16518. }
  16519. if (c === p("#")) {
  16520. this.url.fragment = "";
  16521. this.state = "fragment";
  16522. }
  16523. } else {
  16524. if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) {
  16525. this.parseError = true;
  16526. }
  16527. this.buffer += utf8PercentEncodeCodePoint(c, isPathPercentEncode);
  16528. }
  16529. return true;
  16530. }, "parsePath");
  16531. URLStateMachine.prototype["parse opaque path"] = /* @__PURE__ */ __name(function parseOpaquePath(c) {
  16532. if (c === p("?")) {
  16533. this.url.query = "";
  16534. this.state = "query";
  16535. } else if (c === p("#")) {
  16536. this.url.fragment = "";
  16537. this.state = "fragment";
  16538. } else {
  16539. if (!isNaN(c) && c !== p("%")) {
  16540. this.parseError = true;
  16541. }
  16542. if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) {
  16543. this.parseError = true;
  16544. }
  16545. if (!isNaN(c)) {
  16546. this.url.path += utf8PercentEncodeCodePoint(c, isC0ControlPercentEncode);
  16547. }
  16548. }
  16549. return true;
  16550. }, "parseOpaquePath");
  16551. URLStateMachine.prototype["parse query"] = /* @__PURE__ */ __name(function parseQuery(c, cStr) {
  16552. if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
  16553. this.encodingOverride = "utf-8";
  16554. }
  16555. if (!this.stateOverride && c === p("#") || isNaN(c)) {
  16556. const queryPercentEncodePredicate = isSpecial(this.url) ? isSpecialQueryPercentEncode : isQueryPercentEncode;
  16557. this.url.query += utf8PercentEncodeString(this.buffer, queryPercentEncodePredicate);
  16558. this.buffer = "";
  16559. if (c === p("#")) {
  16560. this.url.fragment = "";
  16561. this.state = "fragment";
  16562. }
  16563. } else if (!isNaN(c)) {
  16564. if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) {
  16565. this.parseError = true;
  16566. }
  16567. this.buffer += cStr;
  16568. }
  16569. return true;
  16570. }, "parseQuery");
  16571. URLStateMachine.prototype["parse fragment"] = /* @__PURE__ */ __name(function parseFragment(c) {
  16572. if (!isNaN(c)) {
  16573. if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) {
  16574. this.parseError = true;
  16575. }
  16576. this.url.fragment += utf8PercentEncodeCodePoint(c, isFragmentPercentEncode);
  16577. }
  16578. return true;
  16579. }, "parseFragment");
  16580. function serializeURL(url, excludeFragment) {
  16581. let output = `${url.scheme}:`;
  16582. if (url.host !== null) {
  16583. output += "//";
  16584. if (url.username !== "" || url.password !== "") {
  16585. output += url.username;
  16586. if (url.password !== "") {
  16587. output += `:${url.password}`;
  16588. }
  16589. output += "@";
  16590. }
  16591. output += serializeHost(url.host);
  16592. if (url.port !== null) {
  16593. output += `:${url.port}`;
  16594. }
  16595. }
  16596. if (url.host === null && !hasAnOpaquePath(url) && url.path.length > 1 && url.path[0] === "") {
  16597. output += "/.";
  16598. }
  16599. output += serializePath(url);
  16600. if (url.query !== null) {
  16601. output += `?${url.query}`;
  16602. }
  16603. if (!excludeFragment && url.fragment !== null) {
  16604. output += `#${url.fragment}`;
  16605. }
  16606. return output;
  16607. }
  16608. __name(serializeURL, "serializeURL");
  16609. function serializeOrigin(tuple) {
  16610. let result = `${tuple.scheme}://`;
  16611. result += serializeHost(tuple.host);
  16612. if (tuple.port !== null) {
  16613. result += `:${tuple.port}`;
  16614. }
  16615. return result;
  16616. }
  16617. __name(serializeOrigin, "serializeOrigin");
  16618. function serializePath(url) {
  16619. if (hasAnOpaquePath(url)) {
  16620. return url.path;
  16621. }
  16622. let output = "";
  16623. for (const segment of url.path) {
  16624. output += `/${segment}`;
  16625. }
  16626. return output;
  16627. }
  16628. __name(serializePath, "serializePath");
  16629. module2.exports.serializeURL = serializeURL;
  16630. module2.exports.serializePath = serializePath;
  16631. module2.exports.serializeURLOrigin = function(url) {
  16632. switch (url.scheme) {
  16633. case "blob":
  16634. try {
  16635. return module2.exports.serializeURLOrigin(module2.exports.parseURL(serializePath(url)));
  16636. } catch (e) {
  16637. return "null";
  16638. }
  16639. case "ftp":
  16640. case "http":
  16641. case "https":
  16642. case "ws":
  16643. case "wss":
  16644. return serializeOrigin({
  16645. scheme: url.scheme,
  16646. host: url.host,
  16647. port: url.port
  16648. });
  16649. case "file":
  16650. return "null";
  16651. default:
  16652. return "null";
  16653. }
  16654. };
  16655. module2.exports.basicURLParse = function(input, options) {
  16656. if (options === void 0) {
  16657. options = {};
  16658. }
  16659. const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);
  16660. if (usm.failure) {
  16661. return null;
  16662. }
  16663. return usm.url;
  16664. };
  16665. module2.exports.setTheUsername = function(url, username) {
  16666. url.username = utf8PercentEncodeString(username, isUserinfoPercentEncode);
  16667. };
  16668. module2.exports.setThePassword = function(url, password) {
  16669. url.password = utf8PercentEncodeString(password, isUserinfoPercentEncode);
  16670. };
  16671. module2.exports.serializeHost = serializeHost;
  16672. module2.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
  16673. module2.exports.hasAnOpaquePath = hasAnOpaquePath;
  16674. module2.exports.serializeInteger = function(integer) {
  16675. return String(integer);
  16676. };
  16677. module2.exports.parseURL = function(input, options) {
  16678. if (options === void 0) {
  16679. options = {};
  16680. }
  16681. return module2.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });
  16682. };
  16683. }
  16684. });
  16685. // node_modules/whatwg-url/lib/urlencoded.js
  16686. var require_urlencoded = __commonJS({
  16687. "node_modules/whatwg-url/lib/urlencoded.js"(exports2, module2) {
  16688. "use strict";
  16689. var { utf8Encode, utf8DecodeWithoutBOM } = require_encoding();
  16690. var { percentDecodeBytes, utf8PercentEncodeString, isURLEncodedPercentEncode } = require_percent_encoding();
  16691. function p(char) {
  16692. return char.codePointAt(0);
  16693. }
  16694. __name(p, "p");
  16695. function parseUrlencoded(input) {
  16696. const sequences = strictlySplitByteSequence(input, p("&"));
  16697. const output = [];
  16698. for (const bytes of sequences) {
  16699. if (bytes.length === 0) {
  16700. continue;
  16701. }
  16702. let name, value;
  16703. const indexOfEqual = bytes.indexOf(p("="));
  16704. if (indexOfEqual >= 0) {
  16705. name = bytes.slice(0, indexOfEqual);
  16706. value = bytes.slice(indexOfEqual + 1);
  16707. } else {
  16708. name = bytes;
  16709. value = new Uint8Array(0);
  16710. }
  16711. name = replaceByteInByteSequence(name, 43, 32);
  16712. value = replaceByteInByteSequence(value, 43, 32);
  16713. const nameString = utf8DecodeWithoutBOM(percentDecodeBytes(name));
  16714. const valueString = utf8DecodeWithoutBOM(percentDecodeBytes(value));
  16715. output.push([nameString, valueString]);
  16716. }
  16717. return output;
  16718. }
  16719. __name(parseUrlencoded, "parseUrlencoded");
  16720. function parseUrlencodedString(input) {
  16721. return parseUrlencoded(utf8Encode(input));
  16722. }
  16723. __name(parseUrlencodedString, "parseUrlencodedString");
  16724. function serializeUrlencoded(tuples, encodingOverride = void 0) {
  16725. let encoding = "utf-8";
  16726. if (encodingOverride !== void 0) {
  16727. encoding = encodingOverride;
  16728. }
  16729. let output = "";
  16730. for (const [i, tuple] of tuples.entries()) {
  16731. const name = utf8PercentEncodeString(tuple[0], isURLEncodedPercentEncode, true);
  16732. let value = tuple[1];
  16733. if (tuple.length > 2 && tuple[2] !== void 0) {
  16734. if (tuple[2] === "hidden" && name === "_charset_") {
  16735. value = encoding;
  16736. } else if (tuple[2] === "file") {
  16737. value = value.name;
  16738. }
  16739. }
  16740. value = utf8PercentEncodeString(value, isURLEncodedPercentEncode, true);
  16741. if (i !== 0) {
  16742. output += "&";
  16743. }
  16744. output += `${name}=${value}`;
  16745. }
  16746. return output;
  16747. }
  16748. __name(serializeUrlencoded, "serializeUrlencoded");
  16749. function strictlySplitByteSequence(buf, cp) {
  16750. const list = [];
  16751. let last = 0;
  16752. let i = buf.indexOf(cp);
  16753. while (i >= 0) {
  16754. list.push(buf.slice(last, i));
  16755. last = i + 1;
  16756. i = buf.indexOf(cp, last);
  16757. }
  16758. if (last !== buf.length) {
  16759. list.push(buf.slice(last));
  16760. }
  16761. return list;
  16762. }
  16763. __name(strictlySplitByteSequence, "strictlySplitByteSequence");
  16764. function replaceByteInByteSequence(buf, from, to) {
  16765. let i = buf.indexOf(from);
  16766. while (i >= 0) {
  16767. buf[i] = to;
  16768. i = buf.indexOf(from, i + 1);
  16769. }
  16770. return buf;
  16771. }
  16772. __name(replaceByteInByteSequence, "replaceByteInByteSequence");
  16773. module2.exports = {
  16774. parseUrlencodedString,
  16775. serializeUrlencoded
  16776. };
  16777. }
  16778. });
  16779. // node_modules/whatwg-url/lib/Function.js
  16780. var require_Function = __commonJS({
  16781. "node_modules/whatwg-url/lib/Function.js"(exports2) {
  16782. "use strict";
  16783. var conversions = require_lib();
  16784. var utils = require_utils2();
  16785. exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => {
  16786. if (typeof value !== "function") {
  16787. throw new globalObject.TypeError(context + " is not a function");
  16788. }
  16789. function invokeTheCallbackFunction(...args) {
  16790. const thisArg = utils.tryWrapperForImpl(this);
  16791. let callResult;
  16792. for (let i = 0; i < args.length; i++) {
  16793. args[i] = utils.tryWrapperForImpl(args[i]);
  16794. }
  16795. callResult = Reflect.apply(value, thisArg, args);
  16796. callResult = conversions["any"](callResult, { context, globals: globalObject });
  16797. return callResult;
  16798. }
  16799. __name(invokeTheCallbackFunction, "invokeTheCallbackFunction");
  16800. invokeTheCallbackFunction.construct = (...args) => {
  16801. for (let i = 0; i < args.length; i++) {
  16802. args[i] = utils.tryWrapperForImpl(args[i]);
  16803. }
  16804. let callResult = Reflect.construct(value, args);
  16805. callResult = conversions["any"](callResult, { context, globals: globalObject });
  16806. return callResult;
  16807. };
  16808. invokeTheCallbackFunction[utils.wrapperSymbol] = value;
  16809. invokeTheCallbackFunction.objectReference = value;
  16810. return invokeTheCallbackFunction;
  16811. };
  16812. }
  16813. });
  16814. // node_modules/whatwg-url/lib/URLSearchParams-impl.js
  16815. var require_URLSearchParams_impl = __commonJS({
  16816. "node_modules/whatwg-url/lib/URLSearchParams-impl.js"(exports2) {
  16817. "use strict";
  16818. var urlencoded = require_urlencoded();
  16819. var _a;
  16820. exports2.implementation = (_a = class {
  16821. constructor(globalObject, constructorArgs, { doNotStripQMark = false }) {
  16822. let init = constructorArgs[0];
  16823. this._list = [];
  16824. this._url = null;
  16825. if (!doNotStripQMark && typeof init === "string" && init[0] === "?") {
  16826. init = init.slice(1);
  16827. }
  16828. if (Array.isArray(init)) {
  16829. for (const pair of init) {
  16830. if (pair.length !== 2) {
  16831. throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not contain exactly two elements.");
  16832. }
  16833. this._list.push([pair[0], pair[1]]);
  16834. }
  16835. } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) {
  16836. for (const name of Object.keys(init)) {
  16837. const value = init[name];
  16838. this._list.push([name, value]);
  16839. }
  16840. } else {
  16841. this._list = urlencoded.parseUrlencodedString(init);
  16842. }
  16843. }
  16844. _updateSteps() {
  16845. if (this._url !== null) {
  16846. let query = urlencoded.serializeUrlencoded(this._list);
  16847. if (query === "") {
  16848. query = null;
  16849. }
  16850. this._url._url.query = query;
  16851. }
  16852. }
  16853. append(name, value) {
  16854. this._list.push([name, value]);
  16855. this._updateSteps();
  16856. }
  16857. delete(name) {
  16858. let i = 0;
  16859. while (i < this._list.length) {
  16860. if (this._list[i][0] === name) {
  16861. this._list.splice(i, 1);
  16862. } else {
  16863. i++;
  16864. }
  16865. }
  16866. this._updateSteps();
  16867. }
  16868. get(name) {
  16869. for (const tuple of this._list) {
  16870. if (tuple[0] === name) {
  16871. return tuple[1];
  16872. }
  16873. }
  16874. return null;
  16875. }
  16876. getAll(name) {
  16877. const output = [];
  16878. for (const tuple of this._list) {
  16879. if (tuple[0] === name) {
  16880. output.push(tuple[1]);
  16881. }
  16882. }
  16883. return output;
  16884. }
  16885. has(name) {
  16886. for (const tuple of this._list) {
  16887. if (tuple[0] === name) {
  16888. return true;
  16889. }
  16890. }
  16891. return false;
  16892. }
  16893. set(name, value) {
  16894. let found = false;
  16895. let i = 0;
  16896. while (i < this._list.length) {
  16897. if (this._list[i][0] === name) {
  16898. if (found) {
  16899. this._list.splice(i, 1);
  16900. } else {
  16901. found = true;
  16902. this._list[i][1] = value;
  16903. i++;
  16904. }
  16905. } else {
  16906. i++;
  16907. }
  16908. }
  16909. if (!found) {
  16910. this._list.push([name, value]);
  16911. }
  16912. this._updateSteps();
  16913. }
  16914. sort() {
  16915. this._list.sort((a, b) => {
  16916. if (a[0] < b[0]) {
  16917. return -1;
  16918. }
  16919. if (a[0] > b[0]) {
  16920. return 1;
  16921. }
  16922. return 0;
  16923. });
  16924. this._updateSteps();
  16925. }
  16926. [Symbol.iterator]() {
  16927. return this._list[Symbol.iterator]();
  16928. }
  16929. toString() {
  16930. return urlencoded.serializeUrlencoded(this._list);
  16931. }
  16932. }, __name(_a, "URLSearchParamsImpl"), _a);
  16933. }
  16934. });
  16935. // node_modules/whatwg-url/lib/URLSearchParams.js
  16936. var require_URLSearchParams = __commonJS({
  16937. "node_modules/whatwg-url/lib/URLSearchParams.js"(exports2) {
  16938. "use strict";
  16939. var conversions = require_lib();
  16940. var utils = require_utils2();
  16941. var Function2 = require_Function();
  16942. var newObjectInRealm = utils.newObjectInRealm;
  16943. var implSymbol = utils.implSymbol;
  16944. var ctorRegistrySymbol = utils.ctorRegistrySymbol;
  16945. var interfaceName = "URLSearchParams";
  16946. exports2.is = (value) => {
  16947. return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation;
  16948. };
  16949. exports2.isImpl = (value) => {
  16950. return utils.isObject(value) && value instanceof Impl.implementation;
  16951. };
  16952. exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => {
  16953. if (exports2.is(value)) {
  16954. return utils.implForWrapper(value);
  16955. }
  16956. throw new globalObject.TypeError(`${context} is not of type 'URLSearchParams'.`);
  16957. };
  16958. exports2.createDefaultIterator = (globalObject, target, kind) => {
  16959. const ctorRegistry = globalObject[ctorRegistrySymbol];
  16960. const iteratorPrototype = ctorRegistry["URLSearchParams Iterator"];
  16961. const iterator = Object.create(iteratorPrototype);
  16962. Object.defineProperty(iterator, utils.iterInternalSymbol, {
  16963. value: { target, kind, index: 0 },
  16964. configurable: true
  16965. });
  16966. return iterator;
  16967. };
  16968. function makeWrapper(globalObject, newTarget) {
  16969. let proto;
  16970. if (newTarget !== void 0) {
  16971. proto = newTarget.prototype;
  16972. }
  16973. if (!utils.isObject(proto)) {
  16974. proto = globalObject[ctorRegistrySymbol]["URLSearchParams"].prototype;
  16975. }
  16976. return Object.create(proto);
  16977. }
  16978. __name(makeWrapper, "makeWrapper");
  16979. exports2.create = (globalObject, constructorArgs, privateData) => {
  16980. const wrapper = makeWrapper(globalObject);
  16981. return exports2.setup(wrapper, globalObject, constructorArgs, privateData);
  16982. };
  16983. exports2.createImpl = (globalObject, constructorArgs, privateData) => {
  16984. const wrapper = exports2.create(globalObject, constructorArgs, privateData);
  16985. return utils.implForWrapper(wrapper);
  16986. };
  16987. exports2._internalSetup = (wrapper, globalObject) => {
  16988. };
  16989. exports2.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => {
  16990. privateData.wrapper = wrapper;
  16991. exports2._internalSetup(wrapper, globalObject);
  16992. Object.defineProperty(wrapper, implSymbol, {
  16993. value: new Impl.implementation(globalObject, constructorArgs, privateData),
  16994. configurable: true
  16995. });
  16996. wrapper[implSymbol][utils.wrapperSymbol] = wrapper;
  16997. if (Impl.init) {
  16998. Impl.init(wrapper[implSymbol]);
  16999. }
  17000. return wrapper;
  17001. };
  17002. exports2.new = (globalObject, newTarget) => {
  17003. const wrapper = makeWrapper(globalObject, newTarget);
  17004. exports2._internalSetup(wrapper, globalObject);
  17005. Object.defineProperty(wrapper, implSymbol, {
  17006. value: Object.create(Impl.implementation.prototype),
  17007. configurable: true
  17008. });
  17009. wrapper[implSymbol][utils.wrapperSymbol] = wrapper;
  17010. if (Impl.init) {
  17011. Impl.init(wrapper[implSymbol]);
  17012. }
  17013. return wrapper[implSymbol];
  17014. };
  17015. var exposed = /* @__PURE__ */ new Set(["Window", "Worker"]);
  17016. exports2.install = (globalObject, globalNames) => {
  17017. if (!globalNames.some((globalName) => exposed.has(globalName))) {
  17018. return;
  17019. }
  17020. const ctorRegistry = utils.initCtorRegistry(globalObject);
  17021. const _URLSearchParams = class _URLSearchParams {
  17022. constructor() {
  17023. const args = [];
  17024. {
  17025. let curArg = arguments[0];
  17026. if (curArg !== void 0) {
  17027. if (utils.isObject(curArg)) {
  17028. if (curArg[Symbol.iterator] !== void 0) {
  17029. if (!utils.isObject(curArg)) {
  17030. throw new globalObject.TypeError(
  17031. "Failed to construct 'URLSearchParams': parameter 1 sequence is not an iterable object."
  17032. );
  17033. } else {
  17034. const V = [];
  17035. const tmp = curArg;
  17036. for (let nextItem of tmp) {
  17037. if (!utils.isObject(nextItem)) {
  17038. throw new globalObject.TypeError(
  17039. "Failed to construct 'URLSearchParams': parameter 1 sequence's element is not an iterable object."
  17040. );
  17041. } else {
  17042. const V2 = [];
  17043. const tmp2 = nextItem;
  17044. for (let nextItem2 of tmp2) {
  17045. nextItem2 = conversions["USVString"](nextItem2, {
  17046. context: "Failed to construct 'URLSearchParams': parameter 1 sequence's element's element",
  17047. globals: globalObject
  17048. });
  17049. V2.push(nextItem2);
  17050. }
  17051. nextItem = V2;
  17052. }
  17053. V.push(nextItem);
  17054. }
  17055. curArg = V;
  17056. }
  17057. } else {
  17058. if (!utils.isObject(curArg)) {
  17059. throw new globalObject.TypeError(
  17060. "Failed to construct 'URLSearchParams': parameter 1 record is not an object."
  17061. );
  17062. } else {
  17063. const result = /* @__PURE__ */ Object.create(null);
  17064. for (const key of Reflect.ownKeys(curArg)) {
  17065. const desc = Object.getOwnPropertyDescriptor(curArg, key);
  17066. if (desc && desc.enumerable) {
  17067. let typedKey = key;
  17068. typedKey = conversions["USVString"](typedKey, {
  17069. context: "Failed to construct 'URLSearchParams': parameter 1 record's key",
  17070. globals: globalObject
  17071. });
  17072. let typedValue = curArg[key];
  17073. typedValue = conversions["USVString"](typedValue, {
  17074. context: "Failed to construct 'URLSearchParams': parameter 1 record's value",
  17075. globals: globalObject
  17076. });
  17077. result[typedKey] = typedValue;
  17078. }
  17079. }
  17080. curArg = result;
  17081. }
  17082. }
  17083. } else {
  17084. curArg = conversions["USVString"](curArg, {
  17085. context: "Failed to construct 'URLSearchParams': parameter 1",
  17086. globals: globalObject
  17087. });
  17088. }
  17089. } else {
  17090. curArg = "";
  17091. }
  17092. args.push(curArg);
  17093. }
  17094. return exports2.setup(Object.create(new.target.prototype), globalObject, args);
  17095. }
  17096. append(name, value) {
  17097. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17098. if (!exports2.is(esValue)) {
  17099. throw new globalObject.TypeError(
  17100. "'append' called on an object that is not a valid instance of URLSearchParams."
  17101. );
  17102. }
  17103. if (arguments.length < 2) {
  17104. throw new globalObject.TypeError(
  17105. `Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.`
  17106. );
  17107. }
  17108. const args = [];
  17109. {
  17110. let curArg = arguments[0];
  17111. curArg = conversions["USVString"](curArg, {
  17112. context: "Failed to execute 'append' on 'URLSearchParams': parameter 1",
  17113. globals: globalObject
  17114. });
  17115. args.push(curArg);
  17116. }
  17117. {
  17118. let curArg = arguments[1];
  17119. curArg = conversions["USVString"](curArg, {
  17120. context: "Failed to execute 'append' on 'URLSearchParams': parameter 2",
  17121. globals: globalObject
  17122. });
  17123. args.push(curArg);
  17124. }
  17125. return utils.tryWrapperForImpl(esValue[implSymbol].append(...args));
  17126. }
  17127. delete(name) {
  17128. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17129. if (!exports2.is(esValue)) {
  17130. throw new globalObject.TypeError(
  17131. "'delete' called on an object that is not a valid instance of URLSearchParams."
  17132. );
  17133. }
  17134. if (arguments.length < 1) {
  17135. throw new globalObject.TypeError(
  17136. `Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.`
  17137. );
  17138. }
  17139. const args = [];
  17140. {
  17141. let curArg = arguments[0];
  17142. curArg = conversions["USVString"](curArg, {
  17143. context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1",
  17144. globals: globalObject
  17145. });
  17146. args.push(curArg);
  17147. }
  17148. return utils.tryWrapperForImpl(esValue[implSymbol].delete(...args));
  17149. }
  17150. get(name) {
  17151. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17152. if (!exports2.is(esValue)) {
  17153. throw new globalObject.TypeError("'get' called on an object that is not a valid instance of URLSearchParams.");
  17154. }
  17155. if (arguments.length < 1) {
  17156. throw new globalObject.TypeError(
  17157. `Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.`
  17158. );
  17159. }
  17160. const args = [];
  17161. {
  17162. let curArg = arguments[0];
  17163. curArg = conversions["USVString"](curArg, {
  17164. context: "Failed to execute 'get' on 'URLSearchParams': parameter 1",
  17165. globals: globalObject
  17166. });
  17167. args.push(curArg);
  17168. }
  17169. return esValue[implSymbol].get(...args);
  17170. }
  17171. getAll(name) {
  17172. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17173. if (!exports2.is(esValue)) {
  17174. throw new globalObject.TypeError(
  17175. "'getAll' called on an object that is not a valid instance of URLSearchParams."
  17176. );
  17177. }
  17178. if (arguments.length < 1) {
  17179. throw new globalObject.TypeError(
  17180. `Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.`
  17181. );
  17182. }
  17183. const args = [];
  17184. {
  17185. let curArg = arguments[0];
  17186. curArg = conversions["USVString"](curArg, {
  17187. context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1",
  17188. globals: globalObject
  17189. });
  17190. args.push(curArg);
  17191. }
  17192. return utils.tryWrapperForImpl(esValue[implSymbol].getAll(...args));
  17193. }
  17194. has(name) {
  17195. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17196. if (!exports2.is(esValue)) {
  17197. throw new globalObject.TypeError("'has' called on an object that is not a valid instance of URLSearchParams.");
  17198. }
  17199. if (arguments.length < 1) {
  17200. throw new globalObject.TypeError(
  17201. `Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.`
  17202. );
  17203. }
  17204. const args = [];
  17205. {
  17206. let curArg = arguments[0];
  17207. curArg = conversions["USVString"](curArg, {
  17208. context: "Failed to execute 'has' on 'URLSearchParams': parameter 1",
  17209. globals: globalObject
  17210. });
  17211. args.push(curArg);
  17212. }
  17213. return esValue[implSymbol].has(...args);
  17214. }
  17215. set(name, value) {
  17216. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17217. if (!exports2.is(esValue)) {
  17218. throw new globalObject.TypeError("'set' called on an object that is not a valid instance of URLSearchParams.");
  17219. }
  17220. if (arguments.length < 2) {
  17221. throw new globalObject.TypeError(
  17222. `Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.`
  17223. );
  17224. }
  17225. const args = [];
  17226. {
  17227. let curArg = arguments[0];
  17228. curArg = conversions["USVString"](curArg, {
  17229. context: "Failed to execute 'set' on 'URLSearchParams': parameter 1",
  17230. globals: globalObject
  17231. });
  17232. args.push(curArg);
  17233. }
  17234. {
  17235. let curArg = arguments[1];
  17236. curArg = conversions["USVString"](curArg, {
  17237. context: "Failed to execute 'set' on 'URLSearchParams': parameter 2",
  17238. globals: globalObject
  17239. });
  17240. args.push(curArg);
  17241. }
  17242. return utils.tryWrapperForImpl(esValue[implSymbol].set(...args));
  17243. }
  17244. sort() {
  17245. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17246. if (!exports2.is(esValue)) {
  17247. throw new globalObject.TypeError("'sort' called on an object that is not a valid instance of URLSearchParams.");
  17248. }
  17249. return utils.tryWrapperForImpl(esValue[implSymbol].sort());
  17250. }
  17251. toString() {
  17252. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17253. if (!exports2.is(esValue)) {
  17254. throw new globalObject.TypeError(
  17255. "'toString' called on an object that is not a valid instance of URLSearchParams."
  17256. );
  17257. }
  17258. return esValue[implSymbol].toString();
  17259. }
  17260. keys() {
  17261. if (!exports2.is(this)) {
  17262. throw new globalObject.TypeError("'keys' called on an object that is not a valid instance of URLSearchParams.");
  17263. }
  17264. return exports2.createDefaultIterator(globalObject, this, "key");
  17265. }
  17266. values() {
  17267. if (!exports2.is(this)) {
  17268. throw new globalObject.TypeError(
  17269. "'values' called on an object that is not a valid instance of URLSearchParams."
  17270. );
  17271. }
  17272. return exports2.createDefaultIterator(globalObject, this, "value");
  17273. }
  17274. entries() {
  17275. if (!exports2.is(this)) {
  17276. throw new globalObject.TypeError(
  17277. "'entries' called on an object that is not a valid instance of URLSearchParams."
  17278. );
  17279. }
  17280. return exports2.createDefaultIterator(globalObject, this, "key+value");
  17281. }
  17282. forEach(callback) {
  17283. if (!exports2.is(this)) {
  17284. throw new globalObject.TypeError(
  17285. "'forEach' called on an object that is not a valid instance of URLSearchParams."
  17286. );
  17287. }
  17288. if (arguments.length < 1) {
  17289. throw new globalObject.TypeError(
  17290. "Failed to execute 'forEach' on 'iterable': 1 argument required, but only 0 present."
  17291. );
  17292. }
  17293. callback = Function2.convert(globalObject, callback, {
  17294. context: "Failed to execute 'forEach' on 'iterable': The callback provided as parameter 1"
  17295. });
  17296. const thisArg = arguments[1];
  17297. let pairs = Array.from(this[implSymbol]);
  17298. let i = 0;
  17299. while (i < pairs.length) {
  17300. const [key, value] = pairs[i].map(utils.tryWrapperForImpl);
  17301. callback.call(thisArg, value, key, this);
  17302. pairs = Array.from(this[implSymbol]);
  17303. i++;
  17304. }
  17305. }
  17306. };
  17307. __name(_URLSearchParams, "URLSearchParams");
  17308. let URLSearchParams = _URLSearchParams;
  17309. Object.defineProperties(URLSearchParams.prototype, {
  17310. append: { enumerable: true },
  17311. delete: { enumerable: true },
  17312. get: { enumerable: true },
  17313. getAll: { enumerable: true },
  17314. has: { enumerable: true },
  17315. set: { enumerable: true },
  17316. sort: { enumerable: true },
  17317. toString: { enumerable: true },
  17318. keys: { enumerable: true },
  17319. values: { enumerable: true },
  17320. entries: { enumerable: true },
  17321. forEach: { enumerable: true },
  17322. [Symbol.toStringTag]: { value: "URLSearchParams", configurable: true },
  17323. [Symbol.iterator]: { value: URLSearchParams.prototype.entries, configurable: true, writable: true }
  17324. });
  17325. ctorRegistry[interfaceName] = URLSearchParams;
  17326. ctorRegistry["URLSearchParams Iterator"] = Object.create(ctorRegistry["%IteratorPrototype%"], {
  17327. [Symbol.toStringTag]: {
  17328. configurable: true,
  17329. value: "URLSearchParams Iterator"
  17330. }
  17331. });
  17332. utils.define(ctorRegistry["URLSearchParams Iterator"], {
  17333. next() {
  17334. const internal = this && this[utils.iterInternalSymbol];
  17335. if (!internal) {
  17336. throw new globalObject.TypeError("next() called on a value that is not a URLSearchParams iterator object");
  17337. }
  17338. const { target, kind, index } = internal;
  17339. const values = Array.from(target[implSymbol]);
  17340. const len = values.length;
  17341. if (index >= len) {
  17342. return newObjectInRealm(globalObject, { value: void 0, done: true });
  17343. }
  17344. const pair = values[index];
  17345. internal.index = index + 1;
  17346. return newObjectInRealm(globalObject, utils.iteratorResult(pair.map(utils.tryWrapperForImpl), kind));
  17347. }
  17348. });
  17349. Object.defineProperty(globalObject, interfaceName, {
  17350. configurable: true,
  17351. writable: true,
  17352. value: URLSearchParams
  17353. });
  17354. };
  17355. var Impl = require_URLSearchParams_impl();
  17356. }
  17357. });
  17358. // node_modules/whatwg-url/lib/URL-impl.js
  17359. var require_URL_impl = __commonJS({
  17360. "node_modules/whatwg-url/lib/URL-impl.js"(exports2) {
  17361. "use strict";
  17362. var usm = require_url_state_machine();
  17363. var urlencoded = require_urlencoded();
  17364. var URLSearchParams = require_URLSearchParams();
  17365. var _a;
  17366. exports2.implementation = (_a = class {
  17367. constructor(globalObject, constructorArgs) {
  17368. const url = constructorArgs[0];
  17369. const base = constructorArgs[1];
  17370. let parsedBase = null;
  17371. if (base !== void 0) {
  17372. parsedBase = usm.basicURLParse(base);
  17373. if (parsedBase === null) {
  17374. throw new TypeError(`Invalid base URL: ${base}`);
  17375. }
  17376. }
  17377. const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });
  17378. if (parsedURL === null) {
  17379. throw new TypeError(`Invalid URL: ${url}`);
  17380. }
  17381. const query = parsedURL.query !== null ? parsedURL.query : "";
  17382. this._url = parsedURL;
  17383. this._query = URLSearchParams.createImpl(globalObject, [query], { doNotStripQMark: true });
  17384. this._query._url = this;
  17385. }
  17386. get href() {
  17387. return usm.serializeURL(this._url);
  17388. }
  17389. set href(v) {
  17390. const parsedURL = usm.basicURLParse(v);
  17391. if (parsedURL === null) {
  17392. throw new TypeError(`Invalid URL: ${v}`);
  17393. }
  17394. this._url = parsedURL;
  17395. this._query._list.splice(0);
  17396. const { query } = parsedURL;
  17397. if (query !== null) {
  17398. this._query._list = urlencoded.parseUrlencodedString(query);
  17399. }
  17400. }
  17401. get origin() {
  17402. return usm.serializeURLOrigin(this._url);
  17403. }
  17404. get protocol() {
  17405. return `${this._url.scheme}:`;
  17406. }
  17407. set protocol(v) {
  17408. usm.basicURLParse(`${v}:`, { url: this._url, stateOverride: "scheme start" });
  17409. }
  17410. get username() {
  17411. return this._url.username;
  17412. }
  17413. set username(v) {
  17414. if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
  17415. return;
  17416. }
  17417. usm.setTheUsername(this._url, v);
  17418. }
  17419. get password() {
  17420. return this._url.password;
  17421. }
  17422. set password(v) {
  17423. if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
  17424. return;
  17425. }
  17426. usm.setThePassword(this._url, v);
  17427. }
  17428. get host() {
  17429. const url = this._url;
  17430. if (url.host === null) {
  17431. return "";
  17432. }
  17433. if (url.port === null) {
  17434. return usm.serializeHost(url.host);
  17435. }
  17436. return `${usm.serializeHost(url.host)}:${usm.serializeInteger(url.port)}`;
  17437. }
  17438. set host(v) {
  17439. if (usm.hasAnOpaquePath(this._url)) {
  17440. return;
  17441. }
  17442. usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
  17443. }
  17444. get hostname() {
  17445. if (this._url.host === null) {
  17446. return "";
  17447. }
  17448. return usm.serializeHost(this._url.host);
  17449. }
  17450. set hostname(v) {
  17451. if (usm.hasAnOpaquePath(this._url)) {
  17452. return;
  17453. }
  17454. usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
  17455. }
  17456. get port() {
  17457. if (this._url.port === null) {
  17458. return "";
  17459. }
  17460. return usm.serializeInteger(this._url.port);
  17461. }
  17462. set port(v) {
  17463. if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
  17464. return;
  17465. }
  17466. if (v === "") {
  17467. this._url.port = null;
  17468. } else {
  17469. usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
  17470. }
  17471. }
  17472. get pathname() {
  17473. return usm.serializePath(this._url);
  17474. }
  17475. set pathname(v) {
  17476. if (usm.hasAnOpaquePath(this._url)) {
  17477. return;
  17478. }
  17479. this._url.path = [];
  17480. usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
  17481. }
  17482. get search() {
  17483. if (this._url.query === null || this._url.query === "") {
  17484. return "";
  17485. }
  17486. return `?${this._url.query}`;
  17487. }
  17488. set search(v) {
  17489. const url = this._url;
  17490. if (v === "") {
  17491. url.query = null;
  17492. this._query._list = [];
  17493. return;
  17494. }
  17495. const input = v[0] === "?" ? v.substring(1) : v;
  17496. url.query = "";
  17497. usm.basicURLParse(input, { url, stateOverride: "query" });
  17498. this._query._list = urlencoded.parseUrlencodedString(input);
  17499. }
  17500. get searchParams() {
  17501. return this._query;
  17502. }
  17503. get hash() {
  17504. if (this._url.fragment === null || this._url.fragment === "") {
  17505. return "";
  17506. }
  17507. return `#${this._url.fragment}`;
  17508. }
  17509. set hash(v) {
  17510. if (v === "") {
  17511. this._url.fragment = null;
  17512. return;
  17513. }
  17514. const input = v[0] === "#" ? v.substring(1) : v;
  17515. this._url.fragment = "";
  17516. usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
  17517. }
  17518. toJSON() {
  17519. return this.href;
  17520. }
  17521. }, __name(_a, "URLImpl"), _a);
  17522. }
  17523. });
  17524. // node_modules/whatwg-url/lib/URL.js
  17525. var require_URL = __commonJS({
  17526. "node_modules/whatwg-url/lib/URL.js"(exports2) {
  17527. "use strict";
  17528. var conversions = require_lib();
  17529. var utils = require_utils2();
  17530. var implSymbol = utils.implSymbol;
  17531. var ctorRegistrySymbol = utils.ctorRegistrySymbol;
  17532. var interfaceName = "URL";
  17533. exports2.is = (value) => {
  17534. return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation;
  17535. };
  17536. exports2.isImpl = (value) => {
  17537. return utils.isObject(value) && value instanceof Impl.implementation;
  17538. };
  17539. exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => {
  17540. if (exports2.is(value)) {
  17541. return utils.implForWrapper(value);
  17542. }
  17543. throw new globalObject.TypeError(`${context} is not of type 'URL'.`);
  17544. };
  17545. function makeWrapper(globalObject, newTarget) {
  17546. let proto;
  17547. if (newTarget !== void 0) {
  17548. proto = newTarget.prototype;
  17549. }
  17550. if (!utils.isObject(proto)) {
  17551. proto = globalObject[ctorRegistrySymbol]["URL"].prototype;
  17552. }
  17553. return Object.create(proto);
  17554. }
  17555. __name(makeWrapper, "makeWrapper");
  17556. exports2.create = (globalObject, constructorArgs, privateData) => {
  17557. const wrapper = makeWrapper(globalObject);
  17558. return exports2.setup(wrapper, globalObject, constructorArgs, privateData);
  17559. };
  17560. exports2.createImpl = (globalObject, constructorArgs, privateData) => {
  17561. const wrapper = exports2.create(globalObject, constructorArgs, privateData);
  17562. return utils.implForWrapper(wrapper);
  17563. };
  17564. exports2._internalSetup = (wrapper, globalObject) => {
  17565. };
  17566. exports2.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => {
  17567. privateData.wrapper = wrapper;
  17568. exports2._internalSetup(wrapper, globalObject);
  17569. Object.defineProperty(wrapper, implSymbol, {
  17570. value: new Impl.implementation(globalObject, constructorArgs, privateData),
  17571. configurable: true
  17572. });
  17573. wrapper[implSymbol][utils.wrapperSymbol] = wrapper;
  17574. if (Impl.init) {
  17575. Impl.init(wrapper[implSymbol]);
  17576. }
  17577. return wrapper;
  17578. };
  17579. exports2.new = (globalObject, newTarget) => {
  17580. const wrapper = makeWrapper(globalObject, newTarget);
  17581. exports2._internalSetup(wrapper, globalObject);
  17582. Object.defineProperty(wrapper, implSymbol, {
  17583. value: Object.create(Impl.implementation.prototype),
  17584. configurable: true
  17585. });
  17586. wrapper[implSymbol][utils.wrapperSymbol] = wrapper;
  17587. if (Impl.init) {
  17588. Impl.init(wrapper[implSymbol]);
  17589. }
  17590. return wrapper[implSymbol];
  17591. };
  17592. var exposed = /* @__PURE__ */ new Set(["Window", "Worker"]);
  17593. exports2.install = (globalObject, globalNames) => {
  17594. if (!globalNames.some((globalName) => exposed.has(globalName))) {
  17595. return;
  17596. }
  17597. const ctorRegistry = utils.initCtorRegistry(globalObject);
  17598. const _URL = class _URL {
  17599. constructor(url) {
  17600. if (arguments.length < 1) {
  17601. throw new globalObject.TypeError(
  17602. `Failed to construct 'URL': 1 argument required, but only ${arguments.length} present.`
  17603. );
  17604. }
  17605. const args = [];
  17606. {
  17607. let curArg = arguments[0];
  17608. curArg = conversions["USVString"](curArg, {
  17609. context: "Failed to construct 'URL': parameter 1",
  17610. globals: globalObject
  17611. });
  17612. args.push(curArg);
  17613. }
  17614. {
  17615. let curArg = arguments[1];
  17616. if (curArg !== void 0) {
  17617. curArg = conversions["USVString"](curArg, {
  17618. context: "Failed to construct 'URL': parameter 2",
  17619. globals: globalObject
  17620. });
  17621. }
  17622. args.push(curArg);
  17623. }
  17624. return exports2.setup(Object.create(new.target.prototype), globalObject, args);
  17625. }
  17626. toJSON() {
  17627. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17628. if (!exports2.is(esValue)) {
  17629. throw new globalObject.TypeError("'toJSON' called on an object that is not a valid instance of URL.");
  17630. }
  17631. return esValue[implSymbol].toJSON();
  17632. }
  17633. get href() {
  17634. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17635. if (!exports2.is(esValue)) {
  17636. throw new globalObject.TypeError("'get href' called on an object that is not a valid instance of URL.");
  17637. }
  17638. return esValue[implSymbol]["href"];
  17639. }
  17640. set href(V) {
  17641. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17642. if (!exports2.is(esValue)) {
  17643. throw new globalObject.TypeError("'set href' called on an object that is not a valid instance of URL.");
  17644. }
  17645. V = conversions["USVString"](V, {
  17646. context: "Failed to set the 'href' property on 'URL': The provided value",
  17647. globals: globalObject
  17648. });
  17649. esValue[implSymbol]["href"] = V;
  17650. }
  17651. toString() {
  17652. const esValue = this;
  17653. if (!exports2.is(esValue)) {
  17654. throw new globalObject.TypeError("'toString' called on an object that is not a valid instance of URL.");
  17655. }
  17656. return esValue[implSymbol]["href"];
  17657. }
  17658. get origin() {
  17659. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17660. if (!exports2.is(esValue)) {
  17661. throw new globalObject.TypeError("'get origin' called on an object that is not a valid instance of URL.");
  17662. }
  17663. return esValue[implSymbol]["origin"];
  17664. }
  17665. get protocol() {
  17666. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17667. if (!exports2.is(esValue)) {
  17668. throw new globalObject.TypeError("'get protocol' called on an object that is not a valid instance of URL.");
  17669. }
  17670. return esValue[implSymbol]["protocol"];
  17671. }
  17672. set protocol(V) {
  17673. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17674. if (!exports2.is(esValue)) {
  17675. throw new globalObject.TypeError("'set protocol' called on an object that is not a valid instance of URL.");
  17676. }
  17677. V = conversions["USVString"](V, {
  17678. context: "Failed to set the 'protocol' property on 'URL': The provided value",
  17679. globals: globalObject
  17680. });
  17681. esValue[implSymbol]["protocol"] = V;
  17682. }
  17683. get username() {
  17684. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17685. if (!exports2.is(esValue)) {
  17686. throw new globalObject.TypeError("'get username' called on an object that is not a valid instance of URL.");
  17687. }
  17688. return esValue[implSymbol]["username"];
  17689. }
  17690. set username(V) {
  17691. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17692. if (!exports2.is(esValue)) {
  17693. throw new globalObject.TypeError("'set username' called on an object that is not a valid instance of URL.");
  17694. }
  17695. V = conversions["USVString"](V, {
  17696. context: "Failed to set the 'username' property on 'URL': The provided value",
  17697. globals: globalObject
  17698. });
  17699. esValue[implSymbol]["username"] = V;
  17700. }
  17701. get password() {
  17702. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17703. if (!exports2.is(esValue)) {
  17704. throw new globalObject.TypeError("'get password' called on an object that is not a valid instance of URL.");
  17705. }
  17706. return esValue[implSymbol]["password"];
  17707. }
  17708. set password(V) {
  17709. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17710. if (!exports2.is(esValue)) {
  17711. throw new globalObject.TypeError("'set password' called on an object that is not a valid instance of URL.");
  17712. }
  17713. V = conversions["USVString"](V, {
  17714. context: "Failed to set the 'password' property on 'URL': The provided value",
  17715. globals: globalObject
  17716. });
  17717. esValue[implSymbol]["password"] = V;
  17718. }
  17719. get host() {
  17720. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17721. if (!exports2.is(esValue)) {
  17722. throw new globalObject.TypeError("'get host' called on an object that is not a valid instance of URL.");
  17723. }
  17724. return esValue[implSymbol]["host"];
  17725. }
  17726. set host(V) {
  17727. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17728. if (!exports2.is(esValue)) {
  17729. throw new globalObject.TypeError("'set host' called on an object that is not a valid instance of URL.");
  17730. }
  17731. V = conversions["USVString"](V, {
  17732. context: "Failed to set the 'host' property on 'URL': The provided value",
  17733. globals: globalObject
  17734. });
  17735. esValue[implSymbol]["host"] = V;
  17736. }
  17737. get hostname() {
  17738. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17739. if (!exports2.is(esValue)) {
  17740. throw new globalObject.TypeError("'get hostname' called on an object that is not a valid instance of URL.");
  17741. }
  17742. return esValue[implSymbol]["hostname"];
  17743. }
  17744. set hostname(V) {
  17745. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17746. if (!exports2.is(esValue)) {
  17747. throw new globalObject.TypeError("'set hostname' called on an object that is not a valid instance of URL.");
  17748. }
  17749. V = conversions["USVString"](V, {
  17750. context: "Failed to set the 'hostname' property on 'URL': The provided value",
  17751. globals: globalObject
  17752. });
  17753. esValue[implSymbol]["hostname"] = V;
  17754. }
  17755. get port() {
  17756. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17757. if (!exports2.is(esValue)) {
  17758. throw new globalObject.TypeError("'get port' called on an object that is not a valid instance of URL.");
  17759. }
  17760. return esValue[implSymbol]["port"];
  17761. }
  17762. set port(V) {
  17763. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17764. if (!exports2.is(esValue)) {
  17765. throw new globalObject.TypeError("'set port' called on an object that is not a valid instance of URL.");
  17766. }
  17767. V = conversions["USVString"](V, {
  17768. context: "Failed to set the 'port' property on 'URL': The provided value",
  17769. globals: globalObject
  17770. });
  17771. esValue[implSymbol]["port"] = V;
  17772. }
  17773. get pathname() {
  17774. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17775. if (!exports2.is(esValue)) {
  17776. throw new globalObject.TypeError("'get pathname' called on an object that is not a valid instance of URL.");
  17777. }
  17778. return esValue[implSymbol]["pathname"];
  17779. }
  17780. set pathname(V) {
  17781. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17782. if (!exports2.is(esValue)) {
  17783. throw new globalObject.TypeError("'set pathname' called on an object that is not a valid instance of URL.");
  17784. }
  17785. V = conversions["USVString"](V, {
  17786. context: "Failed to set the 'pathname' property on 'URL': The provided value",
  17787. globals: globalObject
  17788. });
  17789. esValue[implSymbol]["pathname"] = V;
  17790. }
  17791. get search() {
  17792. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17793. if (!exports2.is(esValue)) {
  17794. throw new globalObject.TypeError("'get search' called on an object that is not a valid instance of URL.");
  17795. }
  17796. return esValue[implSymbol]["search"];
  17797. }
  17798. set search(V) {
  17799. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17800. if (!exports2.is(esValue)) {
  17801. throw new globalObject.TypeError("'set search' called on an object that is not a valid instance of URL.");
  17802. }
  17803. V = conversions["USVString"](V, {
  17804. context: "Failed to set the 'search' property on 'URL': The provided value",
  17805. globals: globalObject
  17806. });
  17807. esValue[implSymbol]["search"] = V;
  17808. }
  17809. get searchParams() {
  17810. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17811. if (!exports2.is(esValue)) {
  17812. throw new globalObject.TypeError("'get searchParams' called on an object that is not a valid instance of URL.");
  17813. }
  17814. return utils.getSameObject(this, "searchParams", () => {
  17815. return utils.tryWrapperForImpl(esValue[implSymbol]["searchParams"]);
  17816. });
  17817. }
  17818. get hash() {
  17819. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17820. if (!exports2.is(esValue)) {
  17821. throw new globalObject.TypeError("'get hash' called on an object that is not a valid instance of URL.");
  17822. }
  17823. return esValue[implSymbol]["hash"];
  17824. }
  17825. set hash(V) {
  17826. const esValue = this !== null && this !== void 0 ? this : globalObject;
  17827. if (!exports2.is(esValue)) {
  17828. throw new globalObject.TypeError("'set hash' called on an object that is not a valid instance of URL.");
  17829. }
  17830. V = conversions["USVString"](V, {
  17831. context: "Failed to set the 'hash' property on 'URL': The provided value",
  17832. globals: globalObject
  17833. });
  17834. esValue[implSymbol]["hash"] = V;
  17835. }
  17836. };
  17837. __name(_URL, "URL");
  17838. let URL = _URL;
  17839. Object.defineProperties(URL.prototype, {
  17840. toJSON: { enumerable: true },
  17841. href: { enumerable: true },
  17842. toString: { enumerable: true },
  17843. origin: { enumerable: true },
  17844. protocol: { enumerable: true },
  17845. username: { enumerable: true },
  17846. password: { enumerable: true },
  17847. host: { enumerable: true },
  17848. hostname: { enumerable: true },
  17849. port: { enumerable: true },
  17850. pathname: { enumerable: true },
  17851. search: { enumerable: true },
  17852. searchParams: { enumerable: true },
  17853. hash: { enumerable: true },
  17854. [Symbol.toStringTag]: { value: "URL", configurable: true }
  17855. });
  17856. ctorRegistry[interfaceName] = URL;
  17857. Object.defineProperty(globalObject, interfaceName, {
  17858. configurable: true,
  17859. writable: true,
  17860. value: URL
  17861. });
  17862. if (globalNames.includes("Window")) {
  17863. Object.defineProperty(globalObject, "webkitURL", {
  17864. configurable: true,
  17865. writable: true,
  17866. value: URL
  17867. });
  17868. }
  17869. };
  17870. var Impl = require_URL_impl();
  17871. }
  17872. });
  17873. // node_modules/whatwg-url/webidl2js-wrapper.js
  17874. var require_webidl2js_wrapper = __commonJS({
  17875. "node_modules/whatwg-url/webidl2js-wrapper.js"(exports2) {
  17876. "use strict";
  17877. var URL = require_URL();
  17878. var URLSearchParams = require_URLSearchParams();
  17879. exports2.URL = URL;
  17880. exports2.URLSearchParams = URLSearchParams;
  17881. }
  17882. });
  17883. // node_modules/whatwg-url/index.js
  17884. var require_whatwg_url = __commonJS({
  17885. "node_modules/whatwg-url/index.js"(exports2) {
  17886. "use strict";
  17887. var { URL, URLSearchParams } = require_webidl2js_wrapper();
  17888. var urlStateMachine = require_url_state_machine();
  17889. var percentEncoding = require_percent_encoding();
  17890. var sharedGlobalObject = { Array, Object, Promise, String, TypeError };
  17891. URL.install(sharedGlobalObject, ["Window"]);
  17892. URLSearchParams.install(sharedGlobalObject, ["Window"]);
  17893. exports2.URL = sharedGlobalObject.URL;
  17894. exports2.URLSearchParams = sharedGlobalObject.URLSearchParams;
  17895. exports2.parseURL = urlStateMachine.parseURL;
  17896. exports2.basicURLParse = urlStateMachine.basicURLParse;
  17897. exports2.serializeURL = urlStateMachine.serializeURL;
  17898. exports2.serializePath = urlStateMachine.serializePath;
  17899. exports2.serializeHost = urlStateMachine.serializeHost;
  17900. exports2.serializeInteger = urlStateMachine.serializeInteger;
  17901. exports2.serializeURLOrigin = urlStateMachine.serializeURLOrigin;
  17902. exports2.setTheUsername = urlStateMachine.setTheUsername;
  17903. exports2.setThePassword = urlStateMachine.setThePassword;
  17904. exports2.cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort;
  17905. exports2.hasAnOpaquePath = urlStateMachine.hasAnOpaquePath;
  17906. exports2.percentDecodeString = percentEncoding.percentDecodeString;
  17907. exports2.percentDecodeBytes = percentEncoding.percentDecodeBytes;
  17908. }
  17909. });
  17910. // node_modules/mongodb-connection-string-url/lib/redact.js
  17911. var require_redact = __commonJS({
  17912. "node_modules/mongodb-connection-string-url/lib/redact.js"(exports2) {
  17913. "use strict";
  17914. var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
  17915. if (k2 === void 0) k2 = k;
  17916. var desc = Object.getOwnPropertyDescriptor(m, k);
  17917. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  17918. desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
  17919. return m[k];
  17920. }, "get") };
  17921. }
  17922. Object.defineProperty(o, k2, desc);
  17923. } : function(o, m, k, k2) {
  17924. if (k2 === void 0) k2 = k;
  17925. o[k2] = m[k];
  17926. });
  17927. var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
  17928. Object.defineProperty(o, "default", { enumerable: true, value: v });
  17929. } : function(o, v) {
  17930. o["default"] = v;
  17931. });
  17932. var __importStar = exports2 && exports2.__importStar || function(mod) {
  17933. if (mod && mod.__esModule) return mod;
  17934. var result = {};
  17935. if (mod != null) {
  17936. for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  17937. }
  17938. __setModuleDefault(result, mod);
  17939. return result;
  17940. };
  17941. Object.defineProperty(exports2, "__esModule", { value: true });
  17942. exports2.redactConnectionString = exports2.redactValidConnectionString = void 0;
  17943. var index_1 = __importStar(require_lib2());
  17944. function redactValidConnectionString(inputUrl, options) {
  17945. var _a, _b;
  17946. const url = inputUrl.clone();
  17947. const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : "_credentials_";
  17948. const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true;
  17949. if ((url.username || url.password) && redactUsernames) {
  17950. url.username = replacementString;
  17951. url.password = "";
  17952. } else if (url.password) {
  17953. url.password = replacementString;
  17954. }
  17955. if (url.searchParams.has("authMechanismProperties")) {
  17956. const props = new index_1.CommaAndColonSeparatedRecord(url.searchParams.get("authMechanismProperties"));
  17957. if (props.get("AWS_SESSION_TOKEN")) {
  17958. props.set("AWS_SESSION_TOKEN", replacementString);
  17959. url.searchParams.set("authMechanismProperties", props.toString());
  17960. }
  17961. }
  17962. if (url.searchParams.has("tlsCertificateKeyFilePassword")) {
  17963. url.searchParams.set("tlsCertificateKeyFilePassword", replacementString);
  17964. }
  17965. if (url.searchParams.has("proxyUsername") && redactUsernames) {
  17966. url.searchParams.set("proxyUsername", replacementString);
  17967. }
  17968. if (url.searchParams.has("proxyPassword")) {
  17969. url.searchParams.set("proxyPassword", replacementString);
  17970. }
  17971. return url;
  17972. }
  17973. __name(redactValidConnectionString, "redactValidConnectionString");
  17974. exports2.redactValidConnectionString = redactValidConnectionString;
  17975. function redactConnectionString(uri, options) {
  17976. var _a, _b;
  17977. const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : "<credentials>";
  17978. const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true;
  17979. let parsed;
  17980. try {
  17981. parsed = new index_1.default(uri);
  17982. } catch (_c) {
  17983. }
  17984. if (parsed) {
  17985. options = { ...options, replacementString: "___credentials___" };
  17986. return parsed.redact(options).toString().replace(/___credentials___/g, replacementString);
  17987. }
  17988. const R = replacementString;
  17989. const replacements = [
  17990. (uri2) => uri2.replace(redactUsernames ? /(\/\/)(.*)(@)/g : /(\/\/[^@]*:)(.*)(@)/g, `$1${R}$3`),
  17991. (uri2) => uri2.replace(/(AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi, `$1${R}`),
  17992. (uri2) => uri2.replace(/(tlsCertificateKeyFilePassword=)([^&]+)/gi, `$1${R}`),
  17993. (uri2) => redactUsernames ? uri2.replace(/(proxyUsername=)([^&]+)/gi, `$1${R}`) : uri2,
  17994. (uri2) => uri2.replace(/(proxyPassword=)([^&]+)/gi, `$1${R}`)
  17995. ];
  17996. for (const replacer of replacements) {
  17997. uri = replacer(uri);
  17998. }
  17999. return uri;
  18000. }
  18001. __name(redactConnectionString, "redactConnectionString");
  18002. exports2.redactConnectionString = redactConnectionString;
  18003. }
  18004. });
  18005. // node_modules/mongodb-connection-string-url/lib/index.js
  18006. var require_lib2 = __commonJS({
  18007. "node_modules/mongodb-connection-string-url/lib/index.js"(exports2) {
  18008. "use strict";
  18009. Object.defineProperty(exports2, "__esModule", { value: true });
  18010. exports2.CommaAndColonSeparatedRecord = exports2.ConnectionString = exports2.redactConnectionString = void 0;
  18011. var whatwg_url_1 = require_whatwg_url();
  18012. var redact_1 = require_redact();
  18013. Object.defineProperty(exports2, "redactConnectionString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  18014. return redact_1.redactConnectionString;
  18015. }, "get") });
  18016. var DUMMY_HOSTNAME = "__this_is_a_placeholder__";
  18017. function connectionStringHasValidScheme(connectionString) {
  18018. return connectionString.startsWith("mongodb://") || connectionString.startsWith("mongodb+srv://");
  18019. }
  18020. __name(connectionStringHasValidScheme, "connectionStringHasValidScheme");
  18021. var HOSTS_REGEX = /^(?<protocol>[^/]+):\/\/(?:(?<username>[^:@]*)(?::(?<password>[^@]*))?@)?(?<hosts>(?!:)[^/?@]*)(?<rest>.*)/;
  18022. var _CaseInsensitiveMap = class _CaseInsensitiveMap extends Map {
  18023. delete(name) {
  18024. return super.delete(this._normalizeKey(name));
  18025. }
  18026. get(name) {
  18027. return super.get(this._normalizeKey(name));
  18028. }
  18029. has(name) {
  18030. return super.has(this._normalizeKey(name));
  18031. }
  18032. set(name, value) {
  18033. return super.set(this._normalizeKey(name), value);
  18034. }
  18035. _normalizeKey(name) {
  18036. name = `${name}`;
  18037. for (const key of this.keys()) {
  18038. if (key.toLowerCase() === name.toLowerCase()) {
  18039. name = key;
  18040. break;
  18041. }
  18042. }
  18043. return name;
  18044. }
  18045. };
  18046. __name(_CaseInsensitiveMap, "CaseInsensitiveMap");
  18047. var CaseInsensitiveMap = _CaseInsensitiveMap;
  18048. function caseInsenstiveURLSearchParams(Ctor) {
  18049. var _a;
  18050. return _a = class extends Ctor {
  18051. append(name, value) {
  18052. return super.append(this._normalizeKey(name), value);
  18053. }
  18054. delete(name) {
  18055. return super.delete(this._normalizeKey(name));
  18056. }
  18057. get(name) {
  18058. return super.get(this._normalizeKey(name));
  18059. }
  18060. getAll(name) {
  18061. return super.getAll(this._normalizeKey(name));
  18062. }
  18063. has(name) {
  18064. return super.has(this._normalizeKey(name));
  18065. }
  18066. set(name, value) {
  18067. return super.set(this._normalizeKey(name), value);
  18068. }
  18069. keys() {
  18070. return super.keys();
  18071. }
  18072. values() {
  18073. return super.values();
  18074. }
  18075. entries() {
  18076. return super.entries();
  18077. }
  18078. [Symbol.iterator]() {
  18079. return super[Symbol.iterator]();
  18080. }
  18081. _normalizeKey(name) {
  18082. return CaseInsensitiveMap.prototype._normalizeKey.call(this, name);
  18083. }
  18084. }, __name(_a, "CaseInsenstiveURLSearchParams"), _a;
  18085. }
  18086. __name(caseInsenstiveURLSearchParams, "caseInsenstiveURLSearchParams");
  18087. var _URLWithoutHost = class _URLWithoutHost extends whatwg_url_1.URL {
  18088. };
  18089. __name(_URLWithoutHost, "URLWithoutHost");
  18090. var URLWithoutHost = _URLWithoutHost;
  18091. var _MongoParseError = class _MongoParseError extends Error {
  18092. get name() {
  18093. return "MongoParseError";
  18094. }
  18095. };
  18096. __name(_MongoParseError, "MongoParseError");
  18097. var MongoParseError = _MongoParseError;
  18098. var _ConnectionString = class _ConnectionString extends URLWithoutHost {
  18099. constructor(uri, options = {}) {
  18100. var _a;
  18101. const { looseValidation } = options;
  18102. if (!looseValidation && !connectionStringHasValidScheme(uri)) {
  18103. throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"');
  18104. }
  18105. const match = uri.match(HOSTS_REGEX);
  18106. if (!match) {
  18107. throw new MongoParseError(`Invalid connection string "${uri}"`);
  18108. }
  18109. const { protocol, username, password, hosts, rest } = (_a = match.groups) !== null && _a !== void 0 ? _a : {};
  18110. if (!looseValidation) {
  18111. if (!protocol || !hosts) {
  18112. throw new MongoParseError(`Protocol and host list are required in "${uri}"`);
  18113. }
  18114. try {
  18115. decodeURIComponent(username !== null && username !== void 0 ? username : "");
  18116. decodeURIComponent(password !== null && password !== void 0 ? password : "");
  18117. } catch (err) {
  18118. throw new MongoParseError(err.message);
  18119. }
  18120. const illegalCharacters = /[:/?#[\]@]/gi;
  18121. if (username === null || username === void 0 ? void 0 : username.match(illegalCharacters)) {
  18122. throw new MongoParseError(`Username contains unescaped characters ${username}`);
  18123. }
  18124. if (!username || !password) {
  18125. const uriWithoutProtocol = uri.replace(`${protocol}://`, "");
  18126. if (uriWithoutProtocol.startsWith("@") || uriWithoutProtocol.startsWith(":")) {
  18127. throw new MongoParseError("URI contained empty userinfo section");
  18128. }
  18129. }
  18130. if (password === null || password === void 0 ? void 0 : password.match(illegalCharacters)) {
  18131. throw new MongoParseError("Password contains unescaped characters");
  18132. }
  18133. }
  18134. let authString = "";
  18135. if (typeof username === "string")
  18136. authString += username;
  18137. if (typeof password === "string")
  18138. authString += `:${password}`;
  18139. if (authString)
  18140. authString += "@";
  18141. try {
  18142. super(`${protocol.toLowerCase()}://${authString}${DUMMY_HOSTNAME}${rest}`);
  18143. } catch (err) {
  18144. if (looseValidation) {
  18145. new _ConnectionString(uri, {
  18146. ...options,
  18147. looseValidation: false
  18148. });
  18149. }
  18150. if (typeof err.message === "string") {
  18151. err.message = err.message.replace(DUMMY_HOSTNAME, hosts);
  18152. }
  18153. throw err;
  18154. }
  18155. this._hosts = hosts.split(",");
  18156. if (!looseValidation) {
  18157. if (this.isSRV && this.hosts.length !== 1) {
  18158. throw new MongoParseError("mongodb+srv URI cannot have multiple service names");
  18159. }
  18160. if (this.isSRV && this.hosts.some((host) => host.includes(":"))) {
  18161. throw new MongoParseError("mongodb+srv URI cannot have port number");
  18162. }
  18163. }
  18164. if (!this.pathname) {
  18165. this.pathname = "/";
  18166. }
  18167. Object.setPrototypeOf(this.searchParams, caseInsenstiveURLSearchParams(this.searchParams.constructor).prototype);
  18168. }
  18169. get host() {
  18170. return DUMMY_HOSTNAME;
  18171. }
  18172. set host(_ignored) {
  18173. throw new Error("No single host for connection string");
  18174. }
  18175. get hostname() {
  18176. return DUMMY_HOSTNAME;
  18177. }
  18178. set hostname(_ignored) {
  18179. throw new Error("No single host for connection string");
  18180. }
  18181. get port() {
  18182. return "";
  18183. }
  18184. set port(_ignored) {
  18185. throw new Error("No single host for connection string");
  18186. }
  18187. get href() {
  18188. return this.toString();
  18189. }
  18190. set href(_ignored) {
  18191. throw new Error("Cannot set href for connection strings");
  18192. }
  18193. get isSRV() {
  18194. return this.protocol.includes("srv");
  18195. }
  18196. get hosts() {
  18197. return this._hosts;
  18198. }
  18199. set hosts(list) {
  18200. this._hosts = list;
  18201. }
  18202. toString() {
  18203. return super.toString().replace(DUMMY_HOSTNAME, this.hosts.join(","));
  18204. }
  18205. clone() {
  18206. return new _ConnectionString(this.toString(), {
  18207. looseValidation: true
  18208. });
  18209. }
  18210. redact(options) {
  18211. return (0, redact_1.redactValidConnectionString)(this, options);
  18212. }
  18213. typedSearchParams() {
  18214. const sametype = false;
  18215. return this.searchParams;
  18216. }
  18217. [Symbol.for("nodejs.util.inspect.custom")]() {
  18218. const { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash } = this;
  18219. return { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash };
  18220. }
  18221. };
  18222. __name(_ConnectionString, "ConnectionString");
  18223. var ConnectionString = _ConnectionString;
  18224. exports2.ConnectionString = ConnectionString;
  18225. var _CommaAndColonSeparatedRecord = class _CommaAndColonSeparatedRecord extends CaseInsensitiveMap {
  18226. constructor(from) {
  18227. super();
  18228. for (const entry of (from !== null && from !== void 0 ? from : "").split(",")) {
  18229. if (!entry)
  18230. continue;
  18231. const colonIndex = entry.indexOf(":");
  18232. if (colonIndex === -1) {
  18233. this.set(entry, "");
  18234. } else {
  18235. this.set(entry.slice(0, colonIndex), entry.slice(colonIndex + 1));
  18236. }
  18237. }
  18238. }
  18239. toString() {
  18240. return [...this].map((entry) => entry.join(":")).join(",");
  18241. }
  18242. };
  18243. __name(_CommaAndColonSeparatedRecord, "CommaAndColonSeparatedRecord");
  18244. var CommaAndColonSeparatedRecord = _CommaAndColonSeparatedRecord;
  18245. exports2.CommaAndColonSeparatedRecord = CommaAndColonSeparatedRecord;
  18246. exports2.default = ConnectionString;
  18247. }
  18248. });
  18249. // node_modules/mongodb/package.json
  18250. var require_package = __commonJS({
  18251. "node_modules/mongodb/package.json"(exports2, module2) {
  18252. module2.exports = {
  18253. name: "mongodb",
  18254. version: "5.9.2",
  18255. description: "The official MongoDB driver for Node.js",
  18256. main: "lib/index.js",
  18257. files: [
  18258. "lib",
  18259. "src",
  18260. "etc/prepare.js",
  18261. "mongodb.d.ts",
  18262. "tsconfig.json"
  18263. ],
  18264. types: "mongodb.d.ts",
  18265. repository: {
  18266. type: "git",
  18267. url: "git@github.com:mongodb/node-mongodb-native.git"
  18268. },
  18269. keywords: [
  18270. "mongodb",
  18271. "driver",
  18272. "official"
  18273. ],
  18274. author: {
  18275. name: "The MongoDB NodeJS Team",
  18276. email: "dbx-node@mongodb.com"
  18277. },
  18278. dependencies: {
  18279. bson: "^5.5.0",
  18280. "mongodb-connection-string-url": "^2.6.0",
  18281. socks: "^2.7.1"
  18282. },
  18283. optionalDependencies: {
  18284. "@mongodb-js/saslprep": "^1.1.0"
  18285. },
  18286. peerDependencies: {
  18287. "@aws-sdk/credential-providers": "^3.188.0",
  18288. "@mongodb-js/zstd": "^1.0.0",
  18289. kerberos: "^1.0.0 || ^2.0.0",
  18290. "mongodb-client-encryption": ">=2.3.0 <3",
  18291. snappy: "^7.2.2"
  18292. },
  18293. peerDependenciesMeta: {
  18294. "@aws-sdk/credential-providers": {
  18295. optional: true
  18296. },
  18297. "@mongodb-js/zstd": {
  18298. optional: true
  18299. },
  18300. kerberos: {
  18301. optional: true
  18302. },
  18303. snappy: {
  18304. optional: true
  18305. },
  18306. "mongodb-client-encryption": {
  18307. optional: true
  18308. }
  18309. },
  18310. devDependencies: {
  18311. "@iarna/toml": "^2.2.5",
  18312. "@istanbuljs/nyc-config-typescript": "^1.0.2",
  18313. "@microsoft/api-extractor": "^7.35.1",
  18314. "@microsoft/tsdoc-config": "^0.16.2",
  18315. "@mongodb-js/zstd": "^1.1.0",
  18316. "@octokit/core": "^4.2.4",
  18317. "@types/chai": "^4.3.5",
  18318. "@types/chai-subset": "^1.3.3",
  18319. "@types/express": "^4.17.17",
  18320. "@types/kerberos": "^1.1.2",
  18321. "@types/mocha": "^10.0.1",
  18322. "@types/node": "^20.1.0",
  18323. "@types/semver": "^7.5.0",
  18324. "@types/sinon": "^10.0.14",
  18325. "@types/sinon-chai": "^3.2.9",
  18326. "@types/whatwg-url": "^11.0.0",
  18327. "@typescript-eslint/eslint-plugin": "^5.59.5",
  18328. "@typescript-eslint/parser": "^5.59.5",
  18329. chai: "^4.3.7",
  18330. "chai-subset": "^1.6.0",
  18331. chalk: "^4.1.2",
  18332. eslint: "^8.40.0",
  18333. "eslint-config-prettier": "^8.8.0",
  18334. "eslint-plugin-import": "^2.27.5",
  18335. "eslint-plugin-prettier": "^4.2.1",
  18336. "eslint-plugin-simple-import-sort": "^10.0.0",
  18337. "eslint-plugin-tsdoc": "^0.2.17",
  18338. express: "^4.18.2",
  18339. "js-yaml": "^4.1.0",
  18340. mocha: "^10.2.0",
  18341. "mocha-sinon": "^2.1.2",
  18342. "mongodb-legacy": "^5.0.0",
  18343. nyc: "^15.1.0",
  18344. prettier: "^2.8.8",
  18345. semver: "^7.5.0",
  18346. sinon: "^15.0.4",
  18347. "sinon-chai": "^3.7.0",
  18348. snappy: "^7.2.2",
  18349. "source-map-support": "^0.5.21",
  18350. "ts-node": "^10.9.1",
  18351. tsd: "^0.28.1",
  18352. typescript: "^5.0.4",
  18353. "typescript-cached-transpile": "^0.0.6",
  18354. "v8-heapsnapshot": "^1.2.0",
  18355. yargs: "^17.7.2"
  18356. },
  18357. license: "Apache-2.0",
  18358. engines: {
  18359. node: ">=14.20.1"
  18360. },
  18361. bugs: {
  18362. url: "https://jira.mongodb.org/projects/NODE/issues/"
  18363. },
  18364. homepage: "https://github.com/mongodb/node-mongodb-native",
  18365. scripts: {
  18366. "build:evergreen": "node .evergreen/generate_evergreen_tasks.js",
  18367. "build:ts": "node ./node_modules/typescript/bin/tsc",
  18368. "build:dts": "npm run build:ts && api-extractor run && node etc/clean_definition_files.cjs",
  18369. "build:docs": "./etc/docs/build.ts",
  18370. "build:typedoc": "typedoc",
  18371. "build:nightly": "node ./.github/scripts/nightly.mjs",
  18372. "check:bench": "node test/benchmarks/driverBench",
  18373. "check:coverage": "nyc npm run test:all",
  18374. "check:integration-coverage": "nyc npm run check:test",
  18375. "check:lambda": "mocha --config test/mocha_lambda.json test/integration/node-specific/examples/handler.test.js",
  18376. "check:lambda:aws": "mocha --config test/mocha_lambda.json test/integration/node-specific/examples/aws_handler.test.js",
  18377. "check:lint": "npm run build:dts && npm run check:dts && npm run check:eslint && npm run check:tsd",
  18378. "check:eslint": "eslint -v && eslint --max-warnings=0 --ext '.js,.ts' src test",
  18379. "check:tsd": "tsd --version && tsd",
  18380. "check:dependencies": "mocha test/action/dependency.test.ts",
  18381. "check:dts": "node ./node_modules/typescript/bin/tsc --noEmit mongodb.d.ts && tsd",
  18382. "check:search-indexes": "nyc mocha --config test/mocha_mongodb.json test/manual/search-index-management.spec.test.ts",
  18383. "check:test": "mocha --config test/mocha_mongodb.json test/integration",
  18384. "check:unit": "mocha test/unit",
  18385. "check:ts": "node ./node_modules/typescript/bin/tsc -v && node ./node_modules/typescript/bin/tsc --noEmit",
  18386. "check:atlas": "mocha --config test/manual/mocharc.json test/manual/atlas_connectivity.test.js",
  18387. "check:adl": "mocha --config test/mocha_mongodb.json test/manual/atlas-data-lake-testing",
  18388. "check:aws": "nyc mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_aws.test.ts",
  18389. "check:oidc": "mocha --config test/mocha_mongodb.json test/manual/mongodb_oidc.prose.test.ts",
  18390. "check:oidc-azure": "mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_oidc_azure.prose.test.ts",
  18391. "check:ocsp": "mocha --config test/manual/mocharc.json test/manual/ocsp_support.test.js",
  18392. "check:kerberos": "nyc mocha --config test/manual/mocharc.json test/manual/kerberos.test.ts",
  18393. "check:tls": "mocha --config test/manual/mocharc.json test/manual/tls_support.test.js",
  18394. "check:ldap": "nyc mocha --config test/manual/mocharc.json test/manual/ldap.test.js",
  18395. "check:socks5": "mocha --config test/manual/mocharc.json test/manual/socks5.test.ts",
  18396. "check:csfle": "mocha --config test/mocha_mongodb.json test/integration/client-side-encryption",
  18397. "check:snappy": "mocha test/unit/assorted/snappy.test.js",
  18398. "fix:eslint": "npm run check:eslint -- --fix",
  18399. prepare: "node etc/prepare.js",
  18400. "preview:docs": "ts-node etc/docs/preview.ts",
  18401. test: "npm run check:lint && npm run test:all",
  18402. "test:all": "npm run check:unit && npm run check:test",
  18403. "update:docs": "npm run build:docs -- --yes"
  18404. },
  18405. tsd: {
  18406. directory: "test/types",
  18407. compilerOptions: {
  18408. strict: true,
  18409. target: "esnext",
  18410. module: "commonjs",
  18411. moduleResolution: "node"
  18412. }
  18413. }
  18414. };
  18415. }
  18416. });
  18417. // node_modules/mongodb/lib/cmap/handshake/client_metadata.js
  18418. var require_client_metadata = __commonJS({
  18419. "node_modules/mongodb/lib/cmap/handshake/client_metadata.js"(exports2) {
  18420. "use strict";
  18421. Object.defineProperty(exports2, "__esModule", { value: true });
  18422. exports2.getFAASEnv = exports2.makeClientMetadata = exports2.LimitedSizeDocument = void 0;
  18423. var os = require("os");
  18424. var process2 = require("process");
  18425. var bson_1 = require_bson2();
  18426. var error_1 = require_error();
  18427. var NODE_DRIVER_VERSION = require_package().version;
  18428. var _LimitedSizeDocument = class _LimitedSizeDocument {
  18429. constructor(maxSize) {
  18430. this.maxSize = maxSize;
  18431. this.document = /* @__PURE__ */ new Map();
  18432. this.documentSize = 5;
  18433. }
  18434. /** Only adds key/value if the bsonByteLength is less than MAX_SIZE */
  18435. ifItFitsItSits(key, value) {
  18436. const newElementSize = bson_1.BSON.serialize((/* @__PURE__ */ new Map()).set(key, value)).byteLength - 5;
  18437. if (newElementSize + this.documentSize > this.maxSize) {
  18438. return false;
  18439. }
  18440. this.documentSize += newElementSize;
  18441. this.document.set(key, value);
  18442. return true;
  18443. }
  18444. toObject() {
  18445. return bson_1.BSON.deserialize(bson_1.BSON.serialize(this.document), {
  18446. promoteLongs: false,
  18447. promoteBuffers: false,
  18448. promoteValues: false,
  18449. useBigInt64: false
  18450. });
  18451. }
  18452. };
  18453. __name(_LimitedSizeDocument, "LimitedSizeDocument");
  18454. var LimitedSizeDocument = _LimitedSizeDocument;
  18455. exports2.LimitedSizeDocument = LimitedSizeDocument;
  18456. function makeClientMetadata(options) {
  18457. const metadataDocument = new LimitedSizeDocument(512);
  18458. const { appName = "" } = options;
  18459. if (appName.length > 0) {
  18460. const name2 = Buffer.byteLength(appName, "utf8") <= 128 ? options.appName : Buffer.from(appName, "utf8").subarray(0, 128).toString("utf8");
  18461. metadataDocument.ifItFitsItSits("application", { name: name2 });
  18462. }
  18463. const { name = "", version = "", platform = "" } = options.driverInfo;
  18464. const driverInfo = {
  18465. name: name.length > 0 ? `nodejs|${name}` : "nodejs",
  18466. version: version.length > 0 ? `${NODE_DRIVER_VERSION}|${version}` : NODE_DRIVER_VERSION
  18467. };
  18468. if (!metadataDocument.ifItFitsItSits("driver", driverInfo)) {
  18469. throw new error_1.MongoInvalidArgumentError("Unable to include driverInfo name and version, metadata cannot exceed 512 bytes");
  18470. }
  18471. let runtimeInfo = getRuntimeInfo();
  18472. if (platform.length > 0) {
  18473. runtimeInfo = `${runtimeInfo}|${platform}`;
  18474. }
  18475. if (!metadataDocument.ifItFitsItSits("platform", runtimeInfo)) {
  18476. throw new error_1.MongoInvalidArgumentError("Unable to include driverInfo platform, metadata cannot exceed 512 bytes");
  18477. }
  18478. const osInfo = (/* @__PURE__ */ new Map()).set("name", process2.platform).set("architecture", process2.arch).set("version", os.release()).set("type", os.type());
  18479. if (!metadataDocument.ifItFitsItSits("os", osInfo)) {
  18480. for (const key of osInfo.keys()) {
  18481. osInfo.delete(key);
  18482. if (osInfo.size === 0)
  18483. break;
  18484. if (metadataDocument.ifItFitsItSits("os", osInfo))
  18485. break;
  18486. }
  18487. }
  18488. const faasEnv = getFAASEnv();
  18489. if (faasEnv != null) {
  18490. if (!metadataDocument.ifItFitsItSits("env", faasEnv)) {
  18491. for (const key of faasEnv.keys()) {
  18492. faasEnv.delete(key);
  18493. if (faasEnv.size === 0)
  18494. break;
  18495. if (metadataDocument.ifItFitsItSits("env", faasEnv))
  18496. break;
  18497. }
  18498. }
  18499. }
  18500. return metadataDocument.toObject();
  18501. }
  18502. __name(makeClientMetadata, "makeClientMetadata");
  18503. exports2.makeClientMetadata = makeClientMetadata;
  18504. function getFAASEnv() {
  18505. const { AWS_EXECUTION_ENV = "", AWS_LAMBDA_RUNTIME_API = "", FUNCTIONS_WORKER_RUNTIME = "", K_SERVICE = "", FUNCTION_NAME = "", VERCEL = "", AWS_LAMBDA_FUNCTION_MEMORY_SIZE = "", AWS_REGION = "", FUNCTION_MEMORY_MB = "", FUNCTION_REGION = "", FUNCTION_TIMEOUT_SEC = "", VERCEL_REGION = "" } = process2.env;
  18506. const isAWSFaaS = AWS_EXECUTION_ENV.startsWith("AWS_Lambda_") || AWS_LAMBDA_RUNTIME_API.length > 0;
  18507. const isAzureFaaS = FUNCTIONS_WORKER_RUNTIME.length > 0;
  18508. const isGCPFaaS = K_SERVICE.length > 0 || FUNCTION_NAME.length > 0;
  18509. const isVercelFaaS = VERCEL.length > 0;
  18510. const faasEnv = /* @__PURE__ */ new Map();
  18511. if (isVercelFaaS && !(isAzureFaaS || isGCPFaaS)) {
  18512. if (VERCEL_REGION.length > 0) {
  18513. faasEnv.set("region", VERCEL_REGION);
  18514. }
  18515. faasEnv.set("name", "vercel");
  18516. return faasEnv;
  18517. }
  18518. if (isAWSFaaS && !(isAzureFaaS || isGCPFaaS || isVercelFaaS)) {
  18519. if (AWS_REGION.length > 0) {
  18520. faasEnv.set("region", AWS_REGION);
  18521. }
  18522. if (AWS_LAMBDA_FUNCTION_MEMORY_SIZE.length > 0 && Number.isInteger(+AWS_LAMBDA_FUNCTION_MEMORY_SIZE)) {
  18523. faasEnv.set("memory_mb", new bson_1.Int32(AWS_LAMBDA_FUNCTION_MEMORY_SIZE));
  18524. }
  18525. faasEnv.set("name", "aws.lambda");
  18526. return faasEnv;
  18527. }
  18528. if (isAzureFaaS && !(isGCPFaaS || isAWSFaaS || isVercelFaaS)) {
  18529. faasEnv.set("name", "azure.func");
  18530. return faasEnv;
  18531. }
  18532. if (isGCPFaaS && !(isAzureFaaS || isAWSFaaS || isVercelFaaS)) {
  18533. if (FUNCTION_REGION.length > 0) {
  18534. faasEnv.set("region", FUNCTION_REGION);
  18535. }
  18536. if (FUNCTION_MEMORY_MB.length > 0 && Number.isInteger(+FUNCTION_MEMORY_MB)) {
  18537. faasEnv.set("memory_mb", new bson_1.Int32(FUNCTION_MEMORY_MB));
  18538. }
  18539. if (FUNCTION_TIMEOUT_SEC.length > 0 && Number.isInteger(+FUNCTION_TIMEOUT_SEC)) {
  18540. faasEnv.set("timeout_sec", new bson_1.Int32(FUNCTION_TIMEOUT_SEC));
  18541. }
  18542. faasEnv.set("name", "gcp.func");
  18543. return faasEnv;
  18544. }
  18545. return null;
  18546. }
  18547. __name(getFAASEnv, "getFAASEnv");
  18548. exports2.getFAASEnv = getFAASEnv;
  18549. function getRuntimeInfo() {
  18550. var _a, _b;
  18551. if ("Deno" in globalThis) {
  18552. const version = typeof ((_a = Deno == null ? void 0 : Deno.version) == null ? void 0 : _a.deno) === "string" ? (_b = Deno == null ? void 0 : Deno.version) == null ? void 0 : _b.deno : "0.0.0-unknown";
  18553. return `Deno v${version}, ${os.endianness()}`;
  18554. }
  18555. if ("Bun" in globalThis) {
  18556. const version = typeof (Bun == null ? void 0 : Bun.version) === "string" ? Bun == null ? void 0 : Bun.version : "0.0.0-unknown";
  18557. return `Bun v${version}, ${os.endianness()}`;
  18558. }
  18559. return `Node.js ${process2.version}, ${os.endianness()}`;
  18560. }
  18561. __name(getRuntimeInfo, "getRuntimeInfo");
  18562. }
  18563. });
  18564. // node_modules/mongodb/lib/cmap/wire_protocol/compression.js
  18565. var require_compression = __commonJS({
  18566. "node_modules/mongodb/lib/cmap/wire_protocol/compression.js"(exports2) {
  18567. "use strict";
  18568. Object.defineProperty(exports2, "__esModule", { value: true });
  18569. exports2.decompress = exports2.compress = exports2.uncompressibleCommands = exports2.Compressor = void 0;
  18570. var util_1 = require("util");
  18571. var zlib = require("zlib");
  18572. var constants_1 = require_constants2();
  18573. var deps_1 = require_deps();
  18574. var error_1 = require_error();
  18575. exports2.Compressor = Object.freeze({
  18576. none: 0,
  18577. snappy: 1,
  18578. zlib: 2,
  18579. zstd: 3
  18580. });
  18581. exports2.uncompressibleCommands = /* @__PURE__ */ new Set([
  18582. constants_1.LEGACY_HELLO_COMMAND,
  18583. "saslStart",
  18584. "saslContinue",
  18585. "getnonce",
  18586. "authenticate",
  18587. "createUser",
  18588. "updateUser",
  18589. "copydbSaslStart",
  18590. "copydbgetnonce",
  18591. "copydb"
  18592. ]);
  18593. var ZSTD_COMPRESSION_LEVEL = 3;
  18594. var zlibInflate = (0, util_1.promisify)(zlib.inflate.bind(zlib));
  18595. var zlibDeflate = (0, util_1.promisify)(zlib.deflate.bind(zlib));
  18596. var zstd;
  18597. var Snappy = null;
  18598. function loadSnappy() {
  18599. if (Snappy == null) {
  18600. const snappyImport = (0, deps_1.getSnappy)();
  18601. if ("kModuleError" in snappyImport) {
  18602. throw snappyImport.kModuleError;
  18603. }
  18604. Snappy = snappyImport;
  18605. }
  18606. return Snappy;
  18607. }
  18608. __name(loadSnappy, "loadSnappy");
  18609. async function compress(options, dataToBeCompressed) {
  18610. const zlibOptions = {};
  18611. switch (options.agreedCompressor) {
  18612. case "snappy": {
  18613. Snappy ?? (Snappy = loadSnappy());
  18614. return Snappy.compress(dataToBeCompressed);
  18615. }
  18616. case "zstd": {
  18617. loadZstd();
  18618. if ("kModuleError" in zstd) {
  18619. throw zstd["kModuleError"];
  18620. }
  18621. return zstd.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL);
  18622. }
  18623. case "zlib": {
  18624. if (options.zlibCompressionLevel) {
  18625. zlibOptions.level = options.zlibCompressionLevel;
  18626. }
  18627. return zlibDeflate(dataToBeCompressed, zlibOptions);
  18628. }
  18629. default: {
  18630. throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${options.agreedCompressor} failed to compress`);
  18631. }
  18632. }
  18633. }
  18634. __name(compress, "compress");
  18635. exports2.compress = compress;
  18636. async function decompress(compressorID, compressedData) {
  18637. if (compressorID !== exports2.Compressor.snappy && compressorID !== exports2.Compressor.zstd && compressorID !== exports2.Compressor.zlib && compressorID !== exports2.Compressor.none) {
  18638. throw new error_1.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})`);
  18639. }
  18640. switch (compressorID) {
  18641. case exports2.Compressor.snappy: {
  18642. Snappy ?? (Snappy = loadSnappy());
  18643. return Snappy.uncompress(compressedData, { asBuffer: true });
  18644. }
  18645. case exports2.Compressor.zstd: {
  18646. loadZstd();
  18647. if ("kModuleError" in zstd) {
  18648. throw zstd["kModuleError"];
  18649. }
  18650. return zstd.decompress(compressedData);
  18651. }
  18652. case exports2.Compressor.zlib: {
  18653. return zlibInflate(compressedData);
  18654. }
  18655. default: {
  18656. return compressedData;
  18657. }
  18658. }
  18659. }
  18660. __name(decompress, "decompress");
  18661. exports2.decompress = decompress;
  18662. function loadZstd() {
  18663. if (!zstd) {
  18664. zstd = (0, deps_1.getZstdLibrary)();
  18665. }
  18666. }
  18667. __name(loadZstd, "loadZstd");
  18668. }
  18669. });
  18670. // node_modules/mongodb/lib/encrypter.js
  18671. var require_encrypter = __commonJS({
  18672. "node_modules/mongodb/lib/encrypter.js"(exports2) {
  18673. "use strict";
  18674. Object.defineProperty(exports2, "__esModule", { value: true });
  18675. exports2.Encrypter = void 0;
  18676. var constants_1 = require_constants2();
  18677. var error_1 = require_error();
  18678. var mongo_client_1 = require_mongo_client();
  18679. var utils_1 = require_utils();
  18680. var AutoEncrypterClass;
  18681. var kInternalClient = Symbol("internalClient");
  18682. var _Encrypter = class _Encrypter {
  18683. constructor(client, uri, options) {
  18684. if (typeof options.autoEncryption !== "object") {
  18685. throw new error_1.MongoInvalidArgumentError('Option "autoEncryption" must be specified');
  18686. }
  18687. this[kInternalClient] = null;
  18688. this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption;
  18689. this.needsConnecting = false;
  18690. if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) {
  18691. options.autoEncryption.keyVaultClient = client;
  18692. } else if (options.autoEncryption.keyVaultClient == null) {
  18693. options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options);
  18694. }
  18695. if (this.bypassAutoEncryption) {
  18696. options.autoEncryption.metadataClient = void 0;
  18697. } else if (options.maxPoolSize === 0) {
  18698. options.autoEncryption.metadataClient = client;
  18699. } else {
  18700. options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options);
  18701. }
  18702. if (options.proxyHost) {
  18703. options.autoEncryption.proxyOptions = {
  18704. proxyHost: options.proxyHost,
  18705. proxyPort: options.proxyPort,
  18706. proxyUsername: options.proxyUsername,
  18707. proxyPassword: options.proxyPassword
  18708. };
  18709. }
  18710. this.autoEncrypter = new AutoEncrypterClass(client, options.autoEncryption);
  18711. }
  18712. getInternalClient(client, uri, options) {
  18713. let internalClient = this[kInternalClient];
  18714. if (internalClient == null) {
  18715. const clonedOptions = {};
  18716. for (const key of [
  18717. ...Object.getOwnPropertyNames(options),
  18718. ...Object.getOwnPropertySymbols(options)
  18719. ]) {
  18720. if (["autoEncryption", "minPoolSize", "servers", "caseTranslate", "dbName"].includes(key))
  18721. continue;
  18722. Reflect.set(clonedOptions, key, Reflect.get(options, key));
  18723. }
  18724. clonedOptions.minPoolSize = 0;
  18725. internalClient = new mongo_client_1.MongoClient(uri, clonedOptions);
  18726. this[kInternalClient] = internalClient;
  18727. for (const eventName of constants_1.MONGO_CLIENT_EVENTS) {
  18728. for (const listener of client.listeners(eventName)) {
  18729. internalClient.on(eventName, listener);
  18730. }
  18731. }
  18732. client.on("newListener", (eventName, listener) => {
  18733. internalClient == null ? void 0 : internalClient.on(eventName, listener);
  18734. });
  18735. this.needsConnecting = true;
  18736. }
  18737. return internalClient;
  18738. }
  18739. async connectInternalClient() {
  18740. const internalClient = this[kInternalClient];
  18741. if (this.needsConnecting && internalClient != null) {
  18742. this.needsConnecting = false;
  18743. await internalClient.connect();
  18744. }
  18745. }
  18746. close(client, force, callback) {
  18747. this.autoEncrypter.teardown(!!force, (e) => {
  18748. const internalClient = this[kInternalClient];
  18749. if (internalClient != null && client !== internalClient) {
  18750. internalClient.close(force).then(() => callback(), (error) => callback(error));
  18751. return;
  18752. }
  18753. callback(e);
  18754. });
  18755. }
  18756. static checkForMongoCrypt() {
  18757. const mongodbClientEncryption = (0, utils_1.getMongoDBClientEncryption)();
  18758. if (mongodbClientEncryption == null) {
  18759. throw new error_1.MongoMissingDependencyError("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project");
  18760. }
  18761. AutoEncrypterClass = mongodbClientEncryption.extension(require_lib3()).AutoEncrypter;
  18762. }
  18763. };
  18764. __name(_Encrypter, "Encrypter");
  18765. var Encrypter = _Encrypter;
  18766. exports2.Encrypter = Encrypter;
  18767. }
  18768. });
  18769. // node_modules/mongodb/lib/mongo_logger.js
  18770. var require_mongo_logger = __commonJS({
  18771. "node_modules/mongodb/lib/mongo_logger.js"(exports2) {
  18772. "use strict";
  18773. Object.defineProperty(exports2, "__esModule", { value: true });
  18774. exports2.MongoLogger = exports2.stringifyWithMaxLen = exports2.createStdioLogger = exports2.MongoLoggableComponent = exports2.SEVERITY_LEVEL_MAP = exports2.DEFAULT_MAX_DOCUMENT_LENGTH = exports2.SeverityLevel = void 0;
  18775. var bson_1 = require_bson();
  18776. var util_1 = require("util");
  18777. var constants_1 = require_constants2();
  18778. var utils_1 = require_utils();
  18779. exports2.SeverityLevel = Object.freeze({
  18780. EMERGENCY: "emergency",
  18781. ALERT: "alert",
  18782. CRITICAL: "critical",
  18783. ERROR: "error",
  18784. WARNING: "warn",
  18785. NOTICE: "notice",
  18786. INFORMATIONAL: "info",
  18787. DEBUG: "debug",
  18788. TRACE: "trace",
  18789. OFF: "off"
  18790. });
  18791. exports2.DEFAULT_MAX_DOCUMENT_LENGTH = 1e3;
  18792. var _SeverityLevelMap = class _SeverityLevelMap extends Map {
  18793. constructor(entries) {
  18794. const newEntries = [];
  18795. for (const [level, value] of entries) {
  18796. newEntries.push([value, level]);
  18797. }
  18798. newEntries.push(...entries);
  18799. super(newEntries);
  18800. }
  18801. getNumericSeverityLevel(severity) {
  18802. return this.get(severity);
  18803. }
  18804. getSeverityLevelName(level) {
  18805. return this.get(level);
  18806. }
  18807. };
  18808. __name(_SeverityLevelMap, "SeverityLevelMap");
  18809. var SeverityLevelMap = _SeverityLevelMap;
  18810. exports2.SEVERITY_LEVEL_MAP = new SeverityLevelMap([
  18811. [exports2.SeverityLevel.OFF, -Infinity],
  18812. [exports2.SeverityLevel.EMERGENCY, 0],
  18813. [exports2.SeverityLevel.ALERT, 1],
  18814. [exports2.SeverityLevel.CRITICAL, 2],
  18815. [exports2.SeverityLevel.ERROR, 3],
  18816. [exports2.SeverityLevel.WARNING, 4],
  18817. [exports2.SeverityLevel.NOTICE, 5],
  18818. [exports2.SeverityLevel.INFORMATIONAL, 6],
  18819. [exports2.SeverityLevel.DEBUG, 7],
  18820. [exports2.SeverityLevel.TRACE, 8]
  18821. ]);
  18822. exports2.MongoLoggableComponent = Object.freeze({
  18823. COMMAND: "command",
  18824. TOPOLOGY: "topology",
  18825. SERVER_SELECTION: "serverSelection",
  18826. CONNECTION: "connection"
  18827. });
  18828. function parseSeverityFromString(s) {
  18829. const validSeverities = Object.values(exports2.SeverityLevel);
  18830. const lowerSeverity = s == null ? void 0 : s.toLowerCase();
  18831. if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) {
  18832. return lowerSeverity;
  18833. }
  18834. return null;
  18835. }
  18836. __name(parseSeverityFromString, "parseSeverityFromString");
  18837. function createStdioLogger(stream) {
  18838. return {
  18839. write: /* @__PURE__ */ __name((log) => {
  18840. stream.write((0, util_1.inspect)(log, { compact: true, breakLength: Infinity }), "utf-8");
  18841. return;
  18842. }, "write")
  18843. };
  18844. }
  18845. __name(createStdioLogger, "createStdioLogger");
  18846. exports2.createStdioLogger = createStdioLogger;
  18847. function resolveLogPath({ MONGODB_LOG_PATH }, { mongodbLogPath }) {
  18848. if (typeof mongodbLogPath === "string" && /^stderr$/i.test(mongodbLogPath)) {
  18849. return createStdioLogger(process.stderr);
  18850. }
  18851. if (typeof mongodbLogPath === "string" && /^stdout$/i.test(mongodbLogPath)) {
  18852. return createStdioLogger(process.stdout);
  18853. }
  18854. if (typeof mongodbLogPath === "object" && typeof (mongodbLogPath == null ? void 0 : mongodbLogPath.write) === "function") {
  18855. return mongodbLogPath;
  18856. }
  18857. if (MONGODB_LOG_PATH && /^stderr$/i.test(MONGODB_LOG_PATH)) {
  18858. return createStdioLogger(process.stderr);
  18859. }
  18860. if (MONGODB_LOG_PATH && /^stdout$/i.test(MONGODB_LOG_PATH)) {
  18861. return createStdioLogger(process.stdout);
  18862. }
  18863. return createStdioLogger(process.stderr);
  18864. }
  18865. __name(resolveLogPath, "resolveLogPath");
  18866. function compareSeverity(s0, s1) {
  18867. const s0Num = exports2.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s0);
  18868. const s1Num = exports2.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s1);
  18869. return s0Num < s1Num ? -1 : s0Num > s1Num ? 1 : 0;
  18870. }
  18871. __name(compareSeverity, "compareSeverity");
  18872. function stringifyWithMaxLen(value, maxDocumentLength) {
  18873. const ejson = bson_1.EJSON.stringify(value);
  18874. return maxDocumentLength !== 0 && ejson.length > maxDocumentLength ? `${ejson.slice(0, maxDocumentLength)}...` : ejson;
  18875. }
  18876. __name(stringifyWithMaxLen, "stringifyWithMaxLen");
  18877. exports2.stringifyWithMaxLen = stringifyWithMaxLen;
  18878. function isLogConvertible(obj) {
  18879. const objAsLogConvertible = obj;
  18880. return objAsLogConvertible.toLog !== void 0 && typeof objAsLogConvertible.toLog === "function";
  18881. }
  18882. __name(isLogConvertible, "isLogConvertible");
  18883. function attachCommandFields(log, commandEvent) {
  18884. log.commandName = commandEvent.commandName;
  18885. log.requestId = commandEvent.requestId;
  18886. log.driverConnectionId = commandEvent == null ? void 0 : commandEvent.connectionId;
  18887. const { host, port } = utils_1.HostAddress.fromString(commandEvent.address).toHostPort();
  18888. log.serverHost = host;
  18889. log.serverPort = port;
  18890. if (commandEvent == null ? void 0 : commandEvent.serviceId) {
  18891. log.serviceId = commandEvent.serviceId.toHexString();
  18892. }
  18893. return log;
  18894. }
  18895. __name(attachCommandFields, "attachCommandFields");
  18896. function attachConnectionFields(log, connectionPoolEvent) {
  18897. const { host, port } = utils_1.HostAddress.fromString(connectionPoolEvent.address).toHostPort();
  18898. log.serverHost = host;
  18899. log.serverPort = port;
  18900. return log;
  18901. }
  18902. __name(attachConnectionFields, "attachConnectionFields");
  18903. function defaultLogTransform(logObject, maxDocumentLength = exports2.DEFAULT_MAX_DOCUMENT_LENGTH) {
  18904. var _a;
  18905. let log = /* @__PURE__ */ Object.create(null);
  18906. switch (logObject.name) {
  18907. case constants_1.COMMAND_STARTED:
  18908. log = attachCommandFields(log, logObject);
  18909. log.message = "Command started";
  18910. log.command = stringifyWithMaxLen(logObject.command, maxDocumentLength);
  18911. log.databaseName = logObject.databaseName;
  18912. return log;
  18913. case constants_1.COMMAND_SUCCEEDED:
  18914. log = attachCommandFields(log, logObject);
  18915. log.message = "Command succeeded";
  18916. log.durationMS = logObject.duration;
  18917. log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength);
  18918. return log;
  18919. case constants_1.COMMAND_FAILED:
  18920. log = attachCommandFields(log, logObject);
  18921. log.message = "Command failed";
  18922. log.durationMS = logObject.duration;
  18923. log.failure = logObject.failure;
  18924. return log;
  18925. case constants_1.CONNECTION_POOL_CREATED:
  18926. log = attachConnectionFields(log, logObject);
  18927. log.message = "Connection pool created";
  18928. if (logObject.options) {
  18929. const { maxIdleTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS } = logObject.options;
  18930. log = {
  18931. ...log,
  18932. maxIdleTimeMS,
  18933. minPoolSize,
  18934. maxPoolSize,
  18935. maxConnecting,
  18936. waitQueueTimeoutMS
  18937. };
  18938. }
  18939. return log;
  18940. case constants_1.CONNECTION_POOL_READY:
  18941. log = attachConnectionFields(log, logObject);
  18942. log.message = "Connection pool ready";
  18943. return log;
  18944. case constants_1.CONNECTION_POOL_CLEARED:
  18945. log = attachConnectionFields(log, logObject);
  18946. log.message = "Connection pool cleared";
  18947. if (((_a = logObject.serviceId) == null ? void 0 : _a._bsontype) === "ObjectId") {
  18948. log.serviceId = logObject.serviceId.toHexString();
  18949. }
  18950. return log;
  18951. case constants_1.CONNECTION_POOL_CLOSED:
  18952. log = attachConnectionFields(log, logObject);
  18953. log.message = "Connection pool closed";
  18954. return log;
  18955. case constants_1.CONNECTION_CREATED:
  18956. log = attachConnectionFields(log, logObject);
  18957. log.message = "Connection created";
  18958. log.driverConnectionId = logObject.connectionId;
  18959. return log;
  18960. case constants_1.CONNECTION_READY:
  18961. log = attachConnectionFields(log, logObject);
  18962. log.message = "Connection ready";
  18963. log.driverConnectionId = logObject.connectionId;
  18964. return log;
  18965. case constants_1.CONNECTION_CLOSED:
  18966. log = attachConnectionFields(log, logObject);
  18967. log.message = "Connection closed";
  18968. log.driverConnectionId = logObject.connectionId;
  18969. switch (logObject.reason) {
  18970. case "stale":
  18971. log.reason = "Connection became stale because the pool was cleared";
  18972. break;
  18973. case "idle":
  18974. log.reason = "Connection has been available but unused for longer than the configured max idle time";
  18975. break;
  18976. case "error":
  18977. log.reason = "An error occurred while using the connection";
  18978. if (logObject.error) {
  18979. log.error = logObject.error;
  18980. }
  18981. break;
  18982. case "poolClosed":
  18983. log.reason = "Connection pool was closed";
  18984. break;
  18985. default:
  18986. log.reason = `Unknown close reason: ${logObject.reason}`;
  18987. }
  18988. return log;
  18989. case constants_1.CONNECTION_CHECK_OUT_STARTED:
  18990. log = attachConnectionFields(log, logObject);
  18991. log.message = "Connection checkout started";
  18992. return log;
  18993. case constants_1.CONNECTION_CHECK_OUT_FAILED:
  18994. log = attachConnectionFields(log, logObject);
  18995. log.message = "Connection checkout failed";
  18996. switch (logObject.reason) {
  18997. case "poolClosed":
  18998. log.reason = "Connection pool was closed";
  18999. break;
  19000. case "timeout":
  19001. log.reason = "Wait queue timeout elapsed without a connection becoming available";
  19002. break;
  19003. case "connectionError":
  19004. log.reason = "An error occurred while trying to establish a new connection";
  19005. if (logObject.error) {
  19006. log.error = logObject.error;
  19007. }
  19008. break;
  19009. default:
  19010. log.reason = `Unknown close reason: ${logObject.reason}`;
  19011. }
  19012. return log;
  19013. case constants_1.CONNECTION_CHECKED_OUT:
  19014. log = attachConnectionFields(log, logObject);
  19015. log.message = "Connection checked out";
  19016. log.driverConnectionId = logObject.connectionId;
  19017. return log;
  19018. case constants_1.CONNECTION_CHECKED_IN:
  19019. log = attachConnectionFields(log, logObject);
  19020. log.message = "Connection checked in";
  19021. log.driverConnectionId = logObject.connectionId;
  19022. return log;
  19023. default:
  19024. for (const [key, value] of Object.entries(logObject)) {
  19025. if (value != null)
  19026. log[key] = value;
  19027. }
  19028. }
  19029. return log;
  19030. }
  19031. __name(defaultLogTransform, "defaultLogTransform");
  19032. var _MongoLogger = class _MongoLogger {
  19033. constructor(options) {
  19034. this.error = this.log.bind(this, "error");
  19035. this.warn = this.log.bind(this, "warn");
  19036. this.info = this.log.bind(this, "info");
  19037. this.debug = this.log.bind(this, "debug");
  19038. this.trace = this.log.bind(this, "trace");
  19039. this.componentSeverities = options.componentSeverities;
  19040. this.maxDocumentLength = options.maxDocumentLength;
  19041. this.logDestination = options.logDestination;
  19042. }
  19043. log(severity, component, message) {
  19044. if (compareSeverity(severity, this.componentSeverities[component]) > 0)
  19045. return;
  19046. let logMessage = { t: /* @__PURE__ */ new Date(), c: component, s: severity };
  19047. if (typeof message === "string") {
  19048. logMessage.message = message;
  19049. } else if (typeof message === "object") {
  19050. if (isLogConvertible(message)) {
  19051. logMessage = { ...logMessage, ...message.toLog() };
  19052. } else {
  19053. logMessage = { ...logMessage, ...defaultLogTransform(message, this.maxDocumentLength) };
  19054. }
  19055. }
  19056. this.logDestination.write(logMessage);
  19057. }
  19058. /**
  19059. * Merges options set through environment variables and the MongoClient, preferring environment
  19060. * variables when both are set, and substituting defaults for values not set. Options set in
  19061. * constructor take precedence over both environment variables and MongoClient options.
  19062. *
  19063. * @remarks
  19064. * When parsing component severity levels, invalid values are treated as unset and replaced with
  19065. * the default severity.
  19066. *
  19067. * @param envOptions - options set for the logger from the environment
  19068. * @param clientOptions - options set for the logger in the MongoClient options
  19069. * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger
  19070. */
  19071. static resolveOptions(envOptions, clientOptions) {
  19072. const combinedOptions = {
  19073. ...envOptions,
  19074. ...clientOptions,
  19075. mongodbLogPath: resolveLogPath(envOptions, clientOptions)
  19076. };
  19077. const defaultSeverity = parseSeverityFromString(combinedOptions.MONGODB_LOG_ALL) ?? exports2.SeverityLevel.OFF;
  19078. return {
  19079. componentSeverities: {
  19080. command: parseSeverityFromString(combinedOptions.MONGODB_LOG_COMMAND) ?? defaultSeverity,
  19081. topology: parseSeverityFromString(combinedOptions.MONGODB_LOG_TOPOLOGY) ?? defaultSeverity,
  19082. serverSelection: parseSeverityFromString(combinedOptions.MONGODB_LOG_SERVER_SELECTION) ?? defaultSeverity,
  19083. connection: parseSeverityFromString(combinedOptions.MONGODB_LOG_CONNECTION) ?? defaultSeverity,
  19084. default: defaultSeverity
  19085. },
  19086. maxDocumentLength: (0, utils_1.parseUnsignedInteger)(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1e3,
  19087. logDestination: combinedOptions.mongodbLogPath
  19088. };
  19089. }
  19090. };
  19091. __name(_MongoLogger, "MongoLogger");
  19092. var MongoLogger = _MongoLogger;
  19093. exports2.MongoLogger = MongoLogger;
  19094. }
  19095. });
  19096. // node_modules/mongodb/lib/connection_string.js
  19097. var require_connection_string = __commonJS({
  19098. "node_modules/mongodb/lib/connection_string.js"(exports2) {
  19099. "use strict";
  19100. Object.defineProperty(exports2, "__esModule", { value: true });
  19101. exports2.FEATURE_FLAGS = exports2.DEFAULT_OPTIONS = exports2.OPTIONS = exports2.parseOptions = exports2.resolveSRVRecord = void 0;
  19102. var dns = require("dns");
  19103. var fs = require("fs");
  19104. var mongodb_connection_string_url_1 = require_lib2();
  19105. var url_1 = require("url");
  19106. var mongo_credentials_1 = require_mongo_credentials();
  19107. var providers_1 = require_providers();
  19108. var client_metadata_1 = require_client_metadata();
  19109. var compression_1 = require_compression();
  19110. var encrypter_1 = require_encrypter();
  19111. var error_1 = require_error();
  19112. var mongo_client_1 = require_mongo_client();
  19113. var mongo_logger_1 = require_mongo_logger();
  19114. var read_concern_1 = require_read_concern();
  19115. var read_preference_1 = require_read_preference();
  19116. var utils_1 = require_utils();
  19117. var write_concern_1 = require_write_concern();
  19118. var VALID_TXT_RECORDS = ["authSource", "replicaSet", "loadBalanced"];
  19119. var LB_SINGLE_HOST_ERROR = "loadBalanced option only supported with a single host in the URI";
  19120. var LB_REPLICA_SET_ERROR = "loadBalanced option not supported with a replicaSet option";
  19121. var LB_DIRECT_CONNECTION_ERROR = "loadBalanced option not supported when directConnection is provided";
  19122. async function resolveSRVRecord(options) {
  19123. if (typeof options.srvHost !== "string") {
  19124. throw new error_1.MongoAPIError('Option "srvHost" must not be empty');
  19125. }
  19126. if (options.srvHost.split(".").length < 3) {
  19127. throw new error_1.MongoAPIError("URI must include hostname, domain name, and tld");
  19128. }
  19129. const lookupAddress = options.srvHost;
  19130. const addresses = await dns.promises.resolveSrv(`_${options.srvServiceName}._tcp.${lookupAddress}`);
  19131. if (addresses.length === 0) {
  19132. throw new error_1.MongoAPIError("No addresses found at host");
  19133. }
  19134. for (const { name } of addresses) {
  19135. if (!(0, utils_1.matchesParentDomain)(name, lookupAddress)) {
  19136. throw new error_1.MongoAPIError("Server record does not share hostname with parent URI");
  19137. }
  19138. }
  19139. const hostAddresses = addresses.map((r) => utils_1.HostAddress.fromString(`${r.name}:${r.port ?? 27017}`));
  19140. validateLoadBalancedOptions(hostAddresses, options, true);
  19141. let record;
  19142. try {
  19143. record = await dns.promises.resolveTxt(lookupAddress);
  19144. } catch (error) {
  19145. if (error.code !== "ENODATA" && error.code !== "ENOTFOUND") {
  19146. throw error;
  19147. }
  19148. return hostAddresses;
  19149. }
  19150. if (record.length > 1) {
  19151. throw new error_1.MongoParseError("Multiple text records not allowed");
  19152. }
  19153. const txtRecordOptions = new url_1.URLSearchParams(record[0].join(""));
  19154. const txtRecordOptionKeys = [...txtRecordOptions.keys()];
  19155. if (txtRecordOptionKeys.some((key) => !VALID_TXT_RECORDS.includes(key))) {
  19156. throw new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(", ")}`);
  19157. }
  19158. if (VALID_TXT_RECORDS.some((option) => txtRecordOptions.get(option) === "")) {
  19159. throw new error_1.MongoParseError("Cannot have empty URI params in DNS TXT Record");
  19160. }
  19161. const source = txtRecordOptions.get("authSource") ?? void 0;
  19162. const replicaSet = txtRecordOptions.get("replicaSet") ?? void 0;
  19163. const loadBalanced = txtRecordOptions.get("loadBalanced") ?? void 0;
  19164. if (!options.userSpecifiedAuthSource && source && options.credentials && !providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism)) {
  19165. options.credentials = mongo_credentials_1.MongoCredentials.merge(options.credentials, { source });
  19166. }
  19167. if (!options.userSpecifiedReplicaSet && replicaSet) {
  19168. options.replicaSet = replicaSet;
  19169. }
  19170. if (loadBalanced === "true") {
  19171. options.loadBalanced = true;
  19172. }
  19173. if (options.replicaSet && options.srvMaxHosts > 0) {
  19174. throw new error_1.MongoParseError("Cannot combine replicaSet option with srvMaxHosts");
  19175. }
  19176. validateLoadBalancedOptions(hostAddresses, options, true);
  19177. return hostAddresses;
  19178. }
  19179. __name(resolveSRVRecord, "resolveSRVRecord");
  19180. exports2.resolveSRVRecord = resolveSRVRecord;
  19181. function checkTLSOptions(allOptions) {
  19182. if (!allOptions)
  19183. return;
  19184. const check = /* @__PURE__ */ __name((a, b) => {
  19185. if (allOptions.has(a) && allOptions.has(b)) {
  19186. throw new error_1.MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`);
  19187. }
  19188. }, "check");
  19189. check("tlsInsecure", "tlsAllowInvalidCertificates");
  19190. check("tlsInsecure", "tlsAllowInvalidHostnames");
  19191. check("tlsInsecure", "tlsDisableCertificateRevocationCheck");
  19192. check("tlsInsecure", "tlsDisableOCSPEndpointCheck");
  19193. check("tlsAllowInvalidCertificates", "tlsDisableCertificateRevocationCheck");
  19194. check("tlsAllowInvalidCertificates", "tlsDisableOCSPEndpointCheck");
  19195. check("tlsDisableCertificateRevocationCheck", "tlsDisableOCSPEndpointCheck");
  19196. }
  19197. __name(checkTLSOptions, "checkTLSOptions");
  19198. var TRUTHS = /* @__PURE__ */ new Set(["true", "t", "1", "y", "yes"]);
  19199. var FALSEHOODS = /* @__PURE__ */ new Set(["false", "f", "0", "n", "no", "-1"]);
  19200. function getBoolean(name, value) {
  19201. if (typeof value === "boolean")
  19202. return value;
  19203. const valueString = String(value).toLowerCase();
  19204. if (TRUTHS.has(valueString)) {
  19205. if (valueString !== "true") {
  19206. (0, utils_1.emitWarningOnce)(`deprecated value for ${name} : ${valueString} - please update to ${name} : true instead`);
  19207. }
  19208. return true;
  19209. }
  19210. if (FALSEHOODS.has(valueString)) {
  19211. if (valueString !== "false") {
  19212. (0, utils_1.emitWarningOnce)(`deprecated value for ${name} : ${valueString} - please update to ${name} : false instead`);
  19213. }
  19214. return false;
  19215. }
  19216. throw new error_1.MongoParseError(`Expected ${name} to be stringified boolean value, got: ${value}`);
  19217. }
  19218. __name(getBoolean, "getBoolean");
  19219. function getIntFromOptions(name, value) {
  19220. const parsedInt = (0, utils_1.parseInteger)(value);
  19221. if (parsedInt != null) {
  19222. return parsedInt;
  19223. }
  19224. throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`);
  19225. }
  19226. __name(getIntFromOptions, "getIntFromOptions");
  19227. function getUIntFromOptions(name, value) {
  19228. const parsedValue = getIntFromOptions(name, value);
  19229. if (parsedValue < 0) {
  19230. throw new error_1.MongoParseError(`${name} can only be a positive int value, got: ${value}`);
  19231. }
  19232. return parsedValue;
  19233. }
  19234. __name(getUIntFromOptions, "getUIntFromOptions");
  19235. function* entriesFromString(value) {
  19236. const keyValuePairs = value.split(",");
  19237. for (const keyValue of keyValuePairs) {
  19238. const [key, value2] = keyValue.split(/:(.*)/);
  19239. if (value2 == null) {
  19240. throw new error_1.MongoParseError("Cannot have undefined values in key value pairs");
  19241. }
  19242. yield [key, value2];
  19243. }
  19244. }
  19245. __name(entriesFromString, "entriesFromString");
  19246. var _CaseInsensitiveMap = class _CaseInsensitiveMap extends Map {
  19247. constructor(entries = []) {
  19248. super(entries.map(([k, v]) => [k.toLowerCase(), v]));
  19249. }
  19250. has(k) {
  19251. return super.has(k.toLowerCase());
  19252. }
  19253. get(k) {
  19254. return super.get(k.toLowerCase());
  19255. }
  19256. set(k, v) {
  19257. return super.set(k.toLowerCase(), v);
  19258. }
  19259. delete(k) {
  19260. return super.delete(k.toLowerCase());
  19261. }
  19262. };
  19263. __name(_CaseInsensitiveMap, "CaseInsensitiveMap");
  19264. var CaseInsensitiveMap = _CaseInsensitiveMap;
  19265. function parseOptions(uri, mongoClient = void 0, options = {}) {
  19266. if (mongoClient != null && !(mongoClient instanceof mongo_client_1.MongoClient)) {
  19267. options = mongoClient;
  19268. mongoClient = void 0;
  19269. }
  19270. if (options.useBigInt64 && typeof options.promoteLongs === "boolean" && !options.promoteLongs) {
  19271. throw new error_1.MongoAPIError("Must request either bigint or Long for int64 deserialization");
  19272. }
  19273. if (options.useBigInt64 && typeof options.promoteValues === "boolean" && !options.promoteValues) {
  19274. throw new error_1.MongoAPIError("Must request either bigint or Long for int64 deserialization");
  19275. }
  19276. const url = new mongodb_connection_string_url_1.default(uri);
  19277. const { hosts, isSRV } = url;
  19278. const mongoOptions = /* @__PURE__ */ Object.create(null);
  19279. for (const flag of Object.getOwnPropertySymbols(options)) {
  19280. if (exports2.FEATURE_FLAGS.has(flag)) {
  19281. mongoOptions[flag] = options[flag];
  19282. }
  19283. }
  19284. mongoOptions.hosts = isSRV ? [] : hosts.map(utils_1.HostAddress.fromString);
  19285. const urlOptions = new CaseInsensitiveMap();
  19286. if (url.pathname !== "/" && url.pathname !== "") {
  19287. const dbName = decodeURIComponent(url.pathname[0] === "/" ? url.pathname.slice(1) : url.pathname);
  19288. if (dbName) {
  19289. urlOptions.set("dbName", [dbName]);
  19290. }
  19291. }
  19292. if (url.username !== "") {
  19293. const auth = {
  19294. username: decodeURIComponent(url.username)
  19295. };
  19296. if (typeof url.password === "string") {
  19297. auth.password = decodeURIComponent(url.password);
  19298. }
  19299. urlOptions.set("auth", [auth]);
  19300. }
  19301. for (const key of url.searchParams.keys()) {
  19302. const values = [...url.searchParams.getAll(key)];
  19303. if (values.includes("")) {
  19304. throw new error_1.MongoAPIError("URI cannot contain options with no value");
  19305. }
  19306. if (!urlOptions.has(key)) {
  19307. urlOptions.set(key, values);
  19308. }
  19309. }
  19310. const objectOptions = new CaseInsensitiveMap(Object.entries(options).filter(([, v]) => v != null));
  19311. if (urlOptions.has("serverApi")) {
  19312. throw new error_1.MongoParseError("URI cannot contain `serverApi`, it can only be passed to the client");
  19313. }
  19314. const uriMechanismProperties = urlOptions.get("authMechanismProperties");
  19315. if (uriMechanismProperties) {
  19316. for (const property of uriMechanismProperties) {
  19317. if (/(^|,)ALLOWED_HOSTS:/.test(property)) {
  19318. throw new error_1.MongoParseError("Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.");
  19319. }
  19320. }
  19321. }
  19322. if (objectOptions.has("loadBalanced")) {
  19323. throw new error_1.MongoParseError("loadBalanced is only a valid option in the URI");
  19324. }
  19325. const allProvidedOptions = new CaseInsensitiveMap();
  19326. const allProvidedKeys = /* @__PURE__ */ new Set([...urlOptions.keys(), ...objectOptions.keys()]);
  19327. for (const key of allProvidedKeys) {
  19328. const values = [];
  19329. const objectOptionValue = objectOptions.get(key);
  19330. if (objectOptionValue != null) {
  19331. values.push(objectOptionValue);
  19332. }
  19333. const urlValues = urlOptions.get(key) ?? [];
  19334. values.push(...urlValues);
  19335. allProvidedOptions.set(key, values);
  19336. }
  19337. const didMapTLSCertificateFile = allProvidedOptions.has("tlsCertificateKeyFile") && !allProvidedOptions.has("tlsCertificateFile");
  19338. if (didMapTLSCertificateFile) {
  19339. allProvidedOptions.set("tlsCertificateFile", allProvidedOptions.get("tlsCertificateKeyFile"));
  19340. }
  19341. if (allProvidedOptions.has("tls") || allProvidedOptions.has("ssl")) {
  19342. const tlsAndSslOpts = (allProvidedOptions.get("tls") || []).concat(allProvidedOptions.get("ssl") || []).map(getBoolean.bind(null, "tls/ssl"));
  19343. if (new Set(tlsAndSslOpts).size !== 1) {
  19344. throw new error_1.MongoParseError("All values of tls/ssl must be the same.");
  19345. }
  19346. }
  19347. checkTLSOptions(allProvidedOptions);
  19348. const unsupportedOptions = (0, utils_1.setDifference)(allProvidedKeys, Array.from(Object.keys(exports2.OPTIONS)).map((s) => s.toLowerCase()));
  19349. if (unsupportedOptions.size !== 0) {
  19350. const optionWord = unsupportedOptions.size > 1 ? "options" : "option";
  19351. const isOrAre = unsupportedOptions.size > 1 ? "are" : "is";
  19352. throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(", ")} ${isOrAre} not supported`);
  19353. }
  19354. for (const [key, descriptor] of Object.entries(exports2.OPTIONS)) {
  19355. const values = allProvidedOptions.get(key);
  19356. if (!values || values.length === 0) {
  19357. if (exports2.DEFAULT_OPTIONS.has(key)) {
  19358. setOption(mongoOptions, key, descriptor, [exports2.DEFAULT_OPTIONS.get(key)]);
  19359. }
  19360. } else {
  19361. const { deprecated } = descriptor;
  19362. const shouldEmitTLSCertificateFileDeprecation = didMapTLSCertificateFile && key === "tlsCertificateFile";
  19363. if (deprecated && !shouldEmitTLSCertificateFileDeprecation) {
  19364. const deprecatedMsg = typeof deprecated === "string" ? `: ${deprecated}` : "";
  19365. (0, utils_1.emitWarning)(`${key} is a deprecated option${deprecatedMsg}`);
  19366. }
  19367. setOption(mongoOptions, key, descriptor, values);
  19368. }
  19369. }
  19370. if (mongoOptions.credentials) {
  19371. const isGssapi = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI;
  19372. const isX509 = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_X509;
  19373. const isAws = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_AWS;
  19374. const isOidc = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_OIDC;
  19375. if ((isGssapi || isX509) && allProvidedOptions.has("authSource") && mongoOptions.credentials.source !== "$external") {
  19376. throw new error_1.MongoParseError(`authMechanism ${mongoOptions.credentials.mechanism} requires an authSource of '$external'`);
  19377. }
  19378. if (!(isGssapi || isX509 || isAws || isOidc) && mongoOptions.dbName && !allProvidedOptions.has("authSource")) {
  19379. mongoOptions.credentials = mongo_credentials_1.MongoCredentials.merge(mongoOptions.credentials, {
  19380. source: mongoOptions.dbName
  19381. });
  19382. }
  19383. if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) {
  19384. throw new error_1.MongoMissingCredentialsError(`When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified`);
  19385. }
  19386. mongoOptions.credentials.validate();
  19387. if (mongoOptions.credentials.password === "" && mongoOptions.credentials.username === "" && mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && Object.keys(mongoOptions.credentials.mechanismProperties).length === 0) {
  19388. delete mongoOptions.credentials;
  19389. }
  19390. }
  19391. if (!mongoOptions.dbName) {
  19392. mongoOptions.dbName = "test";
  19393. }
  19394. validateLoadBalancedOptions(hosts, mongoOptions, isSRV);
  19395. if (mongoClient && mongoOptions.autoEncryption) {
  19396. encrypter_1.Encrypter.checkForMongoCrypt();
  19397. mongoOptions.encrypter = new encrypter_1.Encrypter(mongoClient, uri, options);
  19398. mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter;
  19399. }
  19400. mongoOptions.userSpecifiedAuthSource = objectOptions.has("authSource") || urlOptions.has("authSource");
  19401. mongoOptions.userSpecifiedReplicaSet = objectOptions.has("replicaSet") || urlOptions.has("replicaSet");
  19402. if (isSRV) {
  19403. mongoOptions.srvHost = hosts[0];
  19404. if (mongoOptions.directConnection) {
  19405. throw new error_1.MongoAPIError("SRV URI does not support directConnection");
  19406. }
  19407. if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === "string") {
  19408. throw new error_1.MongoParseError("Cannot use srvMaxHosts option with replicaSet");
  19409. }
  19410. const noUserSpecifiedTLS = !objectOptions.has("tls") && !urlOptions.has("tls");
  19411. const noUserSpecifiedSSL = !objectOptions.has("ssl") && !urlOptions.has("ssl");
  19412. if (noUserSpecifiedTLS && noUserSpecifiedSSL) {
  19413. mongoOptions.tls = true;
  19414. }
  19415. } else {
  19416. const userSpecifiedSrvOptions = urlOptions.has("srvMaxHosts") || objectOptions.has("srvMaxHosts") || urlOptions.has("srvServiceName") || objectOptions.has("srvServiceName");
  19417. if (userSpecifiedSrvOptions) {
  19418. throw new error_1.MongoParseError("Cannot use srvMaxHosts or srvServiceName with a non-srv connection string");
  19419. }
  19420. }
  19421. if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) {
  19422. throw new error_1.MongoParseError("directConnection option requires exactly one host");
  19423. }
  19424. if (!mongoOptions.proxyHost && (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword)) {
  19425. throw new error_1.MongoParseError("Must specify proxyHost if other proxy options are passed");
  19426. }
  19427. if (mongoOptions.proxyUsername && !mongoOptions.proxyPassword || !mongoOptions.proxyUsername && mongoOptions.proxyPassword) {
  19428. throw new error_1.MongoParseError("Can only specify both of proxy username/password or neither");
  19429. }
  19430. const proxyOptions = ["proxyHost", "proxyPort", "proxyUsername", "proxyPassword"].map((key) => urlOptions.get(key) ?? []);
  19431. if (proxyOptions.some((options2) => options2.length > 1)) {
  19432. throw new error_1.MongoParseError("Proxy options cannot be specified multiple times in the connection string");
  19433. }
  19434. const loggerFeatureFlag = Symbol.for("@@mdb.enableMongoLogger");
  19435. mongoOptions[loggerFeatureFlag] = mongoOptions[loggerFeatureFlag] ?? false;
  19436. let loggerEnvOptions = {};
  19437. let loggerClientOptions = {};
  19438. if (mongoOptions[loggerFeatureFlag]) {
  19439. loggerEnvOptions = {
  19440. MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND,
  19441. MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY,
  19442. MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION,
  19443. MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION,
  19444. MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL,
  19445. MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH,
  19446. MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH,
  19447. ...mongoOptions[Symbol.for("@@mdb.internalLoggerConfig")]
  19448. };
  19449. loggerClientOptions = {
  19450. mongodbLogPath: mongoOptions.mongodbLogPath
  19451. };
  19452. }
  19453. mongoOptions.mongoLoggerOptions = mongo_logger_1.MongoLogger.resolveOptions(loggerEnvOptions, loggerClientOptions);
  19454. mongoOptions.metadata = (0, client_metadata_1.makeClientMetadata)(mongoOptions);
  19455. return mongoOptions;
  19456. }
  19457. __name(parseOptions, "parseOptions");
  19458. exports2.parseOptions = parseOptions;
  19459. function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) {
  19460. if (mongoOptions.loadBalanced) {
  19461. if (hosts.length > 1) {
  19462. throw new error_1.MongoParseError(LB_SINGLE_HOST_ERROR);
  19463. }
  19464. if (mongoOptions.replicaSet) {
  19465. throw new error_1.MongoParseError(LB_REPLICA_SET_ERROR);
  19466. }
  19467. if (mongoOptions.directConnection) {
  19468. throw new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR);
  19469. }
  19470. if (isSrv && mongoOptions.srvMaxHosts > 0) {
  19471. throw new error_1.MongoParseError("Cannot limit srv hosts with loadBalanced enabled");
  19472. }
  19473. }
  19474. return;
  19475. }
  19476. __name(validateLoadBalancedOptions, "validateLoadBalancedOptions");
  19477. function setOption(mongoOptions, key, descriptor, values) {
  19478. const { target, type, transform } = descriptor;
  19479. const name = target ?? key;
  19480. switch (type) {
  19481. case "boolean":
  19482. mongoOptions[name] = getBoolean(name, values[0]);
  19483. break;
  19484. case "int":
  19485. mongoOptions[name] = getIntFromOptions(name, values[0]);
  19486. break;
  19487. case "uint":
  19488. mongoOptions[name] = getUIntFromOptions(name, values[0]);
  19489. break;
  19490. case "string":
  19491. if (values[0] == null) {
  19492. break;
  19493. }
  19494. mongoOptions[name] = String(values[0]);
  19495. break;
  19496. case "record":
  19497. if (!(0, utils_1.isRecord)(values[0])) {
  19498. throw new error_1.MongoParseError(`${name} must be an object`);
  19499. }
  19500. mongoOptions[name] = values[0];
  19501. break;
  19502. case "any":
  19503. mongoOptions[name] = values[0];
  19504. break;
  19505. default: {
  19506. if (!transform) {
  19507. throw new error_1.MongoParseError("Descriptors missing a type must define a transform");
  19508. }
  19509. const transformValue = transform({ name, options: mongoOptions, values });
  19510. mongoOptions[name] = transformValue;
  19511. break;
  19512. }
  19513. }
  19514. }
  19515. __name(setOption, "setOption");
  19516. exports2.OPTIONS = {
  19517. appName: {
  19518. type: "string"
  19519. },
  19520. auth: {
  19521. target: "credentials",
  19522. transform({ name, options, values: [value] }) {
  19523. if (!(0, utils_1.isRecord)(value, ["username", "password"])) {
  19524. throw new error_1.MongoParseError(`${name} must be an object with 'username' and 'password' properties`);
  19525. }
  19526. return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
  19527. username: value.username,
  19528. password: value.password
  19529. });
  19530. }
  19531. },
  19532. authMechanism: {
  19533. target: "credentials",
  19534. transform({ options, values: [value] }) {
  19535. var _a, _b;
  19536. const mechanisms = Object.values(providers_1.AuthMechanism);
  19537. const [mechanism] = mechanisms.filter((m) => m.match(RegExp(String.raw`\b${value}\b`, "i")));
  19538. if (!mechanism) {
  19539. throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`);
  19540. }
  19541. let source = (_a = options.credentials) == null ? void 0 : _a.source;
  19542. if (mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism)) {
  19543. source = "$external";
  19544. }
  19545. let password = (_b = options.credentials) == null ? void 0 : _b.password;
  19546. if (mechanism === providers_1.AuthMechanism.MONGODB_X509 && password === "") {
  19547. password = void 0;
  19548. }
  19549. return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
  19550. mechanism,
  19551. source,
  19552. password
  19553. });
  19554. }
  19555. },
  19556. authMechanismProperties: {
  19557. target: "credentials",
  19558. transform({ options, values }) {
  19559. let mechanismProperties = /* @__PURE__ */ Object.create(null);
  19560. for (const optionValue of values) {
  19561. if (typeof optionValue === "string") {
  19562. for (const [key, value] of entriesFromString(optionValue)) {
  19563. try {
  19564. mechanismProperties[key] = getBoolean(key, value);
  19565. } catch {
  19566. mechanismProperties[key] = value;
  19567. }
  19568. }
  19569. } else {
  19570. if (!(0, utils_1.isRecord)(optionValue)) {
  19571. throw new error_1.MongoParseError("AuthMechanismProperties must be an object");
  19572. }
  19573. mechanismProperties = { ...optionValue };
  19574. }
  19575. }
  19576. return mongo_credentials_1.MongoCredentials.merge(options.credentials, {
  19577. mechanismProperties
  19578. });
  19579. }
  19580. },
  19581. authSource: {
  19582. target: "credentials",
  19583. transform({ options, values: [value] }) {
  19584. const source = String(value);
  19585. return mongo_credentials_1.MongoCredentials.merge(options.credentials, { source });
  19586. }
  19587. },
  19588. autoEncryption: {
  19589. type: "record"
  19590. },
  19591. bsonRegExp: {
  19592. type: "boolean"
  19593. },
  19594. serverApi: {
  19595. target: "serverApi",
  19596. transform({ values: [version] }) {
  19597. const serverApiToValidate = typeof version === "string" ? { version } : version;
  19598. const versionToValidate = serverApiToValidate && serverApiToValidate.version;
  19599. if (!versionToValidate) {
  19600. throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`);
  19601. }
  19602. if (!Object.values(mongo_client_1.ServerApiVersion).some((v) => v === versionToValidate)) {
  19603. throw new error_1.MongoParseError(`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`);
  19604. }
  19605. return serverApiToValidate;
  19606. }
  19607. },
  19608. checkKeys: {
  19609. type: "boolean"
  19610. },
  19611. compressors: {
  19612. default: "none",
  19613. target: "compressors",
  19614. transform({ values }) {
  19615. const compressionList = /* @__PURE__ */ new Set();
  19616. for (const compVal of values) {
  19617. const compValArray = typeof compVal === "string" ? compVal.split(",") : compVal;
  19618. if (!Array.isArray(compValArray)) {
  19619. throw new error_1.MongoInvalidArgumentError("compressors must be an array or a comma-delimited list of strings");
  19620. }
  19621. for (const c of compValArray) {
  19622. if (Object.keys(compression_1.Compressor).includes(String(c))) {
  19623. compressionList.add(String(c));
  19624. } else {
  19625. throw new error_1.MongoInvalidArgumentError(`${c} is not a valid compression mechanism. Must be one of: ${Object.keys(compression_1.Compressor)}.`);
  19626. }
  19627. }
  19628. }
  19629. return [...compressionList];
  19630. }
  19631. },
  19632. connectTimeoutMS: {
  19633. default: 3e4,
  19634. type: "uint"
  19635. },
  19636. dbName: {
  19637. type: "string"
  19638. },
  19639. directConnection: {
  19640. default: false,
  19641. type: "boolean"
  19642. },
  19643. driverInfo: {
  19644. default: {},
  19645. type: "record"
  19646. },
  19647. enableUtf8Validation: { type: "boolean", default: true },
  19648. family: {
  19649. transform({ name, values: [value] }) {
  19650. const transformValue = getIntFromOptions(name, value);
  19651. if (transformValue === 4 || transformValue === 6) {
  19652. return transformValue;
  19653. }
  19654. throw new error_1.MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`);
  19655. }
  19656. },
  19657. fieldsAsRaw: {
  19658. type: "record"
  19659. },
  19660. forceServerObjectId: {
  19661. default: false,
  19662. type: "boolean"
  19663. },
  19664. fsync: {
  19665. deprecated: "Please use journal instead",
  19666. target: "writeConcern",
  19667. transform({ name, options, values: [value] }) {
  19668. const wc = write_concern_1.WriteConcern.fromOptions({
  19669. writeConcern: {
  19670. ...options.writeConcern,
  19671. fsync: getBoolean(name, value)
  19672. }
  19673. });
  19674. if (!wc)
  19675. throw new error_1.MongoParseError(`Unable to make a writeConcern from fsync=${value}`);
  19676. return wc;
  19677. }
  19678. },
  19679. heartbeatFrequencyMS: {
  19680. default: 1e4,
  19681. type: "uint"
  19682. },
  19683. ignoreUndefined: {
  19684. type: "boolean"
  19685. },
  19686. j: {
  19687. deprecated: "Please use journal instead",
  19688. target: "writeConcern",
  19689. transform({ name, options, values: [value] }) {
  19690. const wc = write_concern_1.WriteConcern.fromOptions({
  19691. writeConcern: {
  19692. ...options.writeConcern,
  19693. journal: getBoolean(name, value)
  19694. }
  19695. });
  19696. if (!wc)
  19697. throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`);
  19698. return wc;
  19699. }
  19700. },
  19701. journal: {
  19702. target: "writeConcern",
  19703. transform({ name, options, values: [value] }) {
  19704. const wc = write_concern_1.WriteConcern.fromOptions({
  19705. writeConcern: {
  19706. ...options.writeConcern,
  19707. journal: getBoolean(name, value)
  19708. }
  19709. });
  19710. if (!wc)
  19711. throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`);
  19712. return wc;
  19713. }
  19714. },
  19715. keepAlive: {
  19716. default: true,
  19717. type: "boolean",
  19718. deprecated: "Will not be able to turn off in the future."
  19719. },
  19720. keepAliveInitialDelay: {
  19721. default: 12e4,
  19722. type: "uint",
  19723. deprecated: "Will not be configurable in the future."
  19724. },
  19725. loadBalanced: {
  19726. default: false,
  19727. type: "boolean"
  19728. },
  19729. localThresholdMS: {
  19730. default: 15,
  19731. type: "uint"
  19732. },
  19733. maxConnecting: {
  19734. default: 2,
  19735. transform({ name, values: [value] }) {
  19736. const maxConnecting = getUIntFromOptions(name, value);
  19737. if (maxConnecting === 0) {
  19738. throw new error_1.MongoInvalidArgumentError("maxConnecting must be > 0 if specified");
  19739. }
  19740. return maxConnecting;
  19741. }
  19742. },
  19743. maxIdleTimeMS: {
  19744. default: 0,
  19745. type: "uint"
  19746. },
  19747. maxPoolSize: {
  19748. default: 100,
  19749. type: "uint"
  19750. },
  19751. maxStalenessSeconds: {
  19752. target: "readPreference",
  19753. transform({ name, options, values: [value] }) {
  19754. const maxStalenessSeconds = getUIntFromOptions(name, value);
  19755. if (options.readPreference) {
  19756. return read_preference_1.ReadPreference.fromOptions({
  19757. readPreference: { ...options.readPreference, maxStalenessSeconds }
  19758. });
  19759. } else {
  19760. return new read_preference_1.ReadPreference("secondary", void 0, { maxStalenessSeconds });
  19761. }
  19762. }
  19763. },
  19764. minInternalBufferSize: {
  19765. type: "uint"
  19766. },
  19767. minPoolSize: {
  19768. default: 0,
  19769. type: "uint"
  19770. },
  19771. minHeartbeatFrequencyMS: {
  19772. default: 500,
  19773. type: "uint"
  19774. },
  19775. monitorCommands: {
  19776. default: false,
  19777. type: "boolean"
  19778. },
  19779. name: {
  19780. target: "driverInfo",
  19781. transform({ values: [value], options }) {
  19782. return { ...options.driverInfo, name: String(value) };
  19783. }
  19784. },
  19785. noDelay: {
  19786. default: true,
  19787. type: "boolean"
  19788. },
  19789. pkFactory: {
  19790. default: utils_1.DEFAULT_PK_FACTORY,
  19791. transform({ values: [value] }) {
  19792. if ((0, utils_1.isRecord)(value, ["createPk"]) && typeof value.createPk === "function") {
  19793. return value;
  19794. }
  19795. throw new error_1.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${value}`);
  19796. }
  19797. },
  19798. promoteBuffers: {
  19799. type: "boolean"
  19800. },
  19801. promoteLongs: {
  19802. type: "boolean"
  19803. },
  19804. promoteValues: {
  19805. type: "boolean"
  19806. },
  19807. useBigInt64: {
  19808. type: "boolean"
  19809. },
  19810. proxyHost: {
  19811. type: "string"
  19812. },
  19813. proxyPassword: {
  19814. type: "string"
  19815. },
  19816. proxyPort: {
  19817. type: "uint"
  19818. },
  19819. proxyUsername: {
  19820. type: "string"
  19821. },
  19822. raw: {
  19823. default: false,
  19824. type: "boolean"
  19825. },
  19826. readConcern: {
  19827. transform({ values: [value], options }) {
  19828. if (value instanceof read_concern_1.ReadConcern || (0, utils_1.isRecord)(value, ["level"])) {
  19829. return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, ...value });
  19830. }
  19831. throw new error_1.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`);
  19832. }
  19833. },
  19834. readConcernLevel: {
  19835. target: "readConcern",
  19836. transform({ values: [level], options }) {
  19837. return read_concern_1.ReadConcern.fromOptions({
  19838. ...options.readConcern,
  19839. level
  19840. });
  19841. }
  19842. },
  19843. readPreference: {
  19844. default: read_preference_1.ReadPreference.primary,
  19845. transform({ values: [value], options }) {
  19846. var _a, _b, _c;
  19847. if (value instanceof read_preference_1.ReadPreference) {
  19848. return read_preference_1.ReadPreference.fromOptions({
  19849. readPreference: { ...options.readPreference, ...value },
  19850. ...value
  19851. });
  19852. }
  19853. if ((0, utils_1.isRecord)(value, ["mode"])) {
  19854. const rp = read_preference_1.ReadPreference.fromOptions({
  19855. readPreference: { ...options.readPreference, ...value },
  19856. ...value
  19857. });
  19858. if (rp)
  19859. return rp;
  19860. else
  19861. throw new error_1.MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`);
  19862. }
  19863. if (typeof value === "string") {
  19864. const rpOpts = {
  19865. hedge: (_a = options.readPreference) == null ? void 0 : _a.hedge,
  19866. maxStalenessSeconds: (_b = options.readPreference) == null ? void 0 : _b.maxStalenessSeconds
  19867. };
  19868. return new read_preference_1.ReadPreference(value, (_c = options.readPreference) == null ? void 0 : _c.tags, rpOpts);
  19869. }
  19870. throw new error_1.MongoParseError(`Unknown ReadPreference value: ${value}`);
  19871. }
  19872. },
  19873. readPreferenceTags: {
  19874. target: "readPreference",
  19875. transform({ values, options }) {
  19876. const tags = Array.isArray(values[0]) ? values[0] : values;
  19877. const readPreferenceTags = [];
  19878. for (const tag of tags) {
  19879. const readPreferenceTag = /* @__PURE__ */ Object.create(null);
  19880. if (typeof tag === "string") {
  19881. for (const [k, v] of entriesFromString(tag)) {
  19882. readPreferenceTag[k] = v;
  19883. }
  19884. }
  19885. if ((0, utils_1.isRecord)(tag)) {
  19886. for (const [k, v] of Object.entries(tag)) {
  19887. readPreferenceTag[k] = v;
  19888. }
  19889. }
  19890. readPreferenceTags.push(readPreferenceTag);
  19891. }
  19892. return read_preference_1.ReadPreference.fromOptions({
  19893. readPreference: options.readPreference,
  19894. readPreferenceTags
  19895. });
  19896. }
  19897. },
  19898. replicaSet: {
  19899. type: "string"
  19900. },
  19901. retryReads: {
  19902. default: true,
  19903. type: "boolean"
  19904. },
  19905. retryWrites: {
  19906. default: true,
  19907. type: "boolean"
  19908. },
  19909. serializeFunctions: {
  19910. type: "boolean"
  19911. },
  19912. serverSelectionTimeoutMS: {
  19913. default: 3e4,
  19914. type: "uint"
  19915. },
  19916. servername: {
  19917. type: "string"
  19918. },
  19919. socketTimeoutMS: {
  19920. default: 0,
  19921. type: "uint"
  19922. },
  19923. srvMaxHosts: {
  19924. type: "uint",
  19925. default: 0
  19926. },
  19927. srvServiceName: {
  19928. type: "string",
  19929. default: "mongodb"
  19930. },
  19931. ssl: {
  19932. target: "tls",
  19933. type: "boolean"
  19934. },
  19935. sslCA: {
  19936. deprecated: "sslCA is deprecated and will be removed in the next major version. Please use tlsCAFile instead.",
  19937. target: "ca",
  19938. transform({ values: [value] }) {
  19939. return fs.readFileSync(String(value), { encoding: "ascii" });
  19940. }
  19941. },
  19942. sslCRL: {
  19943. deprecated: "sslCRL is deprecated and will be removed in the next major version and be replaced by tlsCRLFile in that release.",
  19944. target: "crl",
  19945. transform({ values: [value] }) {
  19946. return fs.readFileSync(String(value), { encoding: "ascii" });
  19947. }
  19948. },
  19949. sslCert: {
  19950. deprecated: "sslCert is deprecated and will be removed in the next major version. Please use tlsCertificateKeyFile instead.",
  19951. target: "cert",
  19952. transform({ values: [value] }) {
  19953. return fs.readFileSync(String(value), { encoding: "ascii" });
  19954. }
  19955. },
  19956. sslKey: {
  19957. deprecated: "sslKey is deprecated and will be removed in the next major version. Please use tlsCertificateKeyFile instead.",
  19958. target: "key",
  19959. transform({ values: [value] }) {
  19960. return fs.readFileSync(String(value), { encoding: "ascii" });
  19961. }
  19962. },
  19963. sslPass: {
  19964. deprecated: "sslPass is deprecated and will be removed in the next major version. Please use tlsCertificateKeyFilePassword instead.",
  19965. target: "passphrase",
  19966. type: "string"
  19967. },
  19968. sslValidate: {
  19969. deprecated: "sslValidate is deprecated and will be removed in the next major version. Please use tlsAllowInvalidCertificates instead.",
  19970. target: "rejectUnauthorized",
  19971. type: "boolean"
  19972. },
  19973. tls: {
  19974. type: "boolean"
  19975. },
  19976. tlsAllowInvalidCertificates: {
  19977. target: "rejectUnauthorized",
  19978. transform({ name, values: [value] }) {
  19979. return !getBoolean(name, value);
  19980. }
  19981. },
  19982. tlsAllowInvalidHostnames: {
  19983. target: "checkServerIdentity",
  19984. transform({ name, values: [value] }) {
  19985. return getBoolean(name, value) ? () => void 0 : void 0;
  19986. }
  19987. },
  19988. tlsCAFile: {
  19989. target: "ca",
  19990. transform({ values: [value] }) {
  19991. return fs.readFileSync(String(value), { encoding: "ascii" });
  19992. }
  19993. },
  19994. tlsCertificateFile: {
  19995. deprecated: "tlsCertificateFile is deprecated and will be removed in the next major version. Please use tlsCertificateKeyFile instead.",
  19996. target: "cert",
  19997. transform({ values: [value] }) {
  19998. return fs.readFileSync(String(value), { encoding: "ascii" });
  19999. }
  20000. },
  20001. tlsCertificateKeyFile: {
  20002. target: "key",
  20003. transform({ values: [value] }) {
  20004. return fs.readFileSync(String(value), { encoding: "ascii" });
  20005. }
  20006. },
  20007. tlsCertificateKeyFilePassword: {
  20008. target: "passphrase",
  20009. type: "any"
  20010. },
  20011. tlsInsecure: {
  20012. transform({ name, options, values: [value] }) {
  20013. const tlsInsecure = getBoolean(name, value);
  20014. if (tlsInsecure) {
  20015. options.checkServerIdentity = () => void 0;
  20016. options.rejectUnauthorized = false;
  20017. } else {
  20018. options.checkServerIdentity = options.tlsAllowInvalidHostnames ? () => void 0 : void 0;
  20019. options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true;
  20020. }
  20021. return tlsInsecure;
  20022. }
  20023. },
  20024. w: {
  20025. target: "writeConcern",
  20026. transform({ values: [value], options }) {
  20027. return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } });
  20028. }
  20029. },
  20030. waitQueueTimeoutMS: {
  20031. default: 0,
  20032. type: "uint"
  20033. },
  20034. writeConcern: {
  20035. target: "writeConcern",
  20036. transform({ values: [value], options }) {
  20037. if ((0, utils_1.isRecord)(value) || value instanceof write_concern_1.WriteConcern) {
  20038. return write_concern_1.WriteConcern.fromOptions({
  20039. writeConcern: {
  20040. ...options.writeConcern,
  20041. ...value
  20042. }
  20043. });
  20044. } else if (value === "majority" || typeof value === "number") {
  20045. return write_concern_1.WriteConcern.fromOptions({
  20046. writeConcern: {
  20047. ...options.writeConcern,
  20048. w: value
  20049. }
  20050. });
  20051. }
  20052. throw new error_1.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`);
  20053. }
  20054. },
  20055. wtimeout: {
  20056. deprecated: "Please use wtimeoutMS instead",
  20057. target: "writeConcern",
  20058. transform({ values: [value], options }) {
  20059. const wc = write_concern_1.WriteConcern.fromOptions({
  20060. writeConcern: {
  20061. ...options.writeConcern,
  20062. wtimeout: getUIntFromOptions("wtimeout", value)
  20063. }
  20064. });
  20065. if (wc)
  20066. return wc;
  20067. throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`);
  20068. }
  20069. },
  20070. wtimeoutMS: {
  20071. target: "writeConcern",
  20072. transform({ values: [value], options }) {
  20073. const wc = write_concern_1.WriteConcern.fromOptions({
  20074. writeConcern: {
  20075. ...options.writeConcern,
  20076. wtimeoutMS: getUIntFromOptions("wtimeoutMS", value)
  20077. }
  20078. });
  20079. if (wc)
  20080. return wc;
  20081. throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`);
  20082. }
  20083. },
  20084. zlibCompressionLevel: {
  20085. default: 0,
  20086. type: "int"
  20087. },
  20088. // Custom types for modifying core behavior
  20089. connectionType: { type: "any" },
  20090. srvPoller: { type: "any" },
  20091. // Accepted NodeJS Options
  20092. minDHSize: { type: "any" },
  20093. pskCallback: { type: "any" },
  20094. secureContext: { type: "any" },
  20095. enableTrace: { type: "any" },
  20096. requestCert: { type: "any" },
  20097. rejectUnauthorized: { type: "any" },
  20098. checkServerIdentity: { type: "any" },
  20099. ALPNProtocols: { type: "any" },
  20100. SNICallback: { type: "any" },
  20101. session: { type: "any" },
  20102. requestOCSP: { type: "any" },
  20103. localAddress: { type: "any" },
  20104. localPort: { type: "any" },
  20105. hints: { type: "any" },
  20106. lookup: { type: "any" },
  20107. ca: { type: "any" },
  20108. cert: { type: "any" },
  20109. ciphers: { type: "any" },
  20110. crl: { type: "any" },
  20111. ecdhCurve: { type: "any" },
  20112. key: { type: "any" },
  20113. passphrase: { type: "any" },
  20114. pfx: { type: "any" },
  20115. secureProtocol: { type: "any" },
  20116. index: { type: "any" },
  20117. // Legacy Options, these are unused but left here to avoid errors with CSFLE lib
  20118. useNewUrlParser: { type: "boolean" },
  20119. useUnifiedTopology: { type: "boolean" },
  20120. // MongoLogger
  20121. // TODO(NODE-4849): Tighten the type of mongodbLogPath
  20122. mongodbLogPath: { type: "any" }
  20123. };
  20124. exports2.DEFAULT_OPTIONS = new CaseInsensitiveMap(Object.entries(exports2.OPTIONS).filter(([, descriptor]) => descriptor.default != null).map(([k, d]) => [k, d.default]));
  20125. exports2.FEATURE_FLAGS = /* @__PURE__ */ new Set([
  20126. Symbol.for("@@mdb.skipPingOnConnect"),
  20127. Symbol.for("@@mdb.enableMongoLogger"),
  20128. Symbol.for("@@mdb.internalLoggerConfig")
  20129. ]);
  20130. }
  20131. });
  20132. // node_modules/mongodb/lib/sdam/events.js
  20133. var require_events = __commonJS({
  20134. "node_modules/mongodb/lib/sdam/events.js"(exports2) {
  20135. "use strict";
  20136. Object.defineProperty(exports2, "__esModule", { value: true });
  20137. exports2.ServerHeartbeatFailedEvent = exports2.ServerHeartbeatSucceededEvent = exports2.ServerHeartbeatStartedEvent = exports2.TopologyClosedEvent = exports2.TopologyOpeningEvent = exports2.TopologyDescriptionChangedEvent = exports2.ServerClosedEvent = exports2.ServerOpeningEvent = exports2.ServerDescriptionChangedEvent = void 0;
  20138. var _ServerDescriptionChangedEvent = class _ServerDescriptionChangedEvent {
  20139. /** @internal */
  20140. constructor(topologyId, address, previousDescription, newDescription) {
  20141. this.topologyId = topologyId;
  20142. this.address = address;
  20143. this.previousDescription = previousDescription;
  20144. this.newDescription = newDescription;
  20145. }
  20146. };
  20147. __name(_ServerDescriptionChangedEvent, "ServerDescriptionChangedEvent");
  20148. var ServerDescriptionChangedEvent = _ServerDescriptionChangedEvent;
  20149. exports2.ServerDescriptionChangedEvent = ServerDescriptionChangedEvent;
  20150. var _ServerOpeningEvent = class _ServerOpeningEvent {
  20151. /** @internal */
  20152. constructor(topologyId, address) {
  20153. this.topologyId = topologyId;
  20154. this.address = address;
  20155. }
  20156. };
  20157. __name(_ServerOpeningEvent, "ServerOpeningEvent");
  20158. var ServerOpeningEvent = _ServerOpeningEvent;
  20159. exports2.ServerOpeningEvent = ServerOpeningEvent;
  20160. var _ServerClosedEvent = class _ServerClosedEvent {
  20161. /** @internal */
  20162. constructor(topologyId, address) {
  20163. this.topologyId = topologyId;
  20164. this.address = address;
  20165. }
  20166. };
  20167. __name(_ServerClosedEvent, "ServerClosedEvent");
  20168. var ServerClosedEvent = _ServerClosedEvent;
  20169. exports2.ServerClosedEvent = ServerClosedEvent;
  20170. var _TopologyDescriptionChangedEvent = class _TopologyDescriptionChangedEvent {
  20171. /** @internal */
  20172. constructor(topologyId, previousDescription, newDescription) {
  20173. this.topologyId = topologyId;
  20174. this.previousDescription = previousDescription;
  20175. this.newDescription = newDescription;
  20176. }
  20177. };
  20178. __name(_TopologyDescriptionChangedEvent, "TopologyDescriptionChangedEvent");
  20179. var TopologyDescriptionChangedEvent = _TopologyDescriptionChangedEvent;
  20180. exports2.TopologyDescriptionChangedEvent = TopologyDescriptionChangedEvent;
  20181. var _TopologyOpeningEvent = class _TopologyOpeningEvent {
  20182. /** @internal */
  20183. constructor(topologyId) {
  20184. this.topologyId = topologyId;
  20185. }
  20186. };
  20187. __name(_TopologyOpeningEvent, "TopologyOpeningEvent");
  20188. var TopologyOpeningEvent = _TopologyOpeningEvent;
  20189. exports2.TopologyOpeningEvent = TopologyOpeningEvent;
  20190. var _TopologyClosedEvent = class _TopologyClosedEvent {
  20191. /** @internal */
  20192. constructor(topologyId) {
  20193. this.topologyId = topologyId;
  20194. }
  20195. };
  20196. __name(_TopologyClosedEvent, "TopologyClosedEvent");
  20197. var TopologyClosedEvent = _TopologyClosedEvent;
  20198. exports2.TopologyClosedEvent = TopologyClosedEvent;
  20199. var _ServerHeartbeatStartedEvent = class _ServerHeartbeatStartedEvent {
  20200. /** @internal */
  20201. constructor(connectionId) {
  20202. this.connectionId = connectionId;
  20203. }
  20204. };
  20205. __name(_ServerHeartbeatStartedEvent, "ServerHeartbeatStartedEvent");
  20206. var ServerHeartbeatStartedEvent = _ServerHeartbeatStartedEvent;
  20207. exports2.ServerHeartbeatStartedEvent = ServerHeartbeatStartedEvent;
  20208. var _ServerHeartbeatSucceededEvent = class _ServerHeartbeatSucceededEvent {
  20209. /** @internal */
  20210. constructor(connectionId, duration, reply) {
  20211. this.connectionId = connectionId;
  20212. this.duration = duration;
  20213. this.reply = reply ?? {};
  20214. }
  20215. };
  20216. __name(_ServerHeartbeatSucceededEvent, "ServerHeartbeatSucceededEvent");
  20217. var ServerHeartbeatSucceededEvent = _ServerHeartbeatSucceededEvent;
  20218. exports2.ServerHeartbeatSucceededEvent = ServerHeartbeatSucceededEvent;
  20219. var _ServerHeartbeatFailedEvent = class _ServerHeartbeatFailedEvent {
  20220. /** @internal */
  20221. constructor(connectionId, duration, failure) {
  20222. this.connectionId = connectionId;
  20223. this.duration = duration;
  20224. this.failure = failure;
  20225. }
  20226. };
  20227. __name(_ServerHeartbeatFailedEvent, "ServerHeartbeatFailedEvent");
  20228. var ServerHeartbeatFailedEvent = _ServerHeartbeatFailedEvent;
  20229. exports2.ServerHeartbeatFailedEvent = ServerHeartbeatFailedEvent;
  20230. }
  20231. });
  20232. // node_modules/mongodb/lib/cmap/commands.js
  20233. var require_commands = __commonJS({
  20234. "node_modules/mongodb/lib/cmap/commands.js"(exports2) {
  20235. "use strict";
  20236. Object.defineProperty(exports2, "__esModule", { value: true });
  20237. exports2.BinMsg = exports2.Msg = exports2.Response = exports2.Query = void 0;
  20238. var BSON = require_bson2();
  20239. var error_1 = require_error();
  20240. var read_preference_1 = require_read_preference();
  20241. var utils_1 = require_utils();
  20242. var constants_1 = require_constants();
  20243. var _requestId = 0;
  20244. var OPTS_TAILABLE_CURSOR = 2;
  20245. var OPTS_SECONDARY = 4;
  20246. var OPTS_OPLOG_REPLAY = 8;
  20247. var OPTS_NO_CURSOR_TIMEOUT = 16;
  20248. var OPTS_AWAIT_DATA = 32;
  20249. var OPTS_EXHAUST = 64;
  20250. var OPTS_PARTIAL = 128;
  20251. var CURSOR_NOT_FOUND = 1;
  20252. var QUERY_FAILURE = 2;
  20253. var SHARD_CONFIG_STALE = 4;
  20254. var AWAIT_CAPABLE = 8;
  20255. var _Query = class _Query {
  20256. constructor(ns, query, options) {
  20257. if (ns == null)
  20258. throw new error_1.MongoRuntimeError("Namespace must be specified for query");
  20259. if (query == null)
  20260. throw new error_1.MongoRuntimeError("A query document must be specified for query");
  20261. if (ns.indexOf("\0") !== -1) {
  20262. throw new error_1.MongoRuntimeError("Namespace cannot contain a null character");
  20263. }
  20264. this.ns = ns;
  20265. this.query = query;
  20266. this.numberToSkip = options.numberToSkip || 0;
  20267. this.numberToReturn = options.numberToReturn || 0;
  20268. this.returnFieldSelector = options.returnFieldSelector || void 0;
  20269. this.requestId = _Query.getRequestId();
  20270. this.pre32Limit = options.pre32Limit;
  20271. this.serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
  20272. this.ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : false;
  20273. this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;
  20274. this.checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false;
  20275. this.batchSize = this.numberToReturn;
  20276. this.tailable = false;
  20277. this.secondaryOk = typeof options.secondaryOk === "boolean" ? options.secondaryOk : false;
  20278. this.oplogReplay = false;
  20279. this.noCursorTimeout = false;
  20280. this.awaitData = false;
  20281. this.exhaust = false;
  20282. this.partial = false;
  20283. }
  20284. /** Assign next request Id. */
  20285. incRequestId() {
  20286. this.requestId = _requestId++;
  20287. }
  20288. /** Peek next request Id. */
  20289. nextRequestId() {
  20290. return _requestId + 1;
  20291. }
  20292. /** Increment then return next request Id. */
  20293. static getRequestId() {
  20294. return ++_requestId;
  20295. }
  20296. // Uses a single allocated buffer for the process, avoiding multiple memory allocations
  20297. toBin() {
  20298. const buffers = [];
  20299. let projection = null;
  20300. let flags = 0;
  20301. if (this.tailable) {
  20302. flags |= OPTS_TAILABLE_CURSOR;
  20303. }
  20304. if (this.secondaryOk) {
  20305. flags |= OPTS_SECONDARY;
  20306. }
  20307. if (this.oplogReplay) {
  20308. flags |= OPTS_OPLOG_REPLAY;
  20309. }
  20310. if (this.noCursorTimeout) {
  20311. flags |= OPTS_NO_CURSOR_TIMEOUT;
  20312. }
  20313. if (this.awaitData) {
  20314. flags |= OPTS_AWAIT_DATA;
  20315. }
  20316. if (this.exhaust) {
  20317. flags |= OPTS_EXHAUST;
  20318. }
  20319. if (this.partial) {
  20320. flags |= OPTS_PARTIAL;
  20321. }
  20322. if (this.batchSize !== this.numberToReturn)
  20323. this.numberToReturn = this.batchSize;
  20324. const header = Buffer.alloc(
  20325. 4 * 4 + // Header
  20326. 4 + // Flags
  20327. Buffer.byteLength(this.ns) + 1 + // namespace
  20328. 4 + // numberToSkip
  20329. 4
  20330. // numberToReturn
  20331. );
  20332. buffers.push(header);
  20333. const query = BSON.serialize(this.query, {
  20334. checkKeys: this.checkKeys,
  20335. serializeFunctions: this.serializeFunctions,
  20336. ignoreUndefined: this.ignoreUndefined
  20337. });
  20338. buffers.push(query);
  20339. if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) {
  20340. projection = BSON.serialize(this.returnFieldSelector, {
  20341. checkKeys: this.checkKeys,
  20342. serializeFunctions: this.serializeFunctions,
  20343. ignoreUndefined: this.ignoreUndefined
  20344. });
  20345. buffers.push(projection);
  20346. }
  20347. const totalLength = header.length + query.length + (projection ? projection.length : 0);
  20348. let index = 4;
  20349. header[3] = totalLength >> 24 & 255;
  20350. header[2] = totalLength >> 16 & 255;
  20351. header[1] = totalLength >> 8 & 255;
  20352. header[0] = totalLength & 255;
  20353. header[index + 3] = this.requestId >> 24 & 255;
  20354. header[index + 2] = this.requestId >> 16 & 255;
  20355. header[index + 1] = this.requestId >> 8 & 255;
  20356. header[index] = this.requestId & 255;
  20357. index = index + 4;
  20358. header[index + 3] = 0 >> 24 & 255;
  20359. header[index + 2] = 0 >> 16 & 255;
  20360. header[index + 1] = 0 >> 8 & 255;
  20361. header[index] = 0 & 255;
  20362. index = index + 4;
  20363. header[index + 3] = constants_1.OP_QUERY >> 24 & 255;
  20364. header[index + 2] = constants_1.OP_QUERY >> 16 & 255;
  20365. header[index + 1] = constants_1.OP_QUERY >> 8 & 255;
  20366. header[index] = constants_1.OP_QUERY & 255;
  20367. index = index + 4;
  20368. header[index + 3] = flags >> 24 & 255;
  20369. header[index + 2] = flags >> 16 & 255;
  20370. header[index + 1] = flags >> 8 & 255;
  20371. header[index] = flags & 255;
  20372. index = index + 4;
  20373. index = index + header.write(this.ns, index, "utf8") + 1;
  20374. header[index - 1] = 0;
  20375. header[index + 3] = this.numberToSkip >> 24 & 255;
  20376. header[index + 2] = this.numberToSkip >> 16 & 255;
  20377. header[index + 1] = this.numberToSkip >> 8 & 255;
  20378. header[index] = this.numberToSkip & 255;
  20379. index = index + 4;
  20380. header[index + 3] = this.numberToReturn >> 24 & 255;
  20381. header[index + 2] = this.numberToReturn >> 16 & 255;
  20382. header[index + 1] = this.numberToReturn >> 8 & 255;
  20383. header[index] = this.numberToReturn & 255;
  20384. index = index + 4;
  20385. return buffers;
  20386. }
  20387. };
  20388. __name(_Query, "Query");
  20389. var Query = _Query;
  20390. exports2.Query = Query;
  20391. var _Response = class _Response {
  20392. constructor(message, msgHeader, msgBody, opts) {
  20393. this.documents = new Array(0);
  20394. this.parsed = false;
  20395. this.raw = message;
  20396. this.data = msgBody;
  20397. this.opts = opts ?? {
  20398. useBigInt64: false,
  20399. promoteLongs: true,
  20400. promoteValues: true,
  20401. promoteBuffers: false,
  20402. bsonRegExp: false
  20403. };
  20404. this.length = msgHeader.length;
  20405. this.requestId = msgHeader.requestId;
  20406. this.responseTo = msgHeader.responseTo;
  20407. this.opCode = msgHeader.opCode;
  20408. this.fromCompressed = msgHeader.fromCompressed;
  20409. this.useBigInt64 = typeof this.opts.useBigInt64 === "boolean" ? this.opts.useBigInt64 : false;
  20410. this.promoteLongs = typeof this.opts.promoteLongs === "boolean" ? this.opts.promoteLongs : true;
  20411. this.promoteValues = typeof this.opts.promoteValues === "boolean" ? this.opts.promoteValues : true;
  20412. this.promoteBuffers = typeof this.opts.promoteBuffers === "boolean" ? this.opts.promoteBuffers : false;
  20413. this.bsonRegExp = typeof this.opts.bsonRegExp === "boolean" ? this.opts.bsonRegExp : false;
  20414. }
  20415. isParsed() {
  20416. return this.parsed;
  20417. }
  20418. parse(options) {
  20419. if (this.parsed)
  20420. return;
  20421. options = options ?? {};
  20422. const raw = options.raw || false;
  20423. const documentsReturnedIn = options.documentsReturnedIn || null;
  20424. const useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64;
  20425. const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs;
  20426. const promoteValues = options.promoteValues ?? this.opts.promoteValues;
  20427. const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers;
  20428. const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp;
  20429. let bsonSize;
  20430. const _options = {
  20431. useBigInt64,
  20432. promoteLongs,
  20433. promoteValues,
  20434. promoteBuffers,
  20435. bsonRegExp
  20436. };
  20437. this.index = 20;
  20438. this.responseFlags = this.data.readInt32LE(0);
  20439. this.cursorId = new BSON.Long(this.data.readInt32LE(4), this.data.readInt32LE(8));
  20440. this.startingFrom = this.data.readInt32LE(12);
  20441. this.numberReturned = this.data.readInt32LE(16);
  20442. this.documents = new Array(this.numberReturned);
  20443. this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0;
  20444. this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0;
  20445. this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0;
  20446. this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0;
  20447. for (let i = 0; i < this.numberReturned; i++) {
  20448. bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24;
  20449. if (raw) {
  20450. this.documents[i] = this.data.slice(this.index, this.index + bsonSize);
  20451. } else {
  20452. this.documents[i] = BSON.deserialize(this.data.slice(this.index, this.index + bsonSize), _options);
  20453. }
  20454. this.index = this.index + bsonSize;
  20455. }
  20456. if (this.documents.length === 1 && documentsReturnedIn != null && raw) {
  20457. const fieldsAsRaw = {};
  20458. fieldsAsRaw[documentsReturnedIn] = true;
  20459. _options.fieldsAsRaw = fieldsAsRaw;
  20460. const doc = BSON.deserialize(this.documents[0], _options);
  20461. this.documents = [doc];
  20462. }
  20463. this.parsed = true;
  20464. }
  20465. };
  20466. __name(_Response, "Response");
  20467. var Response = _Response;
  20468. exports2.Response = Response;
  20469. var OPTS_CHECKSUM_PRESENT = 1;
  20470. var OPTS_MORE_TO_COME = 2;
  20471. var OPTS_EXHAUST_ALLOWED = 1 << 16;
  20472. var _Msg = class _Msg {
  20473. constructor(ns, command, options) {
  20474. if (command == null)
  20475. throw new error_1.MongoInvalidArgumentError("Query document must be specified for query");
  20476. this.ns = ns;
  20477. this.command = command;
  20478. this.command.$db = (0, utils_1.databaseNamespace)(ns);
  20479. if (options.readPreference && options.readPreference.mode !== read_preference_1.ReadPreference.PRIMARY) {
  20480. this.command.$readPreference = options.readPreference.toJSON();
  20481. }
  20482. this.options = options ?? {};
  20483. this.requestId = options.requestId ? options.requestId : _Msg.getRequestId();
  20484. this.serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
  20485. this.ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : false;
  20486. this.checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false;
  20487. this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;
  20488. this.checksumPresent = false;
  20489. this.moreToCome = options.moreToCome || false;
  20490. this.exhaustAllowed = typeof options.exhaustAllowed === "boolean" ? options.exhaustAllowed : false;
  20491. }
  20492. toBin() {
  20493. const buffers = [];
  20494. let flags = 0;
  20495. if (this.checksumPresent) {
  20496. flags |= OPTS_CHECKSUM_PRESENT;
  20497. }
  20498. if (this.moreToCome) {
  20499. flags |= OPTS_MORE_TO_COME;
  20500. }
  20501. if (this.exhaustAllowed) {
  20502. flags |= OPTS_EXHAUST_ALLOWED;
  20503. }
  20504. const header = Buffer.alloc(
  20505. 4 * 4 + // Header
  20506. 4
  20507. // Flags
  20508. );
  20509. buffers.push(header);
  20510. let totalLength = header.length;
  20511. const command = this.command;
  20512. totalLength += this.makeDocumentSegment(buffers, command);
  20513. header.writeInt32LE(totalLength, 0);
  20514. header.writeInt32LE(this.requestId, 4);
  20515. header.writeInt32LE(0, 8);
  20516. header.writeInt32LE(constants_1.OP_MSG, 12);
  20517. header.writeUInt32LE(flags, 16);
  20518. return buffers;
  20519. }
  20520. makeDocumentSegment(buffers, document) {
  20521. const payloadTypeBuffer = Buffer.alloc(1);
  20522. payloadTypeBuffer[0] = 0;
  20523. const documentBuffer = this.serializeBson(document);
  20524. buffers.push(payloadTypeBuffer);
  20525. buffers.push(documentBuffer);
  20526. return payloadTypeBuffer.length + documentBuffer.length;
  20527. }
  20528. serializeBson(document) {
  20529. return BSON.serialize(document, {
  20530. checkKeys: this.checkKeys,
  20531. serializeFunctions: this.serializeFunctions,
  20532. ignoreUndefined: this.ignoreUndefined
  20533. });
  20534. }
  20535. static getRequestId() {
  20536. _requestId = _requestId + 1 & 2147483647;
  20537. return _requestId;
  20538. }
  20539. };
  20540. __name(_Msg, "Msg");
  20541. var Msg = _Msg;
  20542. exports2.Msg = Msg;
  20543. var _BinMsg = class _BinMsg {
  20544. constructor(message, msgHeader, msgBody, opts) {
  20545. this.parsed = false;
  20546. this.raw = message;
  20547. this.data = msgBody;
  20548. this.opts = opts ?? {
  20549. useBigInt64: false,
  20550. promoteLongs: true,
  20551. promoteValues: true,
  20552. promoteBuffers: false,
  20553. bsonRegExp: false
  20554. };
  20555. this.length = msgHeader.length;
  20556. this.requestId = msgHeader.requestId;
  20557. this.responseTo = msgHeader.responseTo;
  20558. this.opCode = msgHeader.opCode;
  20559. this.fromCompressed = msgHeader.fromCompressed;
  20560. this.responseFlags = msgBody.readInt32LE(0);
  20561. this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0;
  20562. this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0;
  20563. this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0;
  20564. this.useBigInt64 = typeof this.opts.useBigInt64 === "boolean" ? this.opts.useBigInt64 : false;
  20565. this.promoteLongs = typeof this.opts.promoteLongs === "boolean" ? this.opts.promoteLongs : true;
  20566. this.promoteValues = typeof this.opts.promoteValues === "boolean" ? this.opts.promoteValues : true;
  20567. this.promoteBuffers = typeof this.opts.promoteBuffers === "boolean" ? this.opts.promoteBuffers : false;
  20568. this.bsonRegExp = typeof this.opts.bsonRegExp === "boolean" ? this.opts.bsonRegExp : false;
  20569. this.documents = [];
  20570. }
  20571. isParsed() {
  20572. return this.parsed;
  20573. }
  20574. parse(options) {
  20575. if (this.parsed)
  20576. return;
  20577. options = options ?? {};
  20578. this.index = 4;
  20579. const raw = options.raw || false;
  20580. const documentsReturnedIn = options.documentsReturnedIn || null;
  20581. const useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64;
  20582. const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs;
  20583. const promoteValues = options.promoteValues ?? this.opts.promoteValues;
  20584. const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers;
  20585. const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp;
  20586. const validation = this.parseBsonSerializationOptions(options);
  20587. const bsonOptions = {
  20588. useBigInt64,
  20589. promoteLongs,
  20590. promoteValues,
  20591. promoteBuffers,
  20592. bsonRegExp,
  20593. validation
  20594. // Due to the strictness of the BSON libraries validation option we need this cast
  20595. };
  20596. while (this.index < this.data.length) {
  20597. const payloadType = this.data.readUInt8(this.index++);
  20598. if (payloadType === 0) {
  20599. const bsonSize = this.data.readUInt32LE(this.index);
  20600. const bin = this.data.slice(this.index, this.index + bsonSize);
  20601. this.documents.push(raw ? bin : BSON.deserialize(bin, bsonOptions));
  20602. this.index += bsonSize;
  20603. } else if (payloadType === 1) {
  20604. throw new error_1.MongoRuntimeError("OP_MSG Payload Type 1 detected unsupported protocol");
  20605. }
  20606. }
  20607. if (this.documents.length === 1 && documentsReturnedIn != null && raw) {
  20608. const fieldsAsRaw = {};
  20609. fieldsAsRaw[documentsReturnedIn] = true;
  20610. bsonOptions.fieldsAsRaw = fieldsAsRaw;
  20611. const doc = BSON.deserialize(this.documents[0], bsonOptions);
  20612. this.documents = [doc];
  20613. }
  20614. this.parsed = true;
  20615. }
  20616. parseBsonSerializationOptions({ enableUtf8Validation }) {
  20617. if (enableUtf8Validation === false) {
  20618. return { utf8: false };
  20619. }
  20620. return { utf8: { writeErrors: false } };
  20621. }
  20622. };
  20623. __name(_BinMsg, "BinMsg");
  20624. var BinMsg = _BinMsg;
  20625. exports2.BinMsg = BinMsg;
  20626. }
  20627. });
  20628. // node_modules/mongodb/lib/cmap/command_monitoring_events.js
  20629. var require_command_monitoring_events = __commonJS({
  20630. "node_modules/mongodb/lib/cmap/command_monitoring_events.js"(exports2) {
  20631. "use strict";
  20632. Object.defineProperty(exports2, "__esModule", { value: true });
  20633. exports2.SENSITIVE_COMMANDS = exports2.CommandFailedEvent = exports2.CommandSucceededEvent = exports2.CommandStartedEvent = void 0;
  20634. var constants_1 = require_constants2();
  20635. var utils_1 = require_utils();
  20636. var commands_1 = require_commands();
  20637. var _CommandStartedEvent = class _CommandStartedEvent {
  20638. /**
  20639. * Create a started event
  20640. *
  20641. * @internal
  20642. * @param pool - the pool that originated the command
  20643. * @param command - the command
  20644. */
  20645. constructor(connection, command) {
  20646. this.name = constants_1.COMMAND_STARTED;
  20647. const cmd = extractCommand(command);
  20648. const commandName = extractCommandName(cmd);
  20649. const { address, connectionId, serviceId } = extractConnectionDetails(connection);
  20650. if (exports2.SENSITIVE_COMMANDS.has(commandName)) {
  20651. this.commandObj = {};
  20652. this.commandObj[commandName] = true;
  20653. }
  20654. this.address = address;
  20655. this.connectionId = connectionId;
  20656. this.serviceId = serviceId;
  20657. this.requestId = command.requestId;
  20658. this.databaseName = databaseName(command);
  20659. this.commandName = commandName;
  20660. this.command = maybeRedact(commandName, cmd, cmd);
  20661. }
  20662. /* @internal */
  20663. get hasServiceId() {
  20664. return !!this.serviceId;
  20665. }
  20666. };
  20667. __name(_CommandStartedEvent, "CommandStartedEvent");
  20668. var CommandStartedEvent = _CommandStartedEvent;
  20669. exports2.CommandStartedEvent = CommandStartedEvent;
  20670. var _CommandSucceededEvent = class _CommandSucceededEvent {
  20671. /**
  20672. * Create a succeeded event
  20673. *
  20674. * @internal
  20675. * @param pool - the pool that originated the command
  20676. * @param command - the command
  20677. * @param reply - the reply for this command from the server
  20678. * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration
  20679. */
  20680. constructor(connection, command, reply, started) {
  20681. this.name = constants_1.COMMAND_SUCCEEDED;
  20682. const cmd = extractCommand(command);
  20683. const commandName = extractCommandName(cmd);
  20684. const { address, connectionId, serviceId } = extractConnectionDetails(connection);
  20685. this.address = address;
  20686. this.connectionId = connectionId;
  20687. this.serviceId = serviceId;
  20688. this.requestId = command.requestId;
  20689. this.commandName = commandName;
  20690. this.duration = (0, utils_1.calculateDurationInMs)(started);
  20691. this.reply = maybeRedact(commandName, cmd, extractReply(command, reply));
  20692. }
  20693. /* @internal */
  20694. get hasServiceId() {
  20695. return !!this.serviceId;
  20696. }
  20697. };
  20698. __name(_CommandSucceededEvent, "CommandSucceededEvent");
  20699. var CommandSucceededEvent = _CommandSucceededEvent;
  20700. exports2.CommandSucceededEvent = CommandSucceededEvent;
  20701. var _CommandFailedEvent = class _CommandFailedEvent {
  20702. /**
  20703. * Create a failure event
  20704. *
  20705. * @internal
  20706. * @param pool - the pool that originated the command
  20707. * @param command - the command
  20708. * @param error - the generated error or a server error response
  20709. * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration
  20710. */
  20711. constructor(connection, command, error, started) {
  20712. this.name = constants_1.COMMAND_FAILED;
  20713. const cmd = extractCommand(command);
  20714. const commandName = extractCommandName(cmd);
  20715. const { address, connectionId, serviceId } = extractConnectionDetails(connection);
  20716. this.address = address;
  20717. this.connectionId = connectionId;
  20718. this.serviceId = serviceId;
  20719. this.requestId = command.requestId;
  20720. this.commandName = commandName;
  20721. this.duration = (0, utils_1.calculateDurationInMs)(started);
  20722. this.failure = maybeRedact(commandName, cmd, error);
  20723. }
  20724. /* @internal */
  20725. get hasServiceId() {
  20726. return !!this.serviceId;
  20727. }
  20728. };
  20729. __name(_CommandFailedEvent, "CommandFailedEvent");
  20730. var CommandFailedEvent = _CommandFailedEvent;
  20731. exports2.CommandFailedEvent = CommandFailedEvent;
  20732. exports2.SENSITIVE_COMMANDS = /* @__PURE__ */ new Set([
  20733. "authenticate",
  20734. "saslStart",
  20735. "saslContinue",
  20736. "getnonce",
  20737. "createUser",
  20738. "updateUser",
  20739. "copydbgetnonce",
  20740. "copydbsaslstart",
  20741. "copydb"
  20742. ]);
  20743. var HELLO_COMMANDS = /* @__PURE__ */ new Set(["hello", constants_1.LEGACY_HELLO_COMMAND, constants_1.LEGACY_HELLO_COMMAND_CAMEL_CASE]);
  20744. var extractCommandName = /* @__PURE__ */ __name((commandDoc) => Object.keys(commandDoc)[0], "extractCommandName");
  20745. var namespace = /* @__PURE__ */ __name((command) => command.ns, "namespace");
  20746. var databaseName = /* @__PURE__ */ __name((command) => command.ns.split(".")[0], "databaseName");
  20747. var collectionName = /* @__PURE__ */ __name((command) => command.ns.split(".")[1], "collectionName");
  20748. var maybeRedact = /* @__PURE__ */ __name((commandName, commandDoc, result) => exports2.SENSITIVE_COMMANDS.has(commandName) || HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate ? {} : result, "maybeRedact");
  20749. var LEGACY_FIND_QUERY_MAP = {
  20750. $query: "filter",
  20751. $orderby: "sort",
  20752. $hint: "hint",
  20753. $comment: "comment",
  20754. $maxScan: "maxScan",
  20755. $max: "max",
  20756. $min: "min",
  20757. $returnKey: "returnKey",
  20758. $showDiskLoc: "showRecordId",
  20759. $maxTimeMS: "maxTimeMS",
  20760. $snapshot: "snapshot"
  20761. };
  20762. var LEGACY_FIND_OPTIONS_MAP = {
  20763. numberToSkip: "skip",
  20764. numberToReturn: "batchSize",
  20765. returnFieldSelector: "projection"
  20766. };
  20767. var OP_QUERY_KEYS = [
  20768. "tailable",
  20769. "oplogReplay",
  20770. "noCursorTimeout",
  20771. "awaitData",
  20772. "partial",
  20773. "exhaust"
  20774. ];
  20775. function extractCommand(command) {
  20776. var _a;
  20777. if (command instanceof commands_1.Msg) {
  20778. return (0, utils_1.deepCopy)(command.command);
  20779. }
  20780. if ((_a = command.query) == null ? void 0 : _a.$query) {
  20781. let result;
  20782. if (command.ns === "admin.$cmd") {
  20783. result = Object.assign({}, command.query.$query);
  20784. } else {
  20785. result = { find: collectionName(command) };
  20786. Object.keys(LEGACY_FIND_QUERY_MAP).forEach((key) => {
  20787. if (command.query[key] != null) {
  20788. result[LEGACY_FIND_QUERY_MAP[key]] = (0, utils_1.deepCopy)(command.query[key]);
  20789. }
  20790. });
  20791. }
  20792. Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach((key) => {
  20793. const legacyKey = key;
  20794. if (command[legacyKey] != null) {
  20795. result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = (0, utils_1.deepCopy)(command[legacyKey]);
  20796. }
  20797. });
  20798. OP_QUERY_KEYS.forEach((key) => {
  20799. if (command[key]) {
  20800. result[key] = command[key];
  20801. }
  20802. });
  20803. if (command.pre32Limit != null) {
  20804. result.limit = command.pre32Limit;
  20805. }
  20806. if (command.query.$explain) {
  20807. return { explain: result };
  20808. }
  20809. return result;
  20810. }
  20811. const clonedQuery = {};
  20812. const clonedCommand = {};
  20813. if (command.query) {
  20814. for (const k in command.query) {
  20815. clonedQuery[k] = (0, utils_1.deepCopy)(command.query[k]);
  20816. }
  20817. clonedCommand.query = clonedQuery;
  20818. }
  20819. for (const k in command) {
  20820. if (k === "query")
  20821. continue;
  20822. clonedCommand[k] = (0, utils_1.deepCopy)(command[k]);
  20823. }
  20824. return command.query ? clonedQuery : clonedCommand;
  20825. }
  20826. __name(extractCommand, "extractCommand");
  20827. function extractReply(command, reply) {
  20828. if (!reply) {
  20829. return reply;
  20830. }
  20831. if (command instanceof commands_1.Msg) {
  20832. return (0, utils_1.deepCopy)(reply.result ? reply.result : reply);
  20833. }
  20834. if (command.query && command.query.$query != null) {
  20835. return {
  20836. ok: 1,
  20837. cursor: {
  20838. id: (0, utils_1.deepCopy)(reply.cursorId),
  20839. ns: namespace(command),
  20840. firstBatch: (0, utils_1.deepCopy)(reply.documents)
  20841. }
  20842. };
  20843. }
  20844. return (0, utils_1.deepCopy)(reply.result ? reply.result : reply);
  20845. }
  20846. __name(extractReply, "extractReply");
  20847. function extractConnectionDetails(connection) {
  20848. let connectionId;
  20849. if ("id" in connection) {
  20850. connectionId = connection.id;
  20851. }
  20852. return {
  20853. address: connection.address,
  20854. serviceId: connection.serviceId,
  20855. connectionId
  20856. };
  20857. }
  20858. __name(extractConnectionDetails, "extractConnectionDetails");
  20859. }
  20860. });
  20861. // node_modules/mongodb/lib/cmap/message_stream.js
  20862. var require_message_stream = __commonJS({
  20863. "node_modules/mongodb/lib/cmap/message_stream.js"(exports2) {
  20864. "use strict";
  20865. Object.defineProperty(exports2, "__esModule", { value: true });
  20866. exports2.MessageStream = void 0;
  20867. var stream_1 = require("stream");
  20868. var error_1 = require_error();
  20869. var utils_1 = require_utils();
  20870. var commands_1 = require_commands();
  20871. var compression_1 = require_compression();
  20872. var constants_1 = require_constants();
  20873. var MESSAGE_HEADER_SIZE = 16;
  20874. var COMPRESSION_DETAILS_SIZE = 9;
  20875. var kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4;
  20876. var kBuffer = Symbol("buffer");
  20877. var _MessageStream = class _MessageStream extends stream_1.Duplex {
  20878. constructor(options = {}) {
  20879. super(options);
  20880. this.isMonitoringConnection = false;
  20881. this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize;
  20882. this[kBuffer] = new utils_1.BufferPool();
  20883. }
  20884. get buffer() {
  20885. return this[kBuffer];
  20886. }
  20887. _write(chunk, _, callback) {
  20888. this[kBuffer].append(chunk);
  20889. processIncomingData(this, callback);
  20890. }
  20891. _read() {
  20892. return;
  20893. }
  20894. writeCommand(command, operationDescription) {
  20895. const agreedCompressor = operationDescription.agreedCompressor ?? "none";
  20896. if (agreedCompressor === "none" || !canCompress(command)) {
  20897. const data = command.toBin();
  20898. this.push(Array.isArray(data) ? Buffer.concat(data) : data);
  20899. return;
  20900. }
  20901. const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin());
  20902. const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);
  20903. const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12);
  20904. const options = {
  20905. agreedCompressor,
  20906. zlibCompressionLevel: operationDescription.zlibCompressionLevel ?? 0
  20907. };
  20908. (0, compression_1.compress)(options, messageToBeCompressed).then((compressedMessage) => {
  20909. const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE);
  20910. msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, 0);
  20911. msgHeader.writeInt32LE(command.requestId, 4);
  20912. msgHeader.writeInt32LE(0, 8);
  20913. msgHeader.writeInt32LE(constants_1.OP_COMPRESSED, 12);
  20914. const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE);
  20915. compressionDetails.writeInt32LE(originalCommandOpCode, 0);
  20916. compressionDetails.writeInt32LE(messageToBeCompressed.length, 4);
  20917. compressionDetails.writeUInt8(compression_1.Compressor[agreedCompressor], 8);
  20918. this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage]));
  20919. }, (error) => {
  20920. operationDescription.cb(error);
  20921. });
  20922. }
  20923. };
  20924. __name(_MessageStream, "MessageStream");
  20925. var MessageStream = _MessageStream;
  20926. exports2.MessageStream = MessageStream;
  20927. function canCompress(command) {
  20928. const commandDoc = command instanceof commands_1.Msg ? command.command : command.query;
  20929. const commandName = Object.keys(commandDoc)[0];
  20930. return !compression_1.uncompressibleCommands.has(commandName);
  20931. }
  20932. __name(canCompress, "canCompress");
  20933. function processIncomingData(stream, callback) {
  20934. const buffer = stream[kBuffer];
  20935. const sizeOfMessage = buffer.getInt32();
  20936. if (sizeOfMessage == null) {
  20937. return callback();
  20938. }
  20939. if (sizeOfMessage < 0) {
  20940. return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}`));
  20941. }
  20942. if (sizeOfMessage > stream.maxBsonMessageSize) {
  20943. return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`));
  20944. }
  20945. if (sizeOfMessage > buffer.length) {
  20946. return callback();
  20947. }
  20948. const message = buffer.read(sizeOfMessage);
  20949. const messageHeader = {
  20950. length: message.readInt32LE(0),
  20951. requestId: message.readInt32LE(4),
  20952. responseTo: message.readInt32LE(8),
  20953. opCode: message.readInt32LE(12)
  20954. };
  20955. const monitorHasAnotherHello = /* @__PURE__ */ __name(() => {
  20956. if (stream.isMonitoringConnection) {
  20957. const sizeOfMessage2 = buffer.getInt32();
  20958. if (sizeOfMessage2 != null && sizeOfMessage2 <= buffer.length) {
  20959. return true;
  20960. }
  20961. }
  20962. return false;
  20963. }, "monitorHasAnotherHello");
  20964. let ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response;
  20965. if (messageHeader.opCode !== constants_1.OP_COMPRESSED) {
  20966. const messageBody = message.subarray(MESSAGE_HEADER_SIZE);
  20967. if (monitorHasAnotherHello()) {
  20968. return processIncomingData(stream, callback);
  20969. }
  20970. stream.emit("message", new ResponseType(message, messageHeader, messageBody));
  20971. if (buffer.length >= 4) {
  20972. return processIncomingData(stream, callback);
  20973. }
  20974. return callback();
  20975. }
  20976. messageHeader.fromCompressed = true;
  20977. messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE);
  20978. messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4);
  20979. const compressorID = message[MESSAGE_HEADER_SIZE + 8];
  20980. const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);
  20981. ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response;
  20982. (0, compression_1.decompress)(compressorID, compressedBuffer).then((messageBody) => {
  20983. if (messageBody.length !== messageHeader.length) {
  20984. return callback(new error_1.MongoDecompressionError("Message body and message header must be the same length"));
  20985. }
  20986. if (monitorHasAnotherHello()) {
  20987. return processIncomingData(stream, callback);
  20988. }
  20989. stream.emit("message", new ResponseType(message, messageHeader, messageBody));
  20990. if (buffer.length >= 4) {
  20991. return processIncomingData(stream, callback);
  20992. }
  20993. return callback();
  20994. }, (error) => {
  20995. return callback(error);
  20996. });
  20997. }
  20998. __name(processIncomingData, "processIncomingData");
  20999. }
  21000. });
  21001. // node_modules/mongodb/lib/cmap/stream_description.js
  21002. var require_stream_description = __commonJS({
  21003. "node_modules/mongodb/lib/cmap/stream_description.js"(exports2) {
  21004. "use strict";
  21005. Object.defineProperty(exports2, "__esModule", { value: true });
  21006. exports2.StreamDescription = void 0;
  21007. var common_1 = require_common();
  21008. var server_description_1 = require_server_description();
  21009. var RESPONSE_FIELDS = [
  21010. "minWireVersion",
  21011. "maxWireVersion",
  21012. "maxBsonObjectSize",
  21013. "maxMessageSizeBytes",
  21014. "maxWriteBatchSize",
  21015. "logicalSessionTimeoutMinutes"
  21016. ];
  21017. var _StreamDescription = class _StreamDescription {
  21018. constructor(address, options) {
  21019. this.address = address;
  21020. this.type = common_1.ServerType.Unknown;
  21021. this.minWireVersion = void 0;
  21022. this.maxWireVersion = void 0;
  21023. this.maxBsonObjectSize = 16777216;
  21024. this.maxMessageSizeBytes = 48e6;
  21025. this.maxWriteBatchSize = 1e5;
  21026. this.logicalSessionTimeoutMinutes = options == null ? void 0 : options.logicalSessionTimeoutMinutes;
  21027. this.loadBalanced = !!(options == null ? void 0 : options.loadBalanced);
  21028. this.compressors = options && options.compressors && Array.isArray(options.compressors) ? options.compressors : [];
  21029. }
  21030. receiveResponse(response) {
  21031. if (response == null) {
  21032. return;
  21033. }
  21034. this.type = (0, server_description_1.parseServerType)(response);
  21035. for (const field of RESPONSE_FIELDS) {
  21036. if (response[field] != null) {
  21037. this[field] = response[field];
  21038. }
  21039. if ("__nodejs_mock_server__" in response) {
  21040. this.__nodejs_mock_server__ = response["__nodejs_mock_server__"];
  21041. }
  21042. }
  21043. if (response.compression) {
  21044. this.compressor = this.compressors.filter((c) => {
  21045. var _a;
  21046. return (_a = response.compression) == null ? void 0 : _a.includes(c);
  21047. })[0];
  21048. }
  21049. }
  21050. };
  21051. __name(_StreamDescription, "StreamDescription");
  21052. var StreamDescription = _StreamDescription;
  21053. exports2.StreamDescription = StreamDescription;
  21054. }
  21055. });
  21056. // node_modules/mongodb/lib/cmap/connection.js
  21057. var require_connection = __commonJS({
  21058. "node_modules/mongodb/lib/cmap/connection.js"(exports2) {
  21059. "use strict";
  21060. Object.defineProperty(exports2, "__esModule", { value: true });
  21061. exports2.hasSessionSupport = exports2.CryptoConnection = exports2.Connection = void 0;
  21062. var timers_1 = require("timers");
  21063. var util_1 = require("util");
  21064. var constants_1 = require_constants2();
  21065. var error_1 = require_error();
  21066. var mongo_types_1 = require_mongo_types();
  21067. var sessions_1 = require_sessions();
  21068. var utils_1 = require_utils();
  21069. var command_monitoring_events_1 = require_command_monitoring_events();
  21070. var commands_1 = require_commands();
  21071. var message_stream_1 = require_message_stream();
  21072. var stream_description_1 = require_stream_description();
  21073. var shared_1 = require_shared();
  21074. var kStream = Symbol("stream");
  21075. var kQueue = Symbol("queue");
  21076. var kMessageStream = Symbol("messageStream");
  21077. var kGeneration = Symbol("generation");
  21078. var kLastUseTime = Symbol("lastUseTime");
  21079. var kClusterTime = Symbol("clusterTime");
  21080. var kDescription = Symbol("description");
  21081. var kHello = Symbol("hello");
  21082. var kAutoEncrypter = Symbol("autoEncrypter");
  21083. var kDelayedTimeoutId = Symbol("delayedTimeoutId");
  21084. var INVALID_QUEUE_SIZE = "Connection internal queue contains more than 1 operation description";
  21085. var _Connection = class _Connection extends mongo_types_1.TypedEventEmitter {
  21086. constructor(stream, options) {
  21087. var _a;
  21088. super();
  21089. this.commandAsync = (0, util_1.promisify)((ns, cmd, options2, callback) => this.command(ns, cmd, options2, callback));
  21090. this.id = options.id;
  21091. this.address = streamIdentifier(stream, options);
  21092. this.socketTimeoutMS = options.socketTimeoutMS ?? 0;
  21093. this.monitorCommands = options.monitorCommands;
  21094. this.serverApi = options.serverApi;
  21095. this.closed = false;
  21096. this[kHello] = null;
  21097. this[kClusterTime] = null;
  21098. this[kDescription] = new stream_description_1.StreamDescription(this.address, options);
  21099. this[kGeneration] = options.generation;
  21100. this[kLastUseTime] = (0, utils_1.now)();
  21101. this[kQueue] = /* @__PURE__ */ new Map();
  21102. this[kMessageStream] = new message_stream_1.MessageStream({
  21103. ...options,
  21104. maxBsonMessageSize: (_a = this.hello) == null ? void 0 : _a.maxBsonMessageSize
  21105. });
  21106. this[kStream] = stream;
  21107. this[kDelayedTimeoutId] = null;
  21108. this[kMessageStream].on("message", (message) => this.onMessage(message));
  21109. this[kMessageStream].on("error", (error) => this.onError(error));
  21110. this[kStream].on("close", () => this.onClose());
  21111. this[kStream].on("timeout", () => this.onTimeout());
  21112. this[kStream].on("error", () => {
  21113. });
  21114. this[kStream].pipe(this[kMessageStream]);
  21115. this[kMessageStream].pipe(this[kStream]);
  21116. }
  21117. get description() {
  21118. return this[kDescription];
  21119. }
  21120. get hello() {
  21121. return this[kHello];
  21122. }
  21123. // the `connect` method stores the result of the handshake hello on the connection
  21124. set hello(response) {
  21125. this[kDescription].receiveResponse(response);
  21126. this[kDescription] = Object.freeze(this[kDescription]);
  21127. this[kHello] = response;
  21128. }
  21129. // Set the whether the message stream is for a monitoring connection.
  21130. set isMonitoringConnection(value) {
  21131. this[kMessageStream].isMonitoringConnection = value;
  21132. }
  21133. get isMonitoringConnection() {
  21134. return this[kMessageStream].isMonitoringConnection;
  21135. }
  21136. get serviceId() {
  21137. var _a;
  21138. return (_a = this.hello) == null ? void 0 : _a.serviceId;
  21139. }
  21140. get loadBalanced() {
  21141. return this.description.loadBalanced;
  21142. }
  21143. get generation() {
  21144. return this[kGeneration] || 0;
  21145. }
  21146. set generation(generation) {
  21147. this[kGeneration] = generation;
  21148. }
  21149. get idleTime() {
  21150. return (0, utils_1.calculateDurationInMs)(this[kLastUseTime]);
  21151. }
  21152. get clusterTime() {
  21153. return this[kClusterTime];
  21154. }
  21155. get stream() {
  21156. return this[kStream];
  21157. }
  21158. markAvailable() {
  21159. this[kLastUseTime] = (0, utils_1.now)();
  21160. }
  21161. onError(error) {
  21162. this.cleanup(true, error);
  21163. }
  21164. onClose() {
  21165. const message = `connection ${this.id} to ${this.address} closed`;
  21166. this.cleanup(true, new error_1.MongoNetworkError(message));
  21167. }
  21168. onTimeout() {
  21169. this[kDelayedTimeoutId] = (0, timers_1.setTimeout)(() => {
  21170. const message = `connection ${this.id} to ${this.address} timed out`;
  21171. const beforeHandshake = this.hello == null;
  21172. this.cleanup(true, new error_1.MongoNetworkTimeoutError(message, { beforeHandshake }));
  21173. }, 1).unref();
  21174. }
  21175. onMessage(message) {
  21176. const delayedTimeoutId = this[kDelayedTimeoutId];
  21177. if (delayedTimeoutId != null) {
  21178. (0, timers_1.clearTimeout)(delayedTimeoutId);
  21179. this[kDelayedTimeoutId] = null;
  21180. }
  21181. const socketTimeoutMS = this[kStream].timeout ?? 0;
  21182. this[kStream].setTimeout(0);
  21183. this.emit("message", message);
  21184. let operationDescription = this[kQueue].get(message.responseTo);
  21185. if (!operationDescription && this.isMonitoringConnection) {
  21186. if (this[kQueue].size > 1) {
  21187. this.cleanup(true, new error_1.MongoRuntimeError(INVALID_QUEUE_SIZE));
  21188. } else {
  21189. const entry = this[kQueue].entries().next();
  21190. if (entry.value != null) {
  21191. const [requestId, orphaned] = entry.value;
  21192. operationDescription = orphaned;
  21193. this[kQueue].delete(requestId);
  21194. }
  21195. }
  21196. }
  21197. if (!operationDescription) {
  21198. return;
  21199. }
  21200. const callback = operationDescription.cb;
  21201. this[kQueue].delete(message.responseTo);
  21202. if ("moreToCome" in message && message.moreToCome) {
  21203. this[kQueue].set(message.requestId, operationDescription);
  21204. this[kStream].setTimeout(socketTimeoutMS);
  21205. }
  21206. try {
  21207. message.parse(operationDescription);
  21208. } catch (err) {
  21209. callback(err);
  21210. return;
  21211. }
  21212. if (message.documents[0]) {
  21213. const document = message.documents[0];
  21214. const session = operationDescription.session;
  21215. if (session) {
  21216. (0, sessions_1.updateSessionFromResponse)(session, document);
  21217. }
  21218. if (document.$clusterTime) {
  21219. this[kClusterTime] = document.$clusterTime;
  21220. this.emit(_Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime);
  21221. }
  21222. if (document.writeConcernError) {
  21223. callback(new error_1.MongoWriteConcernError(document.writeConcernError, document), document);
  21224. return;
  21225. }
  21226. if (document.ok === 0 || document.$err || document.errmsg || document.code) {
  21227. callback(new error_1.MongoServerError(document));
  21228. return;
  21229. }
  21230. }
  21231. callback(void 0, message.documents[0]);
  21232. }
  21233. destroy(options, callback) {
  21234. if (this.closed) {
  21235. process.nextTick(() => callback == null ? void 0 : callback());
  21236. return;
  21237. }
  21238. if (typeof callback === "function") {
  21239. this.once("close", () => process.nextTick(() => callback()));
  21240. }
  21241. this.removeAllListeners(_Connection.PINNED);
  21242. this.removeAllListeners(_Connection.UNPINNED);
  21243. const message = `connection ${this.id} to ${this.address} closed`;
  21244. this.cleanup(options.force, new error_1.MongoNetworkError(message));
  21245. }
  21246. /**
  21247. * A method that cleans up the connection. When `force` is true, this method
  21248. * forcibly destroys the socket.
  21249. *
  21250. * If an error is provided, any in-flight operations will be closed with the error.
  21251. *
  21252. * This method does nothing if the connection is already closed.
  21253. */
  21254. cleanup(force, error) {
  21255. if (this.closed) {
  21256. return;
  21257. }
  21258. this.closed = true;
  21259. const completeCleanup = /* @__PURE__ */ __name(() => {
  21260. for (const op of this[kQueue].values()) {
  21261. op.cb(error);
  21262. }
  21263. this[kQueue].clear();
  21264. this.emit(_Connection.CLOSE);
  21265. }, "completeCleanup");
  21266. this[kStream].removeAllListeners();
  21267. this[kMessageStream].removeAllListeners();
  21268. this[kMessageStream].destroy();
  21269. if (force) {
  21270. this[kStream].destroy();
  21271. completeCleanup();
  21272. return;
  21273. }
  21274. if (!this[kStream].writableEnded) {
  21275. this[kStream].end(() => {
  21276. this[kStream].destroy();
  21277. completeCleanup();
  21278. });
  21279. } else {
  21280. completeCleanup();
  21281. }
  21282. }
  21283. command(ns, command, options, callback) {
  21284. let cmd = { ...command };
  21285. const readPreference = (0, shared_1.getReadPreference)(options);
  21286. const shouldUseOpMsg = supportsOpMsg(this);
  21287. const session = options == null ? void 0 : options.session;
  21288. let clusterTime = this.clusterTime;
  21289. if (this.serverApi) {
  21290. const { version, strict, deprecationErrors } = this.serverApi;
  21291. cmd.apiVersion = version;
  21292. if (strict != null)
  21293. cmd.apiStrict = strict;
  21294. if (deprecationErrors != null)
  21295. cmd.apiDeprecationErrors = deprecationErrors;
  21296. }
  21297. if (hasSessionSupport(this) && session) {
  21298. if (session.clusterTime && clusterTime && session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)) {
  21299. clusterTime = session.clusterTime;
  21300. }
  21301. const err = (0, sessions_1.applySession)(session, cmd, options);
  21302. if (err) {
  21303. return callback(err);
  21304. }
  21305. } else if (session == null ? void 0 : session.explicit) {
  21306. return callback(new error_1.MongoCompatibilityError("Current topology does not support sessions"));
  21307. }
  21308. if (clusterTime) {
  21309. cmd.$clusterTime = clusterTime;
  21310. }
  21311. if ((0, shared_1.isSharded)(this) && !shouldUseOpMsg && readPreference && readPreference.mode !== "primary") {
  21312. cmd = {
  21313. $query: cmd,
  21314. $readPreference: readPreference.toJSON()
  21315. };
  21316. }
  21317. const commandOptions = Object.assign({
  21318. numberToSkip: 0,
  21319. numberToReturn: -1,
  21320. checkKeys: false,
  21321. // This value is not overridable
  21322. secondaryOk: readPreference.secondaryOk()
  21323. }, options);
  21324. const cmdNs = `${ns.db}.$cmd`;
  21325. const message = shouldUseOpMsg ? new commands_1.Msg(cmdNs, cmd, commandOptions) : new commands_1.Query(cmdNs, cmd, commandOptions);
  21326. try {
  21327. write(this, message, commandOptions, callback);
  21328. } catch (err) {
  21329. callback(err);
  21330. }
  21331. }
  21332. };
  21333. __name(_Connection, "Connection");
  21334. var Connection = _Connection;
  21335. Connection.COMMAND_STARTED = constants_1.COMMAND_STARTED;
  21336. Connection.COMMAND_SUCCEEDED = constants_1.COMMAND_SUCCEEDED;
  21337. Connection.COMMAND_FAILED = constants_1.COMMAND_FAILED;
  21338. Connection.CLUSTER_TIME_RECEIVED = constants_1.CLUSTER_TIME_RECEIVED;
  21339. Connection.CLOSE = constants_1.CLOSE;
  21340. Connection.MESSAGE = constants_1.MESSAGE;
  21341. Connection.PINNED = constants_1.PINNED;
  21342. Connection.UNPINNED = constants_1.UNPINNED;
  21343. exports2.Connection = Connection;
  21344. var _CryptoConnection = class _CryptoConnection extends Connection {
  21345. constructor(stream, options) {
  21346. super(stream, options);
  21347. this[kAutoEncrypter] = options.autoEncrypter;
  21348. }
  21349. /** @internal @override */
  21350. command(ns, cmd, options, callback) {
  21351. const autoEncrypter = this[kAutoEncrypter];
  21352. if (!autoEncrypter) {
  21353. return callback(new error_1.MongoMissingDependencyError("No AutoEncrypter available for encryption"));
  21354. }
  21355. const serverWireVersion = (0, utils_1.maxWireVersion)(this);
  21356. if (serverWireVersion === 0) {
  21357. return super.command(ns, cmd, options, callback);
  21358. }
  21359. if (serverWireVersion < 8) {
  21360. callback(new error_1.MongoCompatibilityError("Auto-encryption requires a minimum MongoDB version of 4.2"));
  21361. return;
  21362. }
  21363. const sort = cmd.find || cmd.findAndModify ? cmd.sort : null;
  21364. const indexKeys = cmd.createIndexes ? cmd.indexes.map((index) => index.key) : null;
  21365. autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => {
  21366. if (err || encrypted == null) {
  21367. callback(err, null);
  21368. return;
  21369. }
  21370. if (sort != null && (cmd.find || cmd.findAndModify)) {
  21371. encrypted.sort = sort;
  21372. }
  21373. if (indexKeys != null && cmd.createIndexes) {
  21374. for (const [offset, index] of indexKeys.entries()) {
  21375. encrypted.indexes[offset].key = index;
  21376. }
  21377. }
  21378. super.command(ns, encrypted, options, (err2, response) => {
  21379. if (err2 || response == null) {
  21380. callback(err2, response);
  21381. return;
  21382. }
  21383. autoEncrypter.decrypt(response, options, callback);
  21384. });
  21385. });
  21386. }
  21387. };
  21388. __name(_CryptoConnection, "CryptoConnection");
  21389. var CryptoConnection = _CryptoConnection;
  21390. exports2.CryptoConnection = CryptoConnection;
  21391. function hasSessionSupport(conn) {
  21392. const description = conn.description;
  21393. return description.logicalSessionTimeoutMinutes != null;
  21394. }
  21395. __name(hasSessionSupport, "hasSessionSupport");
  21396. exports2.hasSessionSupport = hasSessionSupport;
  21397. function supportsOpMsg(conn) {
  21398. const description = conn.description;
  21399. if (description == null) {
  21400. return false;
  21401. }
  21402. return (0, utils_1.maxWireVersion)(conn) >= 6 && !description.__nodejs_mock_server__;
  21403. }
  21404. __name(supportsOpMsg, "supportsOpMsg");
  21405. function streamIdentifier(stream, options) {
  21406. if (options.proxyHost) {
  21407. return options.hostAddress.toString();
  21408. }
  21409. const { remoteAddress, remotePort } = stream;
  21410. if (typeof remoteAddress === "string" && typeof remotePort === "number") {
  21411. return utils_1.HostAddress.fromHostPort(remoteAddress, remotePort).toString();
  21412. }
  21413. return (0, utils_1.uuidV4)().toString("hex");
  21414. }
  21415. __name(streamIdentifier, "streamIdentifier");
  21416. function write(conn, command, options, callback) {
  21417. options = options ?? {};
  21418. const operationDescription = {
  21419. requestId: command.requestId,
  21420. cb: callback,
  21421. session: options.session,
  21422. noResponse: typeof options.noResponse === "boolean" ? options.noResponse : false,
  21423. documentsReturnedIn: options.documentsReturnedIn,
  21424. // for BSON parsing
  21425. useBigInt64: typeof options.useBigInt64 === "boolean" ? options.useBigInt64 : false,
  21426. promoteLongs: typeof options.promoteLongs === "boolean" ? options.promoteLongs : true,
  21427. promoteValues: typeof options.promoteValues === "boolean" ? options.promoteValues : true,
  21428. promoteBuffers: typeof options.promoteBuffers === "boolean" ? options.promoteBuffers : false,
  21429. bsonRegExp: typeof options.bsonRegExp === "boolean" ? options.bsonRegExp : false,
  21430. enableUtf8Validation: typeof options.enableUtf8Validation === "boolean" ? options.enableUtf8Validation : true,
  21431. raw: typeof options.raw === "boolean" ? options.raw : false,
  21432. started: 0
  21433. };
  21434. if (conn[kDescription] && conn[kDescription].compressor) {
  21435. operationDescription.agreedCompressor = conn[kDescription].compressor;
  21436. if (conn[kDescription].zlibCompressionLevel) {
  21437. operationDescription.zlibCompressionLevel = conn[kDescription].zlibCompressionLevel;
  21438. }
  21439. }
  21440. if (typeof options.socketTimeoutMS === "number") {
  21441. conn[kStream].setTimeout(options.socketTimeoutMS);
  21442. } else if (conn.socketTimeoutMS !== 0) {
  21443. conn[kStream].setTimeout(conn.socketTimeoutMS);
  21444. }
  21445. if (conn.monitorCommands) {
  21446. conn.emit(Connection.COMMAND_STARTED, new command_monitoring_events_1.CommandStartedEvent(conn, command));
  21447. operationDescription.started = (0, utils_1.now)();
  21448. operationDescription.cb = (err, reply) => {
  21449. if (err && (reply == null ? void 0 : reply.ok) !== 1) {
  21450. conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, err, operationDescription.started));
  21451. } else {
  21452. if (reply && (reply.ok === 0 || reply.$err)) {
  21453. conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, reply, operationDescription.started));
  21454. } else {
  21455. conn.emit(Connection.COMMAND_SUCCEEDED, new command_monitoring_events_1.CommandSucceededEvent(conn, command, reply, operationDescription.started));
  21456. }
  21457. }
  21458. if (typeof callback === "function") {
  21459. callback(err, err instanceof error_1.MongoWriteConcernError ? void 0 : reply);
  21460. }
  21461. };
  21462. }
  21463. if (!operationDescription.noResponse) {
  21464. conn[kQueue].set(operationDescription.requestId, operationDescription);
  21465. }
  21466. try {
  21467. conn[kMessageStream].writeCommand(command, operationDescription);
  21468. } catch (e) {
  21469. if (!operationDescription.noResponse) {
  21470. conn[kQueue].delete(operationDescription.requestId);
  21471. operationDescription.cb(e);
  21472. return;
  21473. }
  21474. }
  21475. if (operationDescription.noResponse) {
  21476. operationDescription.cb();
  21477. }
  21478. }
  21479. __name(write, "write");
  21480. }
  21481. });
  21482. // node_modules/smart-buffer/build/utils.js
  21483. var require_utils3 = __commonJS({
  21484. "node_modules/smart-buffer/build/utils.js"(exports2) {
  21485. "use strict";
  21486. Object.defineProperty(exports2, "__esModule", { value: true });
  21487. var buffer_1 = require("buffer");
  21488. var ERRORS = {
  21489. INVALID_ENCODING: "Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",
  21490. INVALID_SMARTBUFFER_SIZE: "Invalid size provided. Size must be a valid integer greater than zero.",
  21491. INVALID_SMARTBUFFER_BUFFER: "Invalid Buffer provided in SmartBufferOptions.",
  21492. INVALID_SMARTBUFFER_OBJECT: "Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",
  21493. INVALID_OFFSET: "An invalid offset value was provided.",
  21494. INVALID_OFFSET_NON_NUMBER: "An invalid offset value was provided. A numeric value is required.",
  21495. INVALID_LENGTH: "An invalid length value was provided.",
  21496. INVALID_LENGTH_NON_NUMBER: "An invalid length value was provived. A numeric value is required.",
  21497. INVALID_TARGET_OFFSET: "Target offset is beyond the bounds of the internal SmartBuffer data.",
  21498. INVALID_TARGET_LENGTH: "Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",
  21499. INVALID_READ_BEYOND_BOUNDS: "Attempted to read beyond the bounds of the managed data.",
  21500. INVALID_WRITE_BEYOND_BOUNDS: "Attempted to write beyond the bounds of the managed data."
  21501. };
  21502. exports2.ERRORS = ERRORS;
  21503. function checkEncoding(encoding) {
  21504. if (!buffer_1.Buffer.isEncoding(encoding)) {
  21505. throw new Error(ERRORS.INVALID_ENCODING);
  21506. }
  21507. }
  21508. __name(checkEncoding, "checkEncoding");
  21509. exports2.checkEncoding = checkEncoding;
  21510. function isFiniteInteger(value) {
  21511. return typeof value === "number" && isFinite(value) && isInteger(value);
  21512. }
  21513. __name(isFiniteInteger, "isFiniteInteger");
  21514. exports2.isFiniteInteger = isFiniteInteger;
  21515. function checkOffsetOrLengthValue(value, offset) {
  21516. if (typeof value === "number") {
  21517. if (!isFiniteInteger(value) || value < 0) {
  21518. throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH);
  21519. }
  21520. } else {
  21521. throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER);
  21522. }
  21523. }
  21524. __name(checkOffsetOrLengthValue, "checkOffsetOrLengthValue");
  21525. function checkLengthValue(length) {
  21526. checkOffsetOrLengthValue(length, false);
  21527. }
  21528. __name(checkLengthValue, "checkLengthValue");
  21529. exports2.checkLengthValue = checkLengthValue;
  21530. function checkOffsetValue(offset) {
  21531. checkOffsetOrLengthValue(offset, true);
  21532. }
  21533. __name(checkOffsetValue, "checkOffsetValue");
  21534. exports2.checkOffsetValue = checkOffsetValue;
  21535. function checkTargetOffset(offset, buff) {
  21536. if (offset < 0 || offset > buff.length) {
  21537. throw new Error(ERRORS.INVALID_TARGET_OFFSET);
  21538. }
  21539. }
  21540. __name(checkTargetOffset, "checkTargetOffset");
  21541. exports2.checkTargetOffset = checkTargetOffset;
  21542. function isInteger(value) {
  21543. return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  21544. }
  21545. __name(isInteger, "isInteger");
  21546. function bigIntAndBufferInt64Check(bufferMethod) {
  21547. if (typeof BigInt === "undefined") {
  21548. throw new Error("Platform does not support JS BigInt type.");
  21549. }
  21550. if (typeof buffer_1.Buffer.prototype[bufferMethod] === "undefined") {
  21551. throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`);
  21552. }
  21553. }
  21554. __name(bigIntAndBufferInt64Check, "bigIntAndBufferInt64Check");
  21555. exports2.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check;
  21556. }
  21557. });
  21558. // node_modules/smart-buffer/build/smartbuffer.js
  21559. var require_smartbuffer = __commonJS({
  21560. "node_modules/smart-buffer/build/smartbuffer.js"(exports2) {
  21561. "use strict";
  21562. Object.defineProperty(exports2, "__esModule", { value: true });
  21563. var utils_1 = require_utils3();
  21564. var DEFAULT_SMARTBUFFER_SIZE = 4096;
  21565. var DEFAULT_SMARTBUFFER_ENCODING = "utf8";
  21566. var _SmartBuffer = class _SmartBuffer {
  21567. /**
  21568. * Creates a new SmartBuffer instance.
  21569. *
  21570. * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance.
  21571. */
  21572. constructor(options) {
  21573. this.length = 0;
  21574. this._encoding = DEFAULT_SMARTBUFFER_ENCODING;
  21575. this._writeOffset = 0;
  21576. this._readOffset = 0;
  21577. if (_SmartBuffer.isSmartBufferOptions(options)) {
  21578. if (options.encoding) {
  21579. utils_1.checkEncoding(options.encoding);
  21580. this._encoding = options.encoding;
  21581. }
  21582. if (options.size) {
  21583. if (utils_1.isFiniteInteger(options.size) && options.size > 0) {
  21584. this._buff = Buffer.allocUnsafe(options.size);
  21585. } else {
  21586. throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE);
  21587. }
  21588. } else if (options.buff) {
  21589. if (Buffer.isBuffer(options.buff)) {
  21590. this._buff = options.buff;
  21591. this.length = options.buff.length;
  21592. } else {
  21593. throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER);
  21594. }
  21595. } else {
  21596. this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);
  21597. }
  21598. } else {
  21599. if (typeof options !== "undefined") {
  21600. throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT);
  21601. }
  21602. this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);
  21603. }
  21604. }
  21605. /**
  21606. * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding.
  21607. *
  21608. * @param size { Number } The size of the internal Buffer.
  21609. * @param encoding { String } The BufferEncoding to use for strings.
  21610. *
  21611. * @return { SmartBuffer }
  21612. */
  21613. static fromSize(size, encoding) {
  21614. return new this({
  21615. size,
  21616. encoding
  21617. });
  21618. }
  21619. /**
  21620. * Creates a new SmartBuffer instance with the provided Buffer and optional encoding.
  21621. *
  21622. * @param buffer { Buffer } The Buffer to use as the internal Buffer value.
  21623. * @param encoding { String } The BufferEncoding to use for strings.
  21624. *
  21625. * @return { SmartBuffer }
  21626. */
  21627. static fromBuffer(buff, encoding) {
  21628. return new this({
  21629. buff,
  21630. encoding
  21631. });
  21632. }
  21633. /**
  21634. * Creates a new SmartBuffer instance with the provided SmartBufferOptions options.
  21635. *
  21636. * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance.
  21637. */
  21638. static fromOptions(options) {
  21639. return new this(options);
  21640. }
  21641. /**
  21642. * Type checking function that determines if an object is a SmartBufferOptions object.
  21643. */
  21644. static isSmartBufferOptions(options) {
  21645. const castOptions = options;
  21646. return castOptions && (castOptions.encoding !== void 0 || castOptions.size !== void 0 || castOptions.buff !== void 0);
  21647. }
  21648. // Signed integers
  21649. /**
  21650. * Reads an Int8 value from the current read position or an optionally provided offset.
  21651. *
  21652. * @param offset { Number } The offset to read data from (optional)
  21653. * @return { Number }
  21654. */
  21655. readInt8(offset) {
  21656. return this._readNumberValue(Buffer.prototype.readInt8, 1, offset);
  21657. }
  21658. /**
  21659. * Reads an Int16BE value from the current read position or an optionally provided offset.
  21660. *
  21661. * @param offset { Number } The offset to read data from (optional)
  21662. * @return { Number }
  21663. */
  21664. readInt16BE(offset) {
  21665. return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset);
  21666. }
  21667. /**
  21668. * Reads an Int16LE value from the current read position or an optionally provided offset.
  21669. *
  21670. * @param offset { Number } The offset to read data from (optional)
  21671. * @return { Number }
  21672. */
  21673. readInt16LE(offset) {
  21674. return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset);
  21675. }
  21676. /**
  21677. * Reads an Int32BE value from the current read position or an optionally provided offset.
  21678. *
  21679. * @param offset { Number } The offset to read data from (optional)
  21680. * @return { Number }
  21681. */
  21682. readInt32BE(offset) {
  21683. return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset);
  21684. }
  21685. /**
  21686. * Reads an Int32LE value from the current read position or an optionally provided offset.
  21687. *
  21688. * @param offset { Number } The offset to read data from (optional)
  21689. * @return { Number }
  21690. */
  21691. readInt32LE(offset) {
  21692. return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset);
  21693. }
  21694. /**
  21695. * Reads a BigInt64BE value from the current read position or an optionally provided offset.
  21696. *
  21697. * @param offset { Number } The offset to read data from (optional)
  21698. * @return { BigInt }
  21699. */
  21700. readBigInt64BE(offset) {
  21701. utils_1.bigIntAndBufferInt64Check("readBigInt64BE");
  21702. return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset);
  21703. }
  21704. /**
  21705. * Reads a BigInt64LE value from the current read position or an optionally provided offset.
  21706. *
  21707. * @param offset { Number } The offset to read data from (optional)
  21708. * @return { BigInt }
  21709. */
  21710. readBigInt64LE(offset) {
  21711. utils_1.bigIntAndBufferInt64Check("readBigInt64LE");
  21712. return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset);
  21713. }
  21714. /**
  21715. * Writes an Int8 value to the current write position (or at optional offset).
  21716. *
  21717. * @param value { Number } The value to write.
  21718. * @param offset { Number } The offset to write the value at.
  21719. *
  21720. * @return this
  21721. */
  21722. writeInt8(value, offset) {
  21723. this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset);
  21724. return this;
  21725. }
  21726. /**
  21727. * Inserts an Int8 value at the given offset value.
  21728. *
  21729. * @param value { Number } The value to insert.
  21730. * @param offset { Number } The offset to insert the value at.
  21731. *
  21732. * @return this
  21733. */
  21734. insertInt8(value, offset) {
  21735. return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset);
  21736. }
  21737. /**
  21738. * Writes an Int16BE value to the current write position (or at optional offset).
  21739. *
  21740. * @param value { Number } The value to write.
  21741. * @param offset { Number } The offset to write the value at.
  21742. *
  21743. * @return this
  21744. */
  21745. writeInt16BE(value, offset) {
  21746. return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset);
  21747. }
  21748. /**
  21749. * Inserts an Int16BE value at the given offset value.
  21750. *
  21751. * @param value { Number } The value to insert.
  21752. * @param offset { Number } The offset to insert the value at.
  21753. *
  21754. * @return this
  21755. */
  21756. insertInt16BE(value, offset) {
  21757. return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset);
  21758. }
  21759. /**
  21760. * Writes an Int16LE value to the current write position (or at optional offset).
  21761. *
  21762. * @param value { Number } The value to write.
  21763. * @param offset { Number } The offset to write the value at.
  21764. *
  21765. * @return this
  21766. */
  21767. writeInt16LE(value, offset) {
  21768. return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset);
  21769. }
  21770. /**
  21771. * Inserts an Int16LE value at the given offset value.
  21772. *
  21773. * @param value { Number } The value to insert.
  21774. * @param offset { Number } The offset to insert the value at.
  21775. *
  21776. * @return this
  21777. */
  21778. insertInt16LE(value, offset) {
  21779. return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset);
  21780. }
  21781. /**
  21782. * Writes an Int32BE value to the current write position (or at optional offset).
  21783. *
  21784. * @param value { Number } The value to write.
  21785. * @param offset { Number } The offset to write the value at.
  21786. *
  21787. * @return this
  21788. */
  21789. writeInt32BE(value, offset) {
  21790. return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset);
  21791. }
  21792. /**
  21793. * Inserts an Int32BE value at the given offset value.
  21794. *
  21795. * @param value { Number } The value to insert.
  21796. * @param offset { Number } The offset to insert the value at.
  21797. *
  21798. * @return this
  21799. */
  21800. insertInt32BE(value, offset) {
  21801. return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset);
  21802. }
  21803. /**
  21804. * Writes an Int32LE value to the current write position (or at optional offset).
  21805. *
  21806. * @param value { Number } The value to write.
  21807. * @param offset { Number } The offset to write the value at.
  21808. *
  21809. * @return this
  21810. */
  21811. writeInt32LE(value, offset) {
  21812. return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset);
  21813. }
  21814. /**
  21815. * Inserts an Int32LE value at the given offset value.
  21816. *
  21817. * @param value { Number } The value to insert.
  21818. * @param offset { Number } The offset to insert the value at.
  21819. *
  21820. * @return this
  21821. */
  21822. insertInt32LE(value, offset) {
  21823. return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset);
  21824. }
  21825. /**
  21826. * Writes a BigInt64BE value to the current write position (or at optional offset).
  21827. *
  21828. * @param value { BigInt } The value to write.
  21829. * @param offset { Number } The offset to write the value at.
  21830. *
  21831. * @return this
  21832. */
  21833. writeBigInt64BE(value, offset) {
  21834. utils_1.bigIntAndBufferInt64Check("writeBigInt64BE");
  21835. return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset);
  21836. }
  21837. /**
  21838. * Inserts a BigInt64BE value at the given offset value.
  21839. *
  21840. * @param value { BigInt } The value to insert.
  21841. * @param offset { Number } The offset to insert the value at.
  21842. *
  21843. * @return this
  21844. */
  21845. insertBigInt64BE(value, offset) {
  21846. utils_1.bigIntAndBufferInt64Check("writeBigInt64BE");
  21847. return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset);
  21848. }
  21849. /**
  21850. * Writes a BigInt64LE value to the current write position (or at optional offset).
  21851. *
  21852. * @param value { BigInt } The value to write.
  21853. * @param offset { Number } The offset to write the value at.
  21854. *
  21855. * @return this
  21856. */
  21857. writeBigInt64LE(value, offset) {
  21858. utils_1.bigIntAndBufferInt64Check("writeBigInt64LE");
  21859. return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset);
  21860. }
  21861. /**
  21862. * Inserts a Int64LE value at the given offset value.
  21863. *
  21864. * @param value { BigInt } The value to insert.
  21865. * @param offset { Number } The offset to insert the value at.
  21866. *
  21867. * @return this
  21868. */
  21869. insertBigInt64LE(value, offset) {
  21870. utils_1.bigIntAndBufferInt64Check("writeBigInt64LE");
  21871. return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset);
  21872. }
  21873. // Unsigned Integers
  21874. /**
  21875. * Reads an UInt8 value from the current read position or an optionally provided offset.
  21876. *
  21877. * @param offset { Number } The offset to read data from (optional)
  21878. * @return { Number }
  21879. */
  21880. readUInt8(offset) {
  21881. return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset);
  21882. }
  21883. /**
  21884. * Reads an UInt16BE value from the current read position or an optionally provided offset.
  21885. *
  21886. * @param offset { Number } The offset to read data from (optional)
  21887. * @return { Number }
  21888. */
  21889. readUInt16BE(offset) {
  21890. return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset);
  21891. }
  21892. /**
  21893. * Reads an UInt16LE value from the current read position or an optionally provided offset.
  21894. *
  21895. * @param offset { Number } The offset to read data from (optional)
  21896. * @return { Number }
  21897. */
  21898. readUInt16LE(offset) {
  21899. return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset);
  21900. }
  21901. /**
  21902. * Reads an UInt32BE value from the current read position or an optionally provided offset.
  21903. *
  21904. * @param offset { Number } The offset to read data from (optional)
  21905. * @return { Number }
  21906. */
  21907. readUInt32BE(offset) {
  21908. return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset);
  21909. }
  21910. /**
  21911. * Reads an UInt32LE value from the current read position or an optionally provided offset.
  21912. *
  21913. * @param offset { Number } The offset to read data from (optional)
  21914. * @return { Number }
  21915. */
  21916. readUInt32LE(offset) {
  21917. return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset);
  21918. }
  21919. /**
  21920. * Reads a BigUInt64BE value from the current read position or an optionally provided offset.
  21921. *
  21922. * @param offset { Number } The offset to read data from (optional)
  21923. * @return { BigInt }
  21924. */
  21925. readBigUInt64BE(offset) {
  21926. utils_1.bigIntAndBufferInt64Check("readBigUInt64BE");
  21927. return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset);
  21928. }
  21929. /**
  21930. * Reads a BigUInt64LE value from the current read position or an optionally provided offset.
  21931. *
  21932. * @param offset { Number } The offset to read data from (optional)
  21933. * @return { BigInt }
  21934. */
  21935. readBigUInt64LE(offset) {
  21936. utils_1.bigIntAndBufferInt64Check("readBigUInt64LE");
  21937. return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset);
  21938. }
  21939. /**
  21940. * Writes an UInt8 value to the current write position (or at optional offset).
  21941. *
  21942. * @param value { Number } The value to write.
  21943. * @param offset { Number } The offset to write the value at.
  21944. *
  21945. * @return this
  21946. */
  21947. writeUInt8(value, offset) {
  21948. return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset);
  21949. }
  21950. /**
  21951. * Inserts an UInt8 value at the given offset value.
  21952. *
  21953. * @param value { Number } The value to insert.
  21954. * @param offset { Number } The offset to insert the value at.
  21955. *
  21956. * @return this
  21957. */
  21958. insertUInt8(value, offset) {
  21959. return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset);
  21960. }
  21961. /**
  21962. * Writes an UInt16BE value to the current write position (or at optional offset).
  21963. *
  21964. * @param value { Number } The value to write.
  21965. * @param offset { Number } The offset to write the value at.
  21966. *
  21967. * @return this
  21968. */
  21969. writeUInt16BE(value, offset) {
  21970. return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset);
  21971. }
  21972. /**
  21973. * Inserts an UInt16BE value at the given offset value.
  21974. *
  21975. * @param value { Number } The value to insert.
  21976. * @param offset { Number } The offset to insert the value at.
  21977. *
  21978. * @return this
  21979. */
  21980. insertUInt16BE(value, offset) {
  21981. return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset);
  21982. }
  21983. /**
  21984. * Writes an UInt16LE value to the current write position (or at optional offset).
  21985. *
  21986. * @param value { Number } The value to write.
  21987. * @param offset { Number } The offset to write the value at.
  21988. *
  21989. * @return this
  21990. */
  21991. writeUInt16LE(value, offset) {
  21992. return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset);
  21993. }
  21994. /**
  21995. * Inserts an UInt16LE value at the given offset value.
  21996. *
  21997. * @param value { Number } The value to insert.
  21998. * @param offset { Number } The offset to insert the value at.
  21999. *
  22000. * @return this
  22001. */
  22002. insertUInt16LE(value, offset) {
  22003. return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset);
  22004. }
  22005. /**
  22006. * Writes an UInt32BE value to the current write position (or at optional offset).
  22007. *
  22008. * @param value { Number } The value to write.
  22009. * @param offset { Number } The offset to write the value at.
  22010. *
  22011. * @return this
  22012. */
  22013. writeUInt32BE(value, offset) {
  22014. return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset);
  22015. }
  22016. /**
  22017. * Inserts an UInt32BE value at the given offset value.
  22018. *
  22019. * @param value { Number } The value to insert.
  22020. * @param offset { Number } The offset to insert the value at.
  22021. *
  22022. * @return this
  22023. */
  22024. insertUInt32BE(value, offset) {
  22025. return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset);
  22026. }
  22027. /**
  22028. * Writes an UInt32LE value to the current write position (or at optional offset).
  22029. *
  22030. * @param value { Number } The value to write.
  22031. * @param offset { Number } The offset to write the value at.
  22032. *
  22033. * @return this
  22034. */
  22035. writeUInt32LE(value, offset) {
  22036. return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset);
  22037. }
  22038. /**
  22039. * Inserts an UInt32LE value at the given offset value.
  22040. *
  22041. * @param value { Number } The value to insert.
  22042. * @param offset { Number } The offset to insert the value at.
  22043. *
  22044. * @return this
  22045. */
  22046. insertUInt32LE(value, offset) {
  22047. return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset);
  22048. }
  22049. /**
  22050. * Writes a BigUInt64BE value to the current write position (or at optional offset).
  22051. *
  22052. * @param value { Number } The value to write.
  22053. * @param offset { Number } The offset to write the value at.
  22054. *
  22055. * @return this
  22056. */
  22057. writeBigUInt64BE(value, offset) {
  22058. utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE");
  22059. return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset);
  22060. }
  22061. /**
  22062. * Inserts a BigUInt64BE value at the given offset value.
  22063. *
  22064. * @param value { Number } The value to insert.
  22065. * @param offset { Number } The offset to insert the value at.
  22066. *
  22067. * @return this
  22068. */
  22069. insertBigUInt64BE(value, offset) {
  22070. utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE");
  22071. return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset);
  22072. }
  22073. /**
  22074. * Writes a BigUInt64LE value to the current write position (or at optional offset).
  22075. *
  22076. * @param value { Number } The value to write.
  22077. * @param offset { Number } The offset to write the value at.
  22078. *
  22079. * @return this
  22080. */
  22081. writeBigUInt64LE(value, offset) {
  22082. utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE");
  22083. return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset);
  22084. }
  22085. /**
  22086. * Inserts a BigUInt64LE value at the given offset value.
  22087. *
  22088. * @param value { Number } The value to insert.
  22089. * @param offset { Number } The offset to insert the value at.
  22090. *
  22091. * @return this
  22092. */
  22093. insertBigUInt64LE(value, offset) {
  22094. utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE");
  22095. return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset);
  22096. }
  22097. // Floating Point
  22098. /**
  22099. * Reads an FloatBE value from the current read position or an optionally provided offset.
  22100. *
  22101. * @param offset { Number } The offset to read data from (optional)
  22102. * @return { Number }
  22103. */
  22104. readFloatBE(offset) {
  22105. return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset);
  22106. }
  22107. /**
  22108. * Reads an FloatLE value from the current read position or an optionally provided offset.
  22109. *
  22110. * @param offset { Number } The offset to read data from (optional)
  22111. * @return { Number }
  22112. */
  22113. readFloatLE(offset) {
  22114. return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset);
  22115. }
  22116. /**
  22117. * Writes a FloatBE value to the current write position (or at optional offset).
  22118. *
  22119. * @param value { Number } The value to write.
  22120. * @param offset { Number } The offset to write the value at.
  22121. *
  22122. * @return this
  22123. */
  22124. writeFloatBE(value, offset) {
  22125. return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset);
  22126. }
  22127. /**
  22128. * Inserts a FloatBE value at the given offset value.
  22129. *
  22130. * @param value { Number } The value to insert.
  22131. * @param offset { Number } The offset to insert the value at.
  22132. *
  22133. * @return this
  22134. */
  22135. insertFloatBE(value, offset) {
  22136. return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset);
  22137. }
  22138. /**
  22139. * Writes a FloatLE value to the current write position (or at optional offset).
  22140. *
  22141. * @param value { Number } The value to write.
  22142. * @param offset { Number } The offset to write the value at.
  22143. *
  22144. * @return this
  22145. */
  22146. writeFloatLE(value, offset) {
  22147. return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset);
  22148. }
  22149. /**
  22150. * Inserts a FloatLE value at the given offset value.
  22151. *
  22152. * @param value { Number } The value to insert.
  22153. * @param offset { Number } The offset to insert the value at.
  22154. *
  22155. * @return this
  22156. */
  22157. insertFloatLE(value, offset) {
  22158. return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset);
  22159. }
  22160. // Double Floating Point
  22161. /**
  22162. * Reads an DoublEBE value from the current read position or an optionally provided offset.
  22163. *
  22164. * @param offset { Number } The offset to read data from (optional)
  22165. * @return { Number }
  22166. */
  22167. readDoubleBE(offset) {
  22168. return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset);
  22169. }
  22170. /**
  22171. * Reads an DoubleLE value from the current read position or an optionally provided offset.
  22172. *
  22173. * @param offset { Number } The offset to read data from (optional)
  22174. * @return { Number }
  22175. */
  22176. readDoubleLE(offset) {
  22177. return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset);
  22178. }
  22179. /**
  22180. * Writes a DoubleBE value to the current write position (or at optional offset).
  22181. *
  22182. * @param value { Number } The value to write.
  22183. * @param offset { Number } The offset to write the value at.
  22184. *
  22185. * @return this
  22186. */
  22187. writeDoubleBE(value, offset) {
  22188. return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset);
  22189. }
  22190. /**
  22191. * Inserts a DoubleBE value at the given offset value.
  22192. *
  22193. * @param value { Number } The value to insert.
  22194. * @param offset { Number } The offset to insert the value at.
  22195. *
  22196. * @return this
  22197. */
  22198. insertDoubleBE(value, offset) {
  22199. return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset);
  22200. }
  22201. /**
  22202. * Writes a DoubleLE value to the current write position (or at optional offset).
  22203. *
  22204. * @param value { Number } The value to write.
  22205. * @param offset { Number } The offset to write the value at.
  22206. *
  22207. * @return this
  22208. */
  22209. writeDoubleLE(value, offset) {
  22210. return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset);
  22211. }
  22212. /**
  22213. * Inserts a DoubleLE value at the given offset value.
  22214. *
  22215. * @param value { Number } The value to insert.
  22216. * @param offset { Number } The offset to insert the value at.
  22217. *
  22218. * @return this
  22219. */
  22220. insertDoubleLE(value, offset) {
  22221. return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset);
  22222. }
  22223. // Strings
  22224. /**
  22225. * Reads a String from the current read position.
  22226. *
  22227. * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for
  22228. * the string (Defaults to instance level encoding).
  22229. * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding).
  22230. *
  22231. * @return { String }
  22232. */
  22233. readString(arg1, encoding) {
  22234. let lengthVal;
  22235. if (typeof arg1 === "number") {
  22236. utils_1.checkLengthValue(arg1);
  22237. lengthVal = Math.min(arg1, this.length - this._readOffset);
  22238. } else {
  22239. encoding = arg1;
  22240. lengthVal = this.length - this._readOffset;
  22241. }
  22242. if (typeof encoding !== "undefined") {
  22243. utils_1.checkEncoding(encoding);
  22244. }
  22245. const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding);
  22246. this._readOffset += lengthVal;
  22247. return value;
  22248. }
  22249. /**
  22250. * Inserts a String
  22251. *
  22252. * @param value { String } The String value to insert.
  22253. * @param offset { Number } The offset to insert the string at.
  22254. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
  22255. *
  22256. * @return this
  22257. */
  22258. insertString(value, offset, encoding) {
  22259. utils_1.checkOffsetValue(offset);
  22260. return this._handleString(value, true, offset, encoding);
  22261. }
  22262. /**
  22263. * Writes a String
  22264. *
  22265. * @param value { String } The String value to write.
  22266. * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use.
  22267. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
  22268. *
  22269. * @return this
  22270. */
  22271. writeString(value, arg2, encoding) {
  22272. return this._handleString(value, false, arg2, encoding);
  22273. }
  22274. /**
  22275. * Reads a null-terminated String from the current read position.
  22276. *
  22277. * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding).
  22278. *
  22279. * @return { String }
  22280. */
  22281. readStringNT(encoding) {
  22282. if (typeof encoding !== "undefined") {
  22283. utils_1.checkEncoding(encoding);
  22284. }
  22285. let nullPos = this.length;
  22286. for (let i = this._readOffset; i < this.length; i++) {
  22287. if (this._buff[i] === 0) {
  22288. nullPos = i;
  22289. break;
  22290. }
  22291. }
  22292. const value = this._buff.slice(this._readOffset, nullPos);
  22293. this._readOffset = nullPos + 1;
  22294. return value.toString(encoding || this._encoding);
  22295. }
  22296. /**
  22297. * Inserts a null-terminated String.
  22298. *
  22299. * @param value { String } The String value to write.
  22300. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use.
  22301. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
  22302. *
  22303. * @return this
  22304. */
  22305. insertStringNT(value, offset, encoding) {
  22306. utils_1.checkOffsetValue(offset);
  22307. this.insertString(value, offset, encoding);
  22308. this.insertUInt8(0, offset + value.length);
  22309. return this;
  22310. }
  22311. /**
  22312. * Writes a null-terminated String.
  22313. *
  22314. * @param value { String } The String value to write.
  22315. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use.
  22316. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
  22317. *
  22318. * @return this
  22319. */
  22320. writeStringNT(value, arg2, encoding) {
  22321. this.writeString(value, arg2, encoding);
  22322. this.writeUInt8(0, typeof arg2 === "number" ? arg2 + value.length : this.writeOffset);
  22323. return this;
  22324. }
  22325. // Buffers
  22326. /**
  22327. * Reads a Buffer from the internal read position.
  22328. *
  22329. * @param length { Number } The length of data to read as a Buffer.
  22330. *
  22331. * @return { Buffer }
  22332. */
  22333. readBuffer(length) {
  22334. if (typeof length !== "undefined") {
  22335. utils_1.checkLengthValue(length);
  22336. }
  22337. const lengthVal = typeof length === "number" ? length : this.length;
  22338. const endPoint = Math.min(this.length, this._readOffset + lengthVal);
  22339. const value = this._buff.slice(this._readOffset, endPoint);
  22340. this._readOffset = endPoint;
  22341. return value;
  22342. }
  22343. /**
  22344. * Writes a Buffer to the current write position.
  22345. *
  22346. * @param value { Buffer } The Buffer to write.
  22347. * @param offset { Number } The offset to write the Buffer to.
  22348. *
  22349. * @return this
  22350. */
  22351. insertBuffer(value, offset) {
  22352. utils_1.checkOffsetValue(offset);
  22353. return this._handleBuffer(value, true, offset);
  22354. }
  22355. /**
  22356. * Writes a Buffer to the current write position.
  22357. *
  22358. * @param value { Buffer } The Buffer to write.
  22359. * @param offset { Number } The offset to write the Buffer to.
  22360. *
  22361. * @return this
  22362. */
  22363. writeBuffer(value, offset) {
  22364. return this._handleBuffer(value, false, offset);
  22365. }
  22366. /**
  22367. * Reads a null-terminated Buffer from the current read poisiton.
  22368. *
  22369. * @return { Buffer }
  22370. */
  22371. readBufferNT() {
  22372. let nullPos = this.length;
  22373. for (let i = this._readOffset; i < this.length; i++) {
  22374. if (this._buff[i] === 0) {
  22375. nullPos = i;
  22376. break;
  22377. }
  22378. }
  22379. const value = this._buff.slice(this._readOffset, nullPos);
  22380. this._readOffset = nullPos + 1;
  22381. return value;
  22382. }
  22383. /**
  22384. * Inserts a null-terminated Buffer.
  22385. *
  22386. * @param value { Buffer } The Buffer to write.
  22387. * @param offset { Number } The offset to write the Buffer to.
  22388. *
  22389. * @return this
  22390. */
  22391. insertBufferNT(value, offset) {
  22392. utils_1.checkOffsetValue(offset);
  22393. this.insertBuffer(value, offset);
  22394. this.insertUInt8(0, offset + value.length);
  22395. return this;
  22396. }
  22397. /**
  22398. * Writes a null-terminated Buffer.
  22399. *
  22400. * @param value { Buffer } The Buffer to write.
  22401. * @param offset { Number } The offset to write the Buffer to.
  22402. *
  22403. * @return this
  22404. */
  22405. writeBufferNT(value, offset) {
  22406. if (typeof offset !== "undefined") {
  22407. utils_1.checkOffsetValue(offset);
  22408. }
  22409. this.writeBuffer(value, offset);
  22410. this.writeUInt8(0, typeof offset === "number" ? offset + value.length : this._writeOffset);
  22411. return this;
  22412. }
  22413. /**
  22414. * Clears the SmartBuffer instance to its original empty state.
  22415. */
  22416. clear() {
  22417. this._writeOffset = 0;
  22418. this._readOffset = 0;
  22419. this.length = 0;
  22420. return this;
  22421. }
  22422. /**
  22423. * Gets the remaining data left to be read from the SmartBuffer instance.
  22424. *
  22425. * @return { Number }
  22426. */
  22427. remaining() {
  22428. return this.length - this._readOffset;
  22429. }
  22430. /**
  22431. * Gets the current read offset value of the SmartBuffer instance.
  22432. *
  22433. * @return { Number }
  22434. */
  22435. get readOffset() {
  22436. return this._readOffset;
  22437. }
  22438. /**
  22439. * Sets the read offset value of the SmartBuffer instance.
  22440. *
  22441. * @param offset { Number } - The offset value to set.
  22442. */
  22443. set readOffset(offset) {
  22444. utils_1.checkOffsetValue(offset);
  22445. utils_1.checkTargetOffset(offset, this);
  22446. this._readOffset = offset;
  22447. }
  22448. /**
  22449. * Gets the current write offset value of the SmartBuffer instance.
  22450. *
  22451. * @return { Number }
  22452. */
  22453. get writeOffset() {
  22454. return this._writeOffset;
  22455. }
  22456. /**
  22457. * Sets the write offset value of the SmartBuffer instance.
  22458. *
  22459. * @param offset { Number } - The offset value to set.
  22460. */
  22461. set writeOffset(offset) {
  22462. utils_1.checkOffsetValue(offset);
  22463. utils_1.checkTargetOffset(offset, this);
  22464. this._writeOffset = offset;
  22465. }
  22466. /**
  22467. * Gets the currently set string encoding of the SmartBuffer instance.
  22468. *
  22469. * @return { BufferEncoding } The string Buffer encoding currently set.
  22470. */
  22471. get encoding() {
  22472. return this._encoding;
  22473. }
  22474. /**
  22475. * Sets the string encoding of the SmartBuffer instance.
  22476. *
  22477. * @param encoding { BufferEncoding } The string Buffer encoding to set.
  22478. */
  22479. set encoding(encoding) {
  22480. utils_1.checkEncoding(encoding);
  22481. this._encoding = encoding;
  22482. }
  22483. /**
  22484. * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer)
  22485. *
  22486. * @return { Buffer } The Buffer value.
  22487. */
  22488. get internalBuffer() {
  22489. return this._buff;
  22490. }
  22491. /**
  22492. * Gets the value of the internal managed Buffer (Includes managed data only)
  22493. *
  22494. * @param { Buffer }
  22495. */
  22496. toBuffer() {
  22497. return this._buff.slice(0, this.length);
  22498. }
  22499. /**
  22500. * Gets the String value of the internal managed Buffer
  22501. *
  22502. * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding).
  22503. */
  22504. toString(encoding) {
  22505. const encodingVal = typeof encoding === "string" ? encoding : this._encoding;
  22506. utils_1.checkEncoding(encodingVal);
  22507. return this._buff.toString(encodingVal, 0, this.length);
  22508. }
  22509. /**
  22510. * Destroys the SmartBuffer instance.
  22511. */
  22512. destroy() {
  22513. this.clear();
  22514. return this;
  22515. }
  22516. /**
  22517. * Handles inserting and writing strings.
  22518. *
  22519. * @param value { String } The String value to insert.
  22520. * @param isInsert { Boolean } True if inserting a string, false if writing.
  22521. * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use.
  22522. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
  22523. */
  22524. _handleString(value, isInsert, arg3, encoding) {
  22525. let offsetVal = this._writeOffset;
  22526. let encodingVal = this._encoding;
  22527. if (typeof arg3 === "number") {
  22528. offsetVal = arg3;
  22529. } else if (typeof arg3 === "string") {
  22530. utils_1.checkEncoding(arg3);
  22531. encodingVal = arg3;
  22532. }
  22533. if (typeof encoding === "string") {
  22534. utils_1.checkEncoding(encoding);
  22535. encodingVal = encoding;
  22536. }
  22537. const byteLength = Buffer.byteLength(value, encodingVal);
  22538. if (isInsert) {
  22539. this.ensureInsertable(byteLength, offsetVal);
  22540. } else {
  22541. this._ensureWriteable(byteLength, offsetVal);
  22542. }
  22543. this._buff.write(value, offsetVal, byteLength, encodingVal);
  22544. if (isInsert) {
  22545. this._writeOffset += byteLength;
  22546. } else {
  22547. if (typeof arg3 === "number") {
  22548. this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength);
  22549. } else {
  22550. this._writeOffset += byteLength;
  22551. }
  22552. }
  22553. return this;
  22554. }
  22555. /**
  22556. * Handles writing or insert of a Buffer.
  22557. *
  22558. * @param value { Buffer } The Buffer to write.
  22559. * @param offset { Number } The offset to write the Buffer to.
  22560. */
  22561. _handleBuffer(value, isInsert, offset) {
  22562. const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
  22563. if (isInsert) {
  22564. this.ensureInsertable(value.length, offsetVal);
  22565. } else {
  22566. this._ensureWriteable(value.length, offsetVal);
  22567. }
  22568. value.copy(this._buff, offsetVal);
  22569. if (isInsert) {
  22570. this._writeOffset += value.length;
  22571. } else {
  22572. if (typeof offset === "number") {
  22573. this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length);
  22574. } else {
  22575. this._writeOffset += value.length;
  22576. }
  22577. }
  22578. return this;
  22579. }
  22580. /**
  22581. * Ensures that the internal Buffer is large enough to read data.
  22582. *
  22583. * @param length { Number } The length of the data that needs to be read.
  22584. * @param offset { Number } The offset of the data that needs to be read.
  22585. */
  22586. ensureReadable(length, offset) {
  22587. let offsetVal = this._readOffset;
  22588. if (typeof offset !== "undefined") {
  22589. utils_1.checkOffsetValue(offset);
  22590. offsetVal = offset;
  22591. }
  22592. if (offsetVal < 0 || offsetVal + length > this.length) {
  22593. throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS);
  22594. }
  22595. }
  22596. /**
  22597. * Ensures that the internal Buffer is large enough to insert data.
  22598. *
  22599. * @param dataLength { Number } The length of the data that needs to be written.
  22600. * @param offset { Number } The offset of the data to be written.
  22601. */
  22602. ensureInsertable(dataLength, offset) {
  22603. utils_1.checkOffsetValue(offset);
  22604. this._ensureCapacity(this.length + dataLength);
  22605. if (offset < this.length) {
  22606. this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length);
  22607. }
  22608. if (offset + dataLength > this.length) {
  22609. this.length = offset + dataLength;
  22610. } else {
  22611. this.length += dataLength;
  22612. }
  22613. }
  22614. /**
  22615. * Ensures that the internal Buffer is large enough to write data.
  22616. *
  22617. * @param dataLength { Number } The length of the data that needs to be written.
  22618. * @param offset { Number } The offset of the data to be written (defaults to writeOffset).
  22619. */
  22620. _ensureWriteable(dataLength, offset) {
  22621. const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
  22622. this._ensureCapacity(offsetVal + dataLength);
  22623. if (offsetVal + dataLength > this.length) {
  22624. this.length = offsetVal + dataLength;
  22625. }
  22626. }
  22627. /**
  22628. * Ensures that the internal Buffer is large enough to write at least the given amount of data.
  22629. *
  22630. * @param minLength { Number } The minimum length of the data needs to be written.
  22631. */
  22632. _ensureCapacity(minLength) {
  22633. const oldLength = this._buff.length;
  22634. if (minLength > oldLength) {
  22635. let data = this._buff;
  22636. let newLength = oldLength * 3 / 2 + 1;
  22637. if (newLength < minLength) {
  22638. newLength = minLength;
  22639. }
  22640. this._buff = Buffer.allocUnsafe(newLength);
  22641. data.copy(this._buff, 0, 0, oldLength);
  22642. }
  22643. }
  22644. /**
  22645. * Reads a numeric number value using the provided function.
  22646. *
  22647. * @typeparam T { number | bigint } The type of the value to be read
  22648. *
  22649. * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with.
  22650. * @param byteSize { Number } The number of bytes read.
  22651. * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead.
  22652. *
  22653. * @returns { T } the number value
  22654. */
  22655. _readNumberValue(func, byteSize, offset) {
  22656. this.ensureReadable(byteSize, offset);
  22657. const value = func.call(this._buff, typeof offset === "number" ? offset : this._readOffset);
  22658. if (typeof offset === "undefined") {
  22659. this._readOffset += byteSize;
  22660. }
  22661. return value;
  22662. }
  22663. /**
  22664. * Inserts a numeric number value based on the given offset and value.
  22665. *
  22666. * @typeparam T { number | bigint } The type of the value to be written
  22667. *
  22668. * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with.
  22669. * @param byteSize { Number } The number of bytes written.
  22670. * @param value { T } The number value to write.
  22671. * @param offset { Number } the offset to write the number at (REQUIRED).
  22672. *
  22673. * @returns SmartBuffer this buffer
  22674. */
  22675. _insertNumberValue(func, byteSize, value, offset) {
  22676. utils_1.checkOffsetValue(offset);
  22677. this.ensureInsertable(byteSize, offset);
  22678. func.call(this._buff, value, offset);
  22679. this._writeOffset += byteSize;
  22680. return this;
  22681. }
  22682. /**
  22683. * Writes a numeric number value based on the given offset and value.
  22684. *
  22685. * @typeparam T { number | bigint } The type of the value to be written
  22686. *
  22687. * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with.
  22688. * @param byteSize { Number } The number of bytes written.
  22689. * @param value { T } The number value to write.
  22690. * @param offset { Number } the offset to write the number at (REQUIRED).
  22691. *
  22692. * @returns SmartBuffer this buffer
  22693. */
  22694. _writeNumberValue(func, byteSize, value, offset) {
  22695. if (typeof offset === "number") {
  22696. if (offset < 0) {
  22697. throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);
  22698. }
  22699. utils_1.checkOffsetValue(offset);
  22700. }
  22701. const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
  22702. this._ensureWriteable(byteSize, offsetVal);
  22703. func.call(this._buff, value, offsetVal);
  22704. if (typeof offset === "number") {
  22705. this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize);
  22706. } else {
  22707. this._writeOffset += byteSize;
  22708. }
  22709. return this;
  22710. }
  22711. };
  22712. __name(_SmartBuffer, "SmartBuffer");
  22713. var SmartBuffer = _SmartBuffer;
  22714. exports2.SmartBuffer = SmartBuffer;
  22715. }
  22716. });
  22717. // node_modules/socks/build/common/constants.js
  22718. var require_constants3 = __commonJS({
  22719. "node_modules/socks/build/common/constants.js"(exports2) {
  22720. "use strict";
  22721. Object.defineProperty(exports2, "__esModule", { value: true });
  22722. exports2.SOCKS5_NO_ACCEPTABLE_AUTH = exports2.SOCKS5_CUSTOM_AUTH_END = exports2.SOCKS5_CUSTOM_AUTH_START = exports2.SOCKS_INCOMING_PACKET_SIZES = exports2.SocksClientState = exports2.Socks5Response = exports2.Socks5HostType = exports2.Socks5Auth = exports2.Socks4Response = exports2.SocksCommand = exports2.ERRORS = exports2.DEFAULT_TIMEOUT = void 0;
  22723. var DEFAULT_TIMEOUT = 3e4;
  22724. exports2.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
  22725. var ERRORS = {
  22726. InvalidSocksCommand: "An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",
  22727. InvalidSocksCommandForOperation: "An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",
  22728. InvalidSocksCommandChain: "An invalid SOCKS command was provided. Chaining currently only supports the connect command.",
  22729. InvalidSocksClientOptionsDestination: "An invalid destination host was provided.",
  22730. InvalidSocksClientOptionsExistingSocket: "An invalid existing socket was provided. This should be an instance of stream.Duplex.",
  22731. InvalidSocksClientOptionsProxy: "Invalid SOCKS proxy details were provided.",
  22732. InvalidSocksClientOptionsTimeout: "An invalid timeout value was provided. Please enter a value above 0 (in ms).",
  22733. InvalidSocksClientOptionsProxiesLength: "At least two socks proxies must be provided for chaining.",
  22734. InvalidSocksClientOptionsCustomAuthRange: "Custom auth must be a value between 0x80 and 0xFE.",
  22735. InvalidSocksClientOptionsCustomAuthOptions: "When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",
  22736. NegotiationError: "Negotiation error",
  22737. SocketClosed: "Socket closed",
  22738. ProxyConnectionTimedOut: "Proxy connection timed out",
  22739. InternalError: "SocksClient internal error (this should not happen)",
  22740. InvalidSocks4HandshakeResponse: "Received invalid Socks4 handshake response",
  22741. Socks4ProxyRejectedConnection: "Socks4 Proxy rejected connection",
  22742. InvalidSocks4IncomingConnectionResponse: "Socks4 invalid incoming connection response",
  22743. Socks4ProxyRejectedIncomingBoundConnection: "Socks4 Proxy rejected incoming bound connection",
  22744. InvalidSocks5InitialHandshakeResponse: "Received invalid Socks5 initial handshake response",
  22745. InvalidSocks5IntiailHandshakeSocksVersion: "Received invalid Socks5 initial handshake (invalid socks version)",
  22746. InvalidSocks5InitialHandshakeNoAcceptedAuthType: "Received invalid Socks5 initial handshake (no accepted authentication type)",
  22747. InvalidSocks5InitialHandshakeUnknownAuthType: "Received invalid Socks5 initial handshake (unknown authentication type)",
  22748. Socks5AuthenticationFailed: "Socks5 Authentication failed",
  22749. InvalidSocks5FinalHandshake: "Received invalid Socks5 final handshake response",
  22750. InvalidSocks5FinalHandshakeRejected: "Socks5 proxy rejected connection",
  22751. InvalidSocks5IncomingConnectionResponse: "Received invalid Socks5 incoming connection response",
  22752. Socks5ProxyRejectedIncomingBoundConnection: "Socks5 Proxy rejected incoming bound connection"
  22753. };
  22754. exports2.ERRORS = ERRORS;
  22755. var SOCKS_INCOMING_PACKET_SIZES = {
  22756. Socks5InitialHandshakeResponse: 2,
  22757. Socks5UserPassAuthenticationResponse: 2,
  22758. // Command response + incoming connection (bind)
  22759. Socks5ResponseHeader: 5,
  22760. // We need at least 5 to read the hostname length, then we wait for the address+port information.
  22761. Socks5ResponseIPv4: 10,
  22762. // 4 header + 4 ip + 2 port
  22763. Socks5ResponseIPv6: 22,
  22764. // 4 header + 16 ip + 2 port
  22765. Socks5ResponseHostname: /* @__PURE__ */ __name((hostNameLength) => hostNameLength + 7, "Socks5ResponseHostname"),
  22766. // 4 header + 1 host length + host + 2 port
  22767. // Command response + incoming connection (bind)
  22768. Socks4Response: 8
  22769. // 2 header + 2 port + 4 ip
  22770. };
  22771. exports2.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES;
  22772. var SocksCommand;
  22773. (function(SocksCommand2) {
  22774. SocksCommand2[SocksCommand2["connect"] = 1] = "connect";
  22775. SocksCommand2[SocksCommand2["bind"] = 2] = "bind";
  22776. SocksCommand2[SocksCommand2["associate"] = 3] = "associate";
  22777. })(SocksCommand || (exports2.SocksCommand = SocksCommand = {}));
  22778. var Socks4Response;
  22779. (function(Socks4Response2) {
  22780. Socks4Response2[Socks4Response2["Granted"] = 90] = "Granted";
  22781. Socks4Response2[Socks4Response2["Failed"] = 91] = "Failed";
  22782. Socks4Response2[Socks4Response2["Rejected"] = 92] = "Rejected";
  22783. Socks4Response2[Socks4Response2["RejectedIdent"] = 93] = "RejectedIdent";
  22784. })(Socks4Response || (exports2.Socks4Response = Socks4Response = {}));
  22785. var Socks5Auth;
  22786. (function(Socks5Auth2) {
  22787. Socks5Auth2[Socks5Auth2["NoAuth"] = 0] = "NoAuth";
  22788. Socks5Auth2[Socks5Auth2["GSSApi"] = 1] = "GSSApi";
  22789. Socks5Auth2[Socks5Auth2["UserPass"] = 2] = "UserPass";
  22790. })(Socks5Auth || (exports2.Socks5Auth = Socks5Auth = {}));
  22791. var SOCKS5_CUSTOM_AUTH_START = 128;
  22792. exports2.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START;
  22793. var SOCKS5_CUSTOM_AUTH_END = 254;
  22794. exports2.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END;
  22795. var SOCKS5_NO_ACCEPTABLE_AUTH = 255;
  22796. exports2.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH;
  22797. var Socks5Response;
  22798. (function(Socks5Response2) {
  22799. Socks5Response2[Socks5Response2["Granted"] = 0] = "Granted";
  22800. Socks5Response2[Socks5Response2["Failure"] = 1] = "Failure";
  22801. Socks5Response2[Socks5Response2["NotAllowed"] = 2] = "NotAllowed";
  22802. Socks5Response2[Socks5Response2["NetworkUnreachable"] = 3] = "NetworkUnreachable";
  22803. Socks5Response2[Socks5Response2["HostUnreachable"] = 4] = "HostUnreachable";
  22804. Socks5Response2[Socks5Response2["ConnectionRefused"] = 5] = "ConnectionRefused";
  22805. Socks5Response2[Socks5Response2["TTLExpired"] = 6] = "TTLExpired";
  22806. Socks5Response2[Socks5Response2["CommandNotSupported"] = 7] = "CommandNotSupported";
  22807. Socks5Response2[Socks5Response2["AddressNotSupported"] = 8] = "AddressNotSupported";
  22808. })(Socks5Response || (exports2.Socks5Response = Socks5Response = {}));
  22809. var Socks5HostType;
  22810. (function(Socks5HostType2) {
  22811. Socks5HostType2[Socks5HostType2["IPv4"] = 1] = "IPv4";
  22812. Socks5HostType2[Socks5HostType2["Hostname"] = 3] = "Hostname";
  22813. Socks5HostType2[Socks5HostType2["IPv6"] = 4] = "IPv6";
  22814. })(Socks5HostType || (exports2.Socks5HostType = Socks5HostType = {}));
  22815. var SocksClientState;
  22816. (function(SocksClientState2) {
  22817. SocksClientState2[SocksClientState2["Created"] = 0] = "Created";
  22818. SocksClientState2[SocksClientState2["Connecting"] = 1] = "Connecting";
  22819. SocksClientState2[SocksClientState2["Connected"] = 2] = "Connected";
  22820. SocksClientState2[SocksClientState2["SentInitialHandshake"] = 3] = "SentInitialHandshake";
  22821. SocksClientState2[SocksClientState2["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse";
  22822. SocksClientState2[SocksClientState2["SentAuthentication"] = 5] = "SentAuthentication";
  22823. SocksClientState2[SocksClientState2["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse";
  22824. SocksClientState2[SocksClientState2["SentFinalHandshake"] = 7] = "SentFinalHandshake";
  22825. SocksClientState2[SocksClientState2["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse";
  22826. SocksClientState2[SocksClientState2["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection";
  22827. SocksClientState2[SocksClientState2["Established"] = 10] = "Established";
  22828. SocksClientState2[SocksClientState2["Disconnected"] = 11] = "Disconnected";
  22829. SocksClientState2[SocksClientState2["Error"] = 99] = "Error";
  22830. })(SocksClientState || (exports2.SocksClientState = SocksClientState = {}));
  22831. }
  22832. });
  22833. // node_modules/socks/build/common/util.js
  22834. var require_util = __commonJS({
  22835. "node_modules/socks/build/common/util.js"(exports2) {
  22836. "use strict";
  22837. Object.defineProperty(exports2, "__esModule", { value: true });
  22838. exports2.shuffleArray = exports2.SocksClientError = void 0;
  22839. var _SocksClientError = class _SocksClientError extends Error {
  22840. constructor(message, options) {
  22841. super(message);
  22842. this.options = options;
  22843. }
  22844. };
  22845. __name(_SocksClientError, "SocksClientError");
  22846. var SocksClientError = _SocksClientError;
  22847. exports2.SocksClientError = SocksClientError;
  22848. function shuffleArray(array) {
  22849. for (let i = array.length - 1; i > 0; i--) {
  22850. const j = Math.floor(Math.random() * (i + 1));
  22851. [array[i], array[j]] = [array[j], array[i]];
  22852. }
  22853. }
  22854. __name(shuffleArray, "shuffleArray");
  22855. exports2.shuffleArray = shuffleArray;
  22856. }
  22857. });
  22858. // node_modules/ip-address/dist/common.js
  22859. var require_common3 = __commonJS({
  22860. "node_modules/ip-address/dist/common.js"(exports2) {
  22861. "use strict";
  22862. Object.defineProperty(exports2, "__esModule", { value: true });
  22863. exports2.isCorrect = exports2.isInSubnet = void 0;
  22864. function isInSubnet(address) {
  22865. if (this.subnetMask < address.subnetMask) {
  22866. return false;
  22867. }
  22868. if (this.mask(address.subnetMask) === address.mask()) {
  22869. return true;
  22870. }
  22871. return false;
  22872. }
  22873. __name(isInSubnet, "isInSubnet");
  22874. exports2.isInSubnet = isInSubnet;
  22875. function isCorrect(defaultBits) {
  22876. return function() {
  22877. if (this.addressMinusSuffix !== this.correctForm()) {
  22878. return false;
  22879. }
  22880. if (this.subnetMask === defaultBits && !this.parsedSubnet) {
  22881. return true;
  22882. }
  22883. return this.parsedSubnet === String(this.subnetMask);
  22884. };
  22885. }
  22886. __name(isCorrect, "isCorrect");
  22887. exports2.isCorrect = isCorrect;
  22888. }
  22889. });
  22890. // node_modules/ip-address/dist/v4/constants.js
  22891. var require_constants4 = __commonJS({
  22892. "node_modules/ip-address/dist/v4/constants.js"(exports2) {
  22893. "use strict";
  22894. Object.defineProperty(exports2, "__esModule", { value: true });
  22895. exports2.RE_SUBNET_STRING = exports2.RE_ADDRESS = exports2.GROUPS = exports2.BITS = void 0;
  22896. exports2.BITS = 32;
  22897. exports2.GROUPS = 4;
  22898. exports2.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;
  22899. exports2.RE_SUBNET_STRING = /\/\d{1,2}$/;
  22900. }
  22901. });
  22902. // node_modules/ip-address/dist/address-error.js
  22903. var require_address_error = __commonJS({
  22904. "node_modules/ip-address/dist/address-error.js"(exports2) {
  22905. "use strict";
  22906. Object.defineProperty(exports2, "__esModule", { value: true });
  22907. exports2.AddressError = void 0;
  22908. var _AddressError = class _AddressError extends Error {
  22909. constructor(message, parseMessage) {
  22910. super(message);
  22911. this.name = "AddressError";
  22912. if (parseMessage !== null) {
  22913. this.parseMessage = parseMessage;
  22914. }
  22915. }
  22916. };
  22917. __name(_AddressError, "AddressError");
  22918. var AddressError = _AddressError;
  22919. exports2.AddressError = AddressError;
  22920. }
  22921. });
  22922. // node_modules/jsbn/index.js
  22923. var require_jsbn = __commonJS({
  22924. "node_modules/jsbn/index.js"(exports2, module2) {
  22925. (function() {
  22926. var dbits;
  22927. var canary = 244837814094590;
  22928. var j_lm = (canary & 16777215) == 15715070;
  22929. function BigInteger(a, b, c) {
  22930. if (a != null)
  22931. if ("number" == typeof a) this.fromNumber(a, b, c);
  22932. else if (b == null && "string" != typeof a) this.fromString(a, 256);
  22933. else this.fromString(a, b);
  22934. }
  22935. __name(BigInteger, "BigInteger");
  22936. function nbi() {
  22937. return new BigInteger(null);
  22938. }
  22939. __name(nbi, "nbi");
  22940. function am1(i, x, w, j, c, n) {
  22941. while (--n >= 0) {
  22942. var v = x * this[i++] + w[j] + c;
  22943. c = Math.floor(v / 67108864);
  22944. w[j++] = v & 67108863;
  22945. }
  22946. return c;
  22947. }
  22948. __name(am1, "am1");
  22949. function am2(i, x, w, j, c, n) {
  22950. var xl = x & 32767, xh = x >> 15;
  22951. while (--n >= 0) {
  22952. var l = this[i] & 32767;
  22953. var h = this[i++] >> 15;
  22954. var m = xh * l + h * xl;
  22955. l = xl * l + ((m & 32767) << 15) + w[j] + (c & 1073741823);
  22956. c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
  22957. w[j++] = l & 1073741823;
  22958. }
  22959. return c;
  22960. }
  22961. __name(am2, "am2");
  22962. function am3(i, x, w, j, c, n) {
  22963. var xl = x & 16383, xh = x >> 14;
  22964. while (--n >= 0) {
  22965. var l = this[i] & 16383;
  22966. var h = this[i++] >> 14;
  22967. var m = xh * l + h * xl;
  22968. l = xl * l + ((m & 16383) << 14) + w[j] + c;
  22969. c = (l >> 28) + (m >> 14) + xh * h;
  22970. w[j++] = l & 268435455;
  22971. }
  22972. return c;
  22973. }
  22974. __name(am3, "am3");
  22975. var inBrowser = typeof navigator !== "undefined";
  22976. if (inBrowser && j_lm && navigator.appName == "Microsoft Internet Explorer") {
  22977. BigInteger.prototype.am = am2;
  22978. dbits = 30;
  22979. } else if (inBrowser && j_lm && navigator.appName != "Netscape") {
  22980. BigInteger.prototype.am = am1;
  22981. dbits = 26;
  22982. } else {
  22983. BigInteger.prototype.am = am3;
  22984. dbits = 28;
  22985. }
  22986. BigInteger.prototype.DB = dbits;
  22987. BigInteger.prototype.DM = (1 << dbits) - 1;
  22988. BigInteger.prototype.DV = 1 << dbits;
  22989. var BI_FP = 52;
  22990. BigInteger.prototype.FV = Math.pow(2, BI_FP);
  22991. BigInteger.prototype.F1 = BI_FP - dbits;
  22992. BigInteger.prototype.F2 = 2 * dbits - BI_FP;
  22993. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  22994. var BI_RC = new Array();
  22995. var rr, vv;
  22996. rr = "0".charCodeAt(0);
  22997. for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
  22998. rr = "a".charCodeAt(0);
  22999. for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  23000. rr = "A".charCodeAt(0);
  23001. for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  23002. function int2char(n) {
  23003. return BI_RM.charAt(n);
  23004. }
  23005. __name(int2char, "int2char");
  23006. function intAt(s, i) {
  23007. var c = BI_RC[s.charCodeAt(i)];
  23008. return c == null ? -1 : c;
  23009. }
  23010. __name(intAt, "intAt");
  23011. function bnpCopyTo(r) {
  23012. for (var i = this.t - 1; i >= 0; --i) r[i] = this[i];
  23013. r.t = this.t;
  23014. r.s = this.s;
  23015. }
  23016. __name(bnpCopyTo, "bnpCopyTo");
  23017. function bnpFromInt(x) {
  23018. this.t = 1;
  23019. this.s = x < 0 ? -1 : 0;
  23020. if (x > 0) this[0] = x;
  23021. else if (x < -1) this[0] = x + this.DV;
  23022. else this.t = 0;
  23023. }
  23024. __name(bnpFromInt, "bnpFromInt");
  23025. function nbv(i) {
  23026. var r = nbi();
  23027. r.fromInt(i);
  23028. return r;
  23029. }
  23030. __name(nbv, "nbv");
  23031. function bnpFromString(s, b) {
  23032. var k;
  23033. if (b == 16) k = 4;
  23034. else if (b == 8) k = 3;
  23035. else if (b == 256) k = 8;
  23036. else if (b == 2) k = 1;
  23037. else if (b == 32) k = 5;
  23038. else if (b == 4) k = 2;
  23039. else {
  23040. this.fromRadix(s, b);
  23041. return;
  23042. }
  23043. this.t = 0;
  23044. this.s = 0;
  23045. var i = s.length, mi = false, sh = 0;
  23046. while (--i >= 0) {
  23047. var x = k == 8 ? s[i] & 255 : intAt(s, i);
  23048. if (x < 0) {
  23049. if (s.charAt(i) == "-") mi = true;
  23050. continue;
  23051. }
  23052. mi = false;
  23053. if (sh == 0)
  23054. this[this.t++] = x;
  23055. else if (sh + k > this.DB) {
  23056. this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh;
  23057. this[this.t++] = x >> this.DB - sh;
  23058. } else
  23059. this[this.t - 1] |= x << sh;
  23060. sh += k;
  23061. if (sh >= this.DB) sh -= this.DB;
  23062. }
  23063. if (k == 8 && (s[0] & 128) != 0) {
  23064. this.s = -1;
  23065. if (sh > 0) this[this.t - 1] |= (1 << this.DB - sh) - 1 << sh;
  23066. }
  23067. this.clamp();
  23068. if (mi) BigInteger.ZERO.subTo(this, this);
  23069. }
  23070. __name(bnpFromString, "bnpFromString");
  23071. function bnpClamp() {
  23072. var c = this.s & this.DM;
  23073. while (this.t > 0 && this[this.t - 1] == c) --this.t;
  23074. }
  23075. __name(bnpClamp, "bnpClamp");
  23076. function bnToString(b) {
  23077. if (this.s < 0) return "-" + this.negate().toString(b);
  23078. var k;
  23079. if (b == 16) k = 4;
  23080. else if (b == 8) k = 3;
  23081. else if (b == 2) k = 1;
  23082. else if (b == 32) k = 5;
  23083. else if (b == 4) k = 2;
  23084. else return this.toRadix(b);
  23085. var km = (1 << k) - 1, d, m = false, r = "", i = this.t;
  23086. var p = this.DB - i * this.DB % k;
  23087. if (i-- > 0) {
  23088. if (p < this.DB && (d = this[i] >> p) > 0) {
  23089. m = true;
  23090. r = int2char(d);
  23091. }
  23092. while (i >= 0) {
  23093. if (p < k) {
  23094. d = (this[i] & (1 << p) - 1) << k - p;
  23095. d |= this[--i] >> (p += this.DB - k);
  23096. } else {
  23097. d = this[i] >> (p -= k) & km;
  23098. if (p <= 0) {
  23099. p += this.DB;
  23100. --i;
  23101. }
  23102. }
  23103. if (d > 0) m = true;
  23104. if (m) r += int2char(d);
  23105. }
  23106. }
  23107. return m ? r : "0";
  23108. }
  23109. __name(bnToString, "bnToString");
  23110. function bnNegate() {
  23111. var r = nbi();
  23112. BigInteger.ZERO.subTo(this, r);
  23113. return r;
  23114. }
  23115. __name(bnNegate, "bnNegate");
  23116. function bnAbs() {
  23117. return this.s < 0 ? this.negate() : this;
  23118. }
  23119. __name(bnAbs, "bnAbs");
  23120. function bnCompareTo(a) {
  23121. var r = this.s - a.s;
  23122. if (r != 0) return r;
  23123. var i = this.t;
  23124. r = i - a.t;
  23125. if (r != 0) return this.s < 0 ? -r : r;
  23126. while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r;
  23127. return 0;
  23128. }
  23129. __name(bnCompareTo, "bnCompareTo");
  23130. function nbits(x) {
  23131. var r = 1, t2;
  23132. if ((t2 = x >>> 16) != 0) {
  23133. x = t2;
  23134. r += 16;
  23135. }
  23136. if ((t2 = x >> 8) != 0) {
  23137. x = t2;
  23138. r += 8;
  23139. }
  23140. if ((t2 = x >> 4) != 0) {
  23141. x = t2;
  23142. r += 4;
  23143. }
  23144. if ((t2 = x >> 2) != 0) {
  23145. x = t2;
  23146. r += 2;
  23147. }
  23148. if ((t2 = x >> 1) != 0) {
  23149. x = t2;
  23150. r += 1;
  23151. }
  23152. return r;
  23153. }
  23154. __name(nbits, "nbits");
  23155. function bnBitLength() {
  23156. if (this.t <= 0) return 0;
  23157. return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM);
  23158. }
  23159. __name(bnBitLength, "bnBitLength");
  23160. function bnpDLShiftTo(n, r) {
  23161. var i;
  23162. for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i];
  23163. for (i = n - 1; i >= 0; --i) r[i] = 0;
  23164. r.t = this.t + n;
  23165. r.s = this.s;
  23166. }
  23167. __name(bnpDLShiftTo, "bnpDLShiftTo");
  23168. function bnpDRShiftTo(n, r) {
  23169. for (var i = n; i < this.t; ++i) r[i - n] = this[i];
  23170. r.t = Math.max(this.t - n, 0);
  23171. r.s = this.s;
  23172. }
  23173. __name(bnpDRShiftTo, "bnpDRShiftTo");
  23174. function bnpLShiftTo(n, r) {
  23175. var bs = n % this.DB;
  23176. var cbs = this.DB - bs;
  23177. var bm = (1 << cbs) - 1;
  23178. var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i;
  23179. for (i = this.t - 1; i >= 0; --i) {
  23180. r[i + ds + 1] = this[i] >> cbs | c;
  23181. c = (this[i] & bm) << bs;
  23182. }
  23183. for (i = ds - 1; i >= 0; --i) r[i] = 0;
  23184. r[ds] = c;
  23185. r.t = this.t + ds + 1;
  23186. r.s = this.s;
  23187. r.clamp();
  23188. }
  23189. __name(bnpLShiftTo, "bnpLShiftTo");
  23190. function bnpRShiftTo(n, r) {
  23191. r.s = this.s;
  23192. var ds = Math.floor(n / this.DB);
  23193. if (ds >= this.t) {
  23194. r.t = 0;
  23195. return;
  23196. }
  23197. var bs = n % this.DB;
  23198. var cbs = this.DB - bs;
  23199. var bm = (1 << bs) - 1;
  23200. r[0] = this[ds] >> bs;
  23201. for (var i = ds + 1; i < this.t; ++i) {
  23202. r[i - ds - 1] |= (this[i] & bm) << cbs;
  23203. r[i - ds] = this[i] >> bs;
  23204. }
  23205. if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs;
  23206. r.t = this.t - ds;
  23207. r.clamp();
  23208. }
  23209. __name(bnpRShiftTo, "bnpRShiftTo");
  23210. function bnpSubTo(a, r) {
  23211. var i = 0, c = 0, m = Math.min(a.t, this.t);
  23212. while (i < m) {
  23213. c += this[i] - a[i];
  23214. r[i++] = c & this.DM;
  23215. c >>= this.DB;
  23216. }
  23217. if (a.t < this.t) {
  23218. c -= a.s;
  23219. while (i < this.t) {
  23220. c += this[i];
  23221. r[i++] = c & this.DM;
  23222. c >>= this.DB;
  23223. }
  23224. c += this.s;
  23225. } else {
  23226. c += this.s;
  23227. while (i < a.t) {
  23228. c -= a[i];
  23229. r[i++] = c & this.DM;
  23230. c >>= this.DB;
  23231. }
  23232. c -= a.s;
  23233. }
  23234. r.s = c < 0 ? -1 : 0;
  23235. if (c < -1) r[i++] = this.DV + c;
  23236. else if (c > 0) r[i++] = c;
  23237. r.t = i;
  23238. r.clamp();
  23239. }
  23240. __name(bnpSubTo, "bnpSubTo");
  23241. function bnpMultiplyTo(a, r) {
  23242. var x = this.abs(), y = a.abs();
  23243. var i = x.t;
  23244. r.t = i + y.t;
  23245. while (--i >= 0) r[i] = 0;
  23246. for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
  23247. r.s = 0;
  23248. r.clamp();
  23249. if (this.s != a.s) BigInteger.ZERO.subTo(r, r);
  23250. }
  23251. __name(bnpMultiplyTo, "bnpMultiplyTo");
  23252. function bnpSquareTo(r) {
  23253. var x = this.abs();
  23254. var i = r.t = 2 * x.t;
  23255. while (--i >= 0) r[i] = 0;
  23256. for (i = 0; i < x.t - 1; ++i) {
  23257. var c = x.am(i, x[i], r, 2 * i, 0, 1);
  23258. if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
  23259. r[i + x.t] -= x.DV;
  23260. r[i + x.t + 1] = 1;
  23261. }
  23262. }
  23263. if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
  23264. r.s = 0;
  23265. r.clamp();
  23266. }
  23267. __name(bnpSquareTo, "bnpSquareTo");
  23268. function bnpDivRemTo(m, q, r) {
  23269. var pm = m.abs();
  23270. if (pm.t <= 0) return;
  23271. var pt = this.abs();
  23272. if (pt.t < pm.t) {
  23273. if (q != null) q.fromInt(0);
  23274. if (r != null) this.copyTo(r);
  23275. return;
  23276. }
  23277. if (r == null) r = nbi();
  23278. var y = nbi(), ts = this.s, ms = m.s;
  23279. var nsh = this.DB - nbits(pm[pm.t - 1]);
  23280. if (nsh > 0) {
  23281. pm.lShiftTo(nsh, y);
  23282. pt.lShiftTo(nsh, r);
  23283. } else {
  23284. pm.copyTo(y);
  23285. pt.copyTo(r);
  23286. }
  23287. var ys = y.t;
  23288. var y0 = y[ys - 1];
  23289. if (y0 == 0) return;
  23290. var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0);
  23291. var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2;
  23292. var i = r.t, j = i - ys, t2 = q == null ? nbi() : q;
  23293. y.dlShiftTo(j, t2);
  23294. if (r.compareTo(t2) >= 0) {
  23295. r[r.t++] = 1;
  23296. r.subTo(t2, r);
  23297. }
  23298. BigInteger.ONE.dlShiftTo(ys, t2);
  23299. t2.subTo(y, y);
  23300. while (y.t < ys) y[y.t++] = 0;
  23301. while (--j >= 0) {
  23302. var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
  23303. if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {
  23304. y.dlShiftTo(j, t2);
  23305. r.subTo(t2, r);
  23306. while (r[i] < --qd) r.subTo(t2, r);
  23307. }
  23308. }
  23309. if (q != null) {
  23310. r.drShiftTo(ys, q);
  23311. if (ts != ms) BigInteger.ZERO.subTo(q, q);
  23312. }
  23313. r.t = ys;
  23314. r.clamp();
  23315. if (nsh > 0) r.rShiftTo(nsh, r);
  23316. if (ts < 0) BigInteger.ZERO.subTo(r, r);
  23317. }
  23318. __name(bnpDivRemTo, "bnpDivRemTo");
  23319. function bnMod(a) {
  23320. var r = nbi();
  23321. this.abs().divRemTo(a, null, r);
  23322. if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r);
  23323. return r;
  23324. }
  23325. __name(bnMod, "bnMod");
  23326. function Classic(m) {
  23327. this.m = m;
  23328. }
  23329. __name(Classic, "Classic");
  23330. function cConvert(x) {
  23331. if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
  23332. else return x;
  23333. }
  23334. __name(cConvert, "cConvert");
  23335. function cRevert(x) {
  23336. return x;
  23337. }
  23338. __name(cRevert, "cRevert");
  23339. function cReduce(x) {
  23340. x.divRemTo(this.m, null, x);
  23341. }
  23342. __name(cReduce, "cReduce");
  23343. function cMulTo(x, y, r) {
  23344. x.multiplyTo(y, r);
  23345. this.reduce(r);
  23346. }
  23347. __name(cMulTo, "cMulTo");
  23348. function cSqrTo(x, r) {
  23349. x.squareTo(r);
  23350. this.reduce(r);
  23351. }
  23352. __name(cSqrTo, "cSqrTo");
  23353. Classic.prototype.convert = cConvert;
  23354. Classic.prototype.revert = cRevert;
  23355. Classic.prototype.reduce = cReduce;
  23356. Classic.prototype.mulTo = cMulTo;
  23357. Classic.prototype.sqrTo = cSqrTo;
  23358. function bnpInvDigit() {
  23359. if (this.t < 1) return 0;
  23360. var x = this[0];
  23361. if ((x & 1) == 0) return 0;
  23362. var y = x & 3;
  23363. y = y * (2 - (x & 15) * y) & 15;
  23364. y = y * (2 - (x & 255) * y) & 255;
  23365. y = y * (2 - ((x & 65535) * y & 65535)) & 65535;
  23366. y = y * (2 - x * y % this.DV) % this.DV;
  23367. return y > 0 ? this.DV - y : -y;
  23368. }
  23369. __name(bnpInvDigit, "bnpInvDigit");
  23370. function Montgomery(m) {
  23371. this.m = m;
  23372. this.mp = m.invDigit();
  23373. this.mpl = this.mp & 32767;
  23374. this.mph = this.mp >> 15;
  23375. this.um = (1 << m.DB - 15) - 1;
  23376. this.mt2 = 2 * m.t;
  23377. }
  23378. __name(Montgomery, "Montgomery");
  23379. function montConvert(x) {
  23380. var r = nbi();
  23381. x.abs().dlShiftTo(this.m.t, r);
  23382. r.divRemTo(this.m, null, r);
  23383. if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r);
  23384. return r;
  23385. }
  23386. __name(montConvert, "montConvert");
  23387. function montRevert(x) {
  23388. var r = nbi();
  23389. x.copyTo(r);
  23390. this.reduce(r);
  23391. return r;
  23392. }
  23393. __name(montRevert, "montRevert");
  23394. function montReduce(x) {
  23395. while (x.t <= this.mt2)
  23396. x[x.t++] = 0;
  23397. for (var i = 0; i < this.m.t; ++i) {
  23398. var j = x[i] & 32767;
  23399. var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM;
  23400. j = i + this.m.t;
  23401. x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
  23402. while (x[j] >= x.DV) {
  23403. x[j] -= x.DV;
  23404. x[++j]++;
  23405. }
  23406. }
  23407. x.clamp();
  23408. x.drShiftTo(this.m.t, x);
  23409. if (x.compareTo(this.m) >= 0) x.subTo(this.m, x);
  23410. }
  23411. __name(montReduce, "montReduce");
  23412. function montSqrTo(x, r) {
  23413. x.squareTo(r);
  23414. this.reduce(r);
  23415. }
  23416. __name(montSqrTo, "montSqrTo");
  23417. function montMulTo(x, y, r) {
  23418. x.multiplyTo(y, r);
  23419. this.reduce(r);
  23420. }
  23421. __name(montMulTo, "montMulTo");
  23422. Montgomery.prototype.convert = montConvert;
  23423. Montgomery.prototype.revert = montRevert;
  23424. Montgomery.prototype.reduce = montReduce;
  23425. Montgomery.prototype.mulTo = montMulTo;
  23426. Montgomery.prototype.sqrTo = montSqrTo;
  23427. function bnpIsEven() {
  23428. return (this.t > 0 ? this[0] & 1 : this.s) == 0;
  23429. }
  23430. __name(bnpIsEven, "bnpIsEven");
  23431. function bnpExp(e, z2) {
  23432. if (e > 4294967295 || e < 1) return BigInteger.ONE;
  23433. var r = nbi(), r2 = nbi(), g = z2.convert(this), i = nbits(e) - 1;
  23434. g.copyTo(r);
  23435. while (--i >= 0) {
  23436. z2.sqrTo(r, r2);
  23437. if ((e & 1 << i) > 0) z2.mulTo(r2, g, r);
  23438. else {
  23439. var t2 = r;
  23440. r = r2;
  23441. r2 = t2;
  23442. }
  23443. }
  23444. return z2.revert(r);
  23445. }
  23446. __name(bnpExp, "bnpExp");
  23447. function bnModPowInt(e, m) {
  23448. var z2;
  23449. if (e < 256 || m.isEven()) z2 = new Classic(m);
  23450. else z2 = new Montgomery(m);
  23451. return this.exp(e, z2);
  23452. }
  23453. __name(bnModPowInt, "bnModPowInt");
  23454. BigInteger.prototype.copyTo = bnpCopyTo;
  23455. BigInteger.prototype.fromInt = bnpFromInt;
  23456. BigInteger.prototype.fromString = bnpFromString;
  23457. BigInteger.prototype.clamp = bnpClamp;
  23458. BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  23459. BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  23460. BigInteger.prototype.lShiftTo = bnpLShiftTo;
  23461. BigInteger.prototype.rShiftTo = bnpRShiftTo;
  23462. BigInteger.prototype.subTo = bnpSubTo;
  23463. BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  23464. BigInteger.prototype.squareTo = bnpSquareTo;
  23465. BigInteger.prototype.divRemTo = bnpDivRemTo;
  23466. BigInteger.prototype.invDigit = bnpInvDigit;
  23467. BigInteger.prototype.isEven = bnpIsEven;
  23468. BigInteger.prototype.exp = bnpExp;
  23469. BigInteger.prototype.toString = bnToString;
  23470. BigInteger.prototype.negate = bnNegate;
  23471. BigInteger.prototype.abs = bnAbs;
  23472. BigInteger.prototype.compareTo = bnCompareTo;
  23473. BigInteger.prototype.bitLength = bnBitLength;
  23474. BigInteger.prototype.mod = bnMod;
  23475. BigInteger.prototype.modPowInt = bnModPowInt;
  23476. BigInteger.ZERO = nbv(0);
  23477. BigInteger.ONE = nbv(1);
  23478. function bnClone() {
  23479. var r = nbi();
  23480. this.copyTo(r);
  23481. return r;
  23482. }
  23483. __name(bnClone, "bnClone");
  23484. function bnIntValue() {
  23485. if (this.s < 0) {
  23486. if (this.t == 1) return this[0] - this.DV;
  23487. else if (this.t == 0) return -1;
  23488. } else if (this.t == 1) return this[0];
  23489. else if (this.t == 0) return 0;
  23490. return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0];
  23491. }
  23492. __name(bnIntValue, "bnIntValue");
  23493. function bnByteValue() {
  23494. return this.t == 0 ? this.s : this[0] << 24 >> 24;
  23495. }
  23496. __name(bnByteValue, "bnByteValue");
  23497. function bnShortValue() {
  23498. return this.t == 0 ? this.s : this[0] << 16 >> 16;
  23499. }
  23500. __name(bnShortValue, "bnShortValue");
  23501. function bnpChunkSize(r) {
  23502. return Math.floor(Math.LN2 * this.DB / Math.log(r));
  23503. }
  23504. __name(bnpChunkSize, "bnpChunkSize");
  23505. function bnSigNum() {
  23506. if (this.s < 0) return -1;
  23507. else if (this.t <= 0 || this.t == 1 && this[0] <= 0) return 0;
  23508. else return 1;
  23509. }
  23510. __name(bnSigNum, "bnSigNum");
  23511. function bnpToRadix(b) {
  23512. if (b == null) b = 10;
  23513. if (this.signum() == 0 || b < 2 || b > 36) return "0";
  23514. var cs = this.chunkSize(b);
  23515. var a = Math.pow(b, cs);
  23516. var d = nbv(a), y = nbi(), z2 = nbi(), r = "";
  23517. this.divRemTo(d, y, z2);
  23518. while (y.signum() > 0) {
  23519. r = (a + z2.intValue()).toString(b).substr(1) + r;
  23520. y.divRemTo(d, y, z2);
  23521. }
  23522. return z2.intValue().toString(b) + r;
  23523. }
  23524. __name(bnpToRadix, "bnpToRadix");
  23525. function bnpFromRadix(s, b) {
  23526. this.fromInt(0);
  23527. if (b == null) b = 10;
  23528. var cs = this.chunkSize(b);
  23529. var d = Math.pow(b, cs), mi = false, j = 0, w = 0;
  23530. for (var i = 0; i < s.length; ++i) {
  23531. var x = intAt(s, i);
  23532. if (x < 0) {
  23533. if (s.charAt(i) == "-" && this.signum() == 0) mi = true;
  23534. continue;
  23535. }
  23536. w = b * w + x;
  23537. if (++j >= cs) {
  23538. this.dMultiply(d);
  23539. this.dAddOffset(w, 0);
  23540. j = 0;
  23541. w = 0;
  23542. }
  23543. }
  23544. if (j > 0) {
  23545. this.dMultiply(Math.pow(b, j));
  23546. this.dAddOffset(w, 0);
  23547. }
  23548. if (mi) BigInteger.ZERO.subTo(this, this);
  23549. }
  23550. __name(bnpFromRadix, "bnpFromRadix");
  23551. function bnpFromNumber(a, b, c) {
  23552. if ("number" == typeof b) {
  23553. if (a < 2) this.fromInt(1);
  23554. else {
  23555. this.fromNumber(a, c);
  23556. if (!this.testBit(a - 1))
  23557. this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
  23558. if (this.isEven()) this.dAddOffset(1, 0);
  23559. while (!this.isProbablePrime(b)) {
  23560. this.dAddOffset(2, 0);
  23561. if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
  23562. }
  23563. }
  23564. } else {
  23565. var x = new Array(), t2 = a & 7;
  23566. x.length = (a >> 3) + 1;
  23567. b.nextBytes(x);
  23568. if (t2 > 0) x[0] &= (1 << t2) - 1;
  23569. else x[0] = 0;
  23570. this.fromString(x, 256);
  23571. }
  23572. }
  23573. __name(bnpFromNumber, "bnpFromNumber");
  23574. function bnToByteArray() {
  23575. var i = this.t, r = new Array();
  23576. r[0] = this.s;
  23577. var p = this.DB - i * this.DB % 8, d, k = 0;
  23578. if (i-- > 0) {
  23579. if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p)
  23580. r[k++] = d | this.s << this.DB - p;
  23581. while (i >= 0) {
  23582. if (p < 8) {
  23583. d = (this[i] & (1 << p) - 1) << 8 - p;
  23584. d |= this[--i] >> (p += this.DB - 8);
  23585. } else {
  23586. d = this[i] >> (p -= 8) & 255;
  23587. if (p <= 0) {
  23588. p += this.DB;
  23589. --i;
  23590. }
  23591. }
  23592. if ((d & 128) != 0) d |= -256;
  23593. if (k == 0 && (this.s & 128) != (d & 128)) ++k;
  23594. if (k > 0 || d != this.s) r[k++] = d;
  23595. }
  23596. }
  23597. return r;
  23598. }
  23599. __name(bnToByteArray, "bnToByteArray");
  23600. function bnEquals(a) {
  23601. return this.compareTo(a) == 0;
  23602. }
  23603. __name(bnEquals, "bnEquals");
  23604. function bnMin(a) {
  23605. return this.compareTo(a) < 0 ? this : a;
  23606. }
  23607. __name(bnMin, "bnMin");
  23608. function bnMax(a) {
  23609. return this.compareTo(a) > 0 ? this : a;
  23610. }
  23611. __name(bnMax, "bnMax");
  23612. function bnpBitwiseTo(a, op, r) {
  23613. var i, f, m = Math.min(a.t, this.t);
  23614. for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]);
  23615. if (a.t < this.t) {
  23616. f = a.s & this.DM;
  23617. for (i = m; i < this.t; ++i) r[i] = op(this[i], f);
  23618. r.t = this.t;
  23619. } else {
  23620. f = this.s & this.DM;
  23621. for (i = m; i < a.t; ++i) r[i] = op(f, a[i]);
  23622. r.t = a.t;
  23623. }
  23624. r.s = op(this.s, a.s);
  23625. r.clamp();
  23626. }
  23627. __name(bnpBitwiseTo, "bnpBitwiseTo");
  23628. function op_and(x, y) {
  23629. return x & y;
  23630. }
  23631. __name(op_and, "op_and");
  23632. function bnAnd(a) {
  23633. var r = nbi();
  23634. this.bitwiseTo(a, op_and, r);
  23635. return r;
  23636. }
  23637. __name(bnAnd, "bnAnd");
  23638. function op_or(x, y) {
  23639. return x | y;
  23640. }
  23641. __name(op_or, "op_or");
  23642. function bnOr(a) {
  23643. var r = nbi();
  23644. this.bitwiseTo(a, op_or, r);
  23645. return r;
  23646. }
  23647. __name(bnOr, "bnOr");
  23648. function op_xor(x, y) {
  23649. return x ^ y;
  23650. }
  23651. __name(op_xor, "op_xor");
  23652. function bnXor(a) {
  23653. var r = nbi();
  23654. this.bitwiseTo(a, op_xor, r);
  23655. return r;
  23656. }
  23657. __name(bnXor, "bnXor");
  23658. function op_andnot(x, y) {
  23659. return x & ~y;
  23660. }
  23661. __name(op_andnot, "op_andnot");
  23662. function bnAndNot(a) {
  23663. var r = nbi();
  23664. this.bitwiseTo(a, op_andnot, r);
  23665. return r;
  23666. }
  23667. __name(bnAndNot, "bnAndNot");
  23668. function bnNot() {
  23669. var r = nbi();
  23670. for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i];
  23671. r.t = this.t;
  23672. r.s = ~this.s;
  23673. return r;
  23674. }
  23675. __name(bnNot, "bnNot");
  23676. function bnShiftLeft(n) {
  23677. var r = nbi();
  23678. if (n < 0) this.rShiftTo(-n, r);
  23679. else this.lShiftTo(n, r);
  23680. return r;
  23681. }
  23682. __name(bnShiftLeft, "bnShiftLeft");
  23683. function bnShiftRight(n) {
  23684. var r = nbi();
  23685. if (n < 0) this.lShiftTo(-n, r);
  23686. else this.rShiftTo(n, r);
  23687. return r;
  23688. }
  23689. __name(bnShiftRight, "bnShiftRight");
  23690. function lbit(x) {
  23691. if (x == 0) return -1;
  23692. var r = 0;
  23693. if ((x & 65535) == 0) {
  23694. x >>= 16;
  23695. r += 16;
  23696. }
  23697. if ((x & 255) == 0) {
  23698. x >>= 8;
  23699. r += 8;
  23700. }
  23701. if ((x & 15) == 0) {
  23702. x >>= 4;
  23703. r += 4;
  23704. }
  23705. if ((x & 3) == 0) {
  23706. x >>= 2;
  23707. r += 2;
  23708. }
  23709. if ((x & 1) == 0) ++r;
  23710. return r;
  23711. }
  23712. __name(lbit, "lbit");
  23713. function bnGetLowestSetBit() {
  23714. for (var i = 0; i < this.t; ++i)
  23715. if (this[i] != 0) return i * this.DB + lbit(this[i]);
  23716. if (this.s < 0) return this.t * this.DB;
  23717. return -1;
  23718. }
  23719. __name(bnGetLowestSetBit, "bnGetLowestSetBit");
  23720. function cbit(x) {
  23721. var r = 0;
  23722. while (x != 0) {
  23723. x &= x - 1;
  23724. ++r;
  23725. }
  23726. return r;
  23727. }
  23728. __name(cbit, "cbit");
  23729. function bnBitCount() {
  23730. var r = 0, x = this.s & this.DM;
  23731. for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x);
  23732. return r;
  23733. }
  23734. __name(bnBitCount, "bnBitCount");
  23735. function bnTestBit(n) {
  23736. var j = Math.floor(n / this.DB);
  23737. if (j >= this.t) return this.s != 0;
  23738. return (this[j] & 1 << n % this.DB) != 0;
  23739. }
  23740. __name(bnTestBit, "bnTestBit");
  23741. function bnpChangeBit(n, op) {
  23742. var r = BigInteger.ONE.shiftLeft(n);
  23743. this.bitwiseTo(r, op, r);
  23744. return r;
  23745. }
  23746. __name(bnpChangeBit, "bnpChangeBit");
  23747. function bnSetBit(n) {
  23748. return this.changeBit(n, op_or);
  23749. }
  23750. __name(bnSetBit, "bnSetBit");
  23751. function bnClearBit(n) {
  23752. return this.changeBit(n, op_andnot);
  23753. }
  23754. __name(bnClearBit, "bnClearBit");
  23755. function bnFlipBit(n) {
  23756. return this.changeBit(n, op_xor);
  23757. }
  23758. __name(bnFlipBit, "bnFlipBit");
  23759. function bnpAddTo(a, r) {
  23760. var i = 0, c = 0, m = Math.min(a.t, this.t);
  23761. while (i < m) {
  23762. c += this[i] + a[i];
  23763. r[i++] = c & this.DM;
  23764. c >>= this.DB;
  23765. }
  23766. if (a.t < this.t) {
  23767. c += a.s;
  23768. while (i < this.t) {
  23769. c += this[i];
  23770. r[i++] = c & this.DM;
  23771. c >>= this.DB;
  23772. }
  23773. c += this.s;
  23774. } else {
  23775. c += this.s;
  23776. while (i < a.t) {
  23777. c += a[i];
  23778. r[i++] = c & this.DM;
  23779. c >>= this.DB;
  23780. }
  23781. c += a.s;
  23782. }
  23783. r.s = c < 0 ? -1 : 0;
  23784. if (c > 0) r[i++] = c;
  23785. else if (c < -1) r[i++] = this.DV + c;
  23786. r.t = i;
  23787. r.clamp();
  23788. }
  23789. __name(bnpAddTo, "bnpAddTo");
  23790. function bnAdd(a) {
  23791. var r = nbi();
  23792. this.addTo(a, r);
  23793. return r;
  23794. }
  23795. __name(bnAdd, "bnAdd");
  23796. function bnSubtract(a) {
  23797. var r = nbi();
  23798. this.subTo(a, r);
  23799. return r;
  23800. }
  23801. __name(bnSubtract, "bnSubtract");
  23802. function bnMultiply(a) {
  23803. var r = nbi();
  23804. this.multiplyTo(a, r);
  23805. return r;
  23806. }
  23807. __name(bnMultiply, "bnMultiply");
  23808. function bnSquare() {
  23809. var r = nbi();
  23810. this.squareTo(r);
  23811. return r;
  23812. }
  23813. __name(bnSquare, "bnSquare");
  23814. function bnDivide(a) {
  23815. var r = nbi();
  23816. this.divRemTo(a, r, null);
  23817. return r;
  23818. }
  23819. __name(bnDivide, "bnDivide");
  23820. function bnRemainder(a) {
  23821. var r = nbi();
  23822. this.divRemTo(a, null, r);
  23823. return r;
  23824. }
  23825. __name(bnRemainder, "bnRemainder");
  23826. function bnDivideAndRemainder(a) {
  23827. var q = nbi(), r = nbi();
  23828. this.divRemTo(a, q, r);
  23829. return new Array(q, r);
  23830. }
  23831. __name(bnDivideAndRemainder, "bnDivideAndRemainder");
  23832. function bnpDMultiply(n) {
  23833. this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
  23834. ++this.t;
  23835. this.clamp();
  23836. }
  23837. __name(bnpDMultiply, "bnpDMultiply");
  23838. function bnpDAddOffset(n, w) {
  23839. if (n == 0) return;
  23840. while (this.t <= w) this[this.t++] = 0;
  23841. this[w] += n;
  23842. while (this[w] >= this.DV) {
  23843. this[w] -= this.DV;
  23844. if (++w >= this.t) this[this.t++] = 0;
  23845. ++this[w];
  23846. }
  23847. }
  23848. __name(bnpDAddOffset, "bnpDAddOffset");
  23849. function NullExp() {
  23850. }
  23851. __name(NullExp, "NullExp");
  23852. function nNop(x) {
  23853. return x;
  23854. }
  23855. __name(nNop, "nNop");
  23856. function nMulTo(x, y, r) {
  23857. x.multiplyTo(y, r);
  23858. }
  23859. __name(nMulTo, "nMulTo");
  23860. function nSqrTo(x, r) {
  23861. x.squareTo(r);
  23862. }
  23863. __name(nSqrTo, "nSqrTo");
  23864. NullExp.prototype.convert = nNop;
  23865. NullExp.prototype.revert = nNop;
  23866. NullExp.prototype.mulTo = nMulTo;
  23867. NullExp.prototype.sqrTo = nSqrTo;
  23868. function bnPow(e) {
  23869. return this.exp(e, new NullExp());
  23870. }
  23871. __name(bnPow, "bnPow");
  23872. function bnpMultiplyLowerTo(a, n, r) {
  23873. var i = Math.min(this.t + a.t, n);
  23874. r.s = 0;
  23875. r.t = i;
  23876. while (i > 0) r[--i] = 0;
  23877. var j;
  23878. for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
  23879. for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i);
  23880. r.clamp();
  23881. }
  23882. __name(bnpMultiplyLowerTo, "bnpMultiplyLowerTo");
  23883. function bnpMultiplyUpperTo(a, n, r) {
  23884. --n;
  23885. var i = r.t = this.t + a.t - n;
  23886. r.s = 0;
  23887. while (--i >= 0) r[i] = 0;
  23888. for (i = Math.max(n - this.t, 0); i < a.t; ++i)
  23889. r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
  23890. r.clamp();
  23891. r.drShiftTo(1, r);
  23892. }
  23893. __name(bnpMultiplyUpperTo, "bnpMultiplyUpperTo");
  23894. function Barrett(m) {
  23895. this.r2 = nbi();
  23896. this.q3 = nbi();
  23897. BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
  23898. this.mu = this.r2.divide(m);
  23899. this.m = m;
  23900. }
  23901. __name(Barrett, "Barrett");
  23902. function barrettConvert(x) {
  23903. if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m);
  23904. else if (x.compareTo(this.m) < 0) return x;
  23905. else {
  23906. var r = nbi();
  23907. x.copyTo(r);
  23908. this.reduce(r);
  23909. return r;
  23910. }
  23911. }
  23912. __name(barrettConvert, "barrettConvert");
  23913. function barrettRevert(x) {
  23914. return x;
  23915. }
  23916. __name(barrettRevert, "barrettRevert");
  23917. function barrettReduce(x) {
  23918. x.drShiftTo(this.m.t - 1, this.r2);
  23919. if (x.t > this.m.t + 1) {
  23920. x.t = this.m.t + 1;
  23921. x.clamp();
  23922. }
  23923. this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
  23924. this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
  23925. while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1);
  23926. x.subTo(this.r2, x);
  23927. while (x.compareTo(this.m) >= 0) x.subTo(this.m, x);
  23928. }
  23929. __name(barrettReduce, "barrettReduce");
  23930. function barrettSqrTo(x, r) {
  23931. x.squareTo(r);
  23932. this.reduce(r);
  23933. }
  23934. __name(barrettSqrTo, "barrettSqrTo");
  23935. function barrettMulTo(x, y, r) {
  23936. x.multiplyTo(y, r);
  23937. this.reduce(r);
  23938. }
  23939. __name(barrettMulTo, "barrettMulTo");
  23940. Barrett.prototype.convert = barrettConvert;
  23941. Barrett.prototype.revert = barrettRevert;
  23942. Barrett.prototype.reduce = barrettReduce;
  23943. Barrett.prototype.mulTo = barrettMulTo;
  23944. Barrett.prototype.sqrTo = barrettSqrTo;
  23945. function bnModPow(e, m) {
  23946. var i = e.bitLength(), k, r = nbv(1), z2;
  23947. if (i <= 0) return r;
  23948. else if (i < 18) k = 1;
  23949. else if (i < 48) k = 3;
  23950. else if (i < 144) k = 4;
  23951. else if (i < 768) k = 5;
  23952. else k = 6;
  23953. if (i < 8)
  23954. z2 = new Classic(m);
  23955. else if (m.isEven())
  23956. z2 = new Barrett(m);
  23957. else
  23958. z2 = new Montgomery(m);
  23959. var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1;
  23960. g[1] = z2.convert(this);
  23961. if (k > 1) {
  23962. var g2 = nbi();
  23963. z2.sqrTo(g[1], g2);
  23964. while (n <= km) {
  23965. g[n] = nbi();
  23966. z2.mulTo(g2, g[n - 2], g[n]);
  23967. n += 2;
  23968. }
  23969. }
  23970. var j = e.t - 1, w, is1 = true, r2 = nbi(), t2;
  23971. i = nbits(e[j]) - 1;
  23972. while (j >= 0) {
  23973. if (i >= k1) w = e[j] >> i - k1 & km;
  23974. else {
  23975. w = (e[j] & (1 << i + 1) - 1) << k1 - i;
  23976. if (j > 0) w |= e[j - 1] >> this.DB + i - k1;
  23977. }
  23978. n = k;
  23979. while ((w & 1) == 0) {
  23980. w >>= 1;
  23981. --n;
  23982. }
  23983. if ((i -= n) < 0) {
  23984. i += this.DB;
  23985. --j;
  23986. }
  23987. if (is1) {
  23988. g[w].copyTo(r);
  23989. is1 = false;
  23990. } else {
  23991. while (n > 1) {
  23992. z2.sqrTo(r, r2);
  23993. z2.sqrTo(r2, r);
  23994. n -= 2;
  23995. }
  23996. if (n > 0) z2.sqrTo(r, r2);
  23997. else {
  23998. t2 = r;
  23999. r = r2;
  24000. r2 = t2;
  24001. }
  24002. z2.mulTo(r2, g[w], r);
  24003. }
  24004. while (j >= 0 && (e[j] & 1 << i) == 0) {
  24005. z2.sqrTo(r, r2);
  24006. t2 = r;
  24007. r = r2;
  24008. r2 = t2;
  24009. if (--i < 0) {
  24010. i = this.DB - 1;
  24011. --j;
  24012. }
  24013. }
  24014. }
  24015. return z2.revert(r);
  24016. }
  24017. __name(bnModPow, "bnModPow");
  24018. function bnGCD(a) {
  24019. var x = this.s < 0 ? this.negate() : this.clone();
  24020. var y = a.s < 0 ? a.negate() : a.clone();
  24021. if (x.compareTo(y) < 0) {
  24022. var t2 = x;
  24023. x = y;
  24024. y = t2;
  24025. }
  24026. var i = x.getLowestSetBit(), g = y.getLowestSetBit();
  24027. if (g < 0) return x;
  24028. if (i < g) g = i;
  24029. if (g > 0) {
  24030. x.rShiftTo(g, x);
  24031. y.rShiftTo(g, y);
  24032. }
  24033. while (x.signum() > 0) {
  24034. if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x);
  24035. if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y);
  24036. if (x.compareTo(y) >= 0) {
  24037. x.subTo(y, x);
  24038. x.rShiftTo(1, x);
  24039. } else {
  24040. y.subTo(x, y);
  24041. y.rShiftTo(1, y);
  24042. }
  24043. }
  24044. if (g > 0) y.lShiftTo(g, y);
  24045. return y;
  24046. }
  24047. __name(bnGCD, "bnGCD");
  24048. function bnpModInt(n) {
  24049. if (n <= 0) return 0;
  24050. var d = this.DV % n, r = this.s < 0 ? n - 1 : 0;
  24051. if (this.t > 0)
  24052. if (d == 0) r = this[0] % n;
  24053. else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n;
  24054. return r;
  24055. }
  24056. __name(bnpModInt, "bnpModInt");
  24057. function bnModInverse(m) {
  24058. var ac = m.isEven();
  24059. if (this.isEven() && ac || m.signum() == 0) return BigInteger.ZERO;
  24060. var u = m.clone(), v = this.clone();
  24061. var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
  24062. while (u.signum() != 0) {
  24063. while (u.isEven()) {
  24064. u.rShiftTo(1, u);
  24065. if (ac) {
  24066. if (!a.isEven() || !b.isEven()) {
  24067. a.addTo(this, a);
  24068. b.subTo(m, b);
  24069. }
  24070. a.rShiftTo(1, a);
  24071. } else if (!b.isEven()) b.subTo(m, b);
  24072. b.rShiftTo(1, b);
  24073. }
  24074. while (v.isEven()) {
  24075. v.rShiftTo(1, v);
  24076. if (ac) {
  24077. if (!c.isEven() || !d.isEven()) {
  24078. c.addTo(this, c);
  24079. d.subTo(m, d);
  24080. }
  24081. c.rShiftTo(1, c);
  24082. } else if (!d.isEven()) d.subTo(m, d);
  24083. d.rShiftTo(1, d);
  24084. }
  24085. if (u.compareTo(v) >= 0) {
  24086. u.subTo(v, u);
  24087. if (ac) a.subTo(c, a);
  24088. b.subTo(d, b);
  24089. } else {
  24090. v.subTo(u, v);
  24091. if (ac) c.subTo(a, c);
  24092. d.subTo(b, d);
  24093. }
  24094. }
  24095. if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
  24096. if (d.compareTo(m) >= 0) return d.subtract(m);
  24097. if (d.signum() < 0) d.addTo(m, d);
  24098. else return d;
  24099. if (d.signum() < 0) return d.add(m);
  24100. else return d;
  24101. }
  24102. __name(bnModInverse, "bnModInverse");
  24103. var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
  24104. var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
  24105. function bnIsProbablePrime(t2) {
  24106. var i, x = this.abs();
  24107. if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
  24108. for (i = 0; i < lowprimes.length; ++i)
  24109. if (x[0] == lowprimes[i]) return true;
  24110. return false;
  24111. }
  24112. if (x.isEven()) return false;
  24113. i = 1;
  24114. while (i < lowprimes.length) {
  24115. var m = lowprimes[i], j = i + 1;
  24116. while (j < lowprimes.length && m < lplim) m *= lowprimes[j++];
  24117. m = x.modInt(m);
  24118. while (i < j) if (m % lowprimes[i++] == 0) return false;
  24119. }
  24120. return x.millerRabin(t2);
  24121. }
  24122. __name(bnIsProbablePrime, "bnIsProbablePrime");
  24123. function bnpMillerRabin(t2) {
  24124. var n1 = this.subtract(BigInteger.ONE);
  24125. var k = n1.getLowestSetBit();
  24126. if (k <= 0) return false;
  24127. var r = n1.shiftRight(k);
  24128. t2 = t2 + 1 >> 1;
  24129. if (t2 > lowprimes.length) t2 = lowprimes.length;
  24130. var a = nbi();
  24131. for (var i = 0; i < t2; ++i) {
  24132. a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
  24133. var y = a.modPow(r, this);
  24134. if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
  24135. var j = 1;
  24136. while (j++ < k && y.compareTo(n1) != 0) {
  24137. y = y.modPowInt(2, this);
  24138. if (y.compareTo(BigInteger.ONE) == 0) return false;
  24139. }
  24140. if (y.compareTo(n1) != 0) return false;
  24141. }
  24142. }
  24143. return true;
  24144. }
  24145. __name(bnpMillerRabin, "bnpMillerRabin");
  24146. BigInteger.prototype.chunkSize = bnpChunkSize;
  24147. BigInteger.prototype.toRadix = bnpToRadix;
  24148. BigInteger.prototype.fromRadix = bnpFromRadix;
  24149. BigInteger.prototype.fromNumber = bnpFromNumber;
  24150. BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
  24151. BigInteger.prototype.changeBit = bnpChangeBit;
  24152. BigInteger.prototype.addTo = bnpAddTo;
  24153. BigInteger.prototype.dMultiply = bnpDMultiply;
  24154. BigInteger.prototype.dAddOffset = bnpDAddOffset;
  24155. BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  24156. BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  24157. BigInteger.prototype.modInt = bnpModInt;
  24158. BigInteger.prototype.millerRabin = bnpMillerRabin;
  24159. BigInteger.prototype.clone = bnClone;
  24160. BigInteger.prototype.intValue = bnIntValue;
  24161. BigInteger.prototype.byteValue = bnByteValue;
  24162. BigInteger.prototype.shortValue = bnShortValue;
  24163. BigInteger.prototype.signum = bnSigNum;
  24164. BigInteger.prototype.toByteArray = bnToByteArray;
  24165. BigInteger.prototype.equals = bnEquals;
  24166. BigInteger.prototype.min = bnMin;
  24167. BigInteger.prototype.max = bnMax;
  24168. BigInteger.prototype.and = bnAnd;
  24169. BigInteger.prototype.or = bnOr;
  24170. BigInteger.prototype.xor = bnXor;
  24171. BigInteger.prototype.andNot = bnAndNot;
  24172. BigInteger.prototype.not = bnNot;
  24173. BigInteger.prototype.shiftLeft = bnShiftLeft;
  24174. BigInteger.prototype.shiftRight = bnShiftRight;
  24175. BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
  24176. BigInteger.prototype.bitCount = bnBitCount;
  24177. BigInteger.prototype.testBit = bnTestBit;
  24178. BigInteger.prototype.setBit = bnSetBit;
  24179. BigInteger.prototype.clearBit = bnClearBit;
  24180. BigInteger.prototype.flipBit = bnFlipBit;
  24181. BigInteger.prototype.add = bnAdd;
  24182. BigInteger.prototype.subtract = bnSubtract;
  24183. BigInteger.prototype.multiply = bnMultiply;
  24184. BigInteger.prototype.divide = bnDivide;
  24185. BigInteger.prototype.remainder = bnRemainder;
  24186. BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
  24187. BigInteger.prototype.modPow = bnModPow;
  24188. BigInteger.prototype.modInverse = bnModInverse;
  24189. BigInteger.prototype.pow = bnPow;
  24190. BigInteger.prototype.gcd = bnGCD;
  24191. BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
  24192. BigInteger.prototype.square = bnSquare;
  24193. BigInteger.prototype.Barrett = Barrett;
  24194. var rng_state;
  24195. var rng_pool;
  24196. var rng_pptr;
  24197. function rng_seed_int(x) {
  24198. rng_pool[rng_pptr++] ^= x & 255;
  24199. rng_pool[rng_pptr++] ^= x >> 8 & 255;
  24200. rng_pool[rng_pptr++] ^= x >> 16 & 255;
  24201. rng_pool[rng_pptr++] ^= x >> 24 & 255;
  24202. if (rng_pptr >= rng_psize) rng_pptr -= rng_psize;
  24203. }
  24204. __name(rng_seed_int, "rng_seed_int");
  24205. function rng_seed_time() {
  24206. rng_seed_int((/* @__PURE__ */ new Date()).getTime());
  24207. }
  24208. __name(rng_seed_time, "rng_seed_time");
  24209. if (rng_pool == null) {
  24210. rng_pool = new Array();
  24211. rng_pptr = 0;
  24212. var t;
  24213. if (typeof window !== "undefined" && window.crypto) {
  24214. if (window.crypto.getRandomValues) {
  24215. var ua = new Uint8Array(32);
  24216. window.crypto.getRandomValues(ua);
  24217. for (t = 0; t < 32; ++t)
  24218. rng_pool[rng_pptr++] = ua[t];
  24219. } else if (navigator.appName == "Netscape" && navigator.appVersion < "5") {
  24220. var z = window.crypto.random(32);
  24221. for (t = 0; t < z.length; ++t)
  24222. rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
  24223. }
  24224. }
  24225. while (rng_pptr < rng_psize) {
  24226. t = Math.floor(65536 * Math.random());
  24227. rng_pool[rng_pptr++] = t >>> 8;
  24228. rng_pool[rng_pptr++] = t & 255;
  24229. }
  24230. rng_pptr = 0;
  24231. rng_seed_time();
  24232. }
  24233. function rng_get_byte() {
  24234. if (rng_state == null) {
  24235. rng_seed_time();
  24236. rng_state = prng_newstate();
  24237. rng_state.init(rng_pool);
  24238. for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
  24239. rng_pool[rng_pptr] = 0;
  24240. rng_pptr = 0;
  24241. }
  24242. return rng_state.next();
  24243. }
  24244. __name(rng_get_byte, "rng_get_byte");
  24245. function rng_get_bytes(ba) {
  24246. var i;
  24247. for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
  24248. }
  24249. __name(rng_get_bytes, "rng_get_bytes");
  24250. function SecureRandom() {
  24251. }
  24252. __name(SecureRandom, "SecureRandom");
  24253. SecureRandom.prototype.nextBytes = rng_get_bytes;
  24254. function Arcfour() {
  24255. this.i = 0;
  24256. this.j = 0;
  24257. this.S = new Array();
  24258. }
  24259. __name(Arcfour, "Arcfour");
  24260. function ARC4init(key) {
  24261. var i, j, t2;
  24262. for (i = 0; i < 256; ++i)
  24263. this.S[i] = i;
  24264. j = 0;
  24265. for (i = 0; i < 256; ++i) {
  24266. j = j + this.S[i] + key[i % key.length] & 255;
  24267. t2 = this.S[i];
  24268. this.S[i] = this.S[j];
  24269. this.S[j] = t2;
  24270. }
  24271. this.i = 0;
  24272. this.j = 0;
  24273. }
  24274. __name(ARC4init, "ARC4init");
  24275. function ARC4next() {
  24276. var t2;
  24277. this.i = this.i + 1 & 255;
  24278. this.j = this.j + this.S[this.i] & 255;
  24279. t2 = this.S[this.i];
  24280. this.S[this.i] = this.S[this.j];
  24281. this.S[this.j] = t2;
  24282. return this.S[t2 + this.S[this.i] & 255];
  24283. }
  24284. __name(ARC4next, "ARC4next");
  24285. Arcfour.prototype.init = ARC4init;
  24286. Arcfour.prototype.next = ARC4next;
  24287. function prng_newstate() {
  24288. return new Arcfour();
  24289. }
  24290. __name(prng_newstate, "prng_newstate");
  24291. var rng_psize = 256;
  24292. if (typeof exports2 !== "undefined") {
  24293. exports2 = module2.exports = {
  24294. default: BigInteger,
  24295. BigInteger,
  24296. SecureRandom
  24297. };
  24298. } else {
  24299. this.jsbn = {
  24300. BigInteger,
  24301. SecureRandom
  24302. };
  24303. }
  24304. }).call(exports2);
  24305. }
  24306. });
  24307. // node_modules/sprintf-js/src/sprintf.js
  24308. var require_sprintf = __commonJS({
  24309. "node_modules/sprintf-js/src/sprintf.js"(exports2) {
  24310. !function() {
  24311. "use strict";
  24312. var re = {
  24313. not_string: /[^s]/,
  24314. not_bool: /[^t]/,
  24315. not_type: /[^T]/,
  24316. not_primitive: /[^v]/,
  24317. number: /[diefg]/,
  24318. numeric_arg: /[bcdiefguxX]/,
  24319. json: /[j]/,
  24320. not_json: /[^j]/,
  24321. text: /^[^\x25]+/,
  24322. modulo: /^\x25{2}/,
  24323. placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
  24324. key: /^([a-z_][a-z_\d]*)/i,
  24325. key_access: /^\.([a-z_][a-z_\d]*)/i,
  24326. index_access: /^\[(\d+)\]/,
  24327. sign: /^[+-]/
  24328. };
  24329. function sprintf(key) {
  24330. return sprintf_format(sprintf_parse(key), arguments);
  24331. }
  24332. __name(sprintf, "sprintf");
  24333. function vsprintf(fmt, argv) {
  24334. return sprintf.apply(null, [fmt].concat(argv || []));
  24335. }
  24336. __name(vsprintf, "vsprintf");
  24337. function sprintf_format(parse_tree, argv) {
  24338. var cursor = 1, tree_length = parse_tree.length, arg, output = "", i, k, ph, pad, pad_character, pad_length, is_positive, sign;
  24339. for (i = 0; i < tree_length; i++) {
  24340. if (typeof parse_tree[i] === "string") {
  24341. output += parse_tree[i];
  24342. } else if (typeof parse_tree[i] === "object") {
  24343. ph = parse_tree[i];
  24344. if (ph.keys) {
  24345. arg = argv[cursor];
  24346. for (k = 0; k < ph.keys.length; k++) {
  24347. if (arg == void 0) {
  24348. throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
  24349. }
  24350. arg = arg[ph.keys[k]];
  24351. }
  24352. } else if (ph.param_no) {
  24353. arg = argv[ph.param_no];
  24354. } else {
  24355. arg = argv[cursor++];
  24356. }
  24357. if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
  24358. arg = arg();
  24359. }
  24360. if (re.numeric_arg.test(ph.type) && (typeof arg !== "number" && isNaN(arg))) {
  24361. throw new TypeError(sprintf("[sprintf] expecting number but found %T", arg));
  24362. }
  24363. if (re.number.test(ph.type)) {
  24364. is_positive = arg >= 0;
  24365. }
  24366. switch (ph.type) {
  24367. case "b":
  24368. arg = parseInt(arg, 10).toString(2);
  24369. break;
  24370. case "c":
  24371. arg = String.fromCharCode(parseInt(arg, 10));
  24372. break;
  24373. case "d":
  24374. case "i":
  24375. arg = parseInt(arg, 10);
  24376. break;
  24377. case "j":
  24378. arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
  24379. break;
  24380. case "e":
  24381. arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
  24382. break;
  24383. case "f":
  24384. arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
  24385. break;
  24386. case "g":
  24387. arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
  24388. break;
  24389. case "o":
  24390. arg = (parseInt(arg, 10) >>> 0).toString(8);
  24391. break;
  24392. case "s":
  24393. arg = String(arg);
  24394. arg = ph.precision ? arg.substring(0, ph.precision) : arg;
  24395. break;
  24396. case "t":
  24397. arg = String(!!arg);
  24398. arg = ph.precision ? arg.substring(0, ph.precision) : arg;
  24399. break;
  24400. case "T":
  24401. arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
  24402. arg = ph.precision ? arg.substring(0, ph.precision) : arg;
  24403. break;
  24404. case "u":
  24405. arg = parseInt(arg, 10) >>> 0;
  24406. break;
  24407. case "v":
  24408. arg = arg.valueOf();
  24409. arg = ph.precision ? arg.substring(0, ph.precision) : arg;
  24410. break;
  24411. case "x":
  24412. arg = (parseInt(arg, 10) >>> 0).toString(16);
  24413. break;
  24414. case "X":
  24415. arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
  24416. break;
  24417. }
  24418. if (re.json.test(ph.type)) {
  24419. output += arg;
  24420. } else {
  24421. if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
  24422. sign = is_positive ? "+" : "-";
  24423. arg = arg.toString().replace(re.sign, "");
  24424. } else {
  24425. sign = "";
  24426. }
  24427. pad_character = ph.pad_char ? ph.pad_char === "0" ? "0" : ph.pad_char.charAt(1) : " ";
  24428. pad_length = ph.width - (sign + arg).length;
  24429. pad = ph.width ? pad_length > 0 ? pad_character.repeat(pad_length) : "" : "";
  24430. output += ph.align ? sign + arg + pad : pad_character === "0" ? sign + pad + arg : pad + sign + arg;
  24431. }
  24432. }
  24433. }
  24434. return output;
  24435. }
  24436. __name(sprintf_format, "sprintf_format");
  24437. var sprintf_cache = /* @__PURE__ */ Object.create(null);
  24438. function sprintf_parse(fmt) {
  24439. if (sprintf_cache[fmt]) {
  24440. return sprintf_cache[fmt];
  24441. }
  24442. var _fmt = fmt, match, parse_tree = [], arg_names = 0;
  24443. while (_fmt) {
  24444. if ((match = re.text.exec(_fmt)) !== null) {
  24445. parse_tree.push(match[0]);
  24446. } else if ((match = re.modulo.exec(_fmt)) !== null) {
  24447. parse_tree.push("%");
  24448. } else if ((match = re.placeholder.exec(_fmt)) !== null) {
  24449. if (match[2]) {
  24450. arg_names |= 1;
  24451. var field_list = [], replacement_field = match[2], field_match = [];
  24452. if ((field_match = re.key.exec(replacement_field)) !== null) {
  24453. field_list.push(field_match[1]);
  24454. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") {
  24455. if ((field_match = re.key_access.exec(replacement_field)) !== null) {
  24456. field_list.push(field_match[1]);
  24457. } else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
  24458. field_list.push(field_match[1]);
  24459. } else {
  24460. throw new SyntaxError("[sprintf] failed to parse named argument key");
  24461. }
  24462. }
  24463. } else {
  24464. throw new SyntaxError("[sprintf] failed to parse named argument key");
  24465. }
  24466. match[2] = field_list;
  24467. } else {
  24468. arg_names |= 2;
  24469. }
  24470. if (arg_names === 3) {
  24471. throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");
  24472. }
  24473. parse_tree.push(
  24474. {
  24475. placeholder: match[0],
  24476. param_no: match[1],
  24477. keys: match[2],
  24478. sign: match[3],
  24479. pad_char: match[4],
  24480. align: match[5],
  24481. width: match[6],
  24482. precision: match[7],
  24483. type: match[8]
  24484. }
  24485. );
  24486. } else {
  24487. throw new SyntaxError("[sprintf] unexpected placeholder");
  24488. }
  24489. _fmt = _fmt.substring(match[0].length);
  24490. }
  24491. return sprintf_cache[fmt] = parse_tree;
  24492. }
  24493. __name(sprintf_parse, "sprintf_parse");
  24494. if (typeof exports2 !== "undefined") {
  24495. exports2["sprintf"] = sprintf;
  24496. exports2["vsprintf"] = vsprintf;
  24497. }
  24498. if (typeof window !== "undefined") {
  24499. window["sprintf"] = sprintf;
  24500. window["vsprintf"] = vsprintf;
  24501. if (typeof define === "function" && define["amd"]) {
  24502. define(function() {
  24503. return {
  24504. "sprintf": sprintf,
  24505. "vsprintf": vsprintf
  24506. };
  24507. });
  24508. }
  24509. }
  24510. }();
  24511. }
  24512. });
  24513. // node_modules/ip-address/dist/ipv4.js
  24514. var require_ipv4 = __commonJS({
  24515. "node_modules/ip-address/dist/ipv4.js"(exports2) {
  24516. "use strict";
  24517. var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
  24518. if (k2 === void 0) k2 = k;
  24519. var desc = Object.getOwnPropertyDescriptor(m, k);
  24520. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  24521. desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
  24522. return m[k];
  24523. }, "get") };
  24524. }
  24525. Object.defineProperty(o, k2, desc);
  24526. } : function(o, m, k, k2) {
  24527. if (k2 === void 0) k2 = k;
  24528. o[k2] = m[k];
  24529. });
  24530. var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
  24531. Object.defineProperty(o, "default", { enumerable: true, value: v });
  24532. } : function(o, v) {
  24533. o["default"] = v;
  24534. });
  24535. var __importStar = exports2 && exports2.__importStar || function(mod) {
  24536. if (mod && mod.__esModule) return mod;
  24537. var result = {};
  24538. if (mod != null) {
  24539. for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  24540. }
  24541. __setModuleDefault(result, mod);
  24542. return result;
  24543. };
  24544. Object.defineProperty(exports2, "__esModule", { value: true });
  24545. exports2.Address4 = void 0;
  24546. var common = __importStar(require_common3());
  24547. var constants = __importStar(require_constants4());
  24548. var address_error_1 = require_address_error();
  24549. var jsbn_1 = require_jsbn();
  24550. var sprintf_js_1 = require_sprintf();
  24551. var _Address4 = class _Address4 {
  24552. constructor(address) {
  24553. this.groups = constants.GROUPS;
  24554. this.parsedAddress = [];
  24555. this.parsedSubnet = "";
  24556. this.subnet = "/32";
  24557. this.subnetMask = 32;
  24558. this.v4 = true;
  24559. this.isCorrect = common.isCorrect(constants.BITS);
  24560. this.isInSubnet = common.isInSubnet;
  24561. this.address = address;
  24562. const subnet = constants.RE_SUBNET_STRING.exec(address);
  24563. if (subnet) {
  24564. this.parsedSubnet = subnet[0].replace("/", "");
  24565. this.subnetMask = parseInt(this.parsedSubnet, 10);
  24566. this.subnet = `/${this.subnetMask}`;
  24567. if (this.subnetMask < 0 || this.subnetMask > constants.BITS) {
  24568. throw new address_error_1.AddressError("Invalid subnet mask.");
  24569. }
  24570. address = address.replace(constants.RE_SUBNET_STRING, "");
  24571. }
  24572. this.addressMinusSuffix = address;
  24573. this.parsedAddress = this.parse(address);
  24574. }
  24575. static isValid(address) {
  24576. try {
  24577. new _Address4(address);
  24578. return true;
  24579. } catch (e) {
  24580. return false;
  24581. }
  24582. }
  24583. /*
  24584. * Parses a v4 address
  24585. */
  24586. parse(address) {
  24587. const groups = address.split(".");
  24588. if (!address.match(constants.RE_ADDRESS)) {
  24589. throw new address_error_1.AddressError("Invalid IPv4 address.");
  24590. }
  24591. return groups;
  24592. }
  24593. /**
  24594. * Returns the correct form of an address
  24595. * @memberof Address4
  24596. * @instance
  24597. * @returns {String}
  24598. */
  24599. correctForm() {
  24600. return this.parsedAddress.map((part) => parseInt(part, 10)).join(".");
  24601. }
  24602. /**
  24603. * Converts a hex string to an IPv4 address object
  24604. * @memberof Address4
  24605. * @static
  24606. * @param {string} hex - a hex string to convert
  24607. * @returns {Address4}
  24608. */
  24609. static fromHex(hex) {
  24610. const padded = hex.replace(/:/g, "").padStart(8, "0");
  24611. const groups = [];
  24612. let i;
  24613. for (i = 0; i < 8; i += 2) {
  24614. const h = padded.slice(i, i + 2);
  24615. groups.push(parseInt(h, 16));
  24616. }
  24617. return new _Address4(groups.join("."));
  24618. }
  24619. /**
  24620. * Converts an integer into a IPv4 address object
  24621. * @memberof Address4
  24622. * @static
  24623. * @param {integer} integer - a number to convert
  24624. * @returns {Address4}
  24625. */
  24626. static fromInteger(integer) {
  24627. return _Address4.fromHex(integer.toString(16));
  24628. }
  24629. /**
  24630. * Return an address from in-addr.arpa form
  24631. * @memberof Address4
  24632. * @static
  24633. * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address
  24634. * @returns {Adress4}
  24635. * @example
  24636. * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.)
  24637. * address.correctForm(); // '192.0.2.42'
  24638. */
  24639. static fromArpa(arpaFormAddress) {
  24640. const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, "");
  24641. const address = leader.split(".").reverse().join(".");
  24642. return new _Address4(address);
  24643. }
  24644. /**
  24645. * Converts an IPv4 address object to a hex string
  24646. * @memberof Address4
  24647. * @instance
  24648. * @returns {String}
  24649. */
  24650. toHex() {
  24651. return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)("%02x", parseInt(part, 10))).join(":");
  24652. }
  24653. /**
  24654. * Converts an IPv4 address object to an array of bytes
  24655. * @memberof Address4
  24656. * @instance
  24657. * @returns {Array}
  24658. */
  24659. toArray() {
  24660. return this.parsedAddress.map((part) => parseInt(part, 10));
  24661. }
  24662. /**
  24663. * Converts an IPv4 address object to an IPv6 address group
  24664. * @memberof Address4
  24665. * @instance
  24666. * @returns {String}
  24667. */
  24668. toGroup6() {
  24669. const output = [];
  24670. let i;
  24671. for (i = 0; i < constants.GROUPS; i += 2) {
  24672. const hex = (0, sprintf_js_1.sprintf)("%02x%02x", parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10));
  24673. output.push((0, sprintf_js_1.sprintf)("%x", parseInt(hex, 16)));
  24674. }
  24675. return output.join(":");
  24676. }
  24677. /**
  24678. * Returns the address as a BigInteger
  24679. * @memberof Address4
  24680. * @instance
  24681. * @returns {BigInteger}
  24682. */
  24683. bigInteger() {
  24684. return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)("%02x", parseInt(n, 10))).join(""), 16);
  24685. }
  24686. /**
  24687. * Helper function getting start address.
  24688. * @memberof Address4
  24689. * @instance
  24690. * @returns {BigInteger}
  24691. */
  24692. _startAddress() {
  24693. return new jsbn_1.BigInteger(this.mask() + "0".repeat(constants.BITS - this.subnetMask), 2);
  24694. }
  24695. /**
  24696. * The first address in the range given by this address' subnet.
  24697. * Often referred to as the Network Address.
  24698. * @memberof Address4
  24699. * @instance
  24700. * @returns {Address4}
  24701. */
  24702. startAddress() {
  24703. return _Address4.fromBigInteger(this._startAddress());
  24704. }
  24705. /**
  24706. * The first host address in the range given by this address's subnet ie
  24707. * the first address after the Network Address
  24708. * @memberof Address4
  24709. * @instance
  24710. * @returns {Address4}
  24711. */
  24712. startAddressExclusive() {
  24713. const adjust = new jsbn_1.BigInteger("1");
  24714. return _Address4.fromBigInteger(this._startAddress().add(adjust));
  24715. }
  24716. /**
  24717. * Helper function getting end address.
  24718. * @memberof Address4
  24719. * @instance
  24720. * @returns {BigInteger}
  24721. */
  24722. _endAddress() {
  24723. return new jsbn_1.BigInteger(this.mask() + "1".repeat(constants.BITS - this.subnetMask), 2);
  24724. }
  24725. /**
  24726. * The last address in the range given by this address' subnet
  24727. * Often referred to as the Broadcast
  24728. * @memberof Address4
  24729. * @instance
  24730. * @returns {Address4}
  24731. */
  24732. endAddress() {
  24733. return _Address4.fromBigInteger(this._endAddress());
  24734. }
  24735. /**
  24736. * The last host address in the range given by this address's subnet ie
  24737. * the last address prior to the Broadcast Address
  24738. * @memberof Address4
  24739. * @instance
  24740. * @returns {Address4}
  24741. */
  24742. endAddressExclusive() {
  24743. const adjust = new jsbn_1.BigInteger("1");
  24744. return _Address4.fromBigInteger(this._endAddress().subtract(adjust));
  24745. }
  24746. /**
  24747. * Converts a BigInteger to a v4 address object
  24748. * @memberof Address4
  24749. * @static
  24750. * @param {BigInteger} bigInteger - a BigInteger to convert
  24751. * @returns {Address4}
  24752. */
  24753. static fromBigInteger(bigInteger) {
  24754. return _Address4.fromInteger(parseInt(bigInteger.toString(), 10));
  24755. }
  24756. /**
  24757. * Returns the first n bits of the address, defaulting to the
  24758. * subnet mask
  24759. * @memberof Address4
  24760. * @instance
  24761. * @returns {String}
  24762. */
  24763. mask(mask) {
  24764. if (mask === void 0) {
  24765. mask = this.subnetMask;
  24766. }
  24767. return this.getBitsBase2(0, mask);
  24768. }
  24769. /**
  24770. * Returns the bits in the given range as a base-2 string
  24771. * @memberof Address4
  24772. * @instance
  24773. * @returns {string}
  24774. */
  24775. getBitsBase2(start, end) {
  24776. return this.binaryZeroPad().slice(start, end);
  24777. }
  24778. /**
  24779. * Return the reversed ip6.arpa form of the address
  24780. * @memberof Address4
  24781. * @param {Object} options
  24782. * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix
  24783. * @instance
  24784. * @returns {String}
  24785. */
  24786. reverseForm(options) {
  24787. if (!options) {
  24788. options = {};
  24789. }
  24790. const reversed = this.correctForm().split(".").reverse().join(".");
  24791. if (options.omitSuffix) {
  24792. return reversed;
  24793. }
  24794. return (0, sprintf_js_1.sprintf)("%s.in-addr.arpa.", reversed);
  24795. }
  24796. /**
  24797. * Returns true if the given address is a multicast address
  24798. * @memberof Address4
  24799. * @instance
  24800. * @returns {boolean}
  24801. */
  24802. isMulticast() {
  24803. return this.isInSubnet(new _Address4("224.0.0.0/4"));
  24804. }
  24805. /**
  24806. * Returns a zero-padded base-2 string representation of the address
  24807. * @memberof Address4
  24808. * @instance
  24809. * @returns {string}
  24810. */
  24811. binaryZeroPad() {
  24812. return this.bigInteger().toString(2).padStart(constants.BITS, "0");
  24813. }
  24814. /**
  24815. * Groups an IPv4 address for inclusion at the end of an IPv6 address
  24816. * @returns {String}
  24817. */
  24818. groupForV6() {
  24819. const segments = this.parsedAddress;
  24820. return this.address.replace(constants.RE_ADDRESS, (0, sprintf_js_1.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>', segments.slice(0, 2).join("."), segments.slice(2, 4).join(".")));
  24821. }
  24822. };
  24823. __name(_Address4, "Address4");
  24824. var Address4 = _Address4;
  24825. exports2.Address4 = Address4;
  24826. }
  24827. });
  24828. // node_modules/ip-address/dist/v6/constants.js
  24829. var require_constants5 = __commonJS({
  24830. "node_modules/ip-address/dist/v6/constants.js"(exports2) {
  24831. "use strict";
  24832. Object.defineProperty(exports2, "__esModule", { value: true });
  24833. exports2.RE_URL_WITH_PORT = exports2.RE_URL = exports2.RE_ZONE_STRING = exports2.RE_SUBNET_STRING = exports2.RE_BAD_ADDRESS = exports2.RE_BAD_CHARACTERS = exports2.TYPES = exports2.SCOPES = exports2.GROUPS = exports2.BITS = void 0;
  24834. exports2.BITS = 128;
  24835. exports2.GROUPS = 8;
  24836. exports2.SCOPES = {
  24837. 0: "Reserved",
  24838. 1: "Interface local",
  24839. 2: "Link local",
  24840. 4: "Admin local",
  24841. 5: "Site local",
  24842. 8: "Organization local",
  24843. 14: "Global",
  24844. 15: "Reserved"
  24845. };
  24846. exports2.TYPES = {
  24847. "ff01::1/128": "Multicast (All nodes on this interface)",
  24848. "ff01::2/128": "Multicast (All routers on this interface)",
  24849. "ff02::1/128": "Multicast (All nodes on this link)",
  24850. "ff02::2/128": "Multicast (All routers on this link)",
  24851. "ff05::2/128": "Multicast (All routers in this site)",
  24852. "ff02::5/128": "Multicast (OSPFv3 AllSPF routers)",
  24853. "ff02::6/128": "Multicast (OSPFv3 AllDR routers)",
  24854. "ff02::9/128": "Multicast (RIP routers)",
  24855. "ff02::a/128": "Multicast (EIGRP routers)",
  24856. "ff02::d/128": "Multicast (PIM routers)",
  24857. "ff02::16/128": "Multicast (MLDv2 reports)",
  24858. "ff01::fb/128": "Multicast (mDNSv6)",
  24859. "ff02::fb/128": "Multicast (mDNSv6)",
  24860. "ff05::fb/128": "Multicast (mDNSv6)",
  24861. "ff02::1:2/128": "Multicast (All DHCP servers and relay agents on this link)",
  24862. "ff05::1:2/128": "Multicast (All DHCP servers and relay agents in this site)",
  24863. "ff02::1:3/128": "Multicast (All DHCP servers on this link)",
  24864. "ff05::1:3/128": "Multicast (All DHCP servers in this site)",
  24865. "::/128": "Unspecified",
  24866. "::1/128": "Loopback",
  24867. "ff00::/8": "Multicast",
  24868. "fe80::/10": "Link-local unicast"
  24869. };
  24870. exports2.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi;
  24871. exports2.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;
  24872. exports2.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/;
  24873. exports2.RE_ZONE_STRING = /%.*$/;
  24874. exports2.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/);
  24875. exports2.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);
  24876. }
  24877. });
  24878. // node_modules/ip-address/dist/v6/helpers.js
  24879. var require_helpers = __commonJS({
  24880. "node_modules/ip-address/dist/v6/helpers.js"(exports2) {
  24881. "use strict";
  24882. Object.defineProperty(exports2, "__esModule", { value: true });
  24883. exports2.simpleGroup = exports2.spanLeadingZeroes = exports2.spanAll = exports2.spanAllZeroes = void 0;
  24884. var sprintf_js_1 = require_sprintf();
  24885. function spanAllZeroes(s) {
  24886. return s.replace(/(0+)/g, '<span class="zero">$1</span>');
  24887. }
  24888. __name(spanAllZeroes, "spanAllZeroes");
  24889. exports2.spanAllZeroes = spanAllZeroes;
  24890. function spanAll(s, offset = 0) {
  24891. const letters = s.split("");
  24892. return letters.map(
  24893. (n, i) => (0, sprintf_js_1.sprintf)('<span class="digit value-%s position-%d">%s</span>', n, i + offset, spanAllZeroes(n))
  24894. // XXX Use #base-2 .value-0 instead?
  24895. ).join("");
  24896. }
  24897. __name(spanAll, "spanAll");
  24898. exports2.spanAll = spanAll;
  24899. function spanLeadingZeroesSimple(group) {
  24900. return group.replace(/^(0+)/, '<span class="zero">$1</span>');
  24901. }
  24902. __name(spanLeadingZeroesSimple, "spanLeadingZeroesSimple");
  24903. function spanLeadingZeroes(address) {
  24904. const groups = address.split(":");
  24905. return groups.map((g) => spanLeadingZeroesSimple(g)).join(":");
  24906. }
  24907. __name(spanLeadingZeroes, "spanLeadingZeroes");
  24908. exports2.spanLeadingZeroes = spanLeadingZeroes;
  24909. function simpleGroup(addressString, offset = 0) {
  24910. const groups = addressString.split(":");
  24911. return groups.map((g, i) => {
  24912. if (/group-v4/.test(g)) {
  24913. return g;
  24914. }
  24915. return (0, sprintf_js_1.sprintf)('<span class="hover-group group-%d">%s</span>', i + offset, spanLeadingZeroesSimple(g));
  24916. });
  24917. }
  24918. __name(simpleGroup, "simpleGroup");
  24919. exports2.simpleGroup = simpleGroup;
  24920. }
  24921. });
  24922. // node_modules/ip-address/dist/v6/regular-expressions.js
  24923. var require_regular_expressions = __commonJS({
  24924. "node_modules/ip-address/dist/v6/regular-expressions.js"(exports2) {
  24925. "use strict";
  24926. var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
  24927. if (k2 === void 0) k2 = k;
  24928. var desc = Object.getOwnPropertyDescriptor(m, k);
  24929. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  24930. desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
  24931. return m[k];
  24932. }, "get") };
  24933. }
  24934. Object.defineProperty(o, k2, desc);
  24935. } : function(o, m, k, k2) {
  24936. if (k2 === void 0) k2 = k;
  24937. o[k2] = m[k];
  24938. });
  24939. var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
  24940. Object.defineProperty(o, "default", { enumerable: true, value: v });
  24941. } : function(o, v) {
  24942. o["default"] = v;
  24943. });
  24944. var __importStar = exports2 && exports2.__importStar || function(mod) {
  24945. if (mod && mod.__esModule) return mod;
  24946. var result = {};
  24947. if (mod != null) {
  24948. for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  24949. }
  24950. __setModuleDefault(result, mod);
  24951. return result;
  24952. };
  24953. Object.defineProperty(exports2, "__esModule", { value: true });
  24954. exports2.possibleElisions = exports2.simpleRegularExpression = exports2.ADDRESS_BOUNDARY = exports2.padGroup = exports2.groupPossibilities = void 0;
  24955. var v6 = __importStar(require_constants5());
  24956. var sprintf_js_1 = require_sprintf();
  24957. function groupPossibilities(possibilities) {
  24958. return (0, sprintf_js_1.sprintf)("(%s)", possibilities.join("|"));
  24959. }
  24960. __name(groupPossibilities, "groupPossibilities");
  24961. exports2.groupPossibilities = groupPossibilities;
  24962. function padGroup(group) {
  24963. if (group.length < 4) {
  24964. return (0, sprintf_js_1.sprintf)("0{0,%d}%s", 4 - group.length, group);
  24965. }
  24966. return group;
  24967. }
  24968. __name(padGroup, "padGroup");
  24969. exports2.padGroup = padGroup;
  24970. exports2.ADDRESS_BOUNDARY = "[^A-Fa-f0-9:]";
  24971. function simpleRegularExpression(groups) {
  24972. const zeroIndexes = [];
  24973. groups.forEach((group, i) => {
  24974. const groupInteger = parseInt(group, 16);
  24975. if (groupInteger === 0) {
  24976. zeroIndexes.push(i);
  24977. }
  24978. });
  24979. const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i) => {
  24980. if (i === zeroIndex) {
  24981. const elision = i === 0 || i === v6.GROUPS - 1 ? ":" : "";
  24982. return groupPossibilities([padGroup(group), elision]);
  24983. }
  24984. return padGroup(group);
  24985. }).join(":"));
  24986. possibilities.push(groups.map(padGroup).join(":"));
  24987. return groupPossibilities(possibilities);
  24988. }
  24989. __name(simpleRegularExpression, "simpleRegularExpression");
  24990. exports2.simpleRegularExpression = simpleRegularExpression;
  24991. function possibleElisions(elidedGroups, moreLeft, moreRight) {
  24992. const left = moreLeft ? "" : ":";
  24993. const right = moreRight ? "" : ":";
  24994. const possibilities = [];
  24995. if (!moreLeft && !moreRight) {
  24996. possibilities.push("::");
  24997. }
  24998. if (moreLeft && moreRight) {
  24999. possibilities.push("");
  25000. }
  25001. if (moreRight && !moreLeft || !moreRight && moreLeft) {
  25002. possibilities.push(":");
  25003. }
  25004. possibilities.push((0, sprintf_js_1.sprintf)("%s(:0{1,4}){1,%d}", left, elidedGroups - 1));
  25005. possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){1,%d}%s", elidedGroups - 1, right));
  25006. possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){%d}0{1,4}", elidedGroups - 1));
  25007. for (let groups = 1; groups < elidedGroups - 1; groups++) {
  25008. for (let position = 1; position < elidedGroups - groups; position++) {
  25009. possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}", position, elidedGroups - position - groups - 1));
  25010. }
  25011. }
  25012. return groupPossibilities(possibilities);
  25013. }
  25014. __name(possibleElisions, "possibleElisions");
  25015. exports2.possibleElisions = possibleElisions;
  25016. }
  25017. });
  25018. // node_modules/ip-address/dist/ipv6.js
  25019. var require_ipv6 = __commonJS({
  25020. "node_modules/ip-address/dist/ipv6.js"(exports2) {
  25021. "use strict";
  25022. var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
  25023. if (k2 === void 0) k2 = k;
  25024. var desc = Object.getOwnPropertyDescriptor(m, k);
  25025. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  25026. desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
  25027. return m[k];
  25028. }, "get") };
  25029. }
  25030. Object.defineProperty(o, k2, desc);
  25031. } : function(o, m, k, k2) {
  25032. if (k2 === void 0) k2 = k;
  25033. o[k2] = m[k];
  25034. });
  25035. var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
  25036. Object.defineProperty(o, "default", { enumerable: true, value: v });
  25037. } : function(o, v) {
  25038. o["default"] = v;
  25039. });
  25040. var __importStar = exports2 && exports2.__importStar || function(mod) {
  25041. if (mod && mod.__esModule) return mod;
  25042. var result = {};
  25043. if (mod != null) {
  25044. for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  25045. }
  25046. __setModuleDefault(result, mod);
  25047. return result;
  25048. };
  25049. Object.defineProperty(exports2, "__esModule", { value: true });
  25050. exports2.Address6 = void 0;
  25051. var common = __importStar(require_common3());
  25052. var constants4 = __importStar(require_constants4());
  25053. var constants6 = __importStar(require_constants5());
  25054. var helpers = __importStar(require_helpers());
  25055. var ipv4_1 = require_ipv4();
  25056. var regular_expressions_1 = require_regular_expressions();
  25057. var address_error_1 = require_address_error();
  25058. var jsbn_1 = require_jsbn();
  25059. var sprintf_js_1 = require_sprintf();
  25060. function assert(condition) {
  25061. if (!condition) {
  25062. throw new Error("Assertion failed.");
  25063. }
  25064. }
  25065. __name(assert, "assert");
  25066. function addCommas(number) {
  25067. const r = /(\d+)(\d{3})/;
  25068. while (r.test(number)) {
  25069. number = number.replace(r, "$1,$2");
  25070. }
  25071. return number;
  25072. }
  25073. __name(addCommas, "addCommas");
  25074. function spanLeadingZeroes4(n) {
  25075. n = n.replace(/^(0{1,})([1-9]+)$/, '<span class="parse-error">$1</span>$2');
  25076. n = n.replace(/^(0{1,})(0)$/, '<span class="parse-error">$1</span>$2');
  25077. return n;
  25078. }
  25079. __name(spanLeadingZeroes4, "spanLeadingZeroes4");
  25080. function compact(address, slice) {
  25081. const s1 = [];
  25082. const s2 = [];
  25083. let i;
  25084. for (i = 0; i < address.length; i++) {
  25085. if (i < slice[0]) {
  25086. s1.push(address[i]);
  25087. } else if (i > slice[1]) {
  25088. s2.push(address[i]);
  25089. }
  25090. }
  25091. return s1.concat(["compact"]).concat(s2);
  25092. }
  25093. __name(compact, "compact");
  25094. function paddedHex(octet) {
  25095. return (0, sprintf_js_1.sprintf)("%04x", parseInt(octet, 16));
  25096. }
  25097. __name(paddedHex, "paddedHex");
  25098. function unsignByte(b) {
  25099. return b & 255;
  25100. }
  25101. __name(unsignByte, "unsignByte");
  25102. var _Address6 = class _Address6 {
  25103. constructor(address, optionalGroups) {
  25104. this.addressMinusSuffix = "";
  25105. this.parsedSubnet = "";
  25106. this.subnet = "/128";
  25107. this.subnetMask = 128;
  25108. this.v4 = false;
  25109. this.zone = "";
  25110. this.isInSubnet = common.isInSubnet;
  25111. this.isCorrect = common.isCorrect(constants6.BITS);
  25112. if (optionalGroups === void 0) {
  25113. this.groups = constants6.GROUPS;
  25114. } else {
  25115. this.groups = optionalGroups;
  25116. }
  25117. this.address = address;
  25118. const subnet = constants6.RE_SUBNET_STRING.exec(address);
  25119. if (subnet) {
  25120. this.parsedSubnet = subnet[0].replace("/", "");
  25121. this.subnetMask = parseInt(this.parsedSubnet, 10);
  25122. this.subnet = `/${this.subnetMask}`;
  25123. if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) {
  25124. throw new address_error_1.AddressError("Invalid subnet mask.");
  25125. }
  25126. address = address.replace(constants6.RE_SUBNET_STRING, "");
  25127. } else if (/\//.test(address)) {
  25128. throw new address_error_1.AddressError("Invalid subnet mask.");
  25129. }
  25130. const zone = constants6.RE_ZONE_STRING.exec(address);
  25131. if (zone) {
  25132. this.zone = zone[0];
  25133. address = address.replace(constants6.RE_ZONE_STRING, "");
  25134. }
  25135. this.addressMinusSuffix = address;
  25136. this.parsedAddress = this.parse(this.addressMinusSuffix);
  25137. }
  25138. static isValid(address) {
  25139. try {
  25140. new _Address6(address);
  25141. return true;
  25142. } catch (e) {
  25143. return false;
  25144. }
  25145. }
  25146. /**
  25147. * Convert a BigInteger to a v6 address object
  25148. * @memberof Address6
  25149. * @static
  25150. * @param {BigInteger} bigInteger - a BigInteger to convert
  25151. * @returns {Address6}
  25152. * @example
  25153. * var bigInteger = new BigInteger('1000000000000');
  25154. * var address = Address6.fromBigInteger(bigInteger);
  25155. * address.correctForm(); // '::e8:d4a5:1000'
  25156. */
  25157. static fromBigInteger(bigInteger) {
  25158. const hex = bigInteger.toString(16).padStart(32, "0");
  25159. const groups = [];
  25160. let i;
  25161. for (i = 0; i < constants6.GROUPS; i++) {
  25162. groups.push(hex.slice(i * 4, (i + 1) * 4));
  25163. }
  25164. return new _Address6(groups.join(":"));
  25165. }
  25166. /**
  25167. * Convert a URL (with optional port number) to an address object
  25168. * @memberof Address6
  25169. * @static
  25170. * @param {string} url - a URL with optional port number
  25171. * @example
  25172. * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/');
  25173. * addressAndPort.address.correctForm(); // 'ffff::'
  25174. * addressAndPort.port; // 8080
  25175. */
  25176. static fromURL(url) {
  25177. let host;
  25178. let port = null;
  25179. let result;
  25180. if (url.indexOf("[") !== -1 && url.indexOf("]:") !== -1) {
  25181. result = constants6.RE_URL_WITH_PORT.exec(url);
  25182. if (result === null) {
  25183. return {
  25184. error: "failed to parse address with port",
  25185. address: null,
  25186. port: null
  25187. };
  25188. }
  25189. host = result[1];
  25190. port = result[2];
  25191. } else if (url.indexOf("/") !== -1) {
  25192. url = url.replace(/^[a-z0-9]+:\/\//, "");
  25193. result = constants6.RE_URL.exec(url);
  25194. if (result === null) {
  25195. return {
  25196. error: "failed to parse address from URL",
  25197. address: null,
  25198. port: null
  25199. };
  25200. }
  25201. host = result[1];
  25202. } else {
  25203. host = url;
  25204. }
  25205. if (port) {
  25206. port = parseInt(port, 10);
  25207. if (port < 0 || port > 65536) {
  25208. port = null;
  25209. }
  25210. } else {
  25211. port = null;
  25212. }
  25213. return {
  25214. address: new _Address6(host),
  25215. port
  25216. };
  25217. }
  25218. /**
  25219. * Create an IPv6-mapped address given an IPv4 address
  25220. * @memberof Address6
  25221. * @static
  25222. * @param {string} address - An IPv4 address string
  25223. * @returns {Address6}
  25224. * @example
  25225. * var address = Address6.fromAddress4('192.168.0.1');
  25226. * address.correctForm(); // '::ffff:c0a8:1'
  25227. * address.to4in6(); // '::ffff:192.168.0.1'
  25228. */
  25229. static fromAddress4(address) {
  25230. const address4 = new ipv4_1.Address4(address);
  25231. const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask);
  25232. return new _Address6(`::ffff:${address4.correctForm()}/${mask6}`);
  25233. }
  25234. /**
  25235. * Return an address from ip6.arpa form
  25236. * @memberof Address6
  25237. * @static
  25238. * @param {string} arpaFormAddress - an 'ip6.arpa' form address
  25239. * @returns {Adress6}
  25240. * @example
  25241. * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.)
  25242. * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe'
  25243. */
  25244. static fromArpa(arpaFormAddress) {
  25245. let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, "");
  25246. const semicolonAmount = 7;
  25247. if (address.length !== 63) {
  25248. throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");
  25249. }
  25250. const parts = address.split(".").reverse();
  25251. for (let i = semicolonAmount; i > 0; i--) {
  25252. const insertIndex = i * 4;
  25253. parts.splice(insertIndex, 0, ":");
  25254. }
  25255. address = parts.join("");
  25256. return new _Address6(address);
  25257. }
  25258. /**
  25259. * Return the Microsoft UNC transcription of the address
  25260. * @memberof Address6
  25261. * @instance
  25262. * @returns {String} the Microsoft UNC transcription of the address
  25263. */
  25264. microsoftTranscription() {
  25265. return (0, sprintf_js_1.sprintf)("%s.ipv6-literal.net", this.correctForm().replace(/:/g, "-"));
  25266. }
  25267. /**
  25268. * Return the first n bits of the address, defaulting to the subnet mask
  25269. * @memberof Address6
  25270. * @instance
  25271. * @param {number} [mask=subnet] - the number of bits to mask
  25272. * @returns {String} the first n bits of the address as a string
  25273. */
  25274. mask(mask = this.subnetMask) {
  25275. return this.getBitsBase2(0, mask);
  25276. }
  25277. /**
  25278. * Return the number of possible subnets of a given size in the address
  25279. * @memberof Address6
  25280. * @instance
  25281. * @param {number} [size=128] - the subnet size
  25282. * @returns {String}
  25283. */
  25284. // TODO: probably useful to have a numeric version of this too
  25285. possibleSubnets(subnetSize = 128) {
  25286. const availableBits = constants6.BITS - this.subnetMask;
  25287. const subnetBits = Math.abs(subnetSize - constants6.BITS);
  25288. const subnetPowers = availableBits - subnetBits;
  25289. if (subnetPowers < 0) {
  25290. return "0";
  25291. }
  25292. return addCommas(new jsbn_1.BigInteger("2", 10).pow(subnetPowers).toString(10));
  25293. }
  25294. /**
  25295. * Helper function getting start address.
  25296. * @memberof Address6
  25297. * @instance
  25298. * @returns {BigInteger}
  25299. */
  25300. _startAddress() {
  25301. return new jsbn_1.BigInteger(this.mask() + "0".repeat(constants6.BITS - this.subnetMask), 2);
  25302. }
  25303. /**
  25304. * The first address in the range given by this address' subnet
  25305. * Often referred to as the Network Address.
  25306. * @memberof Address6
  25307. * @instance
  25308. * @returns {Address6}
  25309. */
  25310. startAddress() {
  25311. return _Address6.fromBigInteger(this._startAddress());
  25312. }
  25313. /**
  25314. * The first host address in the range given by this address's subnet ie
  25315. * the first address after the Network Address
  25316. * @memberof Address6
  25317. * @instance
  25318. * @returns {Address6}
  25319. */
  25320. startAddressExclusive() {
  25321. const adjust = new jsbn_1.BigInteger("1");
  25322. return _Address6.fromBigInteger(this._startAddress().add(adjust));
  25323. }
  25324. /**
  25325. * Helper function getting end address.
  25326. * @memberof Address6
  25327. * @instance
  25328. * @returns {BigInteger}
  25329. */
  25330. _endAddress() {
  25331. return new jsbn_1.BigInteger(this.mask() + "1".repeat(constants6.BITS - this.subnetMask), 2);
  25332. }
  25333. /**
  25334. * The last address in the range given by this address' subnet
  25335. * Often referred to as the Broadcast
  25336. * @memberof Address6
  25337. * @instance
  25338. * @returns {Address6}
  25339. */
  25340. endAddress() {
  25341. return _Address6.fromBigInteger(this._endAddress());
  25342. }
  25343. /**
  25344. * The last host address in the range given by this address's subnet ie
  25345. * the last address prior to the Broadcast Address
  25346. * @memberof Address6
  25347. * @instance
  25348. * @returns {Address6}
  25349. */
  25350. endAddressExclusive() {
  25351. const adjust = new jsbn_1.BigInteger("1");
  25352. return _Address6.fromBigInteger(this._endAddress().subtract(adjust));
  25353. }
  25354. /**
  25355. * Return the scope of the address
  25356. * @memberof Address6
  25357. * @instance
  25358. * @returns {String}
  25359. */
  25360. getScope() {
  25361. let scope = constants6.SCOPES[this.getBits(12, 16).intValue()];
  25362. if (this.getType() === "Global unicast" && scope !== "Link local") {
  25363. scope = "Global";
  25364. }
  25365. return scope || "Unknown";
  25366. }
  25367. /**
  25368. * Return the type of the address
  25369. * @memberof Address6
  25370. * @instance
  25371. * @returns {String}
  25372. */
  25373. getType() {
  25374. for (const subnet of Object.keys(constants6.TYPES)) {
  25375. if (this.isInSubnet(new _Address6(subnet))) {
  25376. return constants6.TYPES[subnet];
  25377. }
  25378. }
  25379. return "Global unicast";
  25380. }
  25381. /**
  25382. * Return the bits in the given range as a BigInteger
  25383. * @memberof Address6
  25384. * @instance
  25385. * @returns {BigInteger}
  25386. */
  25387. getBits(start, end) {
  25388. return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2);
  25389. }
  25390. /**
  25391. * Return the bits in the given range as a base-2 string
  25392. * @memberof Address6
  25393. * @instance
  25394. * @returns {String}
  25395. */
  25396. getBitsBase2(start, end) {
  25397. return this.binaryZeroPad().slice(start, end);
  25398. }
  25399. /**
  25400. * Return the bits in the given range as a base-16 string
  25401. * @memberof Address6
  25402. * @instance
  25403. * @returns {String}
  25404. */
  25405. getBitsBase16(start, end) {
  25406. const length = end - start;
  25407. if (length % 4 !== 0) {
  25408. throw new Error("Length of bits to retrieve must be divisible by four");
  25409. }
  25410. return this.getBits(start, end).toString(16).padStart(length / 4, "0");
  25411. }
  25412. /**
  25413. * Return the bits that are set past the subnet mask length
  25414. * @memberof Address6
  25415. * @instance
  25416. * @returns {String}
  25417. */
  25418. getBitsPastSubnet() {
  25419. return this.getBitsBase2(this.subnetMask, constants6.BITS);
  25420. }
  25421. /**
  25422. * Return the reversed ip6.arpa form of the address
  25423. * @memberof Address6
  25424. * @param {Object} options
  25425. * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix
  25426. * @instance
  25427. * @returns {String}
  25428. */
  25429. reverseForm(options) {
  25430. if (!options) {
  25431. options = {};
  25432. }
  25433. const characters = Math.floor(this.subnetMask / 4);
  25434. const reversed = this.canonicalForm().replace(/:/g, "").split("").slice(0, characters).reverse().join(".");
  25435. if (characters > 0) {
  25436. if (options.omitSuffix) {
  25437. return reversed;
  25438. }
  25439. return (0, sprintf_js_1.sprintf)("%s.ip6.arpa.", reversed);
  25440. }
  25441. if (options.omitSuffix) {
  25442. return "";
  25443. }
  25444. return "ip6.arpa.";
  25445. }
  25446. /**
  25447. * Return the correct form of the address
  25448. * @memberof Address6
  25449. * @instance
  25450. * @returns {String}
  25451. */
  25452. correctForm() {
  25453. let i;
  25454. let groups = [];
  25455. let zeroCounter = 0;
  25456. const zeroes = [];
  25457. for (i = 0; i < this.parsedAddress.length; i++) {
  25458. const value = parseInt(this.parsedAddress[i], 16);
  25459. if (value === 0) {
  25460. zeroCounter++;
  25461. }
  25462. if (value !== 0 && zeroCounter > 0) {
  25463. if (zeroCounter > 1) {
  25464. zeroes.push([i - zeroCounter, i - 1]);
  25465. }
  25466. zeroCounter = 0;
  25467. }
  25468. }
  25469. if (zeroCounter > 1) {
  25470. zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]);
  25471. }
  25472. const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1);
  25473. if (zeroes.length > 0) {
  25474. const index = zeroLengths.indexOf(Math.max(...zeroLengths));
  25475. groups = compact(this.parsedAddress, zeroes[index]);
  25476. } else {
  25477. groups = this.parsedAddress;
  25478. }
  25479. for (i = 0; i < groups.length; i++) {
  25480. if (groups[i] !== "compact") {
  25481. groups[i] = parseInt(groups[i], 16).toString(16);
  25482. }
  25483. }
  25484. let correct = groups.join(":");
  25485. correct = correct.replace(/^compact$/, "::");
  25486. correct = correct.replace(/^compact|compact$/, ":");
  25487. correct = correct.replace(/compact/, "");
  25488. return correct;
  25489. }
  25490. /**
  25491. * Return a zero-padded base-2 string representation of the address
  25492. * @memberof Address6
  25493. * @instance
  25494. * @returns {String}
  25495. * @example
  25496. * var address = new Address6('2001:4860:4001:803::1011');
  25497. * address.binaryZeroPad();
  25498. * // '0010000000000001010010000110000001000000000000010000100000000011
  25499. * // 0000000000000000000000000000000000000000000000000001000000010001'
  25500. */
  25501. binaryZeroPad() {
  25502. return this.bigInteger().toString(2).padStart(constants6.BITS, "0");
  25503. }
  25504. // TODO: Improve the semantics of this helper function
  25505. parse4in6(address) {
  25506. const groups = address.split(":");
  25507. const lastGroup = groups.slice(-1)[0];
  25508. const address4 = lastGroup.match(constants4.RE_ADDRESS);
  25509. if (address4) {
  25510. this.parsedAddress4 = address4[0];
  25511. this.address4 = new ipv4_1.Address4(this.parsedAddress4);
  25512. for (let i = 0; i < this.address4.groups; i++) {
  25513. if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) {
  25514. throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join(".")));
  25515. }
  25516. }
  25517. this.v4 = true;
  25518. groups[groups.length - 1] = this.address4.toGroup6();
  25519. address = groups.join(":");
  25520. }
  25521. return address;
  25522. }
  25523. // TODO: Make private?
  25524. parse(address) {
  25525. address = this.parse4in6(address);
  25526. const badCharacters = address.match(constants6.RE_BAD_CHARACTERS);
  25527. if (badCharacters) {
  25528. throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)("Bad character%s detected in address: %s", badCharacters.length > 1 ? "s" : "", badCharacters.join("")), address.replace(constants6.RE_BAD_CHARACTERS, '<span class="parse-error">$1</span>'));
  25529. }
  25530. const badAddress = address.match(constants6.RE_BAD_ADDRESS);
  25531. if (badAddress) {
  25532. throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)("Address failed regex: %s", badAddress.join("")), address.replace(constants6.RE_BAD_ADDRESS, '<span class="parse-error">$1</span>'));
  25533. }
  25534. let groups = [];
  25535. const halves = address.split("::");
  25536. if (halves.length === 2) {
  25537. let first = halves[0].split(":");
  25538. let last = halves[1].split(":");
  25539. if (first.length === 1 && first[0] === "") {
  25540. first = [];
  25541. }
  25542. if (last.length === 1 && last[0] === "") {
  25543. last = [];
  25544. }
  25545. const remaining = this.groups - (first.length + last.length);
  25546. if (!remaining) {
  25547. throw new address_error_1.AddressError("Error parsing groups");
  25548. }
  25549. this.elidedGroups = remaining;
  25550. this.elisionBegin = first.length;
  25551. this.elisionEnd = first.length + this.elidedGroups;
  25552. groups = groups.concat(first);
  25553. for (let i = 0; i < remaining; i++) {
  25554. groups.push("0");
  25555. }
  25556. groups = groups.concat(last);
  25557. } else if (halves.length === 1) {
  25558. groups = address.split(":");
  25559. this.elidedGroups = 0;
  25560. } else {
  25561. throw new address_error_1.AddressError("Too many :: groups found");
  25562. }
  25563. groups = groups.map((group) => (0, sprintf_js_1.sprintf)("%x", parseInt(group, 16)));
  25564. if (groups.length !== this.groups) {
  25565. throw new address_error_1.AddressError("Incorrect number of groups found");
  25566. }
  25567. return groups;
  25568. }
  25569. /**
  25570. * Return the canonical form of the address
  25571. * @memberof Address6
  25572. * @instance
  25573. * @returns {String}
  25574. */
  25575. canonicalForm() {
  25576. return this.parsedAddress.map(paddedHex).join(":");
  25577. }
  25578. /**
  25579. * Return the decimal form of the address
  25580. * @memberof Address6
  25581. * @instance
  25582. * @returns {String}
  25583. */
  25584. decimal() {
  25585. return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)("%05d", parseInt(n, 16))).join(":");
  25586. }
  25587. /**
  25588. * Return the address as a BigInteger
  25589. * @memberof Address6
  25590. * @instance
  25591. * @returns {BigInteger}
  25592. */
  25593. bigInteger() {
  25594. return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(""), 16);
  25595. }
  25596. /**
  25597. * Return the last two groups of this address as an IPv4 address string
  25598. * @memberof Address6
  25599. * @instance
  25600. * @returns {Address4}
  25601. * @example
  25602. * var address = new Address6('2001:4860:4001::1825:bf11');
  25603. * address.to4().correctForm(); // '24.37.191.17'
  25604. */
  25605. to4() {
  25606. const binary = this.binaryZeroPad().split("");
  25607. return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(""), 2).toString(16));
  25608. }
  25609. /**
  25610. * Return the v4-in-v6 form of the address
  25611. * @memberof Address6
  25612. * @instance
  25613. * @returns {String}
  25614. */
  25615. to4in6() {
  25616. const address4 = this.to4();
  25617. const address6 = new _Address6(this.parsedAddress.slice(0, 6).join(":"), 6);
  25618. const correct = address6.correctForm();
  25619. let infix = "";
  25620. if (!/:$/.test(correct)) {
  25621. infix = ":";
  25622. }
  25623. return correct + infix + address4.address;
  25624. }
  25625. /**
  25626. * Return an object containing the Teredo properties of the address
  25627. * @memberof Address6
  25628. * @instance
  25629. * @returns {Object}
  25630. */
  25631. inspectTeredo() {
  25632. const prefix = this.getBitsBase16(0, 32);
  25633. const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger("ffff", 16)).toString();
  25634. const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
  25635. const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger("ffffffff", 16)).toString(16));
  25636. const flags = this.getBits(64, 80);
  25637. const flagsBase2 = this.getBitsBase2(64, 80);
  25638. const coneNat = flags.testBit(15);
  25639. const reserved = flags.testBit(14);
  25640. const groupIndividual = flags.testBit(8);
  25641. const universalLocal = flags.testBit(9);
  25642. const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10);
  25643. return {
  25644. prefix: (0, sprintf_js_1.sprintf)("%s:%s", prefix.slice(0, 4), prefix.slice(4, 8)),
  25645. server4: server4.address,
  25646. client4: client4.address,
  25647. flags: flagsBase2,
  25648. coneNat,
  25649. microsoft: {
  25650. reserved,
  25651. universalLocal,
  25652. groupIndividual,
  25653. nonce
  25654. },
  25655. udpPort
  25656. };
  25657. }
  25658. /**
  25659. * Return an object containing the 6to4 properties of the address
  25660. * @memberof Address6
  25661. * @instance
  25662. * @returns {Object}
  25663. */
  25664. inspect6to4() {
  25665. const prefix = this.getBitsBase16(0, 16);
  25666. const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48));
  25667. return {
  25668. prefix: (0, sprintf_js_1.sprintf)("%s", prefix.slice(0, 4)),
  25669. gateway: gateway.address
  25670. };
  25671. }
  25672. /**
  25673. * Return a v6 6to4 address from a v6 v4inv6 address
  25674. * @memberof Address6
  25675. * @instance
  25676. * @returns {Address6}
  25677. */
  25678. to6to4() {
  25679. if (!this.is4()) {
  25680. return null;
  25681. }
  25682. const addr6to4 = [
  25683. "2002",
  25684. this.getBitsBase16(96, 112),
  25685. this.getBitsBase16(112, 128),
  25686. "",
  25687. "/16"
  25688. ].join(":");
  25689. return new _Address6(addr6to4);
  25690. }
  25691. /**
  25692. * Return a byte array
  25693. * @memberof Address6
  25694. * @instance
  25695. * @returns {Array}
  25696. */
  25697. toByteArray() {
  25698. const byteArray = this.bigInteger().toByteArray();
  25699. if (byteArray.length === 17 && byteArray[0] === 0) {
  25700. return byteArray.slice(1);
  25701. }
  25702. return byteArray;
  25703. }
  25704. /**
  25705. * Return an unsigned byte array
  25706. * @memberof Address6
  25707. * @instance
  25708. * @returns {Array}
  25709. */
  25710. toUnsignedByteArray() {
  25711. return this.toByteArray().map(unsignByte);
  25712. }
  25713. /**
  25714. * Convert a byte array to an Address6 object
  25715. * @memberof Address6
  25716. * @static
  25717. * @returns {Address6}
  25718. */
  25719. static fromByteArray(bytes) {
  25720. return this.fromUnsignedByteArray(bytes.map(unsignByte));
  25721. }
  25722. /**
  25723. * Convert an unsigned byte array to an Address6 object
  25724. * @memberof Address6
  25725. * @static
  25726. * @returns {Address6}
  25727. */
  25728. static fromUnsignedByteArray(bytes) {
  25729. const BYTE_MAX = new jsbn_1.BigInteger("256", 10);
  25730. let result = new jsbn_1.BigInteger("0", 10);
  25731. let multiplier = new jsbn_1.BigInteger("1", 10);
  25732. for (let i = bytes.length - 1; i >= 0; i--) {
  25733. result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10)));
  25734. multiplier = multiplier.multiply(BYTE_MAX);
  25735. }
  25736. return _Address6.fromBigInteger(result);
  25737. }
  25738. /**
  25739. * Returns true if the address is in the canonical form, false otherwise
  25740. * @memberof Address6
  25741. * @instance
  25742. * @returns {boolean}
  25743. */
  25744. isCanonical() {
  25745. return this.addressMinusSuffix === this.canonicalForm();
  25746. }
  25747. /**
  25748. * Returns true if the address is a link local address, false otherwise
  25749. * @memberof Address6
  25750. * @instance
  25751. * @returns {boolean}
  25752. */
  25753. isLinkLocal() {
  25754. if (this.getBitsBase2(0, 64) === "1111111010000000000000000000000000000000000000000000000000000000") {
  25755. return true;
  25756. }
  25757. return false;
  25758. }
  25759. /**
  25760. * Returns true if the address is a multicast address, false otherwise
  25761. * @memberof Address6
  25762. * @instance
  25763. * @returns {boolean}
  25764. */
  25765. isMulticast() {
  25766. return this.getType() === "Multicast";
  25767. }
  25768. /**
  25769. * Returns true if the address is a v4-in-v6 address, false otherwise
  25770. * @memberof Address6
  25771. * @instance
  25772. * @returns {boolean}
  25773. */
  25774. is4() {
  25775. return this.v4;
  25776. }
  25777. /**
  25778. * Returns true if the address is a Teredo address, false otherwise
  25779. * @memberof Address6
  25780. * @instance
  25781. * @returns {boolean}
  25782. */
  25783. isTeredo() {
  25784. return this.isInSubnet(new _Address6("2001::/32"));
  25785. }
  25786. /**
  25787. * Returns true if the address is a 6to4 address, false otherwise
  25788. * @memberof Address6
  25789. * @instance
  25790. * @returns {boolean}
  25791. */
  25792. is6to4() {
  25793. return this.isInSubnet(new _Address6("2002::/16"));
  25794. }
  25795. /**
  25796. * Returns true if the address is a loopback address, false otherwise
  25797. * @memberof Address6
  25798. * @instance
  25799. * @returns {boolean}
  25800. */
  25801. isLoopback() {
  25802. return this.getType() === "Loopback";
  25803. }
  25804. // #endregion
  25805. // #region HTML
  25806. /**
  25807. * @returns {String} the address in link form with a default port of 80
  25808. */
  25809. href(optionalPort) {
  25810. if (optionalPort === void 0) {
  25811. optionalPort = "";
  25812. } else {
  25813. optionalPort = (0, sprintf_js_1.sprintf)(":%s", optionalPort);
  25814. }
  25815. return (0, sprintf_js_1.sprintf)("http://[%s]%s/", this.correctForm(), optionalPort);
  25816. }
  25817. /**
  25818. * @returns {String} a link suitable for conveying the address via a URL hash
  25819. */
  25820. link(options) {
  25821. if (!options) {
  25822. options = {};
  25823. }
  25824. if (options.className === void 0) {
  25825. options.className = "";
  25826. }
  25827. if (options.prefix === void 0) {
  25828. options.prefix = "/#address=";
  25829. }
  25830. if (options.v4 === void 0) {
  25831. options.v4 = false;
  25832. }
  25833. let formFunction = this.correctForm;
  25834. if (options.v4) {
  25835. formFunction = this.to4in6;
  25836. }
  25837. if (options.className) {
  25838. return (0, sprintf_js_1.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>', options.prefix, formFunction.call(this), options.className);
  25839. }
  25840. return (0, sprintf_js_1.sprintf)('<a href="%1$s%2$s">%2$s</a>', options.prefix, formFunction.call(this));
  25841. }
  25842. /**
  25843. * Groups an address
  25844. * @returns {String}
  25845. */
  25846. group() {
  25847. if (this.elidedGroups === 0) {
  25848. return helpers.simpleGroup(this.address).join(":");
  25849. }
  25850. assert(typeof this.elidedGroups === "number");
  25851. assert(typeof this.elisionBegin === "number");
  25852. const output = [];
  25853. const [left, right] = this.address.split("::");
  25854. if (left.length) {
  25855. output.push(...helpers.simpleGroup(left));
  25856. } else {
  25857. output.push("");
  25858. }
  25859. const classes = ["hover-group"];
  25860. for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
  25861. classes.push((0, sprintf_js_1.sprintf)("group-%d", i));
  25862. }
  25863. output.push((0, sprintf_js_1.sprintf)('<span class="%s"></span>', classes.join(" ")));
  25864. if (right.length) {
  25865. output.push(...helpers.simpleGroup(right, this.elisionEnd));
  25866. } else {
  25867. output.push("");
  25868. }
  25869. if (this.is4()) {
  25870. assert(this.address4 instanceof ipv4_1.Address4);
  25871. output.pop();
  25872. output.push(this.address4.groupForV6());
  25873. }
  25874. return output.join(":");
  25875. }
  25876. // #endregion
  25877. // #region Regular expressions
  25878. /**
  25879. * Generate a regular expression string that can be used to find or validate
  25880. * all variations of this address
  25881. * @memberof Address6
  25882. * @instance
  25883. * @param {boolean} substringSearch
  25884. * @returns {string}
  25885. */
  25886. regularExpressionString(substringSearch = false) {
  25887. let output = [];
  25888. const address6 = new _Address6(this.correctForm());
  25889. if (address6.elidedGroups === 0) {
  25890. output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));
  25891. } else if (address6.elidedGroups === constants6.GROUPS) {
  25892. output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS));
  25893. } else {
  25894. const halves = address6.address.split("::");
  25895. if (halves[0].length) {
  25896. output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":")));
  25897. }
  25898. assert(typeof address6.elidedGroups === "number");
  25899. output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0));
  25900. if (halves[1].length) {
  25901. output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":")));
  25902. }
  25903. output = [output.join(":")];
  25904. }
  25905. if (!substringSearch) {
  25906. output = [
  25907. "(?=^|",
  25908. regular_expressions_1.ADDRESS_BOUNDARY,
  25909. "|[^\\w\\:])(",
  25910. ...output,
  25911. ")(?=[^\\w\\:]|",
  25912. regular_expressions_1.ADDRESS_BOUNDARY,
  25913. "|$)"
  25914. ];
  25915. }
  25916. return output.join("");
  25917. }
  25918. /**
  25919. * Generate a regular expression that can be used to find or validate all
  25920. * variations of this address.
  25921. * @memberof Address6
  25922. * @instance
  25923. * @param {boolean} substringSearch
  25924. * @returns {RegExp}
  25925. */
  25926. regularExpression(substringSearch = false) {
  25927. return new RegExp(this.regularExpressionString(substringSearch), "i");
  25928. }
  25929. };
  25930. __name(_Address6, "Address6");
  25931. var Address6 = _Address6;
  25932. exports2.Address6 = Address6;
  25933. }
  25934. });
  25935. // node_modules/ip-address/dist/ip-address.js
  25936. var require_ip_address = __commonJS({
  25937. "node_modules/ip-address/dist/ip-address.js"(exports2) {
  25938. "use strict";
  25939. var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
  25940. if (k2 === void 0) k2 = k;
  25941. var desc = Object.getOwnPropertyDescriptor(m, k);
  25942. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  25943. desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
  25944. return m[k];
  25945. }, "get") };
  25946. }
  25947. Object.defineProperty(o, k2, desc);
  25948. } : function(o, m, k, k2) {
  25949. if (k2 === void 0) k2 = k;
  25950. o[k2] = m[k];
  25951. });
  25952. var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
  25953. Object.defineProperty(o, "default", { enumerable: true, value: v });
  25954. } : function(o, v) {
  25955. o["default"] = v;
  25956. });
  25957. var __importStar = exports2 && exports2.__importStar || function(mod) {
  25958. if (mod && mod.__esModule) return mod;
  25959. var result = {};
  25960. if (mod != null) {
  25961. for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  25962. }
  25963. __setModuleDefault(result, mod);
  25964. return result;
  25965. };
  25966. Object.defineProperty(exports2, "__esModule", { value: true });
  25967. exports2.v6 = exports2.AddressError = exports2.Address6 = exports2.Address4 = void 0;
  25968. var ipv4_1 = require_ipv4();
  25969. Object.defineProperty(exports2, "Address4", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  25970. return ipv4_1.Address4;
  25971. }, "get") });
  25972. var ipv6_1 = require_ipv6();
  25973. Object.defineProperty(exports2, "Address6", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  25974. return ipv6_1.Address6;
  25975. }, "get") });
  25976. var address_error_1 = require_address_error();
  25977. Object.defineProperty(exports2, "AddressError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  25978. return address_error_1.AddressError;
  25979. }, "get") });
  25980. var helpers = __importStar(require_helpers());
  25981. exports2.v6 = { helpers };
  25982. }
  25983. });
  25984. // node_modules/socks/build/common/helpers.js
  25985. var require_helpers2 = __commonJS({
  25986. "node_modules/socks/build/common/helpers.js"(exports2) {
  25987. "use strict";
  25988. Object.defineProperty(exports2, "__esModule", { value: true });
  25989. exports2.ipToBuffer = exports2.int32ToIpv4 = exports2.ipv4ToInt32 = exports2.validateSocksClientChainOptions = exports2.validateSocksClientOptions = void 0;
  25990. var util_1 = require_util();
  25991. var constants_1 = require_constants3();
  25992. var stream = require("stream");
  25993. var ip_address_1 = require_ip_address();
  25994. var net = require("net");
  25995. function validateSocksClientOptions(options, acceptedCommands = ["connect", "bind", "associate"]) {
  25996. if (!constants_1.SocksCommand[options.command]) {
  25997. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options);
  25998. }
  25999. if (acceptedCommands.indexOf(options.command) === -1) {
  26000. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options);
  26001. }
  26002. if (!isValidSocksRemoteHost(options.destination)) {
  26003. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
  26004. }
  26005. if (!isValidSocksProxy(options.proxy)) {
  26006. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
  26007. }
  26008. validateCustomProxyAuth(options.proxy, options);
  26009. if (options.timeout && !isValidTimeoutValue(options.timeout)) {
  26010. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
  26011. }
  26012. if (options.existing_socket && !(options.existing_socket instanceof stream.Duplex)) {
  26013. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options);
  26014. }
  26015. }
  26016. __name(validateSocksClientOptions, "validateSocksClientOptions");
  26017. exports2.validateSocksClientOptions = validateSocksClientOptions;
  26018. function validateSocksClientChainOptions(options) {
  26019. if (options.command !== "connect") {
  26020. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options);
  26021. }
  26022. if (!isValidSocksRemoteHost(options.destination)) {
  26023. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
  26024. }
  26025. if (!(options.proxies && Array.isArray(options.proxies) && options.proxies.length >= 2)) {
  26026. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options);
  26027. }
  26028. options.proxies.forEach((proxy) => {
  26029. if (!isValidSocksProxy(proxy)) {
  26030. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
  26031. }
  26032. validateCustomProxyAuth(proxy, options);
  26033. });
  26034. if (options.timeout && !isValidTimeoutValue(options.timeout)) {
  26035. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
  26036. }
  26037. }
  26038. __name(validateSocksClientChainOptions, "validateSocksClientChainOptions");
  26039. exports2.validateSocksClientChainOptions = validateSocksClientChainOptions;
  26040. function validateCustomProxyAuth(proxy, options) {
  26041. if (proxy.custom_auth_method !== void 0) {
  26042. if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START || proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) {
  26043. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options);
  26044. }
  26045. if (proxy.custom_auth_request_handler === void 0 || typeof proxy.custom_auth_request_handler !== "function") {
  26046. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
  26047. }
  26048. if (proxy.custom_auth_response_size === void 0) {
  26049. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
  26050. }
  26051. if (proxy.custom_auth_response_handler === void 0 || typeof proxy.custom_auth_response_handler !== "function") {
  26052. throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
  26053. }
  26054. }
  26055. }
  26056. __name(validateCustomProxyAuth, "validateCustomProxyAuth");
  26057. function isValidSocksRemoteHost(remoteHost) {
  26058. return remoteHost && typeof remoteHost.host === "string" && typeof remoteHost.port === "number" && remoteHost.port >= 0 && remoteHost.port <= 65535;
  26059. }
  26060. __name(isValidSocksRemoteHost, "isValidSocksRemoteHost");
  26061. function isValidSocksProxy(proxy) {
  26062. return proxy && (typeof proxy.host === "string" || typeof proxy.ipaddress === "string") && typeof proxy.port === "number" && proxy.port >= 0 && proxy.port <= 65535 && (proxy.type === 4 || proxy.type === 5);
  26063. }
  26064. __name(isValidSocksProxy, "isValidSocksProxy");
  26065. function isValidTimeoutValue(value) {
  26066. return typeof value === "number" && value > 0;
  26067. }
  26068. __name(isValidTimeoutValue, "isValidTimeoutValue");
  26069. function ipv4ToInt32(ip) {
  26070. const address = new ip_address_1.Address4(ip);
  26071. return address.toArray().reduce((acc, part) => (acc << 8) + part, 0);
  26072. }
  26073. __name(ipv4ToInt32, "ipv4ToInt32");
  26074. exports2.ipv4ToInt32 = ipv4ToInt32;
  26075. function int32ToIpv4(int32) {
  26076. const octet1 = int32 >>> 24 & 255;
  26077. const octet2 = int32 >>> 16 & 255;
  26078. const octet3 = int32 >>> 8 & 255;
  26079. const octet4 = int32 & 255;
  26080. return [octet1, octet2, octet3, octet4].join(".");
  26081. }
  26082. __name(int32ToIpv4, "int32ToIpv4");
  26083. exports2.int32ToIpv4 = int32ToIpv4;
  26084. function ipToBuffer(ip) {
  26085. if (net.isIPv4(ip)) {
  26086. const address = new ip_address_1.Address4(ip);
  26087. return Buffer.from(address.toArray());
  26088. } else if (net.isIPv6(ip)) {
  26089. const address = new ip_address_1.Address6(ip);
  26090. return Buffer.from(address.canonicalForm().split(":").map((segment) => segment.padStart(4, "0")).join(""), "hex");
  26091. } else {
  26092. throw new Error("Invalid IP address format");
  26093. }
  26094. }
  26095. __name(ipToBuffer, "ipToBuffer");
  26096. exports2.ipToBuffer = ipToBuffer;
  26097. }
  26098. });
  26099. // node_modules/socks/build/common/receivebuffer.js
  26100. var require_receivebuffer = __commonJS({
  26101. "node_modules/socks/build/common/receivebuffer.js"(exports2) {
  26102. "use strict";
  26103. Object.defineProperty(exports2, "__esModule", { value: true });
  26104. exports2.ReceiveBuffer = void 0;
  26105. var _ReceiveBuffer = class _ReceiveBuffer {
  26106. constructor(size = 4096) {
  26107. this.buffer = Buffer.allocUnsafe(size);
  26108. this.offset = 0;
  26109. this.originalSize = size;
  26110. }
  26111. get length() {
  26112. return this.offset;
  26113. }
  26114. append(data) {
  26115. if (!Buffer.isBuffer(data)) {
  26116. throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");
  26117. }
  26118. if (this.offset + data.length >= this.buffer.length) {
  26119. const tmp = this.buffer;
  26120. this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length));
  26121. tmp.copy(this.buffer);
  26122. }
  26123. data.copy(this.buffer, this.offset);
  26124. return this.offset += data.length;
  26125. }
  26126. peek(length) {
  26127. if (length > this.offset) {
  26128. throw new Error("Attempted to read beyond the bounds of the managed internal data.");
  26129. }
  26130. return this.buffer.slice(0, length);
  26131. }
  26132. get(length) {
  26133. if (length > this.offset) {
  26134. throw new Error("Attempted to read beyond the bounds of the managed internal data.");
  26135. }
  26136. const value = Buffer.allocUnsafe(length);
  26137. this.buffer.slice(0, length).copy(value);
  26138. this.buffer.copyWithin(0, length, length + this.offset - length);
  26139. this.offset -= length;
  26140. return value;
  26141. }
  26142. };
  26143. __name(_ReceiveBuffer, "ReceiveBuffer");
  26144. var ReceiveBuffer = _ReceiveBuffer;
  26145. exports2.ReceiveBuffer = ReceiveBuffer;
  26146. }
  26147. });
  26148. // node_modules/socks/build/client/socksclient.js
  26149. var require_socksclient = __commonJS({
  26150. "node_modules/socks/build/client/socksclient.js"(exports2) {
  26151. "use strict";
  26152. var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
  26153. function adopt(value) {
  26154. return value instanceof P ? value : new P(function(resolve) {
  26155. resolve(value);
  26156. });
  26157. }
  26158. __name(adopt, "adopt");
  26159. return new (P || (P = Promise))(function(resolve, reject) {
  26160. function fulfilled(value) {
  26161. try {
  26162. step(generator.next(value));
  26163. } catch (e) {
  26164. reject(e);
  26165. }
  26166. }
  26167. __name(fulfilled, "fulfilled");
  26168. function rejected(value) {
  26169. try {
  26170. step(generator["throw"](value));
  26171. } catch (e) {
  26172. reject(e);
  26173. }
  26174. }
  26175. __name(rejected, "rejected");
  26176. function step(result) {
  26177. result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
  26178. }
  26179. __name(step, "step");
  26180. step((generator = generator.apply(thisArg, _arguments || [])).next());
  26181. });
  26182. };
  26183. Object.defineProperty(exports2, "__esModule", { value: true });
  26184. exports2.SocksClientError = exports2.SocksClient = void 0;
  26185. var events_1 = require("events");
  26186. var net = require("net");
  26187. var smart_buffer_1 = require_smartbuffer();
  26188. var constants_1 = require_constants3();
  26189. var helpers_1 = require_helpers2();
  26190. var receivebuffer_1 = require_receivebuffer();
  26191. var util_1 = require_util();
  26192. Object.defineProperty(exports2, "SocksClientError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  26193. return util_1.SocksClientError;
  26194. }, "get") });
  26195. var ip_address_1 = require_ip_address();
  26196. var _SocksClient = class _SocksClient extends events_1.EventEmitter {
  26197. constructor(options) {
  26198. super();
  26199. this.options = Object.assign({}, options);
  26200. (0, helpers_1.validateSocksClientOptions)(options);
  26201. this.setState(constants_1.SocksClientState.Created);
  26202. }
  26203. /**
  26204. * Creates a new SOCKS connection.
  26205. *
  26206. * Note: Supports callbacks and promises. Only supports the connect command.
  26207. * @param options { SocksClientOptions } Options.
  26208. * @param callback { Function } An optional callback function.
  26209. * @returns { Promise }
  26210. */
  26211. static createConnection(options, callback) {
  26212. return new Promise((resolve, reject) => {
  26213. try {
  26214. (0, helpers_1.validateSocksClientOptions)(options, ["connect"]);
  26215. } catch (err) {
  26216. if (typeof callback === "function") {
  26217. callback(err);
  26218. return resolve(err);
  26219. } else {
  26220. return reject(err);
  26221. }
  26222. }
  26223. const client = new _SocksClient(options);
  26224. client.connect(options.existing_socket);
  26225. client.once("established", (info) => {
  26226. client.removeAllListeners();
  26227. if (typeof callback === "function") {
  26228. callback(null, info);
  26229. resolve(info);
  26230. } else {
  26231. resolve(info);
  26232. }
  26233. });
  26234. client.once("error", (err) => {
  26235. client.removeAllListeners();
  26236. if (typeof callback === "function") {
  26237. callback(err);
  26238. resolve(err);
  26239. } else {
  26240. reject(err);
  26241. }
  26242. });
  26243. });
  26244. }
  26245. /**
  26246. * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies.
  26247. *
  26248. * Note: Supports callbacks and promises. Only supports the connect method.
  26249. * Note: Implemented via createConnection() factory function.
  26250. * @param options { SocksClientChainOptions } Options
  26251. * @param callback { Function } An optional callback function.
  26252. * @returns { Promise }
  26253. */
  26254. static createConnectionChain(options, callback) {
  26255. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  26256. try {
  26257. (0, helpers_1.validateSocksClientChainOptions)(options);
  26258. } catch (err) {
  26259. if (typeof callback === "function") {
  26260. callback(err);
  26261. return resolve(err);
  26262. } else {
  26263. return reject(err);
  26264. }
  26265. }
  26266. if (options.randomizeChain) {
  26267. (0, util_1.shuffleArray)(options.proxies);
  26268. }
  26269. try {
  26270. let sock;
  26271. for (let i = 0; i < options.proxies.length; i++) {
  26272. const nextProxy = options.proxies[i];
  26273. const nextDestination = i === options.proxies.length - 1 ? options.destination : {
  26274. host: options.proxies[i + 1].host || options.proxies[i + 1].ipaddress,
  26275. port: options.proxies[i + 1].port
  26276. };
  26277. const result = yield _SocksClient.createConnection({
  26278. command: "connect",
  26279. proxy: nextProxy,
  26280. destination: nextDestination,
  26281. existing_socket: sock
  26282. });
  26283. sock = sock || result.socket;
  26284. }
  26285. if (typeof callback === "function") {
  26286. callback(null, { socket: sock });
  26287. resolve({ socket: sock });
  26288. } else {
  26289. resolve({ socket: sock });
  26290. }
  26291. } catch (err) {
  26292. if (typeof callback === "function") {
  26293. callback(err);
  26294. resolve(err);
  26295. } else {
  26296. reject(err);
  26297. }
  26298. }
  26299. }));
  26300. }
  26301. /**
  26302. * Creates a SOCKS UDP Frame.
  26303. * @param options
  26304. */
  26305. static createUDPFrame(options) {
  26306. const buff = new smart_buffer_1.SmartBuffer();
  26307. buff.writeUInt16BE(0);
  26308. buff.writeUInt8(options.frameNumber || 0);
  26309. if (net.isIPv4(options.remoteHost.host)) {
  26310. buff.writeUInt8(constants_1.Socks5HostType.IPv4);
  26311. buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host));
  26312. } else if (net.isIPv6(options.remoteHost.host)) {
  26313. buff.writeUInt8(constants_1.Socks5HostType.IPv6);
  26314. buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host));
  26315. } else {
  26316. buff.writeUInt8(constants_1.Socks5HostType.Hostname);
  26317. buff.writeUInt8(Buffer.byteLength(options.remoteHost.host));
  26318. buff.writeString(options.remoteHost.host);
  26319. }
  26320. buff.writeUInt16BE(options.remoteHost.port);
  26321. buff.writeBuffer(options.data);
  26322. return buff.toBuffer();
  26323. }
  26324. /**
  26325. * Parses a SOCKS UDP frame.
  26326. * @param data
  26327. */
  26328. static parseUDPFrame(data) {
  26329. const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
  26330. buff.readOffset = 2;
  26331. const frameNumber = buff.readUInt8();
  26332. const hostType = buff.readUInt8();
  26333. let remoteHost;
  26334. if (hostType === constants_1.Socks5HostType.IPv4) {
  26335. remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE());
  26336. } else if (hostType === constants_1.Socks5HostType.IPv6) {
  26337. remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm();
  26338. } else {
  26339. remoteHost = buff.readString(buff.readUInt8());
  26340. }
  26341. const remotePort = buff.readUInt16BE();
  26342. return {
  26343. frameNumber,
  26344. remoteHost: {
  26345. host: remoteHost,
  26346. port: remotePort
  26347. },
  26348. data: buff.readBuffer()
  26349. };
  26350. }
  26351. /**
  26352. * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state.
  26353. */
  26354. setState(newState) {
  26355. if (this.state !== constants_1.SocksClientState.Error) {
  26356. this.state = newState;
  26357. }
  26358. }
  26359. /**
  26360. * Starts the connection establishment to the proxy and destination.
  26361. * @param existingSocket Connected socket to use instead of creating a new one (internal use).
  26362. */
  26363. connect(existingSocket) {
  26364. this.onDataReceived = (data) => this.onDataReceivedHandler(data);
  26365. this.onClose = () => this.onCloseHandler();
  26366. this.onError = (err) => this.onErrorHandler(err);
  26367. this.onConnect = () => this.onConnectHandler();
  26368. const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT);
  26369. if (timer.unref && typeof timer.unref === "function") {
  26370. timer.unref();
  26371. }
  26372. if (existingSocket) {
  26373. this.socket = existingSocket;
  26374. } else {
  26375. this.socket = new net.Socket();
  26376. }
  26377. this.socket.once("close", this.onClose);
  26378. this.socket.once("error", this.onError);
  26379. this.socket.once("connect", this.onConnect);
  26380. this.socket.on("data", this.onDataReceived);
  26381. this.setState(constants_1.SocksClientState.Connecting);
  26382. this.receiveBuffer = new receivebuffer_1.ReceiveBuffer();
  26383. if (existingSocket) {
  26384. this.socket.emit("connect");
  26385. } else {
  26386. this.socket.connect(this.getSocketOptions());
  26387. if (this.options.set_tcp_nodelay !== void 0 && this.options.set_tcp_nodelay !== null) {
  26388. this.socket.setNoDelay(!!this.options.set_tcp_nodelay);
  26389. }
  26390. }
  26391. this.prependOnceListener("established", (info) => {
  26392. setImmediate(() => {
  26393. if (this.receiveBuffer.length > 0) {
  26394. const excessData = this.receiveBuffer.get(this.receiveBuffer.length);
  26395. info.socket.emit("data", excessData);
  26396. }
  26397. info.socket.resume();
  26398. });
  26399. });
  26400. }
  26401. // Socket options (defaults host/port to options.proxy.host/options.proxy.port)
  26402. getSocketOptions() {
  26403. return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port });
  26404. }
  26405. /**
  26406. * Handles internal Socks timeout callback.
  26407. * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed.
  26408. */
  26409. onEstablishedTimeout() {
  26410. if (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.BoundWaitingForConnection) {
  26411. this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut);
  26412. }
  26413. }
  26414. /**
  26415. * Handles Socket connect event.
  26416. */
  26417. onConnectHandler() {
  26418. this.setState(constants_1.SocksClientState.Connected);
  26419. if (this.options.proxy.type === 4) {
  26420. this.sendSocks4InitialHandshake();
  26421. } else {
  26422. this.sendSocks5InitialHandshake();
  26423. }
  26424. this.setState(constants_1.SocksClientState.SentInitialHandshake);
  26425. }
  26426. /**
  26427. * Handles Socket data event.
  26428. * @param data
  26429. */
  26430. onDataReceivedHandler(data) {
  26431. this.receiveBuffer.append(data);
  26432. this.processData();
  26433. }
  26434. /**
  26435. * Handles processing of the data we have received.
  26436. */
  26437. processData() {
  26438. while (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.Error && this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) {
  26439. if (this.state === constants_1.SocksClientState.SentInitialHandshake) {
  26440. if (this.options.proxy.type === 4) {
  26441. this.handleSocks4FinalHandshakeResponse();
  26442. } else {
  26443. this.handleInitialSocks5HandshakeResponse();
  26444. }
  26445. } else if (this.state === constants_1.SocksClientState.SentAuthentication) {
  26446. this.handleInitialSocks5AuthenticationHandshakeResponse();
  26447. } else if (this.state === constants_1.SocksClientState.SentFinalHandshake) {
  26448. this.handleSocks5FinalHandshakeResponse();
  26449. } else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) {
  26450. if (this.options.proxy.type === 4) {
  26451. this.handleSocks4IncomingConnectionResponse();
  26452. } else {
  26453. this.handleSocks5IncomingConnectionResponse();
  26454. }
  26455. } else {
  26456. this.closeSocket(constants_1.ERRORS.InternalError);
  26457. break;
  26458. }
  26459. }
  26460. }
  26461. /**
  26462. * Handles Socket close event.
  26463. * @param had_error
  26464. */
  26465. onCloseHandler() {
  26466. this.closeSocket(constants_1.ERRORS.SocketClosed);
  26467. }
  26468. /**
  26469. * Handles Socket error event.
  26470. * @param err
  26471. */
  26472. onErrorHandler(err) {
  26473. this.closeSocket(err.message);
  26474. }
  26475. /**
  26476. * Removes internal event listeners on the underlying Socket.
  26477. */
  26478. removeInternalSocketHandlers() {
  26479. this.socket.pause();
  26480. this.socket.removeListener("data", this.onDataReceived);
  26481. this.socket.removeListener("close", this.onClose);
  26482. this.socket.removeListener("error", this.onError);
  26483. this.socket.removeListener("connect", this.onConnect);
  26484. }
  26485. /**
  26486. * Closes and destroys the underlying Socket. Emits an error event.
  26487. * @param err { String } An error string to include in error event.
  26488. */
  26489. closeSocket(err) {
  26490. if (this.state !== constants_1.SocksClientState.Error) {
  26491. this.setState(constants_1.SocksClientState.Error);
  26492. this.socket.destroy();
  26493. this.removeInternalSocketHandlers();
  26494. this.emit("error", new util_1.SocksClientError(err, this.options));
  26495. }
  26496. }
  26497. /**
  26498. * Sends initial Socks v4 handshake request.
  26499. */
  26500. sendSocks4InitialHandshake() {
  26501. const userId = this.options.proxy.userId || "";
  26502. const buff = new smart_buffer_1.SmartBuffer();
  26503. buff.writeUInt8(4);
  26504. buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
  26505. buff.writeUInt16BE(this.options.destination.port);
  26506. if (net.isIPv4(this.options.destination.host)) {
  26507. buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
  26508. buff.writeStringNT(userId);
  26509. } else {
  26510. buff.writeUInt8(0);
  26511. buff.writeUInt8(0);
  26512. buff.writeUInt8(0);
  26513. buff.writeUInt8(1);
  26514. buff.writeStringNT(userId);
  26515. buff.writeStringNT(this.options.destination.host);
  26516. }
  26517. this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response;
  26518. this.socket.write(buff.toBuffer());
  26519. }
  26520. /**
  26521. * Handles Socks v4 handshake response.
  26522. * @param data
  26523. */
  26524. handleSocks4FinalHandshakeResponse() {
  26525. const data = this.receiveBuffer.get(8);
  26526. if (data[1] !== constants_1.Socks4Response.Granted) {
  26527. this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);
  26528. } else {
  26529. if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
  26530. const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
  26531. buff.readOffset = 2;
  26532. const remoteHost = {
  26533. port: buff.readUInt16BE(),
  26534. host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE())
  26535. };
  26536. if (remoteHost.host === "0.0.0.0") {
  26537. remoteHost.host = this.options.proxy.ipaddress;
  26538. }
  26539. this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
  26540. this.emit("bound", { remoteHost, socket: this.socket });
  26541. } else {
  26542. this.setState(constants_1.SocksClientState.Established);
  26543. this.removeInternalSocketHandlers();
  26544. this.emit("established", { socket: this.socket });
  26545. }
  26546. }
  26547. }
  26548. /**
  26549. * Handles Socks v4 incoming connection request (BIND)
  26550. * @param data
  26551. */
  26552. handleSocks4IncomingConnectionResponse() {
  26553. const data = this.receiveBuffer.get(8);
  26554. if (data[1] !== constants_1.Socks4Response.Granted) {
  26555. this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);
  26556. } else {
  26557. const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
  26558. buff.readOffset = 2;
  26559. const remoteHost = {
  26560. port: buff.readUInt16BE(),
  26561. host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE())
  26562. };
  26563. this.setState(constants_1.SocksClientState.Established);
  26564. this.removeInternalSocketHandlers();
  26565. this.emit("established", { remoteHost, socket: this.socket });
  26566. }
  26567. }
  26568. /**
  26569. * Sends initial Socks v5 handshake request.
  26570. */
  26571. sendSocks5InitialHandshake() {
  26572. const buff = new smart_buffer_1.SmartBuffer();
  26573. const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth];
  26574. if (this.options.proxy.userId || this.options.proxy.password) {
  26575. supportedAuthMethods.push(constants_1.Socks5Auth.UserPass);
  26576. }
  26577. if (this.options.proxy.custom_auth_method !== void 0) {
  26578. supportedAuthMethods.push(this.options.proxy.custom_auth_method);
  26579. }
  26580. buff.writeUInt8(5);
  26581. buff.writeUInt8(supportedAuthMethods.length);
  26582. for (const authMethod of supportedAuthMethods) {
  26583. buff.writeUInt8(authMethod);
  26584. }
  26585. this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;
  26586. this.socket.write(buff.toBuffer());
  26587. this.setState(constants_1.SocksClientState.SentInitialHandshake);
  26588. }
  26589. /**
  26590. * Handles initial Socks v5 handshake response.
  26591. * @param data
  26592. */
  26593. handleInitialSocks5HandshakeResponse() {
  26594. const data = this.receiveBuffer.get(2);
  26595. if (data[0] !== 5) {
  26596. this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
  26597. } else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {
  26598. this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
  26599. } else {
  26600. if (data[1] === constants_1.Socks5Auth.NoAuth) {
  26601. this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;
  26602. this.sendSocks5CommandRequest();
  26603. } else if (data[1] === constants_1.Socks5Auth.UserPass) {
  26604. this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;
  26605. this.sendSocks5UserPassAuthentication();
  26606. } else if (data[1] === this.options.proxy.custom_auth_method) {
  26607. this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;
  26608. this.sendSocks5CustomAuthentication();
  26609. } else {
  26610. this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);
  26611. }
  26612. }
  26613. }
  26614. /**
  26615. * Sends Socks v5 user & password auth handshake.
  26616. *
  26617. * Note: No auth and user/pass are currently supported.
  26618. */
  26619. sendSocks5UserPassAuthentication() {
  26620. const userId = this.options.proxy.userId || "";
  26621. const password = this.options.proxy.password || "";
  26622. const buff = new smart_buffer_1.SmartBuffer();
  26623. buff.writeUInt8(1);
  26624. buff.writeUInt8(Buffer.byteLength(userId));
  26625. buff.writeString(userId);
  26626. buff.writeUInt8(Buffer.byteLength(password));
  26627. buff.writeString(password);
  26628. this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse;
  26629. this.socket.write(buff.toBuffer());
  26630. this.setState(constants_1.SocksClientState.SentAuthentication);
  26631. }
  26632. sendSocks5CustomAuthentication() {
  26633. return __awaiter(this, void 0, void 0, function* () {
  26634. this.nextRequiredPacketBufferSize = this.options.proxy.custom_auth_response_size;
  26635. this.socket.write(yield this.options.proxy.custom_auth_request_handler());
  26636. this.setState(constants_1.SocksClientState.SentAuthentication);
  26637. });
  26638. }
  26639. handleSocks5CustomAuthHandshakeResponse(data) {
  26640. return __awaiter(this, void 0, void 0, function* () {
  26641. return yield this.options.proxy.custom_auth_response_handler(data);
  26642. });
  26643. }
  26644. handleSocks5AuthenticationNoAuthHandshakeResponse(data) {
  26645. return __awaiter(this, void 0, void 0, function* () {
  26646. return data[1] === 0;
  26647. });
  26648. }
  26649. handleSocks5AuthenticationUserPassHandshakeResponse(data) {
  26650. return __awaiter(this, void 0, void 0, function* () {
  26651. return data[1] === 0;
  26652. });
  26653. }
  26654. /**
  26655. * Handles Socks v5 auth handshake response.
  26656. * @param data
  26657. */
  26658. handleInitialSocks5AuthenticationHandshakeResponse() {
  26659. return __awaiter(this, void 0, void 0, function* () {
  26660. this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);
  26661. let authResult = false;
  26662. if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) {
  26663. authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));
  26664. } else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) {
  26665. authResult = yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));
  26666. } else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) {
  26667. authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));
  26668. }
  26669. if (!authResult) {
  26670. this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed);
  26671. } else {
  26672. this.sendSocks5CommandRequest();
  26673. }
  26674. });
  26675. }
  26676. /**
  26677. * Sends Socks v5 final handshake request.
  26678. */
  26679. sendSocks5CommandRequest() {
  26680. const buff = new smart_buffer_1.SmartBuffer();
  26681. buff.writeUInt8(5);
  26682. buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
  26683. buff.writeUInt8(0);
  26684. if (net.isIPv4(this.options.destination.host)) {
  26685. buff.writeUInt8(constants_1.Socks5HostType.IPv4);
  26686. buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
  26687. } else if (net.isIPv6(this.options.destination.host)) {
  26688. buff.writeUInt8(constants_1.Socks5HostType.IPv6);
  26689. buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
  26690. } else {
  26691. buff.writeUInt8(constants_1.Socks5HostType.Hostname);
  26692. buff.writeUInt8(this.options.destination.host.length);
  26693. buff.writeString(this.options.destination.host);
  26694. }
  26695. buff.writeUInt16BE(this.options.destination.port);
  26696. this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
  26697. this.socket.write(buff.toBuffer());
  26698. this.setState(constants_1.SocksClientState.SentFinalHandshake);
  26699. }
  26700. /**
  26701. * Handles Socks v5 final handshake response.
  26702. * @param data
  26703. */
  26704. handleSocks5FinalHandshakeResponse() {
  26705. const header = this.receiveBuffer.peek(5);
  26706. if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) {
  26707. this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`);
  26708. } else {
  26709. const addressType = header[3];
  26710. let remoteHost;
  26711. let buff;
  26712. if (addressType === constants_1.Socks5HostType.IPv4) {
  26713. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
  26714. if (this.receiveBuffer.length < dataNeeded) {
  26715. this.nextRequiredPacketBufferSize = dataNeeded;
  26716. return;
  26717. }
  26718. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
  26719. remoteHost = {
  26720. host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
  26721. port: buff.readUInt16BE()
  26722. };
  26723. if (remoteHost.host === "0.0.0.0") {
  26724. remoteHost.host = this.options.proxy.ipaddress;
  26725. }
  26726. } else if (addressType === constants_1.Socks5HostType.Hostname) {
  26727. const hostLength = header[4];
  26728. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);
  26729. if (this.receiveBuffer.length < dataNeeded) {
  26730. this.nextRequiredPacketBufferSize = dataNeeded;
  26731. return;
  26732. }
  26733. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
  26734. remoteHost = {
  26735. host: buff.readString(hostLength),
  26736. port: buff.readUInt16BE()
  26737. };
  26738. } else if (addressType === constants_1.Socks5HostType.IPv6) {
  26739. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
  26740. if (this.receiveBuffer.length < dataNeeded) {
  26741. this.nextRequiredPacketBufferSize = dataNeeded;
  26742. return;
  26743. }
  26744. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
  26745. remoteHost = {
  26746. host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
  26747. port: buff.readUInt16BE()
  26748. };
  26749. }
  26750. this.setState(constants_1.SocksClientState.ReceivedFinalResponse);
  26751. if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) {
  26752. this.setState(constants_1.SocksClientState.Established);
  26753. this.removeInternalSocketHandlers();
  26754. this.emit("established", { remoteHost, socket: this.socket });
  26755. } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
  26756. this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
  26757. this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
  26758. this.emit("bound", { remoteHost, socket: this.socket });
  26759. } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) {
  26760. this.setState(constants_1.SocksClientState.Established);
  26761. this.removeInternalSocketHandlers();
  26762. this.emit("established", {
  26763. remoteHost,
  26764. socket: this.socket
  26765. });
  26766. }
  26767. }
  26768. }
  26769. /**
  26770. * Handles Socks v5 incoming connection request (BIND).
  26771. */
  26772. handleSocks5IncomingConnectionResponse() {
  26773. const header = this.receiveBuffer.peek(5);
  26774. if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) {
  26775. this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`);
  26776. } else {
  26777. const addressType = header[3];
  26778. let remoteHost;
  26779. let buff;
  26780. if (addressType === constants_1.Socks5HostType.IPv4) {
  26781. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
  26782. if (this.receiveBuffer.length < dataNeeded) {
  26783. this.nextRequiredPacketBufferSize = dataNeeded;
  26784. return;
  26785. }
  26786. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
  26787. remoteHost = {
  26788. host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
  26789. port: buff.readUInt16BE()
  26790. };
  26791. if (remoteHost.host === "0.0.0.0") {
  26792. remoteHost.host = this.options.proxy.ipaddress;
  26793. }
  26794. } else if (addressType === constants_1.Socks5HostType.Hostname) {
  26795. const hostLength = header[4];
  26796. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);
  26797. if (this.receiveBuffer.length < dataNeeded) {
  26798. this.nextRequiredPacketBufferSize = dataNeeded;
  26799. return;
  26800. }
  26801. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
  26802. remoteHost = {
  26803. host: buff.readString(hostLength),
  26804. port: buff.readUInt16BE()
  26805. };
  26806. } else if (addressType === constants_1.Socks5HostType.IPv6) {
  26807. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
  26808. if (this.receiveBuffer.length < dataNeeded) {
  26809. this.nextRequiredPacketBufferSize = dataNeeded;
  26810. return;
  26811. }
  26812. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
  26813. remoteHost = {
  26814. host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
  26815. port: buff.readUInt16BE()
  26816. };
  26817. }
  26818. this.setState(constants_1.SocksClientState.Established);
  26819. this.removeInternalSocketHandlers();
  26820. this.emit("established", { remoteHost, socket: this.socket });
  26821. }
  26822. }
  26823. get socksClientOptions() {
  26824. return Object.assign({}, this.options);
  26825. }
  26826. };
  26827. __name(_SocksClient, "SocksClient");
  26828. var SocksClient = _SocksClient;
  26829. exports2.SocksClient = SocksClient;
  26830. }
  26831. });
  26832. // node_modules/socks/build/index.js
  26833. var require_build = __commonJS({
  26834. "node_modules/socks/build/index.js"(exports2) {
  26835. "use strict";
  26836. var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
  26837. if (k2 === void 0) k2 = k;
  26838. var desc = Object.getOwnPropertyDescriptor(m, k);
  26839. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  26840. desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
  26841. return m[k];
  26842. }, "get") };
  26843. }
  26844. Object.defineProperty(o, k2, desc);
  26845. } : function(o, m, k, k2) {
  26846. if (k2 === void 0) k2 = k;
  26847. o[k2] = m[k];
  26848. });
  26849. var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
  26850. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
  26851. };
  26852. Object.defineProperty(exports2, "__esModule", { value: true });
  26853. __exportStar(require_socksclient(), exports2);
  26854. }
  26855. });
  26856. // node_modules/mongodb/lib/cmap/auth/mongocr.js
  26857. var require_mongocr = __commonJS({
  26858. "node_modules/mongodb/lib/cmap/auth/mongocr.js"(exports2) {
  26859. "use strict";
  26860. Object.defineProperty(exports2, "__esModule", { value: true });
  26861. exports2.MongoCR = void 0;
  26862. var crypto = require("crypto");
  26863. var error_1 = require_error();
  26864. var utils_1 = require_utils();
  26865. var auth_provider_1 = require_auth_provider();
  26866. var _MongoCR = class _MongoCR extends auth_provider_1.AuthProvider {
  26867. async auth(authContext) {
  26868. const { connection, credentials } = authContext;
  26869. if (!credentials) {
  26870. throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
  26871. }
  26872. const { username, password, source } = credentials;
  26873. const { nonce } = await connection.commandAsync((0, utils_1.ns)(`${source}.$cmd`), { getnonce: 1 }, void 0);
  26874. const hashPassword = crypto.createHash("md5").update(`${username}:mongo:${password}`, "utf8").digest("hex");
  26875. const key = crypto.createHash("md5").update(`${nonce}${username}${hashPassword}`, "utf8").digest("hex");
  26876. const authenticateCommand = {
  26877. authenticate: 1,
  26878. user: username,
  26879. nonce,
  26880. key
  26881. };
  26882. await connection.commandAsync((0, utils_1.ns)(`${source}.$cmd`), authenticateCommand, void 0);
  26883. }
  26884. };
  26885. __name(_MongoCR, "MongoCR");
  26886. var MongoCR = _MongoCR;
  26887. exports2.MongoCR = MongoCR;
  26888. }
  26889. });
  26890. // node_modules/mongodb/lib/cmap/auth/mongodb_aws.js
  26891. var require_mongodb_aws = __commonJS({
  26892. "node_modules/mongodb/lib/cmap/auth/mongodb_aws.js"(exports2) {
  26893. "use strict";
  26894. Object.defineProperty(exports2, "__esModule", { value: true });
  26895. exports2.MongoDBAWS = void 0;
  26896. var crypto = require("crypto");
  26897. var process2 = require("process");
  26898. var util_1 = require("util");
  26899. var BSON = require_bson2();
  26900. var deps_1 = require_deps();
  26901. var error_1 = require_error();
  26902. var utils_1 = require_utils();
  26903. var auth_provider_1 = require_auth_provider();
  26904. var mongo_credentials_1 = require_mongo_credentials();
  26905. var providers_1 = require_providers();
  26906. var LEGACY_REGIONS = /* @__PURE__ */ new Set([
  26907. "ap-northeast-1",
  26908. "ap-south-1",
  26909. "ap-southeast-1",
  26910. "ap-southeast-2",
  26911. "aws-global",
  26912. "ca-central-1",
  26913. "eu-central-1",
  26914. "eu-north-1",
  26915. "eu-west-1",
  26916. "eu-west-2",
  26917. "eu-west-3",
  26918. "sa-east-1",
  26919. "us-east-1",
  26920. "us-east-2",
  26921. "us-west-1",
  26922. "us-west-2"
  26923. ]);
  26924. var ASCII_N = 110;
  26925. var AWS_RELATIVE_URI = "http://169.254.170.2";
  26926. var AWS_EC2_URI = "http://169.254.169.254";
  26927. var AWS_EC2_PATH = "/latest/meta-data/iam/security-credentials";
  26928. var bsonOptions = {
  26929. useBigInt64: false,
  26930. promoteLongs: true,
  26931. promoteValues: true,
  26932. promoteBuffers: false,
  26933. bsonRegExp: false
  26934. };
  26935. var _MongoDBAWS = class _MongoDBAWS extends auth_provider_1.AuthProvider {
  26936. constructor() {
  26937. super();
  26938. this.randomBytesAsync = (0, util_1.promisify)(crypto.randomBytes);
  26939. }
  26940. async auth(authContext) {
  26941. const { connection } = authContext;
  26942. if (!authContext.credentials) {
  26943. throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
  26944. }
  26945. if ("kModuleError" in deps_1.aws4) {
  26946. throw deps_1.aws4["kModuleError"];
  26947. }
  26948. const { sign } = deps_1.aws4;
  26949. if ((0, utils_1.maxWireVersion)(connection) < 9) {
  26950. throw new error_1.MongoCompatibilityError("MONGODB-AWS authentication requires MongoDB version 4.4 or later");
  26951. }
  26952. if (!authContext.credentials.username) {
  26953. authContext.credentials = await makeTempCredentials(authContext.credentials);
  26954. }
  26955. const { credentials } = authContext;
  26956. const accessKeyId = credentials.username;
  26957. const secretAccessKey = credentials.password;
  26958. const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN;
  26959. const awsCredentials = accessKeyId && secretAccessKey && sessionToken ? { accessKeyId, secretAccessKey, sessionToken } : accessKeyId && secretAccessKey ? { accessKeyId, secretAccessKey } : void 0;
  26960. const db = credentials.source;
  26961. const nonce = await this.randomBytesAsync(32);
  26962. const saslStart = {
  26963. saslStart: 1,
  26964. mechanism: "MONGODB-AWS",
  26965. payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions)
  26966. };
  26967. const saslStartResponse = await connection.commandAsync((0, utils_1.ns)(`${db}.$cmd`), saslStart, void 0);
  26968. const serverResponse = BSON.deserialize(saslStartResponse.payload.buffer, bsonOptions);
  26969. const host = serverResponse.h;
  26970. const serverNonce = serverResponse.s.buffer;
  26971. if (serverNonce.length !== 64) {
  26972. throw new error_1.MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`);
  26973. }
  26974. if (!utils_1.ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) {
  26975. throw new error_1.MongoRuntimeError("Server nonce does not begin with client nonce");
  26976. }
  26977. if (host.length < 1 || host.length > 255 || host.indexOf("..") !== -1) {
  26978. throw new error_1.MongoRuntimeError(`Server returned an invalid host: "${host}"`);
  26979. }
  26980. const body = "Action=GetCallerIdentity&Version=2011-06-15";
  26981. const options = sign({
  26982. method: "POST",
  26983. host,
  26984. region: deriveRegion(serverResponse.h),
  26985. service: "sts",
  26986. headers: {
  26987. "Content-Type": "application/x-www-form-urlencoded",
  26988. "Content-Length": body.length,
  26989. "X-MongoDB-Server-Nonce": utils_1.ByteUtils.toBase64(serverNonce),
  26990. "X-MongoDB-GS2-CB-Flag": "n"
  26991. },
  26992. path: "/",
  26993. body
  26994. }, awsCredentials);
  26995. const payload = {
  26996. a: options.headers.Authorization,
  26997. d: options.headers["X-Amz-Date"]
  26998. };
  26999. if (sessionToken) {
  27000. payload.t = sessionToken;
  27001. }
  27002. const saslContinue = {
  27003. saslContinue: 1,
  27004. conversationId: 1,
  27005. payload: BSON.serialize(payload, bsonOptions)
  27006. };
  27007. await connection.commandAsync((0, utils_1.ns)(`${db}.$cmd`), saslContinue, void 0);
  27008. }
  27009. };
  27010. __name(_MongoDBAWS, "MongoDBAWS");
  27011. var MongoDBAWS = _MongoDBAWS;
  27012. MongoDBAWS.credentialProvider = null;
  27013. exports2.MongoDBAWS = MongoDBAWS;
  27014. async function makeTempCredentials(credentials) {
  27015. function makeMongoCredentialsFromAWSTemp(creds) {
  27016. if (!creds.AccessKeyId || !creds.SecretAccessKey || !creds.Token) {
  27017. throw new error_1.MongoMissingCredentialsError("Could not obtain temporary MONGODB-AWS credentials");
  27018. }
  27019. return new mongo_credentials_1.MongoCredentials({
  27020. username: creds.AccessKeyId,
  27021. password: creds.SecretAccessKey,
  27022. source: credentials.source,
  27023. mechanism: providers_1.AuthMechanism.MONGODB_AWS,
  27024. mechanismProperties: {
  27025. AWS_SESSION_TOKEN: creds.Token
  27026. }
  27027. });
  27028. }
  27029. __name(makeMongoCredentialsFromAWSTemp, "makeMongoCredentialsFromAWSTemp");
  27030. MongoDBAWS.credentialProvider ?? (MongoDBAWS.credentialProvider = (0, deps_1.getAwsCredentialProvider)());
  27031. if ("kModuleError" in MongoDBAWS.credentialProvider) {
  27032. if (process2.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) {
  27033. return makeMongoCredentialsFromAWSTemp(await (0, utils_1.request)(`${AWS_RELATIVE_URI}${process2.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`));
  27034. }
  27035. const token = await (0, utils_1.request)(`${AWS_EC2_URI}/latest/api/token`, {
  27036. method: "PUT",
  27037. json: false,
  27038. headers: { "X-aws-ec2-metadata-token-ttl-seconds": 30 }
  27039. });
  27040. const roleName = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}`, {
  27041. json: false,
  27042. headers: { "X-aws-ec2-metadata-token": token }
  27043. });
  27044. const creds = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, {
  27045. headers: { "X-aws-ec2-metadata-token": token }
  27046. });
  27047. return makeMongoCredentialsFromAWSTemp(creds);
  27048. } else {
  27049. let { AWS_STS_REGIONAL_ENDPOINTS = "", AWS_REGION = "" } = process2.env;
  27050. AWS_STS_REGIONAL_ENDPOINTS = AWS_STS_REGIONAL_ENDPOINTS.toLowerCase();
  27051. AWS_REGION = AWS_REGION.toLowerCase();
  27052. const awsRegionSettingsExist = AWS_REGION.length !== 0 && AWS_STS_REGIONAL_ENDPOINTS.length !== 0;
  27053. const useRegionalSts = AWS_STS_REGIONAL_ENDPOINTS === "regional" || AWS_STS_REGIONAL_ENDPOINTS === "legacy" && !LEGACY_REGIONS.has(AWS_REGION);
  27054. const provider = awsRegionSettingsExist && useRegionalSts ? MongoDBAWS.credentialProvider.fromNodeProviderChain({
  27055. clientConfig: { region: AWS_REGION }
  27056. }) : MongoDBAWS.credentialProvider.fromNodeProviderChain();
  27057. try {
  27058. const creds = await provider();
  27059. return makeMongoCredentialsFromAWSTemp({
  27060. AccessKeyId: creds.accessKeyId,
  27061. SecretAccessKey: creds.secretAccessKey,
  27062. Token: creds.sessionToken,
  27063. Expiration: creds.expiration
  27064. });
  27065. } catch (error) {
  27066. throw new error_1.MongoAWSError(error.message);
  27067. }
  27068. }
  27069. }
  27070. __name(makeTempCredentials, "makeTempCredentials");
  27071. function deriveRegion(host) {
  27072. const parts = host.split(".");
  27073. if (parts.length === 1 || parts[1] === "amazonaws") {
  27074. return "us-east-1";
  27075. }
  27076. return parts[1];
  27077. }
  27078. __name(deriveRegion, "deriveRegion");
  27079. }
  27080. });
  27081. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js
  27082. var require_service_workflow = __commonJS({
  27083. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js"(exports2) {
  27084. "use strict";
  27085. Object.defineProperty(exports2, "__esModule", { value: true });
  27086. exports2.commandDocument = exports2.ServiceWorkflow = void 0;
  27087. var bson_1 = require_bson();
  27088. var utils_1 = require_utils();
  27089. var providers_1 = require_providers();
  27090. var _ServiceWorkflow = class _ServiceWorkflow {
  27091. /**
  27092. * Execute the workflow. Looks for AWS_WEB_IDENTITY_TOKEN_FILE in the environment
  27093. * and then attempts to read the token from that path.
  27094. */
  27095. async execute(connection, credentials) {
  27096. const token = await this.getToken(credentials);
  27097. const command = commandDocument(token);
  27098. return connection.commandAsync((0, utils_1.ns)(credentials.source), command, void 0);
  27099. }
  27100. /**
  27101. * Get the document to add for speculative authentication.
  27102. */
  27103. async speculativeAuth(credentials) {
  27104. const token = await this.getToken(credentials);
  27105. const document = commandDocument(token);
  27106. document.db = credentials.source;
  27107. return { speculativeAuthenticate: document };
  27108. }
  27109. };
  27110. __name(_ServiceWorkflow, "ServiceWorkflow");
  27111. var ServiceWorkflow = _ServiceWorkflow;
  27112. exports2.ServiceWorkflow = ServiceWorkflow;
  27113. function commandDocument(token) {
  27114. return {
  27115. saslStart: 1,
  27116. mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
  27117. payload: bson_1.BSON.serialize({ jwt: token })
  27118. };
  27119. }
  27120. __name(commandDocument, "commandDocument");
  27121. exports2.commandDocument = commandDocument;
  27122. }
  27123. });
  27124. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js
  27125. var require_aws_service_workflow = __commonJS({
  27126. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js"(exports2) {
  27127. "use strict";
  27128. Object.defineProperty(exports2, "__esModule", { value: true });
  27129. exports2.AwsServiceWorkflow = void 0;
  27130. var fs = require("fs");
  27131. var error_1 = require_error();
  27132. var service_workflow_1 = require_service_workflow();
  27133. var TOKEN_MISSING_ERROR = "AWS_WEB_IDENTITY_TOKEN_FILE must be set in the environment.";
  27134. var _AwsServiceWorkflow = class _AwsServiceWorkflow extends service_workflow_1.ServiceWorkflow {
  27135. constructor() {
  27136. super();
  27137. }
  27138. /**
  27139. * Get the token from the environment.
  27140. */
  27141. async getToken() {
  27142. const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE;
  27143. if (!tokenFile) {
  27144. throw new error_1.MongoAWSError(TOKEN_MISSING_ERROR);
  27145. }
  27146. return fs.promises.readFile(tokenFile, "utf8");
  27147. }
  27148. };
  27149. __name(_AwsServiceWorkflow, "AwsServiceWorkflow");
  27150. var AwsServiceWorkflow = _AwsServiceWorkflow;
  27151. exports2.AwsServiceWorkflow = AwsServiceWorkflow;
  27152. }
  27153. });
  27154. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js
  27155. var require_cache = __commonJS({
  27156. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js"(exports2) {
  27157. "use strict";
  27158. Object.defineProperty(exports2, "__esModule", { value: true });
  27159. exports2.Cache = exports2.ExpiringCacheEntry = void 0;
  27160. var EXPIRATION_BUFFER_MS = 3e5;
  27161. var _ExpiringCacheEntry = class _ExpiringCacheEntry {
  27162. /**
  27163. * Create a new expiring token entry.
  27164. */
  27165. constructor(expiration) {
  27166. this.expiration = this.expirationTime(expiration);
  27167. }
  27168. /**
  27169. * The entry is still valid if the expiration is more than
  27170. * 5 minutes from the expiration time.
  27171. */
  27172. isValid() {
  27173. return this.expiration - Date.now() > EXPIRATION_BUFFER_MS;
  27174. }
  27175. /**
  27176. * Get an expiration time in milliseconds past epoch.
  27177. */
  27178. expirationTime(expiresInSeconds) {
  27179. return Date.now() + expiresInSeconds * 1e3;
  27180. }
  27181. };
  27182. __name(_ExpiringCacheEntry, "ExpiringCacheEntry");
  27183. var ExpiringCacheEntry = _ExpiringCacheEntry;
  27184. exports2.ExpiringCacheEntry = ExpiringCacheEntry;
  27185. var _Cache = class _Cache {
  27186. /**
  27187. * Create a new cache.
  27188. */
  27189. constructor() {
  27190. this.entries = /* @__PURE__ */ new Map();
  27191. }
  27192. /**
  27193. * Clear the cache.
  27194. */
  27195. clear() {
  27196. this.entries.clear();
  27197. }
  27198. /**
  27199. * Create a cache key from the address and username.
  27200. */
  27201. hashedCacheKey(address, username, callbackHash) {
  27202. return JSON.stringify([address, username, callbackHash]);
  27203. }
  27204. };
  27205. __name(_Cache, "Cache");
  27206. var Cache = _Cache;
  27207. exports2.Cache = Cache;
  27208. }
  27209. });
  27210. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js
  27211. var require_azure_token_cache = __commonJS({
  27212. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js"(exports2) {
  27213. "use strict";
  27214. Object.defineProperty(exports2, "__esModule", { value: true });
  27215. exports2.AzureTokenCache = exports2.AzureTokenEntry = void 0;
  27216. var cache_1 = require_cache();
  27217. var _AzureTokenEntry = class _AzureTokenEntry extends cache_1.ExpiringCacheEntry {
  27218. /**
  27219. * Instantiate the entry.
  27220. */
  27221. constructor(token, expiration) {
  27222. super(expiration);
  27223. this.token = token;
  27224. }
  27225. };
  27226. __name(_AzureTokenEntry, "AzureTokenEntry");
  27227. var AzureTokenEntry = _AzureTokenEntry;
  27228. exports2.AzureTokenEntry = AzureTokenEntry;
  27229. var _AzureTokenCache = class _AzureTokenCache extends cache_1.Cache {
  27230. /**
  27231. * Add an entry to the cache.
  27232. */
  27233. addEntry(tokenAudience, token) {
  27234. const entry = new AzureTokenEntry(token.access_token, token.expires_in);
  27235. this.entries.set(tokenAudience, entry);
  27236. return entry;
  27237. }
  27238. /**
  27239. * Create a cache key.
  27240. */
  27241. cacheKey(tokenAudience) {
  27242. return tokenAudience;
  27243. }
  27244. /**
  27245. * Delete an entry from the cache.
  27246. */
  27247. deleteEntry(tokenAudience) {
  27248. this.entries.delete(tokenAudience);
  27249. }
  27250. /**
  27251. * Get an Azure token entry from the cache.
  27252. */
  27253. getEntry(tokenAudience) {
  27254. return this.entries.get(tokenAudience);
  27255. }
  27256. };
  27257. __name(_AzureTokenCache, "AzureTokenCache");
  27258. var AzureTokenCache = _AzureTokenCache;
  27259. exports2.AzureTokenCache = AzureTokenCache;
  27260. }
  27261. });
  27262. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js
  27263. var require_azure_service_workflow = __commonJS({
  27264. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js"(exports2) {
  27265. "use strict";
  27266. Object.defineProperty(exports2, "__esModule", { value: true });
  27267. exports2.AzureServiceWorkflow = void 0;
  27268. var error_1 = require_error();
  27269. var utils_1 = require_utils();
  27270. var azure_token_cache_1 = require_azure_token_cache();
  27271. var service_workflow_1 = require_service_workflow();
  27272. var AZURE_BASE_URL = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01";
  27273. var AZURE_HEADERS = Object.freeze({ Metadata: "true", Accept: "application/json" });
  27274. var ENDPOINT_RESULT_ERROR = "Azure endpoint did not return a value with only access_token and expires_in properties";
  27275. var TOKEN_AUDIENCE_MISSING_ERROR = "TOKEN_AUDIENCE must be set in the auth mechanism properties when PROVIDER_NAME is azure.";
  27276. var _AzureServiceWorkflow = class _AzureServiceWorkflow extends service_workflow_1.ServiceWorkflow {
  27277. constructor() {
  27278. super(...arguments);
  27279. this.cache = new azure_token_cache_1.AzureTokenCache();
  27280. }
  27281. /**
  27282. * Get the token from the environment.
  27283. */
  27284. async getToken(credentials) {
  27285. const tokenAudience = credentials == null ? void 0 : credentials.mechanismProperties.TOKEN_AUDIENCE;
  27286. if (!tokenAudience) {
  27287. throw new error_1.MongoAzureError(TOKEN_AUDIENCE_MISSING_ERROR);
  27288. }
  27289. let token;
  27290. const entry = this.cache.getEntry(tokenAudience);
  27291. if (entry == null ? void 0 : entry.isValid()) {
  27292. token = entry.token;
  27293. } else {
  27294. this.cache.deleteEntry(tokenAudience);
  27295. const response = await getAzureTokenData(tokenAudience);
  27296. if (!isEndpointResultValid(response)) {
  27297. throw new error_1.MongoAzureError(ENDPOINT_RESULT_ERROR);
  27298. }
  27299. this.cache.addEntry(tokenAudience, response);
  27300. token = response.access_token;
  27301. }
  27302. return token;
  27303. }
  27304. };
  27305. __name(_AzureServiceWorkflow, "AzureServiceWorkflow");
  27306. var AzureServiceWorkflow = _AzureServiceWorkflow;
  27307. exports2.AzureServiceWorkflow = AzureServiceWorkflow;
  27308. async function getAzureTokenData(tokenAudience) {
  27309. const url = `${AZURE_BASE_URL}&resource=${tokenAudience}`;
  27310. const data = await (0, utils_1.request)(url, {
  27311. json: true,
  27312. headers: AZURE_HEADERS
  27313. });
  27314. return data;
  27315. }
  27316. __name(getAzureTokenData, "getAzureTokenData");
  27317. function isEndpointResultValid(token) {
  27318. if (token == null || typeof token !== "object")
  27319. return false;
  27320. return "access_token" in token && "expires_in" in token;
  27321. }
  27322. __name(isEndpointResultValid, "isEndpointResultValid");
  27323. }
  27324. });
  27325. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js
  27326. var require_callback_lock_cache = __commonJS({
  27327. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js"(exports2) {
  27328. "use strict";
  27329. Object.defineProperty(exports2, "__esModule", { value: true });
  27330. exports2.CallbackLockCache = void 0;
  27331. var error_1 = require_error();
  27332. var cache_1 = require_cache();
  27333. var REQUEST_CALLBACK_REQUIRED_ERROR = "Auth mechanism property REQUEST_TOKEN_CALLBACK is required.";
  27334. var FN_HASH_COUNTER = 0;
  27335. var NO_FUNCTION = /* @__PURE__ */ __name(async () => ({ accessToken: "test" }), "NO_FUNCTION");
  27336. var FN_HASHES = /* @__PURE__ */ new WeakMap();
  27337. FN_HASHES.set(NO_FUNCTION, FN_HASH_COUNTER);
  27338. var _CallbackLockCache = class _CallbackLockCache extends cache_1.Cache {
  27339. /**
  27340. * Get the callbacks for the connection and credentials. If an entry does not
  27341. * exist a new one will get set.
  27342. */
  27343. getEntry(connection, credentials) {
  27344. const requestCallback = credentials.mechanismProperties.REQUEST_TOKEN_CALLBACK;
  27345. const refreshCallback = credentials.mechanismProperties.REFRESH_TOKEN_CALLBACK;
  27346. if (!requestCallback) {
  27347. throw new error_1.MongoInvalidArgumentError(REQUEST_CALLBACK_REQUIRED_ERROR);
  27348. }
  27349. const callbackHash = hashFunctions(requestCallback, refreshCallback);
  27350. const key = this.cacheKey(connection.address, credentials.username, callbackHash);
  27351. const entry = this.entries.get(key);
  27352. if (entry) {
  27353. return entry;
  27354. }
  27355. return this.addEntry(key, callbackHash, requestCallback, refreshCallback);
  27356. }
  27357. /**
  27358. * Set locked callbacks on for connection and credentials.
  27359. */
  27360. addEntry(key, callbackHash, requestCallback, refreshCallback) {
  27361. const entry = {
  27362. requestCallback: withLock(requestCallback),
  27363. refreshCallback: refreshCallback ? withLock(refreshCallback) : void 0,
  27364. callbackHash
  27365. };
  27366. this.entries.set(key, entry);
  27367. return entry;
  27368. }
  27369. /**
  27370. * Create a cache key from the address and username.
  27371. */
  27372. cacheKey(address, username, callbackHash) {
  27373. return this.hashedCacheKey(address, username, callbackHash);
  27374. }
  27375. };
  27376. __name(_CallbackLockCache, "CallbackLockCache");
  27377. var CallbackLockCache = _CallbackLockCache;
  27378. exports2.CallbackLockCache = CallbackLockCache;
  27379. function withLock(callback) {
  27380. let lock = Promise.resolve();
  27381. return async (info, context) => {
  27382. await lock;
  27383. lock = lock.then(() => callback(info, context));
  27384. return lock;
  27385. };
  27386. }
  27387. __name(withLock, "withLock");
  27388. function hashFunctions(requestFn, refreshFn) {
  27389. let requestHash = FN_HASHES.get(requestFn);
  27390. let refreshHash = FN_HASHES.get(refreshFn ?? NO_FUNCTION);
  27391. if (requestHash == null) {
  27392. FN_HASH_COUNTER++;
  27393. requestHash = FN_HASH_COUNTER;
  27394. FN_HASHES.set(requestFn, FN_HASH_COUNTER);
  27395. }
  27396. if (refreshHash == null && refreshFn) {
  27397. FN_HASH_COUNTER++;
  27398. refreshHash = FN_HASH_COUNTER;
  27399. FN_HASHES.set(refreshFn, FN_HASH_COUNTER);
  27400. }
  27401. return `${requestHash}-${refreshHash}`;
  27402. }
  27403. __name(hashFunctions, "hashFunctions");
  27404. }
  27405. });
  27406. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.js
  27407. var require_token_entry_cache = __commonJS({
  27408. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.js"(exports2) {
  27409. "use strict";
  27410. Object.defineProperty(exports2, "__esModule", { value: true });
  27411. exports2.TokenEntryCache = exports2.TokenEntry = void 0;
  27412. var cache_1 = require_cache();
  27413. var DEFAULT_EXPIRATION_SECS = 0;
  27414. var _TokenEntry = class _TokenEntry extends cache_1.ExpiringCacheEntry {
  27415. /**
  27416. * Instantiate the entry.
  27417. */
  27418. constructor(tokenResult, serverInfo, expiration) {
  27419. super(expiration);
  27420. this.tokenResult = tokenResult;
  27421. this.serverInfo = serverInfo;
  27422. }
  27423. };
  27424. __name(_TokenEntry, "TokenEntry");
  27425. var TokenEntry = _TokenEntry;
  27426. exports2.TokenEntry = TokenEntry;
  27427. var _TokenEntryCache = class _TokenEntryCache extends cache_1.Cache {
  27428. /**
  27429. * Set an entry in the token cache.
  27430. */
  27431. addEntry(address, username, callbackHash, tokenResult, serverInfo) {
  27432. const entry = new TokenEntry(tokenResult, serverInfo, tokenResult.expiresInSeconds ?? DEFAULT_EXPIRATION_SECS);
  27433. this.entries.set(this.cacheKey(address, username, callbackHash), entry);
  27434. return entry;
  27435. }
  27436. /**
  27437. * Delete an entry from the cache.
  27438. */
  27439. deleteEntry(address, username, callbackHash) {
  27440. this.entries.delete(this.cacheKey(address, username, callbackHash));
  27441. }
  27442. /**
  27443. * Get an entry from the cache.
  27444. */
  27445. getEntry(address, username, callbackHash) {
  27446. return this.entries.get(this.cacheKey(address, username, callbackHash));
  27447. }
  27448. /**
  27449. * Delete all expired entries from the cache.
  27450. */
  27451. deleteExpiredEntries() {
  27452. for (const [key, entry] of this.entries) {
  27453. if (!entry.isValid()) {
  27454. this.entries.delete(key);
  27455. }
  27456. }
  27457. }
  27458. /**
  27459. * Create a cache key from the address and username.
  27460. */
  27461. cacheKey(address, username, callbackHash) {
  27462. return this.hashedCacheKey(address, username, callbackHash);
  27463. }
  27464. };
  27465. __name(_TokenEntryCache, "TokenEntryCache");
  27466. var TokenEntryCache = _TokenEntryCache;
  27467. exports2.TokenEntryCache = TokenEntryCache;
  27468. }
  27469. });
  27470. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js
  27471. var require_callback_workflow = __commonJS({
  27472. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js"(exports2) {
  27473. "use strict";
  27474. Object.defineProperty(exports2, "__esModule", { value: true });
  27475. exports2.CallbackWorkflow = void 0;
  27476. var bson_1 = require_bson();
  27477. var error_1 = require_error();
  27478. var utils_1 = require_utils();
  27479. var providers_1 = require_providers();
  27480. var callback_lock_cache_1 = require_callback_lock_cache();
  27481. var token_entry_cache_1 = require_token_entry_cache();
  27482. var OIDC_VERSION = 0;
  27483. var TIMEOUT_S = 300;
  27484. var RESULT_PROPERTIES = ["accessToken", "expiresInSeconds", "refreshToken"];
  27485. var CALLBACK_RESULT_ERROR = "User provided OIDC callbacks must return a valid object with an accessToken.";
  27486. var _CallbackWorkflow = class _CallbackWorkflow {
  27487. /**
  27488. * Instantiate the workflow
  27489. */
  27490. constructor() {
  27491. this.cache = new token_entry_cache_1.TokenEntryCache();
  27492. this.callbackCache = new callback_lock_cache_1.CallbackLockCache();
  27493. }
  27494. /**
  27495. * Get the document to add for speculative authentication. This also needs
  27496. * to add a db field from the credentials source.
  27497. */
  27498. async speculativeAuth(credentials) {
  27499. const document = startCommandDocument(credentials);
  27500. document.db = credentials.source;
  27501. return { speculativeAuthenticate: document };
  27502. }
  27503. /**
  27504. * Execute the OIDC callback workflow.
  27505. */
  27506. async execute(connection, credentials, reauthenticating, response) {
  27507. var _a, _b;
  27508. const { requestCallback, refreshCallback, callbackHash } = this.callbackCache.getEntry(connection, credentials);
  27509. const entry = this.cache.getEntry(connection.address, credentials.username, callbackHash);
  27510. let result;
  27511. if (entry) {
  27512. if (entry.isValid() && !reauthenticating) {
  27513. result = await this.finishAuthentication(connection, credentials, entry.tokenResult, (_a = response == null ? void 0 : response.speculativeAuthenticate) == null ? void 0 : _a.conversationId);
  27514. } else {
  27515. const tokenResult = await this.fetchAccessToken(connection, credentials, entry.serverInfo, reauthenticating, callbackHash, requestCallback, refreshCallback);
  27516. try {
  27517. result = await this.finishAuthentication(connection, credentials, tokenResult, reauthenticating ? void 0 : (_b = response == null ? void 0 : response.speculativeAuthenticate) == null ? void 0 : _b.conversationId);
  27518. } catch (error) {
  27519. if (reauthenticating && error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) {
  27520. this.cache.deleteEntry(connection.address, credentials.username, callbackHash);
  27521. result = await this.execute(connection, credentials, reauthenticating);
  27522. } else {
  27523. throw error;
  27524. }
  27525. }
  27526. }
  27527. } else {
  27528. const startDocument = await this.startAuthentication(connection, credentials, reauthenticating, response);
  27529. const conversationId = startDocument.conversationId;
  27530. const serverResult = bson_1.BSON.deserialize(startDocument.payload.buffer);
  27531. const tokenResult = await this.fetchAccessToken(connection, credentials, serverResult, reauthenticating, callbackHash, requestCallback, refreshCallback);
  27532. result = await this.finishAuthentication(connection, credentials, tokenResult, conversationId);
  27533. }
  27534. return result;
  27535. }
  27536. /**
  27537. * Starts the callback authentication process. If there is a speculative
  27538. * authentication document from the initial handshake, then we will use that
  27539. * value to get the issuer, otherwise we will send the saslStart command.
  27540. */
  27541. async startAuthentication(connection, credentials, reauthenticating, response) {
  27542. let result;
  27543. if (!reauthenticating && (response == null ? void 0 : response.speculativeAuthenticate)) {
  27544. result = response.speculativeAuthenticate;
  27545. } else {
  27546. result = await connection.commandAsync((0, utils_1.ns)(credentials.source), startCommandDocument(credentials), void 0);
  27547. }
  27548. return result;
  27549. }
  27550. /**
  27551. * Finishes the callback authentication process.
  27552. */
  27553. async finishAuthentication(connection, credentials, tokenResult, conversationId) {
  27554. const result = await connection.commandAsync((0, utils_1.ns)(credentials.source), finishCommandDocument(tokenResult.accessToken, conversationId), void 0);
  27555. return result;
  27556. }
  27557. /**
  27558. * Fetches an access token using either the request or refresh callbacks and
  27559. * puts it in the cache.
  27560. */
  27561. async fetchAccessToken(connection, credentials, serverInfo, reauthenticating, callbackHash, requestCallback, refreshCallback) {
  27562. const entry = this.cache.getEntry(connection.address, credentials.username, callbackHash);
  27563. let result;
  27564. const context = { timeoutSeconds: TIMEOUT_S, version: OIDC_VERSION };
  27565. if (entry) {
  27566. if (entry.isValid() && !reauthenticating) {
  27567. return entry.tokenResult;
  27568. }
  27569. if (refreshCallback) {
  27570. context.refreshToken = entry.tokenResult.refreshToken;
  27571. result = await refreshCallback(serverInfo, context);
  27572. } else {
  27573. result = await requestCallback(serverInfo, context);
  27574. }
  27575. } else {
  27576. result = await requestCallback(serverInfo, context);
  27577. }
  27578. if (isCallbackResultInvalid(result)) {
  27579. this.cache.deleteEntry(connection.address, credentials.username, callbackHash);
  27580. throw new error_1.MongoMissingCredentialsError(CALLBACK_RESULT_ERROR);
  27581. }
  27582. this.cache.deleteExpiredEntries();
  27583. this.cache.addEntry(connection.address, credentials.username || "", callbackHash, result, serverInfo);
  27584. return result;
  27585. }
  27586. };
  27587. __name(_CallbackWorkflow, "CallbackWorkflow");
  27588. var CallbackWorkflow = _CallbackWorkflow;
  27589. exports2.CallbackWorkflow = CallbackWorkflow;
  27590. function finishCommandDocument(token, conversationId) {
  27591. if (conversationId != null && typeof conversationId === "number") {
  27592. return {
  27593. saslContinue: 1,
  27594. conversationId,
  27595. payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token }))
  27596. };
  27597. }
  27598. return {
  27599. saslStart: 1,
  27600. mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
  27601. payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token }))
  27602. };
  27603. }
  27604. __name(finishCommandDocument, "finishCommandDocument");
  27605. function isCallbackResultInvalid(tokenResult) {
  27606. if (tokenResult == null || typeof tokenResult !== "object")
  27607. return true;
  27608. if (!("accessToken" in tokenResult))
  27609. return true;
  27610. return !Object.getOwnPropertyNames(tokenResult).every((prop) => RESULT_PROPERTIES.includes(prop));
  27611. }
  27612. __name(isCallbackResultInvalid, "isCallbackResultInvalid");
  27613. function startCommandDocument(credentials) {
  27614. const payload = {};
  27615. if (credentials.username) {
  27616. payload.n = credentials.username;
  27617. }
  27618. return {
  27619. saslStart: 1,
  27620. autoAuthorize: 1,
  27621. mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
  27622. payload: new bson_1.Binary(bson_1.BSON.serialize(payload))
  27623. };
  27624. }
  27625. __name(startCommandDocument, "startCommandDocument");
  27626. }
  27627. });
  27628. // node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js
  27629. var require_mongodb_oidc = __commonJS({
  27630. "node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js"(exports2) {
  27631. "use strict";
  27632. Object.defineProperty(exports2, "__esModule", { value: true });
  27633. exports2.MongoDBOIDC = exports2.OIDC_WORKFLOWS = void 0;
  27634. var error_1 = require_error();
  27635. var auth_provider_1 = require_auth_provider();
  27636. var aws_service_workflow_1 = require_aws_service_workflow();
  27637. var azure_service_workflow_1 = require_azure_service_workflow();
  27638. var callback_workflow_1 = require_callback_workflow();
  27639. var MISSING_CREDENTIALS_ERROR = "AuthContext must provide credentials.";
  27640. exports2.OIDC_WORKFLOWS = /* @__PURE__ */ new Map();
  27641. exports2.OIDC_WORKFLOWS.set("callback", new callback_workflow_1.CallbackWorkflow());
  27642. exports2.OIDC_WORKFLOWS.set("aws", new aws_service_workflow_1.AwsServiceWorkflow());
  27643. exports2.OIDC_WORKFLOWS.set("azure", new azure_service_workflow_1.AzureServiceWorkflow());
  27644. var _MongoDBOIDC = class _MongoDBOIDC extends auth_provider_1.AuthProvider {
  27645. /**
  27646. * Instantiate the auth provider.
  27647. */
  27648. constructor() {
  27649. super();
  27650. }
  27651. /**
  27652. * Authenticate using OIDC
  27653. */
  27654. async auth(authContext) {
  27655. const { connection, reauthenticating, response } = authContext;
  27656. const credentials = getCredentials(authContext);
  27657. const workflow = getWorkflow(credentials);
  27658. await workflow.execute(connection, credentials, reauthenticating, response);
  27659. }
  27660. /**
  27661. * Add the speculative auth for the initial handshake.
  27662. */
  27663. async prepare(handshakeDoc, authContext) {
  27664. const credentials = getCredentials(authContext);
  27665. const workflow = getWorkflow(credentials);
  27666. const result = await workflow.speculativeAuth(credentials);
  27667. return { ...handshakeDoc, ...result };
  27668. }
  27669. };
  27670. __name(_MongoDBOIDC, "MongoDBOIDC");
  27671. var MongoDBOIDC = _MongoDBOIDC;
  27672. exports2.MongoDBOIDC = MongoDBOIDC;
  27673. function getCredentials(authContext) {
  27674. const { credentials } = authContext;
  27675. if (!credentials) {
  27676. throw new error_1.MongoMissingCredentialsError(MISSING_CREDENTIALS_ERROR);
  27677. }
  27678. return credentials;
  27679. }
  27680. __name(getCredentials, "getCredentials");
  27681. function getWorkflow(credentials) {
  27682. const providerName = credentials.mechanismProperties.PROVIDER_NAME;
  27683. const workflow = exports2.OIDC_WORKFLOWS.get(providerName || "callback");
  27684. if (!workflow) {
  27685. throw new error_1.MongoInvalidArgumentError(`Could not load workflow for provider ${credentials.mechanismProperties.PROVIDER_NAME}`);
  27686. }
  27687. return workflow;
  27688. }
  27689. __name(getWorkflow, "getWorkflow");
  27690. }
  27691. });
  27692. // node_modules/mongodb/lib/cmap/auth/plain.js
  27693. var require_plain = __commonJS({
  27694. "node_modules/mongodb/lib/cmap/auth/plain.js"(exports2) {
  27695. "use strict";
  27696. Object.defineProperty(exports2, "__esModule", { value: true });
  27697. exports2.Plain = void 0;
  27698. var bson_1 = require_bson2();
  27699. var error_1 = require_error();
  27700. var utils_1 = require_utils();
  27701. var auth_provider_1 = require_auth_provider();
  27702. var _Plain = class _Plain extends auth_provider_1.AuthProvider {
  27703. async auth(authContext) {
  27704. const { connection, credentials } = authContext;
  27705. if (!credentials) {
  27706. throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
  27707. }
  27708. const { username, password } = credentials;
  27709. const payload = new bson_1.Binary(Buffer.from(`\0${username}\0${password}`));
  27710. const command = {
  27711. saslStart: 1,
  27712. mechanism: "PLAIN",
  27713. payload,
  27714. autoAuthorize: 1
  27715. };
  27716. await connection.commandAsync((0, utils_1.ns)("$external.$cmd"), command, void 0);
  27717. }
  27718. };
  27719. __name(_Plain, "Plain");
  27720. var Plain = _Plain;
  27721. exports2.Plain = Plain;
  27722. }
  27723. });
  27724. // node_modules/mongodb/lib/cmap/auth/scram.js
  27725. var require_scram = __commonJS({
  27726. "node_modules/mongodb/lib/cmap/auth/scram.js"(exports2) {
  27727. "use strict";
  27728. Object.defineProperty(exports2, "__esModule", { value: true });
  27729. exports2.ScramSHA256 = exports2.ScramSHA1 = void 0;
  27730. var crypto = require("crypto");
  27731. var util_1 = require("util");
  27732. var bson_1 = require_bson2();
  27733. var deps_1 = require_deps();
  27734. var error_1 = require_error();
  27735. var utils_1 = require_utils();
  27736. var auth_provider_1 = require_auth_provider();
  27737. var providers_1 = require_providers();
  27738. var _ScramSHA = class _ScramSHA extends auth_provider_1.AuthProvider {
  27739. constructor(cryptoMethod) {
  27740. super();
  27741. this.cryptoMethod = cryptoMethod || "sha1";
  27742. this.randomBytesAsync = (0, util_1.promisify)(crypto.randomBytes);
  27743. }
  27744. async prepare(handshakeDoc, authContext) {
  27745. const cryptoMethod = this.cryptoMethod;
  27746. const credentials = authContext.credentials;
  27747. if (!credentials) {
  27748. throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
  27749. }
  27750. if (cryptoMethod === "sha256" && ("kModuleError" in deps_1.saslprep || typeof deps_1.saslprep !== "function")) {
  27751. (0, utils_1.emitWarning)("Warning: no saslprep library specified. Passwords will not be sanitized");
  27752. }
  27753. const nonce = await this.randomBytesAsync(24);
  27754. authContext.nonce = nonce;
  27755. const request = {
  27756. ...handshakeDoc,
  27757. speculativeAuthenticate: {
  27758. ...makeFirstMessage(cryptoMethod, credentials, nonce),
  27759. db: credentials.source
  27760. }
  27761. };
  27762. return request;
  27763. }
  27764. async auth(authContext) {
  27765. const { reauthenticating, response } = authContext;
  27766. if ((response == null ? void 0 : response.speculativeAuthenticate) && !reauthenticating) {
  27767. return continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext);
  27768. }
  27769. return executeScram(this.cryptoMethod, authContext);
  27770. }
  27771. };
  27772. __name(_ScramSHA, "ScramSHA");
  27773. var ScramSHA = _ScramSHA;
  27774. function cleanUsername(username) {
  27775. return username.replace("=", "=3D").replace(",", "=2C");
  27776. }
  27777. __name(cleanUsername, "cleanUsername");
  27778. function clientFirstMessageBare(username, nonce) {
  27779. return Buffer.concat([
  27780. Buffer.from("n=", "utf8"),
  27781. Buffer.from(username, "utf8"),
  27782. Buffer.from(",r=", "utf8"),
  27783. Buffer.from(nonce.toString("base64"), "utf8")
  27784. ]);
  27785. }
  27786. __name(clientFirstMessageBare, "clientFirstMessageBare");
  27787. function makeFirstMessage(cryptoMethod, credentials, nonce) {
  27788. const username = cleanUsername(credentials.username);
  27789. const mechanism = cryptoMethod === "sha1" ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA256;
  27790. return {
  27791. saslStart: 1,
  27792. mechanism,
  27793. payload: new bson_1.Binary(Buffer.concat([Buffer.from("n,,", "utf8"), clientFirstMessageBare(username, nonce)])),
  27794. autoAuthorize: 1,
  27795. options: { skipEmptyExchange: true }
  27796. };
  27797. }
  27798. __name(makeFirstMessage, "makeFirstMessage");
  27799. async function executeScram(cryptoMethod, authContext) {
  27800. const { connection, credentials } = authContext;
  27801. if (!credentials) {
  27802. throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
  27803. }
  27804. if (!authContext.nonce) {
  27805. throw new error_1.MongoInvalidArgumentError("AuthContext must contain a valid nonce property");
  27806. }
  27807. const nonce = authContext.nonce;
  27808. const db = credentials.source;
  27809. const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce);
  27810. const response = await connection.commandAsync((0, utils_1.ns)(`${db}.$cmd`), saslStartCmd, void 0);
  27811. await continueScramConversation(cryptoMethod, response, authContext);
  27812. }
  27813. __name(executeScram, "executeScram");
  27814. async function continueScramConversation(cryptoMethod, response, authContext) {
  27815. const connection = authContext.connection;
  27816. const credentials = authContext.credentials;
  27817. if (!credentials) {
  27818. throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
  27819. }
  27820. if (!authContext.nonce) {
  27821. throw new error_1.MongoInvalidArgumentError("Unable to continue SCRAM without valid nonce");
  27822. }
  27823. const nonce = authContext.nonce;
  27824. const db = credentials.source;
  27825. const username = cleanUsername(credentials.username);
  27826. const password = credentials.password;
  27827. let processedPassword;
  27828. if (cryptoMethod === "sha256") {
  27829. processedPassword = "kModuleError" in deps_1.saslprep || typeof deps_1.saslprep !== "function" ? password : (0, deps_1.saslprep)(password);
  27830. } else {
  27831. processedPassword = passwordDigest(username, password);
  27832. }
  27833. const payload = Buffer.isBuffer(response.payload) ? new bson_1.Binary(response.payload) : response.payload;
  27834. const dict = parsePayload(payload.value());
  27835. const iterations = parseInt(dict.i, 10);
  27836. if (iterations && iterations < 4096) {
  27837. throw new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`);
  27838. }
  27839. const salt = dict.s;
  27840. const rnonce = dict.r;
  27841. if (rnonce.startsWith("nonce")) {
  27842. throw new error_1.MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`);
  27843. }
  27844. const withoutProof = `c=biws,r=${rnonce}`;
  27845. const saltedPassword = HI(processedPassword, Buffer.from(salt, "base64"), iterations, cryptoMethod);
  27846. const clientKey = HMAC(cryptoMethod, saltedPassword, "Client Key");
  27847. const serverKey = HMAC(cryptoMethod, saltedPassword, "Server Key");
  27848. const storedKey = H(cryptoMethod, clientKey);
  27849. const authMessage = [clientFirstMessageBare(username, nonce), payload.value(), withoutProof].join(",");
  27850. const clientSignature = HMAC(cryptoMethod, storedKey, authMessage);
  27851. const clientProof = `p=${xor(clientKey, clientSignature)}`;
  27852. const clientFinal = [withoutProof, clientProof].join(",");
  27853. const serverSignature = HMAC(cryptoMethod, serverKey, authMessage);
  27854. const saslContinueCmd = {
  27855. saslContinue: 1,
  27856. conversationId: response.conversationId,
  27857. payload: new bson_1.Binary(Buffer.from(clientFinal))
  27858. };
  27859. const r = await connection.commandAsync((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, void 0);
  27860. const parsedResponse = parsePayload(r.payload.value());
  27861. if (!compareDigest(Buffer.from(parsedResponse.v, "base64"), serverSignature)) {
  27862. throw new error_1.MongoRuntimeError("Server returned an invalid signature");
  27863. }
  27864. if (r.done !== false) {
  27865. return;
  27866. }
  27867. const retrySaslContinueCmd = {
  27868. saslContinue: 1,
  27869. conversationId: r.conversationId,
  27870. payload: Buffer.alloc(0)
  27871. };
  27872. await connection.commandAsync((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, void 0);
  27873. }
  27874. __name(continueScramConversation, "continueScramConversation");
  27875. function parsePayload(payload) {
  27876. const dict = {};
  27877. const parts = payload.split(",");
  27878. for (let i = 0; i < parts.length; i++) {
  27879. const valueParts = parts[i].split("=");
  27880. dict[valueParts[0]] = valueParts[1];
  27881. }
  27882. return dict;
  27883. }
  27884. __name(parsePayload, "parsePayload");
  27885. function passwordDigest(username, password) {
  27886. if (typeof username !== "string") {
  27887. throw new error_1.MongoInvalidArgumentError("Username must be a string");
  27888. }
  27889. if (typeof password !== "string") {
  27890. throw new error_1.MongoInvalidArgumentError("Password must be a string");
  27891. }
  27892. if (password.length === 0) {
  27893. throw new error_1.MongoInvalidArgumentError("Password cannot be empty");
  27894. }
  27895. let md5;
  27896. try {
  27897. md5 = crypto.createHash("md5");
  27898. } catch (err) {
  27899. if (crypto.getFips()) {
  27900. throw new Error("Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode");
  27901. }
  27902. throw err;
  27903. }
  27904. md5.update(`${username}:mongo:${password}`, "utf8");
  27905. return md5.digest("hex");
  27906. }
  27907. __name(passwordDigest, "passwordDigest");
  27908. function xor(a, b) {
  27909. if (!Buffer.isBuffer(a)) {
  27910. a = Buffer.from(a);
  27911. }
  27912. if (!Buffer.isBuffer(b)) {
  27913. b = Buffer.from(b);
  27914. }
  27915. const length = Math.max(a.length, b.length);
  27916. const res = [];
  27917. for (let i = 0; i < length; i += 1) {
  27918. res.push(a[i] ^ b[i]);
  27919. }
  27920. return Buffer.from(res).toString("base64");
  27921. }
  27922. __name(xor, "xor");
  27923. function H(method, text) {
  27924. return crypto.createHash(method).update(text).digest();
  27925. }
  27926. __name(H, "H");
  27927. function HMAC(method, key, text) {
  27928. return crypto.createHmac(method, key).update(text).digest();
  27929. }
  27930. __name(HMAC, "HMAC");
  27931. var _hiCache = {};
  27932. var _hiCacheCount = 0;
  27933. function _hiCachePurge() {
  27934. _hiCache = {};
  27935. _hiCacheCount = 0;
  27936. }
  27937. __name(_hiCachePurge, "_hiCachePurge");
  27938. var hiLengthMap = {
  27939. sha256: 32,
  27940. sha1: 20
  27941. };
  27942. function HI(data, salt, iterations, cryptoMethod) {
  27943. const key = [data, salt.toString("base64"), iterations].join("_");
  27944. if (_hiCache[key] != null) {
  27945. return _hiCache[key];
  27946. }
  27947. const saltedData = crypto.pbkdf2Sync(data, salt, iterations, hiLengthMap[cryptoMethod], cryptoMethod);
  27948. if (_hiCacheCount >= 200) {
  27949. _hiCachePurge();
  27950. }
  27951. _hiCache[key] = saltedData;
  27952. _hiCacheCount += 1;
  27953. return saltedData;
  27954. }
  27955. __name(HI, "HI");
  27956. function compareDigest(lhs, rhs) {
  27957. if (lhs.length !== rhs.length) {
  27958. return false;
  27959. }
  27960. if (typeof crypto.timingSafeEqual === "function") {
  27961. return crypto.timingSafeEqual(lhs, rhs);
  27962. }
  27963. let result = 0;
  27964. for (let i = 0; i < lhs.length; i++) {
  27965. result |= lhs[i] ^ rhs[i];
  27966. }
  27967. return result === 0;
  27968. }
  27969. __name(compareDigest, "compareDigest");
  27970. var _ScramSHA1 = class _ScramSHA1 extends ScramSHA {
  27971. constructor() {
  27972. super("sha1");
  27973. }
  27974. };
  27975. __name(_ScramSHA1, "ScramSHA1");
  27976. var ScramSHA1 = _ScramSHA1;
  27977. exports2.ScramSHA1 = ScramSHA1;
  27978. var _ScramSHA256 = class _ScramSHA256 extends ScramSHA {
  27979. constructor() {
  27980. super("sha256");
  27981. }
  27982. };
  27983. __name(_ScramSHA256, "ScramSHA256");
  27984. var ScramSHA256 = _ScramSHA256;
  27985. exports2.ScramSHA256 = ScramSHA256;
  27986. }
  27987. });
  27988. // node_modules/mongodb/lib/cmap/auth/x509.js
  27989. var require_x509 = __commonJS({
  27990. "node_modules/mongodb/lib/cmap/auth/x509.js"(exports2) {
  27991. "use strict";
  27992. Object.defineProperty(exports2, "__esModule", { value: true });
  27993. exports2.X509 = void 0;
  27994. var error_1 = require_error();
  27995. var utils_1 = require_utils();
  27996. var auth_provider_1 = require_auth_provider();
  27997. var _X509 = class _X509 extends auth_provider_1.AuthProvider {
  27998. async prepare(handshakeDoc, authContext) {
  27999. const { credentials } = authContext;
  28000. if (!credentials) {
  28001. throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
  28002. }
  28003. return { ...handshakeDoc, speculativeAuthenticate: x509AuthenticateCommand(credentials) };
  28004. }
  28005. async auth(authContext) {
  28006. const connection = authContext.connection;
  28007. const credentials = authContext.credentials;
  28008. if (!credentials) {
  28009. throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials.");
  28010. }
  28011. const response = authContext.response;
  28012. if (response == null ? void 0 : response.speculativeAuthenticate) {
  28013. return;
  28014. }
  28015. await connection.commandAsync((0, utils_1.ns)("$external.$cmd"), x509AuthenticateCommand(credentials), void 0);
  28016. }
  28017. };
  28018. __name(_X509, "X509");
  28019. var X509 = _X509;
  28020. exports2.X509 = X509;
  28021. function x509AuthenticateCommand(credentials) {
  28022. const command = { authenticate: 1, mechanism: "MONGODB-X509" };
  28023. if (credentials.username) {
  28024. command.user = credentials.username;
  28025. }
  28026. return command;
  28027. }
  28028. __name(x509AuthenticateCommand, "x509AuthenticateCommand");
  28029. }
  28030. });
  28031. // node_modules/mongodb/lib/cmap/connect.js
  28032. var require_connect = __commonJS({
  28033. "node_modules/mongodb/lib/cmap/connect.js"(exports2) {
  28034. "use strict";
  28035. Object.defineProperty(exports2, "__esModule", { value: true });
  28036. exports2.LEGAL_TCP_SOCKET_OPTIONS = exports2.LEGAL_TLS_SOCKET_OPTIONS = exports2.prepareHandshakeDocument = exports2.connect = exports2.AUTH_PROVIDERS = void 0;
  28037. var net = require("net");
  28038. var socks_1 = require_build();
  28039. var tls = require("tls");
  28040. var constants_1 = require_constants2();
  28041. var error_1 = require_error();
  28042. var utils_1 = require_utils();
  28043. var auth_provider_1 = require_auth_provider();
  28044. var gssapi_1 = require_gssapi();
  28045. var mongocr_1 = require_mongocr();
  28046. var mongodb_aws_1 = require_mongodb_aws();
  28047. var mongodb_oidc_1 = require_mongodb_oidc();
  28048. var plain_1 = require_plain();
  28049. var providers_1 = require_providers();
  28050. var scram_1 = require_scram();
  28051. var x509_1 = require_x509();
  28052. var connection_1 = require_connection();
  28053. var constants_2 = require_constants();
  28054. exports2.AUTH_PROVIDERS = /* @__PURE__ */ new Map([
  28055. [providers_1.AuthMechanism.MONGODB_AWS, new mongodb_aws_1.MongoDBAWS()],
  28056. [providers_1.AuthMechanism.MONGODB_CR, new mongocr_1.MongoCR()],
  28057. [providers_1.AuthMechanism.MONGODB_GSSAPI, new gssapi_1.GSSAPI()],
  28058. [providers_1.AuthMechanism.MONGODB_OIDC, new mongodb_oidc_1.MongoDBOIDC()],
  28059. [providers_1.AuthMechanism.MONGODB_PLAIN, new plain_1.Plain()],
  28060. [providers_1.AuthMechanism.MONGODB_SCRAM_SHA1, new scram_1.ScramSHA1()],
  28061. [providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, new scram_1.ScramSHA256()],
  28062. [providers_1.AuthMechanism.MONGODB_X509, new x509_1.X509()]
  28063. ]);
  28064. function connect(options, callback) {
  28065. makeConnection({ ...options, existingSocket: void 0 }, (err, socket) => {
  28066. if (err || !socket) {
  28067. return callback(err);
  28068. }
  28069. let ConnectionType = options.connectionType ?? connection_1.Connection;
  28070. if (options.autoEncrypter) {
  28071. ConnectionType = connection_1.CryptoConnection;
  28072. }
  28073. const connection = new ConnectionType(socket, options);
  28074. performInitialHandshake(connection, options).then(() => callback(void 0, connection), (error) => {
  28075. connection.destroy({ force: false });
  28076. callback(error);
  28077. });
  28078. });
  28079. }
  28080. __name(connect, "connect");
  28081. exports2.connect = connect;
  28082. function checkSupportedServer(hello, options) {
  28083. const maxWireVersion = Number(hello.maxWireVersion);
  28084. const minWireVersion = Number(hello.minWireVersion);
  28085. const serverVersionHighEnough = !Number.isNaN(maxWireVersion) && maxWireVersion >= constants_2.MIN_SUPPORTED_WIRE_VERSION;
  28086. const serverVersionLowEnough = !Number.isNaN(minWireVersion) && minWireVersion <= constants_2.MAX_SUPPORTED_WIRE_VERSION;
  28087. if (serverVersionHighEnough) {
  28088. if (serverVersionLowEnough) {
  28089. return null;
  28090. }
  28091. const message2 = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify(hello.minWireVersion)}, but this version of the Node.js Driver requires at most ${constants_2.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MAX_SUPPORTED_SERVER_VERSION})`;
  28092. return new error_1.MongoCompatibilityError(message2);
  28093. }
  28094. const message = `Server at ${options.hostAddress} reports maximum wire version ${JSON.stringify(hello.maxWireVersion) ?? 0}, but this version of the Node.js Driver requires at least ${constants_2.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MIN_SUPPORTED_SERVER_VERSION})`;
  28095. return new error_1.MongoCompatibilityError(message);
  28096. }
  28097. __name(checkSupportedServer, "checkSupportedServer");
  28098. async function performInitialHandshake(conn, options) {
  28099. const credentials = options.credentials;
  28100. if (credentials) {
  28101. if (!(credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT) && !exports2.AUTH_PROVIDERS.get(credentials.mechanism)) {
  28102. throw new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`);
  28103. }
  28104. }
  28105. const authContext = new auth_provider_1.AuthContext(conn, credentials, options);
  28106. conn.authContext = authContext;
  28107. const handshakeDoc = await prepareHandshakeDocument(authContext);
  28108. const handshakeOptions = { ...options };
  28109. if (typeof options.connectTimeoutMS === "number") {
  28110. handshakeOptions.socketTimeoutMS = options.connectTimeoutMS;
  28111. }
  28112. const start = (/* @__PURE__ */ new Date()).getTime();
  28113. const response = await conn.commandAsync((0, utils_1.ns)("admin.$cmd"), handshakeDoc, handshakeOptions);
  28114. if (!("isWritablePrimary" in response)) {
  28115. response.isWritablePrimary = response[constants_1.LEGACY_HELLO_COMMAND];
  28116. }
  28117. if (response.helloOk) {
  28118. conn.helloOk = true;
  28119. }
  28120. const supportedServerErr = checkSupportedServer(response, options);
  28121. if (supportedServerErr) {
  28122. throw supportedServerErr;
  28123. }
  28124. if (options.loadBalanced) {
  28125. if (!response.serviceId) {
  28126. throw new error_1.MongoCompatibilityError("Driver attempted to initialize in load balancing mode, but the server does not support this mode.");
  28127. }
  28128. }
  28129. conn.hello = response;
  28130. conn.lastHelloMS = (/* @__PURE__ */ new Date()).getTime() - start;
  28131. if (!response.arbiterOnly && credentials) {
  28132. authContext.response = response;
  28133. const resolvedCredentials = credentials.resolveAuthMechanism(response);
  28134. const provider = exports2.AUTH_PROVIDERS.get(resolvedCredentials.mechanism);
  28135. if (!provider) {
  28136. throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`);
  28137. }
  28138. try {
  28139. await provider.auth(authContext);
  28140. } catch (error) {
  28141. if (error instanceof error_1.MongoError) {
  28142. error.addErrorLabel(error_1.MongoErrorLabel.HandshakeError);
  28143. if ((0, error_1.needsRetryableWriteLabel)(error, response.maxWireVersion)) {
  28144. error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
  28145. }
  28146. }
  28147. throw error;
  28148. }
  28149. }
  28150. }
  28151. __name(performInitialHandshake, "performInitialHandshake");
  28152. async function prepareHandshakeDocument(authContext) {
  28153. const options = authContext.options;
  28154. const compressors = options.compressors ? options.compressors : [];
  28155. const { serverApi } = authContext.connection;
  28156. const handshakeDoc = {
  28157. [(serverApi == null ? void 0 : serverApi.version) ? "hello" : constants_1.LEGACY_HELLO_COMMAND]: 1,
  28158. helloOk: true,
  28159. client: options.metadata,
  28160. compression: compressors
  28161. };
  28162. if (options.loadBalanced === true) {
  28163. handshakeDoc.loadBalanced = true;
  28164. }
  28165. const credentials = authContext.credentials;
  28166. if (credentials) {
  28167. if (credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) {
  28168. handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`;
  28169. const provider2 = exports2.AUTH_PROVIDERS.get(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256);
  28170. if (!provider2) {
  28171. throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${providers_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`);
  28172. }
  28173. return provider2.prepare(handshakeDoc, authContext);
  28174. }
  28175. const provider = exports2.AUTH_PROVIDERS.get(credentials.mechanism);
  28176. if (!provider) {
  28177. throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`);
  28178. }
  28179. return provider.prepare(handshakeDoc, authContext);
  28180. }
  28181. return handshakeDoc;
  28182. }
  28183. __name(prepareHandshakeDocument, "prepareHandshakeDocument");
  28184. exports2.prepareHandshakeDocument = prepareHandshakeDocument;
  28185. exports2.LEGAL_TLS_SOCKET_OPTIONS = [
  28186. "ALPNProtocols",
  28187. "ca",
  28188. "cert",
  28189. "checkServerIdentity",
  28190. "ciphers",
  28191. "crl",
  28192. "ecdhCurve",
  28193. "key",
  28194. "minDHSize",
  28195. "passphrase",
  28196. "pfx",
  28197. "rejectUnauthorized",
  28198. "secureContext",
  28199. "secureProtocol",
  28200. "servername",
  28201. "session"
  28202. ];
  28203. exports2.LEGAL_TCP_SOCKET_OPTIONS = [
  28204. "family",
  28205. "hints",
  28206. "localAddress",
  28207. "localPort",
  28208. "lookup"
  28209. ];
  28210. function parseConnectOptions(options) {
  28211. const hostAddress = options.hostAddress;
  28212. if (!hostAddress)
  28213. throw new error_1.MongoInvalidArgumentError('Option "hostAddress" is required');
  28214. const result = {};
  28215. for (const name of exports2.LEGAL_TCP_SOCKET_OPTIONS) {
  28216. if (options[name] != null) {
  28217. result[name] = options[name];
  28218. }
  28219. }
  28220. if (typeof hostAddress.socketPath === "string") {
  28221. result.path = hostAddress.socketPath;
  28222. return result;
  28223. } else if (typeof hostAddress.host === "string") {
  28224. result.host = hostAddress.host;
  28225. result.port = hostAddress.port;
  28226. return result;
  28227. } else {
  28228. throw new error_1.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`);
  28229. }
  28230. }
  28231. __name(parseConnectOptions, "parseConnectOptions");
  28232. function parseSslOptions(options) {
  28233. const result = parseConnectOptions(options);
  28234. for (const name of exports2.LEGAL_TLS_SOCKET_OPTIONS) {
  28235. if (options[name] != null) {
  28236. result[name] = options[name];
  28237. }
  28238. }
  28239. if (options.existingSocket) {
  28240. result.socket = options.existingSocket;
  28241. }
  28242. if (result.servername == null && result.host && !net.isIP(result.host)) {
  28243. result.servername = result.host;
  28244. }
  28245. return result;
  28246. }
  28247. __name(parseSslOptions, "parseSslOptions");
  28248. var SOCKET_ERROR_EVENT_LIST = ["error", "close", "timeout", "parseError"];
  28249. var SOCKET_ERROR_EVENTS = new Set(SOCKET_ERROR_EVENT_LIST);
  28250. function makeConnection(options, _callback) {
  28251. const useTLS = options.tls ?? false;
  28252. const keepAlive = options.keepAlive ?? true;
  28253. const socketTimeoutMS = options.socketTimeoutMS ?? Reflect.get(options, "socketTimeout") ?? 0;
  28254. const noDelay = options.noDelay ?? true;
  28255. const connectTimeoutMS = options.connectTimeoutMS ?? 3e4;
  28256. const rejectUnauthorized = options.rejectUnauthorized ?? true;
  28257. const keepAliveInitialDelay = ((options.keepAliveInitialDelay ?? 12e4) > socketTimeoutMS ? Math.round(socketTimeoutMS / 2) : options.keepAliveInitialDelay) ?? 12e4;
  28258. const existingSocket = options.existingSocket;
  28259. let socket;
  28260. const callback = /* @__PURE__ */ __name(function(err, ret) {
  28261. if (err && socket) {
  28262. socket.destroy();
  28263. }
  28264. _callback(err, ret);
  28265. }, "callback");
  28266. if (options.proxyHost != null) {
  28267. return makeSocks5Connection({
  28268. ...options,
  28269. connectTimeoutMS
  28270. // Should always be present for Socks5
  28271. }, callback);
  28272. }
  28273. if (useTLS) {
  28274. const tlsSocket = tls.connect(parseSslOptions(options));
  28275. if (typeof tlsSocket.disableRenegotiation === "function") {
  28276. tlsSocket.disableRenegotiation();
  28277. }
  28278. socket = tlsSocket;
  28279. } else if (existingSocket) {
  28280. socket = existingSocket;
  28281. } else {
  28282. socket = net.createConnection(parseConnectOptions(options));
  28283. }
  28284. socket.setKeepAlive(keepAlive, keepAliveInitialDelay);
  28285. socket.setTimeout(connectTimeoutMS);
  28286. socket.setNoDelay(noDelay);
  28287. const connectEvent = useTLS ? "secureConnect" : "connect";
  28288. let cancellationHandler;
  28289. function errorHandler(eventName) {
  28290. return (err) => {
  28291. SOCKET_ERROR_EVENTS.forEach((event) => socket.removeAllListeners(event));
  28292. if (cancellationHandler && options.cancellationToken) {
  28293. options.cancellationToken.removeListener("cancel", cancellationHandler);
  28294. }
  28295. socket.removeListener(connectEvent, connectHandler);
  28296. callback(connectionFailureError(eventName, err));
  28297. };
  28298. }
  28299. __name(errorHandler, "errorHandler");
  28300. function connectHandler() {
  28301. SOCKET_ERROR_EVENTS.forEach((event) => socket.removeAllListeners(event));
  28302. if (cancellationHandler && options.cancellationToken) {
  28303. options.cancellationToken.removeListener("cancel", cancellationHandler);
  28304. }
  28305. if ("authorizationError" in socket) {
  28306. if (socket.authorizationError && rejectUnauthorized) {
  28307. return callback(socket.authorizationError);
  28308. }
  28309. }
  28310. socket.setTimeout(0);
  28311. callback(void 0, socket);
  28312. }
  28313. __name(connectHandler, "connectHandler");
  28314. SOCKET_ERROR_EVENTS.forEach((event) => socket.once(event, errorHandler(event)));
  28315. if (options.cancellationToken) {
  28316. cancellationHandler = errorHandler("cancel");
  28317. options.cancellationToken.once("cancel", cancellationHandler);
  28318. }
  28319. if (existingSocket) {
  28320. process.nextTick(connectHandler);
  28321. } else {
  28322. socket.once(connectEvent, connectHandler);
  28323. }
  28324. }
  28325. __name(makeConnection, "makeConnection");
  28326. function makeSocks5Connection(options, callback) {
  28327. const hostAddress = utils_1.HostAddress.fromHostPort(
  28328. options.proxyHost ?? "",
  28329. // proxyHost is guaranteed to set here
  28330. options.proxyPort ?? 1080
  28331. );
  28332. makeConnection({
  28333. ...options,
  28334. hostAddress,
  28335. tls: false,
  28336. proxyHost: void 0
  28337. }, (err, rawSocket) => {
  28338. if (err) {
  28339. return callback(err);
  28340. }
  28341. const destination = parseConnectOptions(options);
  28342. if (typeof destination.host !== "string" || typeof destination.port !== "number") {
  28343. return callback(new error_1.MongoInvalidArgumentError("Can only make Socks5 connections to TCP hosts"));
  28344. }
  28345. socks_1.SocksClient.createConnection({
  28346. existing_socket: rawSocket,
  28347. timeout: options.connectTimeoutMS,
  28348. command: "connect",
  28349. destination: {
  28350. host: destination.host,
  28351. port: destination.port
  28352. },
  28353. proxy: {
  28354. // host and port are ignored because we pass existing_socket
  28355. host: "iLoveJavaScript",
  28356. port: 0,
  28357. type: 5,
  28358. userId: options.proxyUsername || void 0,
  28359. password: options.proxyPassword || void 0
  28360. }
  28361. }).then(({ socket }) => {
  28362. makeConnection({
  28363. ...options,
  28364. existingSocket: socket,
  28365. proxyHost: void 0
  28366. }, callback);
  28367. }, (error) => callback(connectionFailureError("error", error)));
  28368. });
  28369. }
  28370. __name(makeSocks5Connection, "makeSocks5Connection");
  28371. function connectionFailureError(type, err) {
  28372. switch (type) {
  28373. case "error":
  28374. return new error_1.MongoNetworkError(err);
  28375. case "timeout":
  28376. return new error_1.MongoNetworkTimeoutError("connection timed out");
  28377. case "close":
  28378. return new error_1.MongoNetworkError("connection closed");
  28379. case "cancel":
  28380. return new error_1.MongoNetworkError("connection establishment was cancelled");
  28381. default:
  28382. return new error_1.MongoNetworkError("unknown network error");
  28383. }
  28384. }
  28385. __name(connectionFailureError, "connectionFailureError");
  28386. }
  28387. });
  28388. // node_modules/mongodb/lib/cmap/connection_pool_events.js
  28389. var require_connection_pool_events = __commonJS({
  28390. "node_modules/mongodb/lib/cmap/connection_pool_events.js"(exports2) {
  28391. "use strict";
  28392. Object.defineProperty(exports2, "__esModule", { value: true });
  28393. exports2.ConnectionPoolClearedEvent = exports2.ConnectionCheckedInEvent = exports2.ConnectionCheckedOutEvent = exports2.ConnectionCheckOutFailedEvent = exports2.ConnectionCheckOutStartedEvent = exports2.ConnectionClosedEvent = exports2.ConnectionReadyEvent = exports2.ConnectionCreatedEvent = exports2.ConnectionPoolClosedEvent = exports2.ConnectionPoolReadyEvent = exports2.ConnectionPoolCreatedEvent = exports2.ConnectionPoolMonitoringEvent = void 0;
  28394. var constants_1 = require_constants2();
  28395. var _ConnectionPoolMonitoringEvent = class _ConnectionPoolMonitoringEvent {
  28396. /** @internal */
  28397. constructor(pool) {
  28398. this.time = /* @__PURE__ */ new Date();
  28399. this.address = pool.address;
  28400. }
  28401. };
  28402. __name(_ConnectionPoolMonitoringEvent, "ConnectionPoolMonitoringEvent");
  28403. var ConnectionPoolMonitoringEvent = _ConnectionPoolMonitoringEvent;
  28404. exports2.ConnectionPoolMonitoringEvent = ConnectionPoolMonitoringEvent;
  28405. var _ConnectionPoolCreatedEvent = class _ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent {
  28406. /** @internal */
  28407. constructor(pool) {
  28408. super(pool);
  28409. this.name = constants_1.CONNECTION_POOL_CREATED;
  28410. if (pool.options.credentials != null) {
  28411. this.options = { ...pool.options, credentials: {} };
  28412. } else {
  28413. this.options = pool.options;
  28414. }
  28415. }
  28416. };
  28417. __name(_ConnectionPoolCreatedEvent, "ConnectionPoolCreatedEvent");
  28418. var ConnectionPoolCreatedEvent = _ConnectionPoolCreatedEvent;
  28419. exports2.ConnectionPoolCreatedEvent = ConnectionPoolCreatedEvent;
  28420. var _ConnectionPoolReadyEvent = class _ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent {
  28421. /** @internal */
  28422. constructor(pool) {
  28423. super(pool);
  28424. this.name = constants_1.CONNECTION_POOL_READY;
  28425. }
  28426. };
  28427. __name(_ConnectionPoolReadyEvent, "ConnectionPoolReadyEvent");
  28428. var ConnectionPoolReadyEvent = _ConnectionPoolReadyEvent;
  28429. exports2.ConnectionPoolReadyEvent = ConnectionPoolReadyEvent;
  28430. var _ConnectionPoolClosedEvent = class _ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent {
  28431. /** @internal */
  28432. constructor(pool) {
  28433. super(pool);
  28434. this.name = constants_1.CONNECTION_POOL_CLOSED;
  28435. }
  28436. };
  28437. __name(_ConnectionPoolClosedEvent, "ConnectionPoolClosedEvent");
  28438. var ConnectionPoolClosedEvent = _ConnectionPoolClosedEvent;
  28439. exports2.ConnectionPoolClosedEvent = ConnectionPoolClosedEvent;
  28440. var _ConnectionCreatedEvent = class _ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent {
  28441. /** @internal */
  28442. constructor(pool, connection) {
  28443. super(pool);
  28444. this.name = constants_1.CONNECTION_CREATED;
  28445. this.connectionId = connection.id;
  28446. }
  28447. };
  28448. __name(_ConnectionCreatedEvent, "ConnectionCreatedEvent");
  28449. var ConnectionCreatedEvent = _ConnectionCreatedEvent;
  28450. exports2.ConnectionCreatedEvent = ConnectionCreatedEvent;
  28451. var _ConnectionReadyEvent = class _ConnectionReadyEvent extends ConnectionPoolMonitoringEvent {
  28452. /** @internal */
  28453. constructor(pool, connection) {
  28454. super(pool);
  28455. this.name = constants_1.CONNECTION_READY;
  28456. this.connectionId = connection.id;
  28457. }
  28458. };
  28459. __name(_ConnectionReadyEvent, "ConnectionReadyEvent");
  28460. var ConnectionReadyEvent = _ConnectionReadyEvent;
  28461. exports2.ConnectionReadyEvent = ConnectionReadyEvent;
  28462. var _ConnectionClosedEvent = class _ConnectionClosedEvent extends ConnectionPoolMonitoringEvent {
  28463. /** @internal */
  28464. constructor(pool, connection, reason, error) {
  28465. super(pool);
  28466. this.name = constants_1.CONNECTION_CLOSED;
  28467. this.connectionId = connection.id;
  28468. this.reason = reason;
  28469. this.serviceId = connection.serviceId;
  28470. this.error = error ?? null;
  28471. }
  28472. };
  28473. __name(_ConnectionClosedEvent, "ConnectionClosedEvent");
  28474. var ConnectionClosedEvent = _ConnectionClosedEvent;
  28475. exports2.ConnectionClosedEvent = ConnectionClosedEvent;
  28476. var _ConnectionCheckOutStartedEvent = class _ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent {
  28477. /** @internal */
  28478. constructor(pool) {
  28479. super(pool);
  28480. this.name = constants_1.CONNECTION_CHECK_OUT_STARTED;
  28481. }
  28482. };
  28483. __name(_ConnectionCheckOutStartedEvent, "ConnectionCheckOutStartedEvent");
  28484. var ConnectionCheckOutStartedEvent = _ConnectionCheckOutStartedEvent;
  28485. exports2.ConnectionCheckOutStartedEvent = ConnectionCheckOutStartedEvent;
  28486. var _ConnectionCheckOutFailedEvent = class _ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent {
  28487. /** @internal */
  28488. constructor(pool, reason, error) {
  28489. super(pool);
  28490. this.name = constants_1.CONNECTION_CHECK_OUT_FAILED;
  28491. this.reason = reason;
  28492. this.error = error;
  28493. }
  28494. };
  28495. __name(_ConnectionCheckOutFailedEvent, "ConnectionCheckOutFailedEvent");
  28496. var ConnectionCheckOutFailedEvent = _ConnectionCheckOutFailedEvent;
  28497. exports2.ConnectionCheckOutFailedEvent = ConnectionCheckOutFailedEvent;
  28498. var _ConnectionCheckedOutEvent = class _ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent {
  28499. /** @internal */
  28500. constructor(pool, connection) {
  28501. super(pool);
  28502. this.name = constants_1.CONNECTION_CHECKED_OUT;
  28503. this.connectionId = connection.id;
  28504. }
  28505. };
  28506. __name(_ConnectionCheckedOutEvent, "ConnectionCheckedOutEvent");
  28507. var ConnectionCheckedOutEvent = _ConnectionCheckedOutEvent;
  28508. exports2.ConnectionCheckedOutEvent = ConnectionCheckedOutEvent;
  28509. var _ConnectionCheckedInEvent = class _ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent {
  28510. /** @internal */
  28511. constructor(pool, connection) {
  28512. super(pool);
  28513. this.name = constants_1.CONNECTION_CHECKED_IN;
  28514. this.connectionId = connection.id;
  28515. }
  28516. };
  28517. __name(_ConnectionCheckedInEvent, "ConnectionCheckedInEvent");
  28518. var ConnectionCheckedInEvent = _ConnectionCheckedInEvent;
  28519. exports2.ConnectionCheckedInEvent = ConnectionCheckedInEvent;
  28520. var _ConnectionPoolClearedEvent = class _ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent {
  28521. /** @internal */
  28522. constructor(pool, options = {}) {
  28523. super(pool);
  28524. this.name = constants_1.CONNECTION_POOL_CLEARED;
  28525. this.serviceId = options.serviceId;
  28526. this.interruptInUseConnections = options.interruptInUseConnections;
  28527. }
  28528. };
  28529. __name(_ConnectionPoolClearedEvent, "ConnectionPoolClearedEvent");
  28530. var ConnectionPoolClearedEvent = _ConnectionPoolClearedEvent;
  28531. exports2.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent;
  28532. }
  28533. });
  28534. // node_modules/mongodb/lib/cmap/errors.js
  28535. var require_errors = __commonJS({
  28536. "node_modules/mongodb/lib/cmap/errors.js"(exports2) {
  28537. "use strict";
  28538. Object.defineProperty(exports2, "__esModule", { value: true });
  28539. exports2.WaitQueueTimeoutError = exports2.PoolClearedOnNetworkError = exports2.PoolClearedError = exports2.PoolClosedError = void 0;
  28540. var error_1 = require_error();
  28541. var _PoolClosedError = class _PoolClosedError extends error_1.MongoDriverError {
  28542. constructor(pool) {
  28543. super("Attempted to check out a connection from closed connection pool");
  28544. this.address = pool.address;
  28545. }
  28546. get name() {
  28547. return "MongoPoolClosedError";
  28548. }
  28549. };
  28550. __name(_PoolClosedError, "PoolClosedError");
  28551. var PoolClosedError = _PoolClosedError;
  28552. exports2.PoolClosedError = PoolClosedError;
  28553. var _PoolClearedError = class _PoolClearedError extends error_1.MongoNetworkError {
  28554. constructor(pool, message) {
  28555. var _a;
  28556. const errorMessage = message ? message : `Connection pool for ${pool.address} was cleared because another operation failed with: "${(_a = pool.serverError) == null ? void 0 : _a.message}"`;
  28557. super(errorMessage);
  28558. this.address = pool.address;
  28559. this.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
  28560. }
  28561. get name() {
  28562. return "MongoPoolClearedError";
  28563. }
  28564. };
  28565. __name(_PoolClearedError, "PoolClearedError");
  28566. var PoolClearedError = _PoolClearedError;
  28567. exports2.PoolClearedError = PoolClearedError;
  28568. var _PoolClearedOnNetworkError = class _PoolClearedOnNetworkError extends PoolClearedError {
  28569. constructor(pool) {
  28570. super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`);
  28571. }
  28572. get name() {
  28573. return "PoolClearedOnNetworkError";
  28574. }
  28575. };
  28576. __name(_PoolClearedOnNetworkError, "PoolClearedOnNetworkError");
  28577. var PoolClearedOnNetworkError = _PoolClearedOnNetworkError;
  28578. exports2.PoolClearedOnNetworkError = PoolClearedOnNetworkError;
  28579. var _WaitQueueTimeoutError = class _WaitQueueTimeoutError extends error_1.MongoDriverError {
  28580. constructor(message, address) {
  28581. super(message);
  28582. this.address = address;
  28583. }
  28584. get name() {
  28585. return "MongoWaitQueueTimeoutError";
  28586. }
  28587. };
  28588. __name(_WaitQueueTimeoutError, "WaitQueueTimeoutError");
  28589. var WaitQueueTimeoutError = _WaitQueueTimeoutError;
  28590. exports2.WaitQueueTimeoutError = WaitQueueTimeoutError;
  28591. }
  28592. });
  28593. // node_modules/mongodb/lib/cmap/connection_pool.js
  28594. var require_connection_pool = __commonJS({
  28595. "node_modules/mongodb/lib/cmap/connection_pool.js"(exports2) {
  28596. "use strict";
  28597. Object.defineProperty(exports2, "__esModule", { value: true });
  28598. exports2.ConnectionPool = exports2.PoolState = void 0;
  28599. var timers_1 = require("timers");
  28600. var constants_1 = require_constants2();
  28601. var error_1 = require_error();
  28602. var mongo_types_1 = require_mongo_types();
  28603. var utils_1 = require_utils();
  28604. var connect_1 = require_connect();
  28605. var connection_1 = require_connection();
  28606. var connection_pool_events_1 = require_connection_pool_events();
  28607. var errors_1 = require_errors();
  28608. var metrics_1 = require_metrics();
  28609. var kServer = Symbol("server");
  28610. var kConnections = Symbol("connections");
  28611. var kPending = Symbol("pending");
  28612. var kCheckedOut = Symbol("checkedOut");
  28613. var kMinPoolSizeTimer = Symbol("minPoolSizeTimer");
  28614. var kGeneration = Symbol("generation");
  28615. var kServiceGenerations = Symbol("serviceGenerations");
  28616. var kConnectionCounter = Symbol("connectionCounter");
  28617. var kCancellationToken = Symbol("cancellationToken");
  28618. var kWaitQueue = Symbol("waitQueue");
  28619. var kCancelled = Symbol("cancelled");
  28620. var kMetrics = Symbol("metrics");
  28621. var kProcessingWaitQueue = Symbol("processingWaitQueue");
  28622. var kPoolState = Symbol("poolState");
  28623. exports2.PoolState = Object.freeze({
  28624. paused: "paused",
  28625. ready: "ready",
  28626. closed: "closed"
  28627. });
  28628. var _ConnectionPool = class _ConnectionPool extends mongo_types_1.TypedEventEmitter {
  28629. constructor(server, options) {
  28630. super();
  28631. this.options = Object.freeze({
  28632. ...options,
  28633. connectionType: connection_1.Connection,
  28634. maxPoolSize: options.maxPoolSize ?? 100,
  28635. minPoolSize: options.minPoolSize ?? 0,
  28636. maxConnecting: options.maxConnecting ?? 2,
  28637. maxIdleTimeMS: options.maxIdleTimeMS ?? 0,
  28638. waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0,
  28639. minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100,
  28640. autoEncrypter: options.autoEncrypter,
  28641. metadata: options.metadata
  28642. });
  28643. if (this.options.minPoolSize > this.options.maxPoolSize) {
  28644. throw new error_1.MongoInvalidArgumentError("Connection pool minimum size must not be greater than maximum pool size");
  28645. }
  28646. this[kPoolState] = exports2.PoolState.paused;
  28647. this[kServer] = server;
  28648. this[kConnections] = new utils_1.List();
  28649. this[kPending] = 0;
  28650. this[kCheckedOut] = /* @__PURE__ */ new Set();
  28651. this[kMinPoolSizeTimer] = void 0;
  28652. this[kGeneration] = 0;
  28653. this[kServiceGenerations] = /* @__PURE__ */ new Map();
  28654. this[kConnectionCounter] = (0, utils_1.makeCounter)(1);
  28655. this[kCancellationToken] = new mongo_types_1.CancellationToken();
  28656. this[kCancellationToken].setMaxListeners(Infinity);
  28657. this[kWaitQueue] = new utils_1.List();
  28658. this[kMetrics] = new metrics_1.ConnectionPoolMetrics();
  28659. this[kProcessingWaitQueue] = false;
  28660. this.mongoLogger = this[kServer].topology.client.mongoLogger;
  28661. this.component = "connection";
  28662. process.nextTick(() => {
  28663. this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this));
  28664. });
  28665. }
  28666. /** The address of the endpoint the pool is connected to */
  28667. get address() {
  28668. return this.options.hostAddress.toString();
  28669. }
  28670. /**
  28671. * Check if the pool has been closed
  28672. *
  28673. * TODO(NODE-3263): We can remove this property once shell no longer needs it
  28674. */
  28675. get closed() {
  28676. return this[kPoolState] === exports2.PoolState.closed;
  28677. }
  28678. /** An integer representing the SDAM generation of the pool */
  28679. get generation() {
  28680. return this[kGeneration];
  28681. }
  28682. /** An integer expressing how many total connections (available + pending + in use) the pool currently has */
  28683. get totalConnectionCount() {
  28684. return this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount;
  28685. }
  28686. /** An integer expressing how many connections are currently available in the pool. */
  28687. get availableConnectionCount() {
  28688. return this[kConnections].length;
  28689. }
  28690. get pendingConnectionCount() {
  28691. return this[kPending];
  28692. }
  28693. get currentCheckedOutCount() {
  28694. return this[kCheckedOut].size;
  28695. }
  28696. get waitQueueSize() {
  28697. return this[kWaitQueue].length;
  28698. }
  28699. get loadBalanced() {
  28700. return this.options.loadBalanced;
  28701. }
  28702. get serviceGenerations() {
  28703. return this[kServiceGenerations];
  28704. }
  28705. get serverError() {
  28706. return this[kServer].description.error;
  28707. }
  28708. /**
  28709. * This is exposed ONLY for use in mongosh, to enable
  28710. * killing all connections if a user quits the shell with
  28711. * operations in progress.
  28712. *
  28713. * This property may be removed as a part of NODE-3263.
  28714. */
  28715. get checkedOutConnections() {
  28716. return this[kCheckedOut];
  28717. }
  28718. /**
  28719. * Get the metrics information for the pool when a wait queue timeout occurs.
  28720. */
  28721. waitQueueErrorMetrics() {
  28722. return this[kMetrics].info(this.options.maxPoolSize);
  28723. }
  28724. /**
  28725. * Set the pool state to "ready"
  28726. */
  28727. ready() {
  28728. if (this[kPoolState] !== exports2.PoolState.paused) {
  28729. return;
  28730. }
  28731. this[kPoolState] = exports2.PoolState.ready;
  28732. this.emitAndLog(_ConnectionPool.CONNECTION_POOL_READY, new connection_pool_events_1.ConnectionPoolReadyEvent(this));
  28733. (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]);
  28734. this.ensureMinPoolSize();
  28735. }
  28736. /**
  28737. * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it
  28738. * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or
  28739. * explicitly destroyed by the new owner.
  28740. */
  28741. checkOut(callback) {
  28742. this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this));
  28743. const waitQueueMember = { callback };
  28744. const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS;
  28745. if (waitQueueTimeoutMS) {
  28746. waitQueueMember.timer = (0, timers_1.setTimeout)(() => {
  28747. waitQueueMember[kCancelled] = true;
  28748. waitQueueMember.timer = void 0;
  28749. this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, "timeout"));
  28750. waitQueueMember.callback(new errors_1.WaitQueueTimeoutError(this.loadBalanced ? this.waitQueueErrorMetrics() : "Timed out while checking out a connection from connection pool", this.address));
  28751. }, waitQueueTimeoutMS);
  28752. }
  28753. this[kWaitQueue].push(waitQueueMember);
  28754. process.nextTick(() => this.processWaitQueue());
  28755. }
  28756. /**
  28757. * Check a connection into the pool.
  28758. *
  28759. * @param connection - The connection to check in
  28760. */
  28761. checkIn(connection) {
  28762. if (!this[kCheckedOut].has(connection)) {
  28763. return;
  28764. }
  28765. const poolClosed = this.closed;
  28766. const stale = this.connectionIsStale(connection);
  28767. const willDestroy = !!(poolClosed || stale || connection.closed);
  28768. if (!willDestroy) {
  28769. connection.markAvailable();
  28770. this[kConnections].unshift(connection);
  28771. }
  28772. this[kCheckedOut].delete(connection);
  28773. this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection));
  28774. if (willDestroy) {
  28775. const reason = connection.closed ? "error" : poolClosed ? "poolClosed" : "stale";
  28776. this.destroyConnection(connection, reason);
  28777. }
  28778. process.nextTick(() => this.processWaitQueue());
  28779. }
  28780. /**
  28781. * Clear the pool
  28782. *
  28783. * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a
  28784. * previous generation will eventually be pruned during subsequent checkouts.
  28785. */
  28786. clear(options = {}) {
  28787. if (this.closed) {
  28788. return;
  28789. }
  28790. if (this.loadBalanced) {
  28791. const { serviceId } = options;
  28792. if (!serviceId) {
  28793. throw new error_1.MongoRuntimeError("ConnectionPool.clear() called in load balanced mode with no serviceId.");
  28794. }
  28795. const sid = serviceId.toHexString();
  28796. const generation = this.serviceGenerations.get(sid);
  28797. if (generation == null) {
  28798. throw new error_1.MongoRuntimeError("Service generations are required in load balancer mode.");
  28799. } else {
  28800. this.serviceGenerations.set(sid, generation + 1);
  28801. }
  28802. this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { serviceId }));
  28803. return;
  28804. }
  28805. const interruptInUseConnections = options.interruptInUseConnections ?? false;
  28806. const oldGeneration = this[kGeneration];
  28807. this[kGeneration] += 1;
  28808. const alreadyPaused = this[kPoolState] === exports2.PoolState.paused;
  28809. this[kPoolState] = exports2.PoolState.paused;
  28810. this.clearMinPoolSizeTimer();
  28811. if (!alreadyPaused) {
  28812. this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, {
  28813. interruptInUseConnections
  28814. }));
  28815. }
  28816. if (interruptInUseConnections) {
  28817. process.nextTick(() => this.interruptInUseConnections(oldGeneration));
  28818. }
  28819. this.processWaitQueue();
  28820. }
  28821. /**
  28822. * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError.
  28823. *
  28824. * Only connections where `connection.generation <= minGeneration` are killed.
  28825. */
  28826. interruptInUseConnections(minGeneration) {
  28827. for (const connection of this[kCheckedOut]) {
  28828. if (connection.generation <= minGeneration) {
  28829. this.checkIn(connection);
  28830. connection.onError(new errors_1.PoolClearedOnNetworkError(this));
  28831. }
  28832. }
  28833. }
  28834. close(_options, _cb) {
  28835. let options = _options;
  28836. const callback = _cb ?? _options;
  28837. if (typeof options === "function") {
  28838. options = {};
  28839. }
  28840. options = Object.assign({ force: false }, options);
  28841. if (this.closed) {
  28842. return callback();
  28843. }
  28844. this[kCancellationToken].emit("cancel");
  28845. if (typeof this[kConnectionCounter].return === "function") {
  28846. this[kConnectionCounter].return(void 0);
  28847. }
  28848. this[kPoolState] = exports2.PoolState.closed;
  28849. this.clearMinPoolSizeTimer();
  28850. this.processWaitQueue();
  28851. (0, utils_1.eachAsync)(this[kConnections].toArray(), (conn, cb) => {
  28852. this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, "poolClosed"));
  28853. conn.destroy({ force: !!options.force }, cb);
  28854. }, (err) => {
  28855. this[kConnections].clear();
  28856. this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.ConnectionPoolClosedEvent(this));
  28857. callback(err);
  28858. });
  28859. }
  28860. /**
  28861. * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda
  28862. * has completed by calling back.
  28863. *
  28864. * NOTE: please note the required signature of `fn`
  28865. *
  28866. * @remarks When in load balancer mode, connections can be pinned to cursors or transactions.
  28867. * In these cases we pass the connection in to this method to ensure it is used and a new
  28868. * connection is not checked out.
  28869. *
  28870. * @param conn - A pinned connection for use in load balancing mode.
  28871. * @param fn - A function which operates on a managed connection
  28872. * @param callback - The original callback
  28873. */
  28874. withConnection(conn, fn, callback) {
  28875. if (conn) {
  28876. fn(void 0, conn, (fnErr, result) => {
  28877. if (fnErr) {
  28878. return this.withReauthentication(fnErr, conn, fn, callback);
  28879. }
  28880. callback(void 0, result);
  28881. });
  28882. return;
  28883. }
  28884. this.checkOut((err, conn2) => {
  28885. fn(err, conn2, (fnErr, result) => {
  28886. if (fnErr) {
  28887. if (conn2) {
  28888. this.withReauthentication(fnErr, conn2, fn, callback);
  28889. } else {
  28890. callback(fnErr);
  28891. }
  28892. } else {
  28893. callback(void 0, result);
  28894. }
  28895. if (conn2) {
  28896. this.checkIn(conn2);
  28897. }
  28898. });
  28899. });
  28900. }
  28901. withReauthentication(fnErr, conn, fn, callback) {
  28902. if (fnErr instanceof error_1.MongoError && fnErr.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) {
  28903. this.reauthenticate(conn, fn, (error, res) => {
  28904. if (error) {
  28905. return callback(error);
  28906. }
  28907. callback(void 0, res);
  28908. });
  28909. } else {
  28910. callback(fnErr);
  28911. }
  28912. }
  28913. /**
  28914. * Reauthenticate on the same connection and then retry the operation.
  28915. */
  28916. reauthenticate(connection, fn, callback) {
  28917. const authContext = connection.authContext;
  28918. if (!authContext) {
  28919. return callback(new error_1.MongoRuntimeError("No auth context found on connection."));
  28920. }
  28921. const credentials = authContext.credentials;
  28922. if (!credentials) {
  28923. return callback(new error_1.MongoMissingCredentialsError("Connection is missing credentials when asked to reauthenticate"));
  28924. }
  28925. const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello || void 0);
  28926. const provider = connect_1.AUTH_PROVIDERS.get(resolvedCredentials.mechanism);
  28927. if (!provider) {
  28928. return callback(new error_1.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${credentials.mechanism}`));
  28929. }
  28930. provider.reauth(authContext).then(() => {
  28931. fn(void 0, connection, (fnErr, fnResult) => {
  28932. if (fnErr) {
  28933. return callback(fnErr);
  28934. }
  28935. callback(void 0, fnResult);
  28936. });
  28937. }, (error) => callback(error));
  28938. }
  28939. /** Clear the min pool size timer */
  28940. clearMinPoolSizeTimer() {
  28941. const minPoolSizeTimer = this[kMinPoolSizeTimer];
  28942. if (minPoolSizeTimer) {
  28943. (0, timers_1.clearTimeout)(minPoolSizeTimer);
  28944. }
  28945. }
  28946. destroyConnection(connection, reason) {
  28947. this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, connection, reason));
  28948. process.nextTick(() => connection.destroy({ force: false }));
  28949. }
  28950. connectionIsStale(connection) {
  28951. const serviceId = connection.serviceId;
  28952. if (this.loadBalanced && serviceId) {
  28953. const sid = serviceId.toHexString();
  28954. const generation = this.serviceGenerations.get(sid);
  28955. return connection.generation !== generation;
  28956. }
  28957. return connection.generation !== this[kGeneration];
  28958. }
  28959. connectionIsIdle(connection) {
  28960. return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS);
  28961. }
  28962. /**
  28963. * Destroys a connection if the connection is perished.
  28964. *
  28965. * @returns `true` if the connection was destroyed, `false` otherwise.
  28966. */
  28967. destroyConnectionIfPerished(connection) {
  28968. const isStale = this.connectionIsStale(connection);
  28969. const isIdle = this.connectionIsIdle(connection);
  28970. if (!isStale && !isIdle && !connection.closed) {
  28971. return false;
  28972. }
  28973. const reason = connection.closed ? "error" : isStale ? "stale" : "idle";
  28974. this.destroyConnection(connection, reason);
  28975. return true;
  28976. }
  28977. createConnection(callback) {
  28978. const connectOptions = {
  28979. ...this.options,
  28980. id: this[kConnectionCounter].next().value,
  28981. generation: this[kGeneration],
  28982. cancellationToken: this[kCancellationToken]
  28983. };
  28984. this[kPending]++;
  28985. this.emitAndLog(_ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(this, { id: connectOptions.id }));
  28986. (0, connect_1.connect)(connectOptions, (err, connection) => {
  28987. if (err || !connection) {
  28988. this[kPending]--;
  28989. this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(
  28990. this,
  28991. { id: connectOptions.id, serviceId: void 0 },
  28992. "error",
  28993. // TODO(NODE-5192): Remove this cast
  28994. err
  28995. ));
  28996. if (err instanceof error_1.MongoNetworkError || err instanceof error_1.MongoServerError) {
  28997. err.connectionGeneration = connectOptions.generation;
  28998. }
  28999. callback(err ?? new error_1.MongoRuntimeError("Connection creation failed without error"));
  29000. return;
  29001. }
  29002. if (this[kPoolState] !== exports2.PoolState.ready) {
  29003. this[kPending]--;
  29004. connection.destroy({ force: true });
  29005. callback(this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this));
  29006. return;
  29007. }
  29008. for (const event of [...constants_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) {
  29009. connection.on(event, (e) => this.emit(event, e));
  29010. }
  29011. if (this.loadBalanced) {
  29012. connection.on(connection_1.Connection.PINNED, (pinType) => this[kMetrics].markPinned(pinType));
  29013. connection.on(connection_1.Connection.UNPINNED, (pinType) => this[kMetrics].markUnpinned(pinType));
  29014. const serviceId = connection.serviceId;
  29015. if (serviceId) {
  29016. let generation;
  29017. const sid = serviceId.toHexString();
  29018. if (generation = this.serviceGenerations.get(sid)) {
  29019. connection.generation = generation;
  29020. } else {
  29021. this.serviceGenerations.set(sid, 0);
  29022. connection.generation = 0;
  29023. }
  29024. }
  29025. }
  29026. connection.markAvailable();
  29027. this.emitAndLog(_ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(this, connection));
  29028. this[kPending]--;
  29029. callback(void 0, connection);
  29030. return;
  29031. });
  29032. }
  29033. ensureMinPoolSize() {
  29034. const minPoolSize = this.options.minPoolSize;
  29035. if (this[kPoolState] !== exports2.PoolState.ready || minPoolSize === 0) {
  29036. return;
  29037. }
  29038. this[kConnections].prune((connection) => this.destroyConnectionIfPerished(connection));
  29039. if (this.totalConnectionCount < minPoolSize && this.pendingConnectionCount < this.options.maxConnecting) {
  29040. this.createConnection((err, connection) => {
  29041. if (err) {
  29042. this[kServer].handleError(err);
  29043. }
  29044. if (!err && connection) {
  29045. this[kConnections].push(connection);
  29046. process.nextTick(() => this.processWaitQueue());
  29047. }
  29048. if (this[kPoolState] === exports2.PoolState.ready) {
  29049. (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]);
  29050. this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS);
  29051. }
  29052. });
  29053. } else {
  29054. (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]);
  29055. this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS);
  29056. }
  29057. }
  29058. processWaitQueue() {
  29059. if (this[kProcessingWaitQueue]) {
  29060. return;
  29061. }
  29062. this[kProcessingWaitQueue] = true;
  29063. while (this.waitQueueSize) {
  29064. const waitQueueMember = this[kWaitQueue].first();
  29065. if (!waitQueueMember) {
  29066. this[kWaitQueue].shift();
  29067. continue;
  29068. }
  29069. if (waitQueueMember[kCancelled]) {
  29070. this[kWaitQueue].shift();
  29071. continue;
  29072. }
  29073. if (this[kPoolState] !== exports2.PoolState.ready) {
  29074. const reason = this.closed ? "poolClosed" : "connectionError";
  29075. const error = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this);
  29076. this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, reason, error));
  29077. if (waitQueueMember.timer) {
  29078. (0, timers_1.clearTimeout)(waitQueueMember.timer);
  29079. }
  29080. this[kWaitQueue].shift();
  29081. waitQueueMember.callback(error);
  29082. continue;
  29083. }
  29084. if (!this.availableConnectionCount) {
  29085. break;
  29086. }
  29087. const connection = this[kConnections].shift();
  29088. if (!connection) {
  29089. break;
  29090. }
  29091. if (!this.destroyConnectionIfPerished(connection)) {
  29092. this[kCheckedOut].add(connection);
  29093. this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection));
  29094. if (waitQueueMember.timer) {
  29095. (0, timers_1.clearTimeout)(waitQueueMember.timer);
  29096. }
  29097. this[kWaitQueue].shift();
  29098. waitQueueMember.callback(void 0, connection);
  29099. }
  29100. }
  29101. const { maxPoolSize, maxConnecting } = this.options;
  29102. while (this.waitQueueSize > 0 && this.pendingConnectionCount < maxConnecting && (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)) {
  29103. const waitQueueMember = this[kWaitQueue].shift();
  29104. if (!waitQueueMember || waitQueueMember[kCancelled]) {
  29105. continue;
  29106. }
  29107. this.createConnection((err, connection) => {
  29108. if (waitQueueMember[kCancelled]) {
  29109. if (!err && connection) {
  29110. this[kConnections].push(connection);
  29111. }
  29112. } else {
  29113. if (err) {
  29114. this.emitAndLog(
  29115. _ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
  29116. // TODO(NODE-5192): Remove this cast
  29117. new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, "connectionError", err)
  29118. );
  29119. } else if (connection) {
  29120. this[kCheckedOut].add(connection);
  29121. this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection));
  29122. }
  29123. if (waitQueueMember.timer) {
  29124. (0, timers_1.clearTimeout)(waitQueueMember.timer);
  29125. }
  29126. waitQueueMember.callback(err, connection);
  29127. }
  29128. process.nextTick(() => this.processWaitQueue());
  29129. });
  29130. }
  29131. this[kProcessingWaitQueue] = false;
  29132. }
  29133. };
  29134. __name(_ConnectionPool, "ConnectionPool");
  29135. var ConnectionPool = _ConnectionPool;
  29136. ConnectionPool.CONNECTION_POOL_CREATED = constants_1.CONNECTION_POOL_CREATED;
  29137. ConnectionPool.CONNECTION_POOL_CLOSED = constants_1.CONNECTION_POOL_CLOSED;
  29138. ConnectionPool.CONNECTION_POOL_CLEARED = constants_1.CONNECTION_POOL_CLEARED;
  29139. ConnectionPool.CONNECTION_POOL_READY = constants_1.CONNECTION_POOL_READY;
  29140. ConnectionPool.CONNECTION_CREATED = constants_1.CONNECTION_CREATED;
  29141. ConnectionPool.CONNECTION_READY = constants_1.CONNECTION_READY;
  29142. ConnectionPool.CONNECTION_CLOSED = constants_1.CONNECTION_CLOSED;
  29143. ConnectionPool.CONNECTION_CHECK_OUT_STARTED = constants_1.CONNECTION_CHECK_OUT_STARTED;
  29144. ConnectionPool.CONNECTION_CHECK_OUT_FAILED = constants_1.CONNECTION_CHECK_OUT_FAILED;
  29145. ConnectionPool.CONNECTION_CHECKED_OUT = constants_1.CONNECTION_CHECKED_OUT;
  29146. ConnectionPool.CONNECTION_CHECKED_IN = constants_1.CONNECTION_CHECKED_IN;
  29147. exports2.ConnectionPool = ConnectionPool;
  29148. }
  29149. });
  29150. // node_modules/mongodb/lib/sdam/monitor.js
  29151. var require_monitor = __commonJS({
  29152. "node_modules/mongodb/lib/sdam/monitor.js"(exports2) {
  29153. "use strict";
  29154. Object.defineProperty(exports2, "__esModule", { value: true });
  29155. exports2.MonitorInterval = exports2.RTTPinger = exports2.Monitor = void 0;
  29156. var timers_1 = require("timers");
  29157. var bson_1 = require_bson2();
  29158. var connect_1 = require_connect();
  29159. var connection_1 = require_connection();
  29160. var constants_1 = require_constants2();
  29161. var error_1 = require_error();
  29162. var mongo_types_1 = require_mongo_types();
  29163. var utils_1 = require_utils();
  29164. var common_1 = require_common();
  29165. var events_1 = require_events();
  29166. var server_1 = require_server();
  29167. var kServer = Symbol("server");
  29168. var kMonitorId = Symbol("monitorId");
  29169. var kConnection = Symbol("connection");
  29170. var kCancellationToken = Symbol("cancellationToken");
  29171. var kRoundTripTime = Symbol("roundTripTime");
  29172. var STATE_IDLE = "idle";
  29173. var STATE_MONITORING = "monitoring";
  29174. var stateTransition = (0, utils_1.makeStateMachine)({
  29175. [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, STATE_IDLE, common_1.STATE_CLOSED],
  29176. [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, STATE_MONITORING],
  29177. [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, common_1.STATE_CLOSING],
  29178. [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, common_1.STATE_CLOSING]
  29179. });
  29180. var INVALID_REQUEST_CHECK_STATES = /* @__PURE__ */ new Set([common_1.STATE_CLOSING, common_1.STATE_CLOSED, STATE_MONITORING]);
  29181. function isInCloseState(monitor) {
  29182. return monitor.s.state === common_1.STATE_CLOSED || monitor.s.state === common_1.STATE_CLOSING;
  29183. }
  29184. __name(isInCloseState, "isInCloseState");
  29185. var _Monitor = class _Monitor extends mongo_types_1.TypedEventEmitter {
  29186. get connection() {
  29187. return this[kConnection];
  29188. }
  29189. constructor(server, options) {
  29190. super();
  29191. this[kServer] = server;
  29192. this[kConnection] = void 0;
  29193. this[kCancellationToken] = new mongo_types_1.CancellationToken();
  29194. this[kCancellationToken].setMaxListeners(Infinity);
  29195. this[kMonitorId] = void 0;
  29196. this.s = {
  29197. state: common_1.STATE_CLOSED
  29198. };
  29199. this.address = server.description.address;
  29200. this.options = Object.freeze({
  29201. connectTimeoutMS: options.connectTimeoutMS ?? 1e4,
  29202. heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 1e4,
  29203. minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500
  29204. });
  29205. const cancellationToken = this[kCancellationToken];
  29206. const connectOptions = Object.assign(
  29207. {
  29208. id: "<monitor>",
  29209. generation: server.pool.generation,
  29210. connectionType: connection_1.Connection,
  29211. cancellationToken,
  29212. hostAddress: server.description.hostAddress
  29213. },
  29214. options,
  29215. // force BSON serialization options
  29216. {
  29217. raw: false,
  29218. useBigInt64: false,
  29219. promoteLongs: true,
  29220. promoteValues: true,
  29221. promoteBuffers: true
  29222. }
  29223. );
  29224. delete connectOptions.credentials;
  29225. if (connectOptions.autoEncrypter) {
  29226. delete connectOptions.autoEncrypter;
  29227. }
  29228. this.connectOptions = Object.freeze(connectOptions);
  29229. }
  29230. connect() {
  29231. if (this.s.state !== common_1.STATE_CLOSED) {
  29232. return;
  29233. }
  29234. const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
  29235. const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
  29236. this[kMonitorId] = new MonitorInterval(monitorServer(this), {
  29237. heartbeatFrequencyMS,
  29238. minHeartbeatFrequencyMS,
  29239. immediate: true
  29240. });
  29241. }
  29242. requestCheck() {
  29243. var _a;
  29244. if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) {
  29245. return;
  29246. }
  29247. (_a = this[kMonitorId]) == null ? void 0 : _a.wake();
  29248. }
  29249. reset() {
  29250. const topologyVersion = this[kServer].description.topologyVersion;
  29251. if (isInCloseState(this) || topologyVersion == null) {
  29252. return;
  29253. }
  29254. stateTransition(this, common_1.STATE_CLOSING);
  29255. resetMonitorState(this);
  29256. stateTransition(this, STATE_IDLE);
  29257. const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
  29258. const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
  29259. this[kMonitorId] = new MonitorInterval(monitorServer(this), {
  29260. heartbeatFrequencyMS,
  29261. minHeartbeatFrequencyMS
  29262. });
  29263. }
  29264. close() {
  29265. if (isInCloseState(this)) {
  29266. return;
  29267. }
  29268. stateTransition(this, common_1.STATE_CLOSING);
  29269. resetMonitorState(this);
  29270. this.emit("close");
  29271. stateTransition(this, common_1.STATE_CLOSED);
  29272. }
  29273. };
  29274. __name(_Monitor, "Monitor");
  29275. var Monitor = _Monitor;
  29276. exports2.Monitor = Monitor;
  29277. function resetMonitorState(monitor) {
  29278. var _a, _b, _c;
  29279. (_a = monitor[kMonitorId]) == null ? void 0 : _a.stop();
  29280. monitor[kMonitorId] = void 0;
  29281. (_b = monitor.rttPinger) == null ? void 0 : _b.close();
  29282. monitor.rttPinger = void 0;
  29283. monitor[kCancellationToken].emit("cancel");
  29284. (_c = monitor[kConnection]) == null ? void 0 : _c.destroy({ force: true });
  29285. monitor[kConnection] = void 0;
  29286. }
  29287. __name(resetMonitorState, "resetMonitorState");
  29288. function checkServer(monitor, callback) {
  29289. let start = (0, utils_1.now)();
  29290. monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address));
  29291. function failureHandler(err) {
  29292. var _a;
  29293. (_a = monitor[kConnection]) == null ? void 0 : _a.destroy({ force: true });
  29294. monitor[kConnection] = void 0;
  29295. monitor.emit(server_1.Server.SERVER_HEARTBEAT_FAILED, new events_1.ServerHeartbeatFailedEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), err));
  29296. const error = !(err instanceof error_1.MongoError) ? new error_1.MongoError(err) : err;
  29297. error.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
  29298. if (error instanceof error_1.MongoNetworkTimeoutError) {
  29299. error.addErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections);
  29300. }
  29301. monitor.emit("resetServer", error);
  29302. callback(err);
  29303. }
  29304. __name(failureHandler, "failureHandler");
  29305. const connection = monitor[kConnection];
  29306. if (connection && !connection.closed) {
  29307. const { serverApi, helloOk } = connection;
  29308. const connectTimeoutMS = monitor.options.connectTimeoutMS;
  29309. const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS;
  29310. const topologyVersion = monitor[kServer].description.topologyVersion;
  29311. const isAwaitable = topologyVersion != null;
  29312. const cmd = {
  29313. [(serverApi == null ? void 0 : serverApi.version) || helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND]: 1,
  29314. ...isAwaitable && topologyVersion ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } : {}
  29315. };
  29316. const options = isAwaitable ? {
  29317. socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0,
  29318. exhaustAllowed: true
  29319. } : { socketTimeoutMS: connectTimeoutMS };
  29320. if (isAwaitable && monitor.rttPinger == null) {
  29321. monitor.rttPinger = new RTTPinger(monitor[kCancellationToken], Object.assign({ heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, monitor.connectOptions));
  29322. }
  29323. connection.command((0, utils_1.ns)("admin.$cmd"), cmd, options, (err, hello) => {
  29324. var _a;
  29325. if (err) {
  29326. return failureHandler(err);
  29327. }
  29328. if (!("isWritablePrimary" in hello)) {
  29329. hello.isWritablePrimary = hello[constants_1.LEGACY_HELLO_COMMAND];
  29330. }
  29331. const duration = isAwaitable && monitor.rttPinger ? monitor.rttPinger.roundTripTime : (0, utils_1.calculateDurationInMs)(start);
  29332. monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, hello));
  29333. if (isAwaitable && hello.topologyVersion) {
  29334. monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address));
  29335. start = (0, utils_1.now)();
  29336. } else {
  29337. (_a = monitor.rttPinger) == null ? void 0 : _a.close();
  29338. monitor.rttPinger = void 0;
  29339. callback(void 0, hello);
  29340. }
  29341. });
  29342. return;
  29343. }
  29344. (0, connect_1.connect)(monitor.connectOptions, (err, conn) => {
  29345. if (err) {
  29346. monitor[kConnection] = void 0;
  29347. failureHandler(err);
  29348. return;
  29349. }
  29350. if (conn) {
  29351. conn.isMonitoringConnection = true;
  29352. if (isInCloseState(monitor)) {
  29353. conn.destroy({ force: true });
  29354. return;
  29355. }
  29356. monitor[kConnection] = conn;
  29357. monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), conn.hello));
  29358. callback(void 0, conn.hello);
  29359. }
  29360. });
  29361. }
  29362. __name(checkServer, "checkServer");
  29363. function monitorServer(monitor) {
  29364. return (callback) => {
  29365. if (monitor.s.state === STATE_MONITORING) {
  29366. process.nextTick(callback);
  29367. return;
  29368. }
  29369. stateTransition(monitor, STATE_MONITORING);
  29370. function done() {
  29371. if (!isInCloseState(monitor)) {
  29372. stateTransition(monitor, STATE_IDLE);
  29373. }
  29374. callback();
  29375. }
  29376. __name(done, "done");
  29377. checkServer(monitor, (err, hello) => {
  29378. if (err) {
  29379. if (monitor[kServer].description.type === common_1.ServerType.Unknown) {
  29380. return done();
  29381. }
  29382. }
  29383. if (hello && hello.topologyVersion) {
  29384. (0, timers_1.setTimeout)(() => {
  29385. var _a;
  29386. if (!isInCloseState(monitor)) {
  29387. (_a = monitor[kMonitorId]) == null ? void 0 : _a.wake();
  29388. }
  29389. }, 0);
  29390. }
  29391. done();
  29392. });
  29393. };
  29394. }
  29395. __name(monitorServer, "monitorServer");
  29396. function makeTopologyVersion(tv) {
  29397. return {
  29398. processId: tv.processId,
  29399. // tests mock counter as just number, but in a real situation counter should always be a Long
  29400. // TODO(NODE-2674): Preserve int64 sent from MongoDB
  29401. counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter)
  29402. };
  29403. }
  29404. __name(makeTopologyVersion, "makeTopologyVersion");
  29405. var _RTTPinger = class _RTTPinger {
  29406. constructor(cancellationToken, options) {
  29407. this.connection = void 0;
  29408. this[kCancellationToken] = cancellationToken;
  29409. this[kRoundTripTime] = 0;
  29410. this.closed = false;
  29411. const heartbeatFrequencyMS = options.heartbeatFrequencyMS;
  29412. this[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(this, options), heartbeatFrequencyMS);
  29413. }
  29414. get roundTripTime() {
  29415. return this[kRoundTripTime];
  29416. }
  29417. close() {
  29418. var _a;
  29419. this.closed = true;
  29420. (0, timers_1.clearTimeout)(this[kMonitorId]);
  29421. (_a = this.connection) == null ? void 0 : _a.destroy({ force: true });
  29422. this.connection = void 0;
  29423. }
  29424. };
  29425. __name(_RTTPinger, "RTTPinger");
  29426. var RTTPinger = _RTTPinger;
  29427. exports2.RTTPinger = RTTPinger;
  29428. function measureRoundTripTime(rttPinger, options) {
  29429. var _a;
  29430. const start = (0, utils_1.now)();
  29431. options.cancellationToken = rttPinger[kCancellationToken];
  29432. const heartbeatFrequencyMS = options.heartbeatFrequencyMS;
  29433. if (rttPinger.closed) {
  29434. return;
  29435. }
  29436. function measureAndReschedule(conn) {
  29437. if (rttPinger.closed) {
  29438. conn == null ? void 0 : conn.destroy({ force: true });
  29439. return;
  29440. }
  29441. if (rttPinger.connection == null) {
  29442. rttPinger.connection = conn;
  29443. }
  29444. rttPinger[kRoundTripTime] = (0, utils_1.calculateDurationInMs)(start);
  29445. rttPinger[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(rttPinger, options), heartbeatFrequencyMS);
  29446. }
  29447. __name(measureAndReschedule, "measureAndReschedule");
  29448. const connection = rttPinger.connection;
  29449. if (connection == null) {
  29450. (0, connect_1.connect)(options, (err, conn) => {
  29451. if (err) {
  29452. rttPinger.connection = void 0;
  29453. rttPinger[kRoundTripTime] = 0;
  29454. return;
  29455. }
  29456. measureAndReschedule(conn);
  29457. });
  29458. return;
  29459. }
  29460. const commandName = ((_a = connection.serverApi) == null ? void 0 : _a.version) || connection.helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND;
  29461. connection.commandAsync((0, utils_1.ns)("admin.$cmd"), { [commandName]: 1 }, void 0).then(() => measureAndReschedule(), () => {
  29462. var _a2;
  29463. (_a2 = rttPinger.connection) == null ? void 0 : _a2.destroy({ force: true });
  29464. rttPinger.connection = void 0;
  29465. rttPinger[kRoundTripTime] = 0;
  29466. });
  29467. }
  29468. __name(measureRoundTripTime, "measureRoundTripTime");
  29469. var _MonitorInterval = class _MonitorInterval {
  29470. constructor(fn, options = {}) {
  29471. this.isExpeditedCallToFnScheduled = false;
  29472. this.stopped = false;
  29473. this.isExecutionInProgress = false;
  29474. this.hasExecutedOnce = false;
  29475. this._executeAndReschedule = () => {
  29476. if (this.stopped)
  29477. return;
  29478. if (this.timerId) {
  29479. (0, timers_1.clearTimeout)(this.timerId);
  29480. }
  29481. this.isExpeditedCallToFnScheduled = false;
  29482. this.isExecutionInProgress = true;
  29483. this.fn(() => {
  29484. this.lastExecutionEnded = (0, utils_1.now)();
  29485. this.isExecutionInProgress = false;
  29486. this._reschedule(this.heartbeatFrequencyMS);
  29487. });
  29488. };
  29489. this.fn = fn;
  29490. this.lastExecutionEnded = -Infinity;
  29491. this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1e3;
  29492. this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500;
  29493. if (options.immediate) {
  29494. this._executeAndReschedule();
  29495. } else {
  29496. this._reschedule(void 0);
  29497. }
  29498. }
  29499. wake() {
  29500. const currentTime = (0, utils_1.now)();
  29501. const timeSinceLastCall = currentTime - this.lastExecutionEnded;
  29502. if (timeSinceLastCall < 0) {
  29503. return this._executeAndReschedule();
  29504. }
  29505. if (this.isExecutionInProgress) {
  29506. return;
  29507. }
  29508. if (this.isExpeditedCallToFnScheduled) {
  29509. return;
  29510. }
  29511. if (timeSinceLastCall < this.minHeartbeatFrequencyMS) {
  29512. this.isExpeditedCallToFnScheduled = true;
  29513. this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall);
  29514. return;
  29515. }
  29516. this._executeAndReschedule();
  29517. }
  29518. stop() {
  29519. this.stopped = true;
  29520. if (this.timerId) {
  29521. (0, timers_1.clearTimeout)(this.timerId);
  29522. this.timerId = void 0;
  29523. }
  29524. this.lastExecutionEnded = -Infinity;
  29525. this.isExpeditedCallToFnScheduled = false;
  29526. }
  29527. toString() {
  29528. return JSON.stringify(this);
  29529. }
  29530. toJSON() {
  29531. const currentTime = (0, utils_1.now)();
  29532. const timeSinceLastCall = currentTime - this.lastExecutionEnded;
  29533. return {
  29534. timerId: this.timerId != null ? "set" : "cleared",
  29535. lastCallTime: this.lastExecutionEnded,
  29536. isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled,
  29537. stopped: this.stopped,
  29538. heartbeatFrequencyMS: this.heartbeatFrequencyMS,
  29539. minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS,
  29540. currentTime,
  29541. timeSinceLastCall
  29542. };
  29543. }
  29544. _reschedule(ms) {
  29545. if (this.stopped)
  29546. return;
  29547. if (this.timerId) {
  29548. (0, timers_1.clearTimeout)(this.timerId);
  29549. }
  29550. this.timerId = (0, timers_1.setTimeout)(this._executeAndReschedule, ms || this.heartbeatFrequencyMS);
  29551. }
  29552. };
  29553. __name(_MonitorInterval, "MonitorInterval");
  29554. var MonitorInterval = _MonitorInterval;
  29555. exports2.MonitorInterval = MonitorInterval;
  29556. }
  29557. });
  29558. // node_modules/mongodb/lib/sdam/server.js
  29559. var require_server = __commonJS({
  29560. "node_modules/mongodb/lib/sdam/server.js"(exports2) {
  29561. "use strict";
  29562. Object.defineProperty(exports2, "__esModule", { value: true });
  29563. exports2.Server = void 0;
  29564. var util_1 = require("util");
  29565. var connection_1 = require_connection();
  29566. var connection_pool_1 = require_connection_pool();
  29567. var errors_1 = require_errors();
  29568. var constants_1 = require_constants2();
  29569. var error_1 = require_error();
  29570. var mongo_types_1 = require_mongo_types();
  29571. var transactions_1 = require_transactions();
  29572. var utils_1 = require_utils();
  29573. var common_1 = require_common();
  29574. var monitor_1 = require_monitor();
  29575. var server_description_1 = require_server_description();
  29576. var stateTransition = (0, utils_1.makeStateMachine)({
  29577. [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING],
  29578. [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED],
  29579. [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED],
  29580. [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED]
  29581. });
  29582. var _Server = class _Server extends mongo_types_1.TypedEventEmitter {
  29583. /**
  29584. * Create a server
  29585. */
  29586. constructor(topology, description, options) {
  29587. super();
  29588. this.commandAsync = (0, util_1.promisify)((ns, cmd, options2, callback) => this.command(ns, cmd, options2, callback));
  29589. this.serverApi = options.serverApi;
  29590. const poolOptions = { hostAddress: description.hostAddress, ...options };
  29591. this.topology = topology;
  29592. this.pool = new connection_pool_1.ConnectionPool(this, poolOptions);
  29593. this.s = {
  29594. description,
  29595. options,
  29596. state: common_1.STATE_CLOSED,
  29597. operationCount: 0
  29598. };
  29599. for (const event of [...constants_1.CMAP_EVENTS, ...constants_1.APM_EVENTS]) {
  29600. this.pool.on(event, (e) => this.emit(event, e));
  29601. }
  29602. this.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => {
  29603. this.clusterTime = clusterTime;
  29604. });
  29605. if (this.loadBalanced) {
  29606. this.monitor = null;
  29607. return;
  29608. }
  29609. this.monitor = new monitor_1.Monitor(this, this.s.options);
  29610. for (const event of constants_1.HEARTBEAT_EVENTS) {
  29611. this.monitor.on(event, (e) => this.emit(event, e));
  29612. }
  29613. this.monitor.on("resetServer", (error) => markServerUnknown(this, error));
  29614. this.monitor.on(_Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => {
  29615. this.emit(_Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, {
  29616. roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration)
  29617. }));
  29618. if (this.s.state === common_1.STATE_CONNECTING) {
  29619. stateTransition(this, common_1.STATE_CONNECTED);
  29620. this.emit(_Server.CONNECT, this);
  29621. }
  29622. });
  29623. }
  29624. get clusterTime() {
  29625. return this.topology.clusterTime;
  29626. }
  29627. set clusterTime(clusterTime) {
  29628. this.topology.clusterTime = clusterTime;
  29629. }
  29630. get description() {
  29631. return this.s.description;
  29632. }
  29633. get name() {
  29634. return this.s.description.address;
  29635. }
  29636. get autoEncrypter() {
  29637. if (this.s.options && this.s.options.autoEncrypter) {
  29638. return this.s.options.autoEncrypter;
  29639. }
  29640. return;
  29641. }
  29642. get loadBalanced() {
  29643. return this.topology.description.type === common_1.TopologyType.LoadBalanced;
  29644. }
  29645. /**
  29646. * Initiate server connect
  29647. */
  29648. connect() {
  29649. var _a;
  29650. if (this.s.state !== common_1.STATE_CLOSED) {
  29651. return;
  29652. }
  29653. stateTransition(this, common_1.STATE_CONNECTING);
  29654. if (!this.loadBalanced) {
  29655. (_a = this.monitor) == null ? void 0 : _a.connect();
  29656. } else {
  29657. stateTransition(this, common_1.STATE_CONNECTED);
  29658. this.emit(_Server.CONNECT, this);
  29659. }
  29660. }
  29661. /** Destroy the server connection */
  29662. destroy(options, callback) {
  29663. var _a;
  29664. if (typeof options === "function") {
  29665. callback = options;
  29666. options = { force: false };
  29667. }
  29668. options = Object.assign({}, { force: false }, options);
  29669. if (this.s.state === common_1.STATE_CLOSED) {
  29670. if (typeof callback === "function") {
  29671. callback();
  29672. }
  29673. return;
  29674. }
  29675. stateTransition(this, common_1.STATE_CLOSING);
  29676. if (!this.loadBalanced) {
  29677. (_a = this.monitor) == null ? void 0 : _a.close();
  29678. }
  29679. this.pool.close(options, (err) => {
  29680. stateTransition(this, common_1.STATE_CLOSED);
  29681. this.emit("closed");
  29682. if (typeof callback === "function") {
  29683. callback(err);
  29684. }
  29685. });
  29686. }
  29687. /**
  29688. * Immediately schedule monitoring of this server. If there already an attempt being made
  29689. * this will be a no-op.
  29690. */
  29691. requestCheck() {
  29692. var _a;
  29693. if (!this.loadBalanced) {
  29694. (_a = this.monitor) == null ? void 0 : _a.requestCheck();
  29695. }
  29696. }
  29697. /**
  29698. * Execute a command
  29699. * @internal
  29700. */
  29701. command(ns, cmd, options, callback) {
  29702. if (callback == null) {
  29703. throw new error_1.MongoInvalidArgumentError("Callback must be provided");
  29704. }
  29705. if (ns.db == null || typeof ns === "string") {
  29706. throw new error_1.MongoInvalidArgumentError("Namespace must not be a string");
  29707. }
  29708. if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) {
  29709. callback(new error_1.MongoServerClosedError());
  29710. return;
  29711. }
  29712. const finalOptions = Object.assign({}, options, { wireProtocolCommand: false });
  29713. if (finalOptions.omitReadPreference) {
  29714. delete finalOptions.readPreference;
  29715. }
  29716. const session = finalOptions.session;
  29717. const conn = session == null ? void 0 : session.pinnedConnection;
  29718. if (this.loadBalanced && session && conn == null && isPinnableCommand(cmd, session)) {
  29719. this.pool.checkOut((err, checkedOut) => {
  29720. if (err || checkedOut == null) {
  29721. if (callback)
  29722. return callback(err);
  29723. return;
  29724. }
  29725. session.pin(checkedOut);
  29726. this.command(ns, cmd, finalOptions, callback);
  29727. });
  29728. return;
  29729. }
  29730. this.incrementOperationCount();
  29731. this.pool.withConnection(conn, (err, conn2, cb) => {
  29732. if (err || !conn2) {
  29733. this.decrementOperationCount();
  29734. if (!err) {
  29735. return cb(new error_1.MongoRuntimeError("Failed to create connection without error"));
  29736. }
  29737. if (!(err instanceof errors_1.PoolClearedError)) {
  29738. this.handleError(err);
  29739. }
  29740. return cb(err);
  29741. }
  29742. conn2.command(ns, cmd, finalOptions, makeOperationHandler(this, conn2, cmd, finalOptions, (error, response) => {
  29743. this.decrementOperationCount();
  29744. cb(error, response);
  29745. }));
  29746. }, callback);
  29747. }
  29748. /**
  29749. * Handle SDAM error
  29750. * @internal
  29751. */
  29752. handleError(error, connection) {
  29753. if (!(error instanceof error_1.MongoError)) {
  29754. return;
  29755. }
  29756. const isStaleError = error.connectionGeneration && error.connectionGeneration < this.pool.generation;
  29757. if (isStaleError) {
  29758. return;
  29759. }
  29760. const isNetworkNonTimeoutError = error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError);
  29761. const isNetworkTimeoutBeforeHandshakeError = (0, error_1.isNetworkErrorBeforeHandshake)(error);
  29762. const isAuthHandshakeError = error.hasErrorLabel(error_1.MongoErrorLabel.HandshakeError);
  29763. if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) {
  29764. if (!this.loadBalanced) {
  29765. error.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
  29766. markServerUnknown(this, error);
  29767. } else if (connection) {
  29768. this.pool.clear({ serviceId: connection.serviceId });
  29769. }
  29770. } else {
  29771. if ((0, error_1.isSDAMUnrecoverableError)(error)) {
  29772. if (shouldHandleStateChangeError(this, error)) {
  29773. const shouldClearPool = (0, utils_1.maxWireVersion)(this) <= 7 || (0, error_1.isNodeShuttingDownError)(error);
  29774. if (this.loadBalanced && connection && shouldClearPool) {
  29775. this.pool.clear({ serviceId: connection.serviceId });
  29776. }
  29777. if (!this.loadBalanced) {
  29778. if (shouldClearPool) {
  29779. error.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
  29780. }
  29781. markServerUnknown(this, error);
  29782. process.nextTick(() => this.requestCheck());
  29783. }
  29784. }
  29785. }
  29786. }
  29787. }
  29788. /**
  29789. * Decrement the operation count, returning the new count.
  29790. */
  29791. decrementOperationCount() {
  29792. return this.s.operationCount -= 1;
  29793. }
  29794. /**
  29795. * Increment the operation count, returning the new count.
  29796. */
  29797. incrementOperationCount() {
  29798. return this.s.operationCount += 1;
  29799. }
  29800. };
  29801. __name(_Server, "Server");
  29802. var Server = _Server;
  29803. Server.SERVER_HEARTBEAT_STARTED = constants_1.SERVER_HEARTBEAT_STARTED;
  29804. Server.SERVER_HEARTBEAT_SUCCEEDED = constants_1.SERVER_HEARTBEAT_SUCCEEDED;
  29805. Server.SERVER_HEARTBEAT_FAILED = constants_1.SERVER_HEARTBEAT_FAILED;
  29806. Server.CONNECT = constants_1.CONNECT;
  29807. Server.DESCRIPTION_RECEIVED = constants_1.DESCRIPTION_RECEIVED;
  29808. Server.CLOSED = constants_1.CLOSED;
  29809. Server.ENDED = constants_1.ENDED;
  29810. exports2.Server = Server;
  29811. function calculateRoundTripTime(oldRtt, duration) {
  29812. if (oldRtt === -1) {
  29813. return duration;
  29814. }
  29815. const alpha = 0.2;
  29816. return alpha * duration + (1 - alpha) * oldRtt;
  29817. }
  29818. __name(calculateRoundTripTime, "calculateRoundTripTime");
  29819. function markServerUnknown(server, error) {
  29820. var _a;
  29821. if (server.loadBalanced) {
  29822. return;
  29823. }
  29824. if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) {
  29825. (_a = server.monitor) == null ? void 0 : _a.reset();
  29826. }
  29827. server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, void 0, { error }));
  29828. }
  29829. __name(markServerUnknown, "markServerUnknown");
  29830. function isPinnableCommand(cmd, session) {
  29831. if (session) {
  29832. return session.inTransaction() || "aggregate" in cmd || "find" in cmd || "getMore" in cmd || "listCollections" in cmd || "listIndexes" in cmd;
  29833. }
  29834. return false;
  29835. }
  29836. __name(isPinnableCommand, "isPinnableCommand");
  29837. function connectionIsStale(pool, connection) {
  29838. if (connection.serviceId) {
  29839. return connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString());
  29840. }
  29841. return connection.generation !== pool.generation;
  29842. }
  29843. __name(connectionIsStale, "connectionIsStale");
  29844. function shouldHandleStateChangeError(server, err) {
  29845. const etv = err.topologyVersion;
  29846. const stv = server.description.topologyVersion;
  29847. return (0, server_description_1.compareTopologyVersion)(stv, etv) < 0;
  29848. }
  29849. __name(shouldHandleStateChangeError, "shouldHandleStateChangeError");
  29850. function inActiveTransaction(session, cmd) {
  29851. return session && session.inTransaction() && !(0, transactions_1.isTransactionCommand)(cmd);
  29852. }
  29853. __name(inActiveTransaction, "inActiveTransaction");
  29854. function isRetryableWritesEnabled(topology) {
  29855. return topology.s.options.retryWrites !== false;
  29856. }
  29857. __name(isRetryableWritesEnabled, "isRetryableWritesEnabled");
  29858. function makeOperationHandler(server, connection, cmd, options, callback) {
  29859. const session = options == null ? void 0 : options.session;
  29860. return /* @__PURE__ */ __name(function handleOperationResult(error, result) {
  29861. if (error == null && result != null) {
  29862. return callback(void 0, result);
  29863. }
  29864. if (options != null && "noResponse" in options && options.noResponse === true) {
  29865. return callback(void 0, null);
  29866. }
  29867. if (!error) {
  29868. return callback(new error_1.MongoUnexpectedServerResponseError("Empty response with no error"));
  29869. }
  29870. if (!(error instanceof error_1.MongoError)) {
  29871. return callback(error);
  29872. }
  29873. if (connectionIsStale(server.pool, connection)) {
  29874. return callback(error);
  29875. }
  29876. if (error instanceof error_1.MongoNetworkError) {
  29877. if (session && !session.hasEnded && session.serverSession) {
  29878. session.serverSession.isDirty = true;
  29879. }
  29880. if (inActiveTransaction(session, cmd) && !error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  29881. error.addErrorLabel(error_1.MongoErrorLabel.TransientTransactionError);
  29882. }
  29883. if ((isRetryableWritesEnabled(server.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && (0, utils_1.supportsRetryableWrites)(server) && !inActiveTransaction(session, cmd)) {
  29884. error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
  29885. }
  29886. } else {
  29887. if ((isRetryableWritesEnabled(server.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && (0, error_1.needsRetryableWriteLabel)(error, (0, utils_1.maxWireVersion)(server)) && !inActiveTransaction(session, cmd)) {
  29888. error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
  29889. }
  29890. }
  29891. if (session && session.isPinned && error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
  29892. session.unpin({ force: true });
  29893. }
  29894. server.handleError(error, connection);
  29895. return callback(error);
  29896. }, "handleOperationResult");
  29897. }
  29898. __name(makeOperationHandler, "makeOperationHandler");
  29899. }
  29900. });
  29901. // node_modules/mongodb/lib/sdam/srv_polling.js
  29902. var require_srv_polling = __commonJS({
  29903. "node_modules/mongodb/lib/sdam/srv_polling.js"(exports2) {
  29904. "use strict";
  29905. Object.defineProperty(exports2, "__esModule", { value: true });
  29906. exports2.SrvPoller = exports2.SrvPollingEvent = void 0;
  29907. var dns = require("dns");
  29908. var timers_1 = require("timers");
  29909. var error_1 = require_error();
  29910. var mongo_types_1 = require_mongo_types();
  29911. var utils_1 = require_utils();
  29912. var _SrvPollingEvent = class _SrvPollingEvent {
  29913. constructor(srvRecords) {
  29914. this.srvRecords = srvRecords;
  29915. }
  29916. hostnames() {
  29917. return new Set(this.srvRecords.map((r) => utils_1.HostAddress.fromSrvRecord(r).toString()));
  29918. }
  29919. };
  29920. __name(_SrvPollingEvent, "SrvPollingEvent");
  29921. var SrvPollingEvent = _SrvPollingEvent;
  29922. exports2.SrvPollingEvent = SrvPollingEvent;
  29923. var _SrvPoller = class _SrvPoller extends mongo_types_1.TypedEventEmitter {
  29924. constructor(options) {
  29925. super();
  29926. if (!options || !options.srvHost) {
  29927. throw new error_1.MongoRuntimeError("Options for SrvPoller must exist and include srvHost");
  29928. }
  29929. this.srvHost = options.srvHost;
  29930. this.srvMaxHosts = options.srvMaxHosts ?? 0;
  29931. this.srvServiceName = options.srvServiceName ?? "mongodb";
  29932. this.rescanSrvIntervalMS = 6e4;
  29933. this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1e4;
  29934. this.haMode = false;
  29935. this.generation = 0;
  29936. this._timeout = void 0;
  29937. }
  29938. get srvAddress() {
  29939. return `_${this.srvServiceName}._tcp.${this.srvHost}`;
  29940. }
  29941. get intervalMS() {
  29942. return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS;
  29943. }
  29944. start() {
  29945. if (!this._timeout) {
  29946. this.schedule();
  29947. }
  29948. }
  29949. stop() {
  29950. if (this._timeout) {
  29951. (0, timers_1.clearTimeout)(this._timeout);
  29952. this.generation += 1;
  29953. this._timeout = void 0;
  29954. }
  29955. }
  29956. // TODO(NODE-4994): implement new logging logic for SrvPoller failures
  29957. schedule() {
  29958. if (this._timeout) {
  29959. (0, timers_1.clearTimeout)(this._timeout);
  29960. }
  29961. this._timeout = (0, timers_1.setTimeout)(() => {
  29962. this._poll().catch(() => null);
  29963. }, this.intervalMS);
  29964. }
  29965. success(srvRecords) {
  29966. this.haMode = false;
  29967. this.schedule();
  29968. this.emit(_SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords));
  29969. }
  29970. failure() {
  29971. this.haMode = true;
  29972. this.schedule();
  29973. }
  29974. async _poll() {
  29975. const generation = this.generation;
  29976. let srvRecords;
  29977. try {
  29978. srvRecords = await dns.promises.resolveSrv(this.srvAddress);
  29979. } catch (dnsError) {
  29980. this.failure();
  29981. return;
  29982. }
  29983. if (generation !== this.generation) {
  29984. return;
  29985. }
  29986. const finalAddresses = [];
  29987. for (const record of srvRecords) {
  29988. if ((0, utils_1.matchesParentDomain)(record.name, this.srvHost)) {
  29989. finalAddresses.push(record);
  29990. }
  29991. }
  29992. if (!finalAddresses.length) {
  29993. this.failure();
  29994. return;
  29995. }
  29996. this.success(finalAddresses);
  29997. }
  29998. };
  29999. __name(_SrvPoller, "SrvPoller");
  30000. var SrvPoller = _SrvPoller;
  30001. SrvPoller.SRV_RECORD_DISCOVERY = "srvRecordDiscovery";
  30002. exports2.SrvPoller = SrvPoller;
  30003. }
  30004. });
  30005. // node_modules/mongodb/lib/sdam/topology.js
  30006. var require_topology = __commonJS({
  30007. "node_modules/mongodb/lib/sdam/topology.js"(exports2) {
  30008. "use strict";
  30009. Object.defineProperty(exports2, "__esModule", { value: true });
  30010. exports2.ServerCapabilities = exports2.Topology = void 0;
  30011. var timers_1 = require("timers");
  30012. var util_1 = require("util");
  30013. var connection_string_1 = require_connection_string();
  30014. var constants_1 = require_constants2();
  30015. var error_1 = require_error();
  30016. var mongo_types_1 = require_mongo_types();
  30017. var read_preference_1 = require_read_preference();
  30018. var utils_1 = require_utils();
  30019. var common_1 = require_common();
  30020. var events_1 = require_events();
  30021. var server_1 = require_server();
  30022. var server_description_1 = require_server_description();
  30023. var server_selection_1 = require_server_selection();
  30024. var srv_polling_1 = require_srv_polling();
  30025. var topology_description_1 = require_topology_description();
  30026. var globalTopologyCounter = 0;
  30027. var stateTransition = (0, utils_1.makeStateMachine)({
  30028. [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING],
  30029. [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED],
  30030. [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED],
  30031. [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED]
  30032. });
  30033. var kCancelled = Symbol("cancelled");
  30034. var kWaitQueue = Symbol("waitQueue");
  30035. var _Topology = class _Topology extends mongo_types_1.TypedEventEmitter {
  30036. /**
  30037. * @param seedlist - a list of HostAddress instances to connect to
  30038. */
  30039. constructor(client, seeds, options) {
  30040. super();
  30041. this.client = client;
  30042. this.selectServerAsync = (0, util_1.promisify)((selector, options2, callback) => this.selectServer(selector, options2, callback));
  30043. options = options ?? {
  30044. hosts: [utils_1.HostAddress.fromString("localhost:27017")],
  30045. ...Object.fromEntries(connection_string_1.DEFAULT_OPTIONS.entries()),
  30046. ...Object.fromEntries(connection_string_1.FEATURE_FLAGS.entries())
  30047. };
  30048. if (typeof seeds === "string") {
  30049. seeds = [utils_1.HostAddress.fromString(seeds)];
  30050. } else if (!Array.isArray(seeds)) {
  30051. seeds = [seeds];
  30052. }
  30053. const seedlist = [];
  30054. for (const seed of seeds) {
  30055. if (typeof seed === "string") {
  30056. seedlist.push(utils_1.HostAddress.fromString(seed));
  30057. } else if (seed instanceof utils_1.HostAddress) {
  30058. seedlist.push(seed);
  30059. } else {
  30060. throw new error_1.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`);
  30061. }
  30062. }
  30063. const topologyType = topologyTypeFromOptions(options);
  30064. const topologyId = globalTopologyCounter++;
  30065. const selectedHosts = options.srvMaxHosts == null || options.srvMaxHosts === 0 || options.srvMaxHosts >= seedlist.length ? seedlist : (0, utils_1.shuffle)(seedlist, options.srvMaxHosts);
  30066. const serverDescriptions = /* @__PURE__ */ new Map();
  30067. for (const hostAddress of selectedHosts) {
  30068. serverDescriptions.set(hostAddress.toString(), new server_description_1.ServerDescription(hostAddress));
  30069. }
  30070. this[kWaitQueue] = new utils_1.List();
  30071. this.s = {
  30072. // the id of this topology
  30073. id: topologyId,
  30074. // passed in options
  30075. options,
  30076. // initial seedlist of servers to connect to
  30077. seedlist,
  30078. // initial state
  30079. state: common_1.STATE_CLOSED,
  30080. // the topology description
  30081. description: new topology_description_1.TopologyDescription(topologyType, serverDescriptions, options.replicaSet, void 0, void 0, void 0, options),
  30082. serverSelectionTimeoutMS: options.serverSelectionTimeoutMS,
  30083. heartbeatFrequencyMS: options.heartbeatFrequencyMS,
  30084. minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS,
  30085. // a map of server instances to normalized addresses
  30086. servers: /* @__PURE__ */ new Map(),
  30087. credentials: options == null ? void 0 : options.credentials,
  30088. clusterTime: void 0,
  30089. // timer management
  30090. connectionTimers: /* @__PURE__ */ new Set(),
  30091. detectShardedTopology: /* @__PURE__ */ __name((ev) => this.detectShardedTopology(ev), "detectShardedTopology"),
  30092. detectSrvRecords: /* @__PURE__ */ __name((ev) => this.detectSrvRecords(ev), "detectSrvRecords")
  30093. };
  30094. if (options.srvHost && !options.loadBalanced) {
  30095. this.s.srvPoller = options.srvPoller ?? new srv_polling_1.SrvPoller({
  30096. heartbeatFrequencyMS: this.s.heartbeatFrequencyMS,
  30097. srvHost: options.srvHost,
  30098. srvMaxHosts: options.srvMaxHosts,
  30099. srvServiceName: options.srvServiceName
  30100. });
  30101. this.on(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology);
  30102. }
  30103. }
  30104. detectShardedTopology(event) {
  30105. var _a, _b, _c;
  30106. const previousType = event.previousDescription.type;
  30107. const newType = event.newDescription.type;
  30108. const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded;
  30109. const srvListeners = (_a = this.s.srvPoller) == null ? void 0 : _a.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY);
  30110. const listeningToSrvPolling = !!(srvListeners == null ? void 0 : srvListeners.includes(this.s.detectSrvRecords));
  30111. if (transitionToSharded && !listeningToSrvPolling) {
  30112. (_b = this.s.srvPoller) == null ? void 0 : _b.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords);
  30113. (_c = this.s.srvPoller) == null ? void 0 : _c.start();
  30114. }
  30115. }
  30116. detectSrvRecords(ev) {
  30117. const previousTopologyDescription = this.s.description;
  30118. this.s.description = this.s.description.updateFromSrvPollingEvent(ev, this.s.options.srvMaxHosts);
  30119. if (this.s.description === previousTopologyDescription) {
  30120. return;
  30121. }
  30122. updateServers(this);
  30123. this.emit(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description));
  30124. }
  30125. /**
  30126. * @returns A `TopologyDescription` for this topology
  30127. */
  30128. get description() {
  30129. return this.s.description;
  30130. }
  30131. get loadBalanced() {
  30132. return this.s.options.loadBalanced;
  30133. }
  30134. get capabilities() {
  30135. return new ServerCapabilities(this.lastHello());
  30136. }
  30137. connect(options, callback) {
  30138. if (typeof options === "function")
  30139. callback = options, options = {};
  30140. options = options ?? {};
  30141. if (this.s.state === common_1.STATE_CONNECTED) {
  30142. if (typeof callback === "function") {
  30143. callback();
  30144. }
  30145. return;
  30146. }
  30147. stateTransition(this, common_1.STATE_CONNECTING);
  30148. this.emit(_Topology.TOPOLOGY_OPENING, new events_1.TopologyOpeningEvent(this.s.id));
  30149. this.emit(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(
  30150. this.s.id,
  30151. new topology_description_1.TopologyDescription(common_1.TopologyType.Unknown),
  30152. // initial is always Unknown
  30153. this.s.description
  30154. ));
  30155. const serverDescriptions = Array.from(this.s.description.servers.values());
  30156. this.s.servers = new Map(serverDescriptions.map((serverDescription) => [
  30157. serverDescription.address,
  30158. createAndConnectServer(this, serverDescription)
  30159. ]));
  30160. if (this.s.options.loadBalanced) {
  30161. for (const description of serverDescriptions) {
  30162. const newDescription = new server_description_1.ServerDescription(description.hostAddress, void 0, {
  30163. loadBalanced: this.s.options.loadBalanced
  30164. });
  30165. this.serverUpdateHandler(newDescription);
  30166. }
  30167. }
  30168. const exitWithError = /* @__PURE__ */ __name((error) => callback ? callback(error) : this.emit(_Topology.ERROR, error), "exitWithError");
  30169. const readPreference = options.readPreference ?? read_preference_1.ReadPreference.primary;
  30170. this.selectServer((0, server_selection_1.readPreferenceServerSelector)(readPreference), options, (err, server) => {
  30171. if (err) {
  30172. return this.close({ force: false }, () => exitWithError(err));
  30173. }
  30174. const skipPingOnConnect = this.s.options[Symbol.for("@@mdb.skipPingOnConnect")] === true;
  30175. if (!skipPingOnConnect && server && this.s.credentials) {
  30176. server.command((0, utils_1.ns)("admin.$cmd"), { ping: 1 }, {}, (err2) => {
  30177. if (err2) {
  30178. return exitWithError(err2);
  30179. }
  30180. stateTransition(this, common_1.STATE_CONNECTED);
  30181. this.emit(_Topology.OPEN, this);
  30182. this.emit(_Topology.CONNECT, this);
  30183. callback == null ? void 0 : callback(void 0, this);
  30184. });
  30185. return;
  30186. }
  30187. stateTransition(this, common_1.STATE_CONNECTED);
  30188. this.emit(_Topology.OPEN, this);
  30189. this.emit(_Topology.CONNECT, this);
  30190. callback == null ? void 0 : callback(void 0, this);
  30191. });
  30192. }
  30193. close(options, callback) {
  30194. options = options ?? { force: false };
  30195. if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) {
  30196. return callback == null ? void 0 : callback();
  30197. }
  30198. const destroyedServers = Array.from(this.s.servers.values(), (server) => {
  30199. return (0, util_1.promisify)(destroyServer)(server, this, { force: !!(options == null ? void 0 : options.force) });
  30200. });
  30201. Promise.all(destroyedServers).then(() => {
  30202. this.s.servers.clear();
  30203. stateTransition(this, common_1.STATE_CLOSING);
  30204. drainWaitQueue(this[kWaitQueue], new error_1.MongoTopologyClosedError());
  30205. (0, common_1.drainTimerQueue)(this.s.connectionTimers);
  30206. if (this.s.srvPoller) {
  30207. this.s.srvPoller.stop();
  30208. this.s.srvPoller.removeListener(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords);
  30209. }
  30210. this.removeListener(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology);
  30211. stateTransition(this, common_1.STATE_CLOSED);
  30212. this.emit(_Topology.TOPOLOGY_CLOSED, new events_1.TopologyClosedEvent(this.s.id));
  30213. }).finally(() => callback == null ? void 0 : callback());
  30214. }
  30215. /**
  30216. * Selects a server according to the selection predicate provided
  30217. *
  30218. * @param selector - An optional selector to select servers by, defaults to a random selection within a latency window
  30219. * @param options - Optional settings related to server selection
  30220. * @param callback - The callback used to indicate success or failure
  30221. * @returns An instance of a `Server` meeting the criteria of the predicate provided
  30222. */
  30223. selectServer(selector, options, callback) {
  30224. let serverSelector;
  30225. if (typeof selector !== "function") {
  30226. if (typeof selector === "string") {
  30227. serverSelector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.fromString(selector));
  30228. } else {
  30229. let readPreference;
  30230. if (selector instanceof read_preference_1.ReadPreference) {
  30231. readPreference = selector;
  30232. } else {
  30233. read_preference_1.ReadPreference.translate(options);
  30234. readPreference = options.readPreference || read_preference_1.ReadPreference.primary;
  30235. }
  30236. serverSelector = (0, server_selection_1.readPreferenceServerSelector)(readPreference);
  30237. }
  30238. } else {
  30239. serverSelector = selector;
  30240. }
  30241. options = Object.assign({}, { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, options);
  30242. const isSharded = this.description.type === common_1.TopologyType.Sharded;
  30243. const session = options.session;
  30244. const transaction = session && session.transaction;
  30245. if (isSharded && transaction && transaction.server) {
  30246. callback(void 0, transaction.server);
  30247. return;
  30248. }
  30249. const waitQueueMember = {
  30250. serverSelector,
  30251. transaction,
  30252. callback
  30253. };
  30254. const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS;
  30255. if (serverSelectionTimeoutMS) {
  30256. waitQueueMember.timer = (0, timers_1.setTimeout)(() => {
  30257. waitQueueMember[kCancelled] = true;
  30258. waitQueueMember.timer = void 0;
  30259. const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
  30260. waitQueueMember.callback(timeoutError);
  30261. }, serverSelectionTimeoutMS);
  30262. }
  30263. this[kWaitQueue].push(waitQueueMember);
  30264. processWaitQueue(this);
  30265. }
  30266. /**
  30267. * Update the internal TopologyDescription with a ServerDescription
  30268. *
  30269. * @param serverDescription - The server to update in the internal list of server descriptions
  30270. */
  30271. serverUpdateHandler(serverDescription) {
  30272. if (!this.s.description.hasServer(serverDescription.address)) {
  30273. return;
  30274. }
  30275. if (isStaleServerDescription(this.s.description, serverDescription)) {
  30276. return;
  30277. }
  30278. const previousTopologyDescription = this.s.description;
  30279. const previousServerDescription = this.s.description.servers.get(serverDescription.address);
  30280. if (!previousServerDescription) {
  30281. return;
  30282. }
  30283. const clusterTime = serverDescription.$clusterTime;
  30284. if (clusterTime) {
  30285. (0, common_1._advanceClusterTime)(this, clusterTime);
  30286. }
  30287. const equalDescriptions = previousServerDescription && previousServerDescription.equals(serverDescription);
  30288. this.s.description = this.s.description.update(serverDescription);
  30289. if (this.s.description.compatibilityError) {
  30290. this.emit(_Topology.ERROR, new error_1.MongoCompatibilityError(this.s.description.compatibilityError));
  30291. return;
  30292. }
  30293. if (!equalDescriptions) {
  30294. const newDescription = this.s.description.servers.get(serverDescription.address);
  30295. if (newDescription) {
  30296. this.emit(_Topology.SERVER_DESCRIPTION_CHANGED, new events_1.ServerDescriptionChangedEvent(this.s.id, serverDescription.address, previousServerDescription, newDescription));
  30297. }
  30298. }
  30299. updateServers(this, serverDescription);
  30300. if (this[kWaitQueue].length > 0) {
  30301. processWaitQueue(this);
  30302. }
  30303. if (!equalDescriptions) {
  30304. this.emit(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description));
  30305. }
  30306. }
  30307. auth(credentials, callback) {
  30308. if (typeof credentials === "function")
  30309. callback = credentials, credentials = void 0;
  30310. if (typeof callback === "function")
  30311. callback(void 0, true);
  30312. }
  30313. get clientMetadata() {
  30314. return this.s.options.metadata;
  30315. }
  30316. isConnected() {
  30317. return this.s.state === common_1.STATE_CONNECTED;
  30318. }
  30319. isDestroyed() {
  30320. return this.s.state === common_1.STATE_CLOSED;
  30321. }
  30322. // NOTE: There are many places in code where we explicitly check the last hello
  30323. // to do feature support detection. This should be done any other way, but for
  30324. // now we will just return the first hello seen, which should suffice.
  30325. lastHello() {
  30326. const serverDescriptions = Array.from(this.description.servers.values());
  30327. if (serverDescriptions.length === 0)
  30328. return {};
  30329. const sd = serverDescriptions.filter((sd2) => sd2.type !== common_1.ServerType.Unknown)[0];
  30330. const result = sd || { maxWireVersion: this.description.commonWireVersion };
  30331. return result;
  30332. }
  30333. get commonWireVersion() {
  30334. return this.description.commonWireVersion;
  30335. }
  30336. get logicalSessionTimeoutMinutes() {
  30337. return this.description.logicalSessionTimeoutMinutes;
  30338. }
  30339. get clusterTime() {
  30340. return this.s.clusterTime;
  30341. }
  30342. set clusterTime(clusterTime) {
  30343. this.s.clusterTime = clusterTime;
  30344. }
  30345. };
  30346. __name(_Topology, "Topology");
  30347. var Topology = _Topology;
  30348. Topology.SERVER_OPENING = constants_1.SERVER_OPENING;
  30349. Topology.SERVER_CLOSED = constants_1.SERVER_CLOSED;
  30350. Topology.SERVER_DESCRIPTION_CHANGED = constants_1.SERVER_DESCRIPTION_CHANGED;
  30351. Topology.TOPOLOGY_OPENING = constants_1.TOPOLOGY_OPENING;
  30352. Topology.TOPOLOGY_CLOSED = constants_1.TOPOLOGY_CLOSED;
  30353. Topology.TOPOLOGY_DESCRIPTION_CHANGED = constants_1.TOPOLOGY_DESCRIPTION_CHANGED;
  30354. Topology.ERROR = constants_1.ERROR;
  30355. Topology.OPEN = constants_1.OPEN;
  30356. Topology.CONNECT = constants_1.CONNECT;
  30357. Topology.CLOSE = constants_1.CLOSE;
  30358. Topology.TIMEOUT = constants_1.TIMEOUT;
  30359. exports2.Topology = Topology;
  30360. function destroyServer(server, topology, options, callback) {
  30361. options = options ?? { force: false };
  30362. for (const event of constants_1.LOCAL_SERVER_EVENTS) {
  30363. server.removeAllListeners(event);
  30364. }
  30365. server.destroy(options, () => {
  30366. topology.emit(Topology.SERVER_CLOSED, new events_1.ServerClosedEvent(topology.s.id, server.description.address));
  30367. for (const event of constants_1.SERVER_RELAY_EVENTS) {
  30368. server.removeAllListeners(event);
  30369. }
  30370. if (typeof callback === "function") {
  30371. callback();
  30372. }
  30373. });
  30374. }
  30375. __name(destroyServer, "destroyServer");
  30376. function topologyTypeFromOptions(options) {
  30377. if (options == null ? void 0 : options.directConnection) {
  30378. return common_1.TopologyType.Single;
  30379. }
  30380. if (options == null ? void 0 : options.replicaSet) {
  30381. return common_1.TopologyType.ReplicaSetNoPrimary;
  30382. }
  30383. if (options == null ? void 0 : options.loadBalanced) {
  30384. return common_1.TopologyType.LoadBalanced;
  30385. }
  30386. return common_1.TopologyType.Unknown;
  30387. }
  30388. __name(topologyTypeFromOptions, "topologyTypeFromOptions");
  30389. function createAndConnectServer(topology, serverDescription) {
  30390. topology.emit(Topology.SERVER_OPENING, new events_1.ServerOpeningEvent(topology.s.id, serverDescription.address));
  30391. const server = new server_1.Server(topology, serverDescription, topology.s.options);
  30392. for (const event of constants_1.SERVER_RELAY_EVENTS) {
  30393. server.on(event, (e) => topology.emit(event, e));
  30394. }
  30395. server.on(server_1.Server.DESCRIPTION_RECEIVED, (description) => topology.serverUpdateHandler(description));
  30396. server.connect();
  30397. return server;
  30398. }
  30399. __name(createAndConnectServer, "createAndConnectServer");
  30400. function updateServers(topology, incomingServerDescription) {
  30401. if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) {
  30402. const server = topology.s.servers.get(incomingServerDescription.address);
  30403. if (server) {
  30404. server.s.description = incomingServerDescription;
  30405. if (incomingServerDescription.error instanceof error_1.MongoError && incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.ResetPool)) {
  30406. const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections);
  30407. server.pool.clear({ interruptInUseConnections });
  30408. } else if (incomingServerDescription.error == null) {
  30409. const newTopologyType = topology.s.description.type;
  30410. const shouldMarkPoolReady = incomingServerDescription.isDataBearing || incomingServerDescription.type !== common_1.ServerType.Unknown && newTopologyType === common_1.TopologyType.Single;
  30411. if (shouldMarkPoolReady) {
  30412. server.pool.ready();
  30413. }
  30414. }
  30415. }
  30416. }
  30417. for (const serverDescription of topology.description.servers.values()) {
  30418. if (!topology.s.servers.has(serverDescription.address)) {
  30419. const server = createAndConnectServer(topology, serverDescription);
  30420. topology.s.servers.set(serverDescription.address, server);
  30421. }
  30422. }
  30423. for (const entry of topology.s.servers) {
  30424. const serverAddress = entry[0];
  30425. if (topology.description.hasServer(serverAddress)) {
  30426. continue;
  30427. }
  30428. if (!topology.s.servers.has(serverAddress)) {
  30429. continue;
  30430. }
  30431. const server = topology.s.servers.get(serverAddress);
  30432. topology.s.servers.delete(serverAddress);
  30433. if (server) {
  30434. destroyServer(server, topology);
  30435. }
  30436. }
  30437. }
  30438. __name(updateServers, "updateServers");
  30439. function drainWaitQueue(queue, err) {
  30440. while (queue.length) {
  30441. const waitQueueMember = queue.shift();
  30442. if (!waitQueueMember) {
  30443. continue;
  30444. }
  30445. if (waitQueueMember.timer) {
  30446. (0, timers_1.clearTimeout)(waitQueueMember.timer);
  30447. }
  30448. if (!waitQueueMember[kCancelled]) {
  30449. waitQueueMember.callback(err);
  30450. }
  30451. }
  30452. }
  30453. __name(drainWaitQueue, "drainWaitQueue");
  30454. function processWaitQueue(topology) {
  30455. if (topology.s.state === common_1.STATE_CLOSED) {
  30456. drainWaitQueue(topology[kWaitQueue], new error_1.MongoTopologyClosedError());
  30457. return;
  30458. }
  30459. const isSharded = topology.description.type === common_1.TopologyType.Sharded;
  30460. const serverDescriptions = Array.from(topology.description.servers.values());
  30461. const membersToProcess = topology[kWaitQueue].length;
  30462. for (let i = 0; i < membersToProcess; ++i) {
  30463. const waitQueueMember = topology[kWaitQueue].shift();
  30464. if (!waitQueueMember) {
  30465. continue;
  30466. }
  30467. if (waitQueueMember[kCancelled]) {
  30468. continue;
  30469. }
  30470. let selectedDescriptions;
  30471. try {
  30472. const serverSelector = waitQueueMember.serverSelector;
  30473. selectedDescriptions = serverSelector ? serverSelector(topology.description, serverDescriptions) : serverDescriptions;
  30474. } catch (e) {
  30475. if (waitQueueMember.timer) {
  30476. (0, timers_1.clearTimeout)(waitQueueMember.timer);
  30477. }
  30478. waitQueueMember.callback(e);
  30479. continue;
  30480. }
  30481. let selectedServer;
  30482. if (selectedDescriptions.length === 0) {
  30483. topology[kWaitQueue].push(waitQueueMember);
  30484. continue;
  30485. } else if (selectedDescriptions.length === 1) {
  30486. selectedServer = topology.s.servers.get(selectedDescriptions[0].address);
  30487. } else {
  30488. const descriptions = (0, utils_1.shuffle)(selectedDescriptions, 2);
  30489. const server1 = topology.s.servers.get(descriptions[0].address);
  30490. const server2 = topology.s.servers.get(descriptions[1].address);
  30491. selectedServer = server1 && server2 && server1.s.operationCount < server2.s.operationCount ? server1 : server2;
  30492. }
  30493. if (!selectedServer) {
  30494. waitQueueMember.callback(new error_1.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology", topology.description));
  30495. return;
  30496. }
  30497. const transaction = waitQueueMember.transaction;
  30498. if (isSharded && transaction && transaction.isActive && selectedServer) {
  30499. transaction.pinServer(selectedServer);
  30500. }
  30501. if (waitQueueMember.timer) {
  30502. (0, timers_1.clearTimeout)(waitQueueMember.timer);
  30503. }
  30504. waitQueueMember.callback(void 0, selectedServer);
  30505. }
  30506. if (topology[kWaitQueue].length > 0) {
  30507. for (const [, server] of topology.s.servers) {
  30508. process.nextTick(/* @__PURE__ */ __name(function scheduleServerCheck() {
  30509. return server.requestCheck();
  30510. }, "scheduleServerCheck"));
  30511. }
  30512. }
  30513. }
  30514. __name(processWaitQueue, "processWaitQueue");
  30515. function isStaleServerDescription(topologyDescription, incomingServerDescription) {
  30516. const currentServerDescription = topologyDescription.servers.get(incomingServerDescription.address);
  30517. const currentTopologyVersion = currentServerDescription == null ? void 0 : currentServerDescription.topologyVersion;
  30518. return (0, server_description_1.compareTopologyVersion)(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0;
  30519. }
  30520. __name(isStaleServerDescription, "isStaleServerDescription");
  30521. var _ServerCapabilities = class _ServerCapabilities {
  30522. constructor(hello) {
  30523. this.minWireVersion = hello.minWireVersion || 0;
  30524. this.maxWireVersion = hello.maxWireVersion || 0;
  30525. }
  30526. get hasAggregationCursor() {
  30527. return this.maxWireVersion >= 1;
  30528. }
  30529. get hasWriteCommands() {
  30530. return this.maxWireVersion >= 2;
  30531. }
  30532. get hasTextSearch() {
  30533. return this.minWireVersion >= 0;
  30534. }
  30535. get hasAuthCommands() {
  30536. return this.maxWireVersion >= 1;
  30537. }
  30538. get hasListCollectionsCommand() {
  30539. return this.maxWireVersion >= 3;
  30540. }
  30541. get hasListIndexesCommand() {
  30542. return this.maxWireVersion >= 3;
  30543. }
  30544. get supportsSnapshotReads() {
  30545. return this.maxWireVersion >= 13;
  30546. }
  30547. get commandsTakeWriteConcern() {
  30548. return this.maxWireVersion >= 5;
  30549. }
  30550. get commandsTakeCollation() {
  30551. return this.maxWireVersion >= 5;
  30552. }
  30553. };
  30554. __name(_ServerCapabilities, "ServerCapabilities");
  30555. var ServerCapabilities = _ServerCapabilities;
  30556. exports2.ServerCapabilities = ServerCapabilities;
  30557. }
  30558. });
  30559. // node_modules/mongodb/lib/mongo_client.js
  30560. var require_mongo_client = __commonJS({
  30561. "node_modules/mongodb/lib/mongo_client.js"(exports2) {
  30562. "use strict";
  30563. Object.defineProperty(exports2, "__esModule", { value: true });
  30564. exports2.MongoClient = exports2.ServerApiVersion = void 0;
  30565. var util_1 = require("util");
  30566. var bson_1 = require_bson2();
  30567. var change_stream_1 = require_change_stream();
  30568. var mongo_credentials_1 = require_mongo_credentials();
  30569. var providers_1 = require_providers();
  30570. var connection_string_1 = require_connection_string();
  30571. var constants_1 = require_constants2();
  30572. var db_1 = require_db();
  30573. var error_1 = require_error();
  30574. var mongo_logger_1 = require_mongo_logger();
  30575. var mongo_types_1 = require_mongo_types();
  30576. var read_preference_1 = require_read_preference();
  30577. var server_selection_1 = require_server_selection();
  30578. var topology_1 = require_topology();
  30579. var sessions_1 = require_sessions();
  30580. var utils_1 = require_utils();
  30581. exports2.ServerApiVersion = Object.freeze({
  30582. v1: "1"
  30583. });
  30584. var kOptions = Symbol("options");
  30585. var _MongoClient = class _MongoClient extends mongo_types_1.TypedEventEmitter {
  30586. constructor(url, options) {
  30587. super();
  30588. this[kOptions] = (0, connection_string_1.parseOptions)(url, this, options);
  30589. this.mongoLogger = new mongo_logger_1.MongoLogger(this[kOptions].mongoLoggerOptions);
  30590. const client = this;
  30591. this.s = {
  30592. url,
  30593. bsonOptions: (0, bson_1.resolveBSONOptions)(this[kOptions]),
  30594. namespace: (0, utils_1.ns)("admin"),
  30595. hasBeenClosed: false,
  30596. sessionPool: new sessions_1.ServerSessionPool(this),
  30597. activeSessions: /* @__PURE__ */ new Set(),
  30598. get options() {
  30599. return client[kOptions];
  30600. },
  30601. get readConcern() {
  30602. return client[kOptions].readConcern;
  30603. },
  30604. get writeConcern() {
  30605. return client[kOptions].writeConcern;
  30606. },
  30607. get readPreference() {
  30608. return client[kOptions].readPreference;
  30609. },
  30610. get isMongoClient() {
  30611. return true;
  30612. }
  30613. };
  30614. }
  30615. /** @see MongoOptions */
  30616. get options() {
  30617. return Object.freeze({ ...this[kOptions] });
  30618. }
  30619. get serverApi() {
  30620. return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi });
  30621. }
  30622. /**
  30623. * Intended for APM use only
  30624. * @internal
  30625. */
  30626. get monitorCommands() {
  30627. return this[kOptions].monitorCommands;
  30628. }
  30629. set monitorCommands(value) {
  30630. this[kOptions].monitorCommands = value;
  30631. }
  30632. /**
  30633. * @deprecated This method will be removed in the next major version.
  30634. */
  30635. get autoEncrypter() {
  30636. return this[kOptions].autoEncrypter;
  30637. }
  30638. get readConcern() {
  30639. return this.s.readConcern;
  30640. }
  30641. get writeConcern() {
  30642. return this.s.writeConcern;
  30643. }
  30644. get readPreference() {
  30645. return this.s.readPreference;
  30646. }
  30647. get bsonOptions() {
  30648. return this.s.bsonOptions;
  30649. }
  30650. /**
  30651. * Connect to MongoDB using a url
  30652. *
  30653. * @see docs.mongodb.org/manual/reference/connection-string/
  30654. */
  30655. async connect() {
  30656. if (this.connectionLock) {
  30657. return this.connectionLock;
  30658. }
  30659. try {
  30660. this.connectionLock = this._connect();
  30661. await this.connectionLock;
  30662. } finally {
  30663. this.connectionLock = void 0;
  30664. }
  30665. return this;
  30666. }
  30667. /**
  30668. * Create a topology to open the connection, must be locked to avoid topology leaks in concurrency scenario.
  30669. * Locking is enforced by the connect method.
  30670. *
  30671. * @internal
  30672. */
  30673. async _connect() {
  30674. var _a, _b, _c, _d, _e;
  30675. if (this.topology && this.topology.isConnected()) {
  30676. return this;
  30677. }
  30678. const options = this[kOptions];
  30679. if (typeof options.srvHost === "string") {
  30680. const hosts = await (0, connection_string_1.resolveSRVRecord)(options);
  30681. for (const [index, host] of hosts.entries()) {
  30682. options.hosts[index] = host;
  30683. }
  30684. }
  30685. if (((_a = options.credentials) == null ? void 0 : _a.mechanism) === providers_1.AuthMechanism.MONGODB_OIDC) {
  30686. const allowedHosts = ((_c = (_b = options.credentials) == null ? void 0 : _b.mechanismProperties) == null ? void 0 : _c.ALLOWED_HOSTS) || mongo_credentials_1.DEFAULT_ALLOWED_HOSTS;
  30687. const isServiceAuth = !!((_e = (_d = options.credentials) == null ? void 0 : _d.mechanismProperties) == null ? void 0 : _e.PROVIDER_NAME);
  30688. if (!isServiceAuth) {
  30689. for (const host of options.hosts) {
  30690. if (!(0, utils_1.hostMatchesWildcards)(host.toHostPort().host, allowedHosts)) {
  30691. throw new error_1.MongoInvalidArgumentError(`Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(",")}'`);
  30692. }
  30693. }
  30694. }
  30695. }
  30696. this.topology = new topology_1.Topology(this, options.hosts, options);
  30697. this.topology.once(topology_1.Topology.OPEN, () => this.emit("open", this));
  30698. for (const event of constants_1.MONGO_CLIENT_EVENTS) {
  30699. this.topology.on(event, (...args) => this.emit(event, ...args));
  30700. }
  30701. const topologyConnect = /* @__PURE__ */ __name(async () => {
  30702. var _a2;
  30703. try {
  30704. await (0, util_1.promisify)((callback) => {
  30705. var _a3;
  30706. return (_a3 = this.topology) == null ? void 0 : _a3.connect(options, callback);
  30707. })();
  30708. } catch (error) {
  30709. (_a2 = this.topology) == null ? void 0 : _a2.close({ force: true });
  30710. throw error;
  30711. }
  30712. }, "topologyConnect");
  30713. if (this.autoEncrypter) {
  30714. const initAutoEncrypter = (0, util_1.promisify)((callback) => {
  30715. var _a2;
  30716. return (_a2 = this.autoEncrypter) == null ? void 0 : _a2.init(callback);
  30717. });
  30718. await initAutoEncrypter();
  30719. await topologyConnect();
  30720. await options.encrypter.connectInternalClient();
  30721. } else {
  30722. await topologyConnect();
  30723. }
  30724. return this;
  30725. }
  30726. /**
  30727. * Close the client and its underlying connections
  30728. *
  30729. * @param force - Force close, emitting no events
  30730. */
  30731. async close(force = false) {
  30732. Object.defineProperty(this.s, "hasBeenClosed", {
  30733. value: true,
  30734. enumerable: true,
  30735. configurable: false,
  30736. writable: false
  30737. });
  30738. const activeSessionEnds = Array.from(this.s.activeSessions, (session) => session.endSession());
  30739. this.s.activeSessions.clear();
  30740. await Promise.all(activeSessionEnds);
  30741. if (this.topology == null) {
  30742. return;
  30743. }
  30744. const selector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.primaryPreferred);
  30745. const topologyDescription = this.topology.description;
  30746. const serverDescriptions = Array.from(topologyDescription.servers.values());
  30747. const servers = selector(topologyDescription, serverDescriptions);
  30748. if (servers.length !== 0) {
  30749. const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id);
  30750. if (endSessions.length !== 0) {
  30751. await this.db("admin").command({ endSessions }, { readPreference: read_preference_1.ReadPreference.primaryPreferred, noResponse: true }).catch(() => null);
  30752. }
  30753. }
  30754. const topology = this.topology;
  30755. this.topology = void 0;
  30756. await new Promise((resolve, reject) => {
  30757. topology.close({ force }, (error) => {
  30758. if (error)
  30759. return reject(error);
  30760. const { encrypter } = this[kOptions];
  30761. if (encrypter) {
  30762. return encrypter.close(this, force, (error2) => {
  30763. if (error2)
  30764. return reject(error2);
  30765. resolve();
  30766. });
  30767. }
  30768. resolve();
  30769. });
  30770. });
  30771. }
  30772. /**
  30773. * Create a new Db instance sharing the current socket connections.
  30774. *
  30775. * @param dbName - The name of the database we want to use. If not provided, use database name from connection string.
  30776. * @param options - Optional settings for Db construction
  30777. */
  30778. db(dbName, options) {
  30779. options = options ?? {};
  30780. if (!dbName) {
  30781. dbName = this.options.dbName;
  30782. }
  30783. const finalOptions = Object.assign({}, this[kOptions], options);
  30784. const db = new db_1.Db(this, dbName, finalOptions);
  30785. return db;
  30786. }
  30787. /**
  30788. * Connect to MongoDB using a url
  30789. *
  30790. * @remarks
  30791. * The programmatically provided options take precedence over the URI options.
  30792. *
  30793. * @see https://www.mongodb.com/docs/manual/reference/connection-string/
  30794. */
  30795. static async connect(url, options) {
  30796. const client = new this(url, options);
  30797. return client.connect();
  30798. }
  30799. /** Starts a new session on the server */
  30800. startSession(options) {
  30801. const session = new sessions_1.ClientSession(this, this.s.sessionPool, { explicit: true, ...options }, this[kOptions]);
  30802. this.s.activeSessions.add(session);
  30803. session.once("ended", () => {
  30804. this.s.activeSessions.delete(session);
  30805. });
  30806. return session;
  30807. }
  30808. async withSession(optionsOrOperation, callback) {
  30809. const options = {
  30810. // Always define an owner
  30811. owner: Symbol(),
  30812. // If it's an object inherit the options
  30813. ...typeof optionsOrOperation === "object" ? optionsOrOperation : {}
  30814. };
  30815. const withSessionCallback = typeof optionsOrOperation === "function" ? optionsOrOperation : callback;
  30816. if (withSessionCallback == null) {
  30817. throw new error_1.MongoInvalidArgumentError("Missing required callback parameter");
  30818. }
  30819. const session = this.startSession(options);
  30820. try {
  30821. await withSessionCallback(session);
  30822. } finally {
  30823. try {
  30824. await session.endSession();
  30825. } catch {
  30826. }
  30827. }
  30828. }
  30829. /**
  30830. * Create a new Change Stream, watching for new changes (insertions, updates,
  30831. * replacements, deletions, and invalidations) in this cluster. Will ignore all
  30832. * changes to system collections, as well as the local, admin, and config databases.
  30833. *
  30834. * @remarks
  30835. * watch() accepts two generic arguments for distinct use cases:
  30836. * - The first is to provide the schema that may be defined for all the data within the current cluster
  30837. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  30838. *
  30839. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  30840. * @param options - Optional settings for the command
  30841. * @typeParam TSchema - Type of the data being detected by the change stream
  30842. * @typeParam TChange - Type of the whole change stream document emitted
  30843. */
  30844. watch(pipeline = [], options = {}) {
  30845. if (!Array.isArray(pipeline)) {
  30846. options = pipeline;
  30847. pipeline = [];
  30848. }
  30849. return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options));
  30850. }
  30851. };
  30852. __name(_MongoClient, "MongoClient");
  30853. var MongoClient2 = _MongoClient;
  30854. exports2.MongoClient = MongoClient2;
  30855. }
  30856. });
  30857. // node_modules/mongodb/lib/change_stream.js
  30858. var require_change_stream = __commonJS({
  30859. "node_modules/mongodb/lib/change_stream.js"(exports2) {
  30860. "use strict";
  30861. Object.defineProperty(exports2, "__esModule", { value: true });
  30862. exports2.ChangeStream = void 0;
  30863. var collection_1 = require_collection();
  30864. var constants_1 = require_constants2();
  30865. var change_stream_cursor_1 = require_change_stream_cursor();
  30866. var db_1 = require_db();
  30867. var error_1 = require_error();
  30868. var mongo_client_1 = require_mongo_client();
  30869. var mongo_types_1 = require_mongo_types();
  30870. var utils_1 = require_utils();
  30871. var kCursorStream = Symbol("cursorStream");
  30872. var kClosed = Symbol("closed");
  30873. var kMode = Symbol("mode");
  30874. var CHANGE_STREAM_OPTIONS = [
  30875. "resumeAfter",
  30876. "startAfter",
  30877. "startAtOperationTime",
  30878. "fullDocument",
  30879. "fullDocumentBeforeChange",
  30880. "showExpandedEvents"
  30881. ];
  30882. var CHANGE_DOMAIN_TYPES = {
  30883. COLLECTION: Symbol("Collection"),
  30884. DATABASE: Symbol("Database"),
  30885. CLUSTER: Symbol("Cluster")
  30886. };
  30887. var CHANGE_STREAM_EVENTS = [constants_1.RESUME_TOKEN_CHANGED, constants_1.END, constants_1.CLOSE];
  30888. var NO_RESUME_TOKEN_ERROR = "A change stream document has been received that lacks a resume token (_id).";
  30889. var CHANGESTREAM_CLOSED_ERROR = "ChangeStream is closed";
  30890. var _ChangeStream = class _ChangeStream extends mongo_types_1.TypedEventEmitter {
  30891. /**
  30892. * @internal
  30893. *
  30894. * @param parent - The parent object that created this change stream
  30895. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents
  30896. */
  30897. constructor(parent, pipeline = [], options = {}) {
  30898. super();
  30899. this.pipeline = pipeline;
  30900. this.options = { ...options };
  30901. delete this.options.writeConcern;
  30902. if (parent instanceof collection_1.Collection) {
  30903. this.type = CHANGE_DOMAIN_TYPES.COLLECTION;
  30904. } else if (parent instanceof db_1.Db) {
  30905. this.type = CHANGE_DOMAIN_TYPES.DATABASE;
  30906. } else if (parent instanceof mongo_client_1.MongoClient) {
  30907. this.type = CHANGE_DOMAIN_TYPES.CLUSTER;
  30908. } else {
  30909. throw new error_1.MongoChangeStreamError("Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient");
  30910. }
  30911. this.parent = parent;
  30912. this.namespace = parent.s.namespace;
  30913. if (!this.options.readPreference && parent.readPreference) {
  30914. this.options.readPreference = parent.readPreference;
  30915. }
  30916. this.cursor = this._createChangeStreamCursor(options);
  30917. this[kClosed] = false;
  30918. this[kMode] = false;
  30919. this.on("newListener", (eventName) => {
  30920. if (eventName === "change" && this.cursor && this.listenerCount("change") === 0) {
  30921. this._streamEvents(this.cursor);
  30922. }
  30923. });
  30924. this.on("removeListener", (eventName) => {
  30925. var _a;
  30926. if (eventName === "change" && this.listenerCount("change") === 0 && this.cursor) {
  30927. (_a = this[kCursorStream]) == null ? void 0 : _a.removeAllListeners("data");
  30928. }
  30929. });
  30930. }
  30931. /** @internal */
  30932. get cursorStream() {
  30933. return this[kCursorStream];
  30934. }
  30935. /** The cached resume token that is used to resume after the most recently returned change. */
  30936. get resumeToken() {
  30937. var _a;
  30938. return (_a = this.cursor) == null ? void 0 : _a.resumeToken;
  30939. }
  30940. /** Check if there is any document still available in the Change Stream */
  30941. async hasNext() {
  30942. this._setIsIterator();
  30943. while (true) {
  30944. try {
  30945. const hasNext = await this.cursor.hasNext();
  30946. return hasNext;
  30947. } catch (error) {
  30948. try {
  30949. await this._processErrorIteratorMode(error);
  30950. } catch (error2) {
  30951. try {
  30952. await this.close();
  30953. } catch {
  30954. }
  30955. throw error2;
  30956. }
  30957. }
  30958. }
  30959. }
  30960. /** Get the next available document from the Change Stream. */
  30961. async next() {
  30962. this._setIsIterator();
  30963. while (true) {
  30964. try {
  30965. const change = await this.cursor.next();
  30966. const processedChange = this._processChange(change ?? null);
  30967. return processedChange;
  30968. } catch (error) {
  30969. try {
  30970. await this._processErrorIteratorMode(error);
  30971. } catch (error2) {
  30972. try {
  30973. await this.close();
  30974. } catch {
  30975. }
  30976. throw error2;
  30977. }
  30978. }
  30979. }
  30980. }
  30981. /**
  30982. * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned
  30983. */
  30984. async tryNext() {
  30985. this._setIsIterator();
  30986. while (true) {
  30987. try {
  30988. const change = await this.cursor.tryNext();
  30989. return change ?? null;
  30990. } catch (error) {
  30991. try {
  30992. await this._processErrorIteratorMode(error);
  30993. } catch (error2) {
  30994. try {
  30995. await this.close();
  30996. } catch {
  30997. }
  30998. throw error2;
  30999. }
  31000. }
  31001. }
  31002. }
  31003. async *[Symbol.asyncIterator]() {
  31004. if (this.closed) {
  31005. return;
  31006. }
  31007. try {
  31008. while (true) {
  31009. yield await this.next();
  31010. }
  31011. } finally {
  31012. try {
  31013. await this.close();
  31014. } catch {
  31015. }
  31016. }
  31017. }
  31018. /** Is the cursor closed */
  31019. get closed() {
  31020. return this[kClosed] || this.cursor.closed;
  31021. }
  31022. /** Close the Change Stream */
  31023. async close() {
  31024. this[kClosed] = true;
  31025. const cursor = this.cursor;
  31026. try {
  31027. await cursor.close();
  31028. } finally {
  31029. this._endStream();
  31030. }
  31031. }
  31032. /**
  31033. * Return a modified Readable stream including a possible transform method.
  31034. *
  31035. * NOTE: When using a Stream to process change stream events, the stream will
  31036. * NOT automatically resume in the case a resumable error is encountered.
  31037. *
  31038. * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed
  31039. */
  31040. stream(options) {
  31041. if (this.closed) {
  31042. throw new error_1.MongoChangeStreamError(CHANGESTREAM_CLOSED_ERROR);
  31043. }
  31044. this.streamOptions = options;
  31045. return this.cursor.stream(options);
  31046. }
  31047. /** @internal */
  31048. _setIsEmitter() {
  31049. if (this[kMode] === "iterator") {
  31050. throw new error_1.MongoAPIError("ChangeStream cannot be used as an EventEmitter after being used as an iterator");
  31051. }
  31052. this[kMode] = "emitter";
  31053. }
  31054. /** @internal */
  31055. _setIsIterator() {
  31056. if (this[kMode] === "emitter") {
  31057. throw new error_1.MongoAPIError("ChangeStream cannot be used as an iterator after being used as an EventEmitter");
  31058. }
  31059. this[kMode] = "iterator";
  31060. }
  31061. /**
  31062. * Create a new change stream cursor based on self's configuration
  31063. * @internal
  31064. */
  31065. _createChangeStreamCursor(options) {
  31066. const changeStreamStageOptions = (0, utils_1.filterOptions)(options, CHANGE_STREAM_OPTIONS);
  31067. if (this.type === CHANGE_DOMAIN_TYPES.CLUSTER) {
  31068. changeStreamStageOptions.allChangesForCluster = true;
  31069. }
  31070. const pipeline = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline];
  31071. const client = this.type === CHANGE_DOMAIN_TYPES.CLUSTER ? this.parent : this.type === CHANGE_DOMAIN_TYPES.DATABASE ? this.parent.client : this.type === CHANGE_DOMAIN_TYPES.COLLECTION ? this.parent.client : null;
  31072. if (client == null) {
  31073. throw new error_1.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`);
  31074. }
  31075. const changeStreamCursor = new change_stream_cursor_1.ChangeStreamCursor(client, this.namespace, pipeline, options);
  31076. for (const event of CHANGE_STREAM_EVENTS) {
  31077. changeStreamCursor.on(event, (e) => this.emit(event, e));
  31078. }
  31079. if (this.listenerCount(_ChangeStream.CHANGE) > 0) {
  31080. this._streamEvents(changeStreamCursor);
  31081. }
  31082. return changeStreamCursor;
  31083. }
  31084. /** @internal */
  31085. _closeEmitterModeWithError(error) {
  31086. this.emit(_ChangeStream.ERROR, error);
  31087. this.close().catch(() => null);
  31088. }
  31089. /** @internal */
  31090. _streamEvents(cursor) {
  31091. this._setIsEmitter();
  31092. const stream = this[kCursorStream] ?? cursor.stream();
  31093. this[kCursorStream] = stream;
  31094. stream.on("data", (change) => {
  31095. try {
  31096. const processedChange = this._processChange(change);
  31097. this.emit(_ChangeStream.CHANGE, processedChange);
  31098. } catch (error) {
  31099. this.emit(_ChangeStream.ERROR, error);
  31100. }
  31101. });
  31102. stream.on("error", (error) => this._processErrorStreamMode(error));
  31103. }
  31104. /** @internal */
  31105. _endStream() {
  31106. const cursorStream = this[kCursorStream];
  31107. if (cursorStream) {
  31108. ["data", "close", "end", "error"].forEach((event) => cursorStream.removeAllListeners(event));
  31109. cursorStream.destroy();
  31110. }
  31111. this[kCursorStream] = void 0;
  31112. }
  31113. /** @internal */
  31114. _processChange(change) {
  31115. if (this[kClosed]) {
  31116. throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR);
  31117. }
  31118. if (change == null) {
  31119. throw new error_1.MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR);
  31120. }
  31121. if (change && !change._id) {
  31122. throw new error_1.MongoChangeStreamError(NO_RESUME_TOKEN_ERROR);
  31123. }
  31124. this.cursor.cacheResumeToken(change._id);
  31125. this.options.startAtOperationTime = void 0;
  31126. return change;
  31127. }
  31128. /** @internal */
  31129. _processErrorStreamMode(changeStreamError) {
  31130. if (this[kClosed])
  31131. return;
  31132. if ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) {
  31133. this._endStream();
  31134. this.cursor.close().catch(() => null);
  31135. const topology = (0, utils_1.getTopology)(this.parent);
  31136. topology.selectServer(this.cursor.readPreference, {}, (serverSelectionError) => {
  31137. if (serverSelectionError)
  31138. return this._closeEmitterModeWithError(changeStreamError);
  31139. this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions);
  31140. });
  31141. } else {
  31142. this._closeEmitterModeWithError(changeStreamError);
  31143. }
  31144. }
  31145. /** @internal */
  31146. async _processErrorIteratorMode(changeStreamError) {
  31147. if (this[kClosed]) {
  31148. throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR);
  31149. }
  31150. if (!(0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) {
  31151. try {
  31152. await this.close();
  31153. } catch {
  31154. }
  31155. throw changeStreamError;
  31156. }
  31157. await this.cursor.close().catch(() => null);
  31158. const topology = (0, utils_1.getTopology)(this.parent);
  31159. try {
  31160. await topology.selectServerAsync(this.cursor.readPreference, {});
  31161. this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions);
  31162. } catch {
  31163. await this.close();
  31164. throw changeStreamError;
  31165. }
  31166. }
  31167. };
  31168. __name(_ChangeStream, "ChangeStream");
  31169. var ChangeStream = _ChangeStream;
  31170. ChangeStream.RESPONSE = constants_1.RESPONSE;
  31171. ChangeStream.MORE = constants_1.MORE;
  31172. ChangeStream.INIT = constants_1.INIT;
  31173. ChangeStream.CLOSE = constants_1.CLOSE;
  31174. ChangeStream.CHANGE = constants_1.CHANGE;
  31175. ChangeStream.END = constants_1.END;
  31176. ChangeStream.ERROR = constants_1.ERROR;
  31177. ChangeStream.RESUME_TOKEN_CHANGED = constants_1.RESUME_TOKEN_CHANGED;
  31178. exports2.ChangeStream = ChangeStream;
  31179. }
  31180. });
  31181. // node_modules/mongodb/lib/gridfs/download.js
  31182. var require_download = __commonJS({
  31183. "node_modules/mongodb/lib/gridfs/download.js"(exports2) {
  31184. "use strict";
  31185. Object.defineProperty(exports2, "__esModule", { value: true });
  31186. exports2.GridFSBucketReadStream = void 0;
  31187. var stream_1 = require("stream");
  31188. var error_1 = require_error();
  31189. var _GridFSBucketReadStream = class _GridFSBucketReadStream extends stream_1.Readable {
  31190. /**
  31191. * @param chunks - Handle for chunks collection
  31192. * @param files - Handle for files collection
  31193. * @param readPreference - The read preference to use
  31194. * @param filter - The filter to use to find the file document
  31195. * @internal
  31196. */
  31197. constructor(chunks, files, readPreference, filter, options) {
  31198. super();
  31199. this.s = {
  31200. bytesToTrim: 0,
  31201. bytesToSkip: 0,
  31202. bytesRead: 0,
  31203. chunks,
  31204. expected: 0,
  31205. files,
  31206. filter,
  31207. init: false,
  31208. expectedEnd: 0,
  31209. options: {
  31210. start: 0,
  31211. end: 0,
  31212. ...options
  31213. },
  31214. readPreference
  31215. };
  31216. }
  31217. /**
  31218. * Reads from the cursor and pushes to the stream.
  31219. * Private Impl, do not call directly
  31220. * @internal
  31221. */
  31222. _read() {
  31223. if (this.destroyed)
  31224. return;
  31225. waitForFile(this, () => doRead(this));
  31226. }
  31227. /**
  31228. * Sets the 0-based offset in bytes to start streaming from. Throws
  31229. * an error if this stream has entered flowing mode
  31230. * (e.g. if you've already called `on('data')`)
  31231. *
  31232. * @param start - 0-based offset in bytes to start streaming from
  31233. */
  31234. start(start = 0) {
  31235. throwIfInitialized(this);
  31236. this.s.options.start = start;
  31237. return this;
  31238. }
  31239. /**
  31240. * Sets the 0-based offset in bytes to start streaming from. Throws
  31241. * an error if this stream has entered flowing mode
  31242. * (e.g. if you've already called `on('data')`)
  31243. *
  31244. * @param end - Offset in bytes to stop reading at
  31245. */
  31246. end(end = 0) {
  31247. throwIfInitialized(this);
  31248. this.s.options.end = end;
  31249. return this;
  31250. }
  31251. /**
  31252. * Marks this stream as aborted (will never push another `data` event)
  31253. * and kills the underlying cursor. Will emit the 'end' event, and then
  31254. * the 'close' event once the cursor is successfully killed.
  31255. */
  31256. async abort() {
  31257. this.push(null);
  31258. this.destroyed = true;
  31259. if (this.s.cursor) {
  31260. try {
  31261. await this.s.cursor.close();
  31262. } finally {
  31263. this.emit(_GridFSBucketReadStream.CLOSE);
  31264. }
  31265. } else {
  31266. if (!this.s.init) {
  31267. this.emit(_GridFSBucketReadStream.CLOSE);
  31268. }
  31269. }
  31270. }
  31271. };
  31272. __name(_GridFSBucketReadStream, "GridFSBucketReadStream");
  31273. var GridFSBucketReadStream = _GridFSBucketReadStream;
  31274. GridFSBucketReadStream.ERROR = "error";
  31275. GridFSBucketReadStream.FILE = "file";
  31276. GridFSBucketReadStream.DATA = "data";
  31277. GridFSBucketReadStream.END = "end";
  31278. GridFSBucketReadStream.CLOSE = "close";
  31279. exports2.GridFSBucketReadStream = GridFSBucketReadStream;
  31280. function throwIfInitialized(stream) {
  31281. if (stream.s.init) {
  31282. throw new error_1.MongoGridFSStreamError("Options cannot be changed after the stream is initialized");
  31283. }
  31284. }
  31285. __name(throwIfInitialized, "throwIfInitialized");
  31286. function doRead(stream) {
  31287. if (stream.destroyed)
  31288. return;
  31289. if (!stream.s.cursor)
  31290. return;
  31291. if (!stream.s.file)
  31292. return;
  31293. const handleReadResult = /* @__PURE__ */ __name(({ error, doc }) => {
  31294. var _a;
  31295. if (stream.destroyed) {
  31296. return;
  31297. }
  31298. if (error) {
  31299. stream.emit(GridFSBucketReadStream.ERROR, error);
  31300. return;
  31301. }
  31302. if (!doc) {
  31303. stream.push(null);
  31304. (_a = stream.s.cursor) == null ? void 0 : _a.close().then(() => {
  31305. stream.emit(GridFSBucketReadStream.CLOSE);
  31306. }, (error2) => {
  31307. stream.emit(GridFSBucketReadStream.ERROR, error2);
  31308. });
  31309. return;
  31310. }
  31311. if (!stream.s.file)
  31312. return;
  31313. const bytesRemaining = stream.s.file.length - stream.s.bytesRead;
  31314. const expectedN = stream.s.expected++;
  31315. const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining);
  31316. if (doc.n > expectedN) {
  31317. return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}`));
  31318. }
  31319. if (doc.n < expectedN) {
  31320. return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`));
  31321. }
  31322. let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer;
  31323. if (buf.byteLength !== expectedLength) {
  31324. if (bytesRemaining <= 0) {
  31325. return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected file length ${stream.s.file.length} bytes but already read ${stream.s.bytesRead} bytes`));
  31326. }
  31327. return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}`));
  31328. }
  31329. stream.s.bytesRead += buf.byteLength;
  31330. if (buf.byteLength === 0) {
  31331. return stream.push(null);
  31332. }
  31333. let sliceStart = null;
  31334. let sliceEnd = null;
  31335. if (stream.s.bytesToSkip != null) {
  31336. sliceStart = stream.s.bytesToSkip;
  31337. stream.s.bytesToSkip = 0;
  31338. }
  31339. const atEndOfStream = expectedN === stream.s.expectedEnd - 1;
  31340. const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip;
  31341. if (atEndOfStream && stream.s.bytesToTrim != null) {
  31342. sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim;
  31343. } else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) {
  31344. sliceEnd = bytesLeftToRead;
  31345. }
  31346. if (sliceStart != null || sliceEnd != null) {
  31347. buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength);
  31348. }
  31349. stream.push(buf);
  31350. return;
  31351. }, "handleReadResult");
  31352. stream.s.cursor.next().then((doc) => handleReadResult({ error: null, doc }), (error) => handleReadResult({ error, doc: null }));
  31353. }
  31354. __name(doRead, "doRead");
  31355. function init(stream) {
  31356. const findOneOptions = {};
  31357. if (stream.s.readPreference) {
  31358. findOneOptions.readPreference = stream.s.readPreference;
  31359. }
  31360. if (stream.s.options && stream.s.options.sort) {
  31361. findOneOptions.sort = stream.s.options.sort;
  31362. }
  31363. if (stream.s.options && stream.s.options.skip) {
  31364. findOneOptions.skip = stream.s.options.skip;
  31365. }
  31366. const handleReadResult = /* @__PURE__ */ __name(({ error, doc }) => {
  31367. if (error) {
  31368. return stream.emit(GridFSBucketReadStream.ERROR, error);
  31369. }
  31370. if (!doc) {
  31371. const identifier = stream.s.filter._id ? stream.s.filter._id.toString() : stream.s.filter.filename;
  31372. const errmsg = `FileNotFound: file ${identifier} was not found`;
  31373. const err = new error_1.MongoRuntimeError(errmsg);
  31374. err.code = "ENOENT";
  31375. return stream.emit(GridFSBucketReadStream.ERROR, err);
  31376. }
  31377. if (doc.length <= 0) {
  31378. stream.push(null);
  31379. return;
  31380. }
  31381. if (stream.destroyed) {
  31382. stream.emit(GridFSBucketReadStream.CLOSE);
  31383. return;
  31384. }
  31385. try {
  31386. stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options);
  31387. } catch (error2) {
  31388. return stream.emit(GridFSBucketReadStream.ERROR, error2);
  31389. }
  31390. const filter = { files_id: doc._id };
  31391. if (stream.s.options && stream.s.options.start != null) {
  31392. const skip = Math.floor(stream.s.options.start / doc.chunkSize);
  31393. if (skip > 0) {
  31394. filter["n"] = { $gte: skip };
  31395. }
  31396. }
  31397. stream.s.cursor = stream.s.chunks.find(filter).sort({ n: 1 });
  31398. if (stream.s.readPreference) {
  31399. stream.s.cursor.withReadPreference(stream.s.readPreference);
  31400. }
  31401. stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize);
  31402. stream.s.file = doc;
  31403. try {
  31404. stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options);
  31405. } catch (error2) {
  31406. return stream.emit(GridFSBucketReadStream.ERROR, error2);
  31407. }
  31408. stream.emit(GridFSBucketReadStream.FILE, doc);
  31409. return;
  31410. }, "handleReadResult");
  31411. stream.s.files.findOne(stream.s.filter, findOneOptions).then((doc) => handleReadResult({ error: null, doc }), (error) => handleReadResult({ error, doc: null }));
  31412. }
  31413. __name(init, "init");
  31414. function waitForFile(stream, callback) {
  31415. if (stream.s.file) {
  31416. return callback();
  31417. }
  31418. if (!stream.s.init) {
  31419. init(stream);
  31420. stream.s.init = true;
  31421. }
  31422. stream.once("file", () => {
  31423. callback();
  31424. });
  31425. }
  31426. __name(waitForFile, "waitForFile");
  31427. function handleStartOption(stream, doc, options) {
  31428. if (options && options.start != null) {
  31429. if (options.start > doc.length) {
  31430. throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be more than the length of the file (${doc.length})`);
  31431. }
  31432. if (options.start < 0) {
  31433. throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`);
  31434. }
  31435. if (options.end != null && options.end < options.start) {
  31436. throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be greater than stream end (${options.end})`);
  31437. }
  31438. stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize;
  31439. stream.s.expected = Math.floor(options.start / doc.chunkSize);
  31440. return options.start - stream.s.bytesRead;
  31441. }
  31442. throw new error_1.MongoInvalidArgumentError("Start option must be defined");
  31443. }
  31444. __name(handleStartOption, "handleStartOption");
  31445. function handleEndOption(stream, doc, cursor, options) {
  31446. if (options && options.end != null) {
  31447. if (options.end > doc.length) {
  31448. throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be more than the length of the file (${doc.length})`);
  31449. }
  31450. if (options.start == null || options.start < 0) {
  31451. throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`);
  31452. }
  31453. const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0;
  31454. cursor.limit(Math.ceil(options.end / doc.chunkSize) - start);
  31455. stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize);
  31456. return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end;
  31457. }
  31458. throw new error_1.MongoInvalidArgumentError("End option must be defined");
  31459. }
  31460. __name(handleEndOption, "handleEndOption");
  31461. }
  31462. });
  31463. // node_modules/mongodb/lib/gridfs/upload.js
  31464. var require_upload = __commonJS({
  31465. "node_modules/mongodb/lib/gridfs/upload.js"(exports2) {
  31466. "use strict";
  31467. Object.defineProperty(exports2, "__esModule", { value: true });
  31468. exports2.GridFSBucketWriteStream = void 0;
  31469. var stream_1 = require("stream");
  31470. var bson_1 = require_bson2();
  31471. var error_1 = require_error();
  31472. var write_concern_1 = require_write_concern();
  31473. var _GridFSBucketWriteStream = class _GridFSBucketWriteStream extends stream_1.Writable {
  31474. /**
  31475. * @param bucket - Handle for this stream's corresponding bucket
  31476. * @param filename - The value of the 'filename' key in the files doc
  31477. * @param options - Optional settings.
  31478. * @internal
  31479. */
  31480. constructor(bucket, filename, options) {
  31481. super();
  31482. options = options ?? {};
  31483. this.bucket = bucket;
  31484. this.chunks = bucket.s._chunksCollection;
  31485. this.filename = filename;
  31486. this.files = bucket.s._filesCollection;
  31487. this.options = options;
  31488. this.writeConcern = write_concern_1.WriteConcern.fromOptions(options) || bucket.s.options.writeConcern;
  31489. this.done = false;
  31490. this.id = options.id ? options.id : new bson_1.ObjectId();
  31491. this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes;
  31492. this.bufToStore = Buffer.alloc(this.chunkSizeBytes);
  31493. this.length = 0;
  31494. this.n = 0;
  31495. this.pos = 0;
  31496. this.state = {
  31497. streamEnd: false,
  31498. outstandingRequests: 0,
  31499. errored: false,
  31500. aborted: false
  31501. };
  31502. if (!this.bucket.s.calledOpenUploadStream) {
  31503. this.bucket.s.calledOpenUploadStream = true;
  31504. checkIndexes(this).then(() => {
  31505. this.bucket.s.checkedIndexes = true;
  31506. this.bucket.emit("index");
  31507. }, () => null);
  31508. }
  31509. }
  31510. write(chunk, encodingOrCallback, callback) {
  31511. const encoding = typeof encodingOrCallback === "function" ? void 0 : encodingOrCallback;
  31512. callback = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
  31513. return waitForIndexes(this, () => doWrite(this, chunk, encoding, callback));
  31514. }
  31515. /**
  31516. * Places this write stream into an aborted state (all future writes fail)
  31517. * and deletes all chunks that have already been written.
  31518. */
  31519. async abort() {
  31520. if (this.state.streamEnd) {
  31521. throw new error_1.MongoAPIError("Cannot abort a stream that has already completed");
  31522. }
  31523. if (this.state.aborted) {
  31524. throw new error_1.MongoAPIError("Cannot call abort() on a stream twice");
  31525. }
  31526. this.state.aborted = true;
  31527. await this.chunks.deleteMany({ files_id: this.id });
  31528. }
  31529. end(chunkOrCallback, encodingOrCallback, callback) {
  31530. const chunk = typeof chunkOrCallback === "function" ? void 0 : chunkOrCallback;
  31531. const encoding = typeof encodingOrCallback === "function" ? void 0 : encodingOrCallback;
  31532. callback = typeof chunkOrCallback === "function" ? chunkOrCallback : typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
  31533. if (this.state.streamEnd || checkAborted(this, callback))
  31534. return this;
  31535. this.state.streamEnd = true;
  31536. if (callback) {
  31537. this.once(_GridFSBucketWriteStream.FINISH, (result) => {
  31538. if (callback)
  31539. callback(void 0, result);
  31540. });
  31541. }
  31542. if (!chunk) {
  31543. waitForIndexes(this, () => !!writeRemnant(this));
  31544. return this;
  31545. }
  31546. this.write(chunk, encoding, () => {
  31547. writeRemnant(this);
  31548. });
  31549. return this;
  31550. }
  31551. };
  31552. __name(_GridFSBucketWriteStream, "GridFSBucketWriteStream");
  31553. var GridFSBucketWriteStream = _GridFSBucketWriteStream;
  31554. GridFSBucketWriteStream.CLOSE = "close";
  31555. GridFSBucketWriteStream.ERROR = "error";
  31556. GridFSBucketWriteStream.FINISH = "finish";
  31557. exports2.GridFSBucketWriteStream = GridFSBucketWriteStream;
  31558. function __handleError(stream, error, callback) {
  31559. if (stream.state.errored) {
  31560. return;
  31561. }
  31562. stream.state.errored = true;
  31563. if (callback) {
  31564. return callback(error);
  31565. }
  31566. stream.emit(GridFSBucketWriteStream.ERROR, error);
  31567. }
  31568. __name(__handleError, "__handleError");
  31569. function createChunkDoc(filesId, n, data) {
  31570. return {
  31571. _id: new bson_1.ObjectId(),
  31572. files_id: filesId,
  31573. n,
  31574. data
  31575. };
  31576. }
  31577. __name(createChunkDoc, "createChunkDoc");
  31578. async function checkChunksIndex(stream) {
  31579. const index = { files_id: 1, n: 1 };
  31580. let indexes;
  31581. try {
  31582. indexes = await stream.chunks.listIndexes().toArray();
  31583. } catch (error) {
  31584. if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
  31585. indexes = [];
  31586. } else {
  31587. throw error;
  31588. }
  31589. }
  31590. const hasChunksIndex = !!indexes.find((index2) => {
  31591. const keys = Object.keys(index2.key);
  31592. if (keys.length === 2 && index2.key.files_id === 1 && index2.key.n === 1) {
  31593. return true;
  31594. }
  31595. return false;
  31596. });
  31597. if (!hasChunksIndex) {
  31598. await stream.chunks.createIndex(index, {
  31599. ...stream.writeConcern,
  31600. background: true,
  31601. unique: true
  31602. });
  31603. }
  31604. }
  31605. __name(checkChunksIndex, "checkChunksIndex");
  31606. function checkDone(stream, callback) {
  31607. if (stream.done)
  31608. return true;
  31609. if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) {
  31610. stream.done = true;
  31611. const filesDoc = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.contentType, stream.options.aliases, stream.options.metadata);
  31612. if (checkAborted(stream, callback)) {
  31613. return false;
  31614. }
  31615. stream.files.insertOne(filesDoc, { writeConcern: stream.writeConcern }).then(() => {
  31616. stream.emit(GridFSBucketWriteStream.FINISH, filesDoc);
  31617. stream.emit(GridFSBucketWriteStream.CLOSE);
  31618. }, (error) => {
  31619. return __handleError(stream, error, callback);
  31620. });
  31621. return true;
  31622. }
  31623. return false;
  31624. }
  31625. __name(checkDone, "checkDone");
  31626. async function checkIndexes(stream) {
  31627. const doc = await stream.files.findOne({}, { projection: { _id: 1 } });
  31628. if (doc != null) {
  31629. return;
  31630. }
  31631. const index = { filename: 1, uploadDate: 1 };
  31632. let indexes;
  31633. try {
  31634. indexes = await stream.files.listIndexes().toArray();
  31635. } catch (error) {
  31636. if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) {
  31637. indexes = [];
  31638. } else {
  31639. throw error;
  31640. }
  31641. }
  31642. const hasFileIndex = !!indexes.find((index2) => {
  31643. const keys = Object.keys(index2.key);
  31644. if (keys.length === 2 && index2.key.filename === 1 && index2.key.uploadDate === 1) {
  31645. return true;
  31646. }
  31647. return false;
  31648. });
  31649. if (!hasFileIndex) {
  31650. await stream.files.createIndex(index, { background: false });
  31651. }
  31652. await checkChunksIndex(stream);
  31653. }
  31654. __name(checkIndexes, "checkIndexes");
  31655. function createFilesDoc(_id, length, chunkSize, filename, contentType, aliases, metadata) {
  31656. const ret = {
  31657. _id,
  31658. length,
  31659. chunkSize,
  31660. uploadDate: /* @__PURE__ */ new Date(),
  31661. filename
  31662. };
  31663. if (contentType) {
  31664. ret.contentType = contentType;
  31665. }
  31666. if (aliases) {
  31667. ret.aliases = aliases;
  31668. }
  31669. if (metadata) {
  31670. ret.metadata = metadata;
  31671. }
  31672. return ret;
  31673. }
  31674. __name(createFilesDoc, "createFilesDoc");
  31675. function doWrite(stream, chunk, encoding, callback) {
  31676. if (checkAborted(stream, callback)) {
  31677. return false;
  31678. }
  31679. const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
  31680. stream.length += inputBuf.length;
  31681. if (stream.pos + inputBuf.length < stream.chunkSizeBytes) {
  31682. inputBuf.copy(stream.bufToStore, stream.pos);
  31683. stream.pos += inputBuf.length;
  31684. callback && callback();
  31685. return true;
  31686. }
  31687. let inputBufRemaining = inputBuf.length;
  31688. let spaceRemaining = stream.chunkSizeBytes - stream.pos;
  31689. let numToCopy = Math.min(spaceRemaining, inputBuf.length);
  31690. let outstandingRequests = 0;
  31691. while (inputBufRemaining > 0) {
  31692. const inputBufPos = inputBuf.length - inputBufRemaining;
  31693. inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy);
  31694. stream.pos += numToCopy;
  31695. spaceRemaining -= numToCopy;
  31696. let doc;
  31697. if (spaceRemaining === 0) {
  31698. doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore));
  31699. ++stream.state.outstandingRequests;
  31700. ++outstandingRequests;
  31701. if (checkAborted(stream, callback)) {
  31702. return false;
  31703. }
  31704. stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then(() => {
  31705. --stream.state.outstandingRequests;
  31706. --outstandingRequests;
  31707. if (!outstandingRequests) {
  31708. stream.emit("drain", doc);
  31709. callback && callback();
  31710. checkDone(stream);
  31711. }
  31712. }, (error) => {
  31713. return __handleError(stream, error);
  31714. });
  31715. spaceRemaining = stream.chunkSizeBytes;
  31716. stream.pos = 0;
  31717. ++stream.n;
  31718. }
  31719. inputBufRemaining -= numToCopy;
  31720. numToCopy = Math.min(spaceRemaining, inputBufRemaining);
  31721. }
  31722. return false;
  31723. }
  31724. __name(doWrite, "doWrite");
  31725. function waitForIndexes(stream, callback) {
  31726. if (stream.bucket.s.checkedIndexes) {
  31727. return callback(false);
  31728. }
  31729. stream.bucket.once("index", () => {
  31730. callback(true);
  31731. });
  31732. return true;
  31733. }
  31734. __name(waitForIndexes, "waitForIndexes");
  31735. function writeRemnant(stream, callback) {
  31736. if (stream.pos === 0) {
  31737. return checkDone(stream, callback);
  31738. }
  31739. ++stream.state.outstandingRequests;
  31740. const remnant = Buffer.alloc(stream.pos);
  31741. stream.bufToStore.copy(remnant, 0, 0, stream.pos);
  31742. const doc = createChunkDoc(stream.id, stream.n, remnant);
  31743. if (checkAborted(stream, callback)) {
  31744. return false;
  31745. }
  31746. stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then(() => {
  31747. --stream.state.outstandingRequests;
  31748. checkDone(stream);
  31749. }, (error) => {
  31750. return __handleError(stream, error);
  31751. });
  31752. return true;
  31753. }
  31754. __name(writeRemnant, "writeRemnant");
  31755. function checkAborted(stream, callback) {
  31756. if (stream.state.aborted) {
  31757. if (typeof callback === "function") {
  31758. callback(new error_1.MongoAPIError("Stream has been aborted"));
  31759. }
  31760. return true;
  31761. }
  31762. return false;
  31763. }
  31764. __name(checkAborted, "checkAborted");
  31765. }
  31766. });
  31767. // node_modules/mongodb/lib/gridfs/index.js
  31768. var require_gridfs = __commonJS({
  31769. "node_modules/mongodb/lib/gridfs/index.js"(exports2) {
  31770. "use strict";
  31771. Object.defineProperty(exports2, "__esModule", { value: true });
  31772. exports2.GridFSBucket = void 0;
  31773. var error_1 = require_error();
  31774. var mongo_types_1 = require_mongo_types();
  31775. var write_concern_1 = require_write_concern();
  31776. var download_1 = require_download();
  31777. var upload_1 = require_upload();
  31778. var DEFAULT_GRIDFS_BUCKET_OPTIONS = {
  31779. bucketName: "fs",
  31780. chunkSizeBytes: 255 * 1024
  31781. };
  31782. var _GridFSBucket = class _GridFSBucket extends mongo_types_1.TypedEventEmitter {
  31783. constructor(db, options) {
  31784. super();
  31785. this.setMaxListeners(0);
  31786. const privateOptions = {
  31787. ...DEFAULT_GRIDFS_BUCKET_OPTIONS,
  31788. ...options,
  31789. writeConcern: write_concern_1.WriteConcern.fromOptions(options)
  31790. };
  31791. this.s = {
  31792. db,
  31793. options: privateOptions,
  31794. _chunksCollection: db.collection(privateOptions.bucketName + ".chunks"),
  31795. _filesCollection: db.collection(privateOptions.bucketName + ".files"),
  31796. checkedIndexes: false,
  31797. calledOpenUploadStream: false
  31798. };
  31799. }
  31800. /**
  31801. * Returns a writable stream (GridFSBucketWriteStream) for writing
  31802. * buffers to GridFS. The stream's 'id' property contains the resulting
  31803. * file's id.
  31804. *
  31805. * @param filename - The value of the 'filename' key in the files doc
  31806. * @param options - Optional settings.
  31807. */
  31808. openUploadStream(filename, options) {
  31809. return new upload_1.GridFSBucketWriteStream(this, filename, options);
  31810. }
  31811. /**
  31812. * Returns a writable stream (GridFSBucketWriteStream) for writing
  31813. * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting
  31814. * file's id.
  31815. */
  31816. openUploadStreamWithId(id, filename, options) {
  31817. return new upload_1.GridFSBucketWriteStream(this, filename, { ...options, id });
  31818. }
  31819. /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */
  31820. openDownloadStream(id, options) {
  31821. return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { _id: id }, options);
  31822. }
  31823. /**
  31824. * Deletes a file with the given id
  31825. *
  31826. * @param id - The id of the file doc
  31827. */
  31828. async delete(id) {
  31829. const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id });
  31830. await this.s._chunksCollection.deleteMany({ files_id: id });
  31831. if (deletedCount === 0) {
  31832. throw new error_1.MongoRuntimeError(`File not found for id ${id}`);
  31833. }
  31834. }
  31835. /** Convenience wrapper around find on the files collection */
  31836. find(filter = {}, options = {}) {
  31837. return this.s._filesCollection.find(filter, options);
  31838. }
  31839. /**
  31840. * Returns a readable stream (GridFSBucketReadStream) for streaming the
  31841. * file with the given name from GridFS. If there are multiple files with
  31842. * the same name, this will stream the most recent file with the given name
  31843. * (as determined by the `uploadDate` field). You can set the `revision`
  31844. * option to change this behavior.
  31845. */
  31846. openDownloadStreamByName(filename, options) {
  31847. let sort = { uploadDate: -1 };
  31848. let skip = void 0;
  31849. if (options && options.revision != null) {
  31850. if (options.revision >= 0) {
  31851. sort = { uploadDate: 1 };
  31852. skip = options.revision;
  31853. } else {
  31854. skip = -options.revision - 1;
  31855. }
  31856. }
  31857. return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { filename }, { ...options, sort, skip });
  31858. }
  31859. /**
  31860. * Renames the file with the given _id to the given string
  31861. *
  31862. * @param id - the id of the file to rename
  31863. * @param filename - new name for the file
  31864. */
  31865. async rename(id, filename) {
  31866. const filter = { _id: id };
  31867. const update = { $set: { filename } };
  31868. const { matchedCount } = await this.s._filesCollection.updateOne(filter, update);
  31869. if (matchedCount === 0) {
  31870. throw new error_1.MongoRuntimeError(`File with id ${id} not found`);
  31871. }
  31872. }
  31873. /** Removes this bucket's files collection, followed by its chunks collection. */
  31874. async drop() {
  31875. await this.s._filesCollection.drop();
  31876. await this.s._chunksCollection.drop();
  31877. }
  31878. };
  31879. __name(_GridFSBucket, "GridFSBucket");
  31880. var GridFSBucket = _GridFSBucket;
  31881. GridFSBucket.INDEX = "index";
  31882. exports2.GridFSBucket = GridFSBucket;
  31883. }
  31884. });
  31885. // node_modules/mongodb/lib/index.js
  31886. var require_lib3 = __commonJS({
  31887. "node_modules/mongodb/lib/index.js"(exports2) {
  31888. "use strict";
  31889. Object.defineProperty(exports2, "__esModule", { value: true });
  31890. exports2.AbstractCursor = exports2.MongoWriteConcernError = exports2.MongoUnexpectedServerResponseError = exports2.MongoTransactionError = exports2.MongoTopologyClosedError = exports2.MongoTailableCursorError = exports2.MongoSystemError = exports2.MongoServerSelectionError = exports2.MongoServerError = exports2.MongoServerClosedError = exports2.MongoRuntimeError = exports2.MongoParseError = exports2.MongoNotConnectedError = exports2.MongoNetworkTimeoutError = exports2.MongoNetworkError = exports2.MongoMissingDependencyError = exports2.MongoMissingCredentialsError = exports2.MongoKerberosError = exports2.MongoInvalidArgumentError = exports2.MongoGridFSStreamError = exports2.MongoGridFSChunkError = exports2.MongoExpiredSessionError = exports2.MongoError = exports2.MongoDriverError = exports2.MongoDecompressionError = exports2.MongoCursorInUseError = exports2.MongoCursorExhaustedError = exports2.MongoCompatibilityError = exports2.MongoChangeStreamError = exports2.MongoBatchReExecutionError = exports2.MongoAzureError = exports2.MongoAWSError = exports2.MongoAPIError = exports2.ChangeStreamCursor = exports2.MongoBulkWriteError = exports2.Timestamp = exports2.ObjectId = exports2.MinKey = exports2.MaxKey = exports2.Long = exports2.Int32 = exports2.Double = exports2.Decimal128 = exports2.DBRef = exports2.Code = exports2.BSONType = exports2.BSONSymbol = exports2.BSONRegExp = exports2.Binary = exports2.BSON = void 0;
  31891. exports2.ServerClosedEvent = exports2.ConnectionReadyEvent = exports2.ConnectionPoolReadyEvent = exports2.ConnectionPoolMonitoringEvent = exports2.ConnectionPoolCreatedEvent = exports2.ConnectionPoolClosedEvent = exports2.ConnectionPoolClearedEvent = exports2.ConnectionCreatedEvent = exports2.ConnectionClosedEvent = exports2.ConnectionCheckOutStartedEvent = exports2.ConnectionCheckOutFailedEvent = exports2.ConnectionCheckedOutEvent = exports2.ConnectionCheckedInEvent = exports2.CommandSucceededEvent = exports2.CommandStartedEvent = exports2.CommandFailedEvent = exports2.WriteConcern = exports2.ReadPreference = exports2.ReadConcern = exports2.TopologyType = exports2.ServerType = exports2.ReadPreferenceMode = exports2.ReadConcernLevel = exports2.ProfilingLevel = exports2.ReturnDocument = exports2.ServerApiVersion = exports2.ExplainVerbosity = exports2.MongoErrorLabel = exports2.AutoEncryptionLoggerLevel = exports2.CURSOR_FLAGS = exports2.Compressor = exports2.AuthMechanism = exports2.GSSAPICanonicalizationValue = exports2.BatchType = exports2.UnorderedBulkOperation = exports2.OrderedBulkOperation = exports2.MongoClient = exports2.ListIndexesCursor = exports2.ListCollectionsCursor = exports2.GridFSBucketWriteStream = exports2.GridFSBucketReadStream = exports2.GridFSBucket = exports2.FindCursor = exports2.Db = exports2.Collection = exports2.ClientSession = exports2.ChangeStream = exports2.CancellationToken = exports2.AggregationCursor = exports2.Admin = void 0;
  31892. exports2.SrvPollingEvent = exports2.TopologyOpeningEvent = exports2.TopologyDescriptionChangedEvent = exports2.TopologyClosedEvent = exports2.ServerOpeningEvent = exports2.ServerHeartbeatSucceededEvent = exports2.ServerHeartbeatStartedEvent = exports2.ServerHeartbeatFailedEvent = exports2.ServerDescriptionChangedEvent = void 0;
  31893. var admin_1 = require_admin();
  31894. Object.defineProperty(exports2, "Admin", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31895. return admin_1.Admin;
  31896. }, "get") });
  31897. var ordered_1 = require_ordered();
  31898. Object.defineProperty(exports2, "OrderedBulkOperation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31899. return ordered_1.OrderedBulkOperation;
  31900. }, "get") });
  31901. var unordered_1 = require_unordered();
  31902. Object.defineProperty(exports2, "UnorderedBulkOperation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31903. return unordered_1.UnorderedBulkOperation;
  31904. }, "get") });
  31905. var change_stream_1 = require_change_stream();
  31906. Object.defineProperty(exports2, "ChangeStream", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31907. return change_stream_1.ChangeStream;
  31908. }, "get") });
  31909. var collection_1 = require_collection();
  31910. Object.defineProperty(exports2, "Collection", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31911. return collection_1.Collection;
  31912. }, "get") });
  31913. var abstract_cursor_1 = require_abstract_cursor();
  31914. Object.defineProperty(exports2, "AbstractCursor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31915. return abstract_cursor_1.AbstractCursor;
  31916. }, "get") });
  31917. var aggregation_cursor_1 = require_aggregation_cursor();
  31918. Object.defineProperty(exports2, "AggregationCursor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31919. return aggregation_cursor_1.AggregationCursor;
  31920. }, "get") });
  31921. var find_cursor_1 = require_find_cursor();
  31922. Object.defineProperty(exports2, "FindCursor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31923. return find_cursor_1.FindCursor;
  31924. }, "get") });
  31925. var list_collections_cursor_1 = require_list_collections_cursor();
  31926. Object.defineProperty(exports2, "ListCollectionsCursor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31927. return list_collections_cursor_1.ListCollectionsCursor;
  31928. }, "get") });
  31929. var list_indexes_cursor_1 = require_list_indexes_cursor();
  31930. Object.defineProperty(exports2, "ListIndexesCursor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31931. return list_indexes_cursor_1.ListIndexesCursor;
  31932. }, "get") });
  31933. var db_1 = require_db();
  31934. Object.defineProperty(exports2, "Db", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31935. return db_1.Db;
  31936. }, "get") });
  31937. var gridfs_1 = require_gridfs();
  31938. Object.defineProperty(exports2, "GridFSBucket", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31939. return gridfs_1.GridFSBucket;
  31940. }, "get") });
  31941. var download_1 = require_download();
  31942. Object.defineProperty(exports2, "GridFSBucketReadStream", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31943. return download_1.GridFSBucketReadStream;
  31944. }, "get") });
  31945. var upload_1 = require_upload();
  31946. Object.defineProperty(exports2, "GridFSBucketWriteStream", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31947. return upload_1.GridFSBucketWriteStream;
  31948. }, "get") });
  31949. var mongo_client_1 = require_mongo_client();
  31950. Object.defineProperty(exports2, "MongoClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31951. return mongo_client_1.MongoClient;
  31952. }, "get") });
  31953. var mongo_types_1 = require_mongo_types();
  31954. Object.defineProperty(exports2, "CancellationToken", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31955. return mongo_types_1.CancellationToken;
  31956. }, "get") });
  31957. var sessions_1 = require_sessions();
  31958. Object.defineProperty(exports2, "ClientSession", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31959. return sessions_1.ClientSession;
  31960. }, "get") });
  31961. var bson_1 = require_bson2();
  31962. Object.defineProperty(exports2, "BSON", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31963. return bson_1.BSON;
  31964. }, "get") });
  31965. var bson_2 = require_bson2();
  31966. Object.defineProperty(exports2, "Binary", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31967. return bson_2.Binary;
  31968. }, "get") });
  31969. Object.defineProperty(exports2, "BSONRegExp", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31970. return bson_2.BSONRegExp;
  31971. }, "get") });
  31972. Object.defineProperty(exports2, "BSONSymbol", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31973. return bson_2.BSONSymbol;
  31974. }, "get") });
  31975. Object.defineProperty(exports2, "BSONType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31976. return bson_2.BSONType;
  31977. }, "get") });
  31978. Object.defineProperty(exports2, "Code", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31979. return bson_2.Code;
  31980. }, "get") });
  31981. Object.defineProperty(exports2, "DBRef", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31982. return bson_2.DBRef;
  31983. }, "get") });
  31984. Object.defineProperty(exports2, "Decimal128", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31985. return bson_2.Decimal128;
  31986. }, "get") });
  31987. Object.defineProperty(exports2, "Double", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31988. return bson_2.Double;
  31989. }, "get") });
  31990. Object.defineProperty(exports2, "Int32", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31991. return bson_2.Int32;
  31992. }, "get") });
  31993. Object.defineProperty(exports2, "Long", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31994. return bson_2.Long;
  31995. }, "get") });
  31996. Object.defineProperty(exports2, "MaxKey", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  31997. return bson_2.MaxKey;
  31998. }, "get") });
  31999. Object.defineProperty(exports2, "MinKey", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32000. return bson_2.MinKey;
  32001. }, "get") });
  32002. Object.defineProperty(exports2, "ObjectId", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32003. return bson_2.ObjectId;
  32004. }, "get") });
  32005. Object.defineProperty(exports2, "Timestamp", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32006. return bson_2.Timestamp;
  32007. }, "get") });
  32008. var common_1 = require_common2();
  32009. Object.defineProperty(exports2, "MongoBulkWriteError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32010. return common_1.MongoBulkWriteError;
  32011. }, "get") });
  32012. var change_stream_cursor_1 = require_change_stream_cursor();
  32013. Object.defineProperty(exports2, "ChangeStreamCursor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32014. return change_stream_cursor_1.ChangeStreamCursor;
  32015. }, "get") });
  32016. var error_1 = require_error();
  32017. Object.defineProperty(exports2, "MongoAPIError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32018. return error_1.MongoAPIError;
  32019. }, "get") });
  32020. Object.defineProperty(exports2, "MongoAWSError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32021. return error_1.MongoAWSError;
  32022. }, "get") });
  32023. Object.defineProperty(exports2, "MongoAzureError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32024. return error_1.MongoAzureError;
  32025. }, "get") });
  32026. Object.defineProperty(exports2, "MongoBatchReExecutionError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32027. return error_1.MongoBatchReExecutionError;
  32028. }, "get") });
  32029. Object.defineProperty(exports2, "MongoChangeStreamError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32030. return error_1.MongoChangeStreamError;
  32031. }, "get") });
  32032. Object.defineProperty(exports2, "MongoCompatibilityError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32033. return error_1.MongoCompatibilityError;
  32034. }, "get") });
  32035. Object.defineProperty(exports2, "MongoCursorExhaustedError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32036. return error_1.MongoCursorExhaustedError;
  32037. }, "get") });
  32038. Object.defineProperty(exports2, "MongoCursorInUseError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32039. return error_1.MongoCursorInUseError;
  32040. }, "get") });
  32041. Object.defineProperty(exports2, "MongoDecompressionError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32042. return error_1.MongoDecompressionError;
  32043. }, "get") });
  32044. Object.defineProperty(exports2, "MongoDriverError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32045. return error_1.MongoDriverError;
  32046. }, "get") });
  32047. Object.defineProperty(exports2, "MongoError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32048. return error_1.MongoError;
  32049. }, "get") });
  32050. Object.defineProperty(exports2, "MongoExpiredSessionError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32051. return error_1.MongoExpiredSessionError;
  32052. }, "get") });
  32053. Object.defineProperty(exports2, "MongoGridFSChunkError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32054. return error_1.MongoGridFSChunkError;
  32055. }, "get") });
  32056. Object.defineProperty(exports2, "MongoGridFSStreamError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32057. return error_1.MongoGridFSStreamError;
  32058. }, "get") });
  32059. Object.defineProperty(exports2, "MongoInvalidArgumentError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32060. return error_1.MongoInvalidArgumentError;
  32061. }, "get") });
  32062. Object.defineProperty(exports2, "MongoKerberosError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32063. return error_1.MongoKerberosError;
  32064. }, "get") });
  32065. Object.defineProperty(exports2, "MongoMissingCredentialsError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32066. return error_1.MongoMissingCredentialsError;
  32067. }, "get") });
  32068. Object.defineProperty(exports2, "MongoMissingDependencyError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32069. return error_1.MongoMissingDependencyError;
  32070. }, "get") });
  32071. Object.defineProperty(exports2, "MongoNetworkError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32072. return error_1.MongoNetworkError;
  32073. }, "get") });
  32074. Object.defineProperty(exports2, "MongoNetworkTimeoutError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32075. return error_1.MongoNetworkTimeoutError;
  32076. }, "get") });
  32077. Object.defineProperty(exports2, "MongoNotConnectedError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32078. return error_1.MongoNotConnectedError;
  32079. }, "get") });
  32080. Object.defineProperty(exports2, "MongoParseError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32081. return error_1.MongoParseError;
  32082. }, "get") });
  32083. Object.defineProperty(exports2, "MongoRuntimeError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32084. return error_1.MongoRuntimeError;
  32085. }, "get") });
  32086. Object.defineProperty(exports2, "MongoServerClosedError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32087. return error_1.MongoServerClosedError;
  32088. }, "get") });
  32089. Object.defineProperty(exports2, "MongoServerError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32090. return error_1.MongoServerError;
  32091. }, "get") });
  32092. Object.defineProperty(exports2, "MongoServerSelectionError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32093. return error_1.MongoServerSelectionError;
  32094. }, "get") });
  32095. Object.defineProperty(exports2, "MongoSystemError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32096. return error_1.MongoSystemError;
  32097. }, "get") });
  32098. Object.defineProperty(exports2, "MongoTailableCursorError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32099. return error_1.MongoTailableCursorError;
  32100. }, "get") });
  32101. Object.defineProperty(exports2, "MongoTopologyClosedError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32102. return error_1.MongoTopologyClosedError;
  32103. }, "get") });
  32104. Object.defineProperty(exports2, "MongoTransactionError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32105. return error_1.MongoTransactionError;
  32106. }, "get") });
  32107. Object.defineProperty(exports2, "MongoUnexpectedServerResponseError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32108. return error_1.MongoUnexpectedServerResponseError;
  32109. }, "get") });
  32110. Object.defineProperty(exports2, "MongoWriteConcernError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32111. return error_1.MongoWriteConcernError;
  32112. }, "get") });
  32113. var common_2 = require_common2();
  32114. Object.defineProperty(exports2, "BatchType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32115. return common_2.BatchType;
  32116. }, "get") });
  32117. var gssapi_1 = require_gssapi();
  32118. Object.defineProperty(exports2, "GSSAPICanonicalizationValue", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32119. return gssapi_1.GSSAPICanonicalizationValue;
  32120. }, "get") });
  32121. var providers_1 = require_providers();
  32122. Object.defineProperty(exports2, "AuthMechanism", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32123. return providers_1.AuthMechanism;
  32124. }, "get") });
  32125. var compression_1 = require_compression();
  32126. Object.defineProperty(exports2, "Compressor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32127. return compression_1.Compressor;
  32128. }, "get") });
  32129. var abstract_cursor_2 = require_abstract_cursor();
  32130. Object.defineProperty(exports2, "CURSOR_FLAGS", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32131. return abstract_cursor_2.CURSOR_FLAGS;
  32132. }, "get") });
  32133. var deps_1 = require_deps();
  32134. Object.defineProperty(exports2, "AutoEncryptionLoggerLevel", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32135. return deps_1.AutoEncryptionLoggerLevel;
  32136. }, "get") });
  32137. var error_2 = require_error();
  32138. Object.defineProperty(exports2, "MongoErrorLabel", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32139. return error_2.MongoErrorLabel;
  32140. }, "get") });
  32141. var explain_1 = require_explain();
  32142. Object.defineProperty(exports2, "ExplainVerbosity", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32143. return explain_1.ExplainVerbosity;
  32144. }, "get") });
  32145. var mongo_client_2 = require_mongo_client();
  32146. Object.defineProperty(exports2, "ServerApiVersion", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32147. return mongo_client_2.ServerApiVersion;
  32148. }, "get") });
  32149. var find_and_modify_1 = require_find_and_modify();
  32150. Object.defineProperty(exports2, "ReturnDocument", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32151. return find_and_modify_1.ReturnDocument;
  32152. }, "get") });
  32153. var set_profiling_level_1 = require_set_profiling_level();
  32154. Object.defineProperty(exports2, "ProfilingLevel", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32155. return set_profiling_level_1.ProfilingLevel;
  32156. }, "get") });
  32157. var read_concern_1 = require_read_concern();
  32158. Object.defineProperty(exports2, "ReadConcernLevel", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32159. return read_concern_1.ReadConcernLevel;
  32160. }, "get") });
  32161. var read_preference_1 = require_read_preference();
  32162. Object.defineProperty(exports2, "ReadPreferenceMode", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32163. return read_preference_1.ReadPreferenceMode;
  32164. }, "get") });
  32165. var common_3 = require_common();
  32166. Object.defineProperty(exports2, "ServerType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32167. return common_3.ServerType;
  32168. }, "get") });
  32169. Object.defineProperty(exports2, "TopologyType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32170. return common_3.TopologyType;
  32171. }, "get") });
  32172. var read_concern_2 = require_read_concern();
  32173. Object.defineProperty(exports2, "ReadConcern", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32174. return read_concern_2.ReadConcern;
  32175. }, "get") });
  32176. var read_preference_2 = require_read_preference();
  32177. Object.defineProperty(exports2, "ReadPreference", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32178. return read_preference_2.ReadPreference;
  32179. }, "get") });
  32180. var write_concern_1 = require_write_concern();
  32181. Object.defineProperty(exports2, "WriteConcern", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32182. return write_concern_1.WriteConcern;
  32183. }, "get") });
  32184. var command_monitoring_events_1 = require_command_monitoring_events();
  32185. Object.defineProperty(exports2, "CommandFailedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32186. return command_monitoring_events_1.CommandFailedEvent;
  32187. }, "get") });
  32188. Object.defineProperty(exports2, "CommandStartedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32189. return command_monitoring_events_1.CommandStartedEvent;
  32190. }, "get") });
  32191. Object.defineProperty(exports2, "CommandSucceededEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32192. return command_monitoring_events_1.CommandSucceededEvent;
  32193. }, "get") });
  32194. var connection_pool_events_1 = require_connection_pool_events();
  32195. Object.defineProperty(exports2, "ConnectionCheckedInEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32196. return connection_pool_events_1.ConnectionCheckedInEvent;
  32197. }, "get") });
  32198. Object.defineProperty(exports2, "ConnectionCheckedOutEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32199. return connection_pool_events_1.ConnectionCheckedOutEvent;
  32200. }, "get") });
  32201. Object.defineProperty(exports2, "ConnectionCheckOutFailedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32202. return connection_pool_events_1.ConnectionCheckOutFailedEvent;
  32203. }, "get") });
  32204. Object.defineProperty(exports2, "ConnectionCheckOutStartedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32205. return connection_pool_events_1.ConnectionCheckOutStartedEvent;
  32206. }, "get") });
  32207. Object.defineProperty(exports2, "ConnectionClosedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32208. return connection_pool_events_1.ConnectionClosedEvent;
  32209. }, "get") });
  32210. Object.defineProperty(exports2, "ConnectionCreatedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32211. return connection_pool_events_1.ConnectionCreatedEvent;
  32212. }, "get") });
  32213. Object.defineProperty(exports2, "ConnectionPoolClearedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32214. return connection_pool_events_1.ConnectionPoolClearedEvent;
  32215. }, "get") });
  32216. Object.defineProperty(exports2, "ConnectionPoolClosedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32217. return connection_pool_events_1.ConnectionPoolClosedEvent;
  32218. }, "get") });
  32219. Object.defineProperty(exports2, "ConnectionPoolCreatedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32220. return connection_pool_events_1.ConnectionPoolCreatedEvent;
  32221. }, "get") });
  32222. Object.defineProperty(exports2, "ConnectionPoolMonitoringEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32223. return connection_pool_events_1.ConnectionPoolMonitoringEvent;
  32224. }, "get") });
  32225. Object.defineProperty(exports2, "ConnectionPoolReadyEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32226. return connection_pool_events_1.ConnectionPoolReadyEvent;
  32227. }, "get") });
  32228. Object.defineProperty(exports2, "ConnectionReadyEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32229. return connection_pool_events_1.ConnectionReadyEvent;
  32230. }, "get") });
  32231. var events_1 = require_events();
  32232. Object.defineProperty(exports2, "ServerClosedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32233. return events_1.ServerClosedEvent;
  32234. }, "get") });
  32235. Object.defineProperty(exports2, "ServerDescriptionChangedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32236. return events_1.ServerDescriptionChangedEvent;
  32237. }, "get") });
  32238. Object.defineProperty(exports2, "ServerHeartbeatFailedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32239. return events_1.ServerHeartbeatFailedEvent;
  32240. }, "get") });
  32241. Object.defineProperty(exports2, "ServerHeartbeatStartedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32242. return events_1.ServerHeartbeatStartedEvent;
  32243. }, "get") });
  32244. Object.defineProperty(exports2, "ServerHeartbeatSucceededEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32245. return events_1.ServerHeartbeatSucceededEvent;
  32246. }, "get") });
  32247. Object.defineProperty(exports2, "ServerOpeningEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32248. return events_1.ServerOpeningEvent;
  32249. }, "get") });
  32250. Object.defineProperty(exports2, "TopologyClosedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32251. return events_1.TopologyClosedEvent;
  32252. }, "get") });
  32253. Object.defineProperty(exports2, "TopologyDescriptionChangedEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32254. return events_1.TopologyDescriptionChangedEvent;
  32255. }, "get") });
  32256. Object.defineProperty(exports2, "TopologyOpeningEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32257. return events_1.TopologyOpeningEvent;
  32258. }, "get") });
  32259. var srv_polling_1 = require_srv_polling();
  32260. Object.defineProperty(exports2, "SrvPollingEvent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
  32261. return srv_polling_1.SrvPollingEvent;
  32262. }, "get") });
  32263. }
  32264. });
  32265. // node_modules/@e22m4u/js-format/src/utils/is-class.js
  32266. function isClass(value) {
  32267. if (!value) return false;
  32268. return typeof value === "function" && /^class\s/.test(Function.prototype.toString.call(value));
  32269. }
  32270. var init_is_class = __esm({
  32271. "node_modules/@e22m4u/js-format/src/utils/is-class.js"() {
  32272. __name(isClass, "isClass");
  32273. }
  32274. });
  32275. // node_modules/@e22m4u/js-format/src/utils/index.js
  32276. var init_utils = __esm({
  32277. "node_modules/@e22m4u/js-format/src/utils/index.js"() {
  32278. init_is_class();
  32279. }
  32280. });
  32281. // node_modules/@e22m4u/js-format/src/value-to-string.js
  32282. function valueToString(input) {
  32283. if (input == null) return String(input);
  32284. if (typeof input === "string") return `"${input}"`;
  32285. if (typeof input === "number" || typeof input === "boolean")
  32286. return String(input);
  32287. if (isClass(input)) return input.name ? input.name : "Class";
  32288. if (input.constructor && input.constructor.name)
  32289. return BASE_CTOR_NAMES.includes(input.constructor.name) ? input.constructor.name : `${input.constructor.name} (instance)`;
  32290. if (typeof input === "object" && input.constructor == null) return "Object";
  32291. return String(input);
  32292. }
  32293. var BASE_CTOR_NAMES;
  32294. var init_value_to_string = __esm({
  32295. "node_modules/@e22m4u/js-format/src/value-to-string.js"() {
  32296. init_utils();
  32297. BASE_CTOR_NAMES = [
  32298. "String",
  32299. "Number",
  32300. "Boolean",
  32301. "Object",
  32302. "Array",
  32303. "Function",
  32304. "Symbol",
  32305. "Map",
  32306. "Set",
  32307. "Date"
  32308. ];
  32309. __name(valueToString, "valueToString");
  32310. }
  32311. });
  32312. // node_modules/@e22m4u/js-format/src/array-to-list.js
  32313. function arrayToList(input) {
  32314. if (Array.isArray(input) && input.length)
  32315. return input.map(valueToString).join(SEPARATOR);
  32316. return valueToString(input);
  32317. }
  32318. var SEPARATOR;
  32319. var init_array_to_list = __esm({
  32320. "node_modules/@e22m4u/js-format/src/array-to-list.js"() {
  32321. init_value_to_string();
  32322. SEPARATOR = ", ";
  32323. __name(arrayToList, "arrayToList");
  32324. }
  32325. });
  32326. // node_modules/@e22m4u/js-format/src/format.js
  32327. function format(pattern) {
  32328. if (pattern instanceof Date) {
  32329. pattern = pattern.toISOString();
  32330. } else if (typeof pattern !== "string") {
  32331. pattern = String(pattern);
  32332. }
  32333. const re = /(%?)(%([sdjvl]))/g;
  32334. const args = Array.prototype.slice.call(arguments, 1);
  32335. if (args.length) {
  32336. pattern = pattern.replace(re, function(match, escaped, ptn, flag) {
  32337. let arg = args.shift();
  32338. switch (flag) {
  32339. case "s":
  32340. arg = String(arg);
  32341. break;
  32342. case "d":
  32343. arg = Number(arg);
  32344. break;
  32345. case "j":
  32346. arg = JSON.stringify(arg);
  32347. break;
  32348. case "v":
  32349. arg = valueToString(arg);
  32350. break;
  32351. case "l":
  32352. arg = arrayToList(arg);
  32353. break;
  32354. }
  32355. if (!escaped) return arg;
  32356. args.unshift(arg);
  32357. return match;
  32358. });
  32359. }
  32360. if (args.length) pattern += " " + args.join(" ");
  32361. pattern = pattern.replace(/%{2}/g, "%");
  32362. return "" + pattern;
  32363. }
  32364. var init_format = __esm({
  32365. "node_modules/@e22m4u/js-format/src/format.js"() {
  32366. init_array_to_list();
  32367. init_value_to_string();
  32368. __name(format, "format");
  32369. }
  32370. });
  32371. // node_modules/@e22m4u/js-format/src/errorf.js
  32372. var _Errorf, Errorf;
  32373. var init_errorf = __esm({
  32374. "node_modules/@e22m4u/js-format/src/errorf.js"() {
  32375. init_format();
  32376. _Errorf = class _Errorf extends Error {
  32377. /**
  32378. * Constructor.
  32379. *
  32380. * @param {string|undefined} pattern
  32381. * @param {any} args
  32382. */
  32383. constructor(pattern = void 0, ...args) {
  32384. const message = pattern != null ? format(pattern, ...args) : void 0;
  32385. super(message);
  32386. }
  32387. };
  32388. __name(_Errorf, "Errorf");
  32389. Errorf = _Errorf;
  32390. }
  32391. });
  32392. // node_modules/@e22m4u/js-format/src/index.js
  32393. var init_src = __esm({
  32394. "node_modules/@e22m4u/js-format/src/index.js"() {
  32395. init_format();
  32396. init_errorf();
  32397. }
  32398. });
  32399. // node_modules/@e22m4u/js-service/src/errors/invalid-argument-error.js
  32400. var _InvalidArgumentError, InvalidArgumentError;
  32401. var init_invalid_argument_error = __esm({
  32402. "node_modules/@e22m4u/js-service/src/errors/invalid-argument-error.js"() {
  32403. init_src();
  32404. _InvalidArgumentError = class _InvalidArgumentError extends Errorf {
  32405. };
  32406. __name(_InvalidArgumentError, "InvalidArgumentError");
  32407. InvalidArgumentError = _InvalidArgumentError;
  32408. }
  32409. });
  32410. // node_modules/@e22m4u/js-service/src/errors/index.js
  32411. var init_errors = __esm({
  32412. "node_modules/@e22m4u/js-service/src/errors/index.js"() {
  32413. init_invalid_argument_error();
  32414. }
  32415. });
  32416. // node_modules/@e22m4u/js-service/src/service-container.js
  32417. var _ServiceContainer, ServiceContainer;
  32418. var init_service_container = __esm({
  32419. "node_modules/@e22m4u/js-service/src/service-container.js"() {
  32420. init_service();
  32421. init_errors();
  32422. _ServiceContainer = class _ServiceContainer {
  32423. /**
  32424. * Services map.
  32425. *
  32426. * @type {Map<any, any>}
  32427. * @private
  32428. */
  32429. _services = /* @__PURE__ */ new Map();
  32430. /**
  32431. * Parent container.
  32432. *
  32433. * @type {ServiceContainer}
  32434. * @private
  32435. */
  32436. _parent;
  32437. /**
  32438. * Constructor.
  32439. *
  32440. * @param {ServiceContainer|undefined} parent
  32441. */
  32442. constructor(parent = void 0) {
  32443. if (parent != null) {
  32444. if (!(parent instanceof _ServiceContainer))
  32445. throw new InvalidArgumentError(
  32446. 'The provided parameter "parent" of ServicesContainer.constructor must be an instance ServiceContainer, but %v given.',
  32447. parent
  32448. );
  32449. this._parent = parent;
  32450. }
  32451. }
  32452. /**
  32453. * Получить существующий или новый экземпляр.
  32454. *
  32455. * @param {*} ctor
  32456. * @param {*} args
  32457. * @return {*}
  32458. */
  32459. get(ctor, ...args) {
  32460. if (!ctor || typeof ctor !== "function")
  32461. throw new InvalidArgumentError(
  32462. "The first argument of ServicesContainer.get must be a class constructor, but %v given.",
  32463. ctor
  32464. );
  32465. if (!this._services.has(ctor) && this._parent && this._parent.has(ctor)) {
  32466. return this._parent.get(ctor);
  32467. }
  32468. let service = this._services.get(ctor);
  32469. if (!service || args.length) {
  32470. service = "prototype" in ctor && ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  32471. this._services.set(ctor, service);
  32472. } else if (typeof service === "function") {
  32473. service = service();
  32474. this._services.set(ctor, service);
  32475. }
  32476. return service;
  32477. }
  32478. /**
  32479. * Проверка существования конструктора в контейнере.
  32480. *
  32481. * @param {*} ctor
  32482. * @return {boolean}
  32483. */
  32484. has(ctor) {
  32485. if (this._services.has(ctor)) return true;
  32486. if (this._parent) return this._parent.has(ctor);
  32487. return false;
  32488. }
  32489. /**
  32490. * Добавить конструктор в контейнер.
  32491. *
  32492. * @param {*} ctor
  32493. * @param {*} args
  32494. * @return {this}
  32495. */
  32496. add(ctor, ...args) {
  32497. if (!ctor || typeof ctor !== "function")
  32498. throw new InvalidArgumentError(
  32499. "The first argument of ServicesContainer.add must be a class constructor, but %v given.",
  32500. ctor
  32501. );
  32502. const factory = /* @__PURE__ */ __name(() => ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args), "factory");
  32503. this._services.set(ctor, factory);
  32504. return this;
  32505. }
  32506. /**
  32507. * Добавить конструктор и создать экземпляр.
  32508. *
  32509. * @param {*} ctor
  32510. * @param {*} args
  32511. * @return {this}
  32512. */
  32513. use(ctor, ...args) {
  32514. if (!ctor || typeof ctor !== "function")
  32515. throw new InvalidArgumentError(
  32516. "The first argument of ServicesContainer.use must be a class constructor, but %v given.",
  32517. ctor
  32518. );
  32519. const service = ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  32520. this._services.set(ctor, service);
  32521. return this;
  32522. }
  32523. /**
  32524. * Добавить конструктор и связанный экземпляр.
  32525. *
  32526. * @param {*} ctor
  32527. * @param {*} service
  32528. * @return {this}
  32529. */
  32530. set(ctor, service) {
  32531. if (!ctor || typeof ctor !== "function")
  32532. throw new InvalidArgumentError(
  32533. "The first argument of ServicesContainer.set must be a class constructor, but %v given.",
  32534. ctor
  32535. );
  32536. if (!service || typeof service !== "object" || Array.isArray(service))
  32537. throw new InvalidArgumentError(
  32538. "The second argument of ServicesContainer.set must be an Object, but %v given.",
  32539. service
  32540. );
  32541. this._services.set(ctor, service);
  32542. return this;
  32543. }
  32544. };
  32545. __name(_ServiceContainer, "ServiceContainer");
  32546. ServiceContainer = _ServiceContainer;
  32547. }
  32548. });
  32549. // node_modules/@e22m4u/js-service/src/service.js
  32550. var _Service, Service;
  32551. var init_service = __esm({
  32552. "node_modules/@e22m4u/js-service/src/service.js"() {
  32553. init_service_container();
  32554. _Service = class _Service {
  32555. /**
  32556. * Container.
  32557. *
  32558. * @type {ServiceContainer}
  32559. */
  32560. container;
  32561. /**
  32562. * Constructor.
  32563. *
  32564. * @param {ServiceContainer|undefined} container
  32565. */
  32566. constructor(container = void 0) {
  32567. this.container = container instanceof ServiceContainer ? container : new ServiceContainer();
  32568. }
  32569. /**
  32570. * Получить существующий или новый экземпляр.
  32571. *
  32572. * @param {*} ctor
  32573. * @param {*} args
  32574. * @return {*}
  32575. */
  32576. getService(ctor, ...args) {
  32577. return this.container.get(ctor, ...args);
  32578. }
  32579. /**
  32580. * Проверка существования конструктора в контейнере.
  32581. *
  32582. * @param {*} ctor
  32583. * @return {boolean}
  32584. */
  32585. hasService(ctor) {
  32586. return this.container.has(ctor);
  32587. }
  32588. /**
  32589. * Добавить конструктор в контейнер.
  32590. *
  32591. * @param {*} ctor
  32592. * @param {*} args
  32593. * @return {this}
  32594. */
  32595. addService(ctor, ...args) {
  32596. this.container.add(ctor, ...args);
  32597. return this;
  32598. }
  32599. /**
  32600. * Добавить конструктор и создать экземпляр.
  32601. *
  32602. * @param {*} ctor
  32603. * @param {*} args
  32604. * @return {this}
  32605. */
  32606. useService(ctor, ...args) {
  32607. this.container.use(ctor, ...args);
  32608. return this;
  32609. }
  32610. /**
  32611. * Добавить конструктор и связанный экземпляр.
  32612. *
  32613. * @param {*} ctor
  32614. * @param {*} service
  32615. * @return {this}
  32616. */
  32617. setService(ctor, service) {
  32618. this.container.set(ctor, service);
  32619. return this;
  32620. }
  32621. };
  32622. __name(_Service, "Service");
  32623. Service = _Service;
  32624. }
  32625. });
  32626. // node_modules/@e22m4u/js-service/src/index.js
  32627. var init_src2 = __esm({
  32628. "node_modules/@e22m4u/js-service/src/index.js"() {
  32629. init_service();
  32630. init_service_container();
  32631. }
  32632. });
  32633. // node_modules/@e22m4u/js-repository/src/errors/not-implemented-error.js
  32634. var _NotImplementedError, NotImplementedError;
  32635. var init_not_implemented_error = __esm({
  32636. "node_modules/@e22m4u/js-repository/src/errors/not-implemented-error.js"() {
  32637. init_src();
  32638. _NotImplementedError = class _NotImplementedError extends Errorf {
  32639. };
  32640. __name(_NotImplementedError, "NotImplementedError");
  32641. NotImplementedError = _NotImplementedError;
  32642. }
  32643. });
  32644. // node_modules/@e22m4u/js-repository/src/errors/invalid-argument-error.js
  32645. var _InvalidArgumentError2, InvalidArgumentError2;
  32646. var init_invalid_argument_error2 = __esm({
  32647. "node_modules/@e22m4u/js-repository/src/errors/invalid-argument-error.js"() {
  32648. init_src();
  32649. _InvalidArgumentError2 = class _InvalidArgumentError2 extends Errorf {
  32650. };
  32651. __name(_InvalidArgumentError2, "InvalidArgumentError");
  32652. InvalidArgumentError2 = _InvalidArgumentError2;
  32653. }
  32654. });
  32655. // node_modules/@e22m4u/js-repository/src/errors/invalid-operator-value-error.js
  32656. var _InvalidOperatorValueError, InvalidOperatorValueError;
  32657. var init_invalid_operator_value_error = __esm({
  32658. "node_modules/@e22m4u/js-repository/src/errors/invalid-operator-value-error.js"() {
  32659. init_src();
  32660. _InvalidOperatorValueError = class _InvalidOperatorValueError extends Error {
  32661. /**
  32662. * Constructor.
  32663. *
  32664. * @param {string} operator
  32665. * @param {string} expected
  32666. * @param {*} value
  32667. */
  32668. constructor(operator, expected, value) {
  32669. super(
  32670. format(
  32671. "Condition of {%s: ...} should have %s, but %v given.",
  32672. operator,
  32673. expected,
  32674. value
  32675. )
  32676. );
  32677. }
  32678. };
  32679. __name(_InvalidOperatorValueError, "InvalidOperatorValueError");
  32680. InvalidOperatorValueError = _InvalidOperatorValueError;
  32681. }
  32682. });
  32683. // node_modules/@e22m4u/js-repository/src/errors/index.js
  32684. var init_errors2 = __esm({
  32685. "node_modules/@e22m4u/js-repository/src/errors/index.js"() {
  32686. init_not_implemented_error();
  32687. init_invalid_argument_error2();
  32688. init_invalid_operator_value_error();
  32689. }
  32690. });
  32691. // node_modules/@e22m4u/js-repository/src/filter/slice-clause-tool.js
  32692. var _SliceClauseTool, SliceClauseTool;
  32693. var init_slice_clause_tool = __esm({
  32694. "node_modules/@e22m4u/js-repository/src/filter/slice-clause-tool.js"() {
  32695. init_src2();
  32696. init_errors2();
  32697. _SliceClauseTool = class _SliceClauseTool extends Service {
  32698. /**
  32699. * Slice.
  32700. *
  32701. * @param {object[]} entities
  32702. * @param {number|undefined} skip
  32703. * @param {number|undefined} limit
  32704. * @returns {object[]}
  32705. */
  32706. slice(entities, skip = void 0, limit = void 0) {
  32707. if (!Array.isArray(entities))
  32708. throw new InvalidArgumentError2(
  32709. "The first argument of SliceClauseTool.slice should be an Array, but %v given.",
  32710. entities
  32711. );
  32712. if (skip != null && typeof skip !== "number")
  32713. throw new InvalidArgumentError2(
  32714. 'The provided option "skip" should be a Number, but %v given.',
  32715. skip
  32716. );
  32717. if (limit != null && typeof limit !== "number")
  32718. throw new InvalidArgumentError2(
  32719. 'The provided option "limit" should be a Number, but %v given.',
  32720. limit
  32721. );
  32722. skip = skip || 0;
  32723. limit = limit || entities.length;
  32724. return entities.slice(skip, skip + limit);
  32725. }
  32726. /**
  32727. * Validate skip clause.
  32728. *
  32729. * @param {number|undefined} skip
  32730. */
  32731. static validateSkipClause(skip) {
  32732. if (skip == null) return;
  32733. if (typeof skip !== "number")
  32734. throw new InvalidArgumentError2(
  32735. 'The provided option "skip" should be a Number, but %v given.',
  32736. skip
  32737. );
  32738. }
  32739. /**
  32740. * Validate limit clause.
  32741. *
  32742. * @param {number|undefined} limit
  32743. */
  32744. static validateLimitClause(limit) {
  32745. if (limit == null) return;
  32746. if (typeof limit !== "number")
  32747. throw new InvalidArgumentError2(
  32748. 'The provided option "limit" should be a Number, but %v given.',
  32749. limit
  32750. );
  32751. }
  32752. };
  32753. __name(_SliceClauseTool, "SliceClauseTool");
  32754. SliceClauseTool = _SliceClauseTool;
  32755. }
  32756. });
  32757. // node_modules/@e22m4u/js-repository/src/utils/is-ctor.js
  32758. var init_is_ctor = __esm({
  32759. "node_modules/@e22m4u/js-repository/src/utils/is-ctor.js"() {
  32760. }
  32761. });
  32762. // node_modules/@e22m4u/js-repository/src/utils/is-promise.js
  32763. function isPromise(value) {
  32764. if (!value) return false;
  32765. if (typeof value !== "object") return false;
  32766. return typeof value.then === "function";
  32767. }
  32768. var init_is_promise = __esm({
  32769. "node_modules/@e22m4u/js-repository/src/utils/is-promise.js"() {
  32770. __name(isPromise, "isPromise");
  32771. }
  32772. });
  32773. // node_modules/@e22m4u/js-repository/src/utils/capitalize.js
  32774. function capitalize(string) {
  32775. if (!string || typeof string !== "string") return string;
  32776. return string.charAt(0).toUpperCase() + string.slice(1);
  32777. }
  32778. var init_capitalize = __esm({
  32779. "node_modules/@e22m4u/js-repository/src/utils/capitalize.js"() {
  32780. __name(capitalize, "capitalize");
  32781. }
  32782. });
  32783. // node_modules/@e22m4u/js-repository/src/utils/clone-deep.js
  32784. function cloneDeep(value) {
  32785. if (!value) return value;
  32786. const types = [Number, String, Boolean];
  32787. let result;
  32788. types.forEach((type) => {
  32789. if (value instanceof type) result = type(value);
  32790. });
  32791. if (result === void 0) {
  32792. if (Array.isArray(value)) {
  32793. result = [];
  32794. value.forEach((child, index) => {
  32795. result[index] = cloneDeep(child);
  32796. });
  32797. } else if (typeof value === "object") {
  32798. if ("nodeType" in value && value.nodeType && "cloneNode" in value && typeof value.cloneNode === "function") {
  32799. result = value.cloneNode(true);
  32800. } else if (!("prototype" in value) || !value.prototype) {
  32801. if (value instanceof Date) {
  32802. result = new Date(value);
  32803. } else if (value.constructor && value.constructor.name === "Object") {
  32804. result = {};
  32805. for (const key in value) {
  32806. result[key] = cloneDeep(value[key]);
  32807. }
  32808. } else {
  32809. result = value;
  32810. }
  32811. } else {
  32812. result = value;
  32813. }
  32814. } else {
  32815. result = value;
  32816. }
  32817. }
  32818. return result;
  32819. }
  32820. var init_clone_deep = __esm({
  32821. "node_modules/@e22m4u/js-repository/src/utils/clone-deep.js"() {
  32822. __name(cloneDeep, "cloneDeep");
  32823. }
  32824. });
  32825. // node_modules/@e22m4u/js-repository/src/utils/singularize.js
  32826. function singularize(noun) {
  32827. if (!noun || typeof noun !== "string") return noun;
  32828. const endings = {
  32829. ves: "fe",
  32830. ies: "y",
  32831. i: "us",
  32832. zes: "ze",
  32833. ses: "s",
  32834. es: "e",
  32835. s: ""
  32836. };
  32837. return noun.replace(
  32838. new RegExp(`(${Object.keys(endings).join("|")})$`),
  32839. (r) => endings[r]
  32840. );
  32841. }
  32842. var init_singularize = __esm({
  32843. "node_modules/@e22m4u/js-repository/src/utils/singularize.js"() {
  32844. __name(singularize, "singularize");
  32845. }
  32846. });
  32847. // node_modules/@e22m4u/js-repository/src/utils/is-deep-equal.js
  32848. function isDeepEqual(firstValue, secondValue) {
  32849. const cached = /* @__PURE__ */ new WeakMap();
  32850. const compare = /* @__PURE__ */ __name((a, b) => {
  32851. if (a === null || b === null) return a === b;
  32852. if (typeof a !== "object" || typeof b !== "object") return a === b;
  32853. const dataTypeA = Array.isArray(a) ? "array" : "object";
  32854. const dataTypeB = Array.isArray(b) ? "array" : "object";
  32855. if (dataTypeA !== dataTypeB) return false;
  32856. const keysA = Object.keys(a);
  32857. const keysB = Object.keys(b);
  32858. if (keysA.length !== keysB.length) return false;
  32859. const symbolsA = Object.getOwnPropertySymbols(a);
  32860. const symbolsB = Object.getOwnPropertySymbols(b);
  32861. if (symbolsA.length !== symbolsB.length) return false;
  32862. let setForA = cached.get(a);
  32863. if (setForA == null) {
  32864. setForA = /* @__PURE__ */ new Set();
  32865. cached.set(a, setForA);
  32866. } else if (setForA.has(b)) {
  32867. return true;
  32868. }
  32869. setForA.add(b);
  32870. let setForB = cached.get(b);
  32871. if (setForB == null) {
  32872. setForB = /* @__PURE__ */ new Set();
  32873. cached.set(b, setForB);
  32874. } else if (setForB.has(a)) {
  32875. return true;
  32876. }
  32877. setForB.add(a);
  32878. const propertyNamesA = [...keysA, ...symbolsA];
  32879. for (const propertyNameA of propertyNamesA) {
  32880. if (!Object.prototype.hasOwnProperty.call(b, propertyNameA)) return false;
  32881. const propertyValueA = a[propertyNameA];
  32882. const propertyValueB = b[propertyNameA];
  32883. if (!compare(propertyValueA, propertyValueB)) return false;
  32884. }
  32885. return true;
  32886. }, "compare");
  32887. return compare(firstValue, secondValue);
  32888. }
  32889. var init_is_deep_equal = __esm({
  32890. "node_modules/@e22m4u/js-repository/src/utils/is-deep-equal.js"() {
  32891. __name(isDeepEqual, "isDeepEqual");
  32892. }
  32893. });
  32894. // node_modules/@e22m4u/js-repository/src/utils/get-ctor-name.js
  32895. function getCtorName(value) {
  32896. if (value === null) return "Null";
  32897. if (value === void 0) return "Undefined";
  32898. return value.constructor && value.constructor.name || void 0;
  32899. }
  32900. var init_get_ctor_name = __esm({
  32901. "node_modules/@e22m4u/js-repository/src/utils/get-ctor-name.js"() {
  32902. __name(getCtorName, "getCtorName");
  32903. }
  32904. });
  32905. // node_modules/@e22m4u/js-repository/src/utils/is-pure-object.js
  32906. function isPureObject(value) {
  32907. return Boolean(
  32908. typeof value === "object" && value && !Array.isArray(value) && (!value.constructor || value.constructor && value.constructor.name === "Object")
  32909. );
  32910. }
  32911. var init_is_pure_object = __esm({
  32912. "node_modules/@e22m4u/js-repository/src/utils/is-pure-object.js"() {
  32913. __name(isPureObject, "isPureObject");
  32914. }
  32915. });
  32916. // node_modules/@e22m4u/js-repository/src/utils/string-to-regexp.js
  32917. function stringToRegexp(pattern, flags = void 0) {
  32918. if (pattern instanceof RegExp) {
  32919. return new RegExp(pattern, flags);
  32920. }
  32921. let regex = "";
  32922. for (let i = 0, n = pattern.length; i < n; i++) {
  32923. const char = pattern.charAt(i);
  32924. if (char === "%") {
  32925. regex += ".*";
  32926. } else {
  32927. regex += char;
  32928. }
  32929. }
  32930. return new RegExp(regex, flags);
  32931. }
  32932. var init_string_to_regexp = __esm({
  32933. "node_modules/@e22m4u/js-repository/src/utils/string-to-regexp.js"() {
  32934. __name(stringToRegexp, "stringToRegexp");
  32935. }
  32936. });
  32937. // node_modules/@e22m4u/js-repository/src/utils/get-value-by-path.js
  32938. function getValueByPath(obj, path, orElse = void 0) {
  32939. if (!obj || typeof obj !== "object") return orElse;
  32940. if (!path || typeof path !== "string") return orElse;
  32941. const keys = path.split(".");
  32942. let value = obj;
  32943. for (const key of keys) {
  32944. if (typeof value === "object" && value !== null && key in value) {
  32945. value = value[key];
  32946. } else {
  32947. value = orElse;
  32948. break;
  32949. }
  32950. }
  32951. return value;
  32952. }
  32953. var init_get_value_by_path = __esm({
  32954. "node_modules/@e22m4u/js-repository/src/utils/get-value-by-path.js"() {
  32955. __name(getValueByPath, "getValueByPath");
  32956. }
  32957. });
  32958. // node_modules/@e22m4u/js-repository/src/utils/transform-promise.js
  32959. function transformPromise(valueOrPromise, transformer) {
  32960. return isPromise(valueOrPromise) ? valueOrPromise.then(transformer) : transformer(valueOrPromise);
  32961. }
  32962. var init_transform_promise = __esm({
  32963. "node_modules/@e22m4u/js-repository/src/utils/transform-promise.js"() {
  32964. init_is_promise();
  32965. __name(transformPromise, "transformPromise");
  32966. }
  32967. });
  32968. // node_modules/@e22m4u/js-repository/src/utils/select-object-keys.js
  32969. function selectObjectKeys(obj, keys) {
  32970. if (!obj || typeof obj !== "object" || Array.isArray(obj))
  32971. throw new InvalidArgumentError2(
  32972. "The first argument of selectObjectKeys should be an Object, but %v given.",
  32973. obj
  32974. );
  32975. if (!Array.isArray(keys))
  32976. throw new InvalidArgumentError2(
  32977. "The second argument of selectObjectKeys should be an Array of String, but %v given.",
  32978. keys
  32979. );
  32980. keys.forEach((key) => {
  32981. if (typeof key !== "string")
  32982. throw new InvalidArgumentError2(
  32983. "The second argument of selectObjectKeys should be an Array of String, but %v given.",
  32984. key
  32985. );
  32986. });
  32987. const result = {};
  32988. const allKeys = Object.keys(obj);
  32989. allKeys.forEach((key) => {
  32990. if (keys.includes(key)) result[key] = obj[key];
  32991. });
  32992. return result;
  32993. }
  32994. var init_select_object_keys = __esm({
  32995. "node_modules/@e22m4u/js-repository/src/utils/select-object-keys.js"() {
  32996. init_errors2();
  32997. __name(selectObjectKeys, "selectObjectKeys");
  32998. }
  32999. });
  33000. // node_modules/@e22m4u/js-repository/src/utils/exclude-object-keys.js
  33001. function excludeObjectKeys(obj, keys) {
  33002. if (typeof obj !== "object" || !obj || Array.isArray(obj))
  33003. throw new InvalidArgumentError2(
  33004. "Cannot exclude keys from a non-Object value, %v given.",
  33005. obj
  33006. );
  33007. const result = { ...obj };
  33008. keys = Array.isArray(keys) ? keys : [keys];
  33009. keys.forEach((key) => delete result[key]);
  33010. return result;
  33011. }
  33012. var init_exclude_object_keys = __esm({
  33013. "node_modules/@e22m4u/js-repository/src/utils/exclude-object-keys.js"() {
  33014. init_errors2();
  33015. __name(excludeObjectKeys, "excludeObjectKeys");
  33016. }
  33017. });
  33018. // node_modules/@e22m4u/js-repository/src/utils/get-decorator-target-type.js
  33019. var init_get_decorator_target_type = __esm({
  33020. "node_modules/@e22m4u/js-repository/src/utils/get-decorator-target-type.js"() {
  33021. }
  33022. });
  33023. // node_modules/@e22m4u/js-repository/src/utils/index.js
  33024. var init_utils2 = __esm({
  33025. "node_modules/@e22m4u/js-repository/src/utils/index.js"() {
  33026. init_is_ctor();
  33027. init_is_promise();
  33028. init_capitalize();
  33029. init_clone_deep();
  33030. init_singularize();
  33031. init_is_deep_equal();
  33032. init_get_ctor_name();
  33033. init_is_pure_object();
  33034. init_string_to_regexp();
  33035. init_get_value_by_path();
  33036. init_transform_promise();
  33037. init_select_object_keys();
  33038. init_exclude_object_keys();
  33039. init_get_decorator_target_type();
  33040. }
  33041. });
  33042. // node_modules/@e22m4u/js-repository/src/filter/order-clause-tool.js
  33043. function compareFn(a, b) {
  33044. let undefinedA, undefinedB;
  33045. for (let i = 0, l = this.length; i < l; i++) {
  33046. const aVal = getValueByPath(a, this[i].key);
  33047. const bVal = getValueByPath(b, this[i].key);
  33048. undefinedB = bVal === void 0 && aVal !== void 0;
  33049. undefinedA = aVal === void 0 && bVal !== void 0;
  33050. if (undefinedB || aVal > bVal) {
  33051. return this[i].reverse;
  33052. } else if (undefinedA || aVal < bVal) {
  33053. return -1 * this[i].reverse;
  33054. }
  33055. }
  33056. return 0;
  33057. }
  33058. var _OrderClauseTool, OrderClauseTool;
  33059. var init_order_clause_tool = __esm({
  33060. "node_modules/@e22m4u/js-repository/src/filter/order-clause-tool.js"() {
  33061. init_src2();
  33062. init_utils2();
  33063. init_errors2();
  33064. _OrderClauseTool = class _OrderClauseTool extends Service {
  33065. /**
  33066. * Sort.
  33067. *
  33068. * @param {object[]} entities
  33069. * @param {string|string[]|undefined} clause
  33070. */
  33071. sort(entities, clause) {
  33072. if (clause == null) return;
  33073. if (Array.isArray(clause) === false) clause = [clause];
  33074. if (!clause.length) return;
  33075. const mapping = [];
  33076. clause.forEach((key, index) => {
  33077. if (!key || typeof key !== "string")
  33078. throw new InvalidArgumentError2(
  33079. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  33080. key
  33081. );
  33082. let reverse = 1;
  33083. const matches = key.match(/\s+(A|DE)SC$/i);
  33084. if (matches) {
  33085. key = key.replace(/\s+(A|DE)SC/i, "");
  33086. if (matches[1].toLowerCase() === "de") reverse = -1;
  33087. }
  33088. mapping[index] = { key, reverse };
  33089. });
  33090. entities.sort(compareFn.bind(mapping));
  33091. }
  33092. /**
  33093. * Validate order clause.
  33094. *
  33095. * @param {string|string[]|undefined} clause
  33096. */
  33097. static validateOrderClause(clause) {
  33098. if (clause == null) return;
  33099. if (Array.isArray(clause) === false) clause = [clause];
  33100. if (!clause.length) return;
  33101. clause.forEach((field) => {
  33102. if (!field || typeof field !== "string")
  33103. throw new InvalidArgumentError2(
  33104. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  33105. field
  33106. );
  33107. });
  33108. }
  33109. /**
  33110. * Normalize order clause.
  33111. *
  33112. * @param {string|string[]|undefined} clause
  33113. * @returns {string[]|undefined}
  33114. */
  33115. static normalizeOrderClause(clause) {
  33116. if (clause == null) return;
  33117. if (Array.isArray(clause) === false) clause = [clause];
  33118. if (!clause.length) return;
  33119. clause.forEach((field) => {
  33120. if (!field || typeof field !== "string")
  33121. throw new InvalidArgumentError2(
  33122. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  33123. field
  33124. );
  33125. });
  33126. return clause;
  33127. }
  33128. };
  33129. __name(_OrderClauseTool, "OrderClauseTool");
  33130. OrderClauseTool = _OrderClauseTool;
  33131. __name(compareFn, "compareFn");
  33132. }
  33133. });
  33134. // node_modules/@e22m4u/js-repository/src/filter/operator-clause-tool.js
  33135. var _OperatorClauseTool, OperatorClauseTool;
  33136. var init_operator_clause_tool = __esm({
  33137. "node_modules/@e22m4u/js-repository/src/filter/operator-clause-tool.js"() {
  33138. init_src2();
  33139. init_utils2();
  33140. init_errors2();
  33141. init_errors2();
  33142. _OperatorClauseTool = class _OperatorClauseTool extends Service {
  33143. /**
  33144. * Compare.
  33145. *
  33146. * @param {*} val1 The 1st value
  33147. * @param {*} val2 The 2nd value
  33148. * @returns {number} 0: =, positive: >, negative <
  33149. */
  33150. compare(val1, val2) {
  33151. if (val1 == null || val2 == null) {
  33152. return val1 == val2 ? 0 : NaN;
  33153. }
  33154. if (typeof val1 === "number") {
  33155. if (typeof val2 === "number" || typeof val2 === "string" || typeof val2 === "boolean") {
  33156. if (val1 === val2) return 0;
  33157. return val1 - Number(val2);
  33158. }
  33159. return NaN;
  33160. }
  33161. if (typeof val1 === "string") {
  33162. const isDigits = /^\d+$/.test(val1);
  33163. if (isDigits) return this.compare(Number(val1), val2);
  33164. try {
  33165. if (val1 > val2) return 1;
  33166. if (val1 < val2) return -1;
  33167. if (val1 == val2) return 0;
  33168. } catch (e) {
  33169. }
  33170. return NaN;
  33171. }
  33172. if (typeof val1 === "boolean") {
  33173. return Number(val1) - Number(val2);
  33174. }
  33175. return val1 === val2 ? 0 : NaN;
  33176. }
  33177. /**
  33178. * Test all operators.
  33179. *
  33180. * @param {object} clause
  33181. * @param {*} value
  33182. * @returns {boolean|undefined}
  33183. */
  33184. testAll(clause, value) {
  33185. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  33186. throw new InvalidArgumentError2(
  33187. "The first argument of OperatorUtils.testAll should be an Object, but %v given.",
  33188. clause
  33189. );
  33190. const eqNeqTest = this.testEqNeq(clause, value);
  33191. if (eqNeqTest !== void 0) return eqNeqTest;
  33192. const gtLtTest = this.testGtLt(clause, value);
  33193. if (gtLtTest !== void 0) return gtLtTest;
  33194. const incTest = this.testInq(clause, value);
  33195. if (incTest !== void 0) return incTest;
  33196. const ninTest = this.testNin(clause, value);
  33197. if (ninTest !== void 0) return ninTest;
  33198. const betweenTest = this.testBetween(clause, value);
  33199. if (betweenTest !== void 0) return betweenTest;
  33200. const existsTest = this.testExists(clause, value);
  33201. if (existsTest !== void 0) return existsTest;
  33202. const likeTest = this.testLike(clause, value);
  33203. if (likeTest !== void 0) return likeTest;
  33204. const nlikeTest = this.testNlike(clause, value);
  33205. if (nlikeTest !== void 0) return nlikeTest;
  33206. const ilikeTest = this.testIlike(clause, value);
  33207. if (ilikeTest !== void 0) return ilikeTest;
  33208. const nilikeTest = this.testNilike(clause, value);
  33209. if (nilikeTest !== void 0) return nilikeTest;
  33210. const regExpTest = this.testRegexp(clause, value);
  33211. if (regExpTest !== void 0) return regExpTest;
  33212. }
  33213. /**
  33214. * Test eq/neq operator.
  33215. *
  33216. * @example
  33217. * ```ts
  33218. * {
  33219. * eq: 'foo',
  33220. * }
  33221. * ```
  33222. *
  33223. * @example
  33224. * ```ts
  33225. * {
  33226. * neq: 'foo',
  33227. * }
  33228. * ```
  33229. *
  33230. * @param {object} clause
  33231. * @param {*} value
  33232. * @returns {boolean|undefined}
  33233. */
  33234. testEqNeq(clause, value) {
  33235. if (!clause || typeof clause !== "object")
  33236. throw new InvalidArgumentError2(
  33237. "The first argument of OperatorUtils.testEqNeq should be an Object, but %v given.",
  33238. clause
  33239. );
  33240. if ("eq" in clause) return this.compare(clause.eq, value) === 0;
  33241. if ("neq" in clause) return this.compare(clause.neq, value) !== 0;
  33242. }
  33243. /**
  33244. * Test lt/gt/lte/gte operator.
  33245. *
  33246. * @example
  33247. * ```ts
  33248. * {
  33249. * lt: 10,
  33250. * }
  33251. * ```
  33252. *
  33253. * @example
  33254. * ```ts
  33255. * {
  33256. * lte: 10,
  33257. * }
  33258. * ```
  33259. *
  33260. * @example
  33261. * ```ts
  33262. * {
  33263. * gt: 10,
  33264. * }
  33265. * ```
  33266. *
  33267. * @example
  33268. * ```ts
  33269. * {
  33270. * gte: 10,
  33271. * }
  33272. * ```
  33273. *
  33274. * @param {object} clause
  33275. * @param {*} value
  33276. * @returns {boolean|undefined}
  33277. */
  33278. testGtLt(clause, value) {
  33279. if (!clause || typeof clause !== "object")
  33280. throw new InvalidArgumentError2(
  33281. "The first argument of OperatorUtils.testGtLt should be an Object, but %v given.",
  33282. clause
  33283. );
  33284. if ("gt" in clause) return this.compare(value, clause.gt) > 0;
  33285. if ("gte" in clause) return this.compare(value, clause.gte) >= 0;
  33286. if ("lt" in clause) return this.compare(value, clause.lt) < 0;
  33287. if ("lte" in clause) return this.compare(value, clause.lte) <= 0;
  33288. }
  33289. /**
  33290. * Test inc operator.
  33291. *
  33292. * @example
  33293. * ```ts
  33294. * {
  33295. * inc: ['foo', 'bar'],
  33296. * }
  33297. * ```
  33298. *
  33299. * @param {object} clause
  33300. * @param {*} value
  33301. * @returns {boolean|undefined}
  33302. */
  33303. testInq(clause, value) {
  33304. if (!clause || typeof clause !== "object")
  33305. throw new InvalidArgumentError2(
  33306. "The first argument of OperatorUtils.testInq should be an Object, but %v given.",
  33307. clause
  33308. );
  33309. if ("inq" in clause && clause.inq !== void 0) {
  33310. if (!clause.inq || !Array.isArray(clause.inq)) {
  33311. throw new InvalidOperatorValueError(
  33312. "inq",
  33313. "an Array of possible values",
  33314. clause.inq
  33315. );
  33316. }
  33317. for (let i = 0; i < clause.inq.length; i++) {
  33318. if (clause.inq[i] == value) return true;
  33319. }
  33320. return false;
  33321. }
  33322. }
  33323. /**
  33324. * Test nin operator.
  33325. *
  33326. * @example
  33327. * ```ts
  33328. * {
  33329. * nin: ['foo', 'bar'],
  33330. * }
  33331. * ```
  33332. *
  33333. * @param {object} clause
  33334. * @param {*} value
  33335. * @returns {boolean|undefined}
  33336. */
  33337. testNin(clause, value) {
  33338. if (!clause || typeof clause !== "object")
  33339. throw new InvalidArgumentError2(
  33340. "The first argument of OperatorUtils.testNin should be an Object, but %v given.",
  33341. clause
  33342. );
  33343. if ("nin" in clause && clause.nin !== void 0) {
  33344. if (!clause.nin || !Array.isArray(clause.nin)) {
  33345. throw new InvalidOperatorValueError(
  33346. "nin",
  33347. "an Array of possible values",
  33348. clause.nin
  33349. );
  33350. }
  33351. for (let i = 0; i < clause.nin.length; i++) {
  33352. if (clause.nin[i] == value) return false;
  33353. }
  33354. return true;
  33355. }
  33356. }
  33357. /**
  33358. * Test between operator.
  33359. *
  33360. * @example
  33361. * ```ts
  33362. * {
  33363. * between: [10, 20],
  33364. * }
  33365. * ```
  33366. *
  33367. * @param {object} clause
  33368. * @param {*} value
  33369. * @returns {boolean|undefined}
  33370. */
  33371. testBetween(clause, value) {
  33372. if (!clause || typeof clause !== "object")
  33373. throw new InvalidArgumentError2(
  33374. "The first argument of OperatorUtils.testBetween should be an Object, but %v given.",
  33375. clause
  33376. );
  33377. if ("between" in clause && clause.between !== void 0) {
  33378. if (!Array.isArray(clause.between) || clause.between.length !== 2) {
  33379. throw new InvalidOperatorValueError(
  33380. "between",
  33381. "an Array of 2 elements",
  33382. clause.between
  33383. );
  33384. }
  33385. return this.testGtLt({ gte: clause.between[0] }, value) && this.testGtLt({ lte: clause.between[1] }, value);
  33386. }
  33387. }
  33388. /**
  33389. * Test exists operator.
  33390. *
  33391. * @example
  33392. * ```ts
  33393. * {
  33394. * exists: true,
  33395. * }
  33396. * ```
  33397. *
  33398. * @param {object} clause
  33399. * @param {*} value
  33400. * @returns {boolean|undefined}
  33401. */
  33402. testExists(clause, value) {
  33403. if (!clause || typeof clause !== "object")
  33404. throw new InvalidArgumentError2(
  33405. "The first argument of OperatorUtils.testExists should be an Object, but %v given.",
  33406. clause
  33407. );
  33408. if ("exists" in clause && clause.exists !== void 0) {
  33409. if (typeof clause.exists !== "boolean") {
  33410. throw new InvalidOperatorValueError(
  33411. "exists",
  33412. "a Boolean",
  33413. clause.exists
  33414. );
  33415. }
  33416. return clause.exists ? value !== void 0 : value === void 0;
  33417. }
  33418. }
  33419. /**
  33420. * Test like operator.
  33421. *
  33422. * @example
  33423. * ```ts
  33424. * {
  33425. * like: 'foo',
  33426. * }
  33427. * ```
  33428. *
  33429. * @param {object} clause
  33430. * @param {*} value
  33431. * @returns {boolean|undefined}
  33432. */
  33433. testLike(clause, value) {
  33434. if (!clause || typeof clause !== "object")
  33435. throw new InvalidArgumentError2(
  33436. "The first argument of OperatorUtils.testLike should be an Object, but %v given.",
  33437. clause
  33438. );
  33439. if ("like" in clause && clause.like !== void 0) {
  33440. if (typeof clause.like !== "string" && !(clause.like instanceof RegExp))
  33441. throw new InvalidOperatorValueError("like", "a String", clause.like);
  33442. return stringToRegexp(clause.like).test(value);
  33443. }
  33444. }
  33445. /**
  33446. * Test nlike operator.
  33447. *
  33448. * @example
  33449. * ```ts
  33450. * {
  33451. * nlike: 'foo',
  33452. * }
  33453. * ```
  33454. *
  33455. * @param {object} clause
  33456. * @param {*} value
  33457. * @returns {boolean|undefined}
  33458. */
  33459. testNlike(clause, value) {
  33460. if (!clause || typeof clause !== "object")
  33461. throw new InvalidArgumentError2(
  33462. "The first argument of OperatorUtils.testNlike should be an Object, but %v given.",
  33463. clause
  33464. );
  33465. if ("nlike" in clause && clause.nlike !== void 0) {
  33466. if (typeof clause.nlike !== "string" && !(clause.nlike instanceof RegExp)) {
  33467. throw new InvalidOperatorValueError("nlike", "a String", clause.nlike);
  33468. }
  33469. return !stringToRegexp(clause.nlike).test(value);
  33470. }
  33471. }
  33472. /**
  33473. * Test ilike operator.
  33474. *
  33475. * @example
  33476. * ```ts
  33477. * {
  33478. * ilike: 'foo',
  33479. * }
  33480. * ```
  33481. *
  33482. * @param {object} clause
  33483. * @param {*} value
  33484. * @returns {boolean|undefined}
  33485. */
  33486. testIlike(clause, value) {
  33487. if (!clause || typeof clause !== "object")
  33488. throw new InvalidArgumentError2(
  33489. "The first argument of OperatorUtils.testIlike should be an Object, but %v given.",
  33490. clause
  33491. );
  33492. if ("ilike" in clause && clause.ilike !== void 0) {
  33493. if (typeof clause.ilike !== "string" && !(clause.ilike instanceof RegExp)) {
  33494. throw new InvalidOperatorValueError("ilike", "a String", clause.ilike);
  33495. }
  33496. return stringToRegexp(clause.ilike, "i").test(value);
  33497. }
  33498. }
  33499. /**
  33500. * Test nilike operator.
  33501. *
  33502. * @example
  33503. * ```ts
  33504. * {
  33505. * nilike: 'foo',
  33506. * }
  33507. * ```
  33508. *
  33509. * @param {object} clause
  33510. * @param {*} value
  33511. * @returns {boolean|undefined}
  33512. */
  33513. testNilike(clause, value) {
  33514. if (!clause || typeof clause !== "object")
  33515. throw new InvalidArgumentError2(
  33516. "The first argument of OperatorUtils.testNilike should be an Object, but %v given.",
  33517. clause
  33518. );
  33519. if ("nilike" in clause && clause.nilike !== void 0) {
  33520. if (typeof clause.nilike !== "string" && !(clause.nilike instanceof RegExp)) {
  33521. throw new InvalidOperatorValueError(
  33522. "nilike",
  33523. "a String",
  33524. clause.nilike
  33525. );
  33526. }
  33527. return !stringToRegexp(clause.nilike, "i").test(value);
  33528. }
  33529. }
  33530. /**
  33531. * Test regexp.
  33532. *
  33533. * @example
  33534. * ```ts
  33535. * {
  33536. * regexp: 'foo.*',
  33537. * }
  33538. * ```
  33539. *
  33540. * @example
  33541. * ```ts
  33542. * {
  33543. * regexp: 'foo.*',
  33544. * flags: 'i',
  33545. * }
  33546. * ```
  33547. *
  33548. * @param {object} clause
  33549. * @param {*} value
  33550. * @returns {boolean|undefined}
  33551. */
  33552. testRegexp(clause, value) {
  33553. if (!clause || typeof clause !== "object")
  33554. throw new InvalidArgumentError2(
  33555. "The first argument of OperatorUtils.testRegexp should be an Object, but %v given.",
  33556. clause
  33557. );
  33558. if ("regexp" in clause && clause.regexp !== void 0) {
  33559. if (typeof clause.regexp !== "string" && !(clause.regexp instanceof RegExp)) {
  33560. throw new InvalidOperatorValueError(
  33561. "regexp",
  33562. "a String",
  33563. clause.regexp
  33564. );
  33565. }
  33566. const flags = clause.flags || void 0;
  33567. if (flags && typeof flags !== "string")
  33568. throw new InvalidArgumentError2(
  33569. "RegExp flags should be a String, but %v given.",
  33570. clause.flags
  33571. );
  33572. if (!value || typeof value !== "string") return false;
  33573. const regExp = stringToRegexp(clause.regexp, flags);
  33574. return !!value.match(regExp);
  33575. }
  33576. }
  33577. };
  33578. __name(_OperatorClauseTool, "OperatorClauseTool");
  33579. OperatorClauseTool = _OperatorClauseTool;
  33580. }
  33581. });
  33582. // node_modules/@e22m4u/js-repository/src/filter/where-clause-tool.js
  33583. var _WhereClauseTool, WhereClauseTool;
  33584. var init_where_clause_tool = __esm({
  33585. "node_modules/@e22m4u/js-repository/src/filter/where-clause-tool.js"() {
  33586. init_src2();
  33587. init_utils2();
  33588. init_errors2();
  33589. init_operator_clause_tool();
  33590. _WhereClauseTool = class _WhereClauseTool extends Service {
  33591. /**
  33592. * Filter by where clause.
  33593. *
  33594. * @example
  33595. * ```
  33596. * const entities = [
  33597. * {foo: 1, bar: 'a'},
  33598. * {foo: 2, bar: 'b'},
  33599. * {foo: 3, bar: 'b'},
  33600. * {foo: 4, bar: 'b'},
  33601. * ];
  33602. *
  33603. * const result = filterByWhereClause(entities, {
  33604. * foo: {gt: 2},
  33605. * bar: 'b',
  33606. * });
  33607. *
  33608. * console.log(result);
  33609. * // [
  33610. * // {foo: 3, bar: 'b'},
  33611. * // {foo: 4, bar: 'b'},
  33612. * // ];
  33613. *
  33614. * ```
  33615. *
  33616. * @param {object[]} entities
  33617. * @param {WhereClause|undefined} where
  33618. * @returns {object[]}
  33619. */
  33620. filter(entities, where = void 0) {
  33621. if (!Array.isArray(entities))
  33622. throw new InvalidArgumentError2(
  33623. "The first argument of WhereClauseTool.filter should be an Array of Object, but %v given.",
  33624. entities
  33625. );
  33626. if (where == null) return entities;
  33627. return entities.filter(this._createFilter(where));
  33628. }
  33629. /**
  33630. * Create where filter.
  33631. *
  33632. * @param {WhereClause} whereClause
  33633. * @returns {Function}
  33634. */
  33635. _createFilter(whereClause) {
  33636. if (typeof whereClause !== "object" || Array.isArray(whereClause))
  33637. throw new InvalidArgumentError2(
  33638. 'The provided option "where" should be an Object, but %v given.',
  33639. whereClause
  33640. );
  33641. const keys = Object.keys(whereClause);
  33642. return (data) => {
  33643. if (typeof data !== "object")
  33644. throw new InvalidArgumentError2(
  33645. "The first argument of WhereClauseTool.filter should be an Array of Object, but %v given.",
  33646. data
  33647. );
  33648. return keys.every((key) => {
  33649. if (key === "and" && key in whereClause) {
  33650. const andClause = whereClause[key];
  33651. if (Array.isArray(andClause))
  33652. return andClause.every((clause) => this._createFilter(clause)(data));
  33653. } else if (key === "or" && key in whereClause) {
  33654. const orClause = whereClause[key];
  33655. if (Array.isArray(orClause))
  33656. return orClause.some((clause) => this._createFilter(clause)(data));
  33657. }
  33658. const value = getValueByPath(data, key);
  33659. const matcher = whereClause[key];
  33660. if (Array.isArray(value)) {
  33661. if (typeof matcher === "object" && matcher !== null && "neq" in matcher && matcher.neq !== void 0) {
  33662. if (value.length === 0) return true;
  33663. return value.every((el, index) => {
  33664. const where = {};
  33665. where[index] = matcher;
  33666. return this._createFilter(where)({ ...value });
  33667. });
  33668. }
  33669. return value.some((el, index) => {
  33670. const where = {};
  33671. where[index] = matcher;
  33672. return this._createFilter(where)({ ...value });
  33673. });
  33674. }
  33675. if (this._test(matcher, value)) return true;
  33676. });
  33677. };
  33678. }
  33679. /**
  33680. * Value testing.
  33681. *
  33682. * @param {*} example
  33683. * @param {*} value
  33684. * @returns {boolean}
  33685. */
  33686. _test(example, value) {
  33687. if (example === null) {
  33688. return value === null;
  33689. }
  33690. if (example === void 0) {
  33691. return value === void 0;
  33692. }
  33693. if (example instanceof RegExp) {
  33694. if (typeof value === "string") return !!value.match(example);
  33695. return false;
  33696. }
  33697. if (typeof example === "object") {
  33698. const operatorsTest = this.getService(OperatorClauseTool).testAll(
  33699. example,
  33700. value
  33701. );
  33702. if (operatorsTest !== void 0) return operatorsTest;
  33703. }
  33704. return example == value;
  33705. }
  33706. /**
  33707. * Validate where clause.
  33708. *
  33709. * @param {WhereClause|undefined} clause
  33710. */
  33711. static validateWhereClause(clause) {
  33712. if (clause == null || typeof clause === "function") return;
  33713. if (typeof clause !== "object" || Array.isArray(clause))
  33714. throw new InvalidArgumentError2(
  33715. 'The provided option "where" should be an Object, but %v given.',
  33716. clause
  33717. );
  33718. }
  33719. };
  33720. __name(_WhereClauseTool, "WhereClauseTool");
  33721. WhereClauseTool = _WhereClauseTool;
  33722. }
  33723. });
  33724. // node_modules/@e22m4u/js-repository/src/definition/model/relations/relation-type.js
  33725. var RelationType;
  33726. var init_relation_type = __esm({
  33727. "node_modules/@e22m4u/js-repository/src/definition/model/relations/relation-type.js"() {
  33728. RelationType = {
  33729. BELONGS_TO: "belongsTo",
  33730. HAS_ONE: "hasOne",
  33731. HAS_MANY: "hasMany",
  33732. REFERENCES_MANY: "referencesMany"
  33733. };
  33734. }
  33735. });
  33736. // node_modules/@e22m4u/js-repository/src/definition/model/relations/relation-definition.js
  33737. var init_relation_definition = __esm({
  33738. "node_modules/@e22m4u/js-repository/src/definition/model/relations/relation-definition.js"() {
  33739. }
  33740. });
  33741. // node_modules/@e22m4u/js-repository/src/definition/model/relations/relations-definition-validator.js
  33742. var _RelationsDefinitionValidator, RelationsDefinitionValidator;
  33743. var init_relations_definition_validator = __esm({
  33744. "node_modules/@e22m4u/js-repository/src/definition/model/relations/relations-definition-validator.js"() {
  33745. init_src2();
  33746. init_relation_type();
  33747. init_relation_type();
  33748. init_errors2();
  33749. _RelationsDefinitionValidator = class _RelationsDefinitionValidator extends Service {
  33750. /**
  33751. * Validate.
  33752. *
  33753. * @param {string} modelName
  33754. * @param {object} relDefs
  33755. */
  33756. validate(modelName, relDefs) {
  33757. if (!modelName || typeof modelName !== "string")
  33758. throw new InvalidArgumentError2(
  33759. "The first argument of RelationsDefinitionValidator.validate should be a non-empty String, but %v given.",
  33760. modelName
  33761. );
  33762. if (!relDefs || typeof relDefs !== "object" || Array.isArray(relDefs))
  33763. throw new InvalidArgumentError2(
  33764. 'The provided option "relations" of the model %v should be an Object, but %v given.',
  33765. modelName,
  33766. relDefs
  33767. );
  33768. const relNames = Object.keys(relDefs);
  33769. relNames.forEach((relName) => {
  33770. const relDef = relDefs[relName];
  33771. this._validateRelation(modelName, relName, relDef);
  33772. });
  33773. }
  33774. /**
  33775. * Validate relation.
  33776. *
  33777. * @param {string} modelName
  33778. * @param {string} relName
  33779. * @param {object} relDef
  33780. */
  33781. _validateRelation(modelName, relName, relDef) {
  33782. if (!modelName || typeof modelName !== "string")
  33783. throw new InvalidArgumentError2(
  33784. "The first argument of RelationsDefinitionValidator._validateRelation should be a non-empty String, but %v given.",
  33785. modelName
  33786. );
  33787. if (!relName || typeof relName !== "string")
  33788. throw new InvalidArgumentError2(
  33789. "The relation name of the model %v should be a non-empty String, but %v given.",
  33790. modelName,
  33791. relName
  33792. );
  33793. if (!relDef || typeof relDef !== "object" || Array.isArray(relDef))
  33794. throw new InvalidArgumentError2(
  33795. "The relation %v of the model %v should be an Object, but %v given.",
  33796. relName,
  33797. modelName,
  33798. relDef
  33799. );
  33800. if (!relDef.type || !Object.values(RelationType).includes(relDef.type))
  33801. throw new InvalidArgumentError2(
  33802. 'The relation %v of the model %v requires the option "type" to have one of relation types: %l, but %v given.',
  33803. relName,
  33804. modelName,
  33805. Object.values(RelationType),
  33806. relDef.type
  33807. );
  33808. this._validateBelongsTo(modelName, relName, relDef);
  33809. this._validateHasOne(modelName, relName, relDef);
  33810. this._validateHasMany(modelName, relName, relDef);
  33811. this._validateReferencesMany(modelName, relName, relDef);
  33812. }
  33813. /**
  33814. * Validate "belongsTo".
  33815. *
  33816. * @example The regular "belongsTo" relation.
  33817. * ```
  33818. * {
  33819. * type: RelationType.BELONGS_TO,
  33820. * model: 'model',
  33821. * foreignKey: 'modelId', // optional
  33822. * }
  33823. * ```
  33824. *
  33825. * @example The polymorphic "belongsTo" relation.
  33826. * ```
  33827. * {
  33828. * type: RelationType.BELONGS_TO,
  33829. * polymorphic: true,
  33830. * foreignKey: 'referenceId', // optional
  33831. * discriminator: 'referenceType', // optional
  33832. * }
  33833. * ```
  33834. *
  33835. * @param {string} modelName
  33836. * @param {string} relName
  33837. * @param {object} relDef
  33838. * @private
  33839. */
  33840. _validateBelongsTo(modelName, relName, relDef) {
  33841. if (relDef.type !== RelationType.BELONGS_TO) return;
  33842. if (relDef.polymorphic) {
  33843. if (typeof relDef.polymorphic !== "boolean")
  33844. throw new InvalidArgumentError2(
  33845. 'The relation %v of the model %v has the type "belongsTo", so it expects the option "polymorphic" to be a Boolean, but %v given.',
  33846. relName,
  33847. modelName,
  33848. relDef.polymorphic
  33849. );
  33850. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  33851. throw new InvalidArgumentError2(
  33852. 'The relation %v of the model %v is a polymorphic "belongsTo" relation, so it expects the provided option "foreignKey" to be a String, but %v given.',
  33853. relName,
  33854. modelName,
  33855. relDef.foreignKey
  33856. );
  33857. if (relDef.discriminator && typeof relDef.discriminator !== "string")
  33858. throw new InvalidArgumentError2(
  33859. 'The relation %v of the model %v is a polymorphic "belongsTo" relation, so it expects the provided option "discriminator" to be a String, but %v given.',
  33860. relName,
  33861. modelName,
  33862. relDef.discriminator
  33863. );
  33864. } else {
  33865. if (!relDef.model || typeof relDef.model !== "string")
  33866. throw new InvalidArgumentError2(
  33867. 'The relation %v of the model %v has the type "belongsTo", so it requires the option "model" to be a non-empty String, but %v given.',
  33868. relName,
  33869. modelName,
  33870. relDef.model
  33871. );
  33872. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  33873. throw new InvalidArgumentError2(
  33874. 'The relation %v of the model %v has the type "belongsTo", so it expects the provided option "foreignKey" to be a String, but %v given.',
  33875. relName,
  33876. modelName,
  33877. relDef.foreignKey
  33878. );
  33879. if (relDef.discriminator)
  33880. throw new InvalidArgumentError2(
  33881. 'The relation %v of the model %v is a non-polymorphic "belongsTo" relation, so it should not have the option "discriminator" to be provided.',
  33882. relName,
  33883. modelName
  33884. );
  33885. }
  33886. }
  33887. /**
  33888. * Validate "hasOne".
  33889. *
  33890. * @example The regular "hasOne" relation.
  33891. * ```
  33892. * {
  33893. * type: RelationType.HAS_ONE,
  33894. * model: 'model',
  33895. * foreignKey: 'modelId',
  33896. * }
  33897. * ```
  33898. *
  33899. * @example The polymorphic "hasOne" relation with a target relation name.
  33900. * ```
  33901. * {
  33902. * type: RelationType.HAS_ONE,
  33903. * model: 'model',
  33904. * polymorphic: 'reference',
  33905. * }
  33906. * ```
  33907. *
  33908. * @example The polymorphic "hasOne" relation with target relation keys.
  33909. * ```
  33910. * {
  33911. * type: RelationType.HAS_ONE,
  33912. * model: 'model',
  33913. * polymorphic: true,
  33914. * foreignKey: 'referenceId',
  33915. * discriminator: 'referenceType',
  33916. * }
  33917. * ```
  33918. *
  33919. * @param {string} modelName
  33920. * @param {string} relName
  33921. * @param {object} relDef
  33922. * @private
  33923. */
  33924. _validateHasOne(modelName, relName, relDef) {
  33925. if (relDef.type !== RelationType.HAS_ONE) return;
  33926. if (!relDef.model || typeof relDef.model !== "string")
  33927. throw new InvalidArgumentError2(
  33928. 'The relation %v of the model %v has the type "hasOne", so it requires the option "model" to be a non-empty String, but %v given.',
  33929. relName,
  33930. modelName,
  33931. relDef.model
  33932. );
  33933. if (relDef.polymorphic) {
  33934. if (typeof relDef.polymorphic === "string") {
  33935. if (relDef.foreignKey)
  33936. throw new InvalidArgumentError2(
  33937. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "foreignKey" to be provided.',
  33938. relName,
  33939. modelName
  33940. );
  33941. if (relDef.discriminator)
  33942. throw new InvalidArgumentError2(
  33943. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "discriminator" to be provided.',
  33944. relName,
  33945. modelName
  33946. );
  33947. } else if (typeof relDef.polymorphic === "boolean") {
  33948. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  33949. throw new InvalidArgumentError2(
  33950. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "foreignKey" to be a non-empty String, but %v given.',
  33951. relName,
  33952. modelName,
  33953. relDef.foreignKey
  33954. );
  33955. if (!relDef.discriminator || typeof relDef.discriminator !== "string")
  33956. throw new InvalidArgumentError2(
  33957. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "discriminator" to be a non-empty String, but %v given.',
  33958. relName,
  33959. modelName,
  33960. relDef.discriminator
  33961. );
  33962. } else {
  33963. throw new InvalidArgumentError2(
  33964. 'The relation %v of the model %v has the type "hasOne", so it expects the provided option "polymorphic" to be a String or a Boolean, but %v given.',
  33965. relName,
  33966. modelName,
  33967. relDef.polymorphic
  33968. );
  33969. }
  33970. } else {
  33971. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  33972. throw new InvalidArgumentError2(
  33973. 'The relation %v of the model %v has the type "hasOne", so it requires the option "foreignKey" to be a non-empty String, but %v given.',
  33974. relName,
  33975. modelName,
  33976. relDef.foreignKey
  33977. );
  33978. if (relDef.discriminator)
  33979. throw new InvalidArgumentError2(
  33980. 'The relation %v of the model %v is a non-polymorphic "hasOne" relation, so it should not have the option "discriminator" to be provided.',
  33981. relName,
  33982. modelName
  33983. );
  33984. }
  33985. }
  33986. /**
  33987. * Validate "hasMany".
  33988. *
  33989. * @example The regular "hasMany" relation.
  33990. * ```
  33991. * {
  33992. * type: RelationType.HAS_MANY,
  33993. * model: 'model',
  33994. * foreignKey: 'modelId',
  33995. * }
  33996. * ```
  33997. *
  33998. * @example The polymorphic "hasMany" relation with a target relation name.
  33999. * ```
  34000. * {
  34001. * type: RelationType.HAS_MANY,
  34002. * model: 'model',
  34003. * polymorphic: 'reference',
  34004. * }
  34005. * ```
  34006. *
  34007. * @example The polymorphic "hasMany" relation with target relation keys.
  34008. * ```
  34009. * {
  34010. * type: RelationType.HAS_MANY,
  34011. * model: 'model',
  34012. * polymorphic: true,
  34013. * foreignKey: 'referenceId',
  34014. * discriminator: 'referenceType',
  34015. * }
  34016. * ```
  34017. *
  34018. * @param {string} modelName
  34019. * @param {string} relName
  34020. * @param {object} relDef
  34021. * @private
  34022. */
  34023. _validateHasMany(modelName, relName, relDef) {
  34024. if (relDef.type !== RelationType.HAS_MANY) return;
  34025. if (!relDef.model || typeof relDef.model !== "string")
  34026. throw new InvalidArgumentError2(
  34027. 'The relation %v of the model %v has the type "hasMany", so it requires the option "model" to be a non-empty String, but %v given.',
  34028. relName,
  34029. modelName,
  34030. relDef.model
  34031. );
  34032. if (relDef.polymorphic) {
  34033. if (typeof relDef.polymorphic === "string") {
  34034. if (relDef.foreignKey)
  34035. throw new InvalidArgumentError2(
  34036. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "foreignKey" to be provided.',
  34037. relName,
  34038. modelName
  34039. );
  34040. if (relDef.discriminator)
  34041. throw new InvalidArgumentError2(
  34042. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "discriminator" to be provided.',
  34043. relName,
  34044. modelName
  34045. );
  34046. } else if (typeof relDef.polymorphic === "boolean") {
  34047. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  34048. throw new InvalidArgumentError2(
  34049. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "foreignKey" to be a non-empty String, but %v given.',
  34050. relName,
  34051. modelName,
  34052. relDef.foreignKey
  34053. );
  34054. if (!relDef.discriminator || typeof relDef.discriminator !== "string")
  34055. throw new InvalidArgumentError2(
  34056. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "discriminator" to be a non-empty String, but %v given.',
  34057. relName,
  34058. modelName,
  34059. relDef.discriminator
  34060. );
  34061. } else {
  34062. throw new InvalidArgumentError2(
  34063. 'The relation %v of the model %v has the type "hasMany", so it expects the provided option "polymorphic" to be a String or a Boolean, but %v given.',
  34064. relName,
  34065. modelName,
  34066. relDef.polymorphic
  34067. );
  34068. }
  34069. } else {
  34070. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  34071. throw new InvalidArgumentError2(
  34072. 'The relation %v of the model %v has the type "hasMany", so it requires the option "foreignKey" to be a non-empty String, but %v given.',
  34073. relName,
  34074. modelName,
  34075. relDef.foreignKey
  34076. );
  34077. if (relDef.discriminator)
  34078. throw new InvalidArgumentError2(
  34079. 'The relation %v of the model %v is a non-polymorphic "hasMany" relation, so it should not have the option "discriminator" to be provided.',
  34080. relName,
  34081. modelName
  34082. );
  34083. }
  34084. }
  34085. /**
  34086. * Validate "referencesMany".
  34087. *
  34088. * @example
  34089. * ```
  34090. * {
  34091. * type: RelationType.REFERENCES_MANY,
  34092. * model: 'model',
  34093. * foreignKey: 'modelIds', // optional
  34094. * }
  34095. * ```
  34096. *
  34097. * @param {string} modelName
  34098. * @param {string} relName
  34099. * @param {object} relDef
  34100. * @private
  34101. */
  34102. _validateReferencesMany(modelName, relName, relDef) {
  34103. if (relDef.type !== RelationType.REFERENCES_MANY) return;
  34104. if (!relDef.model || typeof relDef.model !== "string")
  34105. throw new InvalidArgumentError2(
  34106. 'The relation %v of the model %v has the type "referencesMany", so it requires the option "model" to be a non-empty String, but %v given.',
  34107. relName,
  34108. modelName,
  34109. relDef.model
  34110. );
  34111. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  34112. throw new InvalidArgumentError2(
  34113. 'The relation %v of the model %v has the type "referencesMany", so it expects the provided option "foreignKey" to be a String, but %v given.',
  34114. relName,
  34115. modelName,
  34116. relDef.foreignKey
  34117. );
  34118. if (relDef.discriminator)
  34119. throw new InvalidArgumentError2(
  34120. 'The relation %v of the model %v has the type "referencesMany", so it should not have the option "discriminator" to be provided.',
  34121. relName,
  34122. modelName
  34123. );
  34124. }
  34125. };
  34126. __name(_RelationsDefinitionValidator, "RelationsDefinitionValidator");
  34127. RelationsDefinitionValidator = _RelationsDefinitionValidator;
  34128. }
  34129. });
  34130. // node_modules/@e22m4u/js-repository/src/definition/model/relations/index.js
  34131. var init_relations = __esm({
  34132. "node_modules/@e22m4u/js-repository/src/definition/model/relations/index.js"() {
  34133. init_relation_type();
  34134. init_relation_definition();
  34135. init_relations_definition_validator();
  34136. }
  34137. });
  34138. // node_modules/@e22m4u/js-repository/src/definition/model/properties/data-type.js
  34139. var DataType;
  34140. var init_data_type = __esm({
  34141. "node_modules/@e22m4u/js-repository/src/definition/model/properties/data-type.js"() {
  34142. DataType = {
  34143. ANY: "any",
  34144. STRING: "string",
  34145. NUMBER: "number",
  34146. BOOLEAN: "boolean",
  34147. ARRAY: "array",
  34148. OBJECT: "object"
  34149. };
  34150. }
  34151. });
  34152. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-definition.js
  34153. var init_property_definition = __esm({
  34154. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-definition.js"() {
  34155. }
  34156. });
  34157. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-uniqueness.js
  34158. var PropertyUniqueness;
  34159. var init_property_uniqueness = __esm({
  34160. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-uniqueness.js"() {
  34161. PropertyUniqueness = {
  34162. STRICT: "strict",
  34163. SPARSE: "sparse",
  34164. NON_UNIQUE: "nonUnique"
  34165. };
  34166. }
  34167. });
  34168. // node_modules/@e22m4u/js-repository/src/definition/model/properties/empty-values-definer.js
  34169. var _EmptyValuesDefiner, EmptyValuesDefiner;
  34170. var init_empty_values_definer = __esm({
  34171. "node_modules/@e22m4u/js-repository/src/definition/model/properties/empty-values-definer.js"() {
  34172. init_data_type();
  34173. init_src2();
  34174. init_utils2();
  34175. init_errors2();
  34176. _EmptyValuesDefiner = class _EmptyValuesDefiner extends Service {
  34177. /**
  34178. * Empty values map.
  34179. *
  34180. * @type {Map<string, *[]>}
  34181. */
  34182. _emptyValuesMap = /* @__PURE__ */ new Map([
  34183. [DataType.ANY, [void 0, null]],
  34184. [DataType.STRING, [void 0, null, ""]],
  34185. [DataType.NUMBER, [void 0, null, 0]],
  34186. [DataType.BOOLEAN, [void 0, null]],
  34187. [DataType.ARRAY, [void 0, null, []]],
  34188. [DataType.OBJECT, [void 0, null, {}]]
  34189. ]);
  34190. /**
  34191. * Set empty values of data type.
  34192. *
  34193. * @param {string} dataType
  34194. * @param {*[]} emptyValues
  34195. * @returns {EmptyValuesDefiner}
  34196. */
  34197. setEmptyValuesOf(dataType, emptyValues) {
  34198. if (!Object.values(DataType).includes(dataType))
  34199. throw new InvalidArgumentError2(
  34200. 'The argument "dataType" of the EmptyValuesDefiner.setEmptyValuesOf must be one of data types: %l, but %v given.',
  34201. Object.values(DataType),
  34202. dataType
  34203. );
  34204. if (!Array.isArray(emptyValues))
  34205. throw new InvalidArgumentError2(
  34206. 'The argument "emptyValues" of the EmptyValuesDefiner.setEmptyValuesOf must be an Array, but %v given.',
  34207. emptyValues
  34208. );
  34209. this._emptyValuesMap.set(dataType, emptyValues);
  34210. return this;
  34211. }
  34212. /**
  34213. * Is empty.
  34214. *
  34215. * @param {string} dataType
  34216. * @param {*} value
  34217. * @returns {boolean}
  34218. */
  34219. isEmpty(dataType, value) {
  34220. if (!Object.values(DataType).includes(dataType))
  34221. throw new InvalidArgumentError2(
  34222. 'The argument "dataType" of the EmptyValuesDefiner.isEmpty must be one of data types: %l, but %v given.',
  34223. Object.values(DataType),
  34224. dataType
  34225. );
  34226. return this._emptyValuesMap.get(dataType).some((v) => isDeepEqual(v, value));
  34227. }
  34228. };
  34229. __name(_EmptyValuesDefiner, "EmptyValuesDefiner");
  34230. EmptyValuesDefiner = _EmptyValuesDefiner;
  34231. }
  34232. });
  34233. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/property-validator.js
  34234. var init_property_validator = __esm({
  34235. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/property-validator.js"() {
  34236. }
  34237. });
  34238. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/builtin/regexp-validator.js
  34239. function regexpValidator(value, options, context) {
  34240. if (value == null || options === false) return true;
  34241. if (typeof options !== "string" && !(options instanceof RegExp))
  34242. throw new InvalidArgumentError2(
  34243. 'The validator %v requires the "options" argument as a String or RegExp, but %v given.',
  34244. context.validatorName,
  34245. options
  34246. );
  34247. if (typeof value === "string") {
  34248. const regexp = stringToRegexp(options);
  34249. return regexp.test(value);
  34250. }
  34251. throw new InvalidArgumentError2(
  34252. "The property validator %v requires a String value, but %v given.",
  34253. context.validatorName,
  34254. value
  34255. );
  34256. }
  34257. var init_regexp_validator = __esm({
  34258. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/builtin/regexp-validator.js"() {
  34259. init_utils2();
  34260. init_errors2();
  34261. __name(regexpValidator, "regexpValidator");
  34262. }
  34263. });
  34264. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/builtin/max-length-validator.js
  34265. function maxLengthValidator(value, options, context) {
  34266. if (value == null || options === false) return true;
  34267. if (typeof options !== "number")
  34268. throw new InvalidArgumentError2(
  34269. 'The validator %v requires the "options" argument as a Number, but %v given.',
  34270. context.validatorName,
  34271. options
  34272. );
  34273. if (typeof value === "string" || Array.isArray(value))
  34274. return value.length <= options;
  34275. throw new InvalidArgumentError2(
  34276. "The property validator %v requires a String or an Array value, but %v given.",
  34277. context.validatorName,
  34278. value
  34279. );
  34280. }
  34281. var init_max_length_validator = __esm({
  34282. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/builtin/max-length-validator.js"() {
  34283. init_errors2();
  34284. __name(maxLengthValidator, "maxLengthValidator");
  34285. }
  34286. });
  34287. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/builtin/min-length-validator.js
  34288. function minLengthValidator(value, options, context) {
  34289. if (value == null || options === false) return true;
  34290. if (typeof options !== "number")
  34291. throw new InvalidArgumentError2(
  34292. 'The validator %v requires the "options" argument as a Number, but %v given.',
  34293. context.validatorName,
  34294. options
  34295. );
  34296. if (typeof value === "string" || Array.isArray(value))
  34297. return value.length >= options;
  34298. throw new InvalidArgumentError2(
  34299. "The property validator %v requires a String or an Array value, but %v given.",
  34300. context.validatorName,
  34301. value
  34302. );
  34303. }
  34304. var init_min_length_validator = __esm({
  34305. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/builtin/min-length-validator.js"() {
  34306. init_errors2();
  34307. __name(minLengthValidator, "minLengthValidator");
  34308. }
  34309. });
  34310. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/builtin/index.js
  34311. var init_builtin = __esm({
  34312. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/builtin/index.js"() {
  34313. init_regexp_validator();
  34314. init_max_length_validator();
  34315. init_min_length_validator();
  34316. }
  34317. });
  34318. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/property-validator-registry.js
  34319. var _PropertyValidatorRegistry, PropertyValidatorRegistry;
  34320. var init_property_validator_registry = __esm({
  34321. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/property-validator-registry.js"() {
  34322. init_src2();
  34323. init_builtin();
  34324. init_builtin();
  34325. init_builtin();
  34326. init_errors2();
  34327. _PropertyValidatorRegistry = class _PropertyValidatorRegistry extends Service {
  34328. /**
  34329. * Validators.
  34330. *
  34331. * @type {object}
  34332. */
  34333. _validators = {
  34334. maxLength: maxLengthValidator,
  34335. minLength: minLengthValidator,
  34336. regexp: regexpValidator
  34337. };
  34338. /**
  34339. * Add validator.
  34340. *
  34341. * @param {string} name
  34342. * @param {Function} validator
  34343. * @returns {PropertyValidatorRegistry}
  34344. */
  34345. addValidator(name, validator) {
  34346. if (!name || typeof name !== "string")
  34347. throw new InvalidArgumentError2(
  34348. "A name of the property validator must be a non-empty String, but %v given.",
  34349. name
  34350. );
  34351. if (name in this._validators)
  34352. throw new InvalidArgumentError2(
  34353. "The property validator %v is already defined.",
  34354. name
  34355. );
  34356. if (typeof validator !== "function")
  34357. throw new InvalidArgumentError2(
  34358. "The property validator %v must be a Function, but %v given.",
  34359. name,
  34360. validator
  34361. );
  34362. this._validators[name] = validator;
  34363. return this;
  34364. }
  34365. /**
  34366. * Has validator.
  34367. *
  34368. * @param {string} name
  34369. * @returns {boolean}
  34370. */
  34371. hasValidator(name) {
  34372. return Boolean(this._validators[name]);
  34373. }
  34374. /**
  34375. * Get validator.
  34376. *
  34377. * @param {string} name
  34378. * @returns {Function}
  34379. */
  34380. getValidator(name) {
  34381. const validator = this._validators[name];
  34382. if (!validator)
  34383. throw new InvalidArgumentError2(
  34384. "The property validator %v is not defined.",
  34385. name
  34386. );
  34387. return validator;
  34388. }
  34389. };
  34390. __name(_PropertyValidatorRegistry, "PropertyValidatorRegistry");
  34391. PropertyValidatorRegistry = _PropertyValidatorRegistry;
  34392. }
  34393. });
  34394. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/index.js
  34395. var init_property_validator2 = __esm({
  34396. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-validator/index.js"() {
  34397. init_property_validator();
  34398. init_property_validator_registry();
  34399. }
  34400. });
  34401. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/property-transformer.js
  34402. var init_property_transformer = __esm({
  34403. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/property-transformer.js"() {
  34404. }
  34405. });
  34406. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/trim-transformer.js
  34407. function trimTransformer(value, options, context) {
  34408. if (value == null) return value;
  34409. if (typeof value === "string") return value.trim();
  34410. throw new InvalidArgumentError2(
  34411. "The property transformer %v requires a String value, but %v given.",
  34412. context.transformerName,
  34413. value
  34414. );
  34415. }
  34416. var init_trim_transformer = __esm({
  34417. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/trim-transformer.js"() {
  34418. init_errors2();
  34419. __name(trimTransformer, "trimTransformer");
  34420. }
  34421. });
  34422. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/to-lower-case-transformer.js
  34423. function toLowerCaseTransformer(value, options, context) {
  34424. if (value == null) return value;
  34425. if (typeof value === "string") return value.toLowerCase();
  34426. throw new InvalidArgumentError2(
  34427. "The property transformer %v requires a String value, but %v given.",
  34428. context.transformerName,
  34429. value
  34430. );
  34431. }
  34432. var init_to_lower_case_transformer = __esm({
  34433. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/to-lower-case-transformer.js"() {
  34434. init_errors2();
  34435. __name(toLowerCaseTransformer, "toLowerCaseTransformer");
  34436. }
  34437. });
  34438. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/to-upper-case-transformer.js
  34439. function toUpperCaseTransformer(value, options, context) {
  34440. if (value == null) return value;
  34441. if (typeof value === "string") return value.toUpperCase();
  34442. throw new InvalidArgumentError2(
  34443. "The property transformer %v requires a String value, but %v given.",
  34444. context.transformerName,
  34445. value
  34446. );
  34447. }
  34448. var init_to_upper_case_transformer = __esm({
  34449. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/to-upper-case-transformer.js"() {
  34450. init_errors2();
  34451. __name(toUpperCaseTransformer, "toUpperCaseTransformer");
  34452. }
  34453. });
  34454. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/to-title-case-transformer.js
  34455. function toTitleCaseTransformer(value, options, context) {
  34456. if (value == null) return value;
  34457. if (typeof value === "string")
  34458. return value.replace(new RegExp("\\p{L}\\S*", "gu"), (text) => {
  34459. return text.charAt(0).toUpperCase() + text.substring(1).toLowerCase();
  34460. });
  34461. throw new InvalidArgumentError2(
  34462. "The property transformer %v requires a String value, but %v given.",
  34463. context.transformerName,
  34464. value
  34465. );
  34466. }
  34467. var init_to_title_case_transformer = __esm({
  34468. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/to-title-case-transformer.js"() {
  34469. init_errors2();
  34470. __name(toTitleCaseTransformer, "toTitleCaseTransformer");
  34471. }
  34472. });
  34473. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/index.js
  34474. var init_builtin2 = __esm({
  34475. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/builtin/index.js"() {
  34476. init_trim_transformer();
  34477. init_to_lower_case_transformer();
  34478. init_to_upper_case_transformer();
  34479. init_to_title_case_transformer();
  34480. }
  34481. });
  34482. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/property-transformer-registry.js
  34483. var _PropertyTransformerRegistry, PropertyTransformerRegistry;
  34484. var init_property_transformer_registry = __esm({
  34485. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/property-transformer-registry.js"() {
  34486. init_src2();
  34487. init_builtin2();
  34488. init_builtin2();
  34489. init_builtin2();
  34490. init_builtin2();
  34491. init_errors2();
  34492. _PropertyTransformerRegistry = class _PropertyTransformerRegistry extends Service {
  34493. /**
  34494. * Transformers.
  34495. *
  34496. * @type {object}
  34497. */
  34498. _transformers = {
  34499. trim: trimTransformer,
  34500. toUpperCase: toUpperCaseTransformer,
  34501. toLowerCase: toLowerCaseTransformer,
  34502. toTitleCase: toTitleCaseTransformer
  34503. };
  34504. /**
  34505. * Add transformer.
  34506. *
  34507. * @param {string} name
  34508. * @param {Function} transformer
  34509. * @returns {PropertyTransformerRegistry}
  34510. */
  34511. addTransformer(name, transformer) {
  34512. if (!name || typeof name !== "string")
  34513. throw new InvalidArgumentError2(
  34514. "A name of the property transformer must be a non-empty String, but %v given.",
  34515. name
  34516. );
  34517. if (name in this._transformers)
  34518. throw new InvalidArgumentError2(
  34519. "The property transformer %v is already defined.",
  34520. name
  34521. );
  34522. if (typeof transformer !== "function")
  34523. throw new InvalidArgumentError2(
  34524. "The property transformer %v must be a Function, but %v given.",
  34525. name,
  34526. transformer
  34527. );
  34528. this._transformers[name] = transformer;
  34529. return this;
  34530. }
  34531. /**
  34532. * Has transformer.
  34533. *
  34534. * @param {string} name
  34535. * @returns {boolean}
  34536. */
  34537. hasTransformer(name) {
  34538. return Boolean(this._transformers[name]);
  34539. }
  34540. /**
  34541. * Get transformer.
  34542. *
  34543. * @param {string} name
  34544. * @returns {Function}
  34545. */
  34546. getTransformer(name) {
  34547. const transformer = this._transformers[name];
  34548. if (!transformer)
  34549. throw new InvalidArgumentError2(
  34550. "The property transformer %v is not defined.",
  34551. name
  34552. );
  34553. return transformer;
  34554. }
  34555. };
  34556. __name(_PropertyTransformerRegistry, "PropertyTransformerRegistry");
  34557. PropertyTransformerRegistry = _PropertyTransformerRegistry;
  34558. }
  34559. });
  34560. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/index.js
  34561. var init_property_transformer2 = __esm({
  34562. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-transformer/index.js"() {
  34563. init_property_transformer();
  34564. init_property_transformer_registry();
  34565. }
  34566. });
  34567. // node_modules/@e22m4u/js-repository/src/definition/definition-registry.js
  34568. var _DefinitionRegistry, DefinitionRegistry;
  34569. var init_definition_registry = __esm({
  34570. "node_modules/@e22m4u/js-repository/src/definition/definition-registry.js"() {
  34571. init_src2();
  34572. init_errors2();
  34573. init_model();
  34574. init_definition();
  34575. _DefinitionRegistry = class _DefinitionRegistry extends Service {
  34576. /**
  34577. * Datasources.
  34578. *
  34579. * @type {object}
  34580. */
  34581. _datasources = {};
  34582. /**
  34583. * Models.
  34584. *
  34585. * @type {object}
  34586. */
  34587. _models = {};
  34588. /**
  34589. * Add datasource.
  34590. *
  34591. * @param {object} datasourceDef
  34592. */
  34593. addDatasource(datasourceDef) {
  34594. this.getService(DatasourceDefinitionValidator).validate(datasourceDef);
  34595. const name = datasourceDef.name;
  34596. if (name in this._datasources)
  34597. throw new InvalidArgumentError2(
  34598. "The datasource %v is already defined.",
  34599. name
  34600. );
  34601. this._datasources[name] = datasourceDef;
  34602. }
  34603. /**
  34604. * Has datasource.
  34605. *
  34606. * @param {string} name
  34607. * @returns {boolean}
  34608. */
  34609. hasDatasource(name) {
  34610. return Boolean(this._datasources[name]);
  34611. }
  34612. /**
  34613. * Get datasource.
  34614. *
  34615. * @param {string} name
  34616. * @returns {object}
  34617. */
  34618. getDatasource(name) {
  34619. const datasourceDef = this._datasources[name];
  34620. if (!datasourceDef)
  34621. throw new InvalidArgumentError2("The datasource %v is not defined.", name);
  34622. return datasourceDef;
  34623. }
  34624. /**
  34625. * Add model.
  34626. *
  34627. * @param {object} modelDef
  34628. */
  34629. addModel(modelDef) {
  34630. this.getService(ModelDefinitionValidator).validate(modelDef);
  34631. const name = modelDef.name;
  34632. if (name in this._models)
  34633. throw new InvalidArgumentError2("The model %v is already defined.", name);
  34634. this._models[name] = modelDef;
  34635. }
  34636. /**
  34637. * Has model.
  34638. *
  34639. * @param {string} name
  34640. * @returns {boolean}
  34641. */
  34642. hasModel(name) {
  34643. return Boolean(this._models[name]);
  34644. }
  34645. /**
  34646. * Get model.
  34647. *
  34648. * @param {string} name
  34649. * @returns {object}
  34650. */
  34651. getModel(name) {
  34652. const modelDef = this._models[name];
  34653. if (!modelDef)
  34654. throw new InvalidArgumentError2("The model %v is not defined.", name);
  34655. return modelDef;
  34656. }
  34657. };
  34658. __name(_DefinitionRegistry, "DefinitionRegistry");
  34659. DefinitionRegistry = _DefinitionRegistry;
  34660. }
  34661. });
  34662. // node_modules/@e22m4u/js-repository/src/definition/model/model-definition-utils.js
  34663. var DEFAULT_PRIMARY_KEY_PROPERTY_NAME, _ModelDefinitionUtils, ModelDefinitionUtils;
  34664. var init_model_definition_utils = __esm({
  34665. "node_modules/@e22m4u/js-repository/src/definition/model/model-definition-utils.js"() {
  34666. init_src2();
  34667. init_properties();
  34668. init_utils2();
  34669. init_utils2();
  34670. init_properties();
  34671. init_errors2();
  34672. init_definition_registry();
  34673. DEFAULT_PRIMARY_KEY_PROPERTY_NAME = "id";
  34674. _ModelDefinitionUtils = class _ModelDefinitionUtils extends Service {
  34675. /**
  34676. * Get primary key as property name.
  34677. *
  34678. * @param {string} modelName
  34679. * @returns {string}
  34680. */
  34681. getPrimaryKeyAsPropertyName(modelName) {
  34682. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  34683. const propNames = Object.keys(propDefs).filter((propName) => {
  34684. const propDef = propDefs[propName];
  34685. return propDef && typeof propDef === "object" && propDef.primaryKey;
  34686. });
  34687. if (propNames.length < 1) {
  34688. const isDefaultPrimaryKeyAlreadyInUse = Object.keys(propDefs).includes(
  34689. DEFAULT_PRIMARY_KEY_PROPERTY_NAME
  34690. );
  34691. if (isDefaultPrimaryKeyAlreadyInUse)
  34692. throw new InvalidArgumentError2(
  34693. 'The property name %v of the model %v is defined as a regular property. In this case, a primary key should be defined explicitly. Do use the option "primaryKey" to specify the primary key.',
  34694. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  34695. modelName
  34696. );
  34697. return DEFAULT_PRIMARY_KEY_PROPERTY_NAME;
  34698. }
  34699. return propNames[0];
  34700. }
  34701. /**
  34702. * Get primary key as column name.
  34703. *
  34704. * @param {string} modelName
  34705. * @returns {string}
  34706. */
  34707. getPrimaryKeyAsColumnName(modelName) {
  34708. const pkPropName = this.getPrimaryKeyAsPropertyName(modelName);
  34709. let pkColName;
  34710. try {
  34711. pkColName = this.getColumnNameByPropertyName(modelName, pkPropName);
  34712. } catch (error) {
  34713. if (!(error instanceof InvalidArgumentError2)) throw error;
  34714. }
  34715. if (pkColName === void 0) return pkPropName;
  34716. return pkColName;
  34717. }
  34718. /**
  34719. * Get table name by model name.
  34720. *
  34721. * @param {string} modelName
  34722. * @returns {string}
  34723. */
  34724. getTableNameByModelName(modelName) {
  34725. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  34726. return modelDef.tableName ?? modelName;
  34727. }
  34728. /**
  34729. * Get column name by property name.
  34730. *
  34731. * @param {string} modelName
  34732. * @param {string} propertyName
  34733. * @returns {string}
  34734. */
  34735. getColumnNameByPropertyName(modelName, propertyName) {
  34736. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  34737. const propDef = propDefs[propertyName];
  34738. if (!propDef)
  34739. throw new InvalidArgumentError2(
  34740. "The model %v does not have the property %v.",
  34741. modelName,
  34742. propertyName
  34743. );
  34744. if (propDef && typeof propDef === "object")
  34745. return propDef.columnName ?? propertyName;
  34746. return propertyName;
  34747. }
  34748. /**
  34749. * Get default property value.
  34750. *
  34751. * @param {string} modelName
  34752. * @param {string} propertyName
  34753. * @returns {*}
  34754. */
  34755. getDefaultPropertyValue(modelName, propertyName) {
  34756. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  34757. const propDef = propDefs[propertyName];
  34758. if (!propDef)
  34759. throw new InvalidArgumentError2(
  34760. "The model %v does not have the property %v.",
  34761. modelName,
  34762. propertyName
  34763. );
  34764. if (propDef && typeof propDef === "object")
  34765. return propDef.default instanceof Function ? propDef.default() : propDef.default;
  34766. }
  34767. /**
  34768. * Set default values for empty properties.
  34769. *
  34770. * @param {string} modelName
  34771. * @param {object} modelData
  34772. * @param {boolean|undefined} onlyProvidedProperties
  34773. * @returns {object}
  34774. */
  34775. setDefaultValuesToEmptyProperties(modelName, modelData, onlyProvidedProperties = false) {
  34776. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  34777. const propNames = onlyProvidedProperties ? Object.keys(modelData) : Object.keys(propDefs);
  34778. const extendedData = cloneDeep(modelData);
  34779. const emptyValueDefiner = this.getService(EmptyValuesDefiner);
  34780. propNames.forEach((propName) => {
  34781. const propDef = propDefs[propName];
  34782. const propValue = extendedData[propName];
  34783. const propType = propDef != null ? this.getDataTypeFromPropertyDefinition(propDef) : DataType.ANY;
  34784. const isEmpty = emptyValueDefiner.isEmpty(propType, propValue);
  34785. if (!isEmpty) return;
  34786. if (propDef && typeof propDef === "object" && propDef.default !== void 0) {
  34787. extendedData[propName] = this.getDefaultPropertyValue(
  34788. modelName,
  34789. propName
  34790. );
  34791. }
  34792. });
  34793. return extendedData;
  34794. }
  34795. /**
  34796. * Convert property names to column names.
  34797. *
  34798. * @param {string} modelName
  34799. * @param {object} modelData
  34800. * @returns {object}
  34801. */
  34802. convertPropertyNamesToColumnNames(modelName, modelData) {
  34803. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  34804. const propNames = Object.keys(propDefs);
  34805. const convertedData = cloneDeep(modelData);
  34806. propNames.forEach((propName) => {
  34807. if (!(propName in convertedData)) return;
  34808. const colName = this.getColumnNameByPropertyName(modelName, propName);
  34809. if (propName === colName) return;
  34810. const propValue = convertedData[propName];
  34811. delete convertedData[propName];
  34812. convertedData[colName] = propValue;
  34813. });
  34814. return convertedData;
  34815. }
  34816. /**
  34817. * Convert column names to property names.
  34818. *
  34819. * @param {string} modelName
  34820. * @param {object} tableData
  34821. * @returns {object}
  34822. */
  34823. convertColumnNamesToPropertyNames(modelName, tableData) {
  34824. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  34825. const propNames = Object.keys(propDefs);
  34826. const convertedData = cloneDeep(tableData);
  34827. propNames.forEach((propName) => {
  34828. const colName = this.getColumnNameByPropertyName(modelName, propName);
  34829. if (!(colName in convertedData) || colName === propName) return;
  34830. const colValue = convertedData[colName];
  34831. delete convertedData[colName];
  34832. convertedData[propName] = colValue;
  34833. });
  34834. return convertedData;
  34835. }
  34836. /**
  34837. * Get data type by property name.
  34838. *
  34839. * @param {string} modelName
  34840. * @param {string} propertyName
  34841. * @returns {string}
  34842. */
  34843. getDataTypeByPropertyName(modelName, propertyName) {
  34844. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  34845. const propDef = propDefs[propertyName];
  34846. if (!propDef) {
  34847. const pkPropName = this.getPrimaryKeyAsPropertyName(modelName);
  34848. if (pkPropName === propertyName) return DataType.ANY;
  34849. throw new InvalidArgumentError2(
  34850. "The model %v does not have the property %v.",
  34851. modelName,
  34852. propertyName
  34853. );
  34854. }
  34855. if (typeof propDef === "string") return propDef;
  34856. return propDef.type;
  34857. }
  34858. /**
  34859. * Get data type from property definition.
  34860. *
  34861. * @param {object} propDef
  34862. * @returns {string}
  34863. */
  34864. getDataTypeFromPropertyDefinition(propDef) {
  34865. if ((!propDef || typeof propDef !== "object") && !Object.values(DataType).includes(propDef)) {
  34866. throw new InvalidArgumentError2(
  34867. 'The argument "propDef" of the ModelDefinitionUtils.getDataTypeFromPropertyDefinition should be an Object or the DataType enum, but %v given.',
  34868. propDef
  34869. );
  34870. }
  34871. if (typeof propDef === "string") return propDef;
  34872. const dataType = propDef.type;
  34873. if (!Object.values(DataType).includes(dataType))
  34874. throw new InvalidArgumentError2(
  34875. 'The given Object to the ModelDefinitionUtils.getDataTypeFromPropertyDefinition should have the "type" property with one of values: %l, but %v given.',
  34876. Object.values(DataType),
  34877. propDef.type
  34878. );
  34879. return dataType;
  34880. }
  34881. /**
  34882. * Get own properties definition of primary keys.
  34883. *
  34884. * @param {string} modelName
  34885. * @returns {object}
  34886. */
  34887. getOwnPropertiesDefinitionOfPrimaryKeys(modelName) {
  34888. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  34889. const propDefs = modelDef.properties ?? {};
  34890. const pkPropNames = Object.keys(propDefs).filter((propName) => {
  34891. const propDef = propDefs[propName];
  34892. return typeof propDef === "object" && propDef.primaryKey;
  34893. });
  34894. return pkPropNames.reduce((a, k) => ({ ...a, [k]: propDefs[k] }), {});
  34895. }
  34896. /**
  34897. * Get own properties definition without primary keys.
  34898. *
  34899. * @param {string} modelName
  34900. * @returns {object}
  34901. */
  34902. getOwnPropertiesDefinitionWithoutPrimaryKeys(modelName) {
  34903. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  34904. const propDefs = modelDef.properties ?? {};
  34905. return Object.keys(propDefs).reduce((result, propName) => {
  34906. const propDef = propDefs[propName];
  34907. if (typeof propDef === "object" && propDef.primaryKey) return result;
  34908. return { ...result, [propName]: propDef };
  34909. }, {});
  34910. }
  34911. /**
  34912. * Get properties definition in base model hierarchy.
  34913. *
  34914. * @param {string} modelName
  34915. * @returns {object}
  34916. */
  34917. getPropertiesDefinitionInBaseModelHierarchy(modelName) {
  34918. let result = {};
  34919. let pkPropDefs = {};
  34920. const recursion = /* @__PURE__ */ __name((currModelName, prevModelName = void 0) => {
  34921. if (currModelName === prevModelName)
  34922. throw new InvalidArgumentError2(
  34923. "The model %v has a circular inheritance.",
  34924. currModelName
  34925. );
  34926. if (Object.keys(pkPropDefs).length === 0) {
  34927. pkPropDefs = this.getOwnPropertiesDefinitionOfPrimaryKeys(currModelName);
  34928. result = { ...result, ...pkPropDefs };
  34929. }
  34930. const regularPropDefs = this.getOwnPropertiesDefinitionWithoutPrimaryKeys(currModelName);
  34931. result = { ...regularPropDefs, ...result };
  34932. const modelDef = this.getService(DefinitionRegistry).getModel(currModelName);
  34933. if (modelDef.base) recursion(modelDef.base, currModelName);
  34934. }, "recursion");
  34935. recursion(modelName);
  34936. return result;
  34937. }
  34938. /**
  34939. * Get own relations definition.
  34940. *
  34941. * @param {string} modelName
  34942. * @returns {object}
  34943. */
  34944. getOwnRelationsDefinition(modelName) {
  34945. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  34946. return modelDef.relations ?? {};
  34947. }
  34948. /**
  34949. * Get relations definition in base model hierarchy.
  34950. *
  34951. * @param {string} modelName
  34952. * @returns {object}
  34953. */
  34954. getRelationsDefinitionInBaseModelHierarchy(modelName) {
  34955. let result = {};
  34956. const recursion = /* @__PURE__ */ __name((currModelName, prevModelName = void 0) => {
  34957. if (currModelName === prevModelName)
  34958. throw new InvalidArgumentError2(
  34959. "The model %v has a circular inheritance.",
  34960. currModelName
  34961. );
  34962. const modelDef = this.getService(DefinitionRegistry).getModel(currModelName);
  34963. const ownRelDefs = modelDef.relations ?? {};
  34964. result = { ...ownRelDefs, ...result };
  34965. if (modelDef.base) recursion(modelDef.base, currModelName);
  34966. }, "recursion");
  34967. recursion(modelName);
  34968. return result;
  34969. }
  34970. /**
  34971. * Get relation definition by name.
  34972. *
  34973. * @param {string} modelName
  34974. * @param {string} relationName
  34975. * @returns {object}
  34976. */
  34977. getRelationDefinitionByName(modelName, relationName) {
  34978. const relDefs = this.getRelationsDefinitionInBaseModelHierarchy(modelName);
  34979. const relNames = Object.keys(relDefs);
  34980. let foundDef;
  34981. for (const relName of relNames) {
  34982. if (relName === relationName) {
  34983. foundDef = relDefs[relName];
  34984. break;
  34985. }
  34986. }
  34987. if (!foundDef)
  34988. throw new InvalidArgumentError2(
  34989. "The model %v does not have relation name %v.",
  34990. modelName,
  34991. relationName
  34992. );
  34993. return foundDef;
  34994. }
  34995. /**
  34996. * Exclude object keys by relation names.
  34997. *
  34998. * @param {string} modelName
  34999. * @param {object} modelData
  35000. * @returns {object}
  35001. */
  35002. excludeObjectKeysByRelationNames(modelName, modelData) {
  35003. if (!modelData || typeof modelData !== "object" || Array.isArray(modelData))
  35004. throw new InvalidArgumentError2(
  35005. "The second argument of ModelDefinitionUtils.excludeObjectKeysByRelationNames should be an Object, but %v given.",
  35006. modelData
  35007. );
  35008. const relDefs = this.getRelationsDefinitionInBaseModelHierarchy(modelName);
  35009. const relNames = Object.keys(relDefs);
  35010. return excludeObjectKeys(modelData, relNames);
  35011. }
  35012. };
  35013. __name(_ModelDefinitionUtils, "ModelDefinitionUtils");
  35014. ModelDefinitionUtils = _ModelDefinitionUtils;
  35015. }
  35016. });
  35017. // node_modules/@e22m4u/js-repository/src/definition/model/properties/property-uniqueness-validator.js
  35018. var _PropertyUniquenessValidator, PropertyUniquenessValidator;
  35019. var init_property_uniqueness_validator = __esm({
  35020. "node_modules/@e22m4u/js-repository/src/definition/model/properties/property-uniqueness-validator.js"() {
  35021. init_data_type();
  35022. init_src2();
  35023. init_utils2();
  35024. init_property_uniqueness();
  35025. init_empty_values_definer();
  35026. init_errors2();
  35027. init_model_definition_utils();
  35028. _PropertyUniquenessValidator = class _PropertyUniquenessValidator extends Service {
  35029. /**
  35030. * Validate.
  35031. *
  35032. * @param {Function} countMethod
  35033. * @param {string} methodName
  35034. * @param {string} modelName
  35035. * @param {object} modelData
  35036. * @param {*} modelId
  35037. * @returns {Promise<undefined>}
  35038. */
  35039. async validate(countMethod, methodName, modelName, modelData, modelId = void 0) {
  35040. if (typeof countMethod !== "function")
  35041. throw new InvalidArgumentError2(
  35042. 'The parameter "countMethod" of the PropertyUniquenessValidator must be a Function, but %v given.',
  35043. countMethod
  35044. );
  35045. if (!methodName || typeof methodName !== "string")
  35046. throw new InvalidArgumentError2(
  35047. 'The parameter "methodName" of the PropertyUniquenessValidator must be a non-empty String, but %v given.',
  35048. methodName
  35049. );
  35050. if (!modelName || typeof modelName !== "string")
  35051. throw new InvalidArgumentError2(
  35052. 'The parameter "modelName" of the PropertyUniquenessValidator must be a non-empty String, but %v given.',
  35053. modelName
  35054. );
  35055. if (!isPureObject(modelData))
  35056. throw new InvalidArgumentError2(
  35057. "The data of the model %v should be an Object, but %v given.",
  35058. modelName,
  35059. modelData
  35060. );
  35061. const propDefs = this.getService(
  35062. ModelDefinitionUtils
  35063. ).getPropertiesDefinitionInBaseModelHierarchy(modelName);
  35064. const isPartial = methodName === "patch" || methodName === "patchById";
  35065. const propNames = Object.keys(isPartial ? modelData : propDefs);
  35066. const idProp = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  35067. modelName
  35068. );
  35069. const createError = /* @__PURE__ */ __name((propName, propValue) => new InvalidArgumentError2(
  35070. "An existing document of the model %v already has the property %v with the value %v and should be unique.",
  35071. modelName,
  35072. propName,
  35073. propValue
  35074. ), "createError");
  35075. let willBeReplaced = void 0;
  35076. const emptyValuesDefiner = this.getService(EmptyValuesDefiner);
  35077. for (const propName of propNames) {
  35078. const propDef = propDefs[propName];
  35079. if (!propDef || typeof propDef === "string" || !propDef.unique || propDef.unique === PropertyUniqueness.NON_UNIQUE) {
  35080. continue;
  35081. }
  35082. const propValue = modelData[propName];
  35083. if (propDef.unique === PropertyUniqueness.SPARSE) {
  35084. const propType = propDef.type || DataType.ANY;
  35085. const isEmpty = emptyValuesDefiner.isEmpty(propType, propValue);
  35086. if (isEmpty) continue;
  35087. }
  35088. if (methodName === "create") {
  35089. const count = await countMethod({ [propName]: propValue });
  35090. if (count > 0) throw createError(propName, propValue);
  35091. } else if (methodName === "replaceById") {
  35092. const count = await countMethod({
  35093. [idProp]: { neq: modelId },
  35094. [propName]: propValue
  35095. });
  35096. if (count > 0) throw createError(propName, propValue);
  35097. } else if (methodName === "replaceOrCreate") {
  35098. const idFromData = modelData[idProp];
  35099. if (willBeReplaced == null && idFromData != null) {
  35100. const count = await countMethod({ [idProp]: idFromData });
  35101. willBeReplaced = count > 0;
  35102. }
  35103. if (willBeReplaced) {
  35104. const count = await countMethod({
  35105. [idProp]: { neq: idFromData },
  35106. [propName]: propValue
  35107. });
  35108. if (count > 0) throw createError(propName, propValue);
  35109. } else {
  35110. const count = await countMethod({ [propName]: propValue });
  35111. if (count > 0) throw createError(propName, propValue);
  35112. }
  35113. } else if (methodName === "patch") {
  35114. const count = await countMethod({ [propName]: propValue });
  35115. if (count > 0) throw createError(propName, propValue);
  35116. } else if (methodName === "patchById") {
  35117. const count = await countMethod({
  35118. [idProp]: { neq: modelId },
  35119. [propName]: propValue
  35120. });
  35121. if (count > 0) throw createError(propName, propValue);
  35122. } else {
  35123. throw new InvalidArgumentError2(
  35124. "The PropertyUniquenessValidator does not support the adapter method %v.",
  35125. methodName
  35126. );
  35127. }
  35128. }
  35129. }
  35130. };
  35131. __name(_PropertyUniquenessValidator, "PropertyUniquenessValidator");
  35132. PropertyUniquenessValidator = _PropertyUniquenessValidator;
  35133. }
  35134. });
  35135. // node_modules/@e22m4u/js-repository/src/definition/model/properties/primary-keys-definition-validator.js
  35136. var _PrimaryKeysDefinitionValidator, PrimaryKeysDefinitionValidator;
  35137. var init_primary_keys_definition_validator = __esm({
  35138. "node_modules/@e22m4u/js-repository/src/definition/model/properties/primary-keys-definition-validator.js"() {
  35139. init_src2();
  35140. init_errors2();
  35141. init_model_definition_utils();
  35142. _PrimaryKeysDefinitionValidator = class _PrimaryKeysDefinitionValidator extends Service {
  35143. /**
  35144. * Validate.
  35145. *
  35146. * @param {string} modelName
  35147. * @param {object} propDefs
  35148. */
  35149. validate(modelName, propDefs) {
  35150. const propNames = Object.keys(propDefs).filter((propName) => {
  35151. const propDef = propDefs[propName];
  35152. return propDef && typeof propDef === "object" && propDef.primaryKey;
  35153. });
  35154. if (propNames.length < 1) {
  35155. const isDefaultPrimaryKeyAlreadyInUse = Object.keys(propDefs).includes(DEFAULT_PRIMARY_KEY_PROPERTY_NAME);
  35156. if (isDefaultPrimaryKeyAlreadyInUse)
  35157. throw new InvalidArgumentError2(
  35158. 'The property name %v of the model %v is defined as a regular property. In this case, a primary key should be defined explicitly. Do use the option "primaryKey" to specify the primary key.',
  35159. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  35160. modelName
  35161. );
  35162. return;
  35163. }
  35164. if (propNames.length > 1)
  35165. throw new InvalidArgumentError2(
  35166. "The model definition %v should not have multiple primary keys, but %v keys given.",
  35167. modelName,
  35168. propNames.length
  35169. );
  35170. const pkPropName = propNames[0];
  35171. const pkPropDef = propDefs[pkPropName];
  35172. if (pkPropDef && typeof pkPropDef === "object" && pkPropDef.default !== void 0) {
  35173. throw new InvalidArgumentError2(
  35174. "Do not specify a default value for the primary key %v of the model %v.",
  35175. pkPropName,
  35176. modelName
  35177. );
  35178. }
  35179. }
  35180. };
  35181. __name(_PrimaryKeysDefinitionValidator, "PrimaryKeysDefinitionValidator");
  35182. PrimaryKeysDefinitionValidator = _PrimaryKeysDefinitionValidator;
  35183. }
  35184. });
  35185. // node_modules/@e22m4u/js-repository/src/definition/model/properties/properties-definition-validator.js
  35186. var _PropertiesDefinitionValidator, PropertiesDefinitionValidator;
  35187. var init_properties_definition_validator = __esm({
  35188. "node_modules/@e22m4u/js-repository/src/definition/model/properties/properties-definition-validator.js"() {
  35189. init_src2();
  35190. init_data_type();
  35191. init_utils2();
  35192. init_property_uniqueness();
  35193. init_errors2();
  35194. init_property_validator2();
  35195. init_property_transformer2();
  35196. init_primary_keys_definition_validator();
  35197. _PropertiesDefinitionValidator = class _PropertiesDefinitionValidator extends Service {
  35198. /**
  35199. * Validate.
  35200. *
  35201. * @param {string} modelName
  35202. * @param {object} propDefs
  35203. */
  35204. validate(modelName, propDefs) {
  35205. if (!modelName || typeof modelName !== "string")
  35206. throw new InvalidArgumentError2(
  35207. "The first argument of PropertiesDefinitionValidator.validate should be a non-empty String, but %v given.",
  35208. modelName
  35209. );
  35210. if (!propDefs || typeof propDefs !== "object" || Array.isArray(propDefs)) {
  35211. throw new InvalidArgumentError2(
  35212. 'The provided option "properties" of the model %v should be an Object, but %v given.',
  35213. modelName,
  35214. propDefs
  35215. );
  35216. }
  35217. const propNames = Object.keys(propDefs);
  35218. propNames.forEach((propName) => {
  35219. const propDef = propDefs[propName];
  35220. this._validateProperty(modelName, propName, propDef);
  35221. });
  35222. this.getService(PrimaryKeysDefinitionValidator).validate(
  35223. modelName,
  35224. propDefs
  35225. );
  35226. }
  35227. /**
  35228. * Validate property.
  35229. *
  35230. * @param {string} modelName
  35231. * @param {string} propName
  35232. * @param {object} propDef
  35233. */
  35234. _validateProperty(modelName, propName, propDef) {
  35235. if (!modelName || typeof modelName !== "string")
  35236. throw new InvalidArgumentError2(
  35237. "The first argument of PropertiesDefinitionValidator._validateProperty should be a non-empty String, but %v given.",
  35238. modelName
  35239. );
  35240. if (!propName || typeof propName !== "string")
  35241. throw new InvalidArgumentError2(
  35242. "The property name of the model %v should be a non-empty String, but %v given.",
  35243. modelName,
  35244. propName
  35245. );
  35246. if (!propDef)
  35247. throw new InvalidArgumentError2(
  35248. "The property %v of the model %v should have a property definition, but %v given.",
  35249. propName,
  35250. modelName,
  35251. propDef
  35252. );
  35253. if (typeof propDef === "string") {
  35254. if (!Object.values(DataType).includes(propDef))
  35255. throw new InvalidArgumentError2(
  35256. "In case of a short property definition, the property %v of the model %v should have one of data types: %l, but %v given.",
  35257. propName,
  35258. modelName,
  35259. Object.values(DataType),
  35260. propDef
  35261. );
  35262. return;
  35263. }
  35264. if (!propDef || typeof propDef !== "object" || Array.isArray(propDef)) {
  35265. throw new InvalidArgumentError2(
  35266. "In case of a full property definition, the property %v of the model %v should be an Object, but %v given.",
  35267. propName,
  35268. modelName,
  35269. propDef
  35270. );
  35271. }
  35272. if (!propDef.type || !Object.values(DataType).includes(propDef.type))
  35273. throw new InvalidArgumentError2(
  35274. 'The property %v of the model %v requires the option "type" to have one of data types: %l, but %v given.',
  35275. propName,
  35276. modelName,
  35277. Object.values(DataType),
  35278. propDef.type
  35279. );
  35280. if (propDef.itemType && !Object.values(DataType).includes(propDef.itemType)) {
  35281. throw new InvalidArgumentError2(
  35282. 'The provided option "itemType" of the property %v in the model %v should have one of data types: %l, but %v given.',
  35283. propName,
  35284. modelName,
  35285. Object.values(DataType),
  35286. propDef.itemType
  35287. );
  35288. }
  35289. if (propDef.model && typeof propDef.model !== "string")
  35290. throw new InvalidArgumentError2(
  35291. 'The provided option "model" of the property %v in the model %v should be a String, but %v given.',
  35292. propName,
  35293. modelName,
  35294. propDef.model
  35295. );
  35296. if (propDef.primaryKey && typeof propDef.primaryKey !== "boolean")
  35297. throw new InvalidArgumentError2(
  35298. 'The provided option "primaryKey" of the property %v in the model %v should be a Boolean, but %v given.',
  35299. propName,
  35300. modelName,
  35301. propDef.primaryKey
  35302. );
  35303. if (propDef.columnName && typeof propDef.columnName !== "string")
  35304. throw new InvalidArgumentError2(
  35305. 'The provided option "columnName" of the property %v in the model %v should be a String, but %v given.',
  35306. propName,
  35307. modelName,
  35308. propDef.columnName
  35309. );
  35310. if (propDef.columnType && typeof propDef.columnType !== "string")
  35311. throw new InvalidArgumentError2(
  35312. 'The provided option "columnType" of the property %v in the model %v should be a String, but %v given.',
  35313. propName,
  35314. modelName,
  35315. propDef.columnType
  35316. );
  35317. if (propDef.required && typeof propDef.required !== "boolean")
  35318. throw new InvalidArgumentError2(
  35319. 'The provided option "required" of the property %v in the model %v should be a Boolean, but %v given.',
  35320. propName,
  35321. modelName,
  35322. propDef.required
  35323. );
  35324. if (propDef.required && propDef.default !== void 0)
  35325. throw new InvalidArgumentError2(
  35326. 'The property %v of the model %v is a required property, so it should not have the option "default" to be provided.',
  35327. propName,
  35328. modelName
  35329. );
  35330. if (propDef.primaryKey && propDef.required)
  35331. throw new InvalidArgumentError2(
  35332. 'The property %v of the model %v is a primary key, so it should not have the option "required" to be provided.',
  35333. propName,
  35334. modelName
  35335. );
  35336. if (propDef.primaryKey && propDef.default !== void 0)
  35337. throw new InvalidArgumentError2(
  35338. 'The property %v of the model %v is a primary key, so it should not have the option "default" to be provided.',
  35339. propName,
  35340. modelName
  35341. );
  35342. if (propDef.itemType && propDef.type !== DataType.ARRAY)
  35343. throw new InvalidArgumentError2(
  35344. 'The property %v of the model %v has the non-array type, so it should not have the option "itemType" to be provided.',
  35345. propName,
  35346. modelName,
  35347. propDef.type
  35348. );
  35349. if (propDef.model && propDef.type !== DataType.OBJECT && propDef.itemType !== DataType.OBJECT) {
  35350. if (propDef.type !== DataType.ARRAY) {
  35351. throw new InvalidArgumentError2(
  35352. 'The option "model" is not supported for %s property type, so the property %v of the model %v should not have the option "model" to be provided.',
  35353. capitalize(propDef.type),
  35354. propName,
  35355. modelName
  35356. );
  35357. } else {
  35358. throw new InvalidArgumentError2(
  35359. 'The option "model" is not supported for Array property type of %s, so the property %v of the model %v should not have the option "model" to be provided.',
  35360. capitalize(propDef.itemType),
  35361. propName,
  35362. modelName
  35363. );
  35364. }
  35365. }
  35366. if (propDef.validate != null) {
  35367. const propertyValidatorRegistry = this.getService(
  35368. PropertyValidatorRegistry
  35369. );
  35370. if (propDef.validate && typeof propDef.validate === "string") {
  35371. if (!propertyValidatorRegistry.hasValidator(propDef.validate))
  35372. throw new InvalidArgumentError2(
  35373. "The property validator %v is not found.",
  35374. propDef.validate
  35375. );
  35376. } else if (Array.isArray(propDef.validate)) {
  35377. for (const validatorName of propDef.validate) {
  35378. if (typeof validatorName !== "string")
  35379. throw new InvalidArgumentError2(
  35380. 'The provided option "validate" of the property %v in the model %v has an Array value that should have a non-empty String, but %v given.',
  35381. propName,
  35382. modelName,
  35383. validatorName
  35384. );
  35385. if (!propertyValidatorRegistry.hasValidator(validatorName))
  35386. throw new InvalidArgumentError2(
  35387. "The property validator %v is not found.",
  35388. validatorName
  35389. );
  35390. }
  35391. } else if (typeof propDef.validate === "object") {
  35392. for (const validatorName in propDef.validate) {
  35393. if (!propertyValidatorRegistry.hasValidator(validatorName))
  35394. throw new InvalidArgumentError2(
  35395. "The property validator %v is not found.",
  35396. validatorName
  35397. );
  35398. }
  35399. } else {
  35400. throw new InvalidArgumentError2(
  35401. 'The provided option "validate" of the property %v in the model %v should be a non-empty String, an Array of String or an Object, but %v given.',
  35402. propName,
  35403. modelName,
  35404. propDef.validate
  35405. );
  35406. }
  35407. }
  35408. if (propDef.transform != null) {
  35409. const propertyTransformerRegistry = this.getService(
  35410. PropertyTransformerRegistry
  35411. );
  35412. if (propDef.transform && typeof propDef.transform === "string") {
  35413. if (!propertyTransformerRegistry.hasTransformer(propDef.transform))
  35414. throw new InvalidArgumentError2(
  35415. "The property transformer %v is not found.",
  35416. propDef.transform
  35417. );
  35418. } else if (Array.isArray(propDef.transform)) {
  35419. for (const transformerName of propDef.transform) {
  35420. if (typeof transformerName !== "string")
  35421. throw new InvalidArgumentError2(
  35422. 'The provided option "transform" of the property %v in the model %v has an Array value that should have a non-empty String, but %v given.',
  35423. propName,
  35424. modelName,
  35425. transformerName
  35426. );
  35427. if (!propertyTransformerRegistry.hasTransformer(transformerName))
  35428. throw new InvalidArgumentError2(
  35429. "The property transformer %v is not found.",
  35430. transformerName
  35431. );
  35432. }
  35433. } else if (typeof propDef.transform === "object") {
  35434. for (const transformerName in propDef.transform) {
  35435. if (!propertyTransformerRegistry.hasTransformer(transformerName))
  35436. throw new InvalidArgumentError2(
  35437. "The property transformer %v is not found.",
  35438. transformerName
  35439. );
  35440. }
  35441. } else {
  35442. throw new InvalidArgumentError2(
  35443. 'The provided option "transform" of the property %v in the model %v should be a non-empty String, an Array of String or an Object, but %v given.',
  35444. propName,
  35445. modelName,
  35446. propDef.transform
  35447. );
  35448. }
  35449. }
  35450. if (propDef.unique) {
  35451. if (typeof propDef.unique !== "boolean" && !Object.values(PropertyUniqueness).includes(propDef.unique)) {
  35452. throw new InvalidArgumentError2(
  35453. 'The provided option "unique" of the property %v in the model %v should be a Boolean or one of values: %l, but %v given.',
  35454. propName,
  35455. modelName,
  35456. Object.values(PropertyUniqueness),
  35457. propDef.unique
  35458. );
  35459. }
  35460. }
  35461. if (propDef.unique && propDef.primaryKey)
  35462. throw new InvalidArgumentError2(
  35463. 'The property %v of the model %v is a primary key, so it should not have the option "unique" to be provided.',
  35464. propName,
  35465. modelName
  35466. );
  35467. }
  35468. };
  35469. __name(_PropertiesDefinitionValidator, "PropertiesDefinitionValidator");
  35470. PropertiesDefinitionValidator = _PropertiesDefinitionValidator;
  35471. }
  35472. });
  35473. // node_modules/@e22m4u/js-repository/src/definition/model/properties/index.js
  35474. var init_properties = __esm({
  35475. "node_modules/@e22m4u/js-repository/src/definition/model/properties/index.js"() {
  35476. init_data_type();
  35477. init_property_definition();
  35478. init_property_uniqueness();
  35479. init_empty_values_definer();
  35480. init_property_validator2();
  35481. init_property_transformer2();
  35482. init_property_uniqueness_validator();
  35483. init_properties_definition_validator();
  35484. init_primary_keys_definition_validator();
  35485. }
  35486. });
  35487. // node_modules/@e22m4u/js-repository/src/definition/model/model-definition.js
  35488. var init_model_definition = __esm({
  35489. "node_modules/@e22m4u/js-repository/src/definition/model/model-definition.js"() {
  35490. }
  35491. });
  35492. // node_modules/@e22m4u/js-repository/src/definition/model/model-data-validator.js
  35493. var _ModelDataValidator, ModelDataValidator;
  35494. var init_model_data_validator = __esm({
  35495. "node_modules/@e22m4u/js-repository/src/definition/model/model-data-validator.js"() {
  35496. init_src2();
  35497. init_properties();
  35498. init_utils2();
  35499. init_utils2();
  35500. init_properties();
  35501. init_errors2();
  35502. init_properties();
  35503. init_model_definition_utils();
  35504. _ModelDataValidator = class _ModelDataValidator extends Service {
  35505. /**
  35506. * Validate.
  35507. *
  35508. * @param {string} modelName
  35509. * @param {object} modelData
  35510. * @param {boolean} isPartial
  35511. * @returns {undefined}
  35512. */
  35513. validate(modelName, modelData, isPartial = false) {
  35514. if (!isPureObject(modelData))
  35515. throw new InvalidArgumentError2(
  35516. "The data of the model %v should be an Object, but %v given.",
  35517. modelName,
  35518. modelData
  35519. );
  35520. const propDefs = this.getService(
  35521. ModelDefinitionUtils
  35522. ).getPropertiesDefinitionInBaseModelHierarchy(modelName);
  35523. const propNames = Object.keys(isPartial ? modelData : propDefs);
  35524. propNames.forEach((propName) => {
  35525. const propDef = propDefs[propName];
  35526. if (!propDef) return;
  35527. this._validatePropertyValue(
  35528. modelName,
  35529. propName,
  35530. propDef,
  35531. modelData[propName]
  35532. );
  35533. });
  35534. }
  35535. /**
  35536. * Validate property value.
  35537. *
  35538. * @param {string} modelName
  35539. * @param {string} propName
  35540. * @param {string|object} propDef
  35541. * @param {*} propValue
  35542. * @returns {undefined}
  35543. */
  35544. _validatePropertyValue(modelName, propName, propDef, propValue) {
  35545. const propType = this.getService(ModelDefinitionUtils).getDataTypeFromPropertyDefinition(
  35546. propDef
  35547. );
  35548. const isEmpty = this.getService(EmptyValuesDefiner).isEmpty(
  35549. propType,
  35550. propValue
  35551. );
  35552. if (isEmpty) {
  35553. const isRequired = typeof propDef === "string" ? false : Boolean(propDef.required);
  35554. if (!isRequired) return;
  35555. throw new InvalidArgumentError2(
  35556. "The property %v of the model %v is required, but %v given.",
  35557. propName,
  35558. modelName,
  35559. propValue
  35560. );
  35561. }
  35562. this._validateValueByPropertyValidators(
  35563. modelName,
  35564. propName,
  35565. propDef,
  35566. propValue
  35567. );
  35568. this._validateValueByPropertyType(modelName, propName, propDef, propValue);
  35569. }
  35570. /**
  35571. * Validate value by property type.
  35572. *
  35573. * @param {string} modelName
  35574. * @param {string} propName
  35575. * @param {string|object} propDef
  35576. * @param {*} propValue
  35577. * @param {boolean} isArrayValue
  35578. * @returns {undefined}
  35579. */
  35580. _validateValueByPropertyType(modelName, propName, propDef, propValue, isArrayValue = false) {
  35581. let expectingType;
  35582. if (isArrayValue) {
  35583. if (typeof propDef === "object") {
  35584. expectingType = propDef.itemType ?? DataType.ANY;
  35585. } else {
  35586. expectingType = DataType.ANY;
  35587. }
  35588. } else {
  35589. expectingType = typeof propDef !== "string" ? propDef.type : propDef;
  35590. }
  35591. const createError = /* @__PURE__ */ __name((expected) => {
  35592. const pattern = isArrayValue ? "The array property %v of the model %v must have %s element, but %s given." : "The property %v of the model %v must have %s, but %s given.";
  35593. const ctorName = getCtorName(propValue);
  35594. const givenStr = ctorName ?? typeof propValue;
  35595. return new InvalidArgumentError2(
  35596. pattern,
  35597. propName,
  35598. modelName,
  35599. expected,
  35600. givenStr
  35601. );
  35602. }, "createError");
  35603. switch (expectingType) {
  35604. // STRING
  35605. case DataType.STRING:
  35606. if (typeof propValue !== "string") throw createError("a String");
  35607. break;
  35608. // NUMBER
  35609. case DataType.NUMBER:
  35610. if (typeof propValue !== "number") throw createError("a Number");
  35611. break;
  35612. // BOOLEAN
  35613. case DataType.BOOLEAN:
  35614. if (typeof propValue !== "boolean") throw createError("a Boolean");
  35615. break;
  35616. // ARRAY
  35617. case DataType.ARRAY:
  35618. if (!Array.isArray(propValue)) throw createError("an Array");
  35619. propValue.forEach(
  35620. (value) => this._validateValueByPropertyType(
  35621. modelName,
  35622. propName,
  35623. propDef,
  35624. value,
  35625. true
  35626. )
  35627. );
  35628. break;
  35629. // OBJECT
  35630. case DataType.OBJECT:
  35631. if (!isPureObject(propValue)) throw createError("an Object");
  35632. if (typeof propDef === "object" && propDef.model)
  35633. this.validate(propDef.model, propValue);
  35634. break;
  35635. }
  35636. }
  35637. /**
  35638. * Validate value by property validators.
  35639. *
  35640. * @param {string} modelName
  35641. * @param {string} propName
  35642. * @param {string|object} propDef
  35643. * @param {*} propValue
  35644. * @returns {undefined}
  35645. */
  35646. _validateValueByPropertyValidators(modelName, propName, propDef, propValue) {
  35647. if (typeof propDef === "string" || propDef.validate == null) return;
  35648. const validateDef = propDef.validate;
  35649. const validatorRegistry = this.getService(PropertyValidatorRegistry);
  35650. const createError = /* @__PURE__ */ __name((validatorName) => new InvalidArgumentError2(
  35651. "The property %v of the model %v has an invalid value %v that caught by the validator %v.",
  35652. propName,
  35653. modelName,
  35654. propValue,
  35655. validatorName
  35656. ), "createError");
  35657. const validateBy = /* @__PURE__ */ __name((validatorName, validatorOptions = void 0) => {
  35658. const validator = validatorRegistry.getValidator(validatorName);
  35659. const context = { validatorName, modelName, propName };
  35660. const valid = validator(propValue, validatorOptions, context);
  35661. if (valid instanceof Promise) {
  35662. throw new InvalidArgumentError2(
  35663. "Asynchronous property validators are not supported, but the property validator %v returns a Promise.",
  35664. validatorName
  35665. );
  35666. } else if (valid !== true) {
  35667. throw createError(validatorName);
  35668. }
  35669. }, "validateBy");
  35670. if (validateDef && typeof validateDef === "string") {
  35671. validateBy(validateDef);
  35672. } else if (Array.isArray(validateDef)) {
  35673. validateDef.forEach((validatorName) => validateBy(validatorName));
  35674. } else if (validateDef !== null && typeof validateDef === "object") {
  35675. Object.keys(validateDef).forEach((validatorName) => {
  35676. if (Object.prototype.hasOwnProperty.call(validateDef, validatorName)) {
  35677. const validatorOptions = validateDef[validatorName];
  35678. validateBy(validatorName, validatorOptions);
  35679. }
  35680. });
  35681. } else {
  35682. throw new InvalidArgumentError2(
  35683. 'The provided option "validate" of the property %v in the model %v should be a non-empty String, an Array of String or an Object, but %v given.',
  35684. propName,
  35685. modelName,
  35686. validateDef
  35687. );
  35688. }
  35689. }
  35690. };
  35691. __name(_ModelDataValidator, "ModelDataValidator");
  35692. ModelDataValidator = _ModelDataValidator;
  35693. }
  35694. });
  35695. // node_modules/@e22m4u/js-repository/src/definition/model/model-data-sanitizer.js
  35696. var _ModelDataSanitizer, ModelDataSanitizer;
  35697. var init_model_data_sanitizer = __esm({
  35698. "node_modules/@e22m4u/js-repository/src/definition/model/model-data-sanitizer.js"() {
  35699. init_src2();
  35700. init_errors2();
  35701. init_model_definition_utils();
  35702. _ModelDataSanitizer = class _ModelDataSanitizer extends Service {
  35703. /**
  35704. * Validate.
  35705. *
  35706. * @param {string} modelName
  35707. * @param {object} modelData
  35708. * @returns {object}
  35709. */
  35710. sanitize(modelName, modelData) {
  35711. if (!modelName || typeof modelName !== "string")
  35712. throw new InvalidArgumentError2(
  35713. "The first argument of ModelDataSanitizer.sanitize should be a string, but %v given.",
  35714. modelName
  35715. );
  35716. if (!modelData || typeof modelData !== "object")
  35717. throw new InvalidArgumentError2(
  35718. "The second argument of ModelDataSanitizer.sanitize should be an Object, but %v given.",
  35719. modelData
  35720. );
  35721. return this.getService(
  35722. ModelDefinitionUtils
  35723. ).excludeObjectKeysByRelationNames(modelName, modelData);
  35724. }
  35725. };
  35726. __name(_ModelDataSanitizer, "ModelDataSanitizer");
  35727. ModelDataSanitizer = _ModelDataSanitizer;
  35728. }
  35729. });
  35730. // node_modules/@e22m4u/js-repository/src/definition/model/model-data-transformer.js
  35731. var _ModelDataTransformer, ModelDataTransformer;
  35732. var init_model_data_transformer = __esm({
  35733. "node_modules/@e22m4u/js-repository/src/definition/model/model-data-transformer.js"() {
  35734. init_src2();
  35735. init_utils2();
  35736. init_utils2();
  35737. init_utils2();
  35738. init_properties();
  35739. init_errors2();
  35740. init_model_definition_utils();
  35741. init_properties();
  35742. _ModelDataTransformer = class _ModelDataTransformer extends Service {
  35743. /**
  35744. * Transform.
  35745. *
  35746. * @param {string} modelName
  35747. * @param {object} modelData
  35748. * @param {boolean} isPartial
  35749. * @returns {object|Promise<object>}
  35750. */
  35751. transform(modelName, modelData, isPartial = false) {
  35752. if (!isPureObject(modelData))
  35753. throw new InvalidArgumentError2(
  35754. "The data of the model %v should be an Object, but %v given.",
  35755. modelName,
  35756. modelData
  35757. );
  35758. const emptyValuesDefiner = this.getService(EmptyValuesDefiner);
  35759. const modelDefinitionUtils = this.getService(ModelDefinitionUtils);
  35760. const propDefs = modelDefinitionUtils.getPropertiesDefinitionInBaseModelHierarchy(
  35761. modelName
  35762. );
  35763. const propNames = Object.keys(isPartial ? modelData : propDefs);
  35764. const transformedData = cloneDeep(modelData);
  35765. return propNames.reduce((transformedDataOrPromise, propName) => {
  35766. const propDef = propDefs[propName];
  35767. if (!propDef) return transformedDataOrPromise;
  35768. const propType = modelDefinitionUtils.getDataTypeFromPropertyDefinition(propDef);
  35769. const propValue = modelData[propName];
  35770. const isEmpty = emptyValuesDefiner.isEmpty(propType, propValue);
  35771. if (isEmpty) return transformedDataOrPromise;
  35772. const newPropValueOrPromise = this._transformPropertyValue(
  35773. modelName,
  35774. propName,
  35775. propDef,
  35776. propValue
  35777. );
  35778. return transformPromise(newPropValueOrPromise, (newPropValue) => {
  35779. return transformPromise(transformedDataOrPromise, (resolvedData) => {
  35780. if (newPropValue !== propValue) resolvedData[propName] = newPropValue;
  35781. return resolvedData;
  35782. });
  35783. });
  35784. }, transformedData);
  35785. }
  35786. /**
  35787. * Transform property value.
  35788. *
  35789. * @param {string} modelName
  35790. * @param {string} propName
  35791. * @param {string|object} propDef
  35792. * @param {*} propValue
  35793. * @returns {*}
  35794. */
  35795. _transformPropertyValue(modelName, propName, propDef, propValue) {
  35796. if (typeof propDef === "string" || propDef.transform == null)
  35797. return propValue;
  35798. const transformDef = propDef.transform;
  35799. const transformerRegistry = this.getService(PropertyTransformerRegistry);
  35800. const transformFn = /* @__PURE__ */ __name((value, transformerName, transformerOptions = void 0) => {
  35801. const transformer = transformerRegistry.getTransformer(transformerName);
  35802. const context = { transformerName, modelName, propName };
  35803. return transformer(value, transformerOptions, context);
  35804. }, "transformFn");
  35805. if (transformDef && typeof transformDef === "string") {
  35806. return transformFn(propValue, transformDef);
  35807. } else if (Array.isArray(transformDef)) {
  35808. return transformDef.reduce((valueOrPromise, transformerName) => {
  35809. return transformPromise(valueOrPromise, (value) => {
  35810. return transformFn(value, transformerName);
  35811. });
  35812. }, propValue);
  35813. } else if (transformDef !== null && typeof transformDef === "object") {
  35814. return Object.keys(transformDef).reduce(
  35815. (valueOrPromise, transformerName) => {
  35816. const transformerOptions = transformDef[transformerName];
  35817. return transformPromise(valueOrPromise, (value) => {
  35818. return transformFn(value, transformerName, transformerOptions);
  35819. });
  35820. },
  35821. propValue
  35822. );
  35823. } else {
  35824. throw new InvalidArgumentError2(
  35825. 'The provided option "transform" of the property %v in the model %v should be a non-empty String, an Array of String or an Object, but %v given.',
  35826. propName,
  35827. modelName,
  35828. transformDef
  35829. );
  35830. }
  35831. }
  35832. };
  35833. __name(_ModelDataTransformer, "ModelDataTransformer");
  35834. ModelDataTransformer = _ModelDataTransformer;
  35835. }
  35836. });
  35837. // node_modules/@e22m4u/js-repository/src/definition/model/model-definition-validator.js
  35838. var _ModelDefinitionValidator, ModelDefinitionValidator;
  35839. var init_model_definition_validator = __esm({
  35840. "node_modules/@e22m4u/js-repository/src/definition/model/model-definition-validator.js"() {
  35841. init_src2();
  35842. init_errors2();
  35843. init_relations();
  35844. init_properties();
  35845. _ModelDefinitionValidator = class _ModelDefinitionValidator extends Service {
  35846. /**
  35847. * Validate.
  35848. *
  35849. * @param {object} modelDef
  35850. */
  35851. validate(modelDef) {
  35852. if (!modelDef || typeof modelDef !== "object" || Array.isArray(modelDef))
  35853. throw new InvalidArgumentError2(
  35854. "The model definition should be an Object, but %v given.",
  35855. modelDef
  35856. );
  35857. if (!modelDef.name || typeof modelDef.name !== "string")
  35858. throw new InvalidArgumentError2(
  35859. 'The model definition requires the option "name" as a non-empty String, but %v given.',
  35860. modelDef.name
  35861. );
  35862. if (modelDef.datasource && typeof modelDef.datasource !== "string")
  35863. throw new InvalidArgumentError2(
  35864. 'The provided option "datasource" of the model %v should be a String, but %v given.',
  35865. modelDef.name,
  35866. modelDef.datasource
  35867. );
  35868. if (modelDef.base && typeof modelDef.base !== "string")
  35869. throw new InvalidArgumentError2(
  35870. 'The provided option "base" of the model %v should be a String, but %v given.',
  35871. modelDef.name,
  35872. modelDef.base
  35873. );
  35874. if (modelDef.tableName && typeof modelDef.tableName !== "string")
  35875. throw new InvalidArgumentError2(
  35876. 'The provided option "tableName" of the model %v should be a String, but %v given.',
  35877. modelDef.name,
  35878. modelDef.tableName
  35879. );
  35880. if (modelDef.properties) {
  35881. if (typeof modelDef.properties !== "object" || Array.isArray(modelDef.properties)) {
  35882. throw new InvalidArgumentError2(
  35883. 'The provided option "properties" of the model %v should be an Object, but %v given.',
  35884. modelDef.name,
  35885. modelDef.properties
  35886. );
  35887. }
  35888. this.getService(PropertiesDefinitionValidator).validate(
  35889. modelDef.name,
  35890. modelDef.properties
  35891. );
  35892. }
  35893. if (modelDef.relations) {
  35894. if (typeof modelDef.relations !== "object" || Array.isArray(modelDef.relations)) {
  35895. throw new InvalidArgumentError2(
  35896. 'The provided option "relations" of the model %v should be an Object, but %v given.',
  35897. modelDef.name,
  35898. modelDef.relations
  35899. );
  35900. }
  35901. this.getService(RelationsDefinitionValidator).validate(
  35902. modelDef.name,
  35903. modelDef.relations
  35904. );
  35905. }
  35906. }
  35907. };
  35908. __name(_ModelDefinitionValidator, "ModelDefinitionValidator");
  35909. ModelDefinitionValidator = _ModelDefinitionValidator;
  35910. }
  35911. });
  35912. // node_modules/@e22m4u/js-repository/src/definition/model/index.js
  35913. var init_model = __esm({
  35914. "node_modules/@e22m4u/js-repository/src/definition/model/index.js"() {
  35915. init_relations();
  35916. init_properties();
  35917. init_model_definition();
  35918. init_model_data_validator();
  35919. init_model_data_sanitizer();
  35920. init_model_data_transformer();
  35921. init_model_definition_utils();
  35922. init_model_definition_validator();
  35923. }
  35924. });
  35925. // node_modules/@e22m4u/js-repository/src/definition/datasource/datasource-definition-validator.js
  35926. var _DatasourceDefinitionValidator, DatasourceDefinitionValidator;
  35927. var init_datasource_definition_validator = __esm({
  35928. "node_modules/@e22m4u/js-repository/src/definition/datasource/datasource-definition-validator.js"() {
  35929. init_src2();
  35930. init_errors2();
  35931. _DatasourceDefinitionValidator = class _DatasourceDefinitionValidator extends Service {
  35932. /**
  35933. * Validate.
  35934. *
  35935. * @param {object} datasourceDef
  35936. */
  35937. validate(datasourceDef) {
  35938. if (!datasourceDef || typeof datasourceDef !== "object")
  35939. throw new InvalidArgumentError2(
  35940. "The datasource definition should be an Object, but %v given.",
  35941. datasourceDef
  35942. );
  35943. if (!datasourceDef.name || typeof datasourceDef.name !== "string")
  35944. throw new InvalidArgumentError2(
  35945. 'The datasource definition requires the option "name" as a non-empty String, but %v given.',
  35946. datasourceDef.name
  35947. );
  35948. if (!datasourceDef.adapter || typeof datasourceDef.adapter !== "string")
  35949. throw new InvalidArgumentError2(
  35950. 'The datasource %v requires the option "adapter" as a non-empty String, but %v given.',
  35951. datasourceDef.name,
  35952. datasourceDef.adapter
  35953. );
  35954. }
  35955. };
  35956. __name(_DatasourceDefinitionValidator, "DatasourceDefinitionValidator");
  35957. DatasourceDefinitionValidator = _DatasourceDefinitionValidator;
  35958. }
  35959. });
  35960. // node_modules/@e22m4u/js-repository/src/definition/datasource/index.js
  35961. var init_datasource = __esm({
  35962. "node_modules/@e22m4u/js-repository/src/definition/datasource/index.js"() {
  35963. init_datasource_definition_validator();
  35964. }
  35965. });
  35966. // node_modules/@e22m4u/js-repository/src/definition/index.js
  35967. var init_definition = __esm({
  35968. "node_modules/@e22m4u/js-repository/src/definition/index.js"() {
  35969. init_model();
  35970. init_datasource();
  35971. init_definition_registry();
  35972. }
  35973. });
  35974. // node_modules/@e22m4u/js-repository/src/filter/fields-clause-tool.js
  35975. var _FieldsClauseTool, FieldsClauseTool;
  35976. var init_fields_clause_tool = __esm({
  35977. "node_modules/@e22m4u/js-repository/src/filter/fields-clause-tool.js"() {
  35978. init_src2();
  35979. init_utils2();
  35980. init_errors2();
  35981. init_definition();
  35982. _FieldsClauseTool = class _FieldsClauseTool extends Service {
  35983. /**
  35984. * Filter.
  35985. *
  35986. * @param {object|object[]} input
  35987. * @param {string} modelName
  35988. * @param {string|string[]|undefined} clause
  35989. * @returns {object|object[]}
  35990. */
  35991. filter(input, modelName, clause) {
  35992. const isArray = Array.isArray(input);
  35993. let entities = isArray ? input : [input];
  35994. entities.forEach((entity) => {
  35995. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  35996. throw new InvalidArgumentError2(
  35997. "The first argument of FieldsClauseTool.filter should be an Object or an Array of Object, but %v given.",
  35998. entity
  35999. );
  36000. });
  36001. if (!modelName || typeof modelName !== "string")
  36002. throw new InvalidArgumentError2(
  36003. "The second argument of FieldsClauseTool.filter should be a non-empty String, but %v given.",
  36004. modelName
  36005. );
  36006. if (clause == null) return input;
  36007. const fields = Array.isArray(clause) ? clause.slice() : [clause];
  36008. if (!fields.length) return input;
  36009. fields.forEach((field) => {
  36010. if (!field || typeof field !== "string")
  36011. throw new InvalidArgumentError2(
  36012. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  36013. field
  36014. );
  36015. });
  36016. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36017. modelName
  36018. );
  36019. if (fields.indexOf(pkPropName) === -1) fields.push(pkPropName);
  36020. entities = entities.map((entity) => selectObjectKeys(entity, fields));
  36021. return isArray ? entities : entities[0];
  36022. }
  36023. /**
  36024. * Validate fields clause.
  36025. *
  36026. * @param {string|string[]|undefined} clause
  36027. */
  36028. static validateFieldsClause(clause) {
  36029. if (clause == null) return;
  36030. const fields = Array.isArray(clause) ? clause : [clause];
  36031. if (!fields.length) return;
  36032. fields.forEach((field) => {
  36033. if (!field || typeof field !== "string")
  36034. throw new InvalidArgumentError2(
  36035. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  36036. field
  36037. );
  36038. });
  36039. }
  36040. /**
  36041. * Normalize fields clause.
  36042. *
  36043. * @param {string|string[]|undefined} clause
  36044. * @returns {string[]|undefined}
  36045. */
  36046. static normalizeFieldsClause(clause) {
  36047. if (clause == null) return;
  36048. const fields = Array.isArray(clause) ? clause : [clause];
  36049. if (!fields.length) return;
  36050. fields.forEach((field) => {
  36051. if (!field || typeof field !== "string")
  36052. throw new InvalidArgumentError2(
  36053. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  36054. field
  36055. );
  36056. });
  36057. return fields;
  36058. }
  36059. };
  36060. __name(_FieldsClauseTool, "FieldsClauseTool");
  36061. FieldsClauseTool = _FieldsClauseTool;
  36062. }
  36063. });
  36064. // node_modules/@e22m4u/js-repository/src/relations/has-one-resolver.js
  36065. var _HasOneResolver, HasOneResolver;
  36066. var init_has_one_resolver = __esm({
  36067. "node_modules/@e22m4u/js-repository/src/relations/has-one-resolver.js"() {
  36068. init_src2();
  36069. init_utils2();
  36070. init_definition();
  36071. init_errors2();
  36072. init_repository2();
  36073. init_definition();
  36074. _HasOneResolver = class _HasOneResolver extends Service {
  36075. /**
  36076. * Include to.
  36077. *
  36078. * @param {object[]} entities
  36079. * @param {string} sourceName
  36080. * @param {string} targetName
  36081. * @param {string} relationName
  36082. * @param {string} foreignKey
  36083. * @param {object|undefined} scope
  36084. * @returns {Promise<void>}
  36085. */
  36086. async includeTo(entities, sourceName, targetName, relationName, foreignKey, scope = void 0) {
  36087. if (!entities || !Array.isArray(entities))
  36088. throw new InvalidArgumentError2(
  36089. 'The parameter "entities" of HasOneResolver.includeTo requires an Array of Object, but %v given.',
  36090. entities
  36091. );
  36092. if (!sourceName || typeof sourceName !== "string")
  36093. throw new InvalidArgumentError2(
  36094. 'The parameter "sourceName" of HasOneResolver.includeTo requires a non-empty String, but %v given.',
  36095. sourceName
  36096. );
  36097. if (!targetName || typeof targetName !== "string")
  36098. throw new InvalidArgumentError2(
  36099. 'The parameter "targetName" of HasOneResolver.includeTo requires a non-empty String, but %v given.',
  36100. targetName
  36101. );
  36102. if (!relationName || typeof relationName !== "string")
  36103. throw new InvalidArgumentError2(
  36104. 'The parameter "relationName" of HasOneResolver.includeTo requires a non-empty String, but %v given.',
  36105. relationName
  36106. );
  36107. if (!foreignKey || typeof foreignKey !== "string")
  36108. throw new InvalidArgumentError2(
  36109. 'The parameter "foreignKey" of HasOneResolver.includeTo requires a non-empty String, but %v given.',
  36110. foreignKey
  36111. );
  36112. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36113. throw new InvalidArgumentError2(
  36114. 'The provided parameter "scope" of HasOneResolver.includeTo should be an Object, but %v given.',
  36115. scope
  36116. );
  36117. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36118. sourceName
  36119. );
  36120. const sourceIds = [];
  36121. entities.forEach((entity) => {
  36122. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  36123. throw new InvalidArgumentError2(
  36124. 'The parameter "entities" of HasOneResolver.includeTo requires an Array of Object, but %v given.',
  36125. entity
  36126. );
  36127. const sourceId = entity[sourcePkPropName];
  36128. if (sourceIds.includes(sourceId)) return;
  36129. sourceIds.push(sourceId);
  36130. });
  36131. const promises = [];
  36132. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  36133. scope = scope ? cloneDeep(scope) : {};
  36134. const targetBySourceId = /* @__PURE__ */ new Map();
  36135. sourceIds.forEach((sourceId) => {
  36136. const filter = cloneDeep(scope);
  36137. filter.where = {
  36138. and: [{ [foreignKey]: sourceId }, ...scope.where ? [scope.where] : []]
  36139. };
  36140. filter.limit = 1;
  36141. promises.push(
  36142. targetRepository.find(filter).then((result) => {
  36143. if (result.length) targetBySourceId.set(sourceId, result[0]);
  36144. })
  36145. );
  36146. });
  36147. await Promise.all(promises);
  36148. Array.from(targetBySourceId.keys()).forEach((sourceId) => {
  36149. const sources = entities.filter((v) => v[sourcePkPropName] === sourceId);
  36150. sources.forEach((v) => v[relationName] = targetBySourceId.get(sourceId));
  36151. });
  36152. }
  36153. /**
  36154. * Include polymorphic to.
  36155. *
  36156. * @param {object[]} entities
  36157. * @param {string} sourceName
  36158. * @param {string} targetName
  36159. * @param {string} relationName
  36160. * @param {string} foreignKey
  36161. * @param {string} discriminator
  36162. * @param {object|undefined} scope
  36163. * @returns {Promise<void>}
  36164. */
  36165. async includePolymorphicTo(entities, sourceName, targetName, relationName, foreignKey, discriminator, scope = void 0) {
  36166. if (!entities || !Array.isArray(entities))
  36167. throw new InvalidArgumentError2(
  36168. 'The parameter "entities" of HasOneResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  36169. entities
  36170. );
  36171. if (!sourceName || typeof sourceName !== "string")
  36172. throw new InvalidArgumentError2(
  36173. 'The parameter "sourceName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36174. sourceName
  36175. );
  36176. if (!targetName || typeof targetName !== "string")
  36177. throw new InvalidArgumentError2(
  36178. 'The parameter "targetName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36179. targetName
  36180. );
  36181. if (!relationName || typeof relationName !== "string")
  36182. throw new InvalidArgumentError2(
  36183. 'The parameter "relationName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36184. relationName
  36185. );
  36186. if (!foreignKey || typeof foreignKey !== "string")
  36187. throw new InvalidArgumentError2(
  36188. 'The parameter "foreignKey" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36189. foreignKey
  36190. );
  36191. if (!discriminator || typeof discriminator !== "string")
  36192. throw new InvalidArgumentError2(
  36193. 'The parameter "discriminator" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36194. discriminator
  36195. );
  36196. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36197. throw new InvalidArgumentError2(
  36198. 'The provided parameter "scope" of HasOneResolver.includePolymorphicTo should be an Object, but %v given.',
  36199. scope
  36200. );
  36201. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36202. sourceName
  36203. );
  36204. const sourceIds = [];
  36205. entities.forEach((entity) => {
  36206. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  36207. throw new InvalidArgumentError2(
  36208. 'The parameter "entities" of HasOneResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  36209. entity
  36210. );
  36211. const sourceId = entity[sourcePkPropName];
  36212. if (sourceIds.includes(sourceId)) return;
  36213. sourceIds.push(sourceId);
  36214. });
  36215. const promises = [];
  36216. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  36217. scope = scope ? cloneDeep(scope) : {};
  36218. const targetBySourceId = /* @__PURE__ */ new Map();
  36219. sourceIds.forEach((sourceId) => {
  36220. const filter = cloneDeep(scope);
  36221. filter.where = {
  36222. and: [
  36223. { [foreignKey]: sourceId, [discriminator]: sourceName },
  36224. ...scope.where ? [scope.where] : []
  36225. ]
  36226. };
  36227. filter.limit = 1;
  36228. promises.push(
  36229. targetRepository.find(filter).then((result) => {
  36230. if (result.length) targetBySourceId.set(sourceId, result[0]);
  36231. })
  36232. );
  36233. });
  36234. await Promise.all(promises);
  36235. Array.from(targetBySourceId.keys()).forEach((sourceId) => {
  36236. const sources = entities.filter((v) => v[sourcePkPropName] === sourceId);
  36237. sources.forEach((v) => v[relationName] = targetBySourceId.get(sourceId));
  36238. });
  36239. }
  36240. /**
  36241. * Include polymorphic by relation name.
  36242. *
  36243. * @param {object[]} entities
  36244. * @param {string} sourceName
  36245. * @param {string} targetName
  36246. * @param {string} relationName
  36247. * @param {string} targetRelationName
  36248. * @param {object|undefined} scope
  36249. * @returns {Promise<void>}
  36250. */
  36251. async includePolymorphicByRelationName(entities, sourceName, targetName, relationName, targetRelationName, scope = void 0) {
  36252. if (!entities || !Array.isArray(entities))
  36253. throw new InvalidArgumentError2(
  36254. 'The parameter "entities" of HasOneResolver.includePolymorphicByRelationName requires an Array of Object, but %v given.',
  36255. entities
  36256. );
  36257. if (!sourceName || typeof sourceName !== "string")
  36258. throw new InvalidArgumentError2(
  36259. 'The parameter "sourceName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  36260. sourceName
  36261. );
  36262. if (!targetName || typeof targetName !== "string")
  36263. throw new InvalidArgumentError2(
  36264. 'The parameter "targetName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  36265. targetName
  36266. );
  36267. if (!relationName || typeof relationName !== "string")
  36268. throw new InvalidArgumentError2(
  36269. 'The parameter "relationName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  36270. relationName
  36271. );
  36272. if (!targetRelationName || typeof targetRelationName !== "string")
  36273. throw new InvalidArgumentError2(
  36274. 'The parameter "targetRelationName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  36275. targetRelationName
  36276. );
  36277. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36278. throw new InvalidArgumentError2(
  36279. 'The provided parameter "scope" of HasOneResolver.includePolymorphicByRelationName should be an Object, but %v given.',
  36280. scope
  36281. );
  36282. const targetRelationDef = this.getService(
  36283. ModelDefinitionUtils
  36284. ).getRelationDefinitionByName(targetName, targetRelationName);
  36285. if (targetRelationDef.type !== RelationType.BELONGS_TO)
  36286. throw new InvalidArgumentError2(
  36287. 'The relation %v of the model %v is a polymorphic "hasOne" relation, so it requires the target relation %v to be a polymorphic "belongsTo", but %v type given.',
  36288. relationName,
  36289. sourceName,
  36290. targetRelationName,
  36291. targetRelationDef.type
  36292. );
  36293. if (!targetRelationDef.polymorphic)
  36294. throw new InvalidArgumentError2(
  36295. 'The relation %v of the model %v is a polymorphic "hasOne" relation, so it requires the target relation %v to be a polymorphic too.',
  36296. relationName,
  36297. sourceName,
  36298. targetRelationName
  36299. );
  36300. const foreignKey = targetRelationDef.foreignKey || `${targetRelationName}Id`;
  36301. const discriminator = targetRelationDef.discriminator || `${targetRelationName}Type`;
  36302. return this.includePolymorphicTo(
  36303. entities,
  36304. sourceName,
  36305. targetName,
  36306. relationName,
  36307. foreignKey,
  36308. discriminator,
  36309. scope
  36310. );
  36311. }
  36312. };
  36313. __name(_HasOneResolver, "HasOneResolver");
  36314. HasOneResolver = _HasOneResolver;
  36315. }
  36316. });
  36317. // node_modules/@e22m4u/js-repository/src/relations/has-many-resolver.js
  36318. var _HasManyResolver, HasManyResolver;
  36319. var init_has_many_resolver = __esm({
  36320. "node_modules/@e22m4u/js-repository/src/relations/has-many-resolver.js"() {
  36321. init_src2();
  36322. init_utils2();
  36323. init_definition();
  36324. init_errors2();
  36325. init_repository2();
  36326. init_definition();
  36327. _HasManyResolver = class _HasManyResolver extends Service {
  36328. /**
  36329. * Include to.
  36330. *
  36331. * @param {object[]} entities
  36332. * @param {string} sourceName
  36333. * @param {string} targetName
  36334. * @param {string} relationName
  36335. * @param {string} foreignKey
  36336. * @param {object|undefined} scope
  36337. * @returns {Promise<void>}
  36338. */
  36339. async includeTo(entities, sourceName, targetName, relationName, foreignKey, scope = void 0) {
  36340. if (!entities || !Array.isArray(entities))
  36341. throw new InvalidArgumentError2(
  36342. 'The parameter "entities" of HasManyResolver.includeTo requires an Array of Object, but %v given.',
  36343. entities
  36344. );
  36345. if (!sourceName || typeof sourceName !== "string")
  36346. throw new InvalidArgumentError2(
  36347. 'The parameter "sourceName" of HasManyResolver.includeTo requires a non-empty String, but %v given.',
  36348. sourceName
  36349. );
  36350. if (!targetName || typeof targetName !== "string")
  36351. throw new InvalidArgumentError2(
  36352. 'The parameter "targetName" of HasManyResolver.includeTo requires a non-empty String, but %v given.',
  36353. targetName
  36354. );
  36355. if (!relationName || typeof relationName !== "string")
  36356. throw new InvalidArgumentError2(
  36357. 'The parameter "relationName" of HasManyResolver.includeTo requires a non-empty String, but %v given.',
  36358. relationName
  36359. );
  36360. if (!foreignKey || typeof foreignKey !== "string")
  36361. throw new InvalidArgumentError2(
  36362. 'The parameter "foreignKey" of HasManyResolver.includeTo requires a non-empty String, but %v given.',
  36363. foreignKey
  36364. );
  36365. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36366. throw new InvalidArgumentError2(
  36367. 'The provided parameter "scope" of HasManyResolver.includeTo should be an Object, but %v given.',
  36368. scope
  36369. );
  36370. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36371. sourceName
  36372. );
  36373. const sourceIds = [];
  36374. entities.forEach((entity) => {
  36375. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  36376. throw new InvalidArgumentError2(
  36377. 'The parameter "entities" of HasManyResolver.includeTo requires an Array of Object, but %v given.',
  36378. entity
  36379. );
  36380. const sourceId = entity[sourcePkPropName];
  36381. if (sourceIds.includes(sourceId)) return;
  36382. sourceIds.push(sourceId);
  36383. });
  36384. const promises = [];
  36385. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  36386. scope = scope ? cloneDeep(scope) : {};
  36387. const targetsBySourceId = /* @__PURE__ */ new Map();
  36388. sourceIds.forEach((sourceId) => {
  36389. const filter = cloneDeep(scope);
  36390. filter.where = {
  36391. and: [{ [foreignKey]: sourceId }, ...scope.where ? [scope.where] : []]
  36392. };
  36393. promises.push(
  36394. targetRepository.find(filter).then((result) => {
  36395. if (result.length) {
  36396. let targets = targetsBySourceId.get(sourceId) ?? [];
  36397. targets = [...targets, ...result];
  36398. targetsBySourceId.set(sourceId, targets);
  36399. }
  36400. })
  36401. );
  36402. });
  36403. await Promise.all(promises);
  36404. entities.forEach((entity) => {
  36405. const sourceId = entity[sourcePkPropName];
  36406. entity[relationName] = targetsBySourceId.get(sourceId) ?? [];
  36407. });
  36408. }
  36409. /**
  36410. * Include polymorphic to.
  36411. *
  36412. * @param {object[]} entities
  36413. * @param {string} sourceName
  36414. * @param {string} targetName
  36415. * @param {string} relationName
  36416. * @param {string} foreignKey
  36417. * @param {string} discriminator
  36418. * @param {object|undefined} scope
  36419. * @returns {Promise<void>}
  36420. */
  36421. async includePolymorphicTo(entities, sourceName, targetName, relationName, foreignKey, discriminator, scope = void 0) {
  36422. if (!entities || !Array.isArray(entities))
  36423. throw new InvalidArgumentError2(
  36424. 'The parameter "entities" of HasManyResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  36425. entities
  36426. );
  36427. if (!sourceName || typeof sourceName !== "string")
  36428. throw new InvalidArgumentError2(
  36429. 'The parameter "sourceName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36430. sourceName
  36431. );
  36432. if (!targetName || typeof targetName !== "string")
  36433. throw new InvalidArgumentError2(
  36434. 'The parameter "targetName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36435. targetName
  36436. );
  36437. if (!relationName || typeof relationName !== "string")
  36438. throw new InvalidArgumentError2(
  36439. 'The parameter "relationName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36440. relationName
  36441. );
  36442. if (!foreignKey || typeof foreignKey !== "string")
  36443. throw new InvalidArgumentError2(
  36444. 'The parameter "foreignKey" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36445. foreignKey
  36446. );
  36447. if (!discriminator || typeof discriminator !== "string")
  36448. throw new InvalidArgumentError2(
  36449. 'The parameter "discriminator" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36450. discriminator
  36451. );
  36452. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36453. throw new InvalidArgumentError2(
  36454. 'The provided parameter "scope" of HasManyResolver.includePolymorphicTo should be an Object, but %v given.',
  36455. scope
  36456. );
  36457. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36458. sourceName
  36459. );
  36460. const sourceIds = [];
  36461. entities.forEach((entity) => {
  36462. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  36463. throw new InvalidArgumentError2(
  36464. 'The parameter "entities" of HasManyResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  36465. entity
  36466. );
  36467. const sourceId = entity[sourcePkPropName];
  36468. if (sourceIds.includes(sourceId)) return;
  36469. sourceIds.push(sourceId);
  36470. });
  36471. const promises = [];
  36472. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  36473. scope = scope ? cloneDeep(scope) : {};
  36474. const targetsBySourceId = /* @__PURE__ */ new Map();
  36475. sourceIds.forEach((sourceId) => {
  36476. const filter = cloneDeep(scope);
  36477. filter.where = {
  36478. and: [
  36479. { [foreignKey]: sourceId, [discriminator]: sourceName },
  36480. ...scope.where ? [scope.where] : []
  36481. ]
  36482. };
  36483. promises.push(
  36484. targetRepository.find(filter).then((result) => {
  36485. if (result.length) {
  36486. let targets = targetsBySourceId.get(sourceId) ?? [];
  36487. targets = [...targets, ...result];
  36488. targetsBySourceId.set(sourceId, targets);
  36489. }
  36490. })
  36491. );
  36492. });
  36493. await Promise.all(promises);
  36494. entities.forEach((entity) => {
  36495. const sourceId = entity[sourcePkPropName];
  36496. entity[relationName] = targetsBySourceId.get(sourceId) ?? [];
  36497. });
  36498. }
  36499. /**
  36500. * Include polymorphic by relation name.
  36501. *
  36502. * @param {object[]} entities
  36503. * @param {string} sourceName
  36504. * @param {string} targetName
  36505. * @param {string} relationName
  36506. * @param {string} targetRelationName
  36507. * @param {object|undefined} scope
  36508. * @returns {Promise<void>}
  36509. */
  36510. async includePolymorphicByRelationName(entities, sourceName, targetName, relationName, targetRelationName, scope = void 0) {
  36511. if (!entities || !Array.isArray(entities))
  36512. throw new InvalidArgumentError2(
  36513. 'The parameter "entities" of HasManyResolver.includePolymorphicByRelationName requires an Array of Object, but %v given.',
  36514. entities
  36515. );
  36516. if (!sourceName || typeof sourceName !== "string")
  36517. throw new InvalidArgumentError2(
  36518. 'The parameter "sourceName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  36519. sourceName
  36520. );
  36521. if (!targetName || typeof targetName !== "string")
  36522. throw new InvalidArgumentError2(
  36523. 'The parameter "targetName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  36524. targetName
  36525. );
  36526. if (!relationName || typeof relationName !== "string")
  36527. throw new InvalidArgumentError2(
  36528. 'The parameter "relationName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  36529. relationName
  36530. );
  36531. if (!targetRelationName || typeof targetRelationName !== "string")
  36532. throw new InvalidArgumentError2(
  36533. 'The parameter "targetRelationName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  36534. targetRelationName
  36535. );
  36536. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36537. throw new InvalidArgumentError2(
  36538. 'The provided parameter "scope" of HasManyResolver.includePolymorphicByRelationName should be an Object, but %v given.',
  36539. scope
  36540. );
  36541. const targetRelationDef = this.getService(
  36542. ModelDefinitionUtils
  36543. ).getRelationDefinitionByName(targetName, targetRelationName);
  36544. if (targetRelationDef.type !== RelationType.BELONGS_TO)
  36545. throw new InvalidArgumentError2(
  36546. 'The relation %v of the model %v is a polymorphic "hasMany" relation, so it requires the target relation %v to be a polymorphic "belongsTo", but %v type given.',
  36547. relationName,
  36548. sourceName,
  36549. targetRelationName,
  36550. targetRelationDef.type
  36551. );
  36552. if (!targetRelationDef.polymorphic)
  36553. throw new InvalidArgumentError2(
  36554. 'The relation %v of the model %v is a polymorphic "hasMany" relation, so it requires the target relation %v to be a polymorphic too.',
  36555. relationName,
  36556. sourceName,
  36557. targetRelationName
  36558. );
  36559. const foreignKey = targetRelationDef.foreignKey || `${targetRelationName}Id`;
  36560. const discriminator = targetRelationDef.discriminator || `${targetRelationName}Type`;
  36561. return this.includePolymorphicTo(
  36562. entities,
  36563. sourceName,
  36564. targetName,
  36565. relationName,
  36566. foreignKey,
  36567. discriminator,
  36568. scope
  36569. );
  36570. }
  36571. };
  36572. __name(_HasManyResolver, "HasManyResolver");
  36573. HasManyResolver = _HasManyResolver;
  36574. }
  36575. });
  36576. // node_modules/@e22m4u/js-repository/src/relations/belongs-to-resolver.js
  36577. var _BelongsToResolver, BelongsToResolver;
  36578. var init_belongs_to_resolver = __esm({
  36579. "node_modules/@e22m4u/js-repository/src/relations/belongs-to-resolver.js"() {
  36580. init_src2();
  36581. init_utils2();
  36582. init_utils2();
  36583. init_errors2();
  36584. init_repository2();
  36585. init_definition();
  36586. _BelongsToResolver = class _BelongsToResolver extends Service {
  36587. /**
  36588. * Include to.
  36589. *
  36590. * @param {object[]} entities
  36591. * @param {string} sourceName
  36592. * @param {string} targetName
  36593. * @param {string} relationName
  36594. * @param {string|undefined} foreignKey
  36595. * @param {object|undefined} scope
  36596. * @returns {Promise<void>}
  36597. */
  36598. async includeTo(entities, sourceName, targetName, relationName, foreignKey = void 0, scope = void 0) {
  36599. if (!entities || !Array.isArray(entities))
  36600. throw new InvalidArgumentError2(
  36601. 'The parameter "entities" of BelongsToResolver.includeTo requires an Array of Object, but %v given.',
  36602. entities
  36603. );
  36604. if (!sourceName || typeof sourceName !== "string")
  36605. throw new InvalidArgumentError2(
  36606. 'The parameter "sourceName" of BelongsToResolver.includeTo requires a non-empty String, but %v given.',
  36607. sourceName
  36608. );
  36609. if (!targetName || typeof targetName !== "string")
  36610. throw new InvalidArgumentError2(
  36611. 'The parameter "targetName" of BelongsToResolver.includeTo requires a non-empty String, but %v given.',
  36612. targetName
  36613. );
  36614. if (!relationName || typeof relationName !== "string")
  36615. throw new InvalidArgumentError2(
  36616. 'The parameter "relationName" of BelongsToResolver.includeTo requires a non-empty String, but %v given.',
  36617. relationName
  36618. );
  36619. if (foreignKey && typeof foreignKey !== "string")
  36620. throw new InvalidArgumentError2(
  36621. 'The provided parameter "foreignKey" of BelongsToResolver.includeTo should be a String, but %v given.',
  36622. foreignKey
  36623. );
  36624. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36625. throw new InvalidArgumentError2(
  36626. 'The provided parameter "scope" of BelongsToResolver.includeTo should be an Object, but %v given.',
  36627. scope
  36628. );
  36629. if (foreignKey == null) foreignKey = `${relationName}Id`;
  36630. const targetIds = entities.reduce((acc, entity) => {
  36631. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  36632. throw new InvalidArgumentError2(
  36633. 'The parameter "entities" of BelongsToResolver.includeTo requires an Array of Object, but %v given.',
  36634. entity
  36635. );
  36636. const targetId = entity[foreignKey];
  36637. return targetId != null ? [...acc, targetId] : acc;
  36638. }, []);
  36639. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  36640. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36641. targetName
  36642. );
  36643. scope = scope ? cloneDeep(scope) : {};
  36644. const filter = cloneDeep(scope);
  36645. filter.where = {
  36646. and: [
  36647. { [targetPkPropName]: { inq: targetIds } },
  36648. ...scope.where ? [scope.where] : []
  36649. ]
  36650. };
  36651. const targets = await targetRepository.find(filter);
  36652. entities.forEach((entity) => {
  36653. const target = targets.find(
  36654. (e) => e[targetPkPropName] === entity[foreignKey]
  36655. );
  36656. if (target) entity[relationName] = target;
  36657. });
  36658. }
  36659. /**
  36660. * Include polymorphic to.
  36661. *
  36662. * @param {object[]} entities
  36663. * @param {string} sourceName
  36664. * @param {string} relationName
  36665. * @param {string|undefined} foreignKey
  36666. * @param {string|undefined} discriminator
  36667. * @param {object|undefined} scope
  36668. * @returns {Promise<void>}
  36669. */
  36670. async includePolymorphicTo(entities, sourceName, relationName, foreignKey = void 0, discriminator = void 0, scope = void 0) {
  36671. if (!entities || !Array.isArray(entities))
  36672. throw new InvalidArgumentError2(
  36673. 'The parameter "entities" of BelongsToResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  36674. entities
  36675. );
  36676. if (!sourceName || typeof sourceName !== "string")
  36677. throw new InvalidArgumentError2(
  36678. 'The parameter "sourceName" of BelongsToResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36679. sourceName
  36680. );
  36681. if (!relationName || typeof relationName !== "string")
  36682. throw new InvalidArgumentError2(
  36683. 'The parameter "relationName" of BelongsToResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  36684. relationName
  36685. );
  36686. if (foreignKey && typeof foreignKey !== "string")
  36687. throw new InvalidArgumentError2(
  36688. 'The provided parameter "foreignKey" of BelongsToResolver.includePolymorphicTo should be a String, but %v given.',
  36689. foreignKey
  36690. );
  36691. if (discriminator && typeof discriminator !== "string")
  36692. throw new InvalidArgumentError2(
  36693. 'The provided parameter "discriminator" of BelongsToResolver.includePolymorphicTo should be a String, but %v given.',
  36694. discriminator
  36695. );
  36696. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36697. throw new InvalidArgumentError2(
  36698. 'The provided parameter "scope" of BelongsToResolver.includePolymorphicTo should be an Object, but %v given.',
  36699. scope
  36700. );
  36701. if (foreignKey == null) {
  36702. const singularRelationName = singularize(relationName);
  36703. foreignKey = `${singularRelationName}Id`;
  36704. }
  36705. if (discriminator == null) {
  36706. const singularRelationName = singularize(relationName);
  36707. discriminator = `${singularRelationName}Type`;
  36708. }
  36709. const targetIdsByTargetName = {};
  36710. entities.forEach((entity) => {
  36711. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  36712. throw new InvalidArgumentError2(
  36713. 'The parameter "entities" of BelongsToResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  36714. entity
  36715. );
  36716. const targetId = entity[foreignKey];
  36717. const targetName = entity[discriminator];
  36718. if (targetId == null || targetName == null) return;
  36719. if (targetIdsByTargetName[targetName] == null)
  36720. targetIdsByTargetName[targetName] = [];
  36721. if (!targetIdsByTargetName[targetName].includes(targetId))
  36722. targetIdsByTargetName[targetName].push(targetId);
  36723. });
  36724. const promises = [];
  36725. const targetNames = Object.keys(targetIdsByTargetName);
  36726. scope = scope ? cloneDeep(scope) : {};
  36727. const targetEntitiesByTargetNames = {};
  36728. targetNames.forEach((targetName) => {
  36729. let targetRepository;
  36730. try {
  36731. targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  36732. } catch (error) {
  36733. if (error instanceof InvalidArgumentError2) {
  36734. if (error.message === `The model "${targetName}" is not defined.` || error.message === `The model "${targetName}" does not have a specified datasource.`) {
  36735. return;
  36736. }
  36737. } else {
  36738. throw error;
  36739. }
  36740. }
  36741. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36742. targetName
  36743. );
  36744. const targetFilter = cloneDeep(scope);
  36745. const targetIds = targetIdsByTargetName[targetName];
  36746. targetFilter.where = {
  36747. and: [
  36748. { [targetPkPropName]: { inq: targetIds } },
  36749. ...scope.where ? [scope.where] : []
  36750. ]
  36751. };
  36752. const promise = targetRepository.find(targetFilter).then((result) => {
  36753. targetEntitiesByTargetNames[targetName] = [
  36754. ...targetEntitiesByTargetNames[targetName] ?? [],
  36755. ...result
  36756. ];
  36757. });
  36758. promises.push(promise);
  36759. });
  36760. await Promise.all(promises);
  36761. entities.forEach((entity) => {
  36762. const targetId = entity[foreignKey];
  36763. const targetName = entity[discriminator];
  36764. if (targetId == null || targetName == null || targetEntitiesByTargetNames[targetName] == null) {
  36765. return;
  36766. }
  36767. const targetEntities = targetEntitiesByTargetNames[targetName] ?? [];
  36768. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36769. targetName
  36770. );
  36771. const target = targetEntities.find((e) => e[targetPkPropName] === targetId);
  36772. if (target) entity[relationName] = target;
  36773. });
  36774. }
  36775. };
  36776. __name(_BelongsToResolver, "BelongsToResolver");
  36777. BelongsToResolver = _BelongsToResolver;
  36778. }
  36779. });
  36780. // node_modules/@e22m4u/js-repository/src/relations/references-many-resolver.js
  36781. var _ReferencesManyResolver, ReferencesManyResolver;
  36782. var init_references_many_resolver = __esm({
  36783. "node_modules/@e22m4u/js-repository/src/relations/references-many-resolver.js"() {
  36784. init_src2();
  36785. init_utils2();
  36786. init_utils2();
  36787. init_errors2();
  36788. init_repository2();
  36789. init_definition();
  36790. _ReferencesManyResolver = class _ReferencesManyResolver extends Service {
  36791. /**
  36792. * Include to.
  36793. *
  36794. * @param {object[]} entities
  36795. * @param {string} sourceName
  36796. * @param {string} targetName
  36797. * @param {string} relationName
  36798. * @param {string|undefined} foreignKey
  36799. * @param {object|undefined} scope
  36800. * @returns {Promise<void>}
  36801. */
  36802. async includeTo(entities, sourceName, targetName, relationName, foreignKey = void 0, scope = void 0) {
  36803. if (!entities || !Array.isArray(entities))
  36804. throw new InvalidArgumentError2(
  36805. 'The parameter "entities" of ReferencesManyResolver.includeTo requires an Array of Object, but %v given.',
  36806. entities
  36807. );
  36808. if (!sourceName || typeof sourceName !== "string")
  36809. throw new InvalidArgumentError2(
  36810. 'The parameter "sourceName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v given.',
  36811. sourceName
  36812. );
  36813. if (!targetName || typeof targetName !== "string")
  36814. throw new InvalidArgumentError2(
  36815. 'The parameter "targetName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v given.',
  36816. targetName
  36817. );
  36818. if (!relationName || typeof relationName !== "string")
  36819. throw new InvalidArgumentError2(
  36820. 'The parameter "relationName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v given.',
  36821. relationName
  36822. );
  36823. if (foreignKey && typeof foreignKey !== "string")
  36824. throw new InvalidArgumentError2(
  36825. 'The provided parameter "foreignKey" of ReferencesManyResolver.includeTo should be a String, but %v given.',
  36826. foreignKey
  36827. );
  36828. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  36829. throw new InvalidArgumentError2(
  36830. 'The provided parameter "scope" of ReferencesManyResolver.includeTo should be an Object, but %v given.',
  36831. scope
  36832. );
  36833. if (foreignKey == null) {
  36834. const singularRelationName = singularize(relationName);
  36835. foreignKey = `${singularRelationName}Ids`;
  36836. }
  36837. const targetIds = entities.reduce((acc, entity) => {
  36838. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  36839. throw new InvalidArgumentError2(
  36840. 'The parameter "entities" of ReferencesManyResolver.includeTo requires an Array of Object, but %v given.',
  36841. entity
  36842. );
  36843. const ids = entity[foreignKey];
  36844. if (Array.isArray(ids))
  36845. ids.forEach((id) => {
  36846. if (id == null || acc.includes(id)) return;
  36847. acc.push(id);
  36848. });
  36849. return acc;
  36850. }, []);
  36851. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  36852. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  36853. targetName
  36854. );
  36855. scope = scope ? cloneDeep(scope) : {};
  36856. const filter = cloneDeep(scope);
  36857. filter.where = {
  36858. and: [
  36859. { [targetPkPropName]: { inq: targetIds } },
  36860. ...scope.where ? [scope.where] : []
  36861. ]
  36862. };
  36863. const targets = await targetRepository.find(filter);
  36864. entities.forEach((entity) => {
  36865. const ids = entity[foreignKey];
  36866. entity[relationName] = [];
  36867. if (Array.isArray(ids))
  36868. targets.forEach((target) => {
  36869. const targetId = target[targetPkPropName];
  36870. if (ids.includes(targetId)) entity[relationName].push(target);
  36871. });
  36872. });
  36873. }
  36874. };
  36875. __name(_ReferencesManyResolver, "ReferencesManyResolver");
  36876. ReferencesManyResolver = _ReferencesManyResolver;
  36877. }
  36878. });
  36879. // node_modules/@e22m4u/js-repository/src/relations/index.js
  36880. var init_relations2 = __esm({
  36881. "node_modules/@e22m4u/js-repository/src/relations/index.js"() {
  36882. init_has_one_resolver();
  36883. init_has_many_resolver();
  36884. init_belongs_to_resolver();
  36885. init_references_many_resolver();
  36886. }
  36887. });
  36888. // node_modules/@e22m4u/js-repository/src/filter/include-clause-tool.js
  36889. var _IncludeClauseTool, IncludeClauseTool;
  36890. var init_include_clause_tool = __esm({
  36891. "node_modules/@e22m4u/js-repository/src/filter/include-clause-tool.js"() {
  36892. init_src2();
  36893. init_definition();
  36894. init_relations2();
  36895. init_relations2();
  36896. init_where_clause_tool();
  36897. init_order_clause_tool();
  36898. init_slice_clause_tool();
  36899. init_errors2();
  36900. init_relations2();
  36901. init_fields_clause_tool();
  36902. init_definition();
  36903. init_relations2();
  36904. _IncludeClauseTool = class _IncludeClauseTool extends Service {
  36905. /**
  36906. * Include to.
  36907. *
  36908. * @param {object[]} entities
  36909. * @param {string} modelName
  36910. * @param {IncludeClause|undefined} clause
  36911. * @returns {Promise<void>}
  36912. */
  36913. async includeTo(entities, modelName, clause) {
  36914. clause = _IncludeClauseTool.normalizeIncludeClause(clause);
  36915. const promises = [];
  36916. clause.forEach((inclusion) => {
  36917. const relDef = this.getService(
  36918. ModelDefinitionUtils
  36919. ).getRelationDefinitionByName(modelName, inclusion.relation);
  36920. switch (relDef.type) {
  36921. // BELONGS_TO
  36922. case RelationType.BELONGS_TO:
  36923. if (relDef.polymorphic) {
  36924. promises.push(
  36925. this.getService(BelongsToResolver).includePolymorphicTo(
  36926. entities,
  36927. modelName,
  36928. inclusion.relation,
  36929. relDef.foreignKey,
  36930. relDef.discriminator,
  36931. inclusion.scope
  36932. )
  36933. );
  36934. } else {
  36935. promises.push(
  36936. this.getService(BelongsToResolver).includeTo(
  36937. entities,
  36938. modelName,
  36939. relDef.model,
  36940. inclusion.relation,
  36941. relDef.foreignKey,
  36942. inclusion.scope
  36943. )
  36944. );
  36945. }
  36946. break;
  36947. // HAS_ONE
  36948. case RelationType.HAS_ONE:
  36949. if (relDef.polymorphic && typeof relDef.polymorphic === "string") {
  36950. promises.push(
  36951. this.getService(HasOneResolver).includePolymorphicByRelationName(
  36952. entities,
  36953. modelName,
  36954. relDef.model,
  36955. inclusion.relation,
  36956. relDef.polymorphic,
  36957. inclusion.scope
  36958. )
  36959. );
  36960. } else if (relDef.polymorphic) {
  36961. promises.push(
  36962. this.getService(HasOneResolver).includePolymorphicTo(
  36963. entities,
  36964. modelName,
  36965. relDef.model,
  36966. inclusion.relation,
  36967. relDef.foreignKey,
  36968. relDef.discriminator,
  36969. inclusion.scope
  36970. )
  36971. );
  36972. } else {
  36973. promises.push(
  36974. this.getService(HasOneResolver).includeTo(
  36975. entities,
  36976. modelName,
  36977. relDef.model,
  36978. inclusion.relation,
  36979. relDef.foreignKey,
  36980. inclusion.scope
  36981. )
  36982. );
  36983. }
  36984. break;
  36985. // HAS_MANY
  36986. case RelationType.HAS_MANY:
  36987. if (relDef.polymorphic && typeof relDef.polymorphic === "string") {
  36988. promises.push(
  36989. this.getService(HasManyResolver).includePolymorphicByRelationName(
  36990. entities,
  36991. modelName,
  36992. relDef.model,
  36993. inclusion.relation,
  36994. relDef.polymorphic,
  36995. inclusion.scope
  36996. )
  36997. );
  36998. } else if (relDef.polymorphic) {
  36999. promises.push(
  37000. this.getService(HasManyResolver).includePolymorphicTo(
  37001. entities,
  37002. modelName,
  37003. relDef.model,
  37004. inclusion.relation,
  37005. relDef.foreignKey,
  37006. relDef.discriminator,
  37007. inclusion.scope
  37008. )
  37009. );
  37010. } else {
  37011. promises.push(
  37012. this.getService(HasManyResolver).includeTo(
  37013. entities,
  37014. modelName,
  37015. relDef.model,
  37016. inclusion.relation,
  37017. relDef.foreignKey,
  37018. inclusion.scope
  37019. )
  37020. );
  37021. }
  37022. break;
  37023. case RelationType.REFERENCES_MANY:
  37024. promises.push(
  37025. this.getService(ReferencesManyResolver).includeTo(
  37026. entities,
  37027. modelName,
  37028. relDef.model,
  37029. inclusion.relation,
  37030. relDef.foreignKey,
  37031. inclusion.scope
  37032. )
  37033. );
  37034. break;
  37035. default:
  37036. throw new InvalidArgumentError2(
  37037. "The relation type %v does not have an inclusion resolver.",
  37038. relDef.type
  37039. );
  37040. }
  37041. });
  37042. await Promise.all(promises);
  37043. }
  37044. /**
  37045. * Validate include clause.
  37046. *
  37047. * @param {IncludeClause|undefined} clause
  37048. */
  37049. static validateIncludeClause(clause) {
  37050. if (clause == null) {
  37051. } else if (clause && typeof clause === "string") {
  37052. } else if (Array.isArray(clause)) {
  37053. const relNames = [];
  37054. clause.flat(Infinity).forEach((el) => {
  37055. this.validateIncludeClause(el);
  37056. if (typeof el === "string") {
  37057. relNames.push(el);
  37058. } else if (typeof el === "object") {
  37059. Object.keys(el).forEach((key) => {
  37060. if (Object.prototype.hasOwnProperty.call(el, key))
  37061. relNames.push(key);
  37062. });
  37063. }
  37064. });
  37065. const duplicateNames = relNames.filter(
  37066. (name, i) => relNames.indexOf(name) !== i
  37067. );
  37068. if (duplicateNames.length)
  37069. throw new InvalidArgumentError2(
  37070. 'The provided option "include" has duplicates of %v.',
  37071. duplicateNames[0]
  37072. );
  37073. } else if (typeof clause === "object") {
  37074. if ("relation" in clause) {
  37075. if (!clause.relation || typeof clause.relation !== "string")
  37076. throw new InvalidArgumentError2(
  37077. 'The provided option "relation" should be a non-empty String, but %v given.',
  37078. clause.relation
  37079. );
  37080. if ("scope" in clause && clause) this.validateScopeClause(clause.scope);
  37081. } else {
  37082. Object.keys(clause).forEach((key) => {
  37083. if (!Object.prototype.hasOwnProperty.call(clause, key)) return;
  37084. this.validateIncludeClause(key);
  37085. this.validateIncludeClause(clause[key]);
  37086. });
  37087. }
  37088. } else {
  37089. throw new InvalidArgumentError2(
  37090. 'The provided option "include" should have a non-empty String, an Object or an Array, but %v given.',
  37091. clause
  37092. );
  37093. }
  37094. }
  37095. /**
  37096. * Validate scope clause.
  37097. *
  37098. * @param {object|undefined} clause
  37099. */
  37100. static validateScopeClause(clause) {
  37101. if (clause == null) return;
  37102. if (typeof clause !== "object" || Array.isArray(clause))
  37103. throw new InvalidArgumentError2(
  37104. 'The provided option "scope" should be an Object, but %v given.',
  37105. clause
  37106. );
  37107. if (clause.where != null) {
  37108. WhereClauseTool.validateWhereClause(clause.where);
  37109. }
  37110. if (clause.order != null) {
  37111. OrderClauseTool.validateOrderClause(clause.order);
  37112. }
  37113. if (clause.skip != null) {
  37114. SliceClauseTool.validateSkipClause(clause.skip);
  37115. }
  37116. if (clause.limit != null) {
  37117. SliceClauseTool.validateLimitClause(clause.limit);
  37118. }
  37119. if (clause.fields != null) {
  37120. FieldsClauseTool.validateFieldsClause(clause.fields);
  37121. }
  37122. if (clause.include != null) {
  37123. _IncludeClauseTool.validateIncludeClause(clause.include);
  37124. }
  37125. }
  37126. /**
  37127. * Normalize include clause.
  37128. *
  37129. * @param {IncludeClause|undefined} clause
  37130. * @returns {object[]}
  37131. */
  37132. static normalizeIncludeClause(clause) {
  37133. let result = [];
  37134. if (clause == null) {
  37135. return result;
  37136. } else if (clause && typeof clause === "string") {
  37137. result.push({ relation: clause });
  37138. } else if (Array.isArray(clause)) {
  37139. clause.flat(Infinity).forEach((el) => {
  37140. el = this.normalizeIncludeClause(el);
  37141. result = [...result, ...el];
  37142. });
  37143. const relNames = result.map((v) => v.relation);
  37144. const duplicateNames = relNames.filter(
  37145. (name, i) => relNames.indexOf(name) !== i
  37146. );
  37147. if (duplicateNames.length)
  37148. throw new InvalidArgumentError2(
  37149. 'The provided option "include" has duplicates of %v.',
  37150. duplicateNames[0]
  37151. );
  37152. } else if (typeof clause === "object") {
  37153. if ("relation" in clause) {
  37154. if (!clause.relation || typeof clause.relation !== "string")
  37155. throw new InvalidArgumentError2(
  37156. 'The provided option "relation" should be a non-empty String, but %v given.',
  37157. clause.relation
  37158. );
  37159. const normalized = { relation: clause.relation };
  37160. const scope = this.normalizeScopeClause(clause.scope);
  37161. if (scope) normalized.scope = scope;
  37162. result.push(normalized);
  37163. } else {
  37164. Object.keys(clause).forEach((key) => {
  37165. if (!Object.prototype.hasOwnProperty.call(clause, key)) return;
  37166. this.validateIncludeClause(key);
  37167. const normalized = { relation: key };
  37168. const include = this.normalizeIncludeClause(clause[key]);
  37169. if (include.length) normalized.scope = { include };
  37170. result.push(normalized);
  37171. });
  37172. }
  37173. } else {
  37174. throw new InvalidArgumentError2(
  37175. 'The provided option "include" should have a non-empty String, an Object or an Array, but %v given.',
  37176. clause
  37177. );
  37178. }
  37179. return result;
  37180. }
  37181. /**
  37182. * Normalize scope clause.
  37183. *
  37184. * @param {object|undefined} clause
  37185. * @returns {object|undefined}
  37186. */
  37187. static normalizeScopeClause(clause) {
  37188. if (clause == null) return;
  37189. if (typeof clause !== "object" || Array.isArray(clause))
  37190. throw new InvalidArgumentError2(
  37191. 'The provided option "scope" should be an Object, but %v given.',
  37192. clause
  37193. );
  37194. const result = {};
  37195. if (clause.where != null) {
  37196. WhereClauseTool.validateWhereClause(clause.where);
  37197. result.where = clause.where;
  37198. }
  37199. if (clause.order != null) {
  37200. OrderClauseTool.validateOrderClause(clause.order);
  37201. result.order = clause.order;
  37202. }
  37203. if (clause.skip != null) {
  37204. SliceClauseTool.validateSkipClause(clause.skip);
  37205. result.skip = clause.skip;
  37206. }
  37207. if (clause.limit != null) {
  37208. SliceClauseTool.validateLimitClause(clause.limit);
  37209. result.limit = clause.limit;
  37210. }
  37211. if (clause.fields != null) {
  37212. FieldsClauseTool.validateFieldsClause(clause.fields);
  37213. result.fields = clause.fields;
  37214. }
  37215. if (clause.include != null) {
  37216. result.include = this.normalizeIncludeClause(clause.include);
  37217. }
  37218. if (Object.keys(result).length) return result;
  37219. return void 0;
  37220. }
  37221. };
  37222. __name(_IncludeClauseTool, "IncludeClauseTool");
  37223. IncludeClauseTool = _IncludeClauseTool;
  37224. }
  37225. });
  37226. // node_modules/@e22m4u/js-repository/src/filter/index.js
  37227. var init_filter = __esm({
  37228. "node_modules/@e22m4u/js-repository/src/filter/index.js"() {
  37229. init_slice_clause_tool();
  37230. init_order_clause_tool();
  37231. init_where_clause_tool();
  37232. init_fields_clause_tool();
  37233. init_include_clause_tool();
  37234. init_operator_clause_tool();
  37235. }
  37236. });
  37237. // node_modules/@e22m4u/js-repository/src/adapter/decorator/inclusion-decorator.js
  37238. var _InclusionDecorator, InclusionDecorator;
  37239. var init_inclusion_decorator = __esm({
  37240. "node_modules/@e22m4u/js-repository/src/adapter/decorator/inclusion-decorator.js"() {
  37241. init_adapter();
  37242. init_src2();
  37243. init_filter();
  37244. init_errors2();
  37245. _InclusionDecorator = class _InclusionDecorator extends Service {
  37246. /**
  37247. * Decorate.
  37248. *
  37249. * @param {Adapter} adapter
  37250. */
  37251. decorate(adapter) {
  37252. if (!adapter || !(adapter instanceof Adapter))
  37253. throw new InvalidArgumentError2(
  37254. "The first argument of InclusionDecorator.decorate should be an Adapter instance, but %v given.",
  37255. adapter
  37256. );
  37257. const tool = adapter.getService(IncludeClauseTool);
  37258. const includeTo = /* @__PURE__ */ __name((...args) => tool.includeTo(...args), "includeTo");
  37259. const create = adapter.create;
  37260. adapter.create = async function(modelName, modelData, filter) {
  37261. const retvalData = await create.call(this, modelName, modelData, filter);
  37262. if (filter && typeof filter === "object" && filter.include)
  37263. await includeTo([retvalData], modelName, filter.include);
  37264. return retvalData;
  37265. };
  37266. const replaceById = adapter.replaceById;
  37267. adapter.replaceById = async function(modelName, id, modelData, filter) {
  37268. const retvalData = await replaceById.call(
  37269. this,
  37270. modelName,
  37271. id,
  37272. modelData,
  37273. filter
  37274. );
  37275. if (filter && typeof filter === "object" && filter.include)
  37276. await includeTo([retvalData], modelName, filter.include);
  37277. return retvalData;
  37278. };
  37279. const replaceOrCreate = adapter.replaceOrCreate;
  37280. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  37281. const retvalData = await replaceOrCreate.call(
  37282. this,
  37283. modelName,
  37284. modelData,
  37285. filter
  37286. );
  37287. if (filter && typeof filter === "object" && filter.include)
  37288. await includeTo([retvalData], modelName, filter.include);
  37289. return retvalData;
  37290. };
  37291. const patchById = adapter.patchById;
  37292. adapter.patchById = async function(modelName, id, modelData, filter) {
  37293. const retvalData = await patchById.call(
  37294. this,
  37295. modelName,
  37296. id,
  37297. modelData,
  37298. filter
  37299. );
  37300. if (filter && typeof filter === "object" && filter.include)
  37301. await includeTo([retvalData], modelName, filter.include);
  37302. return retvalData;
  37303. };
  37304. const find = adapter.find;
  37305. adapter.find = async function(modelName, filter) {
  37306. const modelItems = await find.call(this, modelName, filter);
  37307. if (filter && typeof filter === "object" && filter.include)
  37308. await includeTo(modelItems, modelName, filter.include);
  37309. return modelItems;
  37310. };
  37311. const findById = adapter.findById;
  37312. adapter.findById = async function(modelName, id, filter) {
  37313. const retvalData = await findById.call(this, modelName, id, filter);
  37314. if (filter && typeof filter === "object" && filter.include)
  37315. await includeTo([retvalData], modelName, filter.include);
  37316. return retvalData;
  37317. };
  37318. }
  37319. };
  37320. __name(_InclusionDecorator, "InclusionDecorator");
  37321. InclusionDecorator = _InclusionDecorator;
  37322. }
  37323. });
  37324. // node_modules/@e22m4u/js-repository/src/adapter/decorator/default-values-decorator.js
  37325. var _DefaultValuesDecorator, DefaultValuesDecorator;
  37326. var init_default_values_decorator = __esm({
  37327. "node_modules/@e22m4u/js-repository/src/adapter/decorator/default-values-decorator.js"() {
  37328. init_adapter();
  37329. init_src2();
  37330. init_errors2();
  37331. init_definition();
  37332. _DefaultValuesDecorator = class _DefaultValuesDecorator extends Service {
  37333. /**
  37334. * Decorate.
  37335. *
  37336. * @param {Adapter} adapter
  37337. */
  37338. decorate(adapter) {
  37339. if (!adapter || !(adapter instanceof Adapter))
  37340. throw new InvalidArgumentError2(
  37341. "The first argument of DefaultValuesDecorator.decorate should be an Adapter instance, but %v given.",
  37342. adapter
  37343. );
  37344. const utils = adapter.getService(ModelDefinitionUtils);
  37345. const setDefaults = /* @__PURE__ */ __name((...args) => utils.setDefaultValuesToEmptyProperties(...args), "setDefaults");
  37346. const create = adapter.create;
  37347. adapter.create = function(modelName, modelData, filter) {
  37348. modelData = setDefaults(modelName, modelData);
  37349. return create.call(this, modelName, modelData, filter);
  37350. };
  37351. const replaceById = adapter.replaceById;
  37352. adapter.replaceById = function(modelName, id, modelData, filter) {
  37353. modelData = setDefaults(modelName, modelData);
  37354. return replaceById.call(this, modelName, id, modelData, filter);
  37355. };
  37356. const replaceOrCreate = adapter.replaceOrCreate;
  37357. adapter.replaceOrCreate = function(modelName, modelData, filter) {
  37358. modelData = setDefaults(modelName, modelData);
  37359. return replaceOrCreate.call(this, modelName, modelData, filter);
  37360. };
  37361. const patch = adapter.patch;
  37362. adapter.patch = function(modelName, modelData, where) {
  37363. modelData = setDefaults(modelName, modelData, true);
  37364. return patch.call(this, modelName, modelData, where);
  37365. };
  37366. const patchById = adapter.patchById;
  37367. adapter.patchById = function(modelName, id, modelData, filter) {
  37368. modelData = setDefaults(modelName, modelData, true);
  37369. return patchById.call(this, modelName, id, modelData, filter);
  37370. };
  37371. const find = adapter.find;
  37372. adapter.find = async function(modelName, filter) {
  37373. const modelItems = await find.call(this, modelName, filter);
  37374. return modelItems.map((modelItem) => setDefaults(modelName, modelItem));
  37375. };
  37376. const findById = adapter.findById;
  37377. adapter.findById = async function(modelName, id, filter) {
  37378. const retvalData = await findById.call(this, modelName, id, filter);
  37379. return setDefaults(modelName, retvalData);
  37380. };
  37381. }
  37382. };
  37383. __name(_DefaultValuesDecorator, "DefaultValuesDecorator");
  37384. DefaultValuesDecorator = _DefaultValuesDecorator;
  37385. }
  37386. });
  37387. // node_modules/@e22m4u/js-repository/src/adapter/decorator/data-sanitizing-decorator.js
  37388. var _DataSanitizingDecorator, DataSanitizingDecorator;
  37389. var init_data_sanitizing_decorator = __esm({
  37390. "node_modules/@e22m4u/js-repository/src/adapter/decorator/data-sanitizing-decorator.js"() {
  37391. init_adapter();
  37392. init_src2();
  37393. init_errors2();
  37394. init_definition();
  37395. _DataSanitizingDecorator = class _DataSanitizingDecorator extends Service {
  37396. /**
  37397. * Decorate.
  37398. *
  37399. * @param {Adapter} adapter
  37400. */
  37401. decorate(adapter) {
  37402. if (!adapter || !(adapter instanceof Adapter))
  37403. throw new InvalidArgumentError2(
  37404. "The first argument of DataSanitizingDecorator.decorate should be an Adapter instance, but %v given.",
  37405. adapter
  37406. );
  37407. const sanitizer = adapter.getService(ModelDataSanitizer);
  37408. const sanitize = /* @__PURE__ */ __name((...args) => sanitizer.sanitize(...args), "sanitize");
  37409. const create = adapter.create;
  37410. adapter.create = async function(modelName, modelData, filter) {
  37411. modelData = sanitize(modelName, modelData);
  37412. return create.call(this, modelName, modelData, filter);
  37413. };
  37414. const replaceById = adapter.replaceById;
  37415. adapter.replaceById = async function(modelName, id, modelData, filter) {
  37416. modelData = sanitize(modelName, modelData);
  37417. return replaceById.call(this, modelName, id, modelData, filter);
  37418. };
  37419. const replaceOrCreate = adapter.replaceOrCreate;
  37420. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  37421. modelData = sanitize(modelName, modelData);
  37422. return replaceOrCreate.call(this, modelName, modelData, filter);
  37423. };
  37424. const patch = adapter.patch;
  37425. adapter.patch = async function(modelName, modelData, where) {
  37426. modelData = sanitize(modelName, modelData);
  37427. return patch.call(this, modelName, modelData, where);
  37428. };
  37429. const patchById = adapter.patchById;
  37430. adapter.patchById = async function(modelName, id, modelData, filter) {
  37431. modelData = sanitize(modelName, modelData);
  37432. return patchById.call(this, modelName, id, modelData, filter);
  37433. };
  37434. }
  37435. };
  37436. __name(_DataSanitizingDecorator, "DataSanitizingDecorator");
  37437. DataSanitizingDecorator = _DataSanitizingDecorator;
  37438. }
  37439. });
  37440. // node_modules/@e22m4u/js-repository/src/adapter/decorator/data-validation-decorator.js
  37441. var _DataValidationDecorator, DataValidationDecorator;
  37442. var init_data_validation_decorator = __esm({
  37443. "node_modules/@e22m4u/js-repository/src/adapter/decorator/data-validation-decorator.js"() {
  37444. init_adapter();
  37445. init_src2();
  37446. init_errors2();
  37447. init_definition();
  37448. _DataValidationDecorator = class _DataValidationDecorator extends Service {
  37449. /**
  37450. * Decorate.
  37451. *
  37452. * @param {Adapter} adapter
  37453. */
  37454. decorate(adapter) {
  37455. if (!adapter || !(adapter instanceof Adapter))
  37456. throw new InvalidArgumentError2(
  37457. "The first argument of DataValidationDecorator.decorate should be an Adapter instance, but %v given.",
  37458. adapter
  37459. );
  37460. const validator = this.getService(ModelDataValidator);
  37461. const create = adapter.create;
  37462. adapter.create = function(modelName, modelData, filter) {
  37463. validator.validate(modelName, modelData);
  37464. return create.call(this, modelName, modelData, filter);
  37465. };
  37466. const replaceById = adapter.replaceById;
  37467. adapter.replaceById = function(modelName, id, modelData, filter) {
  37468. validator.validate(modelName, modelData);
  37469. return replaceById.call(this, modelName, id, modelData, filter);
  37470. };
  37471. const replaceOrCreate = adapter.replaceOrCreate;
  37472. adapter.replaceOrCreate = function(modelName, modelData, filter) {
  37473. validator.validate(modelName, modelData);
  37474. return replaceOrCreate.call(this, modelName, modelData, filter);
  37475. };
  37476. const patch = adapter.patch;
  37477. adapter.patch = function(modelName, modelData, where) {
  37478. validator.validate(modelName, modelData, true);
  37479. return patch.call(this, modelName, modelData, where);
  37480. };
  37481. const patchById = adapter.patchById;
  37482. adapter.patchById = function(modelName, id, modelData, filter) {
  37483. validator.validate(modelName, modelData, true);
  37484. return patchById.call(this, modelName, id, modelData, filter);
  37485. };
  37486. }
  37487. };
  37488. __name(_DataValidationDecorator, "DataValidationDecorator");
  37489. DataValidationDecorator = _DataValidationDecorator;
  37490. }
  37491. });
  37492. // node_modules/@e22m4u/js-repository/src/adapter/decorator/fields-filtering-decorator.js
  37493. var _FieldsFilteringDecorator, FieldsFilteringDecorator;
  37494. var init_fields_filtering_decorator = __esm({
  37495. "node_modules/@e22m4u/js-repository/src/adapter/decorator/fields-filtering-decorator.js"() {
  37496. init_adapter();
  37497. init_src2();
  37498. init_filter();
  37499. init_errors2();
  37500. _FieldsFilteringDecorator = class _FieldsFilteringDecorator extends Service {
  37501. /**
  37502. * Decorate.
  37503. *
  37504. * @param {Adapter} adapter
  37505. */
  37506. decorate(adapter) {
  37507. if (!adapter || !(adapter instanceof Adapter))
  37508. throw new InvalidArgumentError2(
  37509. "The first argument of FieldsFilteringDecorator.decorate should be an Adapter instance, but %v given.",
  37510. adapter
  37511. );
  37512. const tool = adapter.getService(FieldsClauseTool);
  37513. const selectFields = /* @__PURE__ */ __name((...args) => tool.filter(...args), "selectFields");
  37514. const create = adapter.create;
  37515. adapter.create = async function(modelName, modelData, filter) {
  37516. let result = await create.call(this, modelName, modelData, filter);
  37517. if (filter && typeof filter === "object" && filter.fields)
  37518. result = selectFields(result, modelName, filter.fields);
  37519. return result;
  37520. };
  37521. const replaceById = adapter.replaceById;
  37522. adapter.replaceById = async function(modelName, id, modelData, filter) {
  37523. let result = await replaceById.call(
  37524. this,
  37525. modelName,
  37526. id,
  37527. modelData,
  37528. filter
  37529. );
  37530. if (filter && typeof filter === "object" && filter.fields)
  37531. result = selectFields(result, modelName, filter.fields);
  37532. return result;
  37533. };
  37534. const replaceOrCreate = adapter.replaceOrCreate;
  37535. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  37536. let result = await replaceOrCreate.call(
  37537. this,
  37538. modelName,
  37539. modelData,
  37540. filter
  37541. );
  37542. if (filter && typeof filter === "object" && filter.fields)
  37543. result = selectFields(result, modelName, filter.fields);
  37544. return result;
  37545. };
  37546. const patchById = adapter.patchById;
  37547. adapter.patchById = async function(modelName, id, modelData, filter) {
  37548. let result = await patchById.call(this, modelName, id, modelData, filter);
  37549. if (filter && typeof filter === "object" && filter.fields)
  37550. result = selectFields(result, modelName, filter.fields);
  37551. return result;
  37552. };
  37553. const find = adapter.find;
  37554. adapter.find = async function(modelName, filter) {
  37555. let result = await find.call(this, modelName, filter);
  37556. if (filter && typeof filter === "object" && filter.fields)
  37557. result = selectFields(result, modelName, filter.fields);
  37558. return result;
  37559. };
  37560. const findById = adapter.findById;
  37561. adapter.findById = async function(modelName, id, filter) {
  37562. let result = await findById.call(this, modelName, id, filter);
  37563. if (filter && typeof filter === "object" && filter.fields)
  37564. result = selectFields(result, modelName, filter.fields);
  37565. return result;
  37566. };
  37567. }
  37568. };
  37569. __name(_FieldsFilteringDecorator, "FieldsFilteringDecorator");
  37570. FieldsFilteringDecorator = _FieldsFilteringDecorator;
  37571. }
  37572. });
  37573. // node_modules/@e22m4u/js-repository/src/adapter/decorator/data-transformation-decorator.js
  37574. var _DataTransformationDecorator, DataTransformationDecorator;
  37575. var init_data_transformation_decorator = __esm({
  37576. "node_modules/@e22m4u/js-repository/src/adapter/decorator/data-transformation-decorator.js"() {
  37577. init_adapter();
  37578. init_src2();
  37579. init_errors2();
  37580. init_definition();
  37581. _DataTransformationDecorator = class _DataTransformationDecorator extends Service {
  37582. /**
  37583. * Decorate.
  37584. *
  37585. * @param {Adapter} adapter
  37586. */
  37587. decorate(adapter) {
  37588. if (!adapter || !(adapter instanceof Adapter))
  37589. throw new InvalidArgumentError2(
  37590. "The first argument of DataTransformerDecorator.decorate should be an Adapter instance, but %v given.",
  37591. adapter
  37592. );
  37593. const transformer = this.getService(ModelDataTransformer);
  37594. const create = adapter.create;
  37595. adapter.create = async function(modelName, modelData, filter) {
  37596. modelData = await transformer.transform(modelName, modelData);
  37597. return create.call(this, modelName, modelData, filter);
  37598. };
  37599. const replaceById = adapter.replaceById;
  37600. adapter.replaceById = async function(modelName, id, modelData, filter) {
  37601. modelData = await transformer.transform(modelName, modelData);
  37602. return replaceById.call(this, modelName, id, modelData, filter);
  37603. };
  37604. const replaceOrCreate = adapter.replaceOrCreate;
  37605. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  37606. modelData = await transformer.transform(modelName, modelData);
  37607. return replaceOrCreate.call(this, modelName, modelData, filter);
  37608. };
  37609. const patch = adapter.patch;
  37610. adapter.patch = async function(modelName, modelData, where) {
  37611. modelData = await transformer.transform(modelName, modelData, true);
  37612. return patch.call(this, modelName, modelData, where);
  37613. };
  37614. const patchById = adapter.patchById;
  37615. adapter.patchById = async function(modelName, id, modelData, filter) {
  37616. modelData = await transformer.transform(modelName, modelData, true);
  37617. return patchById.call(this, modelName, id, modelData, filter);
  37618. };
  37619. }
  37620. };
  37621. __name(_DataTransformationDecorator, "DataTransformationDecorator");
  37622. DataTransformationDecorator = _DataTransformationDecorator;
  37623. }
  37624. });
  37625. // node_modules/@e22m4u/js-repository/src/adapter/decorator/property-uniqueness-decorator.js
  37626. var _PropertyUniquenessDecorator, PropertyUniquenessDecorator;
  37627. var init_property_uniqueness_decorator = __esm({
  37628. "node_modules/@e22m4u/js-repository/src/adapter/decorator/property-uniqueness-decorator.js"() {
  37629. init_adapter();
  37630. init_src2();
  37631. init_errors2();
  37632. init_definition();
  37633. _PropertyUniquenessDecorator = class _PropertyUniquenessDecorator extends Service {
  37634. /**
  37635. * Decorate.
  37636. *
  37637. * @param {Adapter} adapter
  37638. */
  37639. decorate(adapter) {
  37640. if (!adapter || !(adapter instanceof Adapter))
  37641. throw new InvalidArgumentError2(
  37642. "The first argument of PropertyUniquenessDecorator.decorate should be an Adapter instance, but %v given.",
  37643. adapter
  37644. );
  37645. const validator = this.getService(PropertyUniquenessValidator);
  37646. const create = adapter.create;
  37647. adapter.create = async function(modelName, modelData, filter) {
  37648. const countMethod = adapter.count.bind(adapter, modelName);
  37649. await validator.validate(countMethod, "create", modelName, modelData);
  37650. return create.call(this, modelName, modelData, filter);
  37651. };
  37652. const replaceById = adapter.replaceById;
  37653. adapter.replaceById = async function(modelName, id, modelData, filter) {
  37654. const countMethod = adapter.count.bind(adapter, modelName);
  37655. await validator.validate(
  37656. countMethod,
  37657. "replaceById",
  37658. modelName,
  37659. modelData,
  37660. id
  37661. );
  37662. return replaceById.call(this, modelName, id, modelData, filter);
  37663. };
  37664. const replaceOrCreate = adapter.replaceOrCreate;
  37665. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  37666. const countMethod = adapter.count.bind(adapter, modelName);
  37667. await validator.validate(
  37668. countMethod,
  37669. "replaceOrCreate",
  37670. modelName,
  37671. modelData
  37672. );
  37673. return replaceOrCreate.call(this, modelName, modelData, filter);
  37674. };
  37675. const patch = adapter.patch;
  37676. adapter.patch = async function(modelName, modelData, where) {
  37677. const countMethod = adapter.count.bind(adapter, modelName);
  37678. await validator.validate(countMethod, "patch", modelName, modelData);
  37679. return patch.call(this, modelName, modelData, where);
  37680. };
  37681. const patchById = adapter.patchById;
  37682. adapter.patchById = async function(modelName, id, modelData, filter) {
  37683. const countMethod = adapter.count.bind(adapter, modelName);
  37684. await validator.validate(
  37685. countMethod,
  37686. "patchById",
  37687. modelName,
  37688. modelData,
  37689. id
  37690. );
  37691. return patchById.call(this, modelName, id, modelData, filter);
  37692. };
  37693. }
  37694. };
  37695. __name(_PropertyUniquenessDecorator, "PropertyUniquenessDecorator");
  37696. PropertyUniquenessDecorator = _PropertyUniquenessDecorator;
  37697. }
  37698. });
  37699. // node_modules/@e22m4u/js-repository/src/adapter/decorator/index.js
  37700. var init_decorator = __esm({
  37701. "node_modules/@e22m4u/js-repository/src/adapter/decorator/index.js"() {
  37702. init_inclusion_decorator();
  37703. init_default_values_decorator();
  37704. init_data_sanitizing_decorator();
  37705. init_data_validation_decorator();
  37706. init_fields_filtering_decorator();
  37707. init_data_transformation_decorator();
  37708. init_property_uniqueness_decorator();
  37709. }
  37710. });
  37711. // node_modules/@e22m4u/js-repository/src/adapter/adapter.js
  37712. var _Adapter, Adapter;
  37713. var init_adapter = __esm({
  37714. "node_modules/@e22m4u/js-repository/src/adapter/adapter.js"() {
  37715. init_src2();
  37716. init_errors2();
  37717. init_decorator();
  37718. init_decorator();
  37719. init_decorator();
  37720. init_decorator();
  37721. init_decorator();
  37722. init_decorator();
  37723. init_decorator();
  37724. _Adapter = class _Adapter extends Service {
  37725. /**
  37726. * Settings.
  37727. *
  37728. * @type {object|undefined}
  37729. */
  37730. _settings;
  37731. /**
  37732. * Settings.
  37733. *
  37734. * @returns {object|undefined}
  37735. */
  37736. get settings() {
  37737. return this._settings;
  37738. }
  37739. /**
  37740. * Constructor.
  37741. *
  37742. * @param {object|undefined} container
  37743. * @param {object|undefined} settings
  37744. */
  37745. constructor(container = void 0, settings = void 0) {
  37746. super(container);
  37747. this._settings = settings;
  37748. if (this.constructor !== _Adapter) {
  37749. this.getService(DataSanitizingDecorator).decorate(this);
  37750. this.getService(DefaultValuesDecorator).decorate(this);
  37751. this.getService(DataTransformationDecorator).decorate(this);
  37752. this.getService(DataValidationDecorator).decorate(this);
  37753. this.getService(PropertyUniquenessDecorator).decorate(this);
  37754. this.getService(FieldsFilteringDecorator).decorate(this);
  37755. this.getService(InclusionDecorator).decorate(this);
  37756. }
  37757. }
  37758. /**
  37759. * Create.
  37760. *
  37761. * @param {string} modelName
  37762. * @param {object} modelData
  37763. * @param {object|undefined} filter
  37764. * @returns {Promise<object>}
  37765. */
  37766. create(modelName, modelData, filter = void 0) {
  37767. throw new NotImplementedError(
  37768. "%s.create is not implemented.",
  37769. this.constructor.name
  37770. );
  37771. }
  37772. /**
  37773. * Replace by id.
  37774. *
  37775. * @param {string} modelName
  37776. * @param {number|string} id
  37777. * @param {object} modelData
  37778. * @param {object|undefined} filter
  37779. * @returns {Promise<object>}
  37780. */
  37781. replaceById(modelName, id, modelData, filter = void 0) {
  37782. throw new NotImplementedError(
  37783. "%s.replaceById is not implemented.",
  37784. this.constructor.name
  37785. );
  37786. }
  37787. /**
  37788. * Replace or create.
  37789. *
  37790. * @param {string} modelName
  37791. * @param {object} modelData
  37792. * @param {object|undefined} filter
  37793. * @returns {Promise<object>}
  37794. */
  37795. replaceOrCreate(modelName, modelData, filter = void 0) {
  37796. throw new NotImplementedError(
  37797. "%s.replaceOrCreate is not implemented.",
  37798. this.constructor.name
  37799. );
  37800. }
  37801. /**
  37802. * Patch.
  37803. *
  37804. * @param {string} modelName
  37805. * @param {object} modelData
  37806. * @param {object|undefined} where
  37807. * @returns {Promise<number>}
  37808. */
  37809. patch(modelName, modelData, where = void 0) {
  37810. throw new NotImplementedError(
  37811. "%s.patch is not implemented.",
  37812. this.constructor.name
  37813. );
  37814. }
  37815. /**
  37816. * Patch by id.
  37817. *
  37818. * @param {string} modelName
  37819. * @param {number|string} id
  37820. * @param {object} modelData
  37821. * @param {object|undefined} filter
  37822. * @returns {Promise<object>}
  37823. */
  37824. patchById(modelName, id, modelData, filter = void 0) {
  37825. throw new NotImplementedError(
  37826. "%s.patchById is not implemented.",
  37827. this.constructor.name
  37828. );
  37829. }
  37830. /**
  37831. * Find.
  37832. *
  37833. * @param {string} modelName
  37834. * @param {object|undefined} filter
  37835. * @returns {Promise<object[]>}
  37836. */
  37837. find(modelName, filter = void 0) {
  37838. throw new NotImplementedError(
  37839. "%s.find is not implemented.",
  37840. this.constructor.name
  37841. );
  37842. }
  37843. /**
  37844. * Find by id.
  37845. *
  37846. * @param {string} modelName
  37847. * @param {number|string} id
  37848. * @param {object|undefined} filter
  37849. * @returns {Promise<object>}
  37850. */
  37851. findById(modelName, id, filter = void 0) {
  37852. throw new NotImplementedError(
  37853. "%s.findById is not implemented.",
  37854. this.constructor.name
  37855. );
  37856. }
  37857. /**
  37858. * Delete.
  37859. *
  37860. * @param {string} modelName
  37861. * @param {object|undefined} where
  37862. * @returns {Promise<number>}
  37863. */
  37864. delete(modelName, where = void 0) {
  37865. throw new NotImplementedError(
  37866. "%s.delete is not implemented.",
  37867. this.constructor.name
  37868. );
  37869. }
  37870. /**
  37871. * Delete by id.
  37872. *
  37873. * @param {string} modelName
  37874. * @param {number|string} id
  37875. * @returns {Promise<boolean>}
  37876. */
  37877. deleteById(modelName, id) {
  37878. throw new NotImplementedError(
  37879. "%s.deleteById is not implemented.",
  37880. this.constructor.name
  37881. );
  37882. }
  37883. /**
  37884. * Exists.
  37885. *
  37886. * @param {string} modelName
  37887. * @param {number|string} id
  37888. * @returns {Promise<boolean>}
  37889. */
  37890. exists(modelName, id) {
  37891. throw new NotImplementedError(
  37892. "%s.exists is not implemented.",
  37893. this.constructor.name
  37894. );
  37895. }
  37896. /**
  37897. * Count.
  37898. *
  37899. * @param {string} modelName
  37900. * @param {object|undefined} where
  37901. * @returns {Promise<number>}
  37902. */
  37903. count(modelName, where = void 0) {
  37904. throw new NotImplementedError(
  37905. "%s.count is not implemented.",
  37906. this.constructor.name
  37907. );
  37908. }
  37909. };
  37910. __name(_Adapter, "Adapter");
  37911. Adapter = _Adapter;
  37912. }
  37913. });
  37914. // node_modules/@e22m4u/js-repository/src/adapter/builtin/memory-adapter.js
  37915. var memory_adapter_exports = {};
  37916. __export(memory_adapter_exports, {
  37917. MemoryAdapter: () => MemoryAdapter
  37918. });
  37919. var _MemoryAdapter, MemoryAdapter;
  37920. var init_memory_adapter = __esm({
  37921. "node_modules/@e22m4u/js-repository/src/adapter/builtin/memory-adapter.js"() {
  37922. init_adapter();
  37923. init_utils2();
  37924. init_utils2();
  37925. init_definition();
  37926. init_filter();
  37927. init_filter();
  37928. init_filter();
  37929. init_errors2();
  37930. init_definition();
  37931. _MemoryAdapter = class _MemoryAdapter extends Adapter {
  37932. /**
  37933. * Tables.
  37934. *
  37935. * @type {Map<string, Map<number, Record<string, any>>>}
  37936. */
  37937. _tables = /* @__PURE__ */ new Map();
  37938. /**
  37939. * Last ids.
  37940. *
  37941. * @type {Map<string, number>}
  37942. */
  37943. _lastIds = /* @__PURE__ */ new Map();
  37944. /**
  37945. * Get table or create.
  37946. *
  37947. * @param {string} modelName
  37948. * @returns {Map<number, object>}
  37949. */
  37950. _getTableOrCreate(modelName) {
  37951. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  37952. let table = this._tables.get(tableName);
  37953. if (table) return table;
  37954. table = /* @__PURE__ */ new Map();
  37955. this._tables.set(tableName, table);
  37956. return table;
  37957. }
  37958. /**
  37959. * Gen next id value.
  37960. *
  37961. * @param {string} modelName
  37962. * @param {string} propName
  37963. * @returns {number}
  37964. */
  37965. _genNextIdValue(modelName, propName) {
  37966. const propType = this.getService(
  37967. ModelDefinitionUtils
  37968. ).getDataTypeByPropertyName(modelName, propName);
  37969. if (propType !== DataType.ANY && propType !== DataType.NUMBER)
  37970. throw new InvalidArgumentError2(
  37971. "The memory adapter able to generate only Number identifiers, but the primary key %v of the model %v is defined as %s. Do provide your own value for the %v property, or change the type in the primary key definition to a Number that will be generated automatically.",
  37972. propName,
  37973. modelName,
  37974. capitalize(propType),
  37975. propName
  37976. );
  37977. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  37978. const lastId = this._lastIds.get(tableName) ?? 0;
  37979. const nextId = lastId + 1;
  37980. this._lastIds.set(tableName, nextId);
  37981. const table = this._getTableOrCreate(modelName);
  37982. const existedIds = Array.from(table.keys());
  37983. if (existedIds.includes(nextId))
  37984. return this._genNextIdValue(modelName, propName);
  37985. return nextId;
  37986. }
  37987. /**
  37988. * Create
  37989. *
  37990. * @param {string} modelName
  37991. * @param {object} modelData
  37992. * @param {object|undefined} filter
  37993. * @returns {Promise<object>}
  37994. */
  37995. // eslint-disable-next-line no-unused-vars
  37996. async create(modelName, modelData, filter = void 0) {
  37997. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  37998. modelName
  37999. );
  38000. let idValue = modelData[pkPropName];
  38001. if (idValue == null || idValue === "" || idValue === 0) {
  38002. idValue = this._genNextIdValue(modelName, pkPropName);
  38003. }
  38004. const table = this._getTableOrCreate(modelName);
  38005. if (table.has(idValue))
  38006. throw new InvalidArgumentError2(
  38007. "The value %v of the primary key %v already exists in the model %v.",
  38008. idValue,
  38009. pkPropName,
  38010. modelName
  38011. );
  38012. modelData = cloneDeep(modelData);
  38013. modelData[pkPropName] = idValue;
  38014. const tableData = this.getService(
  38015. ModelDefinitionUtils
  38016. ).convertPropertyNamesToColumnNames(modelName, modelData);
  38017. table.set(idValue, tableData);
  38018. return this.getService(
  38019. ModelDefinitionUtils
  38020. ).convertColumnNamesToPropertyNames(modelName, tableData);
  38021. }
  38022. /**
  38023. * Replace by id.
  38024. *
  38025. * @param {string} modelName
  38026. * @param {string|number} id
  38027. * @param {object} modelData
  38028. * @param {object|undefined} filter
  38029. * @returns {Promise<object>}
  38030. */
  38031. // eslint-disable-next-line no-unused-vars
  38032. async replaceById(modelName, id, modelData, filter = void 0) {
  38033. const table = this._getTableOrCreate(modelName);
  38034. const isExists = table.has(id);
  38035. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  38036. modelName
  38037. );
  38038. if (!isExists)
  38039. throw new InvalidArgumentError2(
  38040. "The value %v of the primary key %v does not exist in the model %v.",
  38041. id,
  38042. pkPropName,
  38043. modelName
  38044. );
  38045. modelData = cloneDeep(modelData);
  38046. modelData[pkPropName] = id;
  38047. const tableData = this.getService(
  38048. ModelDefinitionUtils
  38049. ).convertPropertyNamesToColumnNames(modelName, modelData);
  38050. table.set(id, tableData);
  38051. return this.getService(
  38052. ModelDefinitionUtils
  38053. ).convertColumnNamesToPropertyNames(modelName, tableData);
  38054. }
  38055. /**
  38056. * Replace or create.
  38057. *
  38058. * @param {string} modelName
  38059. * @param {object} modelData
  38060. * @param {object|undefined} filter
  38061. * @returns {Promise<object>}
  38062. */
  38063. // eslint-disable-next-line no-unused-vars
  38064. async replaceOrCreate(modelName, modelData, filter = void 0) {
  38065. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  38066. modelName
  38067. );
  38068. let idValue = modelData[pkPropName];
  38069. if (idValue == null || idValue === "" || idValue === 0) {
  38070. idValue = this._genNextIdValue(modelName, pkPropName);
  38071. }
  38072. const table = this._getTableOrCreate(modelName);
  38073. modelData = cloneDeep(modelData);
  38074. modelData[pkPropName] = idValue;
  38075. const tableData = this.getService(
  38076. ModelDefinitionUtils
  38077. ).convertPropertyNamesToColumnNames(modelName, modelData);
  38078. table.set(idValue, tableData);
  38079. return this.getService(
  38080. ModelDefinitionUtils
  38081. ).convertColumnNamesToPropertyNames(modelName, tableData);
  38082. }
  38083. /**
  38084. * Patch.
  38085. *
  38086. * @param {string} modelName
  38087. * @param {object} modelData
  38088. * @param {object|undefined} where
  38089. * @returns {Promise<number>}
  38090. */
  38091. async patch(modelName, modelData, where = void 0) {
  38092. const table = this._getTableOrCreate(modelName);
  38093. const tableItems = Array.from(table.values());
  38094. if (!tableItems.length) return 0;
  38095. let modelItems = tableItems.map(
  38096. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  38097. modelName,
  38098. tableItem
  38099. )
  38100. );
  38101. if (where && typeof where === "object")
  38102. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  38103. const size = modelItems.length;
  38104. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  38105. modelName
  38106. );
  38107. modelData = cloneDeep(modelData);
  38108. delete modelData[pkPropName];
  38109. modelItems.forEach((existingModelData) => {
  38110. const mergedModelData = Object.assign({}, existingModelData, modelData);
  38111. const mergedTableData = this.getService(
  38112. ModelDefinitionUtils
  38113. ).convertPropertyNamesToColumnNames(modelName, mergedModelData);
  38114. const idValue = existingModelData[pkPropName];
  38115. table.set(idValue, mergedTableData);
  38116. });
  38117. return size;
  38118. }
  38119. /**
  38120. * Patch by id.
  38121. *
  38122. * @param {string} modelName
  38123. * @param {string|number} id
  38124. * @param {object} modelData
  38125. * @param {object|undefined} filter
  38126. * @returns {Promise<object>}
  38127. */
  38128. // eslint-disable-next-line no-unused-vars
  38129. async patchById(modelName, id, modelData, filter = void 0) {
  38130. const table = this._getTableOrCreate(modelName);
  38131. const existingTableData = table.get(id);
  38132. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  38133. modelName
  38134. );
  38135. if (existingTableData == null)
  38136. throw new InvalidArgumentError2(
  38137. "The value %v of the primary key %v does not exist in the model %v.",
  38138. id,
  38139. pkPropName,
  38140. modelName
  38141. );
  38142. modelData = cloneDeep(modelData);
  38143. delete modelData[pkPropName];
  38144. const existingModelData = this.getService(
  38145. ModelDefinitionUtils
  38146. ).convertColumnNamesToPropertyNames(modelName, existingTableData);
  38147. const mergedModelData = Object.assign({}, existingModelData, modelData);
  38148. const mergedTableData = this.getService(
  38149. ModelDefinitionUtils
  38150. ).convertPropertyNamesToColumnNames(modelName, mergedModelData);
  38151. table.set(id, mergedTableData);
  38152. return this.getService(
  38153. ModelDefinitionUtils
  38154. ).convertColumnNamesToPropertyNames(modelName, mergedTableData);
  38155. }
  38156. /**
  38157. * Find.
  38158. *
  38159. * @param {string} modelName
  38160. * @param {object|undefined} filter
  38161. * @returns {Promise<object[]>}
  38162. */
  38163. async find(modelName, filter = void 0) {
  38164. const table = this._getTableOrCreate(modelName);
  38165. const tableItems = Array.from(table.values());
  38166. let modelItems = tableItems.map(
  38167. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  38168. modelName,
  38169. tableItem
  38170. )
  38171. );
  38172. if (filter && typeof filter === "object") {
  38173. if (filter.where)
  38174. modelItems = this.getService(WhereClauseTool).filter(
  38175. modelItems,
  38176. filter.where
  38177. );
  38178. if (filter.skip || filter.limit)
  38179. modelItems = this.getService(SliceClauseTool).slice(
  38180. modelItems,
  38181. filter.skip,
  38182. filter.limit
  38183. );
  38184. if (filter.order)
  38185. this.getService(OrderClauseTool).sort(modelItems, filter.order);
  38186. }
  38187. return modelItems;
  38188. }
  38189. /**
  38190. * Find by id.
  38191. *
  38192. * @param {string} modelName
  38193. * @param {string|number} id
  38194. * @param {object|undefined} filter
  38195. * @returns {Promise<object>}
  38196. */
  38197. // eslint-disable-next-line no-unused-vars
  38198. async findById(modelName, id, filter = void 0) {
  38199. const table = this._getTableOrCreate(modelName);
  38200. const tableData = table.get(id);
  38201. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  38202. modelName
  38203. );
  38204. if (!tableData)
  38205. throw new InvalidArgumentError2(
  38206. "The value %v of the primary key %v does not exist in the model %v.",
  38207. id,
  38208. pkPropName,
  38209. modelName
  38210. );
  38211. return this.getService(
  38212. ModelDefinitionUtils
  38213. ).convertColumnNamesToPropertyNames(modelName, tableData);
  38214. }
  38215. /**
  38216. * Delete.
  38217. *
  38218. * @param {string} modelName
  38219. * @param {object|undefined} where
  38220. * @returns {Promise<number>}
  38221. */
  38222. async delete(modelName, where = void 0) {
  38223. const table = this._getTableOrCreate(modelName);
  38224. const tableItems = Array.from(table.values());
  38225. if (!tableItems.length) return 0;
  38226. let modelItems = tableItems.map(
  38227. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  38228. modelName,
  38229. tableItem
  38230. )
  38231. );
  38232. if (where && typeof where === "object")
  38233. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  38234. const size = modelItems.length;
  38235. const idPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  38236. modelName
  38237. );
  38238. modelItems.forEach((modelData) => {
  38239. const idValue = modelData[idPropName];
  38240. table.delete(idValue);
  38241. });
  38242. return size;
  38243. }
  38244. /**
  38245. * Delete by id.
  38246. *
  38247. * @param {string} modelName
  38248. * @param {string|number} id
  38249. * @returns {Promise<boolean>}
  38250. */
  38251. async deleteById(modelName, id) {
  38252. const table = this._getTableOrCreate(modelName);
  38253. const isExists = table.has(id);
  38254. table.delete(id);
  38255. return isExists;
  38256. }
  38257. /**
  38258. * Exists.
  38259. *
  38260. * @param {string} modelName
  38261. * @param {string|number} id
  38262. * @returns {Promise<boolean>}
  38263. */
  38264. async exists(modelName, id) {
  38265. const table = this._getTableOrCreate(modelName);
  38266. return table.has(id);
  38267. }
  38268. /**
  38269. * Count.
  38270. *
  38271. * @param {string} modelName
  38272. * @param {object|undefined} where
  38273. * @returns {Promise<number>}
  38274. */
  38275. async count(modelName, where = void 0) {
  38276. const table = this._getTableOrCreate(modelName);
  38277. const tableItems = Array.from(table.values());
  38278. let modelItems = tableItems.map(
  38279. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  38280. modelName,
  38281. tableItem
  38282. )
  38283. );
  38284. if (where && typeof where === "object")
  38285. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  38286. return modelItems.length;
  38287. }
  38288. };
  38289. __name(_MemoryAdapter, "MemoryAdapter");
  38290. MemoryAdapter = _MemoryAdapter;
  38291. }
  38292. });
  38293. // import("./builtin/**/*-adapter.js") in node_modules/@e22m4u/js-repository/src/adapter/adapter-loader.js
  38294. var globImport_builtin_adapter_js;
  38295. var init_ = __esm({
  38296. 'import("./builtin/**/*-adapter.js") in node_modules/@e22m4u/js-repository/src/adapter/adapter-loader.js'() {
  38297. globImport_builtin_adapter_js = __glob({
  38298. "./builtin/memory-adapter.js": () => Promise.resolve().then(() => (init_memory_adapter(), memory_adapter_exports))
  38299. });
  38300. }
  38301. });
  38302. // node_modules/@e22m4u/js-repository/src/adapter/adapter-loader.js
  38303. function findAdapterCtorInModule(module2) {
  38304. let adapterCtor;
  38305. if (!module2 || typeof module2 !== "object" || Array.isArray(module2)) return;
  38306. for (const ctor of Object.values(module2)) {
  38307. if (typeof ctor === "function" && ctor.prototype instanceof Adapter) {
  38308. adapterCtor = ctor;
  38309. break;
  38310. }
  38311. }
  38312. return adapterCtor;
  38313. }
  38314. var _AdapterLoader, AdapterLoader;
  38315. var init_adapter_loader = __esm({
  38316. "node_modules/@e22m4u/js-repository/src/adapter/adapter-loader.js"() {
  38317. init_adapter();
  38318. init_src2();
  38319. init_errors2();
  38320. init_();
  38321. _AdapterLoader = class _AdapterLoader extends Service {
  38322. /**
  38323. * Load by name.
  38324. *
  38325. * @param {string} adapterName
  38326. * @param {object|undefined} settings
  38327. * @returns {Promise<Adapter>}
  38328. */
  38329. async loadByName(adapterName, settings = void 0) {
  38330. if (!adapterName || typeof adapterName !== "string")
  38331. throw new InvalidArgumentError2(
  38332. "The adapter name should be a non-empty String, but %v given.",
  38333. adapterName
  38334. );
  38335. let adapterCtor;
  38336. try {
  38337. const module2 = await globImport_builtin_adapter_js(`./builtin/${adapterName}-adapter.js`);
  38338. adapterCtor = findAdapterCtorInModule(module2);
  38339. } catch (e) {
  38340. }
  38341. if (!adapterCtor)
  38342. try {
  38343. const module2 = await import(`@e22m4u/js-repository-${adapterName}-adapter`);
  38344. adapterCtor = findAdapterCtorInModule(module2);
  38345. } catch (e) {
  38346. }
  38347. if (!adapterCtor)
  38348. throw new InvalidArgumentError2(
  38349. "The adapter %v is not found.",
  38350. adapterName
  38351. );
  38352. return new adapterCtor(this.container, settings);
  38353. }
  38354. };
  38355. __name(_AdapterLoader, "AdapterLoader");
  38356. AdapterLoader = _AdapterLoader;
  38357. __name(findAdapterCtorInModule, "findAdapterCtorInModule");
  38358. }
  38359. });
  38360. // node_modules/@e22m4u/js-repository/src/adapter/adapter-registry.js
  38361. var _AdapterRegistry, AdapterRegistry;
  38362. var init_adapter_registry = __esm({
  38363. "node_modules/@e22m4u/js-repository/src/adapter/adapter-registry.js"() {
  38364. init_adapter();
  38365. init_src2();
  38366. init_adapter_loader();
  38367. init_definition();
  38368. _AdapterRegistry = class _AdapterRegistry extends Service {
  38369. /**
  38370. * Adapters.
  38371. *
  38372. * @type {object}
  38373. */
  38374. _adapters = {};
  38375. /**
  38376. * Get adapter.
  38377. *
  38378. * @param {string} datasourceName
  38379. * @returns {Promise<Adapter>}
  38380. */
  38381. async getAdapter(datasourceName) {
  38382. let adapter = this._adapters[datasourceName];
  38383. if (adapter) return adapter;
  38384. const datasource = this.getService(DefinitionRegistry).getDatasource(datasourceName);
  38385. const adapterName = datasource.adapter;
  38386. adapter = await this.getService(AdapterLoader).loadByName(
  38387. adapterName,
  38388. datasource
  38389. );
  38390. this._adapters[datasourceName] = adapter;
  38391. return adapter;
  38392. }
  38393. };
  38394. __name(_AdapterRegistry, "AdapterRegistry");
  38395. AdapterRegistry = _AdapterRegistry;
  38396. }
  38397. });
  38398. // node_modules/@e22m4u/js-repository/src/adapter/index.js
  38399. var init_adapter2 = __esm({
  38400. "node_modules/@e22m4u/js-repository/src/adapter/index.js"() {
  38401. init_adapter();
  38402. init_adapter_loader();
  38403. init_adapter_registry();
  38404. }
  38405. });
  38406. // node_modules/@e22m4u/js-repository/src/repository/repository.js
  38407. var _Repository, Repository;
  38408. var init_repository = __esm({
  38409. "node_modules/@e22m4u/js-repository/src/repository/repository.js"() {
  38410. init_src2();
  38411. init_adapter2();
  38412. init_adapter2();
  38413. init_errors2();
  38414. init_definition();
  38415. _Repository = class _Repository extends Service {
  38416. /**
  38417. * Model name.
  38418. *
  38419. * @type {string}
  38420. */
  38421. _modelName;
  38422. /**
  38423. * Model name.
  38424. *
  38425. * @returns {string}
  38426. */
  38427. get modelName() {
  38428. return this._modelName;
  38429. }
  38430. /**
  38431. * Datasource name.
  38432. *
  38433. * @type {string}
  38434. */
  38435. _datasourceName;
  38436. /**
  38437. * Datasource name.
  38438. *
  38439. * @returns {string}
  38440. */
  38441. get datasourceName() {
  38442. return this._datasourceName;
  38443. }
  38444. /**
  38445. * Constructor.
  38446. *
  38447. * @typedef {import('@e22m4u/js-service').ServiceContainer} ServiceContainer
  38448. * @param {ServiceContainer} container
  38449. * @param {string} modelName
  38450. */
  38451. constructor(container, modelName) {
  38452. super(container);
  38453. this._modelName = modelName;
  38454. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  38455. const datasourceName = modelDef.datasource;
  38456. if (!datasourceName)
  38457. throw new InvalidArgumentError2(
  38458. "The model %v does not have a specified datasource.",
  38459. modelName
  38460. );
  38461. this._datasourceName = datasourceName;
  38462. }
  38463. /**
  38464. * Get adapter.
  38465. *
  38466. * @returns {Adapter}
  38467. */
  38468. async getAdapter() {
  38469. return this.getService(AdapterRegistry).getAdapter(this.datasourceName);
  38470. }
  38471. /**
  38472. * Create.
  38473. *
  38474. * @param {object} data
  38475. * @param {object|undefined} filter
  38476. * @returns {Promise<object>}
  38477. */
  38478. async create(data, filter = void 0) {
  38479. const adapter = await this.getAdapter();
  38480. return adapter.create(this.modelName, data, filter);
  38481. }
  38482. /**
  38483. * Replace by id.
  38484. *
  38485. * @param {number|string} id
  38486. * @param {object} data
  38487. * @param {object|undefined} filter
  38488. * @returns {Promise<object>}
  38489. */
  38490. async replaceById(id, data, filter = void 0) {
  38491. const adapter = await this.getAdapter();
  38492. return adapter.replaceById(this.modelName, id, data, filter);
  38493. }
  38494. /**
  38495. * Replace or create.
  38496. *
  38497. * @param {object} data
  38498. * @param {object|undefined} filter
  38499. * @returns {Promise<object>}
  38500. */
  38501. async replaceOrCreate(data, filter = void 0) {
  38502. const adapter = await this.getAdapter();
  38503. return adapter.replaceOrCreate(this.modelName, data, filter);
  38504. }
  38505. /**
  38506. * Patch.
  38507. *
  38508. * @param {object} data
  38509. * @param {object|undefined} where
  38510. * @returns {Promise<number>}
  38511. */
  38512. async patch(data, where = void 0) {
  38513. const adapter = await this.getAdapter();
  38514. return adapter.patch(this.modelName, data, where);
  38515. }
  38516. /**
  38517. * Patch by id.
  38518. *
  38519. * @param {number|string} id
  38520. * @param {object} data
  38521. * @param {object|undefined} filter
  38522. * @returns {Promise<object>}
  38523. */
  38524. async patchById(id, data, filter = void 0) {
  38525. const adapter = await this.getAdapter();
  38526. return adapter.patchById(this.modelName, id, data, filter);
  38527. }
  38528. /**
  38529. * Find.
  38530. *
  38531. * @param {object|undefined} filter
  38532. * @returns {Promise<object[]>}
  38533. */
  38534. async find(filter = void 0) {
  38535. const adapter = await this.getAdapter();
  38536. return adapter.find(this.modelName, filter);
  38537. }
  38538. /**
  38539. * Find one.
  38540. *
  38541. * @param {object|undefined} filter
  38542. * @returns {Promise<object|undefined>}
  38543. */
  38544. async findOne(filter = void 0) {
  38545. const adapter = await this.getAdapter();
  38546. filter = filter ?? {};
  38547. filter.limit = 1;
  38548. const result = await adapter.find(this.modelName, filter);
  38549. return result.length ? result[0] : void 0;
  38550. }
  38551. /**
  38552. * Find by id.
  38553. *
  38554. * @param {number|string} id
  38555. * @param {object|undefined} filter
  38556. * @returns {Promise<object>}
  38557. */
  38558. async findById(id, filter = void 0) {
  38559. const adapter = await this.getAdapter();
  38560. return adapter.findById(this.modelName, id, filter);
  38561. }
  38562. /**
  38563. * Delete.
  38564. *
  38565. * @param {object|undefined} where
  38566. * @returns {Promise<number>}
  38567. */
  38568. async delete(where = void 0) {
  38569. const adapter = await this.getAdapter();
  38570. return adapter.delete(this.modelName, where);
  38571. }
  38572. /**
  38573. * Delete by id.
  38574. *
  38575. * @param {number|string} id
  38576. * @returns {Promise<boolean>}
  38577. */
  38578. async deleteById(id) {
  38579. const adapter = await this.getAdapter();
  38580. return adapter.deleteById(this.modelName, id);
  38581. }
  38582. /**
  38583. * Exists.
  38584. *
  38585. * @param {number|string} id
  38586. * @returns {Promise<boolean>}
  38587. */
  38588. async exists(id) {
  38589. const adapter = await this.getAdapter();
  38590. return adapter.exists(this.modelName, id);
  38591. }
  38592. /**
  38593. * Count.
  38594. *
  38595. * @param {object|undefined} where
  38596. * @returns {Promise<number>}
  38597. */
  38598. async count(where = void 0) {
  38599. const adapter = await this.getAdapter();
  38600. return adapter.count(this.modelName, where);
  38601. }
  38602. };
  38603. __name(_Repository, "Repository");
  38604. Repository = _Repository;
  38605. }
  38606. });
  38607. // node_modules/@e22m4u/js-repository/src/repository/repository-registry.js
  38608. var _RepositoryRegistry, RepositoryRegistry;
  38609. var init_repository_registry = __esm({
  38610. "node_modules/@e22m4u/js-repository/src/repository/repository-registry.js"() {
  38611. init_src2();
  38612. init_repository();
  38613. init_errors2();
  38614. _RepositoryRegistry = class _RepositoryRegistry extends Service {
  38615. /**
  38616. * Repositories.
  38617. *
  38618. * @type {object}
  38619. */
  38620. _repositories = {};
  38621. /**
  38622. * Repository ctor.
  38623. *
  38624. * @type {typeof Repository}
  38625. * @private
  38626. */
  38627. _repositoryCtor = Repository;
  38628. /**
  38629. * Set repository ctor.
  38630. *
  38631. * @param {typeof Repository} ctor
  38632. */
  38633. setRepositoryCtor(ctor) {
  38634. if (!ctor || typeof ctor !== "function" || !(ctor.prototype instanceof Repository)) {
  38635. throw new InvalidArgumentError2(
  38636. "The first argument of RepositoryRegistry.setRepositoryCtor must inherit from Repository class, but %v given.",
  38637. ctor
  38638. );
  38639. }
  38640. this._repositoryCtor = ctor;
  38641. }
  38642. /**
  38643. * Get repository.
  38644. *
  38645. * @param {string} modelName
  38646. * @returns {Repository}
  38647. */
  38648. getRepository(modelName) {
  38649. let repository = this._repositories[modelName];
  38650. if (repository) return repository;
  38651. repository = new this._repositoryCtor(this.container, modelName);
  38652. this._repositories[modelName] = repository;
  38653. return repository;
  38654. }
  38655. };
  38656. __name(_RepositoryRegistry, "RepositoryRegistry");
  38657. RepositoryRegistry = _RepositoryRegistry;
  38658. }
  38659. });
  38660. // node_modules/@e22m4u/js-repository/src/repository/index.js
  38661. var init_repository2 = __esm({
  38662. "node_modules/@e22m4u/js-repository/src/repository/index.js"() {
  38663. init_repository();
  38664. init_repository_registry();
  38665. }
  38666. });
  38667. // src/index.js
  38668. var src_exports = {};
  38669. __export(src_exports, {
  38670. MongodbAdapter: () => MongodbAdapter
  38671. });
  38672. module.exports = __toCommonJS(src_exports);
  38673. // src/mongodb-adapter.js
  38674. var import_mongodb2 = __toESM(require_lib3(), 1);
  38675. var import_mongodb3 = __toESM(require_lib3(), 1);
  38676. // src/utils/is-iso-date.js
  38677. function isIsoDate(value) {
  38678. if (!value) return false;
  38679. if (value instanceof Date) return true;
  38680. if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(value)) return false;
  38681. const d = new Date(value);
  38682. return d instanceof Date && !isNaN(d.getTime()) && d.toISOString() === value;
  38683. }
  38684. __name(isIsoDate, "isIsoDate");
  38685. // src/utils/is-object-id.js
  38686. var import_mongodb = __toESM(require_lib3(), 1);
  38687. function isObjectId(value) {
  38688. if (!value) return false;
  38689. if (value instanceof import_mongodb.ObjectId) return true;
  38690. if (typeof value !== "string") return false;
  38691. return value.match(/^[a-fA-F0-9]{24}$/) != null;
  38692. }
  38693. __name(isObjectId, "isObjectId");
  38694. // node_modules/@e22m4u/js-repository/src/schema.js
  38695. init_src2();
  38696. init_repository2();
  38697. init_definition();
  38698. init_repository2();
  38699. // node_modules/@e22m4u/js-repository/src/index.js
  38700. init_utils2();
  38701. init_errors2();
  38702. init_filter();
  38703. init_adapter2();
  38704. init_relations2();
  38705. init_definition();
  38706. init_repository2();
  38707. // src/utils/create-mongodb-url.js
  38708. function createMongodbUrl(options = {}) {
  38709. if (!options || typeof options !== "object" || Array.isArray(options))
  38710. throw new InvalidArgumentError2(
  38711. 'The first argument of "createMongodbUrl" must be an Object, but %v given.',
  38712. options
  38713. );
  38714. if (options.protocol && typeof options.protocol !== "string")
  38715. throw new InvalidArgumentError2(
  38716. 'MongoDB option "protocol" must be a String, but %v given.',
  38717. options.protocol
  38718. );
  38719. if (options.hostname && typeof options.hostname !== "string")
  38720. throw new InvalidArgumentError2(
  38721. 'MongoDB option "hostname" must be a String, but %v given.',
  38722. options.hostname
  38723. );
  38724. if (options.host && typeof options.host !== "string")
  38725. throw new InvalidArgumentError2(
  38726. 'MongoDB option "host" must be a String, but %v given.',
  38727. options.host
  38728. );
  38729. if (options.port && typeof options.port !== "number" && typeof options.port !== "string") {
  38730. throw new InvalidArgumentError2(
  38731. 'MongoDB option "port" must be a Number or a String, but %v given.',
  38732. options.port
  38733. );
  38734. }
  38735. if (options.database && typeof options.database !== "string")
  38736. throw new InvalidArgumentError2(
  38737. 'MongoDB option "database" must be a String, but %v given.',
  38738. options.database
  38739. );
  38740. if (options.db && typeof options.db !== "string")
  38741. throw new InvalidArgumentError2(
  38742. 'MongoDB option "db" must be a String, but %v given.',
  38743. options.db
  38744. );
  38745. if (options.username && typeof options.username !== "string")
  38746. throw new InvalidArgumentError2(
  38747. 'MongoDB option "username" must be a String, but %v given.',
  38748. options.username
  38749. );
  38750. if (options.password && typeof options.password !== "string" && typeof options.password !== "number") {
  38751. throw new InvalidArgumentError2(
  38752. 'MongoDB option "password" must be a String or a Number, but %v given.',
  38753. options.password
  38754. );
  38755. }
  38756. if (options.pass && typeof options.pass !== "string" && typeof options.pass !== "number") {
  38757. throw new InvalidArgumentError2(
  38758. 'MongoDB option "pass" must be a String or a Number, but %v given.',
  38759. options.pass
  38760. );
  38761. }
  38762. const protocol = options.protocol || "mongodb";
  38763. const hostname = options.hostname || options.host || "127.0.0.1";
  38764. const port = options.port || 27017;
  38765. const database = options.database || options.db || "database";
  38766. const username = options.username || options.user;
  38767. const password = options.password || options.pass || void 0;
  38768. let portUrl = "";
  38769. if (protocol !== "mongodb+srv") {
  38770. portUrl = ":" + port;
  38771. }
  38772. if (username && password) {
  38773. return `${protocol}://${username}:${password}@${hostname}${portUrl}/${database}`;
  38774. } else {
  38775. return `${protocol}://${hostname}${portUrl}/${database}`;
  38776. }
  38777. }
  38778. __name(createMongodbUrl, "createMongodbUrl");
  38779. // src/utils/transform-values-deep.js
  38780. function transformValuesDeep(value, transformer) {
  38781. if (!transformer || typeof transformer !== "function")
  38782. throw new InvalidArgumentError2(
  38783. 'The second argument of "transformValuesDeep" must be a Function, but %v given.',
  38784. transformer
  38785. );
  38786. if (Array.isArray(value)) {
  38787. value.forEach((v, i) => value[i] = transformValuesDeep(v, transformer));
  38788. return value;
  38789. } else if (value && typeof value === "object") {
  38790. if (!value.constructor || value.constructor && value.constructor.name === "Object") {
  38791. Object.keys(value).forEach((key) => {
  38792. if (Object.prototype.hasOwnProperty.call(value, key))
  38793. value[key] = transformValuesDeep(value[key], transformer);
  38794. });
  38795. return value;
  38796. } else {
  38797. return transformer(value);
  38798. }
  38799. } else {
  38800. return transformer(value);
  38801. }
  38802. }
  38803. __name(transformValuesDeep, "transformValuesDeep");
  38804. // src/mongodb-adapter.js
  38805. init_src2();
  38806. var MONGODB_OPTION_NAMES = [
  38807. "appname",
  38808. "authMechanism",
  38809. "authMechanismProperties",
  38810. "authSource",
  38811. "compressors",
  38812. "connectTimeoutMS",
  38813. "directConnection",
  38814. "heartbeatFrequencyMS",
  38815. "journal",
  38816. "loadBalanced",
  38817. "localThresholdMS",
  38818. "maxIdleTimeMS",
  38819. "maxPoolSize",
  38820. "maxConnecting",
  38821. "maxStalenessSeconds",
  38822. "minPoolSize",
  38823. "proxyHost",
  38824. "proxyPort",
  38825. "proxyUsername",
  38826. "proxyPassword",
  38827. "readConcernLevel",
  38828. "readPreference",
  38829. "readPreferenceTags",
  38830. "replicaSet",
  38831. "retryReads",
  38832. "retryWrites",
  38833. "serverSelectionTimeoutMS",
  38834. "serverSelectionTryOnce",
  38835. "socketTimeoutMS",
  38836. "srvMaxHosts",
  38837. "srvServiceName",
  38838. "ssl",
  38839. "timeoutMS",
  38840. "tls",
  38841. "tlsAllowInvalidCertificates",
  38842. "tlsAllowInvalidHostnames",
  38843. "tlsCAFile",
  38844. "tlsCertificateKeyFile",
  38845. "tlsCertificateKeyFilePassword",
  38846. "tlsInsecure",
  38847. "w",
  38848. "waitQueueTimeoutMS",
  38849. "wTimeoutMS",
  38850. "zlibCompressionLevel"
  38851. ];
  38852. var DEFAULT_SETTINGS = {
  38853. // connectTimeoutMS: 2500,
  38854. // serverSelectionTimeoutMS: 2500,
  38855. };
  38856. var _MongodbAdapter = class _MongodbAdapter extends Adapter {
  38857. /**
  38858. * Mongodb instance.
  38859. *
  38860. * @type {MongoClient}
  38861. * @private
  38862. */
  38863. _client;
  38864. /**
  38865. * Client.
  38866. *
  38867. * @returns {MongoClient}
  38868. */
  38869. get client() {
  38870. return this._client;
  38871. }
  38872. /**
  38873. * Collections.
  38874. *
  38875. * @type {Map<any, any>}
  38876. * @private
  38877. */
  38878. _collections = /* @__PURE__ */ new Map();
  38879. /**
  38880. * Constructor.
  38881. *
  38882. * @param {ServiceContainer} container
  38883. * @param settings
  38884. */
  38885. constructor(container, settings) {
  38886. settings = Object.assign({}, DEFAULT_SETTINGS, settings || {});
  38887. settings.protocol = settings.protocol || "mongodb";
  38888. settings.hostname = settings.hostname || settings.host || "127.0.0.1";
  38889. settings.port = settings.port || 27017;
  38890. settings.database = settings.database || settings.db || "database";
  38891. super(container, settings);
  38892. const options = selectObjectKeys(this.settings, MONGODB_OPTION_NAMES);
  38893. const url = createMongodbUrl(this.settings);
  38894. this._client = new import_mongodb3.MongoClient(url, options);
  38895. }
  38896. /**
  38897. * Get id prop name.
  38898. *
  38899. * @param modelName
  38900. */
  38901. _getIdPropName(modelName) {
  38902. return this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  38903. modelName
  38904. );
  38905. }
  38906. /**
  38907. * Get id col name.
  38908. *
  38909. * @param modelName
  38910. */
  38911. _getIdColName(modelName) {
  38912. return this.getService(ModelDefinitionUtils).getPrimaryKeyAsColumnName(
  38913. modelName
  38914. );
  38915. }
  38916. /**
  38917. * Coerce id.
  38918. *
  38919. * @param value
  38920. * @return {ObjectId|*}
  38921. * @private
  38922. */
  38923. _coerceId(value) {
  38924. if (value == null) return value;
  38925. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  38926. return value;
  38927. }
  38928. /**
  38929. * Coerce date.
  38930. *
  38931. * @param value
  38932. * @returns {Date|*}
  38933. * @private
  38934. */
  38935. _coerceDate(value) {
  38936. if (value == null) return value;
  38937. if (value instanceof Date) return value;
  38938. if (isIsoDate(value)) return new Date(value);
  38939. return value;
  38940. }
  38941. /**
  38942. * To database.
  38943. *
  38944. * @param {string} modelName
  38945. * @param {object} modelData
  38946. * @return {object}
  38947. * @private
  38948. */
  38949. _toDatabase(modelName, modelData) {
  38950. const tableData = this.getService(
  38951. ModelDefinitionUtils
  38952. ).convertPropertyNamesToColumnNames(modelName, modelData);
  38953. const idColName = this._getIdColName(modelName);
  38954. if (idColName !== "id" && idColName !== "_id")
  38955. throw new InvalidArgumentError2(
  38956. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  38957. idColName
  38958. );
  38959. if (idColName in tableData && idColName !== "_id") {
  38960. tableData._id = tableData[idColName];
  38961. delete tableData[idColName];
  38962. }
  38963. return transformValuesDeep(tableData, (value) => {
  38964. if (value instanceof import_mongodb2.ObjectId) return value;
  38965. if (value instanceof Date) return value;
  38966. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  38967. if (isIsoDate(value)) return new Date(value);
  38968. return value;
  38969. });
  38970. }
  38971. /**
  38972. * From database.
  38973. *
  38974. * @param {string} modelName
  38975. * @param {object} tableData
  38976. * @return {object}
  38977. * @private
  38978. */
  38979. _fromDatabase(modelName, tableData) {
  38980. if ("_id" in tableData) {
  38981. const idColName = this._getIdColName(modelName);
  38982. if (idColName !== "id" && idColName !== "_id")
  38983. throw new InvalidArgumentError2(
  38984. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  38985. idColName
  38986. );
  38987. if (idColName !== "_id") {
  38988. tableData[idColName] = tableData._id;
  38989. delete tableData._id;
  38990. }
  38991. }
  38992. const modelData = this.getService(
  38993. ModelDefinitionUtils
  38994. ).convertColumnNamesToPropertyNames(modelName, tableData);
  38995. return transformValuesDeep(modelData, (value) => {
  38996. if (value instanceof import_mongodb2.ObjectId) return String(value);
  38997. if (value instanceof Date) return value.toISOString();
  38998. return value;
  38999. });
  39000. }
  39001. /**
  39002. * Get collection.
  39003. *
  39004. * @param {string} modelName
  39005. * @return {*}
  39006. * @private
  39007. */
  39008. _getCollection(modelName) {
  39009. let collection = this._collections.get(modelName);
  39010. if (collection) return collection;
  39011. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  39012. collection = this.client.db(this.settings.database).collection(tableName);
  39013. this._collections.set(modelName, collection);
  39014. return collection;
  39015. }
  39016. /**
  39017. * Get id type.
  39018. *
  39019. * @param modelName
  39020. * @return {string|*}
  39021. * @private
  39022. */
  39023. _getIdType(modelName) {
  39024. const utils = this.getService(ModelDefinitionUtils);
  39025. const pkPropName = utils.getPrimaryKeyAsPropertyName(modelName);
  39026. return utils.getDataTypeByPropertyName(modelName, pkPropName);
  39027. }
  39028. /**
  39029. * Build projection.
  39030. *
  39031. * @param {string} modelName
  39032. * @param {string|string[]} fields
  39033. * @return {Record<string, number>|undefined}
  39034. * @private
  39035. */
  39036. _buildProjection(modelName, fields) {
  39037. if (fields == null) return;
  39038. if (Array.isArray(fields) === false) fields = [fields];
  39039. if (!fields.length) return;
  39040. if (fields.indexOf("_id") === -1) fields.push("_id");
  39041. return fields.reduce((acc, field) => {
  39042. if (!field || typeof field !== "string")
  39043. throw new InvalidArgumentError2(
  39044. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  39045. field
  39046. );
  39047. let colName = this._getColName(modelName, field);
  39048. acc[colName] = 1;
  39049. return acc;
  39050. }, {});
  39051. }
  39052. /**
  39053. * Get col name.
  39054. *
  39055. * @param {string} modelName
  39056. * @param {string} propName
  39057. * @return {string}
  39058. * @private
  39059. */
  39060. _getColName(modelName, propName) {
  39061. if (!propName || typeof propName !== "string")
  39062. throw new InvalidArgumentError2(
  39063. "A property name must be a non-empty String, but %v given.",
  39064. propName
  39065. );
  39066. const utils = this.getService(ModelDefinitionUtils);
  39067. let colName = propName;
  39068. try {
  39069. colName = utils.getColumnNameByPropertyName(modelName, propName);
  39070. } catch (error) {
  39071. if (!(error instanceof InvalidArgumentError2) || error.message.indexOf("does not have the property") === -1) {
  39072. throw error;
  39073. }
  39074. }
  39075. return colName;
  39076. }
  39077. /**
  39078. * Build sort.
  39079. *
  39080. * @param {string} modelName
  39081. * @param {string|string[]} clause
  39082. * @return {object|undefined}
  39083. * @private
  39084. */
  39085. _buildSort(modelName, clause) {
  39086. if (clause == null) return;
  39087. if (Array.isArray(clause) === false) clause = [clause];
  39088. if (!clause.length) return;
  39089. const utils = this.getService(ModelDefinitionUtils);
  39090. const idPropName = this._getIdPropName(modelName);
  39091. return clause.reduce((acc, order) => {
  39092. if (!order || typeof order !== "string")
  39093. throw new InvalidArgumentError2(
  39094. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  39095. order
  39096. );
  39097. const direction = order.match(/\s+(A|DE)SC$/);
  39098. let field = order.replace(/\s+(A|DE)SC$/, "").trim();
  39099. if (field === idPropName) {
  39100. field = "_id";
  39101. } else {
  39102. try {
  39103. field = utils.getColumnNameByPropertyName(modelName, field);
  39104. } catch (error) {
  39105. if (!(error instanceof InvalidArgumentError2) || error.message.indexOf("does not have the property") === -1) {
  39106. throw error;
  39107. }
  39108. }
  39109. }
  39110. acc[field] = direction && direction[1] === "DE" ? -1 : 1;
  39111. return acc;
  39112. }, {});
  39113. }
  39114. /**
  39115. * Build query.
  39116. *
  39117. * @param {string} modelName
  39118. * @param {object} clause
  39119. * @return {object}
  39120. * @private
  39121. */
  39122. _buildQuery(modelName, clause) {
  39123. if (clause == null) return;
  39124. if (typeof clause !== "object" || Array.isArray(clause))
  39125. throw new InvalidArgumentError2(
  39126. 'The provided option "where" should be an Object, but %v given.',
  39127. clause
  39128. );
  39129. const query = {};
  39130. const idPropName = this._getIdPropName(modelName);
  39131. Object.keys(clause).forEach((key) => {
  39132. if (String(key).indexOf("$") !== -1)
  39133. throw new InvalidArgumentError2(
  39134. 'The symbol "$" is not supported, but %v given.',
  39135. key
  39136. );
  39137. let cond = clause[key];
  39138. if (key === "and" || key === "or" || key === "nor") {
  39139. if (cond == null) return;
  39140. if (!Array.isArray(cond))
  39141. throw new InvalidOperatorValueError(key, "an Array", cond);
  39142. if (cond.length === 0) return;
  39143. cond = cond.map((c) => this._buildQuery(modelName, c));
  39144. cond = cond.filter((c) => c != null);
  39145. const opKey = "$" + key;
  39146. query[opKey] = query[opKey] ?? [];
  39147. query[opKey] = [...query[opKey], ...cond];
  39148. return;
  39149. }
  39150. if (key === idPropName) {
  39151. key = "_id";
  39152. } else {
  39153. key = this._getColName(modelName, key);
  39154. }
  39155. if (typeof cond === "string") {
  39156. query[key] = this._coerceId(cond);
  39157. query[key] = this._coerceDate(query[key]);
  39158. return;
  39159. }
  39160. if (cond instanceof import_mongodb2.ObjectId) {
  39161. query[key] = cond;
  39162. return;
  39163. }
  39164. if (cond && cond.constructor && cond.constructor.name === "Object") {
  39165. const opConds = [];
  39166. if ("eq" in cond) {
  39167. let eq = this._coerceId(cond.eq);
  39168. eq = this._coerceDate(eq);
  39169. opConds.push({ $eq: eq });
  39170. }
  39171. if ("neq" in cond) {
  39172. let neq = this._coerceId(cond.neq);
  39173. neq = this._coerceDate(neq);
  39174. opConds.push({ $ne: neq });
  39175. }
  39176. if ("gt" in cond) {
  39177. const gt = this._coerceDate(cond.gt);
  39178. opConds.push({ $gt: gt });
  39179. }
  39180. if ("lt" in cond) {
  39181. const lt = this._coerceDate(cond.lt);
  39182. opConds.push({ $lt: lt });
  39183. }
  39184. if ("gte" in cond) {
  39185. const gte = this._coerceDate(cond.gte);
  39186. opConds.push({ $gte: gte });
  39187. }
  39188. if ("lte" in cond) {
  39189. const lte = this._coerceDate(cond.lte);
  39190. opConds.push({ $lte: lte });
  39191. }
  39192. if ("inq" in cond) {
  39193. if (!cond.inq || !Array.isArray(cond.inq))
  39194. throw new InvalidOperatorValueError(
  39195. "inq",
  39196. "an Array of possible values",
  39197. cond.inq
  39198. );
  39199. const inq = cond.inq.map((v) => {
  39200. v = this._coerceId(v);
  39201. v = this._coerceDate(v);
  39202. return v;
  39203. });
  39204. opConds.push({ $in: inq });
  39205. }
  39206. if ("nin" in cond) {
  39207. if (!cond.nin || !Array.isArray(cond.nin))
  39208. throw new InvalidOperatorValueError(
  39209. "nin",
  39210. "an Array of possible values",
  39211. cond
  39212. );
  39213. const nin = cond.nin.map((v) => {
  39214. v = this._coerceId(v);
  39215. v = this._coerceDate(v);
  39216. return v;
  39217. });
  39218. opConds.push({ $nin: nin });
  39219. }
  39220. if ("between" in cond) {
  39221. if (!Array.isArray(cond.between) || cond.between.length !== 2)
  39222. throw new InvalidOperatorValueError(
  39223. "between",
  39224. "an Array of 2 elements",
  39225. cond.between
  39226. );
  39227. const gte = this._coerceDate(cond.between[0]);
  39228. const lte = this._coerceDate(cond.between[1]);
  39229. opConds.push({ $gte: gte, $lte: lte });
  39230. }
  39231. if ("exists" in cond) {
  39232. if (typeof cond.exists !== "boolean")
  39233. throw new InvalidOperatorValueError(
  39234. "exists",
  39235. "a Boolean",
  39236. cond.exists
  39237. );
  39238. opConds.push({ $exists: cond.exists });
  39239. }
  39240. if ("like" in cond) {
  39241. if (typeof cond.like !== "string" && !(cond.like instanceof RegExp))
  39242. throw new InvalidOperatorValueError(
  39243. "like",
  39244. "a String or RegExp",
  39245. cond.like
  39246. );
  39247. opConds.push({ $regex: stringToRegexp(cond.like) });
  39248. }
  39249. if ("nlike" in cond) {
  39250. if (typeof cond.nlike !== "string" && !(cond.nlike instanceof RegExp))
  39251. throw new InvalidOperatorValueError(
  39252. "nlike",
  39253. "a String or RegExp",
  39254. cond.nlike
  39255. );
  39256. opConds.push({ $not: stringToRegexp(cond.nlike) });
  39257. }
  39258. if ("ilike" in cond) {
  39259. if (typeof cond.ilike !== "string" && !(cond.ilike instanceof RegExp))
  39260. throw new InvalidOperatorValueError(
  39261. "ilike",
  39262. "a String or RegExp",
  39263. cond.ilike
  39264. );
  39265. opConds.push({ $regex: stringToRegexp(cond.ilike, "i") });
  39266. }
  39267. if ("nilike" in cond) {
  39268. if (typeof cond.nilike !== "string" && !(cond.nilike instanceof RegExp)) {
  39269. throw new InvalidOperatorValueError(
  39270. "nilike",
  39271. "a String or RegExp",
  39272. cond.nilike
  39273. );
  39274. }
  39275. opConds.push({ $not: stringToRegexp(cond.nilike, "i") });
  39276. }
  39277. if ("regexp" in cond) {
  39278. if (typeof cond.regexp !== "string" && !(cond.regexp instanceof RegExp)) {
  39279. throw new InvalidOperatorValueError(
  39280. "regexp",
  39281. "a String or RegExp",
  39282. cond.regexp
  39283. );
  39284. }
  39285. const flags = cond.flags || void 0;
  39286. if (flags && typeof flags !== "string")
  39287. throw new InvalidArgumentError2(
  39288. "RegExp flags must be a String, but %v given.",
  39289. cond.flags
  39290. );
  39291. opConds.push({ $regex: stringToRegexp(cond.regexp, flags) });
  39292. }
  39293. if (opConds.length === 1) {
  39294. query[key] = opConds[0];
  39295. } else if (opConds.length > 1) {
  39296. query["$and"] = query["$and"] ?? [];
  39297. opConds.forEach((c) => query["$and"].push({ [key]: c }));
  39298. }
  39299. return;
  39300. }
  39301. query[key] = cond;
  39302. });
  39303. return Object.keys(query).length ? query : void 0;
  39304. }
  39305. /**
  39306. * Create.
  39307. *
  39308. * @param {string} modelName
  39309. * @param {object} modelData
  39310. * @param {object|undefined} filter
  39311. * @return {Promise<object>}
  39312. */
  39313. async create(modelName, modelData, filter = void 0) {
  39314. const idPropName = this._getIdPropName(modelName);
  39315. const idValue = modelData[idPropName];
  39316. if (idValue == null || idValue === "" || idValue === 0) {
  39317. const pkType = this._getIdType(modelName);
  39318. if (pkType !== DataType.STRING && pkType !== DataType.ANY)
  39319. throw new InvalidArgumentError2(
  39320. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  39321. capitalize(pkType),
  39322. idPropName
  39323. );
  39324. delete modelData[idPropName];
  39325. }
  39326. const tableData = this._toDatabase(modelName, modelData);
  39327. const table = this._getCollection(modelName);
  39328. const { insertedId } = await table.insertOne(tableData);
  39329. const projection = this._buildProjection(
  39330. modelName,
  39331. filter && filter.fields
  39332. );
  39333. const insertedData = await table.findOne({ _id: insertedId }, { projection });
  39334. return this._fromDatabase(modelName, insertedData);
  39335. }
  39336. /**
  39337. * Replace by id.
  39338. *
  39339. * @param {string} modelName
  39340. * @param {string|number} id
  39341. * @param {object} modelData
  39342. * @param {object|undefined} filter
  39343. * @return {Promise<object>}
  39344. */
  39345. async replaceById(modelName, id, modelData, filter = void 0) {
  39346. id = this._coerceId(id);
  39347. const idPropName = this._getIdPropName(modelName);
  39348. modelData[idPropName] = id;
  39349. const tableData = this._toDatabase(modelName, modelData);
  39350. const table = this._getCollection(modelName);
  39351. const { matchedCount } = await table.replaceOne({ _id: id }, tableData);
  39352. if (matchedCount < 1)
  39353. throw new InvalidArgumentError2("Identifier %v is not found.", String(id));
  39354. const projection = this._buildProjection(
  39355. modelName,
  39356. filter && filter.fields
  39357. );
  39358. const replacedData = await table.findOne({ _id: id }, { projection });
  39359. return this._fromDatabase(modelName, replacedData);
  39360. }
  39361. /**
  39362. * Replace or create.
  39363. *
  39364. * @param {string} modelName
  39365. * @param {object} modelData
  39366. * @param {object|undefined} filter
  39367. * @return {Promise<object>}
  39368. */
  39369. async replaceOrCreate(modelName, modelData, filter = void 0) {
  39370. const idPropName = this._getIdPropName(modelName);
  39371. let idValue = modelData[idPropName];
  39372. idValue = this._coerceId(idValue);
  39373. if (idValue == null || idValue === "" || idValue === 0) {
  39374. const pkType = this._getIdType(modelName);
  39375. if (pkType !== DataType.STRING && pkType !== DataType.ANY)
  39376. throw new InvalidArgumentError2(
  39377. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  39378. capitalize(pkType),
  39379. idPropName
  39380. );
  39381. delete modelData[idPropName];
  39382. idValue = void 0;
  39383. }
  39384. const tableData = this._toDatabase(modelName, modelData);
  39385. const table = this._getCollection(modelName);
  39386. if (idValue == null) {
  39387. const { insertedId } = await table.insertOne(tableData);
  39388. idValue = insertedId;
  39389. } else {
  39390. const { upsertedId } = await table.replaceOne({ _id: idValue }, tableData, {
  39391. upsert: true
  39392. });
  39393. if (upsertedId) idValue = upsertedId;
  39394. }
  39395. const projection = this._buildProjection(
  39396. modelName,
  39397. filter && filter.fields
  39398. );
  39399. const upsertedData = await table.findOne({ _id: idValue }, { projection });
  39400. return this._fromDatabase(modelName, upsertedData);
  39401. }
  39402. /**
  39403. * Patch.
  39404. *
  39405. * @param {string} modelName
  39406. * @param {object} modelData
  39407. * @param {object|undefined} where
  39408. * @return {Promise<number>}
  39409. */
  39410. async patch(modelName, modelData, where = void 0) {
  39411. const idPropName = this._getIdPropName(modelName);
  39412. delete modelData[idPropName];
  39413. const query = this._buildQuery(modelName, where) || {};
  39414. const tableData = this._toDatabase(modelName, modelData);
  39415. const table = this._getCollection(modelName);
  39416. const { matchedCount } = await table.updateMany(query, { $set: tableData });
  39417. return matchedCount;
  39418. }
  39419. /**
  39420. * Patch by id.
  39421. *
  39422. * @param {string} modelName
  39423. * @param {string|number} id
  39424. * @param {object} modelData
  39425. * @param {object|undefined} filter
  39426. * @return {Promise<object>}
  39427. */
  39428. async patchById(modelName, id, modelData, filter = void 0) {
  39429. id = this._coerceId(id);
  39430. const idPropName = this._getIdPropName(modelName);
  39431. delete modelData[idPropName];
  39432. const tableData = this._toDatabase(modelName, modelData);
  39433. const table = this._getCollection(modelName);
  39434. const { matchedCount } = await table.updateOne({ _id: id }, { $set: tableData });
  39435. if (matchedCount < 1)
  39436. throw new InvalidArgumentError2("Identifier %v is not found.", String(id));
  39437. const projection = this._buildProjection(
  39438. modelName,
  39439. filter && filter.fields
  39440. );
  39441. const patchedData = await table.findOne({ _id: id }, { projection });
  39442. return this._fromDatabase(modelName, patchedData);
  39443. }
  39444. /**
  39445. * Find.
  39446. *
  39447. * @param {string} modelName
  39448. * @param {object|undefined} filter
  39449. * @return {Promise<object[]>}
  39450. */
  39451. async find(modelName, filter = void 0) {
  39452. filter = filter || {};
  39453. const query = this._buildQuery(modelName, filter.where);
  39454. const sort = this._buildSort(modelName, filter.order);
  39455. const limit = filter.limit || void 0;
  39456. const skip = filter.skip || void 0;
  39457. const projection = this._buildProjection(modelName, filter.fields);
  39458. const collection = this._getCollection(modelName);
  39459. const options = { sort, limit, skip, projection };
  39460. const tableItems = await collection.find(query, options).toArray();
  39461. return tableItems.map((v) => this._fromDatabase(modelName, v));
  39462. }
  39463. /**
  39464. * Find by id.
  39465. *
  39466. * @param {string} modelName
  39467. * @param {string|number} id
  39468. * @param {object|undefined} filter
  39469. * @return {Promise<object>}
  39470. */
  39471. async findById(modelName, id, filter = void 0) {
  39472. id = this._coerceId(id);
  39473. const table = this._getCollection(modelName);
  39474. const projection = this._buildProjection(
  39475. modelName,
  39476. filter && filter.fields
  39477. );
  39478. const patchedData = await table.findOne({ _id: id }, { projection });
  39479. if (!patchedData)
  39480. throw new InvalidArgumentError2("Identifier %v is not found.", String(id));
  39481. return this._fromDatabase(modelName, patchedData);
  39482. }
  39483. /**
  39484. * Delete.
  39485. *
  39486. * @param {string} modelName
  39487. * @param {object|undefined} where
  39488. * @return {Promise<number>}
  39489. */
  39490. async delete(modelName, where = void 0) {
  39491. const table = this._getCollection(modelName);
  39492. const query = this._buildQuery(modelName, where);
  39493. const { deletedCount } = await table.deleteMany(query);
  39494. return deletedCount;
  39495. }
  39496. /**
  39497. * Delete by id.
  39498. *
  39499. * @param {string} modelName
  39500. * @param {string|number} id
  39501. * @return {Promise<boolean>}
  39502. */
  39503. async deleteById(modelName, id) {
  39504. id = this._coerceId(id);
  39505. const table = this._getCollection(modelName);
  39506. const { deletedCount } = await table.deleteOne({ _id: id });
  39507. return deletedCount > 0;
  39508. }
  39509. /**
  39510. * Exists.
  39511. *
  39512. * @param {string} modelName
  39513. * @param {string|number} id
  39514. * @return {Promise<boolean>}
  39515. */
  39516. async exists(modelName, id) {
  39517. id = this._coerceId(id);
  39518. const table = this._getCollection(modelName);
  39519. const result = await table.findOne({ _id: id }, {});
  39520. return result != null;
  39521. }
  39522. /**
  39523. * Count.
  39524. *
  39525. * @param {string} modelName
  39526. * @param {object|undefined} where
  39527. * @return {Promise<number>}
  39528. */
  39529. async count(modelName, where = void 0) {
  39530. const query = this._buildQuery(modelName, where);
  39531. const table = this._getCollection(modelName);
  39532. return await table.count(query);
  39533. }
  39534. };
  39535. __name(_MongodbAdapter, "MongodbAdapter");
  39536. var MongodbAdapter = _MongodbAdapter;
  39537. // Annotate the CommonJS export names for ESM import in node:
  39538. 0 && (module.exports = {
  39539. MongodbAdapter
  39540. });