api.mjs 2.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834
  1. import { createRequire } from 'module'; const require = createRequire(import.meta.url);
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __typeError = (msg) => {
  9. throw TypeError(msg);
  10. };
  11. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  12. var __require = /* @__PURE__ */ ((x5) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x5, {
  13. get: (a5, b5) => (typeof require !== "undefined" ? require : a5)[b5]
  14. }) : x5)(function(x5) {
  15. if (typeof require !== "undefined") return require.apply(this, arguments);
  16. throw Error('Dynamic require of "' + x5 + '" is not supported');
  17. });
  18. var __esm = (fn, res) => function __init() {
  19. return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  20. };
  21. var __commonJS = (cb, mod) => function __require2() {
  22. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  23. };
  24. var __export = (target, all) => {
  25. for (var name in all)
  26. __defProp(target, name, { get: all[name], enumerable: true });
  27. };
  28. var __copyProps = (to, from, except, desc) => {
  29. if (from && typeof from === "object" || typeof from === "function") {
  30. for (let key of __getOwnPropNames(from))
  31. if (!__hasOwnProp.call(to, key) && key !== except)
  32. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  33. }
  34. return to;
  35. };
  36. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  37. // If the importer is in node compatibility mode or this is not an ESM
  38. // file that has been converted to a CommonJS file using a Babel-
  39. // compatible transform (i.e. "__esModule" has not been set), then set
  40. // "default" to the CommonJS "module.exports" for node compatibility.
  41. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  42. mod
  43. ));
  44. var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  45. var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
  46. var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
  47. var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  48. var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
  49. var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
  50. var __privateWrapper = (obj, member, setter, getter) => ({
  51. set _(value) {
  52. __privateSet(obj, member, value, setter);
  53. },
  54. get _() {
  55. return __privateGet(obj, member, getter);
  56. }
  57. });
  58. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js
  59. function assembleStyles() {
  60. const codes = /* @__PURE__ */ new Map();
  61. for (const [groupName, group] of Object.entries(styles)) {
  62. for (const [styleName, style] of Object.entries(group)) {
  63. styles[styleName] = {
  64. open: `\x1B[${style[0]}m`,
  65. close: `\x1B[${style[1]}m`
  66. };
  67. group[styleName] = styles[styleName];
  68. codes.set(style[0], style[1]);
  69. }
  70. Object.defineProperty(styles, groupName, {
  71. value: group,
  72. enumerable: false
  73. });
  74. }
  75. Object.defineProperty(styles, "codes", {
  76. value: codes,
  77. enumerable: false
  78. });
  79. styles.color.close = "\x1B[39m";
  80. styles.bgColor.close = "\x1B[49m";
  81. styles.color.ansi = wrapAnsi16();
  82. styles.color.ansi256 = wrapAnsi256();
  83. styles.color.ansi16m = wrapAnsi16m();
  84. styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  85. styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  86. styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  87. Object.defineProperties(styles, {
  88. rgbToAnsi256: {
  89. value(red, green, blue) {
  90. if (red === green && green === blue) {
  91. if (red < 8) {
  92. return 16;
  93. }
  94. if (red > 248) {
  95. return 231;
  96. }
  97. return Math.round((red - 8) / 247 * 24) + 232;
  98. }
  99. return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
  100. },
  101. enumerable: false
  102. },
  103. hexToRgb: {
  104. value(hex) {
  105. const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
  106. if (!matches) {
  107. return [0, 0, 0];
  108. }
  109. let [colorString] = matches;
  110. if (colorString.length === 3) {
  111. colorString = [...colorString].map((character) => character + character).join("");
  112. }
  113. const integer = Number.parseInt(colorString, 16);
  114. return [
  115. /* eslint-disable no-bitwise */
  116. integer >> 16 & 255,
  117. integer >> 8 & 255,
  118. integer & 255
  119. /* eslint-enable no-bitwise */
  120. ];
  121. },
  122. enumerable: false
  123. },
  124. hexToAnsi256: {
  125. value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
  126. enumerable: false
  127. },
  128. ansi256ToAnsi: {
  129. value(code) {
  130. if (code < 8) {
  131. return 30 + code;
  132. }
  133. if (code < 16) {
  134. return 90 + (code - 8);
  135. }
  136. let red;
  137. let green;
  138. let blue;
  139. if (code >= 232) {
  140. red = ((code - 232) * 10 + 8) / 255;
  141. green = red;
  142. blue = red;
  143. } else {
  144. code -= 16;
  145. const remainder = code % 36;
  146. red = Math.floor(code / 36) / 5;
  147. green = Math.floor(remainder / 6) / 5;
  148. blue = remainder % 6 / 5;
  149. }
  150. const value = Math.max(red, green, blue) * 2;
  151. if (value === 0) {
  152. return 30;
  153. }
  154. let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
  155. if (value === 2) {
  156. result += 60;
  157. }
  158. return result;
  159. },
  160. enumerable: false
  161. },
  162. rgbToAnsi: {
  163. value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
  164. enumerable: false
  165. },
  166. hexToAnsi: {
  167. value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
  168. enumerable: false
  169. }
  170. });
  171. return styles;
  172. }
  173. var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
  174. var init_ansi_styles = __esm({
  175. "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
  176. "use strict";
  177. ANSI_BACKGROUND_OFFSET = 10;
  178. wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
  179. wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
  180. wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
  181. styles = {
  182. modifier: {
  183. reset: [0, 0],
  184. // 21 isn't widely supported and 22 does the same thing
  185. bold: [1, 22],
  186. dim: [2, 22],
  187. italic: [3, 23],
  188. underline: [4, 24],
  189. overline: [53, 55],
  190. inverse: [7, 27],
  191. hidden: [8, 28],
  192. strikethrough: [9, 29]
  193. },
  194. color: {
  195. black: [30, 39],
  196. red: [31, 39],
  197. green: [32, 39],
  198. yellow: [33, 39],
  199. blue: [34, 39],
  200. magenta: [35, 39],
  201. cyan: [36, 39],
  202. white: [37, 39],
  203. // Bright color
  204. blackBright: [90, 39],
  205. gray: [90, 39],
  206. // Alias of `blackBright`
  207. grey: [90, 39],
  208. // Alias of `blackBright`
  209. redBright: [91, 39],
  210. greenBright: [92, 39],
  211. yellowBright: [93, 39],
  212. blueBright: [94, 39],
  213. magentaBright: [95, 39],
  214. cyanBright: [96, 39],
  215. whiteBright: [97, 39]
  216. },
  217. bgColor: {
  218. bgBlack: [40, 49],
  219. bgRed: [41, 49],
  220. bgGreen: [42, 49],
  221. bgYellow: [43, 49],
  222. bgBlue: [44, 49],
  223. bgMagenta: [45, 49],
  224. bgCyan: [46, 49],
  225. bgWhite: [47, 49],
  226. // Bright color
  227. bgBlackBright: [100, 49],
  228. bgGray: [100, 49],
  229. // Alias of `bgBlackBright`
  230. bgGrey: [100, 49],
  231. // Alias of `bgBlackBright`
  232. bgRedBright: [101, 49],
  233. bgGreenBright: [102, 49],
  234. bgYellowBright: [103, 49],
  235. bgBlueBright: [104, 49],
  236. bgMagentaBright: [105, 49],
  237. bgCyanBright: [106, 49],
  238. bgWhiteBright: [107, 49]
  239. }
  240. };
  241. modifierNames = Object.keys(styles.modifier);
  242. foregroundColorNames = Object.keys(styles.color);
  243. backgroundColorNames = Object.keys(styles.bgColor);
  244. colorNames = [...foregroundColorNames, ...backgroundColorNames];
  245. ansiStyles = assembleStyles();
  246. ansi_styles_default = ansiStyles;
  247. }
  248. });
  249. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js
  250. import process2 from "process";
  251. import os from "os";
  252. import tty from "tty";
  253. function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
  254. const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  255. const position = argv.indexOf(prefix2 + flag);
  256. const terminatorPosition = argv.indexOf("--");
  257. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  258. }
  259. function envForceColor() {
  260. if ("FORCE_COLOR" in env) {
  261. if (env.FORCE_COLOR === "true") {
  262. return 1;
  263. }
  264. if (env.FORCE_COLOR === "false") {
  265. return 0;
  266. }
  267. return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  268. }
  269. }
  270. function translateLevel(level) {
  271. if (level === 0) {
  272. return false;
  273. }
  274. return {
  275. level,
  276. hasBasic: true,
  277. has256: level >= 2,
  278. has16m: level >= 3
  279. };
  280. }
  281. function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  282. const noFlagForceColor = envForceColor();
  283. if (noFlagForceColor !== void 0) {
  284. flagForceColor = noFlagForceColor;
  285. }
  286. const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  287. if (forceColor === 0) {
  288. return 0;
  289. }
  290. if (sniffFlags) {
  291. if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
  292. return 3;
  293. }
  294. if (hasFlag("color=256")) {
  295. return 2;
  296. }
  297. }
  298. if ("TF_BUILD" in env && "AGENT_NAME" in env) {
  299. return 1;
  300. }
  301. if (haveStream && !streamIsTTY && forceColor === void 0) {
  302. return 0;
  303. }
  304. const min = forceColor || 0;
  305. if (env.TERM === "dumb") {
  306. return min;
  307. }
  308. if (process2.platform === "win32") {
  309. const osRelease = os.release().split(".");
  310. if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  311. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  312. }
  313. return 1;
  314. }
  315. if ("CI" in env) {
  316. if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
  317. return 3;
  318. }
  319. if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
  320. return 1;
  321. }
  322. return min;
  323. }
  324. if ("TEAMCITY_VERSION" in env) {
  325. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  326. }
  327. if (env.COLORTERM === "truecolor") {
  328. return 3;
  329. }
  330. if (env.TERM === "xterm-kitty") {
  331. return 3;
  332. }
  333. if ("TERM_PROGRAM" in env) {
  334. const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
  335. switch (env.TERM_PROGRAM) {
  336. case "iTerm.app": {
  337. return version >= 3 ? 3 : 2;
  338. }
  339. case "Apple_Terminal": {
  340. return 2;
  341. }
  342. }
  343. }
  344. if (/-256(color)?$/i.test(env.TERM)) {
  345. return 2;
  346. }
  347. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  348. return 1;
  349. }
  350. if ("COLORTERM" in env) {
  351. return 1;
  352. }
  353. return min;
  354. }
  355. function createSupportsColor(stream, options = {}) {
  356. const level = _supportsColor(stream, {
  357. streamIsTTY: stream && stream.isTTY,
  358. ...options
  359. });
  360. return translateLevel(level);
  361. }
  362. var env, flagForceColor, supportsColor, supports_color_default;
  363. var init_supports_color = __esm({
  364. "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js"() {
  365. "use strict";
  366. ({ env } = process2);
  367. if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
  368. flagForceColor = 0;
  369. } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
  370. flagForceColor = 1;
  371. }
  372. supportsColor = {
  373. stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
  374. stderr: createSupportsColor({ isTTY: tty.isatty(2) })
  375. };
  376. supports_color_default = supportsColor;
  377. }
  378. });
  379. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js
  380. function stringReplaceAll(string, substring2, replacer) {
  381. let index6 = string.indexOf(substring2);
  382. if (index6 === -1) {
  383. return string;
  384. }
  385. const substringLength = substring2.length;
  386. let endIndex = 0;
  387. let returnValue = "";
  388. do {
  389. returnValue += string.slice(endIndex, index6) + substring2 + replacer;
  390. endIndex = index6 + substringLength;
  391. index6 = string.indexOf(substring2, endIndex);
  392. } while (index6 !== -1);
  393. returnValue += string.slice(endIndex);
  394. return returnValue;
  395. }
  396. function stringEncaseCRLFWithFirstIndex(string, prefix2, postfix, index6) {
  397. let endIndex = 0;
  398. let returnValue = "";
  399. do {
  400. const gotCR = string[index6 - 1] === "\r";
  401. returnValue += string.slice(endIndex, gotCR ? index6 - 1 : index6) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix;
  402. endIndex = index6 + 1;
  403. index6 = string.indexOf("\n", endIndex);
  404. } while (index6 !== -1);
  405. returnValue += string.slice(endIndex);
  406. return returnValue;
  407. }
  408. var init_utilities = __esm({
  409. "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js"() {
  410. "use strict";
  411. }
  412. });
  413. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js
  414. function createChalk(options) {
  415. return chalkFactory(options);
  416. }
  417. var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr, source_default;
  418. var init_source = __esm({
  419. "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js"() {
  420. "use strict";
  421. init_ansi_styles();
  422. init_supports_color();
  423. init_utilities();
  424. ({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
  425. GENERATOR = Symbol("GENERATOR");
  426. STYLER = Symbol("STYLER");
  427. IS_EMPTY = Symbol("IS_EMPTY");
  428. levelMapping = [
  429. "ansi",
  430. "ansi",
  431. "ansi256",
  432. "ansi16m"
  433. ];
  434. styles2 = /* @__PURE__ */ Object.create(null);
  435. applyOptions = (object, options = {}) => {
  436. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  437. throw new Error("The `level` option should be an integer from 0 to 3");
  438. }
  439. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  440. object.level = options.level === void 0 ? colorLevel : options.level;
  441. };
  442. chalkFactory = (options) => {
  443. const chalk2 = (...strings) => strings.join(" ");
  444. applyOptions(chalk2, options);
  445. Object.setPrototypeOf(chalk2, createChalk.prototype);
  446. return chalk2;
  447. };
  448. Object.setPrototypeOf(createChalk.prototype, Function.prototype);
  449. for (const [styleName, style] of Object.entries(ansi_styles_default)) {
  450. styles2[styleName] = {
  451. get() {
  452. const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
  453. Object.defineProperty(this, styleName, { value: builder });
  454. return builder;
  455. }
  456. };
  457. }
  458. styles2.visible = {
  459. get() {
  460. const builder = createBuilder(this, this[STYLER], true);
  461. Object.defineProperty(this, "visible", { value: builder });
  462. return builder;
  463. }
  464. };
  465. getModelAnsi = (model, level, type, ...arguments_) => {
  466. if (model === "rgb") {
  467. if (level === "ansi16m") {
  468. return ansi_styles_default[type].ansi16m(...arguments_);
  469. }
  470. if (level === "ansi256") {
  471. return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
  472. }
  473. return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
  474. }
  475. if (model === "hex") {
  476. return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
  477. }
  478. return ansi_styles_default[type][model](...arguments_);
  479. };
  480. usedModels = ["rgb", "hex", "ansi256"];
  481. for (const model of usedModels) {
  482. styles2[model] = {
  483. get() {
  484. const { level } = this;
  485. return function(...arguments_) {
  486. const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
  487. return createBuilder(this, styler, this[IS_EMPTY]);
  488. };
  489. }
  490. };
  491. const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
  492. styles2[bgModel] = {
  493. get() {
  494. const { level } = this;
  495. return function(...arguments_) {
  496. const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
  497. return createBuilder(this, styler, this[IS_EMPTY]);
  498. };
  499. }
  500. };
  501. }
  502. proto = Object.defineProperties(() => {
  503. }, {
  504. ...styles2,
  505. level: {
  506. enumerable: true,
  507. get() {
  508. return this[GENERATOR].level;
  509. },
  510. set(level) {
  511. this[GENERATOR].level = level;
  512. }
  513. }
  514. });
  515. createStyler = (open, close, parent) => {
  516. let openAll;
  517. let closeAll;
  518. if (parent === void 0) {
  519. openAll = open;
  520. closeAll = close;
  521. } else {
  522. openAll = parent.openAll + open;
  523. closeAll = close + parent.closeAll;
  524. }
  525. return {
  526. open,
  527. close,
  528. openAll,
  529. closeAll,
  530. parent
  531. };
  532. };
  533. createBuilder = (self2, _styler, _isEmpty) => {
  534. const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
  535. Object.setPrototypeOf(builder, proto);
  536. builder[GENERATOR] = self2;
  537. builder[STYLER] = _styler;
  538. builder[IS_EMPTY] = _isEmpty;
  539. return builder;
  540. };
  541. applyStyle = (self2, string) => {
  542. if (self2.level <= 0 || !string) {
  543. return self2[IS_EMPTY] ? "" : string;
  544. }
  545. let styler = self2[STYLER];
  546. if (styler === void 0) {
  547. return string;
  548. }
  549. const { openAll, closeAll } = styler;
  550. if (string.includes("\x1B")) {
  551. while (styler !== void 0) {
  552. string = stringReplaceAll(string, styler.close, styler.open);
  553. styler = styler.parent;
  554. }
  555. }
  556. const lfIndex = string.indexOf("\n");
  557. if (lfIndex !== -1) {
  558. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  559. }
  560. return openAll + string + closeAll;
  561. };
  562. Object.defineProperties(createChalk.prototype, styles2);
  563. chalk = createChalk();
  564. chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
  565. source_default = chalk;
  566. }
  567. });
  568. // ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js
  569. var require_old = __commonJS({
  570. "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js"(exports) {
  571. "use strict";
  572. var pathModule = __require("path");
  573. var isWindows = process.platform === "win32";
  574. var fs5 = __require("fs");
  575. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  576. function rethrow() {
  577. var callback;
  578. if (DEBUG) {
  579. var backtrace = new Error();
  580. callback = debugCallback;
  581. } else
  582. callback = missingCallback;
  583. return callback;
  584. function debugCallback(err2) {
  585. if (err2) {
  586. backtrace.message = err2.message;
  587. err2 = backtrace;
  588. missingCallback(err2);
  589. }
  590. }
  591. function missingCallback(err2) {
  592. if (err2) {
  593. if (process.throwDeprecation)
  594. throw err2;
  595. else if (!process.noDeprecation) {
  596. var msg = "fs: missing callback " + (err2.stack || err2.message);
  597. if (process.traceDeprecation)
  598. console.trace(msg);
  599. else
  600. console.error(msg);
  601. }
  602. }
  603. }
  604. }
  605. function maybeCallback(cb) {
  606. return typeof cb === "function" ? cb : rethrow();
  607. }
  608. var normalize = pathModule.normalize;
  609. if (isWindows) {
  610. nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  611. } else {
  612. nextPartRe = /(.*?)(?:[\/]+|$)/g;
  613. }
  614. var nextPartRe;
  615. if (isWindows) {
  616. splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  617. } else {
  618. splitRootRe = /^[\/]*/;
  619. }
  620. var splitRootRe;
  621. exports.realpathSync = function realpathSync(p5, cache5) {
  622. p5 = pathModule.resolve(p5);
  623. if (cache5 && Object.prototype.hasOwnProperty.call(cache5, p5)) {
  624. return cache5[p5];
  625. }
  626. var original = p5, seenLinks = {}, knownHard = {};
  627. var pos;
  628. var current;
  629. var base;
  630. var previous;
  631. start();
  632. function start() {
  633. var m6 = splitRootRe.exec(p5);
  634. pos = m6[0].length;
  635. current = m6[0];
  636. base = m6[0];
  637. previous = "";
  638. if (isWindows && !knownHard[base]) {
  639. fs5.lstatSync(base);
  640. knownHard[base] = true;
  641. }
  642. }
  643. while (pos < p5.length) {
  644. nextPartRe.lastIndex = pos;
  645. var result = nextPartRe.exec(p5);
  646. previous = current;
  647. current += result[0];
  648. base = previous + result[1];
  649. pos = nextPartRe.lastIndex;
  650. if (knownHard[base] || cache5 && cache5[base] === base) {
  651. continue;
  652. }
  653. var resolvedLink;
  654. if (cache5 && Object.prototype.hasOwnProperty.call(cache5, base)) {
  655. resolvedLink = cache5[base];
  656. } else {
  657. var stat2 = fs5.lstatSync(base);
  658. if (!stat2.isSymbolicLink()) {
  659. knownHard[base] = true;
  660. if (cache5) cache5[base] = base;
  661. continue;
  662. }
  663. var linkTarget = null;
  664. if (!isWindows) {
  665. var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
  666. if (seenLinks.hasOwnProperty(id)) {
  667. linkTarget = seenLinks[id];
  668. }
  669. }
  670. if (linkTarget === null) {
  671. fs5.statSync(base);
  672. linkTarget = fs5.readlinkSync(base);
  673. }
  674. resolvedLink = pathModule.resolve(previous, linkTarget);
  675. if (cache5) cache5[base] = resolvedLink;
  676. if (!isWindows) seenLinks[id] = linkTarget;
  677. }
  678. p5 = pathModule.resolve(resolvedLink, p5.slice(pos));
  679. start();
  680. }
  681. if (cache5) cache5[original] = p5;
  682. return p5;
  683. };
  684. exports.realpath = function realpath(p5, cache5, cb) {
  685. if (typeof cb !== "function") {
  686. cb = maybeCallback(cache5);
  687. cache5 = null;
  688. }
  689. p5 = pathModule.resolve(p5);
  690. if (cache5 && Object.prototype.hasOwnProperty.call(cache5, p5)) {
  691. return process.nextTick(cb.bind(null, null, cache5[p5]));
  692. }
  693. var original = p5, seenLinks = {}, knownHard = {};
  694. var pos;
  695. var current;
  696. var base;
  697. var previous;
  698. start();
  699. function start() {
  700. var m6 = splitRootRe.exec(p5);
  701. pos = m6[0].length;
  702. current = m6[0];
  703. base = m6[0];
  704. previous = "";
  705. if (isWindows && !knownHard[base]) {
  706. fs5.lstat(base, function(err2) {
  707. if (err2) return cb(err2);
  708. knownHard[base] = true;
  709. LOOP();
  710. });
  711. } else {
  712. process.nextTick(LOOP);
  713. }
  714. }
  715. function LOOP() {
  716. if (pos >= p5.length) {
  717. if (cache5) cache5[original] = p5;
  718. return cb(null, p5);
  719. }
  720. nextPartRe.lastIndex = pos;
  721. var result = nextPartRe.exec(p5);
  722. previous = current;
  723. current += result[0];
  724. base = previous + result[1];
  725. pos = nextPartRe.lastIndex;
  726. if (knownHard[base] || cache5 && cache5[base] === base) {
  727. return process.nextTick(LOOP);
  728. }
  729. if (cache5 && Object.prototype.hasOwnProperty.call(cache5, base)) {
  730. return gotResolvedLink(cache5[base]);
  731. }
  732. return fs5.lstat(base, gotStat);
  733. }
  734. function gotStat(err2, stat2) {
  735. if (err2) return cb(err2);
  736. if (!stat2.isSymbolicLink()) {
  737. knownHard[base] = true;
  738. if (cache5) cache5[base] = base;
  739. return process.nextTick(LOOP);
  740. }
  741. if (!isWindows) {
  742. var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
  743. if (seenLinks.hasOwnProperty(id)) {
  744. return gotTarget(null, seenLinks[id], base);
  745. }
  746. }
  747. fs5.stat(base, function(err3) {
  748. if (err3) return cb(err3);
  749. fs5.readlink(base, function(err4, target) {
  750. if (!isWindows) seenLinks[id] = target;
  751. gotTarget(err4, target);
  752. });
  753. });
  754. }
  755. function gotTarget(err2, target, base2) {
  756. if (err2) return cb(err2);
  757. var resolvedLink = pathModule.resolve(previous, target);
  758. if (cache5) cache5[base2] = resolvedLink;
  759. gotResolvedLink(resolvedLink);
  760. }
  761. function gotResolvedLink(resolvedLink) {
  762. p5 = pathModule.resolve(resolvedLink, p5.slice(pos));
  763. start();
  764. }
  765. };
  766. }
  767. });
  768. // ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js
  769. var require_fs = __commonJS({
  770. "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js"(exports, module) {
  771. "use strict";
  772. module.exports = realpath;
  773. realpath.realpath = realpath;
  774. realpath.sync = realpathSync;
  775. realpath.realpathSync = realpathSync;
  776. realpath.monkeypatch = monkeypatch;
  777. realpath.unmonkeypatch = unmonkeypatch;
  778. var fs5 = __require("fs");
  779. var origRealpath = fs5.realpath;
  780. var origRealpathSync = fs5.realpathSync;
  781. var version = process.version;
  782. var ok = /^v[0-5]\./.test(version);
  783. var old = require_old();
  784. function newError(er) {
  785. return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
  786. }
  787. function realpath(p5, cache5, cb) {
  788. if (ok) {
  789. return origRealpath(p5, cache5, cb);
  790. }
  791. if (typeof cache5 === "function") {
  792. cb = cache5;
  793. cache5 = null;
  794. }
  795. origRealpath(p5, cache5, function(er, result) {
  796. if (newError(er)) {
  797. old.realpath(p5, cache5, cb);
  798. } else {
  799. cb(er, result);
  800. }
  801. });
  802. }
  803. function realpathSync(p5, cache5) {
  804. if (ok) {
  805. return origRealpathSync(p5, cache5);
  806. }
  807. try {
  808. return origRealpathSync(p5, cache5);
  809. } catch (er) {
  810. if (newError(er)) {
  811. return old.realpathSync(p5, cache5);
  812. } else {
  813. throw er;
  814. }
  815. }
  816. }
  817. function monkeypatch() {
  818. fs5.realpath = realpath;
  819. fs5.realpathSync = realpathSync;
  820. }
  821. function unmonkeypatch() {
  822. fs5.realpath = origRealpath;
  823. fs5.realpathSync = origRealpathSync;
  824. }
  825. }
  826. });
  827. // ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js
  828. var require_path = __commonJS({
  829. "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js"(exports, module) {
  830. "use strict";
  831. var isWindows = typeof process === "object" && process && process.platform === "win32";
  832. module.exports = isWindows ? { sep: "\\" } : { sep: "/" };
  833. }
  834. });
  835. // ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
  836. var require_balanced_match = __commonJS({
  837. "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
  838. "use strict";
  839. module.exports = balanced;
  840. function balanced(a5, b5, str) {
  841. if (a5 instanceof RegExp) a5 = maybeMatch(a5, str);
  842. if (b5 instanceof RegExp) b5 = maybeMatch(b5, str);
  843. var r6 = range(a5, b5, str);
  844. return r6 && {
  845. start: r6[0],
  846. end: r6[1],
  847. pre: str.slice(0, r6[0]),
  848. body: str.slice(r6[0] + a5.length, r6[1]),
  849. post: str.slice(r6[1] + b5.length)
  850. };
  851. }
  852. function maybeMatch(reg, str) {
  853. var m6 = str.match(reg);
  854. return m6 ? m6[0] : null;
  855. }
  856. balanced.range = range;
  857. function range(a5, b5, str) {
  858. var begs, beg, left, right, result;
  859. var ai = str.indexOf(a5);
  860. var bi = str.indexOf(b5, ai + 1);
  861. var i6 = ai;
  862. if (ai >= 0 && bi > 0) {
  863. if (a5 === b5) {
  864. return [ai, bi];
  865. }
  866. begs = [];
  867. left = str.length;
  868. while (i6 >= 0 && !result) {
  869. if (i6 == ai) {
  870. begs.push(i6);
  871. ai = str.indexOf(a5, i6 + 1);
  872. } else if (begs.length == 1) {
  873. result = [begs.pop(), bi];
  874. } else {
  875. beg = begs.pop();
  876. if (beg < left) {
  877. left = beg;
  878. right = bi;
  879. }
  880. bi = str.indexOf(b5, i6 + 1);
  881. }
  882. i6 = ai < bi && ai >= 0 ? ai : bi;
  883. }
  884. if (begs.length) {
  885. result = [left, right];
  886. }
  887. }
  888. return result;
  889. }
  890. }
  891. });
  892. // ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
  893. var require_brace_expansion = __commonJS({
  894. "../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
  895. "use strict";
  896. var balanced = require_balanced_match();
  897. module.exports = expandTop;
  898. var escSlash = "\0SLASH" + Math.random() + "\0";
  899. var escOpen = "\0OPEN" + Math.random() + "\0";
  900. var escClose = "\0CLOSE" + Math.random() + "\0";
  901. var escComma = "\0COMMA" + Math.random() + "\0";
  902. var escPeriod = "\0PERIOD" + Math.random() + "\0";
  903. function numeric(str) {
  904. return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
  905. }
  906. function escapeBraces(str) {
  907. return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
  908. }
  909. function unescapeBraces(str) {
  910. return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
  911. }
  912. function parseCommaParts(str) {
  913. if (!str)
  914. return [""];
  915. var parts = [];
  916. var m6 = balanced("{", "}", str);
  917. if (!m6)
  918. return str.split(",");
  919. var pre = m6.pre;
  920. var body = m6.body;
  921. var post = m6.post;
  922. var p5 = pre.split(",");
  923. p5[p5.length - 1] += "{" + body + "}";
  924. var postParts = parseCommaParts(post);
  925. if (post.length) {
  926. p5[p5.length - 1] += postParts.shift();
  927. p5.push.apply(p5, postParts);
  928. }
  929. parts.push.apply(parts, p5);
  930. return parts;
  931. }
  932. function expandTop(str) {
  933. if (!str)
  934. return [];
  935. if (str.substr(0, 2) === "{}") {
  936. str = "\\{\\}" + str.substr(2);
  937. }
  938. return expand2(escapeBraces(str), true).map(unescapeBraces);
  939. }
  940. function embrace(str) {
  941. return "{" + str + "}";
  942. }
  943. function isPadded(el) {
  944. return /^-?0\d/.test(el);
  945. }
  946. function lte(i6, y2) {
  947. return i6 <= y2;
  948. }
  949. function gte(i6, y2) {
  950. return i6 >= y2;
  951. }
  952. function expand2(str, isTop) {
  953. var expansions = [];
  954. var m6 = balanced("{", "}", str);
  955. if (!m6) return [str];
  956. var pre = m6.pre;
  957. var post = m6.post.length ? expand2(m6.post, false) : [""];
  958. if (/\$$/.test(m6.pre)) {
  959. for (var k5 = 0; k5 < post.length; k5++) {
  960. var expansion = pre + "{" + m6.body + "}" + post[k5];
  961. expansions.push(expansion);
  962. }
  963. } else {
  964. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m6.body);
  965. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m6.body);
  966. var isSequence = isNumericSequence || isAlphaSequence;
  967. var isOptions = m6.body.indexOf(",") >= 0;
  968. if (!isSequence && !isOptions) {
  969. if (m6.post.match(/,.*\}/)) {
  970. str = m6.pre + "{" + m6.body + escClose + m6.post;
  971. return expand2(str);
  972. }
  973. return [str];
  974. }
  975. var n5;
  976. if (isSequence) {
  977. n5 = m6.body.split(/\.\./);
  978. } else {
  979. n5 = parseCommaParts(m6.body);
  980. if (n5.length === 1) {
  981. n5 = expand2(n5[0], false).map(embrace);
  982. if (n5.length === 1) {
  983. return post.map(function(p5) {
  984. return m6.pre + n5[0] + p5;
  985. });
  986. }
  987. }
  988. }
  989. var N;
  990. if (isSequence) {
  991. var x5 = numeric(n5[0]);
  992. var y2 = numeric(n5[1]);
  993. var width = Math.max(n5[0].length, n5[1].length);
  994. var incr = n5.length == 3 ? Math.abs(numeric(n5[2])) : 1;
  995. var test = lte;
  996. var reverse = y2 < x5;
  997. if (reverse) {
  998. incr *= -1;
  999. test = gte;
  1000. }
  1001. var pad = n5.some(isPadded);
  1002. N = [];
  1003. for (var i6 = x5; test(i6, y2); i6 += incr) {
  1004. var c5;
  1005. if (isAlphaSequence) {
  1006. c5 = String.fromCharCode(i6);
  1007. if (c5 === "\\")
  1008. c5 = "";
  1009. } else {
  1010. c5 = String(i6);
  1011. if (pad) {
  1012. var need = width - c5.length;
  1013. if (need > 0) {
  1014. var z2 = new Array(need + 1).join("0");
  1015. if (i6 < 0)
  1016. c5 = "-" + z2 + c5.slice(1);
  1017. else
  1018. c5 = z2 + c5;
  1019. }
  1020. }
  1021. }
  1022. N.push(c5);
  1023. }
  1024. } else {
  1025. N = [];
  1026. for (var j5 = 0; j5 < n5.length; j5++) {
  1027. N.push.apply(N, expand2(n5[j5], false));
  1028. }
  1029. }
  1030. for (var j5 = 0; j5 < N.length; j5++) {
  1031. for (var k5 = 0; k5 < post.length; k5++) {
  1032. var expansion = pre + N[j5] + post[k5];
  1033. if (!isTop || isSequence || expansion)
  1034. expansions.push(expansion);
  1035. }
  1036. }
  1037. }
  1038. return expansions;
  1039. }
  1040. }
  1041. });
  1042. // ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js
  1043. var require_minimatch = __commonJS({
  1044. "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js"(exports, module) {
  1045. "use strict";
  1046. var minimatch2 = module.exports = (p5, pattern, options = {}) => {
  1047. assertValidPattern2(pattern);
  1048. if (!options.nocomment && pattern.charAt(0) === "#") {
  1049. return false;
  1050. }
  1051. return new Minimatch2(pattern, options).match(p5);
  1052. };
  1053. module.exports = minimatch2;
  1054. var path3 = require_path();
  1055. minimatch2.sep = path3.sep;
  1056. var GLOBSTAR2 = Symbol("globstar **");
  1057. minimatch2.GLOBSTAR = GLOBSTAR2;
  1058. var expand2 = require_brace_expansion();
  1059. var plTypes2 = {
  1060. "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
  1061. "?": { open: "(?:", close: ")?" },
  1062. "+": { open: "(?:", close: ")+" },
  1063. "*": { open: "(?:", close: ")*" },
  1064. "@": { open: "(?:", close: ")" }
  1065. };
  1066. var qmark2 = "[^/]";
  1067. var star2 = qmark2 + "*?";
  1068. var twoStarDot2 = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
  1069. var twoStarNoDot2 = "(?:(?!(?:\\/|^)\\.).)*?";
  1070. var charSet2 = (s6) => s6.split("").reduce((set, c5) => {
  1071. set[c5] = true;
  1072. return set;
  1073. }, {});
  1074. var reSpecials2 = charSet2("().*{}+?[]^$\\!");
  1075. var addPatternStartSet2 = charSet2("[.(");
  1076. var slashSplit = /\/+/;
  1077. minimatch2.filter = (pattern, options = {}) => (p5, i6, list) => minimatch2(p5, pattern, options);
  1078. var ext2 = (a5, b5 = {}) => {
  1079. const t6 = {};
  1080. Object.keys(a5).forEach((k5) => t6[k5] = a5[k5]);
  1081. Object.keys(b5).forEach((k5) => t6[k5] = b5[k5]);
  1082. return t6;
  1083. };
  1084. minimatch2.defaults = (def) => {
  1085. if (!def || typeof def !== "object" || !Object.keys(def).length) {
  1086. return minimatch2;
  1087. }
  1088. const orig = minimatch2;
  1089. const m6 = (p5, pattern, options) => orig(p5, pattern, ext2(def, options));
  1090. m6.Minimatch = class Minimatch extends orig.Minimatch {
  1091. constructor(pattern, options) {
  1092. super(pattern, ext2(def, options));
  1093. }
  1094. };
  1095. m6.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
  1096. m6.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
  1097. m6.defaults = (options) => orig.defaults(ext2(def, options));
  1098. m6.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
  1099. m6.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
  1100. m6.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
  1101. return m6;
  1102. };
  1103. minimatch2.braceExpand = (pattern, options) => braceExpand2(pattern, options);
  1104. var braceExpand2 = (pattern, options = {}) => {
  1105. assertValidPattern2(pattern);
  1106. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  1107. return [pattern];
  1108. }
  1109. return expand2(pattern);
  1110. };
  1111. var MAX_PATTERN_LENGTH2 = 1024 * 64;
  1112. var assertValidPattern2 = (pattern) => {
  1113. if (typeof pattern !== "string") {
  1114. throw new TypeError("invalid pattern");
  1115. }
  1116. if (pattern.length > MAX_PATTERN_LENGTH2) {
  1117. throw new TypeError("pattern is too long");
  1118. }
  1119. };
  1120. var SUBPARSE = Symbol("subparse");
  1121. minimatch2.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
  1122. minimatch2.match = (list, pattern, options = {}) => {
  1123. const mm = new Minimatch2(pattern, options);
  1124. list = list.filter((f7) => mm.match(f7));
  1125. if (mm.options.nonull && !list.length) {
  1126. list.push(pattern);
  1127. }
  1128. return list;
  1129. };
  1130. var globUnescape2 = (s6) => s6.replace(/\\(.)/g, "$1");
  1131. var charUnescape = (s6) => s6.replace(/\\([^-\]])/g, "$1");
  1132. var regExpEscape2 = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  1133. var braExpEscape = (s6) => s6.replace(/[[\]\\]/g, "\\$&");
  1134. var Minimatch2 = class {
  1135. constructor(pattern, options) {
  1136. assertValidPattern2(pattern);
  1137. if (!options) options = {};
  1138. this.options = options;
  1139. this.set = [];
  1140. this.pattern = pattern;
  1141. this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  1142. if (this.windowsPathsNoEscape) {
  1143. this.pattern = this.pattern.replace(/\\/g, "/");
  1144. }
  1145. this.regexp = null;
  1146. this.negate = false;
  1147. this.comment = false;
  1148. this.empty = false;
  1149. this.partial = !!options.partial;
  1150. this.make();
  1151. }
  1152. debug() {
  1153. }
  1154. make() {
  1155. const pattern = this.pattern;
  1156. const options = this.options;
  1157. if (!options.nocomment && pattern.charAt(0) === "#") {
  1158. this.comment = true;
  1159. return;
  1160. }
  1161. if (!pattern) {
  1162. this.empty = true;
  1163. return;
  1164. }
  1165. this.parseNegate();
  1166. let set = this.globSet = this.braceExpand();
  1167. if (options.debug) this.debug = (...args) => console.error(...args);
  1168. this.debug(this.pattern, set);
  1169. set = this.globParts = set.map((s6) => s6.split(slashSplit));
  1170. this.debug(this.pattern, set);
  1171. set = set.map((s6, si, set2) => s6.map(this.parse, this));
  1172. this.debug(this.pattern, set);
  1173. set = set.filter((s6) => s6.indexOf(false) === -1);
  1174. this.debug(this.pattern, set);
  1175. this.set = set;
  1176. }
  1177. parseNegate() {
  1178. if (this.options.nonegate) return;
  1179. const pattern = this.pattern;
  1180. let negate2 = false;
  1181. let negateOffset = 0;
  1182. for (let i6 = 0; i6 < pattern.length && pattern.charAt(i6) === "!"; i6++) {
  1183. negate2 = !negate2;
  1184. negateOffset++;
  1185. }
  1186. if (negateOffset) this.pattern = pattern.slice(negateOffset);
  1187. this.negate = negate2;
  1188. }
  1189. // set partial to true to test if, for example,
  1190. // "/a/b" matches the start of "/*/b/*/d"
  1191. // Partial means, if you run out of file before you run
  1192. // out of pattern, then that's fine, as long as all
  1193. // the parts match.
  1194. matchOne(file, pattern, partial) {
  1195. var options = this.options;
  1196. this.debug(
  1197. "matchOne",
  1198. { "this": this, file, pattern }
  1199. );
  1200. this.debug("matchOne", file.length, pattern.length);
  1201. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  1202. this.debug("matchOne loop");
  1203. var p5 = pattern[pi];
  1204. var f7 = file[fi];
  1205. this.debug(pattern, p5, f7);
  1206. if (p5 === false) return false;
  1207. if (p5 === GLOBSTAR2) {
  1208. this.debug("GLOBSTAR", [pattern, p5, f7]);
  1209. var fr = fi;
  1210. var pr = pi + 1;
  1211. if (pr === pl) {
  1212. this.debug("** at the end");
  1213. for (; fi < fl; fi++) {
  1214. if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
  1215. }
  1216. return true;
  1217. }
  1218. while (fr < fl) {
  1219. var swallowee = file[fr];
  1220. this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
  1221. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  1222. this.debug("globstar found match!", fr, fl, swallowee);
  1223. return true;
  1224. } else {
  1225. if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
  1226. this.debug("dot detected!", file, fr, pattern, pr);
  1227. break;
  1228. }
  1229. this.debug("globstar swallow a segment, and continue");
  1230. fr++;
  1231. }
  1232. }
  1233. if (partial) {
  1234. this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
  1235. if (fr === fl) return true;
  1236. }
  1237. return false;
  1238. }
  1239. var hit;
  1240. if (typeof p5 === "string") {
  1241. hit = f7 === p5;
  1242. this.debug("string match", p5, f7, hit);
  1243. } else {
  1244. hit = f7.match(p5);
  1245. this.debug("pattern match", p5, f7, hit);
  1246. }
  1247. if (!hit) return false;
  1248. }
  1249. if (fi === fl && pi === pl) {
  1250. return true;
  1251. } else if (fi === fl) {
  1252. return partial;
  1253. } else if (pi === pl) {
  1254. return fi === fl - 1 && file[fi] === "";
  1255. }
  1256. throw new Error("wtf?");
  1257. }
  1258. braceExpand() {
  1259. return braceExpand2(this.pattern, this.options);
  1260. }
  1261. parse(pattern, isSub) {
  1262. assertValidPattern2(pattern);
  1263. const options = this.options;
  1264. if (pattern === "**") {
  1265. if (!options.noglobstar)
  1266. return GLOBSTAR2;
  1267. else
  1268. pattern = "*";
  1269. }
  1270. if (pattern === "") return "";
  1271. let re = "";
  1272. let hasMagic = false;
  1273. let escaping = false;
  1274. const patternListStack = [];
  1275. const negativeLists = [];
  1276. let stateChar;
  1277. let inClass = false;
  1278. let reClassStart = -1;
  1279. let classStart = -1;
  1280. let cs;
  1281. let pl;
  1282. let sp;
  1283. let dotTravAllowed = pattern.charAt(0) === ".";
  1284. let dotFileAllowed = options.dot || dotTravAllowed;
  1285. const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  1286. const subPatternStart = (p5) => p5.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  1287. const clearStateChar = () => {
  1288. if (stateChar) {
  1289. switch (stateChar) {
  1290. case "*":
  1291. re += star2;
  1292. hasMagic = true;
  1293. break;
  1294. case "?":
  1295. re += qmark2;
  1296. hasMagic = true;
  1297. break;
  1298. default:
  1299. re += "\\" + stateChar;
  1300. break;
  1301. }
  1302. this.debug("clearStateChar %j %j", stateChar, re);
  1303. stateChar = false;
  1304. }
  1305. };
  1306. for (let i6 = 0, c5; i6 < pattern.length && (c5 = pattern.charAt(i6)); i6++) {
  1307. this.debug("%s %s %s %j", pattern, i6, re, c5);
  1308. if (escaping) {
  1309. if (c5 === "/") {
  1310. return false;
  1311. }
  1312. if (reSpecials2[c5]) {
  1313. re += "\\";
  1314. }
  1315. re += c5;
  1316. escaping = false;
  1317. continue;
  1318. }
  1319. switch (c5) {
  1320. /* istanbul ignore next */
  1321. case "/": {
  1322. return false;
  1323. }
  1324. case "\\":
  1325. if (inClass && pattern.charAt(i6 + 1) === "-") {
  1326. re += c5;
  1327. continue;
  1328. }
  1329. clearStateChar();
  1330. escaping = true;
  1331. continue;
  1332. // the various stateChar values
  1333. // for the "extglob" stuff.
  1334. case "?":
  1335. case "*":
  1336. case "+":
  1337. case "@":
  1338. case "!":
  1339. this.debug("%s %s %s %j <-- stateChar", pattern, i6, re, c5);
  1340. if (inClass) {
  1341. this.debug(" in class");
  1342. if (c5 === "!" && i6 === classStart + 1) c5 = "^";
  1343. re += c5;
  1344. continue;
  1345. }
  1346. this.debug("call clearStateChar %j", stateChar);
  1347. clearStateChar();
  1348. stateChar = c5;
  1349. if (options.noext) clearStateChar();
  1350. continue;
  1351. case "(": {
  1352. if (inClass) {
  1353. re += "(";
  1354. continue;
  1355. }
  1356. if (!stateChar) {
  1357. re += "\\(";
  1358. continue;
  1359. }
  1360. const plEntry = {
  1361. type: stateChar,
  1362. start: i6 - 1,
  1363. reStart: re.length,
  1364. open: plTypes2[stateChar].open,
  1365. close: plTypes2[stateChar].close
  1366. };
  1367. this.debug(this.pattern, " ", plEntry);
  1368. patternListStack.push(plEntry);
  1369. re += plEntry.open;
  1370. if (plEntry.start === 0 && plEntry.type !== "!") {
  1371. dotTravAllowed = true;
  1372. re += subPatternStart(pattern.slice(i6 + 1));
  1373. }
  1374. this.debug("plType %j %j", stateChar, re);
  1375. stateChar = false;
  1376. continue;
  1377. }
  1378. case ")": {
  1379. const plEntry = patternListStack[patternListStack.length - 1];
  1380. if (inClass || !plEntry) {
  1381. re += "\\)";
  1382. continue;
  1383. }
  1384. patternListStack.pop();
  1385. clearStateChar();
  1386. hasMagic = true;
  1387. pl = plEntry;
  1388. re += pl.close;
  1389. if (pl.type === "!") {
  1390. negativeLists.push(Object.assign(pl, { reEnd: re.length }));
  1391. }
  1392. continue;
  1393. }
  1394. case "|": {
  1395. const plEntry = patternListStack[patternListStack.length - 1];
  1396. if (inClass || !plEntry) {
  1397. re += "\\|";
  1398. continue;
  1399. }
  1400. clearStateChar();
  1401. re += "|";
  1402. if (plEntry.start === 0 && plEntry.type !== "!") {
  1403. dotTravAllowed = true;
  1404. re += subPatternStart(pattern.slice(i6 + 1));
  1405. }
  1406. continue;
  1407. }
  1408. // these are mostly the same in regexp and glob
  1409. case "[":
  1410. clearStateChar();
  1411. if (inClass) {
  1412. re += "\\" + c5;
  1413. continue;
  1414. }
  1415. inClass = true;
  1416. classStart = i6;
  1417. reClassStart = re.length;
  1418. re += c5;
  1419. continue;
  1420. case "]":
  1421. if (i6 === classStart + 1 || !inClass) {
  1422. re += "\\" + c5;
  1423. continue;
  1424. }
  1425. cs = pattern.substring(classStart + 1, i6);
  1426. try {
  1427. RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
  1428. re += c5;
  1429. } catch (er) {
  1430. re = re.substring(0, reClassStart) + "(?:$.)";
  1431. }
  1432. hasMagic = true;
  1433. inClass = false;
  1434. continue;
  1435. default:
  1436. clearStateChar();
  1437. if (reSpecials2[c5] && !(c5 === "^" && inClass)) {
  1438. re += "\\";
  1439. }
  1440. re += c5;
  1441. break;
  1442. }
  1443. }
  1444. if (inClass) {
  1445. cs = pattern.slice(classStart + 1);
  1446. sp = this.parse(cs, SUBPARSE);
  1447. re = re.substring(0, reClassStart) + "\\[" + sp[0];
  1448. hasMagic = hasMagic || sp[1];
  1449. }
  1450. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  1451. let tail;
  1452. tail = re.slice(pl.reStart + pl.open.length);
  1453. this.debug("setting tail", re, pl);
  1454. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => {
  1455. if (!$2) {
  1456. $2 = "\\";
  1457. }
  1458. return $1 + $1 + $2 + "|";
  1459. });
  1460. this.debug("tail=%j\n %s", tail, tail, pl, re);
  1461. const t6 = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type;
  1462. hasMagic = true;
  1463. re = re.slice(0, pl.reStart) + t6 + "\\(" + tail;
  1464. }
  1465. clearStateChar();
  1466. if (escaping) {
  1467. re += "\\\\";
  1468. }
  1469. const addPatternStart = addPatternStartSet2[re.charAt(0)];
  1470. for (let n5 = negativeLists.length - 1; n5 > -1; n5--) {
  1471. const nl = negativeLists[n5];
  1472. const nlBefore = re.slice(0, nl.reStart);
  1473. const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  1474. let nlAfter = re.slice(nl.reEnd);
  1475. const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
  1476. const closeParensBefore = nlBefore.split(")").length;
  1477. const openParensBefore = nlBefore.split("(").length - closeParensBefore;
  1478. let cleanAfter = nlAfter;
  1479. for (let i6 = 0; i6 < openParensBefore; i6++) {
  1480. cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
  1481. }
  1482. nlAfter = cleanAfter;
  1483. const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
  1484. re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  1485. }
  1486. if (re !== "" && hasMagic) {
  1487. re = "(?=.)" + re;
  1488. }
  1489. if (addPatternStart) {
  1490. re = patternStart() + re;
  1491. }
  1492. if (isSub === SUBPARSE) {
  1493. return [re, hasMagic];
  1494. }
  1495. if (options.nocase && !hasMagic) {
  1496. hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
  1497. }
  1498. if (!hasMagic) {
  1499. return globUnescape2(pattern);
  1500. }
  1501. const flags = options.nocase ? "i" : "";
  1502. try {
  1503. return Object.assign(new RegExp("^" + re + "$", flags), {
  1504. _glob: pattern,
  1505. _src: re
  1506. });
  1507. } catch (er) {
  1508. return new RegExp("$.");
  1509. }
  1510. }
  1511. makeRe() {
  1512. if (this.regexp || this.regexp === false) return this.regexp;
  1513. const set = this.set;
  1514. if (!set.length) {
  1515. this.regexp = false;
  1516. return this.regexp;
  1517. }
  1518. const options = this.options;
  1519. const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot2 : twoStarNoDot2;
  1520. const flags = options.nocase ? "i" : "";
  1521. let re = set.map((pattern) => {
  1522. pattern = pattern.map(
  1523. (p5) => typeof p5 === "string" ? regExpEscape2(p5) : p5 === GLOBSTAR2 ? GLOBSTAR2 : p5._src
  1524. ).reduce((set2, p5) => {
  1525. if (!(set2[set2.length - 1] === GLOBSTAR2 && p5 === GLOBSTAR2)) {
  1526. set2.push(p5);
  1527. }
  1528. return set2;
  1529. }, []);
  1530. pattern.forEach((p5, i6) => {
  1531. if (p5 !== GLOBSTAR2 || pattern[i6 - 1] === GLOBSTAR2) {
  1532. return;
  1533. }
  1534. if (i6 === 0) {
  1535. if (pattern.length > 1) {
  1536. pattern[i6 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i6 + 1];
  1537. } else {
  1538. pattern[i6] = twoStar;
  1539. }
  1540. } else if (i6 === pattern.length - 1) {
  1541. pattern[i6 - 1] += "(?:\\/|" + twoStar + ")?";
  1542. } else {
  1543. pattern[i6 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i6 + 1];
  1544. pattern[i6 + 1] = GLOBSTAR2;
  1545. }
  1546. });
  1547. return pattern.filter((p5) => p5 !== GLOBSTAR2).join("/");
  1548. }).join("|");
  1549. re = "^(?:" + re + ")$";
  1550. if (this.negate) re = "^(?!" + re + ").*$";
  1551. try {
  1552. this.regexp = new RegExp(re, flags);
  1553. } catch (ex) {
  1554. this.regexp = false;
  1555. }
  1556. return this.regexp;
  1557. }
  1558. match(f7, partial = this.partial) {
  1559. this.debug("match", f7, this.pattern);
  1560. if (this.comment) return false;
  1561. if (this.empty) return f7 === "";
  1562. if (f7 === "/" && partial) return true;
  1563. const options = this.options;
  1564. if (path3.sep !== "/") {
  1565. f7 = f7.split(path3.sep).join("/");
  1566. }
  1567. f7 = f7.split(slashSplit);
  1568. this.debug(this.pattern, "split", f7);
  1569. const set = this.set;
  1570. this.debug(this.pattern, "set", set);
  1571. let filename;
  1572. for (let i6 = f7.length - 1; i6 >= 0; i6--) {
  1573. filename = f7[i6];
  1574. if (filename) break;
  1575. }
  1576. for (let i6 = 0; i6 < set.length; i6++) {
  1577. const pattern = set[i6];
  1578. let file = f7;
  1579. if (options.matchBase && pattern.length === 1) {
  1580. file = [filename];
  1581. }
  1582. const hit = this.matchOne(file, pattern, partial);
  1583. if (hit) {
  1584. if (options.flipNegate) return true;
  1585. return !this.negate;
  1586. }
  1587. }
  1588. if (options.flipNegate) return false;
  1589. return this.negate;
  1590. }
  1591. static defaults(def) {
  1592. return minimatch2.defaults(def).Minimatch;
  1593. }
  1594. };
  1595. minimatch2.Minimatch = Minimatch2;
  1596. }
  1597. });
  1598. // ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js
  1599. var require_inherits_browser = __commonJS({
  1600. "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports, module) {
  1601. "use strict";
  1602. if (typeof Object.create === "function") {
  1603. module.exports = function inherits(ctor, superCtor) {
  1604. if (superCtor) {
  1605. ctor.super_ = superCtor;
  1606. ctor.prototype = Object.create(superCtor.prototype, {
  1607. constructor: {
  1608. value: ctor,
  1609. enumerable: false,
  1610. writable: true,
  1611. configurable: true
  1612. }
  1613. });
  1614. }
  1615. };
  1616. } else {
  1617. module.exports = function inherits(ctor, superCtor) {
  1618. if (superCtor) {
  1619. ctor.super_ = superCtor;
  1620. var TempCtor = function() {
  1621. };
  1622. TempCtor.prototype = superCtor.prototype;
  1623. ctor.prototype = new TempCtor();
  1624. ctor.prototype.constructor = ctor;
  1625. }
  1626. };
  1627. }
  1628. }
  1629. });
  1630. // ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js
  1631. var require_inherits = __commonJS({
  1632. "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports, module) {
  1633. "use strict";
  1634. try {
  1635. util2 = __require("util");
  1636. if (typeof util2.inherits !== "function") throw "";
  1637. module.exports = util2.inherits;
  1638. } catch (e6) {
  1639. module.exports = require_inherits_browser();
  1640. }
  1641. var util2;
  1642. }
  1643. });
  1644. // ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js
  1645. var require_common = __commonJS({
  1646. "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js"(exports) {
  1647. "use strict";
  1648. exports.setopts = setopts;
  1649. exports.ownProp = ownProp;
  1650. exports.makeAbs = makeAbs;
  1651. exports.finish = finish;
  1652. exports.mark = mark;
  1653. exports.isIgnored = isIgnored;
  1654. exports.childrenIgnored = childrenIgnored;
  1655. function ownProp(obj, field) {
  1656. return Object.prototype.hasOwnProperty.call(obj, field);
  1657. }
  1658. var fs5 = __require("fs");
  1659. var path3 = __require("path");
  1660. var minimatch2 = require_minimatch();
  1661. var isAbsolute = __require("path").isAbsolute;
  1662. var Minimatch2 = minimatch2.Minimatch;
  1663. function alphasort(a5, b5) {
  1664. return a5.localeCompare(b5, "en");
  1665. }
  1666. function setupIgnores(self2, options) {
  1667. self2.ignore = options.ignore || [];
  1668. if (!Array.isArray(self2.ignore))
  1669. self2.ignore = [self2.ignore];
  1670. if (self2.ignore.length) {
  1671. self2.ignore = self2.ignore.map(ignoreMap);
  1672. }
  1673. }
  1674. function ignoreMap(pattern) {
  1675. var gmatcher = null;
  1676. if (pattern.slice(-3) === "/**") {
  1677. var gpattern = pattern.replace(/(\/\*\*)+$/, "");
  1678. gmatcher = new Minimatch2(gpattern, { dot: true });
  1679. }
  1680. return {
  1681. matcher: new Minimatch2(pattern, { dot: true }),
  1682. gmatcher
  1683. };
  1684. }
  1685. function setopts(self2, pattern, options) {
  1686. if (!options)
  1687. options = {};
  1688. if (options.matchBase && -1 === pattern.indexOf("/")) {
  1689. if (options.noglobstar) {
  1690. throw new Error("base matching requires globstar");
  1691. }
  1692. pattern = "**/" + pattern;
  1693. }
  1694. self2.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  1695. if (self2.windowsPathsNoEscape) {
  1696. pattern = pattern.replace(/\\/g, "/");
  1697. }
  1698. self2.silent = !!options.silent;
  1699. self2.pattern = pattern;
  1700. self2.strict = options.strict !== false;
  1701. self2.realpath = !!options.realpath;
  1702. self2.realpathCache = options.realpathCache || /* @__PURE__ */ Object.create(null);
  1703. self2.follow = !!options.follow;
  1704. self2.dot = !!options.dot;
  1705. self2.mark = !!options.mark;
  1706. self2.nodir = !!options.nodir;
  1707. if (self2.nodir)
  1708. self2.mark = true;
  1709. self2.sync = !!options.sync;
  1710. self2.nounique = !!options.nounique;
  1711. self2.nonull = !!options.nonull;
  1712. self2.nosort = !!options.nosort;
  1713. self2.nocase = !!options.nocase;
  1714. self2.stat = !!options.stat;
  1715. self2.noprocess = !!options.noprocess;
  1716. self2.absolute = !!options.absolute;
  1717. self2.fs = options.fs || fs5;
  1718. self2.maxLength = options.maxLength || Infinity;
  1719. self2.cache = options.cache || /* @__PURE__ */ Object.create(null);
  1720. self2.statCache = options.statCache || /* @__PURE__ */ Object.create(null);
  1721. self2.symlinks = options.symlinks || /* @__PURE__ */ Object.create(null);
  1722. setupIgnores(self2, options);
  1723. self2.changedCwd = false;
  1724. var cwd = process.cwd();
  1725. if (!ownProp(options, "cwd"))
  1726. self2.cwd = path3.resolve(cwd);
  1727. else {
  1728. self2.cwd = path3.resolve(options.cwd);
  1729. self2.changedCwd = self2.cwd !== cwd;
  1730. }
  1731. self2.root = options.root || path3.resolve(self2.cwd, "/");
  1732. self2.root = path3.resolve(self2.root);
  1733. self2.cwdAbs = isAbsolute(self2.cwd) ? self2.cwd : makeAbs(self2, self2.cwd);
  1734. self2.nomount = !!options.nomount;
  1735. if (process.platform === "win32") {
  1736. self2.root = self2.root.replace(/\\/g, "/");
  1737. self2.cwd = self2.cwd.replace(/\\/g, "/");
  1738. self2.cwdAbs = self2.cwdAbs.replace(/\\/g, "/");
  1739. }
  1740. options.nonegate = true;
  1741. options.nocomment = true;
  1742. self2.minimatch = new Minimatch2(pattern, options);
  1743. self2.options = self2.minimatch.options;
  1744. }
  1745. function finish(self2) {
  1746. var nou = self2.nounique;
  1747. var all = nou ? [] : /* @__PURE__ */ Object.create(null);
  1748. for (var i6 = 0, l5 = self2.matches.length; i6 < l5; i6++) {
  1749. var matches = self2.matches[i6];
  1750. if (!matches || Object.keys(matches).length === 0) {
  1751. if (self2.nonull) {
  1752. var literal = self2.minimatch.globSet[i6];
  1753. if (nou)
  1754. all.push(literal);
  1755. else
  1756. all[literal] = true;
  1757. }
  1758. } else {
  1759. var m6 = Object.keys(matches);
  1760. if (nou)
  1761. all.push.apply(all, m6);
  1762. else
  1763. m6.forEach(function(m7) {
  1764. all[m7] = true;
  1765. });
  1766. }
  1767. }
  1768. if (!nou)
  1769. all = Object.keys(all);
  1770. if (!self2.nosort)
  1771. all = all.sort(alphasort);
  1772. if (self2.mark) {
  1773. for (var i6 = 0; i6 < all.length; i6++) {
  1774. all[i6] = self2._mark(all[i6]);
  1775. }
  1776. if (self2.nodir) {
  1777. all = all.filter(function(e6) {
  1778. var notDir = !/\/$/.test(e6);
  1779. var c5 = self2.cache[e6] || self2.cache[makeAbs(self2, e6)];
  1780. if (notDir && c5)
  1781. notDir = c5 !== "DIR" && !Array.isArray(c5);
  1782. return notDir;
  1783. });
  1784. }
  1785. }
  1786. if (self2.ignore.length)
  1787. all = all.filter(function(m7) {
  1788. return !isIgnored(self2, m7);
  1789. });
  1790. self2.found = all;
  1791. }
  1792. function mark(self2, p5) {
  1793. var abs = makeAbs(self2, p5);
  1794. var c5 = self2.cache[abs];
  1795. var m6 = p5;
  1796. if (c5) {
  1797. var isDir = c5 === "DIR" || Array.isArray(c5);
  1798. var slash = p5.slice(-1) === "/";
  1799. if (isDir && !slash)
  1800. m6 += "/";
  1801. else if (!isDir && slash)
  1802. m6 = m6.slice(0, -1);
  1803. if (m6 !== p5) {
  1804. var mabs = makeAbs(self2, m6);
  1805. self2.statCache[mabs] = self2.statCache[abs];
  1806. self2.cache[mabs] = self2.cache[abs];
  1807. }
  1808. }
  1809. return m6;
  1810. }
  1811. function makeAbs(self2, f7) {
  1812. var abs = f7;
  1813. if (f7.charAt(0) === "/") {
  1814. abs = path3.join(self2.root, f7);
  1815. } else if (isAbsolute(f7) || f7 === "") {
  1816. abs = f7;
  1817. } else if (self2.changedCwd) {
  1818. abs = path3.resolve(self2.cwd, f7);
  1819. } else {
  1820. abs = path3.resolve(f7);
  1821. }
  1822. if (process.platform === "win32")
  1823. abs = abs.replace(/\\/g, "/");
  1824. return abs;
  1825. }
  1826. function isIgnored(self2, path4) {
  1827. if (!self2.ignore.length)
  1828. return false;
  1829. return self2.ignore.some(function(item) {
  1830. return item.matcher.match(path4) || !!(item.gmatcher && item.gmatcher.match(path4));
  1831. });
  1832. }
  1833. function childrenIgnored(self2, path4) {
  1834. if (!self2.ignore.length)
  1835. return false;
  1836. return self2.ignore.some(function(item) {
  1837. return !!(item.gmatcher && item.gmatcher.match(path4));
  1838. });
  1839. }
  1840. }
  1841. });
  1842. // ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js
  1843. var require_sync = __commonJS({
  1844. "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js"(exports, module) {
  1845. "use strict";
  1846. module.exports = globSync;
  1847. globSync.GlobSync = GlobSync;
  1848. var rp = require_fs();
  1849. var minimatch2 = require_minimatch();
  1850. var Minimatch2 = minimatch2.Minimatch;
  1851. var Glob = require_glob().Glob;
  1852. var util2 = __require("util");
  1853. var path3 = __require("path");
  1854. var assert = __require("assert");
  1855. var isAbsolute = __require("path").isAbsolute;
  1856. var common = require_common();
  1857. var setopts = common.setopts;
  1858. var ownProp = common.ownProp;
  1859. var childrenIgnored = common.childrenIgnored;
  1860. var isIgnored = common.isIgnored;
  1861. function globSync(pattern, options) {
  1862. if (typeof options === "function" || arguments.length === 3)
  1863. throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
  1864. return new GlobSync(pattern, options).found;
  1865. }
  1866. function GlobSync(pattern, options) {
  1867. if (!pattern)
  1868. throw new Error("must provide pattern");
  1869. if (typeof options === "function" || arguments.length === 3)
  1870. throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
  1871. if (!(this instanceof GlobSync))
  1872. return new GlobSync(pattern, options);
  1873. setopts(this, pattern, options);
  1874. if (this.noprocess)
  1875. return this;
  1876. var n5 = this.minimatch.set.length;
  1877. this.matches = new Array(n5);
  1878. for (var i6 = 0; i6 < n5; i6++) {
  1879. this._process(this.minimatch.set[i6], i6, false);
  1880. }
  1881. this._finish();
  1882. }
  1883. GlobSync.prototype._finish = function() {
  1884. assert.ok(this instanceof GlobSync);
  1885. if (this.realpath) {
  1886. var self2 = this;
  1887. this.matches.forEach(function(matchset, index6) {
  1888. var set = self2.matches[index6] = /* @__PURE__ */ Object.create(null);
  1889. for (var p5 in matchset) {
  1890. try {
  1891. p5 = self2._makeAbs(p5);
  1892. var real = rp.realpathSync(p5, self2.realpathCache);
  1893. set[real] = true;
  1894. } catch (er) {
  1895. if (er.syscall === "stat")
  1896. set[self2._makeAbs(p5)] = true;
  1897. else
  1898. throw er;
  1899. }
  1900. }
  1901. });
  1902. }
  1903. common.finish(this);
  1904. };
  1905. GlobSync.prototype._process = function(pattern, index6, inGlobStar) {
  1906. assert.ok(this instanceof GlobSync);
  1907. var n5 = 0;
  1908. while (typeof pattern[n5] === "string") {
  1909. n5++;
  1910. }
  1911. var prefix2;
  1912. switch (n5) {
  1913. // if not, then this is rather simple
  1914. case pattern.length:
  1915. this._processSimple(pattern.join("/"), index6);
  1916. return;
  1917. case 0:
  1918. prefix2 = null;
  1919. break;
  1920. default:
  1921. prefix2 = pattern.slice(0, n5).join("/");
  1922. break;
  1923. }
  1924. var remain = pattern.slice(n5);
  1925. var read;
  1926. if (prefix2 === null)
  1927. read = ".";
  1928. else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p5) {
  1929. return typeof p5 === "string" ? p5 : "[*]";
  1930. }).join("/"))) {
  1931. if (!prefix2 || !isAbsolute(prefix2))
  1932. prefix2 = "/" + prefix2;
  1933. read = prefix2;
  1934. } else
  1935. read = prefix2;
  1936. var abs = this._makeAbs(read);
  1937. if (childrenIgnored(this, read))
  1938. return;
  1939. var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
  1940. if (isGlobStar)
  1941. this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar);
  1942. else
  1943. this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar);
  1944. };
  1945. GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar) {
  1946. var entries = this._readdir(abs, inGlobStar);
  1947. if (!entries)
  1948. return;
  1949. var pn = remain[0];
  1950. var negate2 = !!this.minimatch.negate;
  1951. var rawGlob = pn._glob;
  1952. var dotOk = this.dot || rawGlob.charAt(0) === ".";
  1953. var matchedEntries = [];
  1954. for (var i6 = 0; i6 < entries.length; i6++) {
  1955. var e6 = entries[i6];
  1956. if (e6.charAt(0) !== "." || dotOk) {
  1957. var m6;
  1958. if (negate2 && !prefix2) {
  1959. m6 = !e6.match(pn);
  1960. } else {
  1961. m6 = e6.match(pn);
  1962. }
  1963. if (m6)
  1964. matchedEntries.push(e6);
  1965. }
  1966. }
  1967. var len = matchedEntries.length;
  1968. if (len === 0)
  1969. return;
  1970. if (remain.length === 1 && !this.mark && !this.stat) {
  1971. if (!this.matches[index6])
  1972. this.matches[index6] = /* @__PURE__ */ Object.create(null);
  1973. for (var i6 = 0; i6 < len; i6++) {
  1974. var e6 = matchedEntries[i6];
  1975. if (prefix2) {
  1976. if (prefix2.slice(-1) !== "/")
  1977. e6 = prefix2 + "/" + e6;
  1978. else
  1979. e6 = prefix2 + e6;
  1980. }
  1981. if (e6.charAt(0) === "/" && !this.nomount) {
  1982. e6 = path3.join(this.root, e6);
  1983. }
  1984. this._emitMatch(index6, e6);
  1985. }
  1986. return;
  1987. }
  1988. remain.shift();
  1989. for (var i6 = 0; i6 < len; i6++) {
  1990. var e6 = matchedEntries[i6];
  1991. var newPattern;
  1992. if (prefix2)
  1993. newPattern = [prefix2, e6];
  1994. else
  1995. newPattern = [e6];
  1996. this._process(newPattern.concat(remain), index6, inGlobStar);
  1997. }
  1998. };
  1999. GlobSync.prototype._emitMatch = function(index6, e6) {
  2000. if (isIgnored(this, e6))
  2001. return;
  2002. var abs = this._makeAbs(e6);
  2003. if (this.mark)
  2004. e6 = this._mark(e6);
  2005. if (this.absolute) {
  2006. e6 = abs;
  2007. }
  2008. if (this.matches[index6][e6])
  2009. return;
  2010. if (this.nodir) {
  2011. var c5 = this.cache[abs];
  2012. if (c5 === "DIR" || Array.isArray(c5))
  2013. return;
  2014. }
  2015. this.matches[index6][e6] = true;
  2016. if (this.stat)
  2017. this._stat(e6);
  2018. };
  2019. GlobSync.prototype._readdirInGlobStar = function(abs) {
  2020. if (this.follow)
  2021. return this._readdir(abs, false);
  2022. var entries;
  2023. var lstat;
  2024. var stat2;
  2025. try {
  2026. lstat = this.fs.lstatSync(abs);
  2027. } catch (er) {
  2028. if (er.code === "ENOENT") {
  2029. return null;
  2030. }
  2031. }
  2032. var isSym = lstat && lstat.isSymbolicLink();
  2033. this.symlinks[abs] = isSym;
  2034. if (!isSym && lstat && !lstat.isDirectory())
  2035. this.cache[abs] = "FILE";
  2036. else
  2037. entries = this._readdir(abs, false);
  2038. return entries;
  2039. };
  2040. GlobSync.prototype._readdir = function(abs, inGlobStar) {
  2041. var entries;
  2042. if (inGlobStar && !ownProp(this.symlinks, abs))
  2043. return this._readdirInGlobStar(abs);
  2044. if (ownProp(this.cache, abs)) {
  2045. var c5 = this.cache[abs];
  2046. if (!c5 || c5 === "FILE")
  2047. return null;
  2048. if (Array.isArray(c5))
  2049. return c5;
  2050. }
  2051. try {
  2052. return this._readdirEntries(abs, this.fs.readdirSync(abs));
  2053. } catch (er) {
  2054. this._readdirError(abs, er);
  2055. return null;
  2056. }
  2057. };
  2058. GlobSync.prototype._readdirEntries = function(abs, entries) {
  2059. if (!this.mark && !this.stat) {
  2060. for (var i6 = 0; i6 < entries.length; i6++) {
  2061. var e6 = entries[i6];
  2062. if (abs === "/")
  2063. e6 = abs + e6;
  2064. else
  2065. e6 = abs + "/" + e6;
  2066. this.cache[e6] = true;
  2067. }
  2068. }
  2069. this.cache[abs] = entries;
  2070. return entries;
  2071. };
  2072. GlobSync.prototype._readdirError = function(f7, er) {
  2073. switch (er.code) {
  2074. case "ENOTSUP":
  2075. // https://github.com/isaacs/node-glob/issues/205
  2076. case "ENOTDIR":
  2077. var abs = this._makeAbs(f7);
  2078. this.cache[abs] = "FILE";
  2079. if (abs === this.cwdAbs) {
  2080. var error2 = new Error(er.code + " invalid cwd " + this.cwd);
  2081. error2.path = this.cwd;
  2082. error2.code = er.code;
  2083. throw error2;
  2084. }
  2085. break;
  2086. case "ENOENT":
  2087. // not terribly unusual
  2088. case "ELOOP":
  2089. case "ENAMETOOLONG":
  2090. case "UNKNOWN":
  2091. this.cache[this._makeAbs(f7)] = false;
  2092. break;
  2093. default:
  2094. this.cache[this._makeAbs(f7)] = false;
  2095. if (this.strict)
  2096. throw er;
  2097. if (!this.silent)
  2098. console.error("glob error", er);
  2099. break;
  2100. }
  2101. };
  2102. GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar) {
  2103. var entries = this._readdir(abs, inGlobStar);
  2104. if (!entries)
  2105. return;
  2106. var remainWithoutGlobStar = remain.slice(1);
  2107. var gspref = prefix2 ? [prefix2] : [];
  2108. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  2109. this._process(noGlobStar, index6, false);
  2110. var len = entries.length;
  2111. var isSym = this.symlinks[abs];
  2112. if (isSym && inGlobStar)
  2113. return;
  2114. for (var i6 = 0; i6 < len; i6++) {
  2115. var e6 = entries[i6];
  2116. if (e6.charAt(0) === "." && !this.dot)
  2117. continue;
  2118. var instead = gspref.concat(entries[i6], remainWithoutGlobStar);
  2119. this._process(instead, index6, true);
  2120. var below = gspref.concat(entries[i6], remain);
  2121. this._process(below, index6, true);
  2122. }
  2123. };
  2124. GlobSync.prototype._processSimple = function(prefix2, index6) {
  2125. var exists = this._stat(prefix2);
  2126. if (!this.matches[index6])
  2127. this.matches[index6] = /* @__PURE__ */ Object.create(null);
  2128. if (!exists)
  2129. return;
  2130. if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
  2131. var trail = /[\/\\]$/.test(prefix2);
  2132. if (prefix2.charAt(0) === "/") {
  2133. prefix2 = path3.join(this.root, prefix2);
  2134. } else {
  2135. prefix2 = path3.resolve(this.root, prefix2);
  2136. if (trail)
  2137. prefix2 += "/";
  2138. }
  2139. }
  2140. if (process.platform === "win32")
  2141. prefix2 = prefix2.replace(/\\/g, "/");
  2142. this._emitMatch(index6, prefix2);
  2143. };
  2144. GlobSync.prototype._stat = function(f7) {
  2145. var abs = this._makeAbs(f7);
  2146. var needDir = f7.slice(-1) === "/";
  2147. if (f7.length > this.maxLength)
  2148. return false;
  2149. if (!this.stat && ownProp(this.cache, abs)) {
  2150. var c5 = this.cache[abs];
  2151. if (Array.isArray(c5))
  2152. c5 = "DIR";
  2153. if (!needDir || c5 === "DIR")
  2154. return c5;
  2155. if (needDir && c5 === "FILE")
  2156. return false;
  2157. }
  2158. var exists;
  2159. var stat2 = this.statCache[abs];
  2160. if (!stat2) {
  2161. var lstat;
  2162. try {
  2163. lstat = this.fs.lstatSync(abs);
  2164. } catch (er) {
  2165. if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
  2166. this.statCache[abs] = false;
  2167. return false;
  2168. }
  2169. }
  2170. if (lstat && lstat.isSymbolicLink()) {
  2171. try {
  2172. stat2 = this.fs.statSync(abs);
  2173. } catch (er) {
  2174. stat2 = lstat;
  2175. }
  2176. } else {
  2177. stat2 = lstat;
  2178. }
  2179. }
  2180. this.statCache[abs] = stat2;
  2181. var c5 = true;
  2182. if (stat2)
  2183. c5 = stat2.isDirectory() ? "DIR" : "FILE";
  2184. this.cache[abs] = this.cache[abs] || c5;
  2185. if (needDir && c5 === "FILE")
  2186. return false;
  2187. return c5;
  2188. };
  2189. GlobSync.prototype._mark = function(p5) {
  2190. return common.mark(this, p5);
  2191. };
  2192. GlobSync.prototype._makeAbs = function(f7) {
  2193. return common.makeAbs(this, f7);
  2194. };
  2195. }
  2196. });
  2197. // ../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js
  2198. var require_wrappy = __commonJS({
  2199. "../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports, module) {
  2200. "use strict";
  2201. module.exports = wrappy;
  2202. function wrappy(fn, cb) {
  2203. if (fn && cb) return wrappy(fn)(cb);
  2204. if (typeof fn !== "function")
  2205. throw new TypeError("need wrapper function");
  2206. Object.keys(fn).forEach(function(k5) {
  2207. wrapper[k5] = fn[k5];
  2208. });
  2209. return wrapper;
  2210. function wrapper() {
  2211. var args = new Array(arguments.length);
  2212. for (var i6 = 0; i6 < args.length; i6++) {
  2213. args[i6] = arguments[i6];
  2214. }
  2215. var ret = fn.apply(this, args);
  2216. var cb2 = args[args.length - 1];
  2217. if (typeof ret === "function" && ret !== cb2) {
  2218. Object.keys(cb2).forEach(function(k5) {
  2219. ret[k5] = cb2[k5];
  2220. });
  2221. }
  2222. return ret;
  2223. }
  2224. }
  2225. }
  2226. });
  2227. // ../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
  2228. var require_once = __commonJS({
  2229. "../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports, module) {
  2230. "use strict";
  2231. var wrappy = require_wrappy();
  2232. module.exports = wrappy(once);
  2233. module.exports.strict = wrappy(onceStrict);
  2234. once.proto = once(function() {
  2235. Object.defineProperty(Function.prototype, "once", {
  2236. value: function() {
  2237. return once(this);
  2238. },
  2239. configurable: true
  2240. });
  2241. Object.defineProperty(Function.prototype, "onceStrict", {
  2242. value: function() {
  2243. return onceStrict(this);
  2244. },
  2245. configurable: true
  2246. });
  2247. });
  2248. function once(fn) {
  2249. var f7 = function() {
  2250. if (f7.called) return f7.value;
  2251. f7.called = true;
  2252. return f7.value = fn.apply(this, arguments);
  2253. };
  2254. f7.called = false;
  2255. return f7;
  2256. }
  2257. function onceStrict(fn) {
  2258. var f7 = function() {
  2259. if (f7.called)
  2260. throw new Error(f7.onceError);
  2261. f7.called = true;
  2262. return f7.value = fn.apply(this, arguments);
  2263. };
  2264. var name = fn.name || "Function wrapped with `once`";
  2265. f7.onceError = name + " shouldn't be called more than once";
  2266. f7.called = false;
  2267. return f7;
  2268. }
  2269. }
  2270. });
  2271. // ../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js
  2272. var require_inflight = __commonJS({
  2273. "../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js"(exports, module) {
  2274. "use strict";
  2275. var wrappy = require_wrappy();
  2276. var reqs = /* @__PURE__ */ Object.create(null);
  2277. var once = require_once();
  2278. module.exports = wrappy(inflight);
  2279. function inflight(key, cb) {
  2280. if (reqs[key]) {
  2281. reqs[key].push(cb);
  2282. return null;
  2283. } else {
  2284. reqs[key] = [cb];
  2285. return makeres(key);
  2286. }
  2287. }
  2288. function makeres(key) {
  2289. return once(function RES() {
  2290. var cbs = reqs[key];
  2291. var len = cbs.length;
  2292. var args = slice(arguments);
  2293. try {
  2294. for (var i6 = 0; i6 < len; i6++) {
  2295. cbs[i6].apply(null, args);
  2296. }
  2297. } finally {
  2298. if (cbs.length > len) {
  2299. cbs.splice(0, len);
  2300. process.nextTick(function() {
  2301. RES.apply(null, args);
  2302. });
  2303. } else {
  2304. delete reqs[key];
  2305. }
  2306. }
  2307. });
  2308. }
  2309. function slice(args) {
  2310. var length = args.length;
  2311. var array2 = [];
  2312. for (var i6 = 0; i6 < length; i6++) array2[i6] = args[i6];
  2313. return array2;
  2314. }
  2315. }
  2316. });
  2317. // ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js
  2318. var require_glob = __commonJS({
  2319. "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js"(exports, module) {
  2320. "use strict";
  2321. module.exports = glob2;
  2322. var rp = require_fs();
  2323. var minimatch2 = require_minimatch();
  2324. var Minimatch2 = minimatch2.Minimatch;
  2325. var inherits = require_inherits();
  2326. var EE = __require("events").EventEmitter;
  2327. var path3 = __require("path");
  2328. var assert = __require("assert");
  2329. var isAbsolute = __require("path").isAbsolute;
  2330. var globSync = require_sync();
  2331. var common = require_common();
  2332. var setopts = common.setopts;
  2333. var ownProp = common.ownProp;
  2334. var inflight = require_inflight();
  2335. var util2 = __require("util");
  2336. var childrenIgnored = common.childrenIgnored;
  2337. var isIgnored = common.isIgnored;
  2338. var once = require_once();
  2339. function glob2(pattern, options, cb) {
  2340. if (typeof options === "function") cb = options, options = {};
  2341. if (!options) options = {};
  2342. if (options.sync) {
  2343. if (cb)
  2344. throw new TypeError("callback provided to sync glob");
  2345. return globSync(pattern, options);
  2346. }
  2347. return new Glob(pattern, options, cb);
  2348. }
  2349. glob2.sync = globSync;
  2350. var GlobSync = glob2.GlobSync = globSync.GlobSync;
  2351. glob2.glob = glob2;
  2352. function extend(origin, add) {
  2353. if (add === null || typeof add !== "object") {
  2354. return origin;
  2355. }
  2356. var keys = Object.keys(add);
  2357. var i6 = keys.length;
  2358. while (i6--) {
  2359. origin[keys[i6]] = add[keys[i6]];
  2360. }
  2361. return origin;
  2362. }
  2363. glob2.hasMagic = function(pattern, options_) {
  2364. var options = extend({}, options_);
  2365. options.noprocess = true;
  2366. var g5 = new Glob(pattern, options);
  2367. var set = g5.minimatch.set;
  2368. if (!pattern)
  2369. return false;
  2370. if (set.length > 1)
  2371. return true;
  2372. for (var j5 = 0; j5 < set[0].length; j5++) {
  2373. if (typeof set[0][j5] !== "string")
  2374. return true;
  2375. }
  2376. return false;
  2377. };
  2378. glob2.Glob = Glob;
  2379. inherits(Glob, EE);
  2380. function Glob(pattern, options, cb) {
  2381. if (typeof options === "function") {
  2382. cb = options;
  2383. options = null;
  2384. }
  2385. if (options && options.sync) {
  2386. if (cb)
  2387. throw new TypeError("callback provided to sync glob");
  2388. return new GlobSync(pattern, options);
  2389. }
  2390. if (!(this instanceof Glob))
  2391. return new Glob(pattern, options, cb);
  2392. setopts(this, pattern, options);
  2393. this._didRealPath = false;
  2394. var n5 = this.minimatch.set.length;
  2395. this.matches = new Array(n5);
  2396. if (typeof cb === "function") {
  2397. cb = once(cb);
  2398. this.on("error", cb);
  2399. this.on("end", function(matches) {
  2400. cb(null, matches);
  2401. });
  2402. }
  2403. var self2 = this;
  2404. this._processing = 0;
  2405. this._emitQueue = [];
  2406. this._processQueue = [];
  2407. this.paused = false;
  2408. if (this.noprocess)
  2409. return this;
  2410. if (n5 === 0)
  2411. return done();
  2412. var sync2 = true;
  2413. for (var i6 = 0; i6 < n5; i6++) {
  2414. this._process(this.minimatch.set[i6], i6, false, done);
  2415. }
  2416. sync2 = false;
  2417. function done() {
  2418. --self2._processing;
  2419. if (self2._processing <= 0) {
  2420. if (sync2) {
  2421. process.nextTick(function() {
  2422. self2._finish();
  2423. });
  2424. } else {
  2425. self2._finish();
  2426. }
  2427. }
  2428. }
  2429. }
  2430. Glob.prototype._finish = function() {
  2431. assert(this instanceof Glob);
  2432. if (this.aborted)
  2433. return;
  2434. if (this.realpath && !this._didRealpath)
  2435. return this._realpath();
  2436. common.finish(this);
  2437. this.emit("end", this.found);
  2438. };
  2439. Glob.prototype._realpath = function() {
  2440. if (this._didRealpath)
  2441. return;
  2442. this._didRealpath = true;
  2443. var n5 = this.matches.length;
  2444. if (n5 === 0)
  2445. return this._finish();
  2446. var self2 = this;
  2447. for (var i6 = 0; i6 < this.matches.length; i6++)
  2448. this._realpathSet(i6, next);
  2449. function next() {
  2450. if (--n5 === 0)
  2451. self2._finish();
  2452. }
  2453. };
  2454. Glob.prototype._realpathSet = function(index6, cb) {
  2455. var matchset = this.matches[index6];
  2456. if (!matchset)
  2457. return cb();
  2458. var found = Object.keys(matchset);
  2459. var self2 = this;
  2460. var n5 = found.length;
  2461. if (n5 === 0)
  2462. return cb();
  2463. var set = this.matches[index6] = /* @__PURE__ */ Object.create(null);
  2464. found.forEach(function(p5, i6) {
  2465. p5 = self2._makeAbs(p5);
  2466. rp.realpath(p5, self2.realpathCache, function(er, real) {
  2467. if (!er)
  2468. set[real] = true;
  2469. else if (er.syscall === "stat")
  2470. set[p5] = true;
  2471. else
  2472. self2.emit("error", er);
  2473. if (--n5 === 0) {
  2474. self2.matches[index6] = set;
  2475. cb();
  2476. }
  2477. });
  2478. });
  2479. };
  2480. Glob.prototype._mark = function(p5) {
  2481. return common.mark(this, p5);
  2482. };
  2483. Glob.prototype._makeAbs = function(f7) {
  2484. return common.makeAbs(this, f7);
  2485. };
  2486. Glob.prototype.abort = function() {
  2487. this.aborted = true;
  2488. this.emit("abort");
  2489. };
  2490. Glob.prototype.pause = function() {
  2491. if (!this.paused) {
  2492. this.paused = true;
  2493. this.emit("pause");
  2494. }
  2495. };
  2496. Glob.prototype.resume = function() {
  2497. if (this.paused) {
  2498. this.emit("resume");
  2499. this.paused = false;
  2500. if (this._emitQueue.length) {
  2501. var eq = this._emitQueue.slice(0);
  2502. this._emitQueue.length = 0;
  2503. for (var i6 = 0; i6 < eq.length; i6++) {
  2504. var e6 = eq[i6];
  2505. this._emitMatch(e6[0], e6[1]);
  2506. }
  2507. }
  2508. if (this._processQueue.length) {
  2509. var pq = this._processQueue.slice(0);
  2510. this._processQueue.length = 0;
  2511. for (var i6 = 0; i6 < pq.length; i6++) {
  2512. var p5 = pq[i6];
  2513. this._processing--;
  2514. this._process(p5[0], p5[1], p5[2], p5[3]);
  2515. }
  2516. }
  2517. }
  2518. };
  2519. Glob.prototype._process = function(pattern, index6, inGlobStar, cb) {
  2520. assert(this instanceof Glob);
  2521. assert(typeof cb === "function");
  2522. if (this.aborted)
  2523. return;
  2524. this._processing++;
  2525. if (this.paused) {
  2526. this._processQueue.push([pattern, index6, inGlobStar, cb]);
  2527. return;
  2528. }
  2529. var n5 = 0;
  2530. while (typeof pattern[n5] === "string") {
  2531. n5++;
  2532. }
  2533. var prefix2;
  2534. switch (n5) {
  2535. // if not, then this is rather simple
  2536. case pattern.length:
  2537. this._processSimple(pattern.join("/"), index6, cb);
  2538. return;
  2539. case 0:
  2540. prefix2 = null;
  2541. break;
  2542. default:
  2543. prefix2 = pattern.slice(0, n5).join("/");
  2544. break;
  2545. }
  2546. var remain = pattern.slice(n5);
  2547. var read;
  2548. if (prefix2 === null)
  2549. read = ".";
  2550. else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p5) {
  2551. return typeof p5 === "string" ? p5 : "[*]";
  2552. }).join("/"))) {
  2553. if (!prefix2 || !isAbsolute(prefix2))
  2554. prefix2 = "/" + prefix2;
  2555. read = prefix2;
  2556. } else
  2557. read = prefix2;
  2558. var abs = this._makeAbs(read);
  2559. if (childrenIgnored(this, read))
  2560. return cb();
  2561. var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
  2562. if (isGlobStar)
  2563. this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar, cb);
  2564. else
  2565. this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar, cb);
  2566. };
  2567. Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
  2568. var self2 = this;
  2569. this._readdir(abs, inGlobStar, function(er, entries) {
  2570. return self2._processReaddir2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
  2571. });
  2572. };
  2573. Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
  2574. if (!entries)
  2575. return cb();
  2576. var pn = remain[0];
  2577. var negate2 = !!this.minimatch.negate;
  2578. var rawGlob = pn._glob;
  2579. var dotOk = this.dot || rawGlob.charAt(0) === ".";
  2580. var matchedEntries = [];
  2581. for (var i6 = 0; i6 < entries.length; i6++) {
  2582. var e6 = entries[i6];
  2583. if (e6.charAt(0) !== "." || dotOk) {
  2584. var m6;
  2585. if (negate2 && !prefix2) {
  2586. m6 = !e6.match(pn);
  2587. } else {
  2588. m6 = e6.match(pn);
  2589. }
  2590. if (m6)
  2591. matchedEntries.push(e6);
  2592. }
  2593. }
  2594. var len = matchedEntries.length;
  2595. if (len === 0)
  2596. return cb();
  2597. if (remain.length === 1 && !this.mark && !this.stat) {
  2598. if (!this.matches[index6])
  2599. this.matches[index6] = /* @__PURE__ */ Object.create(null);
  2600. for (var i6 = 0; i6 < len; i6++) {
  2601. var e6 = matchedEntries[i6];
  2602. if (prefix2) {
  2603. if (prefix2 !== "/")
  2604. e6 = prefix2 + "/" + e6;
  2605. else
  2606. e6 = prefix2 + e6;
  2607. }
  2608. if (e6.charAt(0) === "/" && !this.nomount) {
  2609. e6 = path3.join(this.root, e6);
  2610. }
  2611. this._emitMatch(index6, e6);
  2612. }
  2613. return cb();
  2614. }
  2615. remain.shift();
  2616. for (var i6 = 0; i6 < len; i6++) {
  2617. var e6 = matchedEntries[i6];
  2618. var newPattern;
  2619. if (prefix2) {
  2620. if (prefix2 !== "/")
  2621. e6 = prefix2 + "/" + e6;
  2622. else
  2623. e6 = prefix2 + e6;
  2624. }
  2625. this._process([e6].concat(remain), index6, inGlobStar, cb);
  2626. }
  2627. cb();
  2628. };
  2629. Glob.prototype._emitMatch = function(index6, e6) {
  2630. if (this.aborted)
  2631. return;
  2632. if (isIgnored(this, e6))
  2633. return;
  2634. if (this.paused) {
  2635. this._emitQueue.push([index6, e6]);
  2636. return;
  2637. }
  2638. var abs = isAbsolute(e6) ? e6 : this._makeAbs(e6);
  2639. if (this.mark)
  2640. e6 = this._mark(e6);
  2641. if (this.absolute)
  2642. e6 = abs;
  2643. if (this.matches[index6][e6])
  2644. return;
  2645. if (this.nodir) {
  2646. var c5 = this.cache[abs];
  2647. if (c5 === "DIR" || Array.isArray(c5))
  2648. return;
  2649. }
  2650. this.matches[index6][e6] = true;
  2651. var st = this.statCache[abs];
  2652. if (st)
  2653. this.emit("stat", e6, st);
  2654. this.emit("match", e6);
  2655. };
  2656. Glob.prototype._readdirInGlobStar = function(abs, cb) {
  2657. if (this.aborted)
  2658. return;
  2659. if (this.follow)
  2660. return this._readdir(abs, false, cb);
  2661. var lstatkey = "lstat\0" + abs;
  2662. var self2 = this;
  2663. var lstatcb = inflight(lstatkey, lstatcb_);
  2664. if (lstatcb)
  2665. self2.fs.lstat(abs, lstatcb);
  2666. function lstatcb_(er, lstat) {
  2667. if (er && er.code === "ENOENT")
  2668. return cb();
  2669. var isSym = lstat && lstat.isSymbolicLink();
  2670. self2.symlinks[abs] = isSym;
  2671. if (!isSym && lstat && !lstat.isDirectory()) {
  2672. self2.cache[abs] = "FILE";
  2673. cb();
  2674. } else
  2675. self2._readdir(abs, false, cb);
  2676. }
  2677. };
  2678. Glob.prototype._readdir = function(abs, inGlobStar, cb) {
  2679. if (this.aborted)
  2680. return;
  2681. cb = inflight("readdir\0" + abs + "\0" + inGlobStar, cb);
  2682. if (!cb)
  2683. return;
  2684. if (inGlobStar && !ownProp(this.symlinks, abs))
  2685. return this._readdirInGlobStar(abs, cb);
  2686. if (ownProp(this.cache, abs)) {
  2687. var c5 = this.cache[abs];
  2688. if (!c5 || c5 === "FILE")
  2689. return cb();
  2690. if (Array.isArray(c5))
  2691. return cb(null, c5);
  2692. }
  2693. var self2 = this;
  2694. self2.fs.readdir(abs, readdirCb(this, abs, cb));
  2695. };
  2696. function readdirCb(self2, abs, cb) {
  2697. return function(er, entries) {
  2698. if (er)
  2699. self2._readdirError(abs, er, cb);
  2700. else
  2701. self2._readdirEntries(abs, entries, cb);
  2702. };
  2703. }
  2704. Glob.prototype._readdirEntries = function(abs, entries, cb) {
  2705. if (this.aborted)
  2706. return;
  2707. if (!this.mark && !this.stat) {
  2708. for (var i6 = 0; i6 < entries.length; i6++) {
  2709. var e6 = entries[i6];
  2710. if (abs === "/")
  2711. e6 = abs + e6;
  2712. else
  2713. e6 = abs + "/" + e6;
  2714. this.cache[e6] = true;
  2715. }
  2716. }
  2717. this.cache[abs] = entries;
  2718. return cb(null, entries);
  2719. };
  2720. Glob.prototype._readdirError = function(f7, er, cb) {
  2721. if (this.aborted)
  2722. return;
  2723. switch (er.code) {
  2724. case "ENOTSUP":
  2725. // https://github.com/isaacs/node-glob/issues/205
  2726. case "ENOTDIR":
  2727. var abs = this._makeAbs(f7);
  2728. this.cache[abs] = "FILE";
  2729. if (abs === this.cwdAbs) {
  2730. var error2 = new Error(er.code + " invalid cwd " + this.cwd);
  2731. error2.path = this.cwd;
  2732. error2.code = er.code;
  2733. this.emit("error", error2);
  2734. this.abort();
  2735. }
  2736. break;
  2737. case "ENOENT":
  2738. // not terribly unusual
  2739. case "ELOOP":
  2740. case "ENAMETOOLONG":
  2741. case "UNKNOWN":
  2742. this.cache[this._makeAbs(f7)] = false;
  2743. break;
  2744. default:
  2745. this.cache[this._makeAbs(f7)] = false;
  2746. if (this.strict) {
  2747. this.emit("error", er);
  2748. this.abort();
  2749. }
  2750. if (!this.silent)
  2751. console.error("glob error", er);
  2752. break;
  2753. }
  2754. return cb();
  2755. };
  2756. Glob.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
  2757. var self2 = this;
  2758. this._readdir(abs, inGlobStar, function(er, entries) {
  2759. self2._processGlobStar2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
  2760. });
  2761. };
  2762. Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
  2763. if (!entries)
  2764. return cb();
  2765. var remainWithoutGlobStar = remain.slice(1);
  2766. var gspref = prefix2 ? [prefix2] : [];
  2767. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  2768. this._process(noGlobStar, index6, false, cb);
  2769. var isSym = this.symlinks[abs];
  2770. var len = entries.length;
  2771. if (isSym && inGlobStar)
  2772. return cb();
  2773. for (var i6 = 0; i6 < len; i6++) {
  2774. var e6 = entries[i6];
  2775. if (e6.charAt(0) === "." && !this.dot)
  2776. continue;
  2777. var instead = gspref.concat(entries[i6], remainWithoutGlobStar);
  2778. this._process(instead, index6, true, cb);
  2779. var below = gspref.concat(entries[i6], remain);
  2780. this._process(below, index6, true, cb);
  2781. }
  2782. cb();
  2783. };
  2784. Glob.prototype._processSimple = function(prefix2, index6, cb) {
  2785. var self2 = this;
  2786. this._stat(prefix2, function(er, exists) {
  2787. self2._processSimple2(prefix2, index6, er, exists, cb);
  2788. });
  2789. };
  2790. Glob.prototype._processSimple2 = function(prefix2, index6, er, exists, cb) {
  2791. if (!this.matches[index6])
  2792. this.matches[index6] = /* @__PURE__ */ Object.create(null);
  2793. if (!exists)
  2794. return cb();
  2795. if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
  2796. var trail = /[\/\\]$/.test(prefix2);
  2797. if (prefix2.charAt(0) === "/") {
  2798. prefix2 = path3.join(this.root, prefix2);
  2799. } else {
  2800. prefix2 = path3.resolve(this.root, prefix2);
  2801. if (trail)
  2802. prefix2 += "/";
  2803. }
  2804. }
  2805. if (process.platform === "win32")
  2806. prefix2 = prefix2.replace(/\\/g, "/");
  2807. this._emitMatch(index6, prefix2);
  2808. cb();
  2809. };
  2810. Glob.prototype._stat = function(f7, cb) {
  2811. var abs = this._makeAbs(f7);
  2812. var needDir = f7.slice(-1) === "/";
  2813. if (f7.length > this.maxLength)
  2814. return cb();
  2815. if (!this.stat && ownProp(this.cache, abs)) {
  2816. var c5 = this.cache[abs];
  2817. if (Array.isArray(c5))
  2818. c5 = "DIR";
  2819. if (!needDir || c5 === "DIR")
  2820. return cb(null, c5);
  2821. if (needDir && c5 === "FILE")
  2822. return cb();
  2823. }
  2824. var exists;
  2825. var stat2 = this.statCache[abs];
  2826. if (stat2 !== void 0) {
  2827. if (stat2 === false)
  2828. return cb(null, stat2);
  2829. else {
  2830. var type = stat2.isDirectory() ? "DIR" : "FILE";
  2831. if (needDir && type === "FILE")
  2832. return cb();
  2833. else
  2834. return cb(null, type, stat2);
  2835. }
  2836. }
  2837. var self2 = this;
  2838. var statcb = inflight("stat\0" + abs, lstatcb_);
  2839. if (statcb)
  2840. self2.fs.lstat(abs, statcb);
  2841. function lstatcb_(er, lstat) {
  2842. if (lstat && lstat.isSymbolicLink()) {
  2843. return self2.fs.stat(abs, function(er2, stat3) {
  2844. if (er2)
  2845. self2._stat2(f7, abs, null, lstat, cb);
  2846. else
  2847. self2._stat2(f7, abs, er2, stat3, cb);
  2848. });
  2849. } else {
  2850. self2._stat2(f7, abs, er, lstat, cb);
  2851. }
  2852. }
  2853. };
  2854. Glob.prototype._stat2 = function(f7, abs, er, stat2, cb) {
  2855. if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
  2856. this.statCache[abs] = false;
  2857. return cb();
  2858. }
  2859. var needDir = f7.slice(-1) === "/";
  2860. this.statCache[abs] = stat2;
  2861. if (abs.slice(-1) === "/" && stat2 && !stat2.isDirectory())
  2862. return cb(null, false, stat2);
  2863. var c5 = true;
  2864. if (stat2)
  2865. c5 = stat2.isDirectory() ? "DIR" : "FILE";
  2866. this.cache[abs] = this.cache[abs] || c5;
  2867. if (needDir && c5 === "FILE")
  2868. return cb();
  2869. return cb(null, c5, stat2);
  2870. };
  2871. }
  2872. });
  2873. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/readline.js
  2874. var require_readline = __commonJS({
  2875. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/readline.js"(exports) {
  2876. "use strict";
  2877. var __importDefault = exports && exports.__importDefault || function(mod) {
  2878. return mod && mod.__esModule ? mod : { "default": mod };
  2879. };
  2880. Object.defineProperty(exports, "__esModule", { value: true });
  2881. exports.createClosable = exports.stdout = exports.stdin = void 0;
  2882. var readline_1 = __importDefault(__require("readline"));
  2883. exports.stdin = process.stdin;
  2884. exports.stdout = process.stdout;
  2885. readline_1.default.emitKeypressEvents(exports.stdin);
  2886. var createClosable = () => {
  2887. return readline_1.default.createInterface({
  2888. input: exports.stdin,
  2889. escapeCodeTimeout: 50
  2890. });
  2891. };
  2892. exports.createClosable = createClosable;
  2893. }
  2894. });
  2895. // ../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
  2896. var require_src = __commonJS({
  2897. "../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
  2898. "use strict";
  2899. var ESC = "\x1B";
  2900. var CSI = `${ESC}[`;
  2901. var beep = "\x07";
  2902. var cursor = {
  2903. to(x5, y2) {
  2904. if (!y2) return `${CSI}${x5 + 1}G`;
  2905. return `${CSI}${y2 + 1};${x5 + 1}H`;
  2906. },
  2907. move(x5, y2) {
  2908. let ret = "";
  2909. if (x5 < 0) ret += `${CSI}${-x5}D`;
  2910. else if (x5 > 0) ret += `${CSI}${x5}C`;
  2911. if (y2 < 0) ret += `${CSI}${-y2}A`;
  2912. else if (y2 > 0) ret += `${CSI}${y2}B`;
  2913. return ret;
  2914. },
  2915. up: (count = 1) => `${CSI}${count}A`,
  2916. down: (count = 1) => `${CSI}${count}B`,
  2917. forward: (count = 1) => `${CSI}${count}C`,
  2918. backward: (count = 1) => `${CSI}${count}D`,
  2919. nextLine: (count = 1) => `${CSI}E`.repeat(count),
  2920. prevLine: (count = 1) => `${CSI}F`.repeat(count),
  2921. left: `${CSI}G`,
  2922. hide: `${CSI}?25l`,
  2923. show: `${CSI}?25h`,
  2924. save: `${ESC}7`,
  2925. restore: `${ESC}8`
  2926. };
  2927. var scroll = {
  2928. up: (count = 1) => `${CSI}S`.repeat(count),
  2929. down: (count = 1) => `${CSI}T`.repeat(count)
  2930. };
  2931. var erase = {
  2932. screen: `${CSI}2J`,
  2933. up: (count = 1) => `${CSI}1J`.repeat(count),
  2934. down: (count = 1) => `${CSI}J`.repeat(count),
  2935. line: `${CSI}2K`,
  2936. lineEnd: `${CSI}K`,
  2937. lineStart: `${CSI}1K`,
  2938. lines(count) {
  2939. let clear = "";
  2940. for (let i6 = 0; i6 < count; i6++)
  2941. clear += this.line + (i6 < count - 1 ? cursor.up() : "");
  2942. if (count)
  2943. clear += cursor.left;
  2944. return clear;
  2945. }
  2946. };
  2947. module.exports = { cursor, scroll, erase, beep };
  2948. }
  2949. });
  2950. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/utils.js
  2951. var require_utils = __commonJS({
  2952. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/utils.js"(exports) {
  2953. "use strict";
  2954. Object.defineProperty(exports, "__esModule", { value: true });
  2955. exports.clear = exports.stringWidth = exports.fallbackStringWidth = exports.stripAnsi = exports.strip = void 0;
  2956. var sisteransi_1 = require_src();
  2957. var strip = (str) => {
  2958. const pattern = [
  2959. "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
  2960. "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
  2961. ].join("|");
  2962. const RGX = new RegExp(pattern, "g");
  2963. return typeof str === "string" ? str.replace(RGX, "") : str;
  2964. };
  2965. exports.strip = strip;
  2966. var stripAnsi = (str) => {
  2967. if (typeof Bun !== "undefined" && Bun.stripANSI) {
  2968. return Bun.stripANSI(str);
  2969. }
  2970. return (0, exports.strip)(str);
  2971. };
  2972. exports.stripAnsi = stripAnsi;
  2973. var fallbackStringWidth = (str) => {
  2974. let len = 0;
  2975. const stripped = (0, exports.stripAnsi)(str);
  2976. for (const _3 of stripped)
  2977. len++;
  2978. return len;
  2979. };
  2980. exports.fallbackStringWidth = fallbackStringWidth;
  2981. var stringWidth = (str) => {
  2982. if (typeof Bun !== "undefined" && Bun.stringWidth)
  2983. return Bun.stringWidth(str);
  2984. return (0, exports.fallbackStringWidth)(str);
  2985. };
  2986. exports.stringWidth = stringWidth;
  2987. var clear = function(prompt, perLine) {
  2988. if (!perLine)
  2989. return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
  2990. let rows = 0;
  2991. const lines = prompt.split(/\r?\n/);
  2992. for (let line of lines) {
  2993. rows += 1 + Math.floor(Math.max((0, exports.stringWidth)(line) - 1, 0) / perLine);
  2994. }
  2995. return sisteransi_1.erase.lines(rows);
  2996. };
  2997. exports.clear = clear;
  2998. }
  2999. });
  3000. // ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
  3001. var require_lodash = __commonJS({
  3002. "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports, module) {
  3003. "use strict";
  3004. var FUNC_ERROR_TEXT = "Expected a function";
  3005. var NAN = 0 / 0;
  3006. var symbolTag = "[object Symbol]";
  3007. var reTrim = /^\s+|\s+$/g;
  3008. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  3009. var reIsBinary = /^0b[01]+$/i;
  3010. var reIsOctal = /^0o[0-7]+$/i;
  3011. var freeParseInt = parseInt;
  3012. var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
  3013. var freeSelf = typeof self == "object" && self && self.Object === Object && self;
  3014. var root = freeGlobal || freeSelf || Function("return this")();
  3015. var objectProto = Object.prototype;
  3016. var objectToString = objectProto.toString;
  3017. var nativeMax = Math.max;
  3018. var nativeMin = Math.min;
  3019. var now = function() {
  3020. return root.Date.now();
  3021. };
  3022. function debounce(func, wait, options) {
  3023. var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
  3024. if (typeof func != "function") {
  3025. throw new TypeError(FUNC_ERROR_TEXT);
  3026. }
  3027. wait = toNumber(wait) || 0;
  3028. if (isObject(options)) {
  3029. leading = !!options.leading;
  3030. maxing = "maxWait" in options;
  3031. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  3032. trailing = "trailing" in options ? !!options.trailing : trailing;
  3033. }
  3034. function invokeFunc(time) {
  3035. var args = lastArgs, thisArg = lastThis;
  3036. lastArgs = lastThis = void 0;
  3037. lastInvokeTime = time;
  3038. result = func.apply(thisArg, args);
  3039. return result;
  3040. }
  3041. function leadingEdge(time) {
  3042. lastInvokeTime = time;
  3043. timerId = setTimeout(timerExpired, wait);
  3044. return leading ? invokeFunc(time) : result;
  3045. }
  3046. function remainingWait(time) {
  3047. var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
  3048. return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
  3049. }
  3050. function shouldInvoke(time) {
  3051. var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
  3052. return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
  3053. }
  3054. function timerExpired() {
  3055. var time = now();
  3056. if (shouldInvoke(time)) {
  3057. return trailingEdge(time);
  3058. }
  3059. timerId = setTimeout(timerExpired, remainingWait(time));
  3060. }
  3061. function trailingEdge(time) {
  3062. timerId = void 0;
  3063. if (trailing && lastArgs) {
  3064. return invokeFunc(time);
  3065. }
  3066. lastArgs = lastThis = void 0;
  3067. return result;
  3068. }
  3069. function cancel() {
  3070. if (timerId !== void 0) {
  3071. clearTimeout(timerId);
  3072. }
  3073. lastInvokeTime = 0;
  3074. lastArgs = lastCallTime = lastThis = timerId = void 0;
  3075. }
  3076. function flush2() {
  3077. return timerId === void 0 ? result : trailingEdge(now());
  3078. }
  3079. function debounced() {
  3080. var time = now(), isInvoking = shouldInvoke(time);
  3081. lastArgs = arguments;
  3082. lastThis = this;
  3083. lastCallTime = time;
  3084. if (isInvoking) {
  3085. if (timerId === void 0) {
  3086. return leadingEdge(lastCallTime);
  3087. }
  3088. if (maxing) {
  3089. timerId = setTimeout(timerExpired, wait);
  3090. return invokeFunc(lastCallTime);
  3091. }
  3092. }
  3093. if (timerId === void 0) {
  3094. timerId = setTimeout(timerExpired, wait);
  3095. }
  3096. return result;
  3097. }
  3098. debounced.cancel = cancel;
  3099. debounced.flush = flush2;
  3100. return debounced;
  3101. }
  3102. function throttle(func, wait, options) {
  3103. var leading = true, trailing = true;
  3104. if (typeof func != "function") {
  3105. throw new TypeError(FUNC_ERROR_TEXT);
  3106. }
  3107. if (isObject(options)) {
  3108. leading = "leading" in options ? !!options.leading : leading;
  3109. trailing = "trailing" in options ? !!options.trailing : trailing;
  3110. }
  3111. return debounce(func, wait, {
  3112. "leading": leading,
  3113. "maxWait": wait,
  3114. "trailing": trailing
  3115. });
  3116. }
  3117. function isObject(value) {
  3118. var type = typeof value;
  3119. return !!value && (type == "object" || type == "function");
  3120. }
  3121. function isObjectLike(value) {
  3122. return !!value && typeof value == "object";
  3123. }
  3124. function isSymbol(value) {
  3125. return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
  3126. }
  3127. function toNumber(value) {
  3128. if (typeof value == "number") {
  3129. return value;
  3130. }
  3131. if (isSymbol(value)) {
  3132. return NAN;
  3133. }
  3134. if (isObject(value)) {
  3135. var other = typeof value.valueOf == "function" ? value.valueOf() : value;
  3136. value = isObject(other) ? other + "" : other;
  3137. }
  3138. if (typeof value != "string") {
  3139. return value === 0 ? value : +value;
  3140. }
  3141. value = value.replace(reTrim, "");
  3142. var isBinary = reIsBinary.test(value);
  3143. return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
  3144. }
  3145. module.exports = throttle;
  3146. }
  3147. });
  3148. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/index.js
  3149. var require_hanji = __commonJS({
  3150. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/index.js"(exports) {
  3151. "use strict";
  3152. var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
  3153. function adopt(value) {
  3154. return value instanceof P ? value : new P(function(resolve) {
  3155. resolve(value);
  3156. });
  3157. }
  3158. return new (P || (P = Promise))(function(resolve, reject) {
  3159. function fulfilled(value) {
  3160. try {
  3161. step(generator.next(value));
  3162. } catch (e6) {
  3163. reject(e6);
  3164. }
  3165. }
  3166. function rejected(value) {
  3167. try {
  3168. step(generator["throw"](value));
  3169. } catch (e6) {
  3170. reject(e6);
  3171. }
  3172. }
  3173. function step(result) {
  3174. result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
  3175. }
  3176. step((generator = generator.apply(thisArg, _arguments || [])).next());
  3177. });
  3178. };
  3179. var __importDefault = exports && exports.__importDefault || function(mod) {
  3180. return mod && mod.__esModule ? mod : { "default": mod };
  3181. };
  3182. Object.defineProperty(exports, "__esModule", { value: true });
  3183. exports.TaskTerminal = exports.TaskView = exports.Terminal = exports.deferred = exports.SelectState = exports.Prompt = void 0;
  3184. exports.render = render7;
  3185. exports.renderWithTask = renderWithTask5;
  3186. exports.onTerminate = onTerminate;
  3187. var readline_1 = require_readline();
  3188. var sisteransi_1 = require_src();
  3189. var utils_1 = require_utils();
  3190. var lodash_throttle_1 = __importDefault(require_lodash());
  3191. var Prompt3 = class {
  3192. constructor() {
  3193. this.attachCallbacks = [];
  3194. this.detachCallbacks = [];
  3195. this.inputCallbacks = [];
  3196. }
  3197. requestLayout() {
  3198. this.terminal.requestLayout();
  3199. }
  3200. on(type, callback) {
  3201. if (type === "attach") {
  3202. this.attachCallbacks.push(callback);
  3203. } else if (type === "detach") {
  3204. this.detachCallbacks.push(callback);
  3205. } else if (type === "input") {
  3206. this.inputCallbacks.push(callback);
  3207. }
  3208. }
  3209. attach(terminal) {
  3210. this.terminal = terminal;
  3211. this.attachCallbacks.forEach((it) => it(terminal));
  3212. }
  3213. detach(terminal) {
  3214. this.detachCallbacks.forEach((it) => it(terminal));
  3215. this.terminal = void 0;
  3216. }
  3217. input(str, key) {
  3218. this.inputCallbacks.forEach((it) => it(str, key));
  3219. }
  3220. };
  3221. exports.Prompt = Prompt3;
  3222. var SelectState3 = class {
  3223. constructor(items) {
  3224. this.items = items;
  3225. this.selectedIdx = 0;
  3226. }
  3227. bind(prompt) {
  3228. prompt.on("input", (str, key) => {
  3229. const invalidate = this.consume(str, key);
  3230. if (invalidate)
  3231. prompt.requestLayout();
  3232. });
  3233. }
  3234. consume(str, key) {
  3235. if (!key)
  3236. return false;
  3237. if (key.name === "down") {
  3238. this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
  3239. return true;
  3240. }
  3241. if (key.name === "up") {
  3242. this.selectedIdx -= 1;
  3243. this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
  3244. return true;
  3245. }
  3246. return false;
  3247. }
  3248. };
  3249. exports.SelectState = SelectState3;
  3250. var deferred = () => {
  3251. let resolve;
  3252. let reject;
  3253. const promise = new Promise((res, rej) => {
  3254. resolve = res;
  3255. reject = rej;
  3256. });
  3257. return {
  3258. resolve,
  3259. reject,
  3260. promise
  3261. };
  3262. };
  3263. exports.deferred = deferred;
  3264. var Terminal = class {
  3265. constructor(view5, stdin, stdout, closable) {
  3266. this.view = view5;
  3267. this.stdin = stdin;
  3268. this.stdout = stdout;
  3269. this.closable = closable;
  3270. this.text = "";
  3271. this.status = "idle";
  3272. if (this.stdin.isTTY)
  3273. this.stdin.setRawMode(true);
  3274. const keypress = (str, key) => {
  3275. if (key.name === "c" && key.ctrl === true) {
  3276. this.requestLayout();
  3277. this.view.detach(this);
  3278. this.tearDown(keypress);
  3279. if (terminateHandler) {
  3280. terminateHandler(this.stdin, this.stdout);
  3281. return;
  3282. }
  3283. this.stdout.write(`
  3284. ^C
  3285. `);
  3286. process.exit(1);
  3287. }
  3288. if (key.name === "escape") {
  3289. this.status = "aborted";
  3290. this.requestLayout();
  3291. this.view.detach(this);
  3292. this.tearDown(keypress);
  3293. this.resolve({ status: "aborted", data: void 0 });
  3294. return;
  3295. }
  3296. if (key.name === "return") {
  3297. this.status = "submitted";
  3298. this.requestLayout();
  3299. this.view.detach(this);
  3300. this.tearDown(keypress);
  3301. this.resolve({ status: "submitted", data: this.view.result() });
  3302. return;
  3303. }
  3304. view5.input(str, key);
  3305. };
  3306. this.stdin.on("keypress", keypress);
  3307. this.view.attach(this);
  3308. const { resolve, promise } = (0, exports.deferred)();
  3309. this.resolve = resolve;
  3310. this.promise = promise;
  3311. this.renderFunc = (0, lodash_throttle_1.default)((str) => {
  3312. this.stdout.write(str);
  3313. });
  3314. }
  3315. tearDown(keypress) {
  3316. this.stdout.write(sisteransi_1.cursor.show);
  3317. this.stdin.removeListener("keypress", keypress);
  3318. if (this.stdin.isTTY)
  3319. this.stdin.setRawMode(false);
  3320. this.closable.close();
  3321. }
  3322. result() {
  3323. return this.promise;
  3324. }
  3325. toggleCursor(state2) {
  3326. if (state2 === "hide") {
  3327. this.stdout.write(sisteransi_1.cursor.hide);
  3328. } else {
  3329. this.stdout.write(sisteransi_1.cursor.show);
  3330. }
  3331. }
  3332. requestLayout() {
  3333. const string = this.view.render(this.status);
  3334. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  3335. this.text = string;
  3336. this.renderFunc(`${clearPrefix}${string}`);
  3337. }
  3338. };
  3339. exports.Terminal = Terminal;
  3340. var TaskView2 = class {
  3341. constructor() {
  3342. this.attachCallbacks = [];
  3343. this.detachCallbacks = [];
  3344. }
  3345. requestLayout() {
  3346. this.terminal.requestLayout();
  3347. }
  3348. attach(terminal) {
  3349. this.terminal = terminal;
  3350. this.attachCallbacks.forEach((it) => it(terminal));
  3351. }
  3352. detach(terminal) {
  3353. this.detachCallbacks.forEach((it) => it(terminal));
  3354. this.terminal = void 0;
  3355. }
  3356. on(type, callback) {
  3357. if (type === "attach") {
  3358. this.attachCallbacks.push(callback);
  3359. } else if (type === "detach") {
  3360. this.detachCallbacks.push(callback);
  3361. }
  3362. }
  3363. };
  3364. exports.TaskView = TaskView2;
  3365. var TaskTerminal = class {
  3366. constructor(view5, stdout) {
  3367. this.view = view5;
  3368. this.stdout = stdout;
  3369. this.text = "";
  3370. this.view.attach(this);
  3371. }
  3372. requestLayout() {
  3373. const string = this.view.render("pending");
  3374. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  3375. this.text = string;
  3376. this.stdout.write(`${clearPrefix}${string}`);
  3377. }
  3378. clear() {
  3379. const string = this.view.render("done");
  3380. this.view.detach(this);
  3381. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  3382. this.stdout.write(`${clearPrefix}${string}`);
  3383. }
  3384. reject(err2) {
  3385. const string = this.view.render("rejected", err2);
  3386. this.view.detach(this);
  3387. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  3388. this.stdout.write(`${clearPrefix}${string}`);
  3389. }
  3390. };
  3391. exports.TaskTerminal = TaskTerminal;
  3392. function render7(view5) {
  3393. if (typeof view5 === "string") {
  3394. process.stdout.write(`${view5}
  3395. `);
  3396. return;
  3397. }
  3398. if (!process.stdin.isTTY || !process.stdout.isTTY) {
  3399. return Promise.reject(new Error("Interactive prompts require a TTY terminal (process.stdin.isTTY or process.stdout.isTTY is false). This can happen when running in CI, piped input, or non-interactive shells."));
  3400. }
  3401. const closable = (0, readline_1.createClosable)();
  3402. const terminal = new Terminal(view5, readline_1.stdin, readline_1.stdout, closable);
  3403. terminal.requestLayout();
  3404. return terminal.result();
  3405. }
  3406. function renderWithTask5(view5, task) {
  3407. return __awaiter(this, void 0, void 0, function* () {
  3408. const terminal = new TaskTerminal(view5, process.stdout);
  3409. terminal.requestLayout();
  3410. try {
  3411. const result = yield task;
  3412. terminal.clear();
  3413. return result;
  3414. } catch (err2) {
  3415. terminal.reject(err2);
  3416. process.exit(1);
  3417. }
  3418. });
  3419. }
  3420. var terminateHandler;
  3421. function onTerminate(callback) {
  3422. terminateHandler = callback;
  3423. }
  3424. }
  3425. });
  3426. // src/global.ts
  3427. function assertUnreachable(x5) {
  3428. throw new Error("Didn't expect to get here");
  3429. }
  3430. var originUUID, snapshotVersion, mapValues, mapKeys, mapEntries, customMapEntries;
  3431. var init_global = __esm({
  3432. "src/global.ts"() {
  3433. "use strict";
  3434. originUUID = "00000000-0000-0000-0000-000000000000";
  3435. snapshotVersion = "7";
  3436. mapValues = (obj, map2) => {
  3437. const result = Object.keys(obj).reduce(function(result2, key) {
  3438. result2[key] = map2(obj[key]);
  3439. return result2;
  3440. }, {});
  3441. return result;
  3442. };
  3443. mapKeys = (obj, map2) => {
  3444. const result = Object.fromEntries(
  3445. Object.entries(obj).map(([key, val2]) => {
  3446. const newKey = map2(key, val2);
  3447. return [newKey, val2];
  3448. })
  3449. );
  3450. return result;
  3451. };
  3452. mapEntries = (obj, map2) => {
  3453. const result = Object.fromEntries(
  3454. Object.entries(obj).map(([key, val2]) => {
  3455. const [newKey, newVal] = map2(key, val2);
  3456. return [newKey, newVal];
  3457. })
  3458. );
  3459. return result;
  3460. };
  3461. customMapEntries = (obj, map2) => {
  3462. const result = Object.fromEntries(
  3463. Object.entries(obj).map(([key, val2]) => {
  3464. const [newKey, newVal] = map2(key, val2);
  3465. return [newKey, newVal];
  3466. })
  3467. );
  3468. return result;
  3469. };
  3470. }
  3471. });
  3472. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js
  3473. var util, objectUtil, ZodParsedType, getParsedType;
  3474. var init_util = __esm({
  3475. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js"() {
  3476. "use strict";
  3477. (function(util2) {
  3478. util2.assertEqual = (_3) => {
  3479. };
  3480. function assertIs(_arg) {
  3481. }
  3482. util2.assertIs = assertIs;
  3483. function assertNever(_x) {
  3484. throw new Error();
  3485. }
  3486. util2.assertNever = assertNever;
  3487. util2.arrayToEnum = (items) => {
  3488. const obj = {};
  3489. for (const item of items) {
  3490. obj[item] = item;
  3491. }
  3492. return obj;
  3493. };
  3494. util2.getValidEnumValues = (obj) => {
  3495. const validKeys = util2.objectKeys(obj).filter((k5) => typeof obj[obj[k5]] !== "number");
  3496. const filtered = {};
  3497. for (const k5 of validKeys) {
  3498. filtered[k5] = obj[k5];
  3499. }
  3500. return util2.objectValues(filtered);
  3501. };
  3502. util2.objectValues = (obj) => {
  3503. return util2.objectKeys(obj).map(function(e6) {
  3504. return obj[e6];
  3505. });
  3506. };
  3507. util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
  3508. const keys = [];
  3509. for (const key in object) {
  3510. if (Object.prototype.hasOwnProperty.call(object, key)) {
  3511. keys.push(key);
  3512. }
  3513. }
  3514. return keys;
  3515. };
  3516. util2.find = (arr, checker) => {
  3517. for (const item of arr) {
  3518. if (checker(item))
  3519. return item;
  3520. }
  3521. return void 0;
  3522. };
  3523. util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2;
  3524. function joinValues(array2, separator = " | ") {
  3525. return array2.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
  3526. }
  3527. util2.joinValues = joinValues;
  3528. util2.jsonStringifyReplacer = (_3, value) => {
  3529. if (typeof value === "bigint") {
  3530. return value.toString();
  3531. }
  3532. return value;
  3533. };
  3534. })(util || (util = {}));
  3535. (function(objectUtil2) {
  3536. objectUtil2.mergeShapes = (first, second) => {
  3537. return {
  3538. ...first,
  3539. ...second
  3540. // second overwrites first
  3541. };
  3542. };
  3543. })(objectUtil || (objectUtil = {}));
  3544. ZodParsedType = util.arrayToEnum([
  3545. "string",
  3546. "nan",
  3547. "number",
  3548. "integer",
  3549. "float",
  3550. "boolean",
  3551. "date",
  3552. "bigint",
  3553. "symbol",
  3554. "function",
  3555. "undefined",
  3556. "null",
  3557. "array",
  3558. "object",
  3559. "unknown",
  3560. "promise",
  3561. "void",
  3562. "never",
  3563. "map",
  3564. "set"
  3565. ]);
  3566. getParsedType = (data) => {
  3567. const t6 = typeof data;
  3568. switch (t6) {
  3569. case "undefined":
  3570. return ZodParsedType.undefined;
  3571. case "string":
  3572. return ZodParsedType.string;
  3573. case "number":
  3574. return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
  3575. case "boolean":
  3576. return ZodParsedType.boolean;
  3577. case "function":
  3578. return ZodParsedType.function;
  3579. case "bigint":
  3580. return ZodParsedType.bigint;
  3581. case "symbol":
  3582. return ZodParsedType.symbol;
  3583. case "object":
  3584. if (Array.isArray(data)) {
  3585. return ZodParsedType.array;
  3586. }
  3587. if (data === null) {
  3588. return ZodParsedType.null;
  3589. }
  3590. if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
  3591. return ZodParsedType.promise;
  3592. }
  3593. if (typeof Map !== "undefined" && data instanceof Map) {
  3594. return ZodParsedType.map;
  3595. }
  3596. if (typeof Set !== "undefined" && data instanceof Set) {
  3597. return ZodParsedType.set;
  3598. }
  3599. if (typeof Date !== "undefined" && data instanceof Date) {
  3600. return ZodParsedType.date;
  3601. }
  3602. return ZodParsedType.object;
  3603. default:
  3604. return ZodParsedType.unknown;
  3605. }
  3606. };
  3607. }
  3608. });
  3609. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js
  3610. var ZodIssueCode, quotelessJson, ZodError;
  3611. var init_ZodError = __esm({
  3612. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js"() {
  3613. "use strict";
  3614. init_util();
  3615. ZodIssueCode = util.arrayToEnum([
  3616. "invalid_type",
  3617. "invalid_literal",
  3618. "custom",
  3619. "invalid_union",
  3620. "invalid_union_discriminator",
  3621. "invalid_enum_value",
  3622. "unrecognized_keys",
  3623. "invalid_arguments",
  3624. "invalid_return_type",
  3625. "invalid_date",
  3626. "invalid_string",
  3627. "too_small",
  3628. "too_big",
  3629. "invalid_intersection_types",
  3630. "not_multiple_of",
  3631. "not_finite"
  3632. ]);
  3633. quotelessJson = (obj) => {
  3634. const json = JSON.stringify(obj, null, 2);
  3635. return json.replace(/"([^"]+)":/g, "$1:");
  3636. };
  3637. ZodError = class _ZodError extends Error {
  3638. get errors() {
  3639. return this.issues;
  3640. }
  3641. constructor(issues) {
  3642. super();
  3643. this.issues = [];
  3644. this.addIssue = (sub) => {
  3645. this.issues = [...this.issues, sub];
  3646. };
  3647. this.addIssues = (subs = []) => {
  3648. this.issues = [...this.issues, ...subs];
  3649. };
  3650. const actualProto = new.target.prototype;
  3651. if (Object.setPrototypeOf) {
  3652. Object.setPrototypeOf(this, actualProto);
  3653. } else {
  3654. this.__proto__ = actualProto;
  3655. }
  3656. this.name = "ZodError";
  3657. this.issues = issues;
  3658. }
  3659. format(_mapper) {
  3660. const mapper = _mapper || function(issue) {
  3661. return issue.message;
  3662. };
  3663. const fieldErrors = { _errors: [] };
  3664. const processError = (error2) => {
  3665. for (const issue of error2.issues) {
  3666. if (issue.code === "invalid_union") {
  3667. issue.unionErrors.map(processError);
  3668. } else if (issue.code === "invalid_return_type") {
  3669. processError(issue.returnTypeError);
  3670. } else if (issue.code === "invalid_arguments") {
  3671. processError(issue.argumentsError);
  3672. } else if (issue.path.length === 0) {
  3673. fieldErrors._errors.push(mapper(issue));
  3674. } else {
  3675. let curr = fieldErrors;
  3676. let i6 = 0;
  3677. while (i6 < issue.path.length) {
  3678. const el = issue.path[i6];
  3679. const terminal = i6 === issue.path.length - 1;
  3680. if (!terminal) {
  3681. curr[el] = curr[el] || { _errors: [] };
  3682. } else {
  3683. curr[el] = curr[el] || { _errors: [] };
  3684. curr[el]._errors.push(mapper(issue));
  3685. }
  3686. curr = curr[el];
  3687. i6++;
  3688. }
  3689. }
  3690. }
  3691. };
  3692. processError(this);
  3693. return fieldErrors;
  3694. }
  3695. static assert(value) {
  3696. if (!(value instanceof _ZodError)) {
  3697. throw new Error(`Not a ZodError: ${value}`);
  3698. }
  3699. }
  3700. toString() {
  3701. return this.message;
  3702. }
  3703. get message() {
  3704. return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  3705. }
  3706. get isEmpty() {
  3707. return this.issues.length === 0;
  3708. }
  3709. flatten(mapper = (issue) => issue.message) {
  3710. const fieldErrors = {};
  3711. const formErrors = [];
  3712. for (const sub of this.issues) {
  3713. if (sub.path.length > 0) {
  3714. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
  3715. fieldErrors[sub.path[0]].push(mapper(sub));
  3716. } else {
  3717. formErrors.push(mapper(sub));
  3718. }
  3719. }
  3720. return { formErrors, fieldErrors };
  3721. }
  3722. get formErrors() {
  3723. return this.flatten();
  3724. }
  3725. };
  3726. ZodError.create = (issues) => {
  3727. const error2 = new ZodError(issues);
  3728. return error2;
  3729. };
  3730. }
  3731. });
  3732. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js
  3733. var errorMap, en_default;
  3734. var init_en = __esm({
  3735. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js"() {
  3736. "use strict";
  3737. init_ZodError();
  3738. init_util();
  3739. errorMap = (issue, _ctx) => {
  3740. let message;
  3741. switch (issue.code) {
  3742. case ZodIssueCode.invalid_type:
  3743. if (issue.received === ZodParsedType.undefined) {
  3744. message = "Required";
  3745. } else {
  3746. message = `Expected ${issue.expected}, received ${issue.received}`;
  3747. }
  3748. break;
  3749. case ZodIssueCode.invalid_literal:
  3750. message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
  3751. break;
  3752. case ZodIssueCode.unrecognized_keys:
  3753. message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
  3754. break;
  3755. case ZodIssueCode.invalid_union:
  3756. message = `Invalid input`;
  3757. break;
  3758. case ZodIssueCode.invalid_union_discriminator:
  3759. message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
  3760. break;
  3761. case ZodIssueCode.invalid_enum_value:
  3762. message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
  3763. break;
  3764. case ZodIssueCode.invalid_arguments:
  3765. message = `Invalid function arguments`;
  3766. break;
  3767. case ZodIssueCode.invalid_return_type:
  3768. message = `Invalid function return type`;
  3769. break;
  3770. case ZodIssueCode.invalid_date:
  3771. message = `Invalid date`;
  3772. break;
  3773. case ZodIssueCode.invalid_string:
  3774. if (typeof issue.validation === "object") {
  3775. if ("includes" in issue.validation) {
  3776. message = `Invalid input: must include "${issue.validation.includes}"`;
  3777. if (typeof issue.validation.position === "number") {
  3778. message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
  3779. }
  3780. } else if ("startsWith" in issue.validation) {
  3781. message = `Invalid input: must start with "${issue.validation.startsWith}"`;
  3782. } else if ("endsWith" in issue.validation) {
  3783. message = `Invalid input: must end with "${issue.validation.endsWith}"`;
  3784. } else {
  3785. util.assertNever(issue.validation);
  3786. }
  3787. } else if (issue.validation !== "regex") {
  3788. message = `Invalid ${issue.validation}`;
  3789. } else {
  3790. message = "Invalid";
  3791. }
  3792. break;
  3793. case ZodIssueCode.too_small:
  3794. if (issue.type === "array")
  3795. message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
  3796. else if (issue.type === "string")
  3797. message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
  3798. else if (issue.type === "number")
  3799. message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
  3800. else if (issue.type === "date")
  3801. message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
  3802. else
  3803. message = "Invalid input";
  3804. break;
  3805. case ZodIssueCode.too_big:
  3806. if (issue.type === "array")
  3807. message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
  3808. else if (issue.type === "string")
  3809. message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
  3810. else if (issue.type === "number")
  3811. message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
  3812. else if (issue.type === "bigint")
  3813. message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
  3814. else if (issue.type === "date")
  3815. message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
  3816. else
  3817. message = "Invalid input";
  3818. break;
  3819. case ZodIssueCode.custom:
  3820. message = `Invalid input`;
  3821. break;
  3822. case ZodIssueCode.invalid_intersection_types:
  3823. message = `Intersection results could not be merged`;
  3824. break;
  3825. case ZodIssueCode.not_multiple_of:
  3826. message = `Number must be a multiple of ${issue.multipleOf}`;
  3827. break;
  3828. case ZodIssueCode.not_finite:
  3829. message = "Number must be finite";
  3830. break;
  3831. default:
  3832. message = _ctx.defaultError;
  3833. util.assertNever(issue);
  3834. }
  3835. return { message };
  3836. };
  3837. en_default = errorMap;
  3838. }
  3839. });
  3840. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js
  3841. function setErrorMap(map2) {
  3842. overrideErrorMap = map2;
  3843. }
  3844. function getErrorMap() {
  3845. return overrideErrorMap;
  3846. }
  3847. var overrideErrorMap;
  3848. var init_errors = __esm({
  3849. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js"() {
  3850. "use strict";
  3851. init_en();
  3852. overrideErrorMap = en_default;
  3853. }
  3854. });
  3855. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
  3856. function addIssueToContext(ctx, issueData) {
  3857. const overrideMap = getErrorMap();
  3858. const issue = makeIssue({
  3859. issueData,
  3860. data: ctx.data,
  3861. path: ctx.path,
  3862. errorMaps: [
  3863. ctx.common.contextualErrorMap,
  3864. // contextual error map is first priority
  3865. ctx.schemaErrorMap,
  3866. // then schema-bound map if available
  3867. overrideMap,
  3868. // then global override map
  3869. overrideMap === en_default ? void 0 : en_default
  3870. // then global default map
  3871. ].filter((x5) => !!x5)
  3872. });
  3873. ctx.common.issues.push(issue);
  3874. }
  3875. var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
  3876. var init_parseUtil = __esm({
  3877. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js"() {
  3878. "use strict";
  3879. init_errors();
  3880. init_en();
  3881. makeIssue = (params) => {
  3882. const { data, path: path3, errorMaps, issueData } = params;
  3883. const fullPath = [...path3, ...issueData.path || []];
  3884. const fullIssue = {
  3885. ...issueData,
  3886. path: fullPath
  3887. };
  3888. if (issueData.message !== void 0) {
  3889. return {
  3890. ...issueData,
  3891. path: fullPath,
  3892. message: issueData.message
  3893. };
  3894. }
  3895. let errorMessage = "";
  3896. const maps = errorMaps.filter((m6) => !!m6).slice().reverse();
  3897. for (const map2 of maps) {
  3898. errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
  3899. }
  3900. return {
  3901. ...issueData,
  3902. path: fullPath,
  3903. message: errorMessage
  3904. };
  3905. };
  3906. EMPTY_PATH = [];
  3907. ParseStatus = class _ParseStatus {
  3908. constructor() {
  3909. this.value = "valid";
  3910. }
  3911. dirty() {
  3912. if (this.value === "valid")
  3913. this.value = "dirty";
  3914. }
  3915. abort() {
  3916. if (this.value !== "aborted")
  3917. this.value = "aborted";
  3918. }
  3919. static mergeArray(status, results) {
  3920. const arrayValue = [];
  3921. for (const s6 of results) {
  3922. if (s6.status === "aborted")
  3923. return INVALID;
  3924. if (s6.status === "dirty")
  3925. status.dirty();
  3926. arrayValue.push(s6.value);
  3927. }
  3928. return { status: status.value, value: arrayValue };
  3929. }
  3930. static async mergeObjectAsync(status, pairs) {
  3931. const syncPairs = [];
  3932. for (const pair of pairs) {
  3933. const key = await pair.key;
  3934. const value = await pair.value;
  3935. syncPairs.push({
  3936. key,
  3937. value
  3938. });
  3939. }
  3940. return _ParseStatus.mergeObjectSync(status, syncPairs);
  3941. }
  3942. static mergeObjectSync(status, pairs) {
  3943. const finalObject = {};
  3944. for (const pair of pairs) {
  3945. const { key, value } = pair;
  3946. if (key.status === "aborted")
  3947. return INVALID;
  3948. if (value.status === "aborted")
  3949. return INVALID;
  3950. if (key.status === "dirty")
  3951. status.dirty();
  3952. if (value.status === "dirty")
  3953. status.dirty();
  3954. if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
  3955. finalObject[key.value] = value.value;
  3956. }
  3957. }
  3958. return { status: status.value, value: finalObject };
  3959. }
  3960. };
  3961. INVALID = Object.freeze({
  3962. status: "aborted"
  3963. });
  3964. DIRTY = (value) => ({ status: "dirty", value });
  3965. OK = (value) => ({ status: "valid", value });
  3966. isAborted = (x5) => x5.status === "aborted";
  3967. isDirty = (x5) => x5.status === "dirty";
  3968. isValid = (x5) => x5.status === "valid";
  3969. isAsync = (x5) => typeof Promise !== "undefined" && x5 instanceof Promise;
  3970. }
  3971. });
  3972. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js
  3973. var init_typeAliases = __esm({
  3974. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js"() {
  3975. "use strict";
  3976. }
  3977. });
  3978. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js
  3979. var errorUtil;
  3980. var init_errorUtil = __esm({
  3981. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js"() {
  3982. "use strict";
  3983. (function(errorUtil2) {
  3984. errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  3985. errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
  3986. })(errorUtil || (errorUtil = {}));
  3987. }
  3988. });
  3989. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js
  3990. function processCreateParams(params) {
  3991. if (!params)
  3992. return {};
  3993. const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  3994. if (errorMap2 && (invalid_type_error || required_error)) {
  3995. throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  3996. }
  3997. if (errorMap2)
  3998. return { errorMap: errorMap2, description };
  3999. const customMap = (iss, ctx) => {
  4000. const { message } = params;
  4001. if (iss.code === "invalid_enum_value") {
  4002. return { message: message ?? ctx.defaultError };
  4003. }
  4004. if (typeof ctx.data === "undefined") {
  4005. return { message: message ?? required_error ?? ctx.defaultError };
  4006. }
  4007. if (iss.code !== "invalid_type")
  4008. return { message: ctx.defaultError };
  4009. return { message: message ?? invalid_type_error ?? ctx.defaultError };
  4010. };
  4011. return { errorMap: customMap, description };
  4012. }
  4013. function timeRegexSource(args) {
  4014. let secondsRegexSource = `[0-5]\\d`;
  4015. if (args.precision) {
  4016. secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  4017. } else if (args.precision == null) {
  4018. secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  4019. }
  4020. const secondsQuantifier = args.precision ? "+" : "?";
  4021. return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
  4022. }
  4023. function timeRegex(args) {
  4024. return new RegExp(`^${timeRegexSource(args)}$`);
  4025. }
  4026. function datetimeRegex(args) {
  4027. let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  4028. const opts = [];
  4029. opts.push(args.local ? `Z?` : `Z`);
  4030. if (args.offset)
  4031. opts.push(`([+-]\\d{2}:?\\d{2})`);
  4032. regex = `${regex}(${opts.join("|")})`;
  4033. return new RegExp(`^${regex}$`);
  4034. }
  4035. function isValidIP(ip, version) {
  4036. if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
  4037. return true;
  4038. }
  4039. if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
  4040. return true;
  4041. }
  4042. return false;
  4043. }
  4044. function isValidJWT(jwt, alg) {
  4045. if (!jwtRegex.test(jwt))
  4046. return false;
  4047. try {
  4048. const [header] = jwt.split(".");
  4049. const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
  4050. const decoded = JSON.parse(atob(base64));
  4051. if (typeof decoded !== "object" || decoded === null)
  4052. return false;
  4053. if ("typ" in decoded && decoded?.typ !== "JWT")
  4054. return false;
  4055. if (!decoded.alg)
  4056. return false;
  4057. if (alg && decoded.alg !== alg)
  4058. return false;
  4059. return true;
  4060. } catch {
  4061. return false;
  4062. }
  4063. }
  4064. function isValidCidr(ip, version) {
  4065. if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
  4066. return true;
  4067. }
  4068. if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
  4069. return true;
  4070. }
  4071. return false;
  4072. }
  4073. function floatSafeRemainder(val2, step) {
  4074. const valDecCount = (val2.toString().split(".")[1] || "").length;
  4075. const stepDecCount = (step.toString().split(".")[1] || "").length;
  4076. const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  4077. const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", ""));
  4078. const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  4079. return valInt % stepInt / 10 ** decCount;
  4080. }
  4081. function deepPartialify(schema6) {
  4082. if (schema6 instanceof ZodObject) {
  4083. const newShape = {};
  4084. for (const key in schema6.shape) {
  4085. const fieldSchema = schema6.shape[key];
  4086. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
  4087. }
  4088. return new ZodObject({
  4089. ...schema6._def,
  4090. shape: () => newShape
  4091. });
  4092. } else if (schema6 instanceof ZodArray) {
  4093. return new ZodArray({
  4094. ...schema6._def,
  4095. type: deepPartialify(schema6.element)
  4096. });
  4097. } else if (schema6 instanceof ZodOptional) {
  4098. return ZodOptional.create(deepPartialify(schema6.unwrap()));
  4099. } else if (schema6 instanceof ZodNullable) {
  4100. return ZodNullable.create(deepPartialify(schema6.unwrap()));
  4101. } else if (schema6 instanceof ZodTuple) {
  4102. return ZodTuple.create(schema6.items.map((item) => deepPartialify(item)));
  4103. } else {
  4104. return schema6;
  4105. }
  4106. }
  4107. function mergeValues(a5, b5) {
  4108. const aType = getParsedType(a5);
  4109. const bType = getParsedType(b5);
  4110. if (a5 === b5) {
  4111. return { valid: true, data: a5 };
  4112. } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  4113. const bKeys = util.objectKeys(b5);
  4114. const sharedKeys = util.objectKeys(a5).filter((key) => bKeys.indexOf(key) !== -1);
  4115. const newObj = { ...a5, ...b5 };
  4116. for (const key of sharedKeys) {
  4117. const sharedValue = mergeValues(a5[key], b5[key]);
  4118. if (!sharedValue.valid) {
  4119. return { valid: false };
  4120. }
  4121. newObj[key] = sharedValue.data;
  4122. }
  4123. return { valid: true, data: newObj };
  4124. } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  4125. if (a5.length !== b5.length) {
  4126. return { valid: false };
  4127. }
  4128. const newArray = [];
  4129. for (let index6 = 0; index6 < a5.length; index6++) {
  4130. const itemA = a5[index6];
  4131. const itemB = b5[index6];
  4132. const sharedValue = mergeValues(itemA, itemB);
  4133. if (!sharedValue.valid) {
  4134. return { valid: false };
  4135. }
  4136. newArray.push(sharedValue.data);
  4137. }
  4138. return { valid: true, data: newArray };
  4139. } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a5 === +b5) {
  4140. return { valid: true, data: a5 };
  4141. } else {
  4142. return { valid: false };
  4143. }
  4144. }
  4145. function createZodEnum(values, params) {
  4146. return new ZodEnum({
  4147. values,
  4148. typeName: ZodFirstPartyTypeKind.ZodEnum,
  4149. ...processCreateParams(params)
  4150. });
  4151. }
  4152. function cleanParams(params, data) {
  4153. const p5 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  4154. const p22 = typeof p5 === "string" ? { message: p5 } : p5;
  4155. return p22;
  4156. }
  4157. function custom(check, _params2 = {}, fatal) {
  4158. if (check)
  4159. return ZodAny.create().superRefine((data, ctx) => {
  4160. const r6 = check(data);
  4161. if (r6 instanceof Promise) {
  4162. return r6.then((r7) => {
  4163. if (!r7) {
  4164. const params = cleanParams(_params2, data);
  4165. const _fatal = params.fatal ?? fatal ?? true;
  4166. ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
  4167. }
  4168. });
  4169. }
  4170. if (!r6) {
  4171. const params = cleanParams(_params2, data);
  4172. const _fatal = params.fatal ?? fatal ?? true;
  4173. ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
  4174. }
  4175. return;
  4176. });
  4177. return ZodAny.create();
  4178. }
  4179. var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER;
  4180. var init_types = __esm({
  4181. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js"() {
  4182. "use strict";
  4183. init_ZodError();
  4184. init_errors();
  4185. init_errorUtil();
  4186. init_parseUtil();
  4187. init_util();
  4188. ParseInputLazyPath = class {
  4189. constructor(parent, value, path3, key) {
  4190. this._cachedPath = [];
  4191. this.parent = parent;
  4192. this.data = value;
  4193. this._path = path3;
  4194. this._key = key;
  4195. }
  4196. get path() {
  4197. if (!this._cachedPath.length) {
  4198. if (Array.isArray(this._key)) {
  4199. this._cachedPath.push(...this._path, ...this._key);
  4200. } else {
  4201. this._cachedPath.push(...this._path, this._key);
  4202. }
  4203. }
  4204. return this._cachedPath;
  4205. }
  4206. };
  4207. handleResult = (ctx, result) => {
  4208. if (isValid(result)) {
  4209. return { success: true, data: result.value };
  4210. } else {
  4211. if (!ctx.common.issues.length) {
  4212. throw new Error("Validation failed but no issues detected.");
  4213. }
  4214. return {
  4215. success: false,
  4216. get error() {
  4217. if (this._error)
  4218. return this._error;
  4219. const error2 = new ZodError(ctx.common.issues);
  4220. this._error = error2;
  4221. return this._error;
  4222. }
  4223. };
  4224. }
  4225. };
  4226. ZodType = class {
  4227. get description() {
  4228. return this._def.description;
  4229. }
  4230. _getType(input) {
  4231. return getParsedType(input.data);
  4232. }
  4233. _getOrReturnCtx(input, ctx) {
  4234. return ctx || {
  4235. common: input.parent.common,
  4236. data: input.data,
  4237. parsedType: getParsedType(input.data),
  4238. schemaErrorMap: this._def.errorMap,
  4239. path: input.path,
  4240. parent: input.parent
  4241. };
  4242. }
  4243. _processInputParams(input) {
  4244. return {
  4245. status: new ParseStatus(),
  4246. ctx: {
  4247. common: input.parent.common,
  4248. data: input.data,
  4249. parsedType: getParsedType(input.data),
  4250. schemaErrorMap: this._def.errorMap,
  4251. path: input.path,
  4252. parent: input.parent
  4253. }
  4254. };
  4255. }
  4256. _parseSync(input) {
  4257. const result = this._parse(input);
  4258. if (isAsync(result)) {
  4259. throw new Error("Synchronous parse encountered promise.");
  4260. }
  4261. return result;
  4262. }
  4263. _parseAsync(input) {
  4264. const result = this._parse(input);
  4265. return Promise.resolve(result);
  4266. }
  4267. parse(data, params) {
  4268. const result = this.safeParse(data, params);
  4269. if (result.success)
  4270. return result.data;
  4271. throw result.error;
  4272. }
  4273. safeParse(data, params) {
  4274. const ctx = {
  4275. common: {
  4276. issues: [],
  4277. async: params?.async ?? false,
  4278. contextualErrorMap: params?.errorMap
  4279. },
  4280. path: params?.path || [],
  4281. schemaErrorMap: this._def.errorMap,
  4282. parent: null,
  4283. data,
  4284. parsedType: getParsedType(data)
  4285. };
  4286. const result = this._parseSync({ data, path: ctx.path, parent: ctx });
  4287. return handleResult(ctx, result);
  4288. }
  4289. "~validate"(data) {
  4290. const ctx = {
  4291. common: {
  4292. issues: [],
  4293. async: !!this["~standard"].async
  4294. },
  4295. path: [],
  4296. schemaErrorMap: this._def.errorMap,
  4297. parent: null,
  4298. data,
  4299. parsedType: getParsedType(data)
  4300. };
  4301. if (!this["~standard"].async) {
  4302. try {
  4303. const result = this._parseSync({ data, path: [], parent: ctx });
  4304. return isValid(result) ? {
  4305. value: result.value
  4306. } : {
  4307. issues: ctx.common.issues
  4308. };
  4309. } catch (err2) {
  4310. if (err2?.message?.toLowerCase()?.includes("encountered")) {
  4311. this["~standard"].async = true;
  4312. }
  4313. ctx.common = {
  4314. issues: [],
  4315. async: true
  4316. };
  4317. }
  4318. }
  4319. return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
  4320. value: result.value
  4321. } : {
  4322. issues: ctx.common.issues
  4323. });
  4324. }
  4325. async parseAsync(data, params) {
  4326. const result = await this.safeParseAsync(data, params);
  4327. if (result.success)
  4328. return result.data;
  4329. throw result.error;
  4330. }
  4331. async safeParseAsync(data, params) {
  4332. const ctx = {
  4333. common: {
  4334. issues: [],
  4335. contextualErrorMap: params?.errorMap,
  4336. async: true
  4337. },
  4338. path: params?.path || [],
  4339. schemaErrorMap: this._def.errorMap,
  4340. parent: null,
  4341. data,
  4342. parsedType: getParsedType(data)
  4343. };
  4344. const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
  4345. const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
  4346. return handleResult(ctx, result);
  4347. }
  4348. refine(check, message) {
  4349. const getIssueProperties = (val2) => {
  4350. if (typeof message === "string" || typeof message === "undefined") {
  4351. return { message };
  4352. } else if (typeof message === "function") {
  4353. return message(val2);
  4354. } else {
  4355. return message;
  4356. }
  4357. };
  4358. return this._refinement((val2, ctx) => {
  4359. const result = check(val2);
  4360. const setError = () => ctx.addIssue({
  4361. code: ZodIssueCode.custom,
  4362. ...getIssueProperties(val2)
  4363. });
  4364. if (typeof Promise !== "undefined" && result instanceof Promise) {
  4365. return result.then((data) => {
  4366. if (!data) {
  4367. setError();
  4368. return false;
  4369. } else {
  4370. return true;
  4371. }
  4372. });
  4373. }
  4374. if (!result) {
  4375. setError();
  4376. return false;
  4377. } else {
  4378. return true;
  4379. }
  4380. });
  4381. }
  4382. refinement(check, refinementData) {
  4383. return this._refinement((val2, ctx) => {
  4384. if (!check(val2)) {
  4385. ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
  4386. return false;
  4387. } else {
  4388. return true;
  4389. }
  4390. });
  4391. }
  4392. _refinement(refinement) {
  4393. return new ZodEffects({
  4394. schema: this,
  4395. typeName: ZodFirstPartyTypeKind.ZodEffects,
  4396. effect: { type: "refinement", refinement }
  4397. });
  4398. }
  4399. superRefine(refinement) {
  4400. return this._refinement(refinement);
  4401. }
  4402. constructor(def) {
  4403. this.spa = this.safeParseAsync;
  4404. this._def = def;
  4405. this.parse = this.parse.bind(this);
  4406. this.safeParse = this.safeParse.bind(this);
  4407. this.parseAsync = this.parseAsync.bind(this);
  4408. this.safeParseAsync = this.safeParseAsync.bind(this);
  4409. this.spa = this.spa.bind(this);
  4410. this.refine = this.refine.bind(this);
  4411. this.refinement = this.refinement.bind(this);
  4412. this.superRefine = this.superRefine.bind(this);
  4413. this.optional = this.optional.bind(this);
  4414. this.nullable = this.nullable.bind(this);
  4415. this.nullish = this.nullish.bind(this);
  4416. this.array = this.array.bind(this);
  4417. this.promise = this.promise.bind(this);
  4418. this.or = this.or.bind(this);
  4419. this.and = this.and.bind(this);
  4420. this.transform = this.transform.bind(this);
  4421. this.brand = this.brand.bind(this);
  4422. this.default = this.default.bind(this);
  4423. this.catch = this.catch.bind(this);
  4424. this.describe = this.describe.bind(this);
  4425. this.pipe = this.pipe.bind(this);
  4426. this.readonly = this.readonly.bind(this);
  4427. this.isNullable = this.isNullable.bind(this);
  4428. this.isOptional = this.isOptional.bind(this);
  4429. this["~standard"] = {
  4430. version: 1,
  4431. vendor: "zod",
  4432. validate: (data) => this["~validate"](data)
  4433. };
  4434. }
  4435. optional() {
  4436. return ZodOptional.create(this, this._def);
  4437. }
  4438. nullable() {
  4439. return ZodNullable.create(this, this._def);
  4440. }
  4441. nullish() {
  4442. return this.nullable().optional();
  4443. }
  4444. array() {
  4445. return ZodArray.create(this);
  4446. }
  4447. promise() {
  4448. return ZodPromise.create(this, this._def);
  4449. }
  4450. or(option) {
  4451. return ZodUnion.create([this, option], this._def);
  4452. }
  4453. and(incoming) {
  4454. return ZodIntersection.create(this, incoming, this._def);
  4455. }
  4456. transform(transform) {
  4457. return new ZodEffects({
  4458. ...processCreateParams(this._def),
  4459. schema: this,
  4460. typeName: ZodFirstPartyTypeKind.ZodEffects,
  4461. effect: { type: "transform", transform }
  4462. });
  4463. }
  4464. default(def) {
  4465. const defaultValueFunc = typeof def === "function" ? def : () => def;
  4466. return new ZodDefault({
  4467. ...processCreateParams(this._def),
  4468. innerType: this,
  4469. defaultValue: defaultValueFunc,
  4470. typeName: ZodFirstPartyTypeKind.ZodDefault
  4471. });
  4472. }
  4473. brand() {
  4474. return new ZodBranded({
  4475. typeName: ZodFirstPartyTypeKind.ZodBranded,
  4476. type: this,
  4477. ...processCreateParams(this._def)
  4478. });
  4479. }
  4480. catch(def) {
  4481. const catchValueFunc = typeof def === "function" ? def : () => def;
  4482. return new ZodCatch({
  4483. ...processCreateParams(this._def),
  4484. innerType: this,
  4485. catchValue: catchValueFunc,
  4486. typeName: ZodFirstPartyTypeKind.ZodCatch
  4487. });
  4488. }
  4489. describe(description) {
  4490. const This = this.constructor;
  4491. return new This({
  4492. ...this._def,
  4493. description
  4494. });
  4495. }
  4496. pipe(target) {
  4497. return ZodPipeline.create(this, target);
  4498. }
  4499. readonly() {
  4500. return ZodReadonly.create(this);
  4501. }
  4502. isOptional() {
  4503. return this.safeParse(void 0).success;
  4504. }
  4505. isNullable() {
  4506. return this.safeParse(null).success;
  4507. }
  4508. };
  4509. cuidRegex = /^c[^\s-]{8,}$/i;
  4510. cuid2Regex = /^[0-9a-z]+$/;
  4511. ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
  4512. uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
  4513. nanoidRegex = /^[a-z0-9_-]{21}$/i;
  4514. jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
  4515. durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
  4516. emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
  4517. _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
  4518. ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
  4519. ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
  4520. ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
  4521. ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
  4522. base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
  4523. base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
  4524. dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
  4525. dateRegex = new RegExp(`^${dateRegexSource}$`);
  4526. ZodString = class _ZodString extends ZodType {
  4527. _parse(input) {
  4528. if (this._def.coerce) {
  4529. input.data = String(input.data);
  4530. }
  4531. const parsedType = this._getType(input);
  4532. if (parsedType !== ZodParsedType.string) {
  4533. const ctx2 = this._getOrReturnCtx(input);
  4534. addIssueToContext(ctx2, {
  4535. code: ZodIssueCode.invalid_type,
  4536. expected: ZodParsedType.string,
  4537. received: ctx2.parsedType
  4538. });
  4539. return INVALID;
  4540. }
  4541. const status = new ParseStatus();
  4542. let ctx = void 0;
  4543. for (const check of this._def.checks) {
  4544. if (check.kind === "min") {
  4545. if (input.data.length < check.value) {
  4546. ctx = this._getOrReturnCtx(input, ctx);
  4547. addIssueToContext(ctx, {
  4548. code: ZodIssueCode.too_small,
  4549. minimum: check.value,
  4550. type: "string",
  4551. inclusive: true,
  4552. exact: false,
  4553. message: check.message
  4554. });
  4555. status.dirty();
  4556. }
  4557. } else if (check.kind === "max") {
  4558. if (input.data.length > check.value) {
  4559. ctx = this._getOrReturnCtx(input, ctx);
  4560. addIssueToContext(ctx, {
  4561. code: ZodIssueCode.too_big,
  4562. maximum: check.value,
  4563. type: "string",
  4564. inclusive: true,
  4565. exact: false,
  4566. message: check.message
  4567. });
  4568. status.dirty();
  4569. }
  4570. } else if (check.kind === "length") {
  4571. const tooBig = input.data.length > check.value;
  4572. const tooSmall = input.data.length < check.value;
  4573. if (tooBig || tooSmall) {
  4574. ctx = this._getOrReturnCtx(input, ctx);
  4575. if (tooBig) {
  4576. addIssueToContext(ctx, {
  4577. code: ZodIssueCode.too_big,
  4578. maximum: check.value,
  4579. type: "string",
  4580. inclusive: true,
  4581. exact: true,
  4582. message: check.message
  4583. });
  4584. } else if (tooSmall) {
  4585. addIssueToContext(ctx, {
  4586. code: ZodIssueCode.too_small,
  4587. minimum: check.value,
  4588. type: "string",
  4589. inclusive: true,
  4590. exact: true,
  4591. message: check.message
  4592. });
  4593. }
  4594. status.dirty();
  4595. }
  4596. } else if (check.kind === "email") {
  4597. if (!emailRegex.test(input.data)) {
  4598. ctx = this._getOrReturnCtx(input, ctx);
  4599. addIssueToContext(ctx, {
  4600. validation: "email",
  4601. code: ZodIssueCode.invalid_string,
  4602. message: check.message
  4603. });
  4604. status.dirty();
  4605. }
  4606. } else if (check.kind === "emoji") {
  4607. if (!emojiRegex) {
  4608. emojiRegex = new RegExp(_emojiRegex, "u");
  4609. }
  4610. if (!emojiRegex.test(input.data)) {
  4611. ctx = this._getOrReturnCtx(input, ctx);
  4612. addIssueToContext(ctx, {
  4613. validation: "emoji",
  4614. code: ZodIssueCode.invalid_string,
  4615. message: check.message
  4616. });
  4617. status.dirty();
  4618. }
  4619. } else if (check.kind === "uuid") {
  4620. if (!uuidRegex.test(input.data)) {
  4621. ctx = this._getOrReturnCtx(input, ctx);
  4622. addIssueToContext(ctx, {
  4623. validation: "uuid",
  4624. code: ZodIssueCode.invalid_string,
  4625. message: check.message
  4626. });
  4627. status.dirty();
  4628. }
  4629. } else if (check.kind === "nanoid") {
  4630. if (!nanoidRegex.test(input.data)) {
  4631. ctx = this._getOrReturnCtx(input, ctx);
  4632. addIssueToContext(ctx, {
  4633. validation: "nanoid",
  4634. code: ZodIssueCode.invalid_string,
  4635. message: check.message
  4636. });
  4637. status.dirty();
  4638. }
  4639. } else if (check.kind === "cuid") {
  4640. if (!cuidRegex.test(input.data)) {
  4641. ctx = this._getOrReturnCtx(input, ctx);
  4642. addIssueToContext(ctx, {
  4643. validation: "cuid",
  4644. code: ZodIssueCode.invalid_string,
  4645. message: check.message
  4646. });
  4647. status.dirty();
  4648. }
  4649. } else if (check.kind === "cuid2") {
  4650. if (!cuid2Regex.test(input.data)) {
  4651. ctx = this._getOrReturnCtx(input, ctx);
  4652. addIssueToContext(ctx, {
  4653. validation: "cuid2",
  4654. code: ZodIssueCode.invalid_string,
  4655. message: check.message
  4656. });
  4657. status.dirty();
  4658. }
  4659. } else if (check.kind === "ulid") {
  4660. if (!ulidRegex.test(input.data)) {
  4661. ctx = this._getOrReturnCtx(input, ctx);
  4662. addIssueToContext(ctx, {
  4663. validation: "ulid",
  4664. code: ZodIssueCode.invalid_string,
  4665. message: check.message
  4666. });
  4667. status.dirty();
  4668. }
  4669. } else if (check.kind === "url") {
  4670. try {
  4671. new URL(input.data);
  4672. } catch {
  4673. ctx = this._getOrReturnCtx(input, ctx);
  4674. addIssueToContext(ctx, {
  4675. validation: "url",
  4676. code: ZodIssueCode.invalid_string,
  4677. message: check.message
  4678. });
  4679. status.dirty();
  4680. }
  4681. } else if (check.kind === "regex") {
  4682. check.regex.lastIndex = 0;
  4683. const testResult = check.regex.test(input.data);
  4684. if (!testResult) {
  4685. ctx = this._getOrReturnCtx(input, ctx);
  4686. addIssueToContext(ctx, {
  4687. validation: "regex",
  4688. code: ZodIssueCode.invalid_string,
  4689. message: check.message
  4690. });
  4691. status.dirty();
  4692. }
  4693. } else if (check.kind === "trim") {
  4694. input.data = input.data.trim();
  4695. } else if (check.kind === "includes") {
  4696. if (!input.data.includes(check.value, check.position)) {
  4697. ctx = this._getOrReturnCtx(input, ctx);
  4698. addIssueToContext(ctx, {
  4699. code: ZodIssueCode.invalid_string,
  4700. validation: { includes: check.value, position: check.position },
  4701. message: check.message
  4702. });
  4703. status.dirty();
  4704. }
  4705. } else if (check.kind === "toLowerCase") {
  4706. input.data = input.data.toLowerCase();
  4707. } else if (check.kind === "toUpperCase") {
  4708. input.data = input.data.toUpperCase();
  4709. } else if (check.kind === "startsWith") {
  4710. if (!input.data.startsWith(check.value)) {
  4711. ctx = this._getOrReturnCtx(input, ctx);
  4712. addIssueToContext(ctx, {
  4713. code: ZodIssueCode.invalid_string,
  4714. validation: { startsWith: check.value },
  4715. message: check.message
  4716. });
  4717. status.dirty();
  4718. }
  4719. } else if (check.kind === "endsWith") {
  4720. if (!input.data.endsWith(check.value)) {
  4721. ctx = this._getOrReturnCtx(input, ctx);
  4722. addIssueToContext(ctx, {
  4723. code: ZodIssueCode.invalid_string,
  4724. validation: { endsWith: check.value },
  4725. message: check.message
  4726. });
  4727. status.dirty();
  4728. }
  4729. } else if (check.kind === "datetime") {
  4730. const regex = datetimeRegex(check);
  4731. if (!regex.test(input.data)) {
  4732. ctx = this._getOrReturnCtx(input, ctx);
  4733. addIssueToContext(ctx, {
  4734. code: ZodIssueCode.invalid_string,
  4735. validation: "datetime",
  4736. message: check.message
  4737. });
  4738. status.dirty();
  4739. }
  4740. } else if (check.kind === "date") {
  4741. const regex = dateRegex;
  4742. if (!regex.test(input.data)) {
  4743. ctx = this._getOrReturnCtx(input, ctx);
  4744. addIssueToContext(ctx, {
  4745. code: ZodIssueCode.invalid_string,
  4746. validation: "date",
  4747. message: check.message
  4748. });
  4749. status.dirty();
  4750. }
  4751. } else if (check.kind === "time") {
  4752. const regex = timeRegex(check);
  4753. if (!regex.test(input.data)) {
  4754. ctx = this._getOrReturnCtx(input, ctx);
  4755. addIssueToContext(ctx, {
  4756. code: ZodIssueCode.invalid_string,
  4757. validation: "time",
  4758. message: check.message
  4759. });
  4760. status.dirty();
  4761. }
  4762. } else if (check.kind === "duration") {
  4763. if (!durationRegex.test(input.data)) {
  4764. ctx = this._getOrReturnCtx(input, ctx);
  4765. addIssueToContext(ctx, {
  4766. validation: "duration",
  4767. code: ZodIssueCode.invalid_string,
  4768. message: check.message
  4769. });
  4770. status.dirty();
  4771. }
  4772. } else if (check.kind === "ip") {
  4773. if (!isValidIP(input.data, check.version)) {
  4774. ctx = this._getOrReturnCtx(input, ctx);
  4775. addIssueToContext(ctx, {
  4776. validation: "ip",
  4777. code: ZodIssueCode.invalid_string,
  4778. message: check.message
  4779. });
  4780. status.dirty();
  4781. }
  4782. } else if (check.kind === "jwt") {
  4783. if (!isValidJWT(input.data, check.alg)) {
  4784. ctx = this._getOrReturnCtx(input, ctx);
  4785. addIssueToContext(ctx, {
  4786. validation: "jwt",
  4787. code: ZodIssueCode.invalid_string,
  4788. message: check.message
  4789. });
  4790. status.dirty();
  4791. }
  4792. } else if (check.kind === "cidr") {
  4793. if (!isValidCidr(input.data, check.version)) {
  4794. ctx = this._getOrReturnCtx(input, ctx);
  4795. addIssueToContext(ctx, {
  4796. validation: "cidr",
  4797. code: ZodIssueCode.invalid_string,
  4798. message: check.message
  4799. });
  4800. status.dirty();
  4801. }
  4802. } else if (check.kind === "base64") {
  4803. if (!base64Regex.test(input.data)) {
  4804. ctx = this._getOrReturnCtx(input, ctx);
  4805. addIssueToContext(ctx, {
  4806. validation: "base64",
  4807. code: ZodIssueCode.invalid_string,
  4808. message: check.message
  4809. });
  4810. status.dirty();
  4811. }
  4812. } else if (check.kind === "base64url") {
  4813. if (!base64urlRegex.test(input.data)) {
  4814. ctx = this._getOrReturnCtx(input, ctx);
  4815. addIssueToContext(ctx, {
  4816. validation: "base64url",
  4817. code: ZodIssueCode.invalid_string,
  4818. message: check.message
  4819. });
  4820. status.dirty();
  4821. }
  4822. } else {
  4823. util.assertNever(check);
  4824. }
  4825. }
  4826. return { status: status.value, value: input.data };
  4827. }
  4828. _regex(regex, validation, message) {
  4829. return this.refinement((data) => regex.test(data), {
  4830. validation,
  4831. code: ZodIssueCode.invalid_string,
  4832. ...errorUtil.errToObj(message)
  4833. });
  4834. }
  4835. _addCheck(check) {
  4836. return new _ZodString({
  4837. ...this._def,
  4838. checks: [...this._def.checks, check]
  4839. });
  4840. }
  4841. email(message) {
  4842. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  4843. }
  4844. url(message) {
  4845. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  4846. }
  4847. emoji(message) {
  4848. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  4849. }
  4850. uuid(message) {
  4851. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  4852. }
  4853. nanoid(message) {
  4854. return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  4855. }
  4856. cuid(message) {
  4857. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  4858. }
  4859. cuid2(message) {
  4860. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  4861. }
  4862. ulid(message) {
  4863. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  4864. }
  4865. base64(message) {
  4866. return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  4867. }
  4868. base64url(message) {
  4869. return this._addCheck({
  4870. kind: "base64url",
  4871. ...errorUtil.errToObj(message)
  4872. });
  4873. }
  4874. jwt(options) {
  4875. return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  4876. }
  4877. ip(options) {
  4878. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  4879. }
  4880. cidr(options) {
  4881. return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  4882. }
  4883. datetime(options) {
  4884. if (typeof options === "string") {
  4885. return this._addCheck({
  4886. kind: "datetime",
  4887. precision: null,
  4888. offset: false,
  4889. local: false,
  4890. message: options
  4891. });
  4892. }
  4893. return this._addCheck({
  4894. kind: "datetime",
  4895. precision: typeof options?.precision === "undefined" ? null : options?.precision,
  4896. offset: options?.offset ?? false,
  4897. local: options?.local ?? false,
  4898. ...errorUtil.errToObj(options?.message)
  4899. });
  4900. }
  4901. date(message) {
  4902. return this._addCheck({ kind: "date", message });
  4903. }
  4904. time(options) {
  4905. if (typeof options === "string") {
  4906. return this._addCheck({
  4907. kind: "time",
  4908. precision: null,
  4909. message: options
  4910. });
  4911. }
  4912. return this._addCheck({
  4913. kind: "time",
  4914. precision: typeof options?.precision === "undefined" ? null : options?.precision,
  4915. ...errorUtil.errToObj(options?.message)
  4916. });
  4917. }
  4918. duration(message) {
  4919. return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  4920. }
  4921. regex(regex, message) {
  4922. return this._addCheck({
  4923. kind: "regex",
  4924. regex,
  4925. ...errorUtil.errToObj(message)
  4926. });
  4927. }
  4928. includes(value, options) {
  4929. return this._addCheck({
  4930. kind: "includes",
  4931. value,
  4932. position: options?.position,
  4933. ...errorUtil.errToObj(options?.message)
  4934. });
  4935. }
  4936. startsWith(value, message) {
  4937. return this._addCheck({
  4938. kind: "startsWith",
  4939. value,
  4940. ...errorUtil.errToObj(message)
  4941. });
  4942. }
  4943. endsWith(value, message) {
  4944. return this._addCheck({
  4945. kind: "endsWith",
  4946. value,
  4947. ...errorUtil.errToObj(message)
  4948. });
  4949. }
  4950. min(minLength, message) {
  4951. return this._addCheck({
  4952. kind: "min",
  4953. value: minLength,
  4954. ...errorUtil.errToObj(message)
  4955. });
  4956. }
  4957. max(maxLength, message) {
  4958. return this._addCheck({
  4959. kind: "max",
  4960. value: maxLength,
  4961. ...errorUtil.errToObj(message)
  4962. });
  4963. }
  4964. length(len, message) {
  4965. return this._addCheck({
  4966. kind: "length",
  4967. value: len,
  4968. ...errorUtil.errToObj(message)
  4969. });
  4970. }
  4971. /**
  4972. * Equivalent to `.min(1)`
  4973. */
  4974. nonempty(message) {
  4975. return this.min(1, errorUtil.errToObj(message));
  4976. }
  4977. trim() {
  4978. return new _ZodString({
  4979. ...this._def,
  4980. checks: [...this._def.checks, { kind: "trim" }]
  4981. });
  4982. }
  4983. toLowerCase() {
  4984. return new _ZodString({
  4985. ...this._def,
  4986. checks: [...this._def.checks, { kind: "toLowerCase" }]
  4987. });
  4988. }
  4989. toUpperCase() {
  4990. return new _ZodString({
  4991. ...this._def,
  4992. checks: [...this._def.checks, { kind: "toUpperCase" }]
  4993. });
  4994. }
  4995. get isDatetime() {
  4996. return !!this._def.checks.find((ch) => ch.kind === "datetime");
  4997. }
  4998. get isDate() {
  4999. return !!this._def.checks.find((ch) => ch.kind === "date");
  5000. }
  5001. get isTime() {
  5002. return !!this._def.checks.find((ch) => ch.kind === "time");
  5003. }
  5004. get isDuration() {
  5005. return !!this._def.checks.find((ch) => ch.kind === "duration");
  5006. }
  5007. get isEmail() {
  5008. return !!this._def.checks.find((ch) => ch.kind === "email");
  5009. }
  5010. get isURL() {
  5011. return !!this._def.checks.find((ch) => ch.kind === "url");
  5012. }
  5013. get isEmoji() {
  5014. return !!this._def.checks.find((ch) => ch.kind === "emoji");
  5015. }
  5016. get isUUID() {
  5017. return !!this._def.checks.find((ch) => ch.kind === "uuid");
  5018. }
  5019. get isNANOID() {
  5020. return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  5021. }
  5022. get isCUID() {
  5023. return !!this._def.checks.find((ch) => ch.kind === "cuid");
  5024. }
  5025. get isCUID2() {
  5026. return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  5027. }
  5028. get isULID() {
  5029. return !!this._def.checks.find((ch) => ch.kind === "ulid");
  5030. }
  5031. get isIP() {
  5032. return !!this._def.checks.find((ch) => ch.kind === "ip");
  5033. }
  5034. get isCIDR() {
  5035. return !!this._def.checks.find((ch) => ch.kind === "cidr");
  5036. }
  5037. get isBase64() {
  5038. return !!this._def.checks.find((ch) => ch.kind === "base64");
  5039. }
  5040. get isBase64url() {
  5041. return !!this._def.checks.find((ch) => ch.kind === "base64url");
  5042. }
  5043. get minLength() {
  5044. let min = null;
  5045. for (const ch of this._def.checks) {
  5046. if (ch.kind === "min") {
  5047. if (min === null || ch.value > min)
  5048. min = ch.value;
  5049. }
  5050. }
  5051. return min;
  5052. }
  5053. get maxLength() {
  5054. let max = null;
  5055. for (const ch of this._def.checks) {
  5056. if (ch.kind === "max") {
  5057. if (max === null || ch.value < max)
  5058. max = ch.value;
  5059. }
  5060. }
  5061. return max;
  5062. }
  5063. };
  5064. ZodString.create = (params) => {
  5065. return new ZodString({
  5066. checks: [],
  5067. typeName: ZodFirstPartyTypeKind.ZodString,
  5068. coerce: params?.coerce ?? false,
  5069. ...processCreateParams(params)
  5070. });
  5071. };
  5072. ZodNumber = class _ZodNumber extends ZodType {
  5073. constructor() {
  5074. super(...arguments);
  5075. this.min = this.gte;
  5076. this.max = this.lte;
  5077. this.step = this.multipleOf;
  5078. }
  5079. _parse(input) {
  5080. if (this._def.coerce) {
  5081. input.data = Number(input.data);
  5082. }
  5083. const parsedType = this._getType(input);
  5084. if (parsedType !== ZodParsedType.number) {
  5085. const ctx2 = this._getOrReturnCtx(input);
  5086. addIssueToContext(ctx2, {
  5087. code: ZodIssueCode.invalid_type,
  5088. expected: ZodParsedType.number,
  5089. received: ctx2.parsedType
  5090. });
  5091. return INVALID;
  5092. }
  5093. let ctx = void 0;
  5094. const status = new ParseStatus();
  5095. for (const check of this._def.checks) {
  5096. if (check.kind === "int") {
  5097. if (!util.isInteger(input.data)) {
  5098. ctx = this._getOrReturnCtx(input, ctx);
  5099. addIssueToContext(ctx, {
  5100. code: ZodIssueCode.invalid_type,
  5101. expected: "integer",
  5102. received: "float",
  5103. message: check.message
  5104. });
  5105. status.dirty();
  5106. }
  5107. } else if (check.kind === "min") {
  5108. const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
  5109. if (tooSmall) {
  5110. ctx = this._getOrReturnCtx(input, ctx);
  5111. addIssueToContext(ctx, {
  5112. code: ZodIssueCode.too_small,
  5113. minimum: check.value,
  5114. type: "number",
  5115. inclusive: check.inclusive,
  5116. exact: false,
  5117. message: check.message
  5118. });
  5119. status.dirty();
  5120. }
  5121. } else if (check.kind === "max") {
  5122. const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
  5123. if (tooBig) {
  5124. ctx = this._getOrReturnCtx(input, ctx);
  5125. addIssueToContext(ctx, {
  5126. code: ZodIssueCode.too_big,
  5127. maximum: check.value,
  5128. type: "number",
  5129. inclusive: check.inclusive,
  5130. exact: false,
  5131. message: check.message
  5132. });
  5133. status.dirty();
  5134. }
  5135. } else if (check.kind === "multipleOf") {
  5136. if (floatSafeRemainder(input.data, check.value) !== 0) {
  5137. ctx = this._getOrReturnCtx(input, ctx);
  5138. addIssueToContext(ctx, {
  5139. code: ZodIssueCode.not_multiple_of,
  5140. multipleOf: check.value,
  5141. message: check.message
  5142. });
  5143. status.dirty();
  5144. }
  5145. } else if (check.kind === "finite") {
  5146. if (!Number.isFinite(input.data)) {
  5147. ctx = this._getOrReturnCtx(input, ctx);
  5148. addIssueToContext(ctx, {
  5149. code: ZodIssueCode.not_finite,
  5150. message: check.message
  5151. });
  5152. status.dirty();
  5153. }
  5154. } else {
  5155. util.assertNever(check);
  5156. }
  5157. }
  5158. return { status: status.value, value: input.data };
  5159. }
  5160. gte(value, message) {
  5161. return this.setLimit("min", value, true, errorUtil.toString(message));
  5162. }
  5163. gt(value, message) {
  5164. return this.setLimit("min", value, false, errorUtil.toString(message));
  5165. }
  5166. lte(value, message) {
  5167. return this.setLimit("max", value, true, errorUtil.toString(message));
  5168. }
  5169. lt(value, message) {
  5170. return this.setLimit("max", value, false, errorUtil.toString(message));
  5171. }
  5172. setLimit(kind, value, inclusive, message) {
  5173. return new _ZodNumber({
  5174. ...this._def,
  5175. checks: [
  5176. ...this._def.checks,
  5177. {
  5178. kind,
  5179. value,
  5180. inclusive,
  5181. message: errorUtil.toString(message)
  5182. }
  5183. ]
  5184. });
  5185. }
  5186. _addCheck(check) {
  5187. return new _ZodNumber({
  5188. ...this._def,
  5189. checks: [...this._def.checks, check]
  5190. });
  5191. }
  5192. int(message) {
  5193. return this._addCheck({
  5194. kind: "int",
  5195. message: errorUtil.toString(message)
  5196. });
  5197. }
  5198. positive(message) {
  5199. return this._addCheck({
  5200. kind: "min",
  5201. value: 0,
  5202. inclusive: false,
  5203. message: errorUtil.toString(message)
  5204. });
  5205. }
  5206. negative(message) {
  5207. return this._addCheck({
  5208. kind: "max",
  5209. value: 0,
  5210. inclusive: false,
  5211. message: errorUtil.toString(message)
  5212. });
  5213. }
  5214. nonpositive(message) {
  5215. return this._addCheck({
  5216. kind: "max",
  5217. value: 0,
  5218. inclusive: true,
  5219. message: errorUtil.toString(message)
  5220. });
  5221. }
  5222. nonnegative(message) {
  5223. return this._addCheck({
  5224. kind: "min",
  5225. value: 0,
  5226. inclusive: true,
  5227. message: errorUtil.toString(message)
  5228. });
  5229. }
  5230. multipleOf(value, message) {
  5231. return this._addCheck({
  5232. kind: "multipleOf",
  5233. value,
  5234. message: errorUtil.toString(message)
  5235. });
  5236. }
  5237. finite(message) {
  5238. return this._addCheck({
  5239. kind: "finite",
  5240. message: errorUtil.toString(message)
  5241. });
  5242. }
  5243. safe(message) {
  5244. return this._addCheck({
  5245. kind: "min",
  5246. inclusive: true,
  5247. value: Number.MIN_SAFE_INTEGER,
  5248. message: errorUtil.toString(message)
  5249. })._addCheck({
  5250. kind: "max",
  5251. inclusive: true,
  5252. value: Number.MAX_SAFE_INTEGER,
  5253. message: errorUtil.toString(message)
  5254. });
  5255. }
  5256. get minValue() {
  5257. let min = null;
  5258. for (const ch of this._def.checks) {
  5259. if (ch.kind === "min") {
  5260. if (min === null || ch.value > min)
  5261. min = ch.value;
  5262. }
  5263. }
  5264. return min;
  5265. }
  5266. get maxValue() {
  5267. let max = null;
  5268. for (const ch of this._def.checks) {
  5269. if (ch.kind === "max") {
  5270. if (max === null || ch.value < max)
  5271. max = ch.value;
  5272. }
  5273. }
  5274. return max;
  5275. }
  5276. get isInt() {
  5277. return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  5278. }
  5279. get isFinite() {
  5280. let max = null;
  5281. let min = null;
  5282. for (const ch of this._def.checks) {
  5283. if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
  5284. return true;
  5285. } else if (ch.kind === "min") {
  5286. if (min === null || ch.value > min)
  5287. min = ch.value;
  5288. } else if (ch.kind === "max") {
  5289. if (max === null || ch.value < max)
  5290. max = ch.value;
  5291. }
  5292. }
  5293. return Number.isFinite(min) && Number.isFinite(max);
  5294. }
  5295. };
  5296. ZodNumber.create = (params) => {
  5297. return new ZodNumber({
  5298. checks: [],
  5299. typeName: ZodFirstPartyTypeKind.ZodNumber,
  5300. coerce: params?.coerce || false,
  5301. ...processCreateParams(params)
  5302. });
  5303. };
  5304. ZodBigInt = class _ZodBigInt extends ZodType {
  5305. constructor() {
  5306. super(...arguments);
  5307. this.min = this.gte;
  5308. this.max = this.lte;
  5309. }
  5310. _parse(input) {
  5311. if (this._def.coerce) {
  5312. try {
  5313. input.data = BigInt(input.data);
  5314. } catch {
  5315. return this._getInvalidInput(input);
  5316. }
  5317. }
  5318. const parsedType = this._getType(input);
  5319. if (parsedType !== ZodParsedType.bigint) {
  5320. return this._getInvalidInput(input);
  5321. }
  5322. let ctx = void 0;
  5323. const status = new ParseStatus();
  5324. for (const check of this._def.checks) {
  5325. if (check.kind === "min") {
  5326. const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
  5327. if (tooSmall) {
  5328. ctx = this._getOrReturnCtx(input, ctx);
  5329. addIssueToContext(ctx, {
  5330. code: ZodIssueCode.too_small,
  5331. type: "bigint",
  5332. minimum: check.value,
  5333. inclusive: check.inclusive,
  5334. message: check.message
  5335. });
  5336. status.dirty();
  5337. }
  5338. } else if (check.kind === "max") {
  5339. const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
  5340. if (tooBig) {
  5341. ctx = this._getOrReturnCtx(input, ctx);
  5342. addIssueToContext(ctx, {
  5343. code: ZodIssueCode.too_big,
  5344. type: "bigint",
  5345. maximum: check.value,
  5346. inclusive: check.inclusive,
  5347. message: check.message
  5348. });
  5349. status.dirty();
  5350. }
  5351. } else if (check.kind === "multipleOf") {
  5352. if (input.data % check.value !== BigInt(0)) {
  5353. ctx = this._getOrReturnCtx(input, ctx);
  5354. addIssueToContext(ctx, {
  5355. code: ZodIssueCode.not_multiple_of,
  5356. multipleOf: check.value,
  5357. message: check.message
  5358. });
  5359. status.dirty();
  5360. }
  5361. } else {
  5362. util.assertNever(check);
  5363. }
  5364. }
  5365. return { status: status.value, value: input.data };
  5366. }
  5367. _getInvalidInput(input) {
  5368. const ctx = this._getOrReturnCtx(input);
  5369. addIssueToContext(ctx, {
  5370. code: ZodIssueCode.invalid_type,
  5371. expected: ZodParsedType.bigint,
  5372. received: ctx.parsedType
  5373. });
  5374. return INVALID;
  5375. }
  5376. gte(value, message) {
  5377. return this.setLimit("min", value, true, errorUtil.toString(message));
  5378. }
  5379. gt(value, message) {
  5380. return this.setLimit("min", value, false, errorUtil.toString(message));
  5381. }
  5382. lte(value, message) {
  5383. return this.setLimit("max", value, true, errorUtil.toString(message));
  5384. }
  5385. lt(value, message) {
  5386. return this.setLimit("max", value, false, errorUtil.toString(message));
  5387. }
  5388. setLimit(kind, value, inclusive, message) {
  5389. return new _ZodBigInt({
  5390. ...this._def,
  5391. checks: [
  5392. ...this._def.checks,
  5393. {
  5394. kind,
  5395. value,
  5396. inclusive,
  5397. message: errorUtil.toString(message)
  5398. }
  5399. ]
  5400. });
  5401. }
  5402. _addCheck(check) {
  5403. return new _ZodBigInt({
  5404. ...this._def,
  5405. checks: [...this._def.checks, check]
  5406. });
  5407. }
  5408. positive(message) {
  5409. return this._addCheck({
  5410. kind: "min",
  5411. value: BigInt(0),
  5412. inclusive: false,
  5413. message: errorUtil.toString(message)
  5414. });
  5415. }
  5416. negative(message) {
  5417. return this._addCheck({
  5418. kind: "max",
  5419. value: BigInt(0),
  5420. inclusive: false,
  5421. message: errorUtil.toString(message)
  5422. });
  5423. }
  5424. nonpositive(message) {
  5425. return this._addCheck({
  5426. kind: "max",
  5427. value: BigInt(0),
  5428. inclusive: true,
  5429. message: errorUtil.toString(message)
  5430. });
  5431. }
  5432. nonnegative(message) {
  5433. return this._addCheck({
  5434. kind: "min",
  5435. value: BigInt(0),
  5436. inclusive: true,
  5437. message: errorUtil.toString(message)
  5438. });
  5439. }
  5440. multipleOf(value, message) {
  5441. return this._addCheck({
  5442. kind: "multipleOf",
  5443. value,
  5444. message: errorUtil.toString(message)
  5445. });
  5446. }
  5447. get minValue() {
  5448. let min = null;
  5449. for (const ch of this._def.checks) {
  5450. if (ch.kind === "min") {
  5451. if (min === null || ch.value > min)
  5452. min = ch.value;
  5453. }
  5454. }
  5455. return min;
  5456. }
  5457. get maxValue() {
  5458. let max = null;
  5459. for (const ch of this._def.checks) {
  5460. if (ch.kind === "max") {
  5461. if (max === null || ch.value < max)
  5462. max = ch.value;
  5463. }
  5464. }
  5465. return max;
  5466. }
  5467. };
  5468. ZodBigInt.create = (params) => {
  5469. return new ZodBigInt({
  5470. checks: [],
  5471. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  5472. coerce: params?.coerce ?? false,
  5473. ...processCreateParams(params)
  5474. });
  5475. };
  5476. ZodBoolean = class extends ZodType {
  5477. _parse(input) {
  5478. if (this._def.coerce) {
  5479. input.data = Boolean(input.data);
  5480. }
  5481. const parsedType = this._getType(input);
  5482. if (parsedType !== ZodParsedType.boolean) {
  5483. const ctx = this._getOrReturnCtx(input);
  5484. addIssueToContext(ctx, {
  5485. code: ZodIssueCode.invalid_type,
  5486. expected: ZodParsedType.boolean,
  5487. received: ctx.parsedType
  5488. });
  5489. return INVALID;
  5490. }
  5491. return OK(input.data);
  5492. }
  5493. };
  5494. ZodBoolean.create = (params) => {
  5495. return new ZodBoolean({
  5496. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  5497. coerce: params?.coerce || false,
  5498. ...processCreateParams(params)
  5499. });
  5500. };
  5501. ZodDate = class _ZodDate extends ZodType {
  5502. _parse(input) {
  5503. if (this._def.coerce) {
  5504. input.data = new Date(input.data);
  5505. }
  5506. const parsedType = this._getType(input);
  5507. if (parsedType !== ZodParsedType.date) {
  5508. const ctx2 = this._getOrReturnCtx(input);
  5509. addIssueToContext(ctx2, {
  5510. code: ZodIssueCode.invalid_type,
  5511. expected: ZodParsedType.date,
  5512. received: ctx2.parsedType
  5513. });
  5514. return INVALID;
  5515. }
  5516. if (Number.isNaN(input.data.getTime())) {
  5517. const ctx2 = this._getOrReturnCtx(input);
  5518. addIssueToContext(ctx2, {
  5519. code: ZodIssueCode.invalid_date
  5520. });
  5521. return INVALID;
  5522. }
  5523. const status = new ParseStatus();
  5524. let ctx = void 0;
  5525. for (const check of this._def.checks) {
  5526. if (check.kind === "min") {
  5527. if (input.data.getTime() < check.value) {
  5528. ctx = this._getOrReturnCtx(input, ctx);
  5529. addIssueToContext(ctx, {
  5530. code: ZodIssueCode.too_small,
  5531. message: check.message,
  5532. inclusive: true,
  5533. exact: false,
  5534. minimum: check.value,
  5535. type: "date"
  5536. });
  5537. status.dirty();
  5538. }
  5539. } else if (check.kind === "max") {
  5540. if (input.data.getTime() > check.value) {
  5541. ctx = this._getOrReturnCtx(input, ctx);
  5542. addIssueToContext(ctx, {
  5543. code: ZodIssueCode.too_big,
  5544. message: check.message,
  5545. inclusive: true,
  5546. exact: false,
  5547. maximum: check.value,
  5548. type: "date"
  5549. });
  5550. status.dirty();
  5551. }
  5552. } else {
  5553. util.assertNever(check);
  5554. }
  5555. }
  5556. return {
  5557. status: status.value,
  5558. value: new Date(input.data.getTime())
  5559. };
  5560. }
  5561. _addCheck(check) {
  5562. return new _ZodDate({
  5563. ...this._def,
  5564. checks: [...this._def.checks, check]
  5565. });
  5566. }
  5567. min(minDate, message) {
  5568. return this._addCheck({
  5569. kind: "min",
  5570. value: minDate.getTime(),
  5571. message: errorUtil.toString(message)
  5572. });
  5573. }
  5574. max(maxDate, message) {
  5575. return this._addCheck({
  5576. kind: "max",
  5577. value: maxDate.getTime(),
  5578. message: errorUtil.toString(message)
  5579. });
  5580. }
  5581. get minDate() {
  5582. let min = null;
  5583. for (const ch of this._def.checks) {
  5584. if (ch.kind === "min") {
  5585. if (min === null || ch.value > min)
  5586. min = ch.value;
  5587. }
  5588. }
  5589. return min != null ? new Date(min) : null;
  5590. }
  5591. get maxDate() {
  5592. let max = null;
  5593. for (const ch of this._def.checks) {
  5594. if (ch.kind === "max") {
  5595. if (max === null || ch.value < max)
  5596. max = ch.value;
  5597. }
  5598. }
  5599. return max != null ? new Date(max) : null;
  5600. }
  5601. };
  5602. ZodDate.create = (params) => {
  5603. return new ZodDate({
  5604. checks: [],
  5605. coerce: params?.coerce || false,
  5606. typeName: ZodFirstPartyTypeKind.ZodDate,
  5607. ...processCreateParams(params)
  5608. });
  5609. };
  5610. ZodSymbol = class extends ZodType {
  5611. _parse(input) {
  5612. const parsedType = this._getType(input);
  5613. if (parsedType !== ZodParsedType.symbol) {
  5614. const ctx = this._getOrReturnCtx(input);
  5615. addIssueToContext(ctx, {
  5616. code: ZodIssueCode.invalid_type,
  5617. expected: ZodParsedType.symbol,
  5618. received: ctx.parsedType
  5619. });
  5620. return INVALID;
  5621. }
  5622. return OK(input.data);
  5623. }
  5624. };
  5625. ZodSymbol.create = (params) => {
  5626. return new ZodSymbol({
  5627. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  5628. ...processCreateParams(params)
  5629. });
  5630. };
  5631. ZodUndefined = class extends ZodType {
  5632. _parse(input) {
  5633. const parsedType = this._getType(input);
  5634. if (parsedType !== ZodParsedType.undefined) {
  5635. const ctx = this._getOrReturnCtx(input);
  5636. addIssueToContext(ctx, {
  5637. code: ZodIssueCode.invalid_type,
  5638. expected: ZodParsedType.undefined,
  5639. received: ctx.parsedType
  5640. });
  5641. return INVALID;
  5642. }
  5643. return OK(input.data);
  5644. }
  5645. };
  5646. ZodUndefined.create = (params) => {
  5647. return new ZodUndefined({
  5648. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  5649. ...processCreateParams(params)
  5650. });
  5651. };
  5652. ZodNull = class extends ZodType {
  5653. _parse(input) {
  5654. const parsedType = this._getType(input);
  5655. if (parsedType !== ZodParsedType.null) {
  5656. const ctx = this._getOrReturnCtx(input);
  5657. addIssueToContext(ctx, {
  5658. code: ZodIssueCode.invalid_type,
  5659. expected: ZodParsedType.null,
  5660. received: ctx.parsedType
  5661. });
  5662. return INVALID;
  5663. }
  5664. return OK(input.data);
  5665. }
  5666. };
  5667. ZodNull.create = (params) => {
  5668. return new ZodNull({
  5669. typeName: ZodFirstPartyTypeKind.ZodNull,
  5670. ...processCreateParams(params)
  5671. });
  5672. };
  5673. ZodAny = class extends ZodType {
  5674. constructor() {
  5675. super(...arguments);
  5676. this._any = true;
  5677. }
  5678. _parse(input) {
  5679. return OK(input.data);
  5680. }
  5681. };
  5682. ZodAny.create = (params) => {
  5683. return new ZodAny({
  5684. typeName: ZodFirstPartyTypeKind.ZodAny,
  5685. ...processCreateParams(params)
  5686. });
  5687. };
  5688. ZodUnknown = class extends ZodType {
  5689. constructor() {
  5690. super(...arguments);
  5691. this._unknown = true;
  5692. }
  5693. _parse(input) {
  5694. return OK(input.data);
  5695. }
  5696. };
  5697. ZodUnknown.create = (params) => {
  5698. return new ZodUnknown({
  5699. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  5700. ...processCreateParams(params)
  5701. });
  5702. };
  5703. ZodNever = class extends ZodType {
  5704. _parse(input) {
  5705. const ctx = this._getOrReturnCtx(input);
  5706. addIssueToContext(ctx, {
  5707. code: ZodIssueCode.invalid_type,
  5708. expected: ZodParsedType.never,
  5709. received: ctx.parsedType
  5710. });
  5711. return INVALID;
  5712. }
  5713. };
  5714. ZodNever.create = (params) => {
  5715. return new ZodNever({
  5716. typeName: ZodFirstPartyTypeKind.ZodNever,
  5717. ...processCreateParams(params)
  5718. });
  5719. };
  5720. ZodVoid = class extends ZodType {
  5721. _parse(input) {
  5722. const parsedType = this._getType(input);
  5723. if (parsedType !== ZodParsedType.undefined) {
  5724. const ctx = this._getOrReturnCtx(input);
  5725. addIssueToContext(ctx, {
  5726. code: ZodIssueCode.invalid_type,
  5727. expected: ZodParsedType.void,
  5728. received: ctx.parsedType
  5729. });
  5730. return INVALID;
  5731. }
  5732. return OK(input.data);
  5733. }
  5734. };
  5735. ZodVoid.create = (params) => {
  5736. return new ZodVoid({
  5737. typeName: ZodFirstPartyTypeKind.ZodVoid,
  5738. ...processCreateParams(params)
  5739. });
  5740. };
  5741. ZodArray = class _ZodArray extends ZodType {
  5742. _parse(input) {
  5743. const { ctx, status } = this._processInputParams(input);
  5744. const def = this._def;
  5745. if (ctx.parsedType !== ZodParsedType.array) {
  5746. addIssueToContext(ctx, {
  5747. code: ZodIssueCode.invalid_type,
  5748. expected: ZodParsedType.array,
  5749. received: ctx.parsedType
  5750. });
  5751. return INVALID;
  5752. }
  5753. if (def.exactLength !== null) {
  5754. const tooBig = ctx.data.length > def.exactLength.value;
  5755. const tooSmall = ctx.data.length < def.exactLength.value;
  5756. if (tooBig || tooSmall) {
  5757. addIssueToContext(ctx, {
  5758. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  5759. minimum: tooSmall ? def.exactLength.value : void 0,
  5760. maximum: tooBig ? def.exactLength.value : void 0,
  5761. type: "array",
  5762. inclusive: true,
  5763. exact: true,
  5764. message: def.exactLength.message
  5765. });
  5766. status.dirty();
  5767. }
  5768. }
  5769. if (def.minLength !== null) {
  5770. if (ctx.data.length < def.minLength.value) {
  5771. addIssueToContext(ctx, {
  5772. code: ZodIssueCode.too_small,
  5773. minimum: def.minLength.value,
  5774. type: "array",
  5775. inclusive: true,
  5776. exact: false,
  5777. message: def.minLength.message
  5778. });
  5779. status.dirty();
  5780. }
  5781. }
  5782. if (def.maxLength !== null) {
  5783. if (ctx.data.length > def.maxLength.value) {
  5784. addIssueToContext(ctx, {
  5785. code: ZodIssueCode.too_big,
  5786. maximum: def.maxLength.value,
  5787. type: "array",
  5788. inclusive: true,
  5789. exact: false,
  5790. message: def.maxLength.message
  5791. });
  5792. status.dirty();
  5793. }
  5794. }
  5795. if (ctx.common.async) {
  5796. return Promise.all([...ctx.data].map((item, i6) => {
  5797. return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i6));
  5798. })).then((result2) => {
  5799. return ParseStatus.mergeArray(status, result2);
  5800. });
  5801. }
  5802. const result = [...ctx.data].map((item, i6) => {
  5803. return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i6));
  5804. });
  5805. return ParseStatus.mergeArray(status, result);
  5806. }
  5807. get element() {
  5808. return this._def.type;
  5809. }
  5810. min(minLength, message) {
  5811. return new _ZodArray({
  5812. ...this._def,
  5813. minLength: { value: minLength, message: errorUtil.toString(message) }
  5814. });
  5815. }
  5816. max(maxLength, message) {
  5817. return new _ZodArray({
  5818. ...this._def,
  5819. maxLength: { value: maxLength, message: errorUtil.toString(message) }
  5820. });
  5821. }
  5822. length(len, message) {
  5823. return new _ZodArray({
  5824. ...this._def,
  5825. exactLength: { value: len, message: errorUtil.toString(message) }
  5826. });
  5827. }
  5828. nonempty(message) {
  5829. return this.min(1, message);
  5830. }
  5831. };
  5832. ZodArray.create = (schema6, params) => {
  5833. return new ZodArray({
  5834. type: schema6,
  5835. minLength: null,
  5836. maxLength: null,
  5837. exactLength: null,
  5838. typeName: ZodFirstPartyTypeKind.ZodArray,
  5839. ...processCreateParams(params)
  5840. });
  5841. };
  5842. ZodObject = class _ZodObject extends ZodType {
  5843. constructor() {
  5844. super(...arguments);
  5845. this._cached = null;
  5846. this.nonstrict = this.passthrough;
  5847. this.augment = this.extend;
  5848. }
  5849. _getCached() {
  5850. if (this._cached !== null)
  5851. return this._cached;
  5852. const shape = this._def.shape();
  5853. const keys = util.objectKeys(shape);
  5854. this._cached = { shape, keys };
  5855. return this._cached;
  5856. }
  5857. _parse(input) {
  5858. const parsedType = this._getType(input);
  5859. if (parsedType !== ZodParsedType.object) {
  5860. const ctx2 = this._getOrReturnCtx(input);
  5861. addIssueToContext(ctx2, {
  5862. code: ZodIssueCode.invalid_type,
  5863. expected: ZodParsedType.object,
  5864. received: ctx2.parsedType
  5865. });
  5866. return INVALID;
  5867. }
  5868. const { status, ctx } = this._processInputParams(input);
  5869. const { shape, keys: shapeKeys } = this._getCached();
  5870. const extraKeys = [];
  5871. if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
  5872. for (const key in ctx.data) {
  5873. if (!shapeKeys.includes(key)) {
  5874. extraKeys.push(key);
  5875. }
  5876. }
  5877. }
  5878. const pairs = [];
  5879. for (const key of shapeKeys) {
  5880. const keyValidator = shape[key];
  5881. const value = ctx.data[key];
  5882. pairs.push({
  5883. key: { status: "valid", value: key },
  5884. value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
  5885. alwaysSet: key in ctx.data
  5886. });
  5887. }
  5888. if (this._def.catchall instanceof ZodNever) {
  5889. const unknownKeys = this._def.unknownKeys;
  5890. if (unknownKeys === "passthrough") {
  5891. for (const key of extraKeys) {
  5892. pairs.push({
  5893. key: { status: "valid", value: key },
  5894. value: { status: "valid", value: ctx.data[key] }
  5895. });
  5896. }
  5897. } else if (unknownKeys === "strict") {
  5898. if (extraKeys.length > 0) {
  5899. addIssueToContext(ctx, {
  5900. code: ZodIssueCode.unrecognized_keys,
  5901. keys: extraKeys
  5902. });
  5903. status.dirty();
  5904. }
  5905. } else if (unknownKeys === "strip") {
  5906. } else {
  5907. throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
  5908. }
  5909. } else {
  5910. const catchall = this._def.catchall;
  5911. for (const key of extraKeys) {
  5912. const value = ctx.data[key];
  5913. pairs.push({
  5914. key: { status: "valid", value: key },
  5915. value: catchall._parse(
  5916. new ParseInputLazyPath(ctx, value, ctx.path, key)
  5917. //, ctx.child(key), value, getParsedType(value)
  5918. ),
  5919. alwaysSet: key in ctx.data
  5920. });
  5921. }
  5922. }
  5923. if (ctx.common.async) {
  5924. return Promise.resolve().then(async () => {
  5925. const syncPairs = [];
  5926. for (const pair of pairs) {
  5927. const key = await pair.key;
  5928. const value = await pair.value;
  5929. syncPairs.push({
  5930. key,
  5931. value,
  5932. alwaysSet: pair.alwaysSet
  5933. });
  5934. }
  5935. return syncPairs;
  5936. }).then((syncPairs) => {
  5937. return ParseStatus.mergeObjectSync(status, syncPairs);
  5938. });
  5939. } else {
  5940. return ParseStatus.mergeObjectSync(status, pairs);
  5941. }
  5942. }
  5943. get shape() {
  5944. return this._def.shape();
  5945. }
  5946. strict(message) {
  5947. errorUtil.errToObj;
  5948. return new _ZodObject({
  5949. ...this._def,
  5950. unknownKeys: "strict",
  5951. ...message !== void 0 ? {
  5952. errorMap: (issue, ctx) => {
  5953. const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
  5954. if (issue.code === "unrecognized_keys")
  5955. return {
  5956. message: errorUtil.errToObj(message).message ?? defaultError
  5957. };
  5958. return {
  5959. message: defaultError
  5960. };
  5961. }
  5962. } : {}
  5963. });
  5964. }
  5965. strip() {
  5966. return new _ZodObject({
  5967. ...this._def,
  5968. unknownKeys: "strip"
  5969. });
  5970. }
  5971. passthrough() {
  5972. return new _ZodObject({
  5973. ...this._def,
  5974. unknownKeys: "passthrough"
  5975. });
  5976. }
  5977. // const AugmentFactory =
  5978. // <Def extends ZodObjectDef>(def: Def) =>
  5979. // <Augmentation extends ZodRawShape>(
  5980. // augmentation: Augmentation
  5981. // ): ZodObject<
  5982. // extendShape<ReturnType<Def["shape"]>, Augmentation>,
  5983. // Def["unknownKeys"],
  5984. // Def["catchall"]
  5985. // > => {
  5986. // return new ZodObject({
  5987. // ...def,
  5988. // shape: () => ({
  5989. // ...def.shape(),
  5990. // ...augmentation,
  5991. // }),
  5992. // }) as any;
  5993. // };
  5994. extend(augmentation) {
  5995. return new _ZodObject({
  5996. ...this._def,
  5997. shape: () => ({
  5998. ...this._def.shape(),
  5999. ...augmentation
  6000. })
  6001. });
  6002. }
  6003. /**
  6004. * Prior to zod@1.0.12 there was a bug in the
  6005. * inferred type of merged objects. Please
  6006. * upgrade if you are experiencing issues.
  6007. */
  6008. merge(merging) {
  6009. const merged = new _ZodObject({
  6010. unknownKeys: merging._def.unknownKeys,
  6011. catchall: merging._def.catchall,
  6012. shape: () => ({
  6013. ...this._def.shape(),
  6014. ...merging._def.shape()
  6015. }),
  6016. typeName: ZodFirstPartyTypeKind.ZodObject
  6017. });
  6018. return merged;
  6019. }
  6020. // merge<
  6021. // Incoming extends AnyZodObject,
  6022. // Augmentation extends Incoming["shape"],
  6023. // NewOutput extends {
  6024. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  6025. // ? Augmentation[k]["_output"]
  6026. // : k extends keyof Output
  6027. // ? Output[k]
  6028. // : never;
  6029. // },
  6030. // NewInput extends {
  6031. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  6032. // ? Augmentation[k]["_input"]
  6033. // : k extends keyof Input
  6034. // ? Input[k]
  6035. // : never;
  6036. // }
  6037. // >(
  6038. // merging: Incoming
  6039. // ): ZodObject<
  6040. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  6041. // Incoming["_def"]["unknownKeys"],
  6042. // Incoming["_def"]["catchall"],
  6043. // NewOutput,
  6044. // NewInput
  6045. // > {
  6046. // const merged: any = new ZodObject({
  6047. // unknownKeys: merging._def.unknownKeys,
  6048. // catchall: merging._def.catchall,
  6049. // shape: () =>
  6050. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  6051. // typeName: ZodFirstPartyTypeKind.ZodObject,
  6052. // }) as any;
  6053. // return merged;
  6054. // }
  6055. setKey(key, schema6) {
  6056. return this.augment({ [key]: schema6 });
  6057. }
  6058. // merge<Incoming extends AnyZodObject>(
  6059. // merging: Incoming
  6060. // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  6061. // ZodObject<
  6062. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  6063. // Incoming["_def"]["unknownKeys"],
  6064. // Incoming["_def"]["catchall"]
  6065. // > {
  6066. // // const mergedShape = objectUtil.mergeShapes(
  6067. // // this._def.shape(),
  6068. // // merging._def.shape()
  6069. // // );
  6070. // const merged: any = new ZodObject({
  6071. // unknownKeys: merging._def.unknownKeys,
  6072. // catchall: merging._def.catchall,
  6073. // shape: () =>
  6074. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  6075. // typeName: ZodFirstPartyTypeKind.ZodObject,
  6076. // }) as any;
  6077. // return merged;
  6078. // }
  6079. catchall(index6) {
  6080. return new _ZodObject({
  6081. ...this._def,
  6082. catchall: index6
  6083. });
  6084. }
  6085. pick(mask) {
  6086. const shape = {};
  6087. for (const key of util.objectKeys(mask)) {
  6088. if (mask[key] && this.shape[key]) {
  6089. shape[key] = this.shape[key];
  6090. }
  6091. }
  6092. return new _ZodObject({
  6093. ...this._def,
  6094. shape: () => shape
  6095. });
  6096. }
  6097. omit(mask) {
  6098. const shape = {};
  6099. for (const key of util.objectKeys(this.shape)) {
  6100. if (!mask[key]) {
  6101. shape[key] = this.shape[key];
  6102. }
  6103. }
  6104. return new _ZodObject({
  6105. ...this._def,
  6106. shape: () => shape
  6107. });
  6108. }
  6109. /**
  6110. * @deprecated
  6111. */
  6112. deepPartial() {
  6113. return deepPartialify(this);
  6114. }
  6115. partial(mask) {
  6116. const newShape = {};
  6117. for (const key of util.objectKeys(this.shape)) {
  6118. const fieldSchema = this.shape[key];
  6119. if (mask && !mask[key]) {
  6120. newShape[key] = fieldSchema;
  6121. } else {
  6122. newShape[key] = fieldSchema.optional();
  6123. }
  6124. }
  6125. return new _ZodObject({
  6126. ...this._def,
  6127. shape: () => newShape
  6128. });
  6129. }
  6130. required(mask) {
  6131. const newShape = {};
  6132. for (const key of util.objectKeys(this.shape)) {
  6133. if (mask && !mask[key]) {
  6134. newShape[key] = this.shape[key];
  6135. } else {
  6136. const fieldSchema = this.shape[key];
  6137. let newField = fieldSchema;
  6138. while (newField instanceof ZodOptional) {
  6139. newField = newField._def.innerType;
  6140. }
  6141. newShape[key] = newField;
  6142. }
  6143. }
  6144. return new _ZodObject({
  6145. ...this._def,
  6146. shape: () => newShape
  6147. });
  6148. }
  6149. keyof() {
  6150. return createZodEnum(util.objectKeys(this.shape));
  6151. }
  6152. };
  6153. ZodObject.create = (shape, params) => {
  6154. return new ZodObject({
  6155. shape: () => shape,
  6156. unknownKeys: "strip",
  6157. catchall: ZodNever.create(),
  6158. typeName: ZodFirstPartyTypeKind.ZodObject,
  6159. ...processCreateParams(params)
  6160. });
  6161. };
  6162. ZodObject.strictCreate = (shape, params) => {
  6163. return new ZodObject({
  6164. shape: () => shape,
  6165. unknownKeys: "strict",
  6166. catchall: ZodNever.create(),
  6167. typeName: ZodFirstPartyTypeKind.ZodObject,
  6168. ...processCreateParams(params)
  6169. });
  6170. };
  6171. ZodObject.lazycreate = (shape, params) => {
  6172. return new ZodObject({
  6173. shape,
  6174. unknownKeys: "strip",
  6175. catchall: ZodNever.create(),
  6176. typeName: ZodFirstPartyTypeKind.ZodObject,
  6177. ...processCreateParams(params)
  6178. });
  6179. };
  6180. ZodUnion = class extends ZodType {
  6181. _parse(input) {
  6182. const { ctx } = this._processInputParams(input);
  6183. const options = this._def.options;
  6184. function handleResults(results) {
  6185. for (const result of results) {
  6186. if (result.result.status === "valid") {
  6187. return result.result;
  6188. }
  6189. }
  6190. for (const result of results) {
  6191. if (result.result.status === "dirty") {
  6192. ctx.common.issues.push(...result.ctx.common.issues);
  6193. return result.result;
  6194. }
  6195. }
  6196. const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
  6197. addIssueToContext(ctx, {
  6198. code: ZodIssueCode.invalid_union,
  6199. unionErrors
  6200. });
  6201. return INVALID;
  6202. }
  6203. if (ctx.common.async) {
  6204. return Promise.all(options.map(async (option) => {
  6205. const childCtx = {
  6206. ...ctx,
  6207. common: {
  6208. ...ctx.common,
  6209. issues: []
  6210. },
  6211. parent: null
  6212. };
  6213. return {
  6214. result: await option._parseAsync({
  6215. data: ctx.data,
  6216. path: ctx.path,
  6217. parent: childCtx
  6218. }),
  6219. ctx: childCtx
  6220. };
  6221. })).then(handleResults);
  6222. } else {
  6223. let dirty = void 0;
  6224. const issues = [];
  6225. for (const option of options) {
  6226. const childCtx = {
  6227. ...ctx,
  6228. common: {
  6229. ...ctx.common,
  6230. issues: []
  6231. },
  6232. parent: null
  6233. };
  6234. const result = option._parseSync({
  6235. data: ctx.data,
  6236. path: ctx.path,
  6237. parent: childCtx
  6238. });
  6239. if (result.status === "valid") {
  6240. return result;
  6241. } else if (result.status === "dirty" && !dirty) {
  6242. dirty = { result, ctx: childCtx };
  6243. }
  6244. if (childCtx.common.issues.length) {
  6245. issues.push(childCtx.common.issues);
  6246. }
  6247. }
  6248. if (dirty) {
  6249. ctx.common.issues.push(...dirty.ctx.common.issues);
  6250. return dirty.result;
  6251. }
  6252. const unionErrors = issues.map((issues2) => new ZodError(issues2));
  6253. addIssueToContext(ctx, {
  6254. code: ZodIssueCode.invalid_union,
  6255. unionErrors
  6256. });
  6257. return INVALID;
  6258. }
  6259. }
  6260. get options() {
  6261. return this._def.options;
  6262. }
  6263. };
  6264. ZodUnion.create = (types3, params) => {
  6265. return new ZodUnion({
  6266. options: types3,
  6267. typeName: ZodFirstPartyTypeKind.ZodUnion,
  6268. ...processCreateParams(params)
  6269. });
  6270. };
  6271. getDiscriminator = (type) => {
  6272. if (type instanceof ZodLazy) {
  6273. return getDiscriminator(type.schema);
  6274. } else if (type instanceof ZodEffects) {
  6275. return getDiscriminator(type.innerType());
  6276. } else if (type instanceof ZodLiteral) {
  6277. return [type.value];
  6278. } else if (type instanceof ZodEnum) {
  6279. return type.options;
  6280. } else if (type instanceof ZodNativeEnum) {
  6281. return util.objectValues(type.enum);
  6282. } else if (type instanceof ZodDefault) {
  6283. return getDiscriminator(type._def.innerType);
  6284. } else if (type instanceof ZodUndefined) {
  6285. return [void 0];
  6286. } else if (type instanceof ZodNull) {
  6287. return [null];
  6288. } else if (type instanceof ZodOptional) {
  6289. return [void 0, ...getDiscriminator(type.unwrap())];
  6290. } else if (type instanceof ZodNullable) {
  6291. return [null, ...getDiscriminator(type.unwrap())];
  6292. } else if (type instanceof ZodBranded) {
  6293. return getDiscriminator(type.unwrap());
  6294. } else if (type instanceof ZodReadonly) {
  6295. return getDiscriminator(type.unwrap());
  6296. } else if (type instanceof ZodCatch) {
  6297. return getDiscriminator(type._def.innerType);
  6298. } else {
  6299. return [];
  6300. }
  6301. };
  6302. ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
  6303. _parse(input) {
  6304. const { ctx } = this._processInputParams(input);
  6305. if (ctx.parsedType !== ZodParsedType.object) {
  6306. addIssueToContext(ctx, {
  6307. code: ZodIssueCode.invalid_type,
  6308. expected: ZodParsedType.object,
  6309. received: ctx.parsedType
  6310. });
  6311. return INVALID;
  6312. }
  6313. const discriminator = this.discriminator;
  6314. const discriminatorValue = ctx.data[discriminator];
  6315. const option = this.optionsMap.get(discriminatorValue);
  6316. if (!option) {
  6317. addIssueToContext(ctx, {
  6318. code: ZodIssueCode.invalid_union_discriminator,
  6319. options: Array.from(this.optionsMap.keys()),
  6320. path: [discriminator]
  6321. });
  6322. return INVALID;
  6323. }
  6324. if (ctx.common.async) {
  6325. return option._parseAsync({
  6326. data: ctx.data,
  6327. path: ctx.path,
  6328. parent: ctx
  6329. });
  6330. } else {
  6331. return option._parseSync({
  6332. data: ctx.data,
  6333. path: ctx.path,
  6334. parent: ctx
  6335. });
  6336. }
  6337. }
  6338. get discriminator() {
  6339. return this._def.discriminator;
  6340. }
  6341. get options() {
  6342. return this._def.options;
  6343. }
  6344. get optionsMap() {
  6345. return this._def.optionsMap;
  6346. }
  6347. /**
  6348. * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
  6349. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
  6350. * have a different value for each object in the union.
  6351. * @param discriminator the name of the discriminator property
  6352. * @param types an array of object schemas
  6353. * @param params
  6354. */
  6355. static create(discriminator, options, params) {
  6356. const optionsMap = /* @__PURE__ */ new Map();
  6357. for (const type of options) {
  6358. const discriminatorValues = getDiscriminator(type.shape[discriminator]);
  6359. if (!discriminatorValues.length) {
  6360. throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
  6361. }
  6362. for (const value of discriminatorValues) {
  6363. if (optionsMap.has(value)) {
  6364. throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
  6365. }
  6366. optionsMap.set(value, type);
  6367. }
  6368. }
  6369. return new _ZodDiscriminatedUnion({
  6370. typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  6371. discriminator,
  6372. options,
  6373. optionsMap,
  6374. ...processCreateParams(params)
  6375. });
  6376. }
  6377. };
  6378. ZodIntersection = class extends ZodType {
  6379. _parse(input) {
  6380. const { status, ctx } = this._processInputParams(input);
  6381. const handleParsed = (parsedLeft, parsedRight) => {
  6382. if (isAborted(parsedLeft) || isAborted(parsedRight)) {
  6383. return INVALID;
  6384. }
  6385. const merged = mergeValues(parsedLeft.value, parsedRight.value);
  6386. if (!merged.valid) {
  6387. addIssueToContext(ctx, {
  6388. code: ZodIssueCode.invalid_intersection_types
  6389. });
  6390. return INVALID;
  6391. }
  6392. if (isDirty(parsedLeft) || isDirty(parsedRight)) {
  6393. status.dirty();
  6394. }
  6395. return { status: status.value, value: merged.data };
  6396. };
  6397. if (ctx.common.async) {
  6398. return Promise.all([
  6399. this._def.left._parseAsync({
  6400. data: ctx.data,
  6401. path: ctx.path,
  6402. parent: ctx
  6403. }),
  6404. this._def.right._parseAsync({
  6405. data: ctx.data,
  6406. path: ctx.path,
  6407. parent: ctx
  6408. })
  6409. ]).then(([left, right]) => handleParsed(left, right));
  6410. } else {
  6411. return handleParsed(this._def.left._parseSync({
  6412. data: ctx.data,
  6413. path: ctx.path,
  6414. parent: ctx
  6415. }), this._def.right._parseSync({
  6416. data: ctx.data,
  6417. path: ctx.path,
  6418. parent: ctx
  6419. }));
  6420. }
  6421. }
  6422. };
  6423. ZodIntersection.create = (left, right, params) => {
  6424. return new ZodIntersection({
  6425. left,
  6426. right,
  6427. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  6428. ...processCreateParams(params)
  6429. });
  6430. };
  6431. ZodTuple = class _ZodTuple extends ZodType {
  6432. _parse(input) {
  6433. const { status, ctx } = this._processInputParams(input);
  6434. if (ctx.parsedType !== ZodParsedType.array) {
  6435. addIssueToContext(ctx, {
  6436. code: ZodIssueCode.invalid_type,
  6437. expected: ZodParsedType.array,
  6438. received: ctx.parsedType
  6439. });
  6440. return INVALID;
  6441. }
  6442. if (ctx.data.length < this._def.items.length) {
  6443. addIssueToContext(ctx, {
  6444. code: ZodIssueCode.too_small,
  6445. minimum: this._def.items.length,
  6446. inclusive: true,
  6447. exact: false,
  6448. type: "array"
  6449. });
  6450. return INVALID;
  6451. }
  6452. const rest = this._def.rest;
  6453. if (!rest && ctx.data.length > this._def.items.length) {
  6454. addIssueToContext(ctx, {
  6455. code: ZodIssueCode.too_big,
  6456. maximum: this._def.items.length,
  6457. inclusive: true,
  6458. exact: false,
  6459. type: "array"
  6460. });
  6461. status.dirty();
  6462. }
  6463. const items = [...ctx.data].map((item, itemIndex) => {
  6464. const schema6 = this._def.items[itemIndex] || this._def.rest;
  6465. if (!schema6)
  6466. return null;
  6467. return schema6._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
  6468. }).filter((x5) => !!x5);
  6469. if (ctx.common.async) {
  6470. return Promise.all(items).then((results) => {
  6471. return ParseStatus.mergeArray(status, results);
  6472. });
  6473. } else {
  6474. return ParseStatus.mergeArray(status, items);
  6475. }
  6476. }
  6477. get items() {
  6478. return this._def.items;
  6479. }
  6480. rest(rest) {
  6481. return new _ZodTuple({
  6482. ...this._def,
  6483. rest
  6484. });
  6485. }
  6486. };
  6487. ZodTuple.create = (schemas, params) => {
  6488. if (!Array.isArray(schemas)) {
  6489. throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  6490. }
  6491. return new ZodTuple({
  6492. items: schemas,
  6493. typeName: ZodFirstPartyTypeKind.ZodTuple,
  6494. rest: null,
  6495. ...processCreateParams(params)
  6496. });
  6497. };
  6498. ZodRecord = class _ZodRecord extends ZodType {
  6499. get keySchema() {
  6500. return this._def.keyType;
  6501. }
  6502. get valueSchema() {
  6503. return this._def.valueType;
  6504. }
  6505. _parse(input) {
  6506. const { status, ctx } = this._processInputParams(input);
  6507. if (ctx.parsedType !== ZodParsedType.object) {
  6508. addIssueToContext(ctx, {
  6509. code: ZodIssueCode.invalid_type,
  6510. expected: ZodParsedType.object,
  6511. received: ctx.parsedType
  6512. });
  6513. return INVALID;
  6514. }
  6515. const pairs = [];
  6516. const keyType = this._def.keyType;
  6517. const valueType = this._def.valueType;
  6518. for (const key in ctx.data) {
  6519. pairs.push({
  6520. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
  6521. value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
  6522. alwaysSet: key in ctx.data
  6523. });
  6524. }
  6525. if (ctx.common.async) {
  6526. return ParseStatus.mergeObjectAsync(status, pairs);
  6527. } else {
  6528. return ParseStatus.mergeObjectSync(status, pairs);
  6529. }
  6530. }
  6531. get element() {
  6532. return this._def.valueType;
  6533. }
  6534. static create(first, second, third) {
  6535. if (second instanceof ZodType) {
  6536. return new _ZodRecord({
  6537. keyType: first,
  6538. valueType: second,
  6539. typeName: ZodFirstPartyTypeKind.ZodRecord,
  6540. ...processCreateParams(third)
  6541. });
  6542. }
  6543. return new _ZodRecord({
  6544. keyType: ZodString.create(),
  6545. valueType: first,
  6546. typeName: ZodFirstPartyTypeKind.ZodRecord,
  6547. ...processCreateParams(second)
  6548. });
  6549. }
  6550. };
  6551. ZodMap = class extends ZodType {
  6552. get keySchema() {
  6553. return this._def.keyType;
  6554. }
  6555. get valueSchema() {
  6556. return this._def.valueType;
  6557. }
  6558. _parse(input) {
  6559. const { status, ctx } = this._processInputParams(input);
  6560. if (ctx.parsedType !== ZodParsedType.map) {
  6561. addIssueToContext(ctx, {
  6562. code: ZodIssueCode.invalid_type,
  6563. expected: ZodParsedType.map,
  6564. received: ctx.parsedType
  6565. });
  6566. return INVALID;
  6567. }
  6568. const keyType = this._def.keyType;
  6569. const valueType = this._def.valueType;
  6570. const pairs = [...ctx.data.entries()].map(([key, value], index6) => {
  6571. return {
  6572. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])),
  6573. value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"]))
  6574. };
  6575. });
  6576. if (ctx.common.async) {
  6577. const finalMap = /* @__PURE__ */ new Map();
  6578. return Promise.resolve().then(async () => {
  6579. for (const pair of pairs) {
  6580. const key = await pair.key;
  6581. const value = await pair.value;
  6582. if (key.status === "aborted" || value.status === "aborted") {
  6583. return INVALID;
  6584. }
  6585. if (key.status === "dirty" || value.status === "dirty") {
  6586. status.dirty();
  6587. }
  6588. finalMap.set(key.value, value.value);
  6589. }
  6590. return { status: status.value, value: finalMap };
  6591. });
  6592. } else {
  6593. const finalMap = /* @__PURE__ */ new Map();
  6594. for (const pair of pairs) {
  6595. const key = pair.key;
  6596. const value = pair.value;
  6597. if (key.status === "aborted" || value.status === "aborted") {
  6598. return INVALID;
  6599. }
  6600. if (key.status === "dirty" || value.status === "dirty") {
  6601. status.dirty();
  6602. }
  6603. finalMap.set(key.value, value.value);
  6604. }
  6605. return { status: status.value, value: finalMap };
  6606. }
  6607. }
  6608. };
  6609. ZodMap.create = (keyType, valueType, params) => {
  6610. return new ZodMap({
  6611. valueType,
  6612. keyType,
  6613. typeName: ZodFirstPartyTypeKind.ZodMap,
  6614. ...processCreateParams(params)
  6615. });
  6616. };
  6617. ZodSet = class _ZodSet extends ZodType {
  6618. _parse(input) {
  6619. const { status, ctx } = this._processInputParams(input);
  6620. if (ctx.parsedType !== ZodParsedType.set) {
  6621. addIssueToContext(ctx, {
  6622. code: ZodIssueCode.invalid_type,
  6623. expected: ZodParsedType.set,
  6624. received: ctx.parsedType
  6625. });
  6626. return INVALID;
  6627. }
  6628. const def = this._def;
  6629. if (def.minSize !== null) {
  6630. if (ctx.data.size < def.minSize.value) {
  6631. addIssueToContext(ctx, {
  6632. code: ZodIssueCode.too_small,
  6633. minimum: def.minSize.value,
  6634. type: "set",
  6635. inclusive: true,
  6636. exact: false,
  6637. message: def.minSize.message
  6638. });
  6639. status.dirty();
  6640. }
  6641. }
  6642. if (def.maxSize !== null) {
  6643. if (ctx.data.size > def.maxSize.value) {
  6644. addIssueToContext(ctx, {
  6645. code: ZodIssueCode.too_big,
  6646. maximum: def.maxSize.value,
  6647. type: "set",
  6648. inclusive: true,
  6649. exact: false,
  6650. message: def.maxSize.message
  6651. });
  6652. status.dirty();
  6653. }
  6654. }
  6655. const valueType = this._def.valueType;
  6656. function finalizeSet(elements2) {
  6657. const parsedSet = /* @__PURE__ */ new Set();
  6658. for (const element of elements2) {
  6659. if (element.status === "aborted")
  6660. return INVALID;
  6661. if (element.status === "dirty")
  6662. status.dirty();
  6663. parsedSet.add(element.value);
  6664. }
  6665. return { status: status.value, value: parsedSet };
  6666. }
  6667. const elements = [...ctx.data.values()].map((item, i6) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i6)));
  6668. if (ctx.common.async) {
  6669. return Promise.all(elements).then((elements2) => finalizeSet(elements2));
  6670. } else {
  6671. return finalizeSet(elements);
  6672. }
  6673. }
  6674. min(minSize, message) {
  6675. return new _ZodSet({
  6676. ...this._def,
  6677. minSize: { value: minSize, message: errorUtil.toString(message) }
  6678. });
  6679. }
  6680. max(maxSize, message) {
  6681. return new _ZodSet({
  6682. ...this._def,
  6683. maxSize: { value: maxSize, message: errorUtil.toString(message) }
  6684. });
  6685. }
  6686. size(size, message) {
  6687. return this.min(size, message).max(size, message);
  6688. }
  6689. nonempty(message) {
  6690. return this.min(1, message);
  6691. }
  6692. };
  6693. ZodSet.create = (valueType, params) => {
  6694. return new ZodSet({
  6695. valueType,
  6696. minSize: null,
  6697. maxSize: null,
  6698. typeName: ZodFirstPartyTypeKind.ZodSet,
  6699. ...processCreateParams(params)
  6700. });
  6701. };
  6702. ZodFunction = class _ZodFunction extends ZodType {
  6703. constructor() {
  6704. super(...arguments);
  6705. this.validate = this.implement;
  6706. }
  6707. _parse(input) {
  6708. const { ctx } = this._processInputParams(input);
  6709. if (ctx.parsedType !== ZodParsedType.function) {
  6710. addIssueToContext(ctx, {
  6711. code: ZodIssueCode.invalid_type,
  6712. expected: ZodParsedType.function,
  6713. received: ctx.parsedType
  6714. });
  6715. return INVALID;
  6716. }
  6717. function makeArgsIssue(args, error2) {
  6718. return makeIssue({
  6719. data: args,
  6720. path: ctx.path,
  6721. errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5),
  6722. issueData: {
  6723. code: ZodIssueCode.invalid_arguments,
  6724. argumentsError: error2
  6725. }
  6726. });
  6727. }
  6728. function makeReturnsIssue(returns, error2) {
  6729. return makeIssue({
  6730. data: returns,
  6731. path: ctx.path,
  6732. errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5),
  6733. issueData: {
  6734. code: ZodIssueCode.invalid_return_type,
  6735. returnTypeError: error2
  6736. }
  6737. });
  6738. }
  6739. const params = { errorMap: ctx.common.contextualErrorMap };
  6740. const fn = ctx.data;
  6741. if (this._def.returns instanceof ZodPromise) {
  6742. const me = this;
  6743. return OK(async function(...args) {
  6744. const error2 = new ZodError([]);
  6745. const parsedArgs = await me._def.args.parseAsync(args, params).catch((e6) => {
  6746. error2.addIssue(makeArgsIssue(args, e6));
  6747. throw error2;
  6748. });
  6749. const result = await Reflect.apply(fn, this, parsedArgs);
  6750. const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e6) => {
  6751. error2.addIssue(makeReturnsIssue(result, e6));
  6752. throw error2;
  6753. });
  6754. return parsedReturns;
  6755. });
  6756. } else {
  6757. const me = this;
  6758. return OK(function(...args) {
  6759. const parsedArgs = me._def.args.safeParse(args, params);
  6760. if (!parsedArgs.success) {
  6761. throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
  6762. }
  6763. const result = Reflect.apply(fn, this, parsedArgs.data);
  6764. const parsedReturns = me._def.returns.safeParse(result, params);
  6765. if (!parsedReturns.success) {
  6766. throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
  6767. }
  6768. return parsedReturns.data;
  6769. });
  6770. }
  6771. }
  6772. parameters() {
  6773. return this._def.args;
  6774. }
  6775. returnType() {
  6776. return this._def.returns;
  6777. }
  6778. args(...items) {
  6779. return new _ZodFunction({
  6780. ...this._def,
  6781. args: ZodTuple.create(items).rest(ZodUnknown.create())
  6782. });
  6783. }
  6784. returns(returnType) {
  6785. return new _ZodFunction({
  6786. ...this._def,
  6787. returns: returnType
  6788. });
  6789. }
  6790. implement(func) {
  6791. const validatedFunc = this.parse(func);
  6792. return validatedFunc;
  6793. }
  6794. strictImplement(func) {
  6795. const validatedFunc = this.parse(func);
  6796. return validatedFunc;
  6797. }
  6798. static create(args, returns, params) {
  6799. return new _ZodFunction({
  6800. args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
  6801. returns: returns || ZodUnknown.create(),
  6802. typeName: ZodFirstPartyTypeKind.ZodFunction,
  6803. ...processCreateParams(params)
  6804. });
  6805. }
  6806. };
  6807. ZodLazy = class extends ZodType {
  6808. get schema() {
  6809. return this._def.getter();
  6810. }
  6811. _parse(input) {
  6812. const { ctx } = this._processInputParams(input);
  6813. const lazySchema = this._def.getter();
  6814. return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  6815. }
  6816. };
  6817. ZodLazy.create = (getter, params) => {
  6818. return new ZodLazy({
  6819. getter,
  6820. typeName: ZodFirstPartyTypeKind.ZodLazy,
  6821. ...processCreateParams(params)
  6822. });
  6823. };
  6824. ZodLiteral = class extends ZodType {
  6825. _parse(input) {
  6826. if (input.data !== this._def.value) {
  6827. const ctx = this._getOrReturnCtx(input);
  6828. addIssueToContext(ctx, {
  6829. received: ctx.data,
  6830. code: ZodIssueCode.invalid_literal,
  6831. expected: this._def.value
  6832. });
  6833. return INVALID;
  6834. }
  6835. return { status: "valid", value: input.data };
  6836. }
  6837. get value() {
  6838. return this._def.value;
  6839. }
  6840. };
  6841. ZodLiteral.create = (value, params) => {
  6842. return new ZodLiteral({
  6843. value,
  6844. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  6845. ...processCreateParams(params)
  6846. });
  6847. };
  6848. ZodEnum = class _ZodEnum extends ZodType {
  6849. _parse(input) {
  6850. if (typeof input.data !== "string") {
  6851. const ctx = this._getOrReturnCtx(input);
  6852. const expectedValues = this._def.values;
  6853. addIssueToContext(ctx, {
  6854. expected: util.joinValues(expectedValues),
  6855. received: ctx.parsedType,
  6856. code: ZodIssueCode.invalid_type
  6857. });
  6858. return INVALID;
  6859. }
  6860. if (!this._cache) {
  6861. this._cache = new Set(this._def.values);
  6862. }
  6863. if (!this._cache.has(input.data)) {
  6864. const ctx = this._getOrReturnCtx(input);
  6865. const expectedValues = this._def.values;
  6866. addIssueToContext(ctx, {
  6867. received: ctx.data,
  6868. code: ZodIssueCode.invalid_enum_value,
  6869. options: expectedValues
  6870. });
  6871. return INVALID;
  6872. }
  6873. return OK(input.data);
  6874. }
  6875. get options() {
  6876. return this._def.values;
  6877. }
  6878. get enum() {
  6879. const enumValues = {};
  6880. for (const val2 of this._def.values) {
  6881. enumValues[val2] = val2;
  6882. }
  6883. return enumValues;
  6884. }
  6885. get Values() {
  6886. const enumValues = {};
  6887. for (const val2 of this._def.values) {
  6888. enumValues[val2] = val2;
  6889. }
  6890. return enumValues;
  6891. }
  6892. get Enum() {
  6893. const enumValues = {};
  6894. for (const val2 of this._def.values) {
  6895. enumValues[val2] = val2;
  6896. }
  6897. return enumValues;
  6898. }
  6899. extract(values, newDef = this._def) {
  6900. return _ZodEnum.create(values, {
  6901. ...this._def,
  6902. ...newDef
  6903. });
  6904. }
  6905. exclude(values, newDef = this._def) {
  6906. return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
  6907. ...this._def,
  6908. ...newDef
  6909. });
  6910. }
  6911. };
  6912. ZodEnum.create = createZodEnum;
  6913. ZodNativeEnum = class extends ZodType {
  6914. _parse(input) {
  6915. const nativeEnumValues = util.getValidEnumValues(this._def.values);
  6916. const ctx = this._getOrReturnCtx(input);
  6917. if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
  6918. const expectedValues = util.objectValues(nativeEnumValues);
  6919. addIssueToContext(ctx, {
  6920. expected: util.joinValues(expectedValues),
  6921. received: ctx.parsedType,
  6922. code: ZodIssueCode.invalid_type
  6923. });
  6924. return INVALID;
  6925. }
  6926. if (!this._cache) {
  6927. this._cache = new Set(util.getValidEnumValues(this._def.values));
  6928. }
  6929. if (!this._cache.has(input.data)) {
  6930. const expectedValues = util.objectValues(nativeEnumValues);
  6931. addIssueToContext(ctx, {
  6932. received: ctx.data,
  6933. code: ZodIssueCode.invalid_enum_value,
  6934. options: expectedValues
  6935. });
  6936. return INVALID;
  6937. }
  6938. return OK(input.data);
  6939. }
  6940. get enum() {
  6941. return this._def.values;
  6942. }
  6943. };
  6944. ZodNativeEnum.create = (values, params) => {
  6945. return new ZodNativeEnum({
  6946. values,
  6947. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  6948. ...processCreateParams(params)
  6949. });
  6950. };
  6951. ZodPromise = class extends ZodType {
  6952. unwrap() {
  6953. return this._def.type;
  6954. }
  6955. _parse(input) {
  6956. const { ctx } = this._processInputParams(input);
  6957. if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
  6958. addIssueToContext(ctx, {
  6959. code: ZodIssueCode.invalid_type,
  6960. expected: ZodParsedType.promise,
  6961. received: ctx.parsedType
  6962. });
  6963. return INVALID;
  6964. }
  6965. const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
  6966. return OK(promisified.then((data) => {
  6967. return this._def.type.parseAsync(data, {
  6968. path: ctx.path,
  6969. errorMap: ctx.common.contextualErrorMap
  6970. });
  6971. }));
  6972. }
  6973. };
  6974. ZodPromise.create = (schema6, params) => {
  6975. return new ZodPromise({
  6976. type: schema6,
  6977. typeName: ZodFirstPartyTypeKind.ZodPromise,
  6978. ...processCreateParams(params)
  6979. });
  6980. };
  6981. ZodEffects = class extends ZodType {
  6982. innerType() {
  6983. return this._def.schema;
  6984. }
  6985. sourceType() {
  6986. return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  6987. }
  6988. _parse(input) {
  6989. const { status, ctx } = this._processInputParams(input);
  6990. const effect = this._def.effect || null;
  6991. const checkCtx = {
  6992. addIssue: (arg) => {
  6993. addIssueToContext(ctx, arg);
  6994. if (arg.fatal) {
  6995. status.abort();
  6996. } else {
  6997. status.dirty();
  6998. }
  6999. },
  7000. get path() {
  7001. return ctx.path;
  7002. }
  7003. };
  7004. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
  7005. if (effect.type === "preprocess") {
  7006. const processed = effect.transform(ctx.data, checkCtx);
  7007. if (ctx.common.async) {
  7008. return Promise.resolve(processed).then(async (processed2) => {
  7009. if (status.value === "aborted")
  7010. return INVALID;
  7011. const result = await this._def.schema._parseAsync({
  7012. data: processed2,
  7013. path: ctx.path,
  7014. parent: ctx
  7015. });
  7016. if (result.status === "aborted")
  7017. return INVALID;
  7018. if (result.status === "dirty")
  7019. return DIRTY(result.value);
  7020. if (status.value === "dirty")
  7021. return DIRTY(result.value);
  7022. return result;
  7023. });
  7024. } else {
  7025. if (status.value === "aborted")
  7026. return INVALID;
  7027. const result = this._def.schema._parseSync({
  7028. data: processed,
  7029. path: ctx.path,
  7030. parent: ctx
  7031. });
  7032. if (result.status === "aborted")
  7033. return INVALID;
  7034. if (result.status === "dirty")
  7035. return DIRTY(result.value);
  7036. if (status.value === "dirty")
  7037. return DIRTY(result.value);
  7038. return result;
  7039. }
  7040. }
  7041. if (effect.type === "refinement") {
  7042. const executeRefinement = (acc) => {
  7043. const result = effect.refinement(acc, checkCtx);
  7044. if (ctx.common.async) {
  7045. return Promise.resolve(result);
  7046. }
  7047. if (result instanceof Promise) {
  7048. throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
  7049. }
  7050. return acc;
  7051. };
  7052. if (ctx.common.async === false) {
  7053. const inner = this._def.schema._parseSync({
  7054. data: ctx.data,
  7055. path: ctx.path,
  7056. parent: ctx
  7057. });
  7058. if (inner.status === "aborted")
  7059. return INVALID;
  7060. if (inner.status === "dirty")
  7061. status.dirty();
  7062. executeRefinement(inner.value);
  7063. return { status: status.value, value: inner.value };
  7064. } else {
  7065. return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
  7066. if (inner.status === "aborted")
  7067. return INVALID;
  7068. if (inner.status === "dirty")
  7069. status.dirty();
  7070. return executeRefinement(inner.value).then(() => {
  7071. return { status: status.value, value: inner.value };
  7072. });
  7073. });
  7074. }
  7075. }
  7076. if (effect.type === "transform") {
  7077. if (ctx.common.async === false) {
  7078. const base = this._def.schema._parseSync({
  7079. data: ctx.data,
  7080. path: ctx.path,
  7081. parent: ctx
  7082. });
  7083. if (!isValid(base))
  7084. return INVALID;
  7085. const result = effect.transform(base.value, checkCtx);
  7086. if (result instanceof Promise) {
  7087. throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
  7088. }
  7089. return { status: status.value, value: result };
  7090. } else {
  7091. return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
  7092. if (!isValid(base))
  7093. return INVALID;
  7094. return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
  7095. status: status.value,
  7096. value: result
  7097. }));
  7098. });
  7099. }
  7100. }
  7101. util.assertNever(effect);
  7102. }
  7103. };
  7104. ZodEffects.create = (schema6, effect, params) => {
  7105. return new ZodEffects({
  7106. schema: schema6,
  7107. typeName: ZodFirstPartyTypeKind.ZodEffects,
  7108. effect,
  7109. ...processCreateParams(params)
  7110. });
  7111. };
  7112. ZodEffects.createWithPreprocess = (preprocess, schema6, params) => {
  7113. return new ZodEffects({
  7114. schema: schema6,
  7115. effect: { type: "preprocess", transform: preprocess },
  7116. typeName: ZodFirstPartyTypeKind.ZodEffects,
  7117. ...processCreateParams(params)
  7118. });
  7119. };
  7120. ZodOptional = class extends ZodType {
  7121. _parse(input) {
  7122. const parsedType = this._getType(input);
  7123. if (parsedType === ZodParsedType.undefined) {
  7124. return OK(void 0);
  7125. }
  7126. return this._def.innerType._parse(input);
  7127. }
  7128. unwrap() {
  7129. return this._def.innerType;
  7130. }
  7131. };
  7132. ZodOptional.create = (type, params) => {
  7133. return new ZodOptional({
  7134. innerType: type,
  7135. typeName: ZodFirstPartyTypeKind.ZodOptional,
  7136. ...processCreateParams(params)
  7137. });
  7138. };
  7139. ZodNullable = class extends ZodType {
  7140. _parse(input) {
  7141. const parsedType = this._getType(input);
  7142. if (parsedType === ZodParsedType.null) {
  7143. return OK(null);
  7144. }
  7145. return this._def.innerType._parse(input);
  7146. }
  7147. unwrap() {
  7148. return this._def.innerType;
  7149. }
  7150. };
  7151. ZodNullable.create = (type, params) => {
  7152. return new ZodNullable({
  7153. innerType: type,
  7154. typeName: ZodFirstPartyTypeKind.ZodNullable,
  7155. ...processCreateParams(params)
  7156. });
  7157. };
  7158. ZodDefault = class extends ZodType {
  7159. _parse(input) {
  7160. const { ctx } = this._processInputParams(input);
  7161. let data = ctx.data;
  7162. if (ctx.parsedType === ZodParsedType.undefined) {
  7163. data = this._def.defaultValue();
  7164. }
  7165. return this._def.innerType._parse({
  7166. data,
  7167. path: ctx.path,
  7168. parent: ctx
  7169. });
  7170. }
  7171. removeDefault() {
  7172. return this._def.innerType;
  7173. }
  7174. };
  7175. ZodDefault.create = (type, params) => {
  7176. return new ZodDefault({
  7177. innerType: type,
  7178. typeName: ZodFirstPartyTypeKind.ZodDefault,
  7179. defaultValue: typeof params.default === "function" ? params.default : () => params.default,
  7180. ...processCreateParams(params)
  7181. });
  7182. };
  7183. ZodCatch = class extends ZodType {
  7184. _parse(input) {
  7185. const { ctx } = this._processInputParams(input);
  7186. const newCtx = {
  7187. ...ctx,
  7188. common: {
  7189. ...ctx.common,
  7190. issues: []
  7191. }
  7192. };
  7193. const result = this._def.innerType._parse({
  7194. data: newCtx.data,
  7195. path: newCtx.path,
  7196. parent: {
  7197. ...newCtx
  7198. }
  7199. });
  7200. if (isAsync(result)) {
  7201. return result.then((result2) => {
  7202. return {
  7203. status: "valid",
  7204. value: result2.status === "valid" ? result2.value : this._def.catchValue({
  7205. get error() {
  7206. return new ZodError(newCtx.common.issues);
  7207. },
  7208. input: newCtx.data
  7209. })
  7210. };
  7211. });
  7212. } else {
  7213. return {
  7214. status: "valid",
  7215. value: result.status === "valid" ? result.value : this._def.catchValue({
  7216. get error() {
  7217. return new ZodError(newCtx.common.issues);
  7218. },
  7219. input: newCtx.data
  7220. })
  7221. };
  7222. }
  7223. }
  7224. removeCatch() {
  7225. return this._def.innerType;
  7226. }
  7227. };
  7228. ZodCatch.create = (type, params) => {
  7229. return new ZodCatch({
  7230. innerType: type,
  7231. typeName: ZodFirstPartyTypeKind.ZodCatch,
  7232. catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
  7233. ...processCreateParams(params)
  7234. });
  7235. };
  7236. ZodNaN = class extends ZodType {
  7237. _parse(input) {
  7238. const parsedType = this._getType(input);
  7239. if (parsedType !== ZodParsedType.nan) {
  7240. const ctx = this._getOrReturnCtx(input);
  7241. addIssueToContext(ctx, {
  7242. code: ZodIssueCode.invalid_type,
  7243. expected: ZodParsedType.nan,
  7244. received: ctx.parsedType
  7245. });
  7246. return INVALID;
  7247. }
  7248. return { status: "valid", value: input.data };
  7249. }
  7250. };
  7251. ZodNaN.create = (params) => {
  7252. return new ZodNaN({
  7253. typeName: ZodFirstPartyTypeKind.ZodNaN,
  7254. ...processCreateParams(params)
  7255. });
  7256. };
  7257. BRAND = Symbol("zod_brand");
  7258. ZodBranded = class extends ZodType {
  7259. _parse(input) {
  7260. const { ctx } = this._processInputParams(input);
  7261. const data = ctx.data;
  7262. return this._def.type._parse({
  7263. data,
  7264. path: ctx.path,
  7265. parent: ctx
  7266. });
  7267. }
  7268. unwrap() {
  7269. return this._def.type;
  7270. }
  7271. };
  7272. ZodPipeline = class _ZodPipeline extends ZodType {
  7273. _parse(input) {
  7274. const { status, ctx } = this._processInputParams(input);
  7275. if (ctx.common.async) {
  7276. const handleAsync = async () => {
  7277. const inResult = await this._def.in._parseAsync({
  7278. data: ctx.data,
  7279. path: ctx.path,
  7280. parent: ctx
  7281. });
  7282. if (inResult.status === "aborted")
  7283. return INVALID;
  7284. if (inResult.status === "dirty") {
  7285. status.dirty();
  7286. return DIRTY(inResult.value);
  7287. } else {
  7288. return this._def.out._parseAsync({
  7289. data: inResult.value,
  7290. path: ctx.path,
  7291. parent: ctx
  7292. });
  7293. }
  7294. };
  7295. return handleAsync();
  7296. } else {
  7297. const inResult = this._def.in._parseSync({
  7298. data: ctx.data,
  7299. path: ctx.path,
  7300. parent: ctx
  7301. });
  7302. if (inResult.status === "aborted")
  7303. return INVALID;
  7304. if (inResult.status === "dirty") {
  7305. status.dirty();
  7306. return {
  7307. status: "dirty",
  7308. value: inResult.value
  7309. };
  7310. } else {
  7311. return this._def.out._parseSync({
  7312. data: inResult.value,
  7313. path: ctx.path,
  7314. parent: ctx
  7315. });
  7316. }
  7317. }
  7318. }
  7319. static create(a5, b5) {
  7320. return new _ZodPipeline({
  7321. in: a5,
  7322. out: b5,
  7323. typeName: ZodFirstPartyTypeKind.ZodPipeline
  7324. });
  7325. }
  7326. };
  7327. ZodReadonly = class extends ZodType {
  7328. _parse(input) {
  7329. const result = this._def.innerType._parse(input);
  7330. const freeze = (data) => {
  7331. if (isValid(data)) {
  7332. data.value = Object.freeze(data.value);
  7333. }
  7334. return data;
  7335. };
  7336. return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  7337. }
  7338. unwrap() {
  7339. return this._def.innerType;
  7340. }
  7341. };
  7342. ZodReadonly.create = (type, params) => {
  7343. return new ZodReadonly({
  7344. innerType: type,
  7345. typeName: ZodFirstPartyTypeKind.ZodReadonly,
  7346. ...processCreateParams(params)
  7347. });
  7348. };
  7349. late = {
  7350. object: ZodObject.lazycreate
  7351. };
  7352. (function(ZodFirstPartyTypeKind2) {
  7353. ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  7354. ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  7355. ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  7356. ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  7357. ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  7358. ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  7359. ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  7360. ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  7361. ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  7362. ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  7363. ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  7364. ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  7365. ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  7366. ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  7367. ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  7368. ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  7369. ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  7370. ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  7371. ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  7372. ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  7373. ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  7374. ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  7375. ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  7376. ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  7377. ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  7378. ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  7379. ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  7380. ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  7381. ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  7382. ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  7383. ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  7384. ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  7385. ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  7386. ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  7387. ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  7388. ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
  7389. })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
  7390. instanceOfType = (cls, params = {
  7391. message: `Input not instance of ${cls.name}`
  7392. }) => custom((data) => data instanceof cls, params);
  7393. stringType = ZodString.create;
  7394. numberType = ZodNumber.create;
  7395. nanType = ZodNaN.create;
  7396. bigIntType = ZodBigInt.create;
  7397. booleanType = ZodBoolean.create;
  7398. dateType = ZodDate.create;
  7399. symbolType = ZodSymbol.create;
  7400. undefinedType = ZodUndefined.create;
  7401. nullType = ZodNull.create;
  7402. anyType = ZodAny.create;
  7403. unknownType = ZodUnknown.create;
  7404. neverType = ZodNever.create;
  7405. voidType = ZodVoid.create;
  7406. arrayType = ZodArray.create;
  7407. objectType = ZodObject.create;
  7408. strictObjectType = ZodObject.strictCreate;
  7409. unionType = ZodUnion.create;
  7410. discriminatedUnionType = ZodDiscriminatedUnion.create;
  7411. intersectionType = ZodIntersection.create;
  7412. tupleType = ZodTuple.create;
  7413. recordType = ZodRecord.create;
  7414. mapType = ZodMap.create;
  7415. setType = ZodSet.create;
  7416. functionType = ZodFunction.create;
  7417. lazyType = ZodLazy.create;
  7418. literalType = ZodLiteral.create;
  7419. enumType = ZodEnum.create;
  7420. nativeEnumType = ZodNativeEnum.create;
  7421. promiseType = ZodPromise.create;
  7422. effectsType = ZodEffects.create;
  7423. optionalType = ZodOptional.create;
  7424. nullableType = ZodNullable.create;
  7425. preprocessType = ZodEffects.createWithPreprocess;
  7426. pipelineType = ZodPipeline.create;
  7427. ostring = () => stringType().optional();
  7428. onumber = () => numberType().optional();
  7429. oboolean = () => booleanType().optional();
  7430. coerce = {
  7431. string: (arg) => ZodString.create({ ...arg, coerce: true }),
  7432. number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
  7433. boolean: (arg) => ZodBoolean.create({
  7434. ...arg,
  7435. coerce: true
  7436. }),
  7437. bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
  7438. date: (arg) => ZodDate.create({ ...arg, coerce: true })
  7439. };
  7440. NEVER = INVALID;
  7441. }
  7442. });
  7443. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js
  7444. var external_exports = {};
  7445. __export(external_exports, {
  7446. BRAND: () => BRAND,
  7447. DIRTY: () => DIRTY,
  7448. EMPTY_PATH: () => EMPTY_PATH,
  7449. INVALID: () => INVALID,
  7450. NEVER: () => NEVER,
  7451. OK: () => OK,
  7452. ParseStatus: () => ParseStatus,
  7453. Schema: () => ZodType,
  7454. ZodAny: () => ZodAny,
  7455. ZodArray: () => ZodArray,
  7456. ZodBigInt: () => ZodBigInt,
  7457. ZodBoolean: () => ZodBoolean,
  7458. ZodBranded: () => ZodBranded,
  7459. ZodCatch: () => ZodCatch,
  7460. ZodDate: () => ZodDate,
  7461. ZodDefault: () => ZodDefault,
  7462. ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  7463. ZodEffects: () => ZodEffects,
  7464. ZodEnum: () => ZodEnum,
  7465. ZodError: () => ZodError,
  7466. ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  7467. ZodFunction: () => ZodFunction,
  7468. ZodIntersection: () => ZodIntersection,
  7469. ZodIssueCode: () => ZodIssueCode,
  7470. ZodLazy: () => ZodLazy,
  7471. ZodLiteral: () => ZodLiteral,
  7472. ZodMap: () => ZodMap,
  7473. ZodNaN: () => ZodNaN,
  7474. ZodNativeEnum: () => ZodNativeEnum,
  7475. ZodNever: () => ZodNever,
  7476. ZodNull: () => ZodNull,
  7477. ZodNullable: () => ZodNullable,
  7478. ZodNumber: () => ZodNumber,
  7479. ZodObject: () => ZodObject,
  7480. ZodOptional: () => ZodOptional,
  7481. ZodParsedType: () => ZodParsedType,
  7482. ZodPipeline: () => ZodPipeline,
  7483. ZodPromise: () => ZodPromise,
  7484. ZodReadonly: () => ZodReadonly,
  7485. ZodRecord: () => ZodRecord,
  7486. ZodSchema: () => ZodType,
  7487. ZodSet: () => ZodSet,
  7488. ZodString: () => ZodString,
  7489. ZodSymbol: () => ZodSymbol,
  7490. ZodTransformer: () => ZodEffects,
  7491. ZodTuple: () => ZodTuple,
  7492. ZodType: () => ZodType,
  7493. ZodUndefined: () => ZodUndefined,
  7494. ZodUnion: () => ZodUnion,
  7495. ZodUnknown: () => ZodUnknown,
  7496. ZodVoid: () => ZodVoid,
  7497. addIssueToContext: () => addIssueToContext,
  7498. any: () => anyType,
  7499. array: () => arrayType,
  7500. bigint: () => bigIntType,
  7501. boolean: () => booleanType,
  7502. coerce: () => coerce,
  7503. custom: () => custom,
  7504. date: () => dateType,
  7505. datetimeRegex: () => datetimeRegex,
  7506. defaultErrorMap: () => en_default,
  7507. discriminatedUnion: () => discriminatedUnionType,
  7508. effect: () => effectsType,
  7509. enum: () => enumType,
  7510. function: () => functionType,
  7511. getErrorMap: () => getErrorMap,
  7512. getParsedType: () => getParsedType,
  7513. instanceof: () => instanceOfType,
  7514. intersection: () => intersectionType,
  7515. isAborted: () => isAborted,
  7516. isAsync: () => isAsync,
  7517. isDirty: () => isDirty,
  7518. isValid: () => isValid,
  7519. late: () => late,
  7520. lazy: () => lazyType,
  7521. literal: () => literalType,
  7522. makeIssue: () => makeIssue,
  7523. map: () => mapType,
  7524. nan: () => nanType,
  7525. nativeEnum: () => nativeEnumType,
  7526. never: () => neverType,
  7527. null: () => nullType,
  7528. nullable: () => nullableType,
  7529. number: () => numberType,
  7530. object: () => objectType,
  7531. objectUtil: () => objectUtil,
  7532. oboolean: () => oboolean,
  7533. onumber: () => onumber,
  7534. optional: () => optionalType,
  7535. ostring: () => ostring,
  7536. pipeline: () => pipelineType,
  7537. preprocess: () => preprocessType,
  7538. promise: () => promiseType,
  7539. quotelessJson: () => quotelessJson,
  7540. record: () => recordType,
  7541. set: () => setType,
  7542. setErrorMap: () => setErrorMap,
  7543. strictObject: () => strictObjectType,
  7544. string: () => stringType,
  7545. symbol: () => symbolType,
  7546. transformer: () => effectsType,
  7547. tuple: () => tupleType,
  7548. undefined: () => undefinedType,
  7549. union: () => unionType,
  7550. unknown: () => unknownType,
  7551. util: () => util,
  7552. void: () => voidType
  7553. });
  7554. var init_external = __esm({
  7555. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js"() {
  7556. "use strict";
  7557. init_errors();
  7558. init_parseUtil();
  7559. init_typeAliases();
  7560. init_util();
  7561. init_types();
  7562. init_ZodError();
  7563. }
  7564. });
  7565. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js
  7566. var init_v3 = __esm({
  7567. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js"() {
  7568. "use strict";
  7569. init_external();
  7570. init_external();
  7571. }
  7572. });
  7573. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js
  7574. var init_esm = __esm({
  7575. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js"() {
  7576. "use strict";
  7577. init_v3();
  7578. init_v3();
  7579. }
  7580. });
  7581. // src/serializer/gelSchema.ts
  7582. var enumSchema, enumSchemaV1, indexColumn, index, fk, sequenceSchema, roleSchema, sequenceSquashed, column, checkConstraint, columnSquashed, compositePK, uniqueConstraint, policy, policySquashed, viewWithOption, matViewWithOption, mergedViewWithOption, view, table, schemaHash, kitInternals, gelSchemaExternal, gelSchemaInternal, tableSquashed, gelSchemaSquashed, gelSchema, dryGel;
  7583. var init_gelSchema = __esm({
  7584. "src/serializer/gelSchema.ts"() {
  7585. "use strict";
  7586. init_global();
  7587. init_esm();
  7588. enumSchema = objectType({
  7589. name: stringType(),
  7590. schema: stringType(),
  7591. values: stringType().array()
  7592. }).strict();
  7593. enumSchemaV1 = objectType({
  7594. name: stringType(),
  7595. values: recordType(stringType(), stringType())
  7596. }).strict();
  7597. indexColumn = objectType({
  7598. expression: stringType(),
  7599. isExpression: booleanType(),
  7600. asc: booleanType(),
  7601. nulls: stringType().optional(),
  7602. opclass: stringType().optional()
  7603. });
  7604. index = objectType({
  7605. name: stringType(),
  7606. columns: indexColumn.array(),
  7607. isUnique: booleanType(),
  7608. with: recordType(stringType(), anyType()).optional(),
  7609. method: stringType().default("btree"),
  7610. where: stringType().optional(),
  7611. concurrently: booleanType().default(false)
  7612. }).strict();
  7613. fk = objectType({
  7614. name: stringType(),
  7615. tableFrom: stringType(),
  7616. columnsFrom: stringType().array(),
  7617. tableTo: stringType(),
  7618. schemaTo: stringType().optional(),
  7619. columnsTo: stringType().array(),
  7620. onUpdate: stringType().optional(),
  7621. onDelete: stringType().optional()
  7622. }).strict();
  7623. sequenceSchema = objectType({
  7624. name: stringType(),
  7625. increment: stringType().optional(),
  7626. minValue: stringType().optional(),
  7627. maxValue: stringType().optional(),
  7628. startWith: stringType().optional(),
  7629. cache: stringType().optional(),
  7630. cycle: booleanType().optional(),
  7631. schema: stringType()
  7632. }).strict();
  7633. roleSchema = objectType({
  7634. name: stringType(),
  7635. createDb: booleanType().optional(),
  7636. createRole: booleanType().optional(),
  7637. inherit: booleanType().optional()
  7638. }).strict();
  7639. sequenceSquashed = objectType({
  7640. name: stringType(),
  7641. schema: stringType(),
  7642. values: stringType()
  7643. }).strict();
  7644. column = objectType({
  7645. name: stringType(),
  7646. type: stringType(),
  7647. typeSchema: stringType().optional(),
  7648. primaryKey: booleanType(),
  7649. notNull: booleanType(),
  7650. default: anyType().optional(),
  7651. isUnique: anyType().optional(),
  7652. uniqueName: stringType().optional(),
  7653. nullsNotDistinct: booleanType().optional(),
  7654. generated: objectType({
  7655. type: literalType("stored"),
  7656. as: stringType()
  7657. }).optional(),
  7658. identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
  7659. }).strict();
  7660. checkConstraint = objectType({
  7661. name: stringType(),
  7662. value: stringType()
  7663. }).strict();
  7664. columnSquashed = objectType({
  7665. name: stringType(),
  7666. type: stringType(),
  7667. typeSchema: stringType().optional(),
  7668. primaryKey: booleanType(),
  7669. notNull: booleanType(),
  7670. default: anyType().optional(),
  7671. isUnique: anyType().optional(),
  7672. uniqueName: stringType().optional(),
  7673. nullsNotDistinct: booleanType().optional(),
  7674. generated: objectType({
  7675. type: literalType("stored"),
  7676. as: stringType()
  7677. }).optional(),
  7678. identity: stringType().optional()
  7679. }).strict();
  7680. compositePK = objectType({
  7681. name: stringType(),
  7682. columns: stringType().array()
  7683. }).strict();
  7684. uniqueConstraint = objectType({
  7685. name: stringType(),
  7686. columns: stringType().array(),
  7687. nullsNotDistinct: booleanType()
  7688. }).strict();
  7689. policy = objectType({
  7690. name: stringType(),
  7691. as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
  7692. for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
  7693. to: stringType().array().optional(),
  7694. using: stringType().optional(),
  7695. withCheck: stringType().optional(),
  7696. on: stringType().optional(),
  7697. schema: stringType().optional()
  7698. }).strict();
  7699. policySquashed = objectType({
  7700. name: stringType(),
  7701. values: stringType()
  7702. }).strict();
  7703. viewWithOption = objectType({
  7704. checkOption: enumType(["local", "cascaded"]).optional(),
  7705. securityBarrier: booleanType().optional(),
  7706. securityInvoker: booleanType().optional()
  7707. }).strict();
  7708. matViewWithOption = objectType({
  7709. fillfactor: numberType().optional(),
  7710. toastTupleTarget: numberType().optional(),
  7711. parallelWorkers: numberType().optional(),
  7712. autovacuumEnabled: booleanType().optional(),
  7713. vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
  7714. vacuumTruncate: booleanType().optional(),
  7715. autovacuumVacuumThreshold: numberType().optional(),
  7716. autovacuumVacuumScaleFactor: numberType().optional(),
  7717. autovacuumVacuumCostDelay: numberType().optional(),
  7718. autovacuumVacuumCostLimit: numberType().optional(),
  7719. autovacuumFreezeMinAge: numberType().optional(),
  7720. autovacuumFreezeMaxAge: numberType().optional(),
  7721. autovacuumFreezeTableAge: numberType().optional(),
  7722. autovacuumMultixactFreezeMinAge: numberType().optional(),
  7723. autovacuumMultixactFreezeMaxAge: numberType().optional(),
  7724. autovacuumMultixactFreezeTableAge: numberType().optional(),
  7725. logAutovacuumMinDuration: numberType().optional(),
  7726. userCatalogTable: booleanType().optional()
  7727. }).strict();
  7728. mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
  7729. view = objectType({
  7730. name: stringType(),
  7731. schema: stringType(),
  7732. columns: recordType(stringType(), column),
  7733. definition: stringType().optional(),
  7734. materialized: booleanType(),
  7735. with: mergedViewWithOption.optional(),
  7736. isExisting: booleanType(),
  7737. withNoData: booleanType().optional(),
  7738. using: stringType().optional(),
  7739. tablespace: stringType().optional()
  7740. }).strict();
  7741. table = objectType({
  7742. name: stringType(),
  7743. schema: stringType(),
  7744. columns: recordType(stringType(), column),
  7745. indexes: recordType(stringType(), index),
  7746. foreignKeys: recordType(stringType(), fk),
  7747. compositePrimaryKeys: recordType(stringType(), compositePK),
  7748. uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
  7749. policies: recordType(stringType(), policy).default({}),
  7750. checkConstraints: recordType(stringType(), checkConstraint).default({}),
  7751. isRLSEnabled: booleanType().default(false)
  7752. }).strict();
  7753. schemaHash = objectType({
  7754. id: stringType(),
  7755. prevId: stringType()
  7756. });
  7757. kitInternals = objectType({
  7758. tables: recordType(
  7759. stringType(),
  7760. objectType({
  7761. columns: recordType(
  7762. stringType(),
  7763. objectType({
  7764. isArray: booleanType().optional(),
  7765. dimensions: numberType().optional(),
  7766. rawType: stringType().optional(),
  7767. isDefaultAnExpression: booleanType().optional()
  7768. }).optional()
  7769. )
  7770. }).optional()
  7771. )
  7772. }).optional();
  7773. gelSchemaExternal = objectType({
  7774. version: literalType("1"),
  7775. dialect: literalType("gel"),
  7776. tables: arrayType(table),
  7777. enums: arrayType(enumSchemaV1),
  7778. schemas: arrayType(objectType({ name: stringType() })),
  7779. _meta: objectType({
  7780. schemas: recordType(stringType(), stringType()),
  7781. tables: recordType(stringType(), stringType()),
  7782. columns: recordType(stringType(), stringType())
  7783. })
  7784. }).strict();
  7785. gelSchemaInternal = objectType({
  7786. version: literalType("1"),
  7787. dialect: literalType("gel"),
  7788. tables: recordType(stringType(), table),
  7789. enums: recordType(stringType(), enumSchema),
  7790. schemas: recordType(stringType(), stringType()),
  7791. views: recordType(stringType(), view).default({}),
  7792. sequences: recordType(stringType(), sequenceSchema).default({}),
  7793. roles: recordType(stringType(), roleSchema).default({}),
  7794. policies: recordType(stringType(), policy).default({}),
  7795. _meta: objectType({
  7796. schemas: recordType(stringType(), stringType()),
  7797. tables: recordType(stringType(), stringType()),
  7798. columns: recordType(stringType(), stringType())
  7799. }),
  7800. internal: kitInternals
  7801. }).strict();
  7802. tableSquashed = objectType({
  7803. name: stringType(),
  7804. schema: stringType(),
  7805. columns: recordType(stringType(), columnSquashed),
  7806. indexes: recordType(stringType(), stringType()),
  7807. foreignKeys: recordType(stringType(), stringType()),
  7808. compositePrimaryKeys: recordType(stringType(), stringType()),
  7809. uniqueConstraints: recordType(stringType(), stringType()),
  7810. policies: recordType(stringType(), stringType()),
  7811. checkConstraints: recordType(stringType(), stringType()),
  7812. isRLSEnabled: booleanType().default(false)
  7813. }).strict();
  7814. gelSchemaSquashed = objectType({
  7815. version: literalType("1"),
  7816. dialect: literalType("gel"),
  7817. tables: recordType(stringType(), tableSquashed),
  7818. enums: recordType(stringType(), enumSchema),
  7819. schemas: recordType(stringType(), stringType()),
  7820. views: recordType(stringType(), view),
  7821. sequences: recordType(stringType(), sequenceSquashed),
  7822. roles: recordType(stringType(), roleSchema).default({}),
  7823. policies: recordType(stringType(), policySquashed).default({})
  7824. }).strict();
  7825. gelSchema = gelSchemaInternal.merge(schemaHash);
  7826. dryGel = gelSchema.parse({
  7827. version: "1",
  7828. dialect: "gel",
  7829. id: originUUID,
  7830. prevId: "",
  7831. tables: {},
  7832. enums: {},
  7833. schemas: {},
  7834. policies: {},
  7835. roles: {},
  7836. sequences: {},
  7837. _meta: {
  7838. schemas: {},
  7839. tables: {},
  7840. columns: {}
  7841. }
  7842. });
  7843. }
  7844. });
  7845. // src/serializer/mysqlSchema.ts
  7846. var index2, fk2, column2, tableV3, compositePK2, uniqueConstraint2, checkConstraint2, tableV4, table2, viewMeta, view2, kitInternals2, dialect, schemaHash2, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed2, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
  7847. var init_mysqlSchema = __esm({
  7848. "src/serializer/mysqlSchema.ts"() {
  7849. "use strict";
  7850. init_esm();
  7851. init_global();
  7852. index2 = objectType({
  7853. name: stringType(),
  7854. columns: stringType().array(),
  7855. isUnique: booleanType(),
  7856. using: enumType(["btree", "hash"]).optional(),
  7857. algorithm: enumType(["default", "inplace", "copy"]).optional(),
  7858. lock: enumType(["default", "none", "shared", "exclusive"]).optional()
  7859. }).strict();
  7860. fk2 = objectType({
  7861. name: stringType(),
  7862. tableFrom: stringType(),
  7863. columnsFrom: stringType().array(),
  7864. tableTo: stringType(),
  7865. columnsTo: stringType().array(),
  7866. onUpdate: stringType().optional(),
  7867. onDelete: stringType().optional()
  7868. }).strict();
  7869. column2 = objectType({
  7870. name: stringType(),
  7871. type: stringType(),
  7872. primaryKey: booleanType(),
  7873. notNull: booleanType(),
  7874. autoincrement: booleanType().optional(),
  7875. default: anyType().optional(),
  7876. onUpdate: anyType().optional(),
  7877. generated: objectType({
  7878. type: enumType(["stored", "virtual"]),
  7879. as: stringType()
  7880. }).optional()
  7881. }).strict();
  7882. tableV3 = objectType({
  7883. name: stringType(),
  7884. columns: recordType(stringType(), column2),
  7885. indexes: recordType(stringType(), index2),
  7886. foreignKeys: recordType(stringType(), fk2)
  7887. }).strict();
  7888. compositePK2 = objectType({
  7889. name: stringType(),
  7890. columns: stringType().array()
  7891. }).strict();
  7892. uniqueConstraint2 = objectType({
  7893. name: stringType(),
  7894. columns: stringType().array()
  7895. }).strict();
  7896. checkConstraint2 = objectType({
  7897. name: stringType(),
  7898. value: stringType()
  7899. }).strict();
  7900. tableV4 = objectType({
  7901. name: stringType(),
  7902. schema: stringType().optional(),
  7903. columns: recordType(stringType(), column2),
  7904. indexes: recordType(stringType(), index2),
  7905. foreignKeys: recordType(stringType(), fk2)
  7906. }).strict();
  7907. table2 = objectType({
  7908. name: stringType(),
  7909. columns: recordType(stringType(), column2),
  7910. indexes: recordType(stringType(), index2),
  7911. foreignKeys: recordType(stringType(), fk2),
  7912. compositePrimaryKeys: recordType(stringType(), compositePK2),
  7913. uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
  7914. checkConstraint: recordType(stringType(), checkConstraint2).default({})
  7915. }).strict();
  7916. viewMeta = objectType({
  7917. algorithm: enumType(["undefined", "merge", "temptable"]),
  7918. sqlSecurity: enumType(["definer", "invoker"]),
  7919. withCheckOption: enumType(["local", "cascaded"]).optional()
  7920. }).strict();
  7921. view2 = objectType({
  7922. name: stringType(),
  7923. columns: recordType(stringType(), column2),
  7924. definition: stringType().optional(),
  7925. isExisting: booleanType()
  7926. }).strict().merge(viewMeta);
  7927. kitInternals2 = objectType({
  7928. tables: recordType(
  7929. stringType(),
  7930. objectType({
  7931. columns: recordType(
  7932. stringType(),
  7933. objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
  7934. )
  7935. }).optional()
  7936. ).optional(),
  7937. indexes: recordType(
  7938. stringType(),
  7939. objectType({
  7940. columns: recordType(
  7941. stringType(),
  7942. objectType({ isExpression: booleanType().optional() }).optional()
  7943. )
  7944. }).optional()
  7945. ).optional()
  7946. }).optional();
  7947. dialect = literalType("mysql");
  7948. schemaHash2 = objectType({
  7949. id: stringType(),
  7950. prevId: stringType()
  7951. });
  7952. schemaInternalV3 = objectType({
  7953. version: literalType("3"),
  7954. dialect,
  7955. tables: recordType(stringType(), tableV3)
  7956. }).strict();
  7957. schemaInternalV4 = objectType({
  7958. version: literalType("4"),
  7959. dialect,
  7960. tables: recordType(stringType(), tableV4),
  7961. schemas: recordType(stringType(), stringType())
  7962. }).strict();
  7963. schemaInternalV5 = objectType({
  7964. version: literalType("5"),
  7965. dialect,
  7966. tables: recordType(stringType(), table2),
  7967. schemas: recordType(stringType(), stringType()),
  7968. _meta: objectType({
  7969. schemas: recordType(stringType(), stringType()),
  7970. tables: recordType(stringType(), stringType()),
  7971. columns: recordType(stringType(), stringType())
  7972. }),
  7973. internal: kitInternals2
  7974. }).strict();
  7975. schemaInternal = objectType({
  7976. version: literalType("5"),
  7977. dialect,
  7978. tables: recordType(stringType(), table2),
  7979. views: recordType(stringType(), view2).default({}),
  7980. _meta: objectType({
  7981. tables: recordType(stringType(), stringType()),
  7982. columns: recordType(stringType(), stringType())
  7983. }),
  7984. internal: kitInternals2
  7985. }).strict();
  7986. schemaV3 = schemaInternalV3.merge(schemaHash2);
  7987. schemaV4 = schemaInternalV4.merge(schemaHash2);
  7988. schemaV5 = schemaInternalV5.merge(schemaHash2);
  7989. schema = schemaInternal.merge(schemaHash2);
  7990. tableSquashedV4 = objectType({
  7991. name: stringType(),
  7992. schema: stringType().optional(),
  7993. columns: recordType(stringType(), column2),
  7994. indexes: recordType(stringType(), stringType()),
  7995. foreignKeys: recordType(stringType(), stringType())
  7996. }).strict();
  7997. tableSquashed2 = objectType({
  7998. name: stringType(),
  7999. columns: recordType(stringType(), column2),
  8000. indexes: recordType(stringType(), stringType()),
  8001. foreignKeys: recordType(stringType(), stringType()),
  8002. compositePrimaryKeys: recordType(stringType(), stringType()),
  8003. uniqueConstraints: recordType(stringType(), stringType()).default({}),
  8004. checkConstraints: recordType(stringType(), stringType()).default({})
  8005. }).strict();
  8006. viewSquashed = view2.omit({
  8007. algorithm: true,
  8008. sqlSecurity: true,
  8009. withCheckOption: true
  8010. }).extend({ meta: stringType() });
  8011. schemaSquashed = objectType({
  8012. version: literalType("5"),
  8013. dialect,
  8014. tables: recordType(stringType(), tableSquashed2),
  8015. views: recordType(stringType(), viewSquashed)
  8016. }).strict();
  8017. schemaSquashedV4 = objectType({
  8018. version: literalType("4"),
  8019. dialect,
  8020. tables: recordType(stringType(), tableSquashedV4),
  8021. schemas: recordType(stringType(), stringType())
  8022. }).strict();
  8023. MySqlSquasher = {
  8024. squashIdx: (idx) => {
  8025. index2.parse(idx);
  8026. return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
  8027. },
  8028. unsquashIdx: (input) => {
  8029. const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
  8030. const destructed = {
  8031. name,
  8032. columns: columnsString.split(","),
  8033. isUnique: isUnique === "true",
  8034. using: using ? using : void 0,
  8035. algorithm: algorithm ? algorithm : void 0,
  8036. lock: lock ? lock : void 0
  8037. };
  8038. return index2.parse(destructed);
  8039. },
  8040. squashPK: (pk) => {
  8041. return `${pk.name};${pk.columns.join(",")}`;
  8042. },
  8043. unsquashPK: (pk) => {
  8044. const splitted = pk.split(";");
  8045. return { name: splitted[0], columns: splitted[1].split(",") };
  8046. },
  8047. squashUnique: (unq) => {
  8048. return `${unq.name};${unq.columns.join(",")}`;
  8049. },
  8050. unsquashUnique: (unq) => {
  8051. const [name, columns] = unq.split(";");
  8052. return { name, columns: columns.split(",") };
  8053. },
  8054. squashFK: (fk5) => {
  8055. return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
  8056. },
  8057. unsquashFK: (input) => {
  8058. const [
  8059. name,
  8060. tableFrom,
  8061. columnsFromStr,
  8062. tableTo,
  8063. columnsToStr,
  8064. onUpdate,
  8065. onDelete
  8066. ] = input.split(";");
  8067. const result = fk2.parse({
  8068. name,
  8069. tableFrom,
  8070. columnsFrom: columnsFromStr.split(","),
  8071. tableTo,
  8072. columnsTo: columnsToStr.split(","),
  8073. onUpdate,
  8074. onDelete
  8075. });
  8076. return result;
  8077. },
  8078. squashCheck: (input) => {
  8079. return `${input.name};${input.value}`;
  8080. },
  8081. unsquashCheck: (input) => {
  8082. const [name, value] = input.split(";");
  8083. return { name, value };
  8084. },
  8085. squashView: (view5) => {
  8086. return `${view5.algorithm};${view5.sqlSecurity};${view5.withCheckOption}`;
  8087. },
  8088. unsquashView: (meta) => {
  8089. const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
  8090. const toReturn = {
  8091. algorithm,
  8092. sqlSecurity,
  8093. withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
  8094. };
  8095. return viewMeta.parse(toReturn);
  8096. }
  8097. };
  8098. squashMysqlScheme = (json) => {
  8099. const mappedTables = Object.fromEntries(
  8100. Object.entries(json.tables).map((it) => {
  8101. const squashedIndexes = mapValues(it[1].indexes, (index6) => {
  8102. return MySqlSquasher.squashIdx(index6);
  8103. });
  8104. const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
  8105. return MySqlSquasher.squashFK(fk5);
  8106. });
  8107. const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
  8108. return MySqlSquasher.squashPK(pk);
  8109. });
  8110. const squashedUniqueConstraints = mapValues(
  8111. it[1].uniqueConstraints,
  8112. (unq) => {
  8113. return MySqlSquasher.squashUnique(unq);
  8114. }
  8115. );
  8116. const squashedCheckConstraints = mapValues(it[1].checkConstraint, (check) => {
  8117. return MySqlSquasher.squashCheck(check);
  8118. });
  8119. return [
  8120. it[0],
  8121. {
  8122. name: it[1].name,
  8123. columns: it[1].columns,
  8124. indexes: squashedIndexes,
  8125. foreignKeys: squashedFKs,
  8126. compositePrimaryKeys: squashedPKs,
  8127. uniqueConstraints: squashedUniqueConstraints,
  8128. checkConstraints: squashedCheckConstraints
  8129. }
  8130. ];
  8131. })
  8132. );
  8133. const mappedViews = Object.fromEntries(
  8134. Object.entries(json.views).map(([key, value]) => {
  8135. const meta = MySqlSquasher.squashView(value);
  8136. return [key, {
  8137. name: value.name,
  8138. isExisting: value.isExisting,
  8139. columns: value.columns,
  8140. definition: value.definition,
  8141. meta
  8142. }];
  8143. })
  8144. );
  8145. return {
  8146. version: "5",
  8147. dialect: json.dialect,
  8148. tables: mappedTables,
  8149. views: mappedViews
  8150. };
  8151. };
  8152. mysqlSchema = schema;
  8153. mysqlSchemaV5 = schemaV5;
  8154. mysqlSchemaSquashed = schemaSquashed;
  8155. backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]);
  8156. dryMySql = mysqlSchema.parse({
  8157. version: "5",
  8158. dialect: "mysql",
  8159. id: originUUID,
  8160. prevId: "",
  8161. tables: {},
  8162. schemas: {},
  8163. views: {},
  8164. _meta: {
  8165. schemas: {},
  8166. tables: {},
  8167. columns: {}
  8168. }
  8169. });
  8170. }
  8171. });
  8172. // src/serializer/pgSchema.ts
  8173. var indexV2, columnV2, tableV2, enumSchemaV12, enumSchema2, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn2, index3, indexV4, indexV5, indexV6, fk3, sequenceSchema2, roleSchema2, sequenceSquashed2, columnV7, column3, checkConstraint3, columnSquashed2, tableV32, compositePK3, uniqueConstraint3, policy2, policySquashed2, viewWithOption2, matViewWithOption2, mergedViewWithOption2, view3, tableV42, tableV5, tableV6, tableV7, table3, schemaHash3, kitInternals3, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed3, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
  8174. var init_pgSchema = __esm({
  8175. "src/serializer/pgSchema.ts"() {
  8176. "use strict";
  8177. init_global();
  8178. init_esm();
  8179. indexV2 = objectType({
  8180. name: stringType(),
  8181. columns: recordType(
  8182. stringType(),
  8183. objectType({
  8184. name: stringType()
  8185. })
  8186. ),
  8187. isUnique: booleanType()
  8188. }).strict();
  8189. columnV2 = objectType({
  8190. name: stringType(),
  8191. type: stringType(),
  8192. primaryKey: booleanType(),
  8193. notNull: booleanType(),
  8194. default: anyType().optional(),
  8195. references: stringType().optional()
  8196. }).strict();
  8197. tableV2 = objectType({
  8198. name: stringType(),
  8199. columns: recordType(stringType(), columnV2),
  8200. indexes: recordType(stringType(), indexV2)
  8201. }).strict();
  8202. enumSchemaV12 = objectType({
  8203. name: stringType(),
  8204. values: recordType(stringType(), stringType())
  8205. }).strict();
  8206. enumSchema2 = objectType({
  8207. name: stringType(),
  8208. schema: stringType(),
  8209. values: stringType().array()
  8210. }).strict();
  8211. pgSchemaV2 = objectType({
  8212. version: literalType("2"),
  8213. tables: recordType(stringType(), tableV2),
  8214. enums: recordType(stringType(), enumSchemaV12)
  8215. }).strict();
  8216. references = objectType({
  8217. foreignKeyName: stringType(),
  8218. table: stringType(),
  8219. column: stringType(),
  8220. onDelete: stringType().optional(),
  8221. onUpdate: stringType().optional()
  8222. }).strict();
  8223. columnV1 = objectType({
  8224. name: stringType(),
  8225. type: stringType(),
  8226. primaryKey: booleanType(),
  8227. notNull: booleanType(),
  8228. default: anyType().optional(),
  8229. references: references.optional()
  8230. }).strict();
  8231. tableV1 = objectType({
  8232. name: stringType(),
  8233. columns: recordType(stringType(), columnV1),
  8234. indexes: recordType(stringType(), indexV2)
  8235. }).strict();
  8236. pgSchemaV1 = objectType({
  8237. version: literalType("1"),
  8238. tables: recordType(stringType(), tableV1),
  8239. enums: recordType(stringType(), enumSchemaV12)
  8240. }).strict();
  8241. indexColumn2 = objectType({
  8242. expression: stringType(),
  8243. isExpression: booleanType(),
  8244. asc: booleanType(),
  8245. nulls: stringType().optional(),
  8246. opclass: stringType().optional()
  8247. });
  8248. index3 = objectType({
  8249. name: stringType(),
  8250. columns: indexColumn2.array(),
  8251. isUnique: booleanType(),
  8252. with: recordType(stringType(), anyType()).optional(),
  8253. method: stringType().default("btree"),
  8254. where: stringType().optional(),
  8255. concurrently: booleanType().default(false)
  8256. }).strict();
  8257. indexV4 = objectType({
  8258. name: stringType(),
  8259. columns: stringType().array(),
  8260. isUnique: booleanType(),
  8261. with: recordType(stringType(), stringType()).optional(),
  8262. method: stringType().default("btree"),
  8263. where: stringType().optional(),
  8264. concurrently: booleanType().default(false)
  8265. }).strict();
  8266. indexV5 = objectType({
  8267. name: stringType(),
  8268. columns: stringType().array(),
  8269. isUnique: booleanType(),
  8270. with: recordType(stringType(), stringType()).optional(),
  8271. method: stringType().default("btree"),
  8272. where: stringType().optional(),
  8273. concurrently: booleanType().default(false)
  8274. }).strict();
  8275. indexV6 = objectType({
  8276. name: stringType(),
  8277. columns: stringType().array(),
  8278. isUnique: booleanType(),
  8279. with: recordType(stringType(), stringType()).optional(),
  8280. method: stringType().default("btree"),
  8281. where: stringType().optional(),
  8282. concurrently: booleanType().default(false)
  8283. }).strict();
  8284. fk3 = objectType({
  8285. name: stringType(),
  8286. tableFrom: stringType(),
  8287. columnsFrom: stringType().array(),
  8288. tableTo: stringType(),
  8289. schemaTo: stringType().optional(),
  8290. columnsTo: stringType().array(),
  8291. onUpdate: stringType().optional(),
  8292. onDelete: stringType().optional()
  8293. }).strict();
  8294. sequenceSchema2 = objectType({
  8295. name: stringType(),
  8296. increment: stringType().optional(),
  8297. minValue: stringType().optional(),
  8298. maxValue: stringType().optional(),
  8299. startWith: stringType().optional(),
  8300. cache: stringType().optional(),
  8301. cycle: booleanType().optional(),
  8302. schema: stringType()
  8303. }).strict();
  8304. roleSchema2 = objectType({
  8305. name: stringType(),
  8306. createDb: booleanType().optional(),
  8307. createRole: booleanType().optional(),
  8308. inherit: booleanType().optional()
  8309. }).strict();
  8310. sequenceSquashed2 = objectType({
  8311. name: stringType(),
  8312. schema: stringType(),
  8313. values: stringType()
  8314. }).strict();
  8315. columnV7 = objectType({
  8316. name: stringType(),
  8317. type: stringType(),
  8318. typeSchema: stringType().optional(),
  8319. primaryKey: booleanType(),
  8320. notNull: booleanType(),
  8321. default: anyType().optional(),
  8322. isUnique: anyType().optional(),
  8323. uniqueName: stringType().optional(),
  8324. nullsNotDistinct: booleanType().optional()
  8325. }).strict();
  8326. column3 = objectType({
  8327. name: stringType(),
  8328. type: stringType(),
  8329. typeSchema: stringType().optional(),
  8330. primaryKey: booleanType(),
  8331. notNull: booleanType(),
  8332. default: anyType().optional(),
  8333. isUnique: anyType().optional(),
  8334. uniqueName: stringType().optional(),
  8335. nullsNotDistinct: booleanType().optional(),
  8336. generated: objectType({
  8337. type: literalType("stored"),
  8338. as: stringType()
  8339. }).optional(),
  8340. identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
  8341. }).strict();
  8342. checkConstraint3 = objectType({
  8343. name: stringType(),
  8344. value: stringType()
  8345. }).strict();
  8346. columnSquashed2 = objectType({
  8347. name: stringType(),
  8348. type: stringType(),
  8349. typeSchema: stringType().optional(),
  8350. primaryKey: booleanType(),
  8351. notNull: booleanType(),
  8352. default: anyType().optional(),
  8353. isUnique: anyType().optional(),
  8354. uniqueName: stringType().optional(),
  8355. nullsNotDistinct: booleanType().optional(),
  8356. generated: objectType({
  8357. type: literalType("stored"),
  8358. as: stringType()
  8359. }).optional(),
  8360. identity: stringType().optional()
  8361. }).strict();
  8362. tableV32 = objectType({
  8363. name: stringType(),
  8364. columns: recordType(stringType(), column3),
  8365. indexes: recordType(stringType(), index3),
  8366. foreignKeys: recordType(stringType(), fk3)
  8367. }).strict();
  8368. compositePK3 = objectType({
  8369. name: stringType(),
  8370. columns: stringType().array()
  8371. }).strict();
  8372. uniqueConstraint3 = objectType({
  8373. name: stringType(),
  8374. columns: stringType().array(),
  8375. nullsNotDistinct: booleanType()
  8376. }).strict();
  8377. policy2 = objectType({
  8378. name: stringType(),
  8379. as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
  8380. for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
  8381. to: stringType().array().optional(),
  8382. using: stringType().optional(),
  8383. withCheck: stringType().optional(),
  8384. on: stringType().optional(),
  8385. schema: stringType().optional()
  8386. }).strict();
  8387. policySquashed2 = objectType({
  8388. name: stringType(),
  8389. values: stringType()
  8390. }).strict();
  8391. viewWithOption2 = objectType({
  8392. checkOption: enumType(["local", "cascaded"]).optional(),
  8393. securityBarrier: booleanType().optional(),
  8394. securityInvoker: booleanType().optional()
  8395. }).strict();
  8396. matViewWithOption2 = objectType({
  8397. fillfactor: numberType().optional(),
  8398. toastTupleTarget: numberType().optional(),
  8399. parallelWorkers: numberType().optional(),
  8400. autovacuumEnabled: booleanType().optional(),
  8401. vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
  8402. vacuumTruncate: booleanType().optional(),
  8403. autovacuumVacuumThreshold: numberType().optional(),
  8404. autovacuumVacuumScaleFactor: numberType().optional(),
  8405. autovacuumVacuumCostDelay: numberType().optional(),
  8406. autovacuumVacuumCostLimit: numberType().optional(),
  8407. autovacuumFreezeMinAge: numberType().optional(),
  8408. autovacuumFreezeMaxAge: numberType().optional(),
  8409. autovacuumFreezeTableAge: numberType().optional(),
  8410. autovacuumMultixactFreezeMinAge: numberType().optional(),
  8411. autovacuumMultixactFreezeMaxAge: numberType().optional(),
  8412. autovacuumMultixactFreezeTableAge: numberType().optional(),
  8413. logAutovacuumMinDuration: numberType().optional(),
  8414. userCatalogTable: booleanType().optional()
  8415. }).strict();
  8416. mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict();
  8417. view3 = objectType({
  8418. name: stringType(),
  8419. schema: stringType(),
  8420. columns: recordType(stringType(), column3),
  8421. definition: stringType().optional(),
  8422. materialized: booleanType(),
  8423. with: mergedViewWithOption2.optional(),
  8424. isExisting: booleanType(),
  8425. withNoData: booleanType().optional(),
  8426. using: stringType().optional(),
  8427. tablespace: stringType().optional()
  8428. }).strict();
  8429. tableV42 = objectType({
  8430. name: stringType(),
  8431. schema: stringType(),
  8432. columns: recordType(stringType(), column3),
  8433. indexes: recordType(stringType(), indexV4),
  8434. foreignKeys: recordType(stringType(), fk3)
  8435. }).strict();
  8436. tableV5 = objectType({
  8437. name: stringType(),
  8438. schema: stringType(),
  8439. columns: recordType(stringType(), column3),
  8440. indexes: recordType(stringType(), indexV5),
  8441. foreignKeys: recordType(stringType(), fk3),
  8442. compositePrimaryKeys: recordType(stringType(), compositePK3),
  8443. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
  8444. }).strict();
  8445. tableV6 = objectType({
  8446. name: stringType(),
  8447. schema: stringType(),
  8448. columns: recordType(stringType(), column3),
  8449. indexes: recordType(stringType(), indexV6),
  8450. foreignKeys: recordType(stringType(), fk3),
  8451. compositePrimaryKeys: recordType(stringType(), compositePK3),
  8452. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
  8453. }).strict();
  8454. tableV7 = objectType({
  8455. name: stringType(),
  8456. schema: stringType(),
  8457. columns: recordType(stringType(), columnV7),
  8458. indexes: recordType(stringType(), index3),
  8459. foreignKeys: recordType(stringType(), fk3),
  8460. compositePrimaryKeys: recordType(stringType(), compositePK3),
  8461. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
  8462. }).strict();
  8463. table3 = objectType({
  8464. name: stringType(),
  8465. schema: stringType(),
  8466. columns: recordType(stringType(), column3),
  8467. indexes: recordType(stringType(), index3),
  8468. foreignKeys: recordType(stringType(), fk3),
  8469. compositePrimaryKeys: recordType(stringType(), compositePK3),
  8470. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}),
  8471. policies: recordType(stringType(), policy2).default({}),
  8472. checkConstraints: recordType(stringType(), checkConstraint3).default({}),
  8473. isRLSEnabled: booleanType().default(false)
  8474. }).strict();
  8475. schemaHash3 = objectType({
  8476. id: stringType(),
  8477. prevId: stringType()
  8478. });
  8479. kitInternals3 = objectType({
  8480. tables: recordType(
  8481. stringType(),
  8482. objectType({
  8483. columns: recordType(
  8484. stringType(),
  8485. objectType({
  8486. isArray: booleanType().optional(),
  8487. dimensions: numberType().optional(),
  8488. rawType: stringType().optional(),
  8489. isDefaultAnExpression: booleanType().optional()
  8490. }).optional()
  8491. )
  8492. }).optional()
  8493. )
  8494. }).optional();
  8495. pgSchemaInternalV3 = objectType({
  8496. version: literalType("3"),
  8497. dialect: literalType("pg"),
  8498. tables: recordType(stringType(), tableV32),
  8499. enums: recordType(stringType(), enumSchemaV12)
  8500. }).strict();
  8501. pgSchemaInternalV4 = objectType({
  8502. version: literalType("4"),
  8503. dialect: literalType("pg"),
  8504. tables: recordType(stringType(), tableV42),
  8505. enums: recordType(stringType(), enumSchemaV12),
  8506. schemas: recordType(stringType(), stringType())
  8507. }).strict();
  8508. pgSchemaInternalV5 = objectType({
  8509. version: literalType("5"),
  8510. dialect: literalType("pg"),
  8511. tables: recordType(stringType(), tableV5),
  8512. enums: recordType(stringType(), enumSchemaV12),
  8513. schemas: recordType(stringType(), stringType()),
  8514. _meta: objectType({
  8515. schemas: recordType(stringType(), stringType()),
  8516. tables: recordType(stringType(), stringType()),
  8517. columns: recordType(stringType(), stringType())
  8518. }),
  8519. internal: kitInternals3
  8520. }).strict();
  8521. pgSchemaInternalV6 = objectType({
  8522. version: literalType("6"),
  8523. dialect: literalType("postgresql"),
  8524. tables: recordType(stringType(), tableV6),
  8525. enums: recordType(stringType(), enumSchema2),
  8526. schemas: recordType(stringType(), stringType()),
  8527. _meta: objectType({
  8528. schemas: recordType(stringType(), stringType()),
  8529. tables: recordType(stringType(), stringType()),
  8530. columns: recordType(stringType(), stringType())
  8531. }),
  8532. internal: kitInternals3
  8533. }).strict();
  8534. pgSchemaExternal = objectType({
  8535. version: literalType("5"),
  8536. dialect: literalType("pg"),
  8537. tables: arrayType(table3),
  8538. enums: arrayType(enumSchemaV12),
  8539. schemas: arrayType(objectType({ name: stringType() })),
  8540. _meta: objectType({
  8541. schemas: recordType(stringType(), stringType()),
  8542. tables: recordType(stringType(), stringType()),
  8543. columns: recordType(stringType(), stringType())
  8544. })
  8545. }).strict();
  8546. pgSchemaInternalV7 = objectType({
  8547. version: literalType("7"),
  8548. dialect: literalType("postgresql"),
  8549. tables: recordType(stringType(), tableV7),
  8550. enums: recordType(stringType(), enumSchema2),
  8551. schemas: recordType(stringType(), stringType()),
  8552. sequences: recordType(stringType(), sequenceSchema2),
  8553. _meta: objectType({
  8554. schemas: recordType(stringType(), stringType()),
  8555. tables: recordType(stringType(), stringType()),
  8556. columns: recordType(stringType(), stringType())
  8557. }),
  8558. internal: kitInternals3
  8559. }).strict();
  8560. pgSchemaInternal = objectType({
  8561. version: literalType("7"),
  8562. dialect: literalType("postgresql"),
  8563. tables: recordType(stringType(), table3),
  8564. enums: recordType(stringType(), enumSchema2),
  8565. schemas: recordType(stringType(), stringType()),
  8566. views: recordType(stringType(), view3).default({}),
  8567. sequences: recordType(stringType(), sequenceSchema2).default({}),
  8568. roles: recordType(stringType(), roleSchema2).default({}),
  8569. policies: recordType(stringType(), policy2).default({}),
  8570. _meta: objectType({
  8571. schemas: recordType(stringType(), stringType()),
  8572. tables: recordType(stringType(), stringType()),
  8573. columns: recordType(stringType(), stringType())
  8574. }),
  8575. internal: kitInternals3
  8576. }).strict();
  8577. tableSquashed3 = objectType({
  8578. name: stringType(),
  8579. schema: stringType(),
  8580. columns: recordType(stringType(), columnSquashed2),
  8581. indexes: recordType(stringType(), stringType()),
  8582. foreignKeys: recordType(stringType(), stringType()),
  8583. compositePrimaryKeys: recordType(stringType(), stringType()),
  8584. uniqueConstraints: recordType(stringType(), stringType()),
  8585. policies: recordType(stringType(), stringType()),
  8586. checkConstraints: recordType(stringType(), stringType()),
  8587. isRLSEnabled: booleanType().default(false)
  8588. }).strict();
  8589. tableSquashedV42 = objectType({
  8590. name: stringType(),
  8591. schema: stringType(),
  8592. columns: recordType(stringType(), column3),
  8593. indexes: recordType(stringType(), stringType()),
  8594. foreignKeys: recordType(stringType(), stringType())
  8595. }).strict();
  8596. pgSchemaSquashedV4 = objectType({
  8597. version: literalType("4"),
  8598. dialect: literalType("pg"),
  8599. tables: recordType(stringType(), tableSquashedV42),
  8600. enums: recordType(stringType(), enumSchemaV12),
  8601. schemas: recordType(stringType(), stringType())
  8602. }).strict();
  8603. pgSchemaSquashedV6 = objectType({
  8604. version: literalType("6"),
  8605. dialect: literalType("postgresql"),
  8606. tables: recordType(stringType(), tableSquashed3),
  8607. enums: recordType(stringType(), enumSchema2),
  8608. schemas: recordType(stringType(), stringType())
  8609. }).strict();
  8610. pgSchemaSquashed = objectType({
  8611. version: literalType("7"),
  8612. dialect: literalType("postgresql"),
  8613. tables: recordType(stringType(), tableSquashed3),
  8614. enums: recordType(stringType(), enumSchema2),
  8615. schemas: recordType(stringType(), stringType()),
  8616. views: recordType(stringType(), view3),
  8617. sequences: recordType(stringType(), sequenceSquashed2),
  8618. roles: recordType(stringType(), roleSchema2).default({}),
  8619. policies: recordType(stringType(), policySquashed2).default({})
  8620. }).strict();
  8621. pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash3);
  8622. pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash3);
  8623. pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash3);
  8624. pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash3);
  8625. pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash3);
  8626. pgSchema = pgSchemaInternal.merge(schemaHash3);
  8627. backwardCompatiblePgSchema = unionType([
  8628. pgSchemaV5,
  8629. pgSchemaV6,
  8630. pgSchema
  8631. ]);
  8632. PgSquasher = {
  8633. squashIdx: (idx) => {
  8634. index3.parse(idx);
  8635. return `${idx.name};${idx.columns.map(
  8636. (c5) => `${c5.expression}--${c5.isExpression}--${c5.asc}--${c5.nulls}--${c5.opclass ? c5.opclass : ""}`
  8637. ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
  8638. },
  8639. unsquashIdx: (input) => {
  8640. const [
  8641. name,
  8642. columnsString,
  8643. isUnique,
  8644. concurrently,
  8645. method,
  8646. where,
  8647. idxWith
  8648. ] = input.split(";");
  8649. const columnString = columnsString.split(",,");
  8650. const columns = [];
  8651. for (const column6 of columnString) {
  8652. const [expression, isExpression, asc, nulls, opclass] = column6.split("--");
  8653. columns.push({
  8654. nulls,
  8655. isExpression: isExpression === "true",
  8656. asc: asc === "true",
  8657. expression,
  8658. opclass: opclass === "undefined" ? void 0 : opclass
  8659. });
  8660. }
  8661. const result = index3.parse({
  8662. name,
  8663. columns,
  8664. isUnique: isUnique === "true",
  8665. concurrently: concurrently === "true",
  8666. method,
  8667. where: where === "undefined" ? void 0 : where,
  8668. with: !idxWith || idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
  8669. });
  8670. return result;
  8671. },
  8672. squashIdxPush: (idx) => {
  8673. index3.parse(idx);
  8674. return `${idx.name};${idx.columns.map((c5) => `${c5.isExpression ? "" : c5.expression}--${c5.asc}--${c5.nulls}`).join(",,")};${idx.isUnique};${idx.method};${JSON.stringify(idx.with)}`;
  8675. },
  8676. unsquashIdxPush: (input) => {
  8677. const [name, columnsString, isUnique, method, idxWith] = input.split(";");
  8678. const columnString = columnsString.split("--");
  8679. const columns = [];
  8680. for (const column6 of columnString) {
  8681. const [expression, asc, nulls, opclass] = column6.split(",");
  8682. columns.push({
  8683. nulls,
  8684. isExpression: expression === "",
  8685. asc: asc === "true",
  8686. expression
  8687. });
  8688. }
  8689. const result = index3.parse({
  8690. name,
  8691. columns,
  8692. isUnique: isUnique === "true",
  8693. concurrently: false,
  8694. method,
  8695. with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
  8696. });
  8697. return result;
  8698. },
  8699. squashFK: (fk5) => {
  8700. return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""};${fk5.schemaTo || "public"}`;
  8701. },
  8702. squashPolicy: (policy5) => {
  8703. return `${policy5.name}--${policy5.as}--${policy5.for}--${policy5.to?.join(",")}--${policy5.using}--${policy5.withCheck}--${policy5.on}`;
  8704. },
  8705. unsquashPolicy: (policy5) => {
  8706. const splitted = policy5.split("--");
  8707. return {
  8708. name: splitted[0],
  8709. as: splitted[1],
  8710. for: splitted[2],
  8711. to: splitted[3].split(","),
  8712. using: splitted[4] !== "undefined" ? splitted[4] : void 0,
  8713. withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0,
  8714. on: splitted[6] !== "undefined" ? splitted[6] : void 0
  8715. };
  8716. },
  8717. squashPolicyPush: (policy5) => {
  8718. return `${policy5.name}--${policy5.as}--${policy5.for}--${policy5.to?.join(",")}--${policy5.on}`;
  8719. },
  8720. unsquashPolicyPush: (policy5) => {
  8721. const splitted = policy5.split("--");
  8722. return {
  8723. name: splitted[0],
  8724. as: splitted[1],
  8725. for: splitted[2],
  8726. to: splitted[3].split(","),
  8727. on: splitted[4] !== "undefined" ? splitted[4] : void 0
  8728. };
  8729. },
  8730. squashPK: (pk) => {
  8731. return `${pk.columns.join(",")};${pk.name}`;
  8732. },
  8733. unsquashPK: (pk) => {
  8734. const splitted = pk.split(";");
  8735. return { name: splitted[1], columns: splitted[0].split(",") };
  8736. },
  8737. squashUnique: (unq) => {
  8738. return `${unq.name};${unq.columns.join(",")};${unq.nullsNotDistinct}`;
  8739. },
  8740. unsquashUnique: (unq) => {
  8741. const [name, columns, nullsNotDistinct] = unq.split(";");
  8742. return {
  8743. name,
  8744. columns: columns.split(","),
  8745. nullsNotDistinct: nullsNotDistinct === "true"
  8746. };
  8747. },
  8748. unsquashFK: (input) => {
  8749. const [
  8750. name,
  8751. tableFrom,
  8752. columnsFromStr,
  8753. tableTo,
  8754. columnsToStr,
  8755. onUpdate,
  8756. onDelete,
  8757. schemaTo
  8758. ] = input.split(";");
  8759. const result = fk3.parse({
  8760. name,
  8761. tableFrom,
  8762. columnsFrom: columnsFromStr.split(","),
  8763. schemaTo,
  8764. tableTo,
  8765. columnsTo: columnsToStr.split(","),
  8766. onUpdate,
  8767. onDelete
  8768. });
  8769. return result;
  8770. },
  8771. squashSequence: (seq) => {
  8772. return `${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
  8773. },
  8774. unsquashSequence: (seq) => {
  8775. const splitted = seq.split(";");
  8776. return {
  8777. minValue: splitted[0] !== "undefined" ? splitted[0] : void 0,
  8778. maxValue: splitted[1] !== "undefined" ? splitted[1] : void 0,
  8779. increment: splitted[2] !== "undefined" ? splitted[2] : void 0,
  8780. startWith: splitted[3] !== "undefined" ? splitted[3] : void 0,
  8781. cache: splitted[4] !== "undefined" ? splitted[4] : void 0,
  8782. cycle: splitted[5] === "true"
  8783. };
  8784. },
  8785. squashIdentity: (seq) => {
  8786. return `${seq.name};${seq.type};${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
  8787. },
  8788. unsquashIdentity: (seq) => {
  8789. const splitted = seq.split(";");
  8790. return {
  8791. name: splitted[0],
  8792. type: splitted[1],
  8793. minValue: splitted[2] !== "undefined" ? splitted[2] : void 0,
  8794. maxValue: splitted[3] !== "undefined" ? splitted[3] : void 0,
  8795. increment: splitted[4] !== "undefined" ? splitted[4] : void 0,
  8796. startWith: splitted[5] !== "undefined" ? splitted[5] : void 0,
  8797. cache: splitted[6] !== "undefined" ? splitted[6] : void 0,
  8798. cycle: splitted[7] === "true"
  8799. };
  8800. },
  8801. squashCheck: (check) => {
  8802. return `${check.name};${check.value}`;
  8803. },
  8804. unsquashCheck: (input) => {
  8805. const [
  8806. name,
  8807. value
  8808. ] = input.split(";");
  8809. return { name, value };
  8810. }
  8811. };
  8812. squashPgScheme = (json, action) => {
  8813. const mappedTables = Object.fromEntries(
  8814. Object.entries(json.tables).map((it) => {
  8815. const squashedIndexes = mapValues(it[1].indexes, (index6) => {
  8816. return action === "push" ? PgSquasher.squashIdxPush(index6) : PgSquasher.squashIdx(index6);
  8817. });
  8818. const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
  8819. return PgSquasher.squashFK(fk5);
  8820. });
  8821. const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
  8822. return PgSquasher.squashPK(pk);
  8823. });
  8824. const mappedColumns = Object.fromEntries(
  8825. Object.entries(it[1].columns).map((it2) => {
  8826. const mappedIdentity = it2[1].identity ? PgSquasher.squashIdentity(it2[1].identity) : void 0;
  8827. return [
  8828. it2[0],
  8829. {
  8830. ...it2[1],
  8831. identity: mappedIdentity
  8832. }
  8833. ];
  8834. })
  8835. );
  8836. const squashedUniqueConstraints = mapValues(
  8837. it[1].uniqueConstraints,
  8838. (unq) => {
  8839. return PgSquasher.squashUnique(unq);
  8840. }
  8841. );
  8842. const squashedPolicies = mapValues(it[1].policies, (policy5) => {
  8843. return action === "push" ? PgSquasher.squashPolicyPush(policy5) : PgSquasher.squashPolicy(policy5);
  8844. });
  8845. const squashedChecksContraints = mapValues(
  8846. it[1].checkConstraints,
  8847. (check) => {
  8848. return PgSquasher.squashCheck(check);
  8849. }
  8850. );
  8851. return [
  8852. it[0],
  8853. {
  8854. name: it[1].name,
  8855. schema: it[1].schema,
  8856. columns: mappedColumns,
  8857. indexes: squashedIndexes,
  8858. foreignKeys: squashedFKs,
  8859. compositePrimaryKeys: squashedPKs,
  8860. uniqueConstraints: squashedUniqueConstraints,
  8861. policies: squashedPolicies,
  8862. checkConstraints: squashedChecksContraints,
  8863. isRLSEnabled: it[1].isRLSEnabled ?? false
  8864. }
  8865. ];
  8866. })
  8867. );
  8868. const mappedSequences = Object.fromEntries(
  8869. Object.entries(json.sequences).map((it) => {
  8870. return [
  8871. it[0],
  8872. {
  8873. name: it[1].name,
  8874. schema: it[1].schema,
  8875. values: PgSquasher.squashSequence(it[1])
  8876. }
  8877. ];
  8878. })
  8879. );
  8880. const mappedPolicies = Object.fromEntries(
  8881. Object.entries(json.policies).map((it) => {
  8882. return [
  8883. it[0],
  8884. {
  8885. name: it[1].name,
  8886. values: action === "push" ? PgSquasher.squashPolicyPush(it[1]) : PgSquasher.squashPolicy(it[1])
  8887. }
  8888. ];
  8889. })
  8890. );
  8891. return {
  8892. version: "7",
  8893. dialect: json.dialect,
  8894. tables: mappedTables,
  8895. enums: json.enums,
  8896. schemas: json.schemas,
  8897. views: json.views,
  8898. policies: mappedPolicies,
  8899. sequences: mappedSequences,
  8900. roles: json.roles
  8901. };
  8902. };
  8903. dryPg = pgSchema.parse({
  8904. version: snapshotVersion,
  8905. dialect: "postgresql",
  8906. id: originUUID,
  8907. prevId: "",
  8908. tables: {},
  8909. enums: {},
  8910. schemas: {},
  8911. policies: {},
  8912. roles: {},
  8913. sequences: {},
  8914. _meta: {
  8915. schemas: {},
  8916. tables: {},
  8917. columns: {}
  8918. }
  8919. });
  8920. }
  8921. });
  8922. // src/serializer/singlestoreSchema.ts
  8923. var index4, column4, compositePK4, uniqueConstraint4, table4, viewMeta2, kitInternals4, dialect2, schemaHash4, schemaInternal2, schema2, tableSquashed4, schemaSquashed2, SingleStoreSquasher, squashSingleStoreScheme, singlestoreSchema, singlestoreSchemaSquashed, backwardCompatibleSingleStoreSchema, drySingleStore;
  8924. var init_singlestoreSchema = __esm({
  8925. "src/serializer/singlestoreSchema.ts"() {
  8926. "use strict";
  8927. init_esm();
  8928. init_global();
  8929. index4 = objectType({
  8930. name: stringType(),
  8931. columns: stringType().array(),
  8932. isUnique: booleanType(),
  8933. using: enumType(["btree", "hash"]).optional(),
  8934. algorithm: enumType(["default", "inplace", "copy"]).optional(),
  8935. lock: enumType(["default", "none", "shared", "exclusive"]).optional()
  8936. }).strict();
  8937. column4 = objectType({
  8938. name: stringType(),
  8939. type: stringType(),
  8940. primaryKey: booleanType(),
  8941. notNull: booleanType(),
  8942. autoincrement: booleanType().optional(),
  8943. default: anyType().optional(),
  8944. onUpdate: anyType().optional(),
  8945. generated: objectType({
  8946. type: enumType(["stored", "virtual"]),
  8947. as: stringType()
  8948. }).optional()
  8949. }).strict();
  8950. compositePK4 = objectType({
  8951. name: stringType(),
  8952. columns: stringType().array()
  8953. }).strict();
  8954. uniqueConstraint4 = objectType({
  8955. name: stringType(),
  8956. columns: stringType().array()
  8957. }).strict();
  8958. table4 = objectType({
  8959. name: stringType(),
  8960. columns: recordType(stringType(), column4),
  8961. indexes: recordType(stringType(), index4),
  8962. compositePrimaryKeys: recordType(stringType(), compositePK4),
  8963. uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({})
  8964. }).strict();
  8965. viewMeta2 = objectType({
  8966. algorithm: enumType(["undefined", "merge", "temptable"]),
  8967. sqlSecurity: enumType(["definer", "invoker"]),
  8968. withCheckOption: enumType(["local", "cascaded"]).optional()
  8969. }).strict();
  8970. kitInternals4 = objectType({
  8971. tables: recordType(
  8972. stringType(),
  8973. objectType({
  8974. columns: recordType(
  8975. stringType(),
  8976. objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
  8977. )
  8978. }).optional()
  8979. ).optional(),
  8980. indexes: recordType(
  8981. stringType(),
  8982. objectType({
  8983. columns: recordType(
  8984. stringType(),
  8985. objectType({ isExpression: booleanType().optional() }).optional()
  8986. )
  8987. }).optional()
  8988. ).optional()
  8989. }).optional();
  8990. dialect2 = literalType("singlestore");
  8991. schemaHash4 = objectType({
  8992. id: stringType(),
  8993. prevId: stringType()
  8994. });
  8995. schemaInternal2 = objectType({
  8996. version: literalType("1"),
  8997. dialect: dialect2,
  8998. tables: recordType(stringType(), table4),
  8999. /* views: record(string(), view).default({}), */
  9000. _meta: objectType({
  9001. tables: recordType(stringType(), stringType()),
  9002. columns: recordType(stringType(), stringType())
  9003. }),
  9004. internal: kitInternals4
  9005. }).strict();
  9006. schema2 = schemaInternal2.merge(schemaHash4);
  9007. tableSquashed4 = objectType({
  9008. name: stringType(),
  9009. columns: recordType(stringType(), column4),
  9010. indexes: recordType(stringType(), stringType()),
  9011. compositePrimaryKeys: recordType(stringType(), stringType()),
  9012. uniqueConstraints: recordType(stringType(), stringType()).default({})
  9013. }).strict();
  9014. schemaSquashed2 = objectType({
  9015. version: literalType("1"),
  9016. dialect: dialect2,
  9017. tables: recordType(stringType(), tableSquashed4)
  9018. /* views: record(string(), viewSquashed), */
  9019. }).strict();
  9020. SingleStoreSquasher = {
  9021. squashIdx: (idx) => {
  9022. index4.parse(idx);
  9023. return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
  9024. },
  9025. unsquashIdx: (input) => {
  9026. const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
  9027. const destructed = {
  9028. name,
  9029. columns: columnsString.split(","),
  9030. isUnique: isUnique === "true",
  9031. using: using ? using : void 0,
  9032. algorithm: algorithm ? algorithm : void 0,
  9033. lock: lock ? lock : void 0
  9034. };
  9035. return index4.parse(destructed);
  9036. },
  9037. squashPK: (pk) => {
  9038. return `${pk.name};${pk.columns.join(",")}`;
  9039. },
  9040. unsquashPK: (pk) => {
  9041. const splitted = pk.split(";");
  9042. return { name: splitted[0], columns: splitted[1].split(",") };
  9043. },
  9044. squashUnique: (unq) => {
  9045. return `${unq.name};${unq.columns.join(",")}`;
  9046. },
  9047. unsquashUnique: (unq) => {
  9048. const [name, columns] = unq.split(";");
  9049. return { name, columns: columns.split(",") };
  9050. }
  9051. /* squashView: (view: View): string => {
  9052. return `${view.algorithm};${view.sqlSecurity};${view.withCheckOption}`;
  9053. },
  9054. unsquashView: (meta: string): SquasherViewMeta => {
  9055. const [algorithm, sqlSecurity, withCheckOption] = meta.split(';');
  9056. const toReturn = {
  9057. algorithm: algorithm,
  9058. sqlSecurity: sqlSecurity,
  9059. withCheckOption: withCheckOption !== 'undefined' ? withCheckOption : undefined,
  9060. };
  9061. return viewMeta.parse(toReturn);
  9062. }, */
  9063. };
  9064. squashSingleStoreScheme = (json) => {
  9065. const mappedTables = Object.fromEntries(
  9066. Object.entries(json.tables).map((it) => {
  9067. const squashedIndexes = mapValues(it[1].indexes, (index6) => {
  9068. return SingleStoreSquasher.squashIdx(index6);
  9069. });
  9070. const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
  9071. return SingleStoreSquasher.squashPK(pk);
  9072. });
  9073. const squashedUniqueConstraints = mapValues(
  9074. it[1].uniqueConstraints,
  9075. (unq) => {
  9076. return SingleStoreSquasher.squashUnique(unq);
  9077. }
  9078. );
  9079. return [
  9080. it[0],
  9081. {
  9082. name: it[1].name,
  9083. columns: it[1].columns,
  9084. indexes: squashedIndexes,
  9085. compositePrimaryKeys: squashedPKs,
  9086. uniqueConstraints: squashedUniqueConstraints
  9087. }
  9088. ];
  9089. })
  9090. );
  9091. return {
  9092. version: "1",
  9093. dialect: json.dialect,
  9094. tables: mappedTables
  9095. /* views: mappedViews, */
  9096. };
  9097. };
  9098. singlestoreSchema = schema2;
  9099. singlestoreSchemaSquashed = schemaSquashed2;
  9100. backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]);
  9101. drySingleStore = singlestoreSchema.parse({
  9102. version: "1",
  9103. dialect: "singlestore",
  9104. id: originUUID,
  9105. prevId: "",
  9106. tables: {},
  9107. schemas: {},
  9108. /* views: {}, */
  9109. _meta: {
  9110. schemas: {},
  9111. tables: {},
  9112. columns: {}
  9113. }
  9114. });
  9115. }
  9116. });
  9117. // src/serializer/sqliteSchema.ts
  9118. var index5, fk4, compositePK5, column5, tableV33, uniqueConstraint5, checkConstraint4, table5, view4, dialect3, schemaHash5, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals5, latestVersion, schemaInternal3, schemaV32, schemaV42, schemaV52, schema3, tableSquashed5, schemaSquashed3, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
  9119. var init_sqliteSchema = __esm({
  9120. "src/serializer/sqliteSchema.ts"() {
  9121. "use strict";
  9122. init_esm();
  9123. init_global();
  9124. index5 = objectType({
  9125. name: stringType(),
  9126. columns: stringType().array(),
  9127. where: stringType().optional(),
  9128. isUnique: booleanType()
  9129. }).strict();
  9130. fk4 = objectType({
  9131. name: stringType(),
  9132. tableFrom: stringType(),
  9133. columnsFrom: stringType().array(),
  9134. tableTo: stringType(),
  9135. columnsTo: stringType().array(),
  9136. onUpdate: stringType().optional(),
  9137. onDelete: stringType().optional()
  9138. }).strict();
  9139. compositePK5 = objectType({
  9140. columns: stringType().array(),
  9141. name: stringType().optional()
  9142. }).strict();
  9143. column5 = objectType({
  9144. name: stringType(),
  9145. type: stringType(),
  9146. primaryKey: booleanType(),
  9147. notNull: booleanType(),
  9148. autoincrement: booleanType().optional(),
  9149. default: anyType().optional(),
  9150. generated: objectType({
  9151. type: enumType(["stored", "virtual"]),
  9152. as: stringType()
  9153. }).optional()
  9154. }).strict();
  9155. tableV33 = objectType({
  9156. name: stringType(),
  9157. columns: recordType(stringType(), column5),
  9158. indexes: recordType(stringType(), index5),
  9159. foreignKeys: recordType(stringType(), fk4)
  9160. }).strict();
  9161. uniqueConstraint5 = objectType({
  9162. name: stringType(),
  9163. columns: stringType().array()
  9164. }).strict();
  9165. checkConstraint4 = objectType({
  9166. name: stringType(),
  9167. value: stringType()
  9168. }).strict();
  9169. table5 = objectType({
  9170. name: stringType(),
  9171. columns: recordType(stringType(), column5),
  9172. indexes: recordType(stringType(), index5),
  9173. foreignKeys: recordType(stringType(), fk4),
  9174. compositePrimaryKeys: recordType(stringType(), compositePK5),
  9175. uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}),
  9176. checkConstraints: recordType(stringType(), checkConstraint4).default({})
  9177. }).strict();
  9178. view4 = objectType({
  9179. name: stringType(),
  9180. columns: recordType(stringType(), column5),
  9181. definition: stringType().optional(),
  9182. isExisting: booleanType()
  9183. }).strict();
  9184. dialect3 = enumType(["sqlite"]);
  9185. schemaHash5 = objectType({
  9186. id: stringType(),
  9187. prevId: stringType()
  9188. }).strict();
  9189. schemaInternalV32 = objectType({
  9190. version: literalType("3"),
  9191. dialect: dialect3,
  9192. tables: recordType(stringType(), tableV33),
  9193. enums: objectType({})
  9194. }).strict();
  9195. schemaInternalV42 = objectType({
  9196. version: literalType("4"),
  9197. dialect: dialect3,
  9198. tables: recordType(stringType(), table5),
  9199. views: recordType(stringType(), view4).default({}),
  9200. enums: objectType({})
  9201. }).strict();
  9202. schemaInternalV52 = objectType({
  9203. version: literalType("5"),
  9204. dialect: dialect3,
  9205. tables: recordType(stringType(), table5),
  9206. enums: objectType({}),
  9207. _meta: objectType({
  9208. tables: recordType(stringType(), stringType()),
  9209. columns: recordType(stringType(), stringType())
  9210. })
  9211. }).strict();
  9212. kitInternals5 = objectType({
  9213. indexes: recordType(
  9214. stringType(),
  9215. objectType({
  9216. columns: recordType(
  9217. stringType(),
  9218. objectType({ isExpression: booleanType().optional() }).optional()
  9219. )
  9220. }).optional()
  9221. ).optional()
  9222. }).optional();
  9223. latestVersion = literalType("6");
  9224. schemaInternal3 = objectType({
  9225. version: latestVersion,
  9226. dialect: dialect3,
  9227. tables: recordType(stringType(), table5),
  9228. views: recordType(stringType(), view4).default({}),
  9229. enums: objectType({}),
  9230. _meta: objectType({
  9231. tables: recordType(stringType(), stringType()),
  9232. columns: recordType(stringType(), stringType())
  9233. }),
  9234. internal: kitInternals5
  9235. }).strict();
  9236. schemaV32 = schemaInternalV32.merge(schemaHash5).strict();
  9237. schemaV42 = schemaInternalV42.merge(schemaHash5).strict();
  9238. schemaV52 = schemaInternalV52.merge(schemaHash5).strict();
  9239. schema3 = schemaInternal3.merge(schemaHash5).strict();
  9240. tableSquashed5 = objectType({
  9241. name: stringType(),
  9242. columns: recordType(stringType(), column5),
  9243. indexes: recordType(stringType(), stringType()),
  9244. foreignKeys: recordType(stringType(), stringType()),
  9245. compositePrimaryKeys: recordType(stringType(), stringType()),
  9246. uniqueConstraints: recordType(stringType(), stringType()).default({}),
  9247. checkConstraints: recordType(stringType(), stringType()).default({})
  9248. }).strict();
  9249. schemaSquashed3 = objectType({
  9250. version: latestVersion,
  9251. dialect: dialect3,
  9252. tables: recordType(stringType(), tableSquashed5),
  9253. views: recordType(stringType(), view4),
  9254. enums: anyType()
  9255. }).strict();
  9256. SQLiteSquasher = {
  9257. squashIdx: (idx) => {
  9258. index5.parse(idx);
  9259. return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`;
  9260. },
  9261. unsquashIdx: (input) => {
  9262. const [name, columnsString, isUnique, where] = input.split(";");
  9263. const result = index5.parse({
  9264. name,
  9265. columns: columnsString.split(","),
  9266. isUnique: isUnique === "true",
  9267. where: where ?? void 0
  9268. });
  9269. return result;
  9270. },
  9271. squashUnique: (unq) => {
  9272. return `${unq.name};${unq.columns.join(",")}`;
  9273. },
  9274. unsquashUnique: (unq) => {
  9275. const [name, columns] = unq.split(";");
  9276. return { name, columns: columns.split(",") };
  9277. },
  9278. squashFK: (fk5) => {
  9279. return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
  9280. },
  9281. unsquashFK: (input) => {
  9282. const [
  9283. name,
  9284. tableFrom,
  9285. columnsFromStr,
  9286. tableTo,
  9287. columnsToStr,
  9288. onUpdate,
  9289. onDelete
  9290. ] = input.split(";");
  9291. const result = fk4.parse({
  9292. name,
  9293. tableFrom,
  9294. columnsFrom: columnsFromStr.split(","),
  9295. tableTo,
  9296. columnsTo: columnsToStr.split(","),
  9297. onUpdate,
  9298. onDelete
  9299. });
  9300. return result;
  9301. },
  9302. squashPushFK: (fk5) => {
  9303. return `${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
  9304. },
  9305. unsquashPushFK: (input) => {
  9306. const [
  9307. tableFrom,
  9308. columnsFromStr,
  9309. tableTo,
  9310. columnsToStr,
  9311. onUpdate,
  9312. onDelete
  9313. ] = input.split(";");
  9314. const result = fk4.parse({
  9315. name: "",
  9316. tableFrom,
  9317. columnsFrom: columnsFromStr.split(","),
  9318. tableTo,
  9319. columnsTo: columnsToStr.split(","),
  9320. onUpdate,
  9321. onDelete
  9322. });
  9323. return result;
  9324. },
  9325. squashPK: (pk) => {
  9326. return pk.columns.join(",");
  9327. },
  9328. unsquashPK: (pk) => {
  9329. return pk.split(",");
  9330. },
  9331. squashCheck: (check) => {
  9332. return `${check.name};${check.value}`;
  9333. },
  9334. unsquashCheck: (input) => {
  9335. const [
  9336. name,
  9337. value
  9338. ] = input.split(";");
  9339. return { name, value };
  9340. }
  9341. };
  9342. squashSqliteScheme = (json, action) => {
  9343. const mappedTables = Object.fromEntries(
  9344. Object.entries(json.tables).map((it) => {
  9345. const squashedIndexes = mapValues(it[1].indexes, (index6) => {
  9346. return SQLiteSquasher.squashIdx(index6);
  9347. });
  9348. const squashedFKs = customMapEntries(
  9349. it[1].foreignKeys,
  9350. (key, value) => {
  9351. return action === "push" ? [
  9352. SQLiteSquasher.squashPushFK(value),
  9353. SQLiteSquasher.squashPushFK(value)
  9354. ] : [key, SQLiteSquasher.squashFK(value)];
  9355. }
  9356. );
  9357. const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
  9358. return SQLiteSquasher.squashPK(pk);
  9359. });
  9360. const squashedUniqueConstraints = mapValues(
  9361. it[1].uniqueConstraints,
  9362. (unq) => {
  9363. return SQLiteSquasher.squashUnique(unq);
  9364. }
  9365. );
  9366. const squashedCheckConstraints = mapValues(
  9367. it[1].checkConstraints,
  9368. (check) => {
  9369. return SQLiteSquasher.squashCheck(check);
  9370. }
  9371. );
  9372. return [
  9373. it[0],
  9374. {
  9375. name: it[1].name,
  9376. columns: it[1].columns,
  9377. indexes: squashedIndexes,
  9378. foreignKeys: squashedFKs,
  9379. compositePrimaryKeys: squashedPKs,
  9380. uniqueConstraints: squashedUniqueConstraints,
  9381. checkConstraints: squashedCheckConstraints
  9382. }
  9383. ];
  9384. })
  9385. );
  9386. return {
  9387. version: "6",
  9388. dialect: json.dialect,
  9389. tables: mappedTables,
  9390. views: json.views,
  9391. enums: json.enums
  9392. };
  9393. };
  9394. drySQLite = schema3.parse({
  9395. version: "6",
  9396. dialect: "sqlite",
  9397. id: originUUID,
  9398. prevId: "",
  9399. tables: {},
  9400. views: {},
  9401. enums: {},
  9402. _meta: {
  9403. tables: {},
  9404. columns: {}
  9405. }
  9406. });
  9407. sqliteSchemaV5 = schemaV52;
  9408. sqliteSchema = schema3;
  9409. SQLiteSchemaSquashed = schemaSquashed3;
  9410. backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]);
  9411. }
  9412. });
  9413. // src/utils.ts
  9414. import { parse } from "url";
  9415. function isPgArrayType(sqlType) {
  9416. return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
  9417. }
  9418. function findAddedAndRemoved(columnNames1, columnNames2) {
  9419. const set1 = new Set(columnNames1);
  9420. const set2 = new Set(columnNames2);
  9421. const addedColumns = columnNames2.filter((it) => !set1.has(it));
  9422. const removedColumns = columnNames1.filter((it) => !set2.has(it));
  9423. return { addedColumns, removedColumns };
  9424. }
  9425. function escapeSingleQuotes(str) {
  9426. return str.replace(/'/g, "''");
  9427. }
  9428. var copy, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl, normalisePGliteUrl;
  9429. var init_utils = __esm({
  9430. "src/utils.ts"() {
  9431. "use strict";
  9432. init_views();
  9433. init_global();
  9434. init_gelSchema();
  9435. init_mysqlSchema();
  9436. init_pgSchema();
  9437. init_singlestoreSchema();
  9438. init_sqliteSchema();
  9439. copy = (it) => {
  9440. return JSON.parse(JSON.stringify(it));
  9441. };
  9442. prepareMigrationMeta = (schemas, tables, columns) => {
  9443. const _meta = {
  9444. schemas: {},
  9445. tables: {},
  9446. columns: {}
  9447. };
  9448. schemas.forEach((it) => {
  9449. const from = schemaRenameKey(it.from);
  9450. const to = schemaRenameKey(it.to);
  9451. _meta.schemas[from] = to;
  9452. });
  9453. tables.forEach((it) => {
  9454. const from = tableRenameKey(it.from);
  9455. const to = tableRenameKey(it.to);
  9456. _meta.tables[from] = to;
  9457. });
  9458. columns.forEach((it) => {
  9459. const from = columnRenameKey(it.from.table, it.from.schema, it.from.column);
  9460. const to = columnRenameKey(it.to.table, it.to.schema, it.to.column);
  9461. _meta.columns[from] = to;
  9462. });
  9463. return _meta;
  9464. };
  9465. schemaRenameKey = (it) => {
  9466. return it;
  9467. };
  9468. tableRenameKey = (it) => {
  9469. const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`;
  9470. return out;
  9471. };
  9472. columnRenameKey = (table6, schema6, column6) => {
  9473. const out = schema6 ? `"${schema6}"."${table6}"."${column6}"` : `"${table6}"."${column6}"`;
  9474. return out;
  9475. };
  9476. normaliseSQLiteUrl = (it, type) => {
  9477. if (type === "libsql") {
  9478. if (it.startsWith("file:")) {
  9479. return it;
  9480. }
  9481. try {
  9482. const url = parse(it);
  9483. if (url.protocol === null) {
  9484. return `file:${it}`;
  9485. }
  9486. return it;
  9487. } catch (e6) {
  9488. return `file:${it}`;
  9489. }
  9490. }
  9491. if (type === "better-sqlite") {
  9492. if (it.startsWith("file:")) {
  9493. return it.substring(5);
  9494. }
  9495. return it;
  9496. }
  9497. assertUnreachable(type);
  9498. };
  9499. normalisePGliteUrl = (it) => {
  9500. if (it.startsWith("file:")) {
  9501. return it.substring(5);
  9502. }
  9503. return it;
  9504. };
  9505. }
  9506. });
  9507. // src/cli/views.ts
  9508. var import_hanji, warning, err, error, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, ProgressView;
  9509. var init_views = __esm({
  9510. "src/cli/views.ts"() {
  9511. "use strict";
  9512. init_source();
  9513. import_hanji = __toESM(require_hanji());
  9514. init_utils();
  9515. warning = (msg) => {
  9516. (0, import_hanji.render)(`[${source_default.yellow("Warning")}] ${msg}`);
  9517. };
  9518. err = (msg) => {
  9519. (0, import_hanji.render)(`${source_default.bold.red("Error")} ${msg}`);
  9520. };
  9521. error = (error2, greyMsg = "") => {
  9522. return `${source_default.bgRed.bold(" Error ")} ${error2} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
  9523. };
  9524. isRenamePromptItem = (item) => {
  9525. return "from" in item && "to" in item;
  9526. };
  9527. ResolveColumnSelect = class extends import_hanji.Prompt {
  9528. constructor(tableName, base, data) {
  9529. super();
  9530. this.tableName = tableName;
  9531. this.base = base;
  9532. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  9533. this.data = new import_hanji.SelectState(data);
  9534. this.data.bind(this);
  9535. }
  9536. render(status) {
  9537. if (status === "submitted" || status === "aborted") {
  9538. return "\n";
  9539. }
  9540. let text = `
  9541. Is ${source_default.bold.blue(
  9542. this.base.name
  9543. )} column in ${source_default.bold.blue(
  9544. this.tableName
  9545. )} table created or renamed from another column?
  9546. `;
  9547. const isSelectedRenamed = isRenamePromptItem(
  9548. this.data.items[this.data.selectedIdx]
  9549. );
  9550. const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
  9551. const labelLength = this.data.items.filter((it) => isRenamePromptItem(it)).map((it) => {
  9552. return this.base.name.length + 3 + it["from"].name.length;
  9553. }).reduce((a5, b5) => {
  9554. if (a5 > b5) {
  9555. return a5;
  9556. }
  9557. return b5;
  9558. }, 0);
  9559. this.data.items.forEach((it, idx) => {
  9560. const isSelected = idx === this.data.selectedIdx;
  9561. const isRenamed = isRenamePromptItem(it);
  9562. const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
  9563. const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename column")}` : `${source_default.green("+")} ${title} ${source_default.gray("create column")}`;
  9564. text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
  9565. text += idx !== this.data.items.length - 1 ? "\n" : "";
  9566. });
  9567. return text;
  9568. }
  9569. result() {
  9570. return this.data.items[this.data.selectedIdx];
  9571. }
  9572. };
  9573. tableKey = (it) => {
  9574. return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`;
  9575. };
  9576. ResolveSelectNamed = class extends import_hanji.Prompt {
  9577. constructor(base, data, entityType) {
  9578. super();
  9579. this.base = base;
  9580. this.entityType = entityType;
  9581. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  9582. this.state = new import_hanji.SelectState(data);
  9583. this.state.bind(this);
  9584. }
  9585. render(status) {
  9586. if (status === "submitted" || status === "aborted") {
  9587. return "";
  9588. }
  9589. const key = this.base.name;
  9590. let text = `
  9591. Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
  9592. `;
  9593. const isSelectedRenamed = isRenamePromptItem(
  9594. this.state.items[this.state.selectedIdx]
  9595. );
  9596. const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
  9597. const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => {
  9598. const it = _3;
  9599. const keyFrom = it.from.name;
  9600. return key.length + 3 + keyFrom.length;
  9601. }).reduce((a5, b5) => {
  9602. if (a5 > b5) {
  9603. return a5;
  9604. }
  9605. return b5;
  9606. }, 0);
  9607. const entityType = this.entityType;
  9608. this.state.items.forEach((it, idx) => {
  9609. const isSelected = idx === this.state.selectedIdx;
  9610. const isRenamed = isRenamePromptItem(it);
  9611. const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
  9612. const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
  9613. text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
  9614. text += idx !== this.state.items.length - 1 ? "\n" : "";
  9615. });
  9616. return text;
  9617. }
  9618. result() {
  9619. return this.state.items[this.state.selectedIdx];
  9620. }
  9621. };
  9622. ResolveSelect = class extends import_hanji.Prompt {
  9623. constructor(base, data, entityType) {
  9624. super();
  9625. this.base = base;
  9626. this.entityType = entityType;
  9627. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  9628. this.state = new import_hanji.SelectState(data);
  9629. this.state.bind(this);
  9630. this.base = base;
  9631. }
  9632. render(status) {
  9633. if (status === "submitted" || status === "aborted") {
  9634. return "";
  9635. }
  9636. const key = tableKey(this.base);
  9637. let text = `
  9638. Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
  9639. `;
  9640. const isSelectedRenamed = isRenamePromptItem(
  9641. this.state.items[this.state.selectedIdx]
  9642. );
  9643. const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
  9644. const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => {
  9645. const it = _3;
  9646. const keyFrom = tableKey(it.from);
  9647. return key.length + 3 + keyFrom.length;
  9648. }).reduce((a5, b5) => {
  9649. if (a5 > b5) {
  9650. return a5;
  9651. }
  9652. return b5;
  9653. }, 0);
  9654. const entityType = this.entityType;
  9655. this.state.items.forEach((it, idx) => {
  9656. const isSelected = idx === this.state.selectedIdx;
  9657. const isRenamed = isRenamePromptItem(it);
  9658. const title = isRenamed ? `${tableKey(it.from)} \u203A ${tableKey(it.to)}`.padEnd(labelLength, " ") : tableKey(it).padEnd(labelLength, " ");
  9659. const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
  9660. text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
  9661. text += idx !== this.state.items.length - 1 ? "\n" : "";
  9662. });
  9663. return text;
  9664. }
  9665. result() {
  9666. return this.state.items[this.state.selectedIdx];
  9667. }
  9668. };
  9669. ResolveSchemasSelect = class extends import_hanji.Prompt {
  9670. constructor(base, data) {
  9671. super();
  9672. this.base = base;
  9673. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  9674. this.state = new import_hanji.SelectState(data);
  9675. this.state.bind(this);
  9676. this.base = base;
  9677. }
  9678. render(status) {
  9679. if (status === "submitted" || status === "aborted") {
  9680. return "";
  9681. }
  9682. let text = `
  9683. Is ${source_default.bold.blue(
  9684. this.base.name
  9685. )} schema created or renamed from another schema?
  9686. `;
  9687. const isSelectedRenamed = isRenamePromptItem(
  9688. this.state.items[this.state.selectedIdx]
  9689. );
  9690. const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
  9691. const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((it) => {
  9692. return this.base.name.length + 3 + it["from"].name.length;
  9693. }).reduce((a5, b5) => {
  9694. if (a5 > b5) {
  9695. return a5;
  9696. }
  9697. return b5;
  9698. }, 0);
  9699. this.state.items.forEach((it, idx) => {
  9700. const isSelected = idx === this.state.selectedIdx;
  9701. const isRenamed = isRenamePromptItem(it);
  9702. const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
  9703. const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename schema")}` : `${source_default.green("+")} ${title} ${source_default.gray("create schema")}`;
  9704. text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
  9705. text += idx !== this.state.items.length - 1 ? "\n" : "";
  9706. });
  9707. return text;
  9708. }
  9709. result() {
  9710. return this.state.items[this.state.selectedIdx];
  9711. }
  9712. };
  9713. Spinner = class {
  9714. constructor(frames) {
  9715. this.frames = frames;
  9716. this.offset = 0;
  9717. this.tick = () => {
  9718. this.iterator();
  9719. };
  9720. this.value = () => {
  9721. return this.frames[this.offset];
  9722. };
  9723. this.iterator = () => {
  9724. this.offset += 1;
  9725. this.offset %= frames.length - 1;
  9726. };
  9727. }
  9728. };
  9729. ProgressView = class extends import_hanji.TaskView {
  9730. constructor(progressText, successText) {
  9731. super();
  9732. this.progressText = progressText;
  9733. this.successText = successText;
  9734. this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
  9735. this.timeout = setInterval(() => {
  9736. this.spinner.tick();
  9737. this.requestLayout();
  9738. }, 128);
  9739. this.on("detach", () => clearInterval(this.timeout));
  9740. }
  9741. render(status) {
  9742. if (status === "pending" || status === "rejected") {
  9743. const spin = this.spinner.value();
  9744. return `[${spin}] ${this.progressText}
  9745. `;
  9746. }
  9747. return `[${source_default.green("\u2713")}] ${this.successText}
  9748. `;
  9749. }
  9750. };
  9751. }
  9752. });
  9753. // src/serializer/index.ts
  9754. import fs from "fs";
  9755. import Path from "path";
  9756. var glob, prepareFilenames;
  9757. var init_serializer = __esm({
  9758. "src/serializer/index.ts"() {
  9759. "use strict";
  9760. glob = __toESM(require_glob());
  9761. init_views();
  9762. prepareFilenames = (path3) => {
  9763. if (typeof path3 === "string") {
  9764. path3 = [path3];
  9765. }
  9766. const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || "";
  9767. const result = path3.reduce((result2, cur) => {
  9768. const globbed = glob.sync(`${prefix2}${cur}`);
  9769. globbed.forEach((it) => {
  9770. const fileName = fs.lstatSync(it).isDirectory() ? null : Path.resolve(it);
  9771. const filenames = fileName ? [fileName] : fs.readdirSync(it).map((file) => Path.join(Path.resolve(it), file));
  9772. filenames.filter((file) => !fs.lstatSync(file).isDirectory()).forEach((file) => result2.add(file));
  9773. });
  9774. return result2;
  9775. }, /* @__PURE__ */ new Set());
  9776. const res = [...result];
  9777. const errors = res.filter((it) => {
  9778. return !(it.endsWith(".ts") || it.endsWith(".js") || it.endsWith(".cjs") || it.endsWith(".mjs") || it.endsWith(".mts") || it.endsWith(".cts"));
  9779. });
  9780. if (res.length === 0) {
  9781. console.log(
  9782. error(
  9783. `No schema files found for path config [${path3.map((it) => `'${it}'`).join(", ")}]`
  9784. )
  9785. );
  9786. console.log(
  9787. error(
  9788. `If path represents a file - please make sure to use .ts or other extension in the path`
  9789. )
  9790. );
  9791. process.exit(1);
  9792. }
  9793. return res;
  9794. };
  9795. }
  9796. });
  9797. // src/migrationPreparator.ts
  9798. var init_migrationPreparator = __esm({
  9799. "src/migrationPreparator.ts"() {
  9800. "use strict";
  9801. init_serializer();
  9802. init_mysqlSchema();
  9803. init_pgSchema();
  9804. init_singlestoreSchema();
  9805. init_sqliteSchema();
  9806. }
  9807. });
  9808. // ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js
  9809. var require_heap = __commonJS({
  9810. "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js"(exports, module) {
  9811. "use strict";
  9812. (function() {
  9813. var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
  9814. floor = Math.floor, min = Math.min;
  9815. defaultCmp = function(x5, y2) {
  9816. if (x5 < y2) {
  9817. return -1;
  9818. }
  9819. if (x5 > y2) {
  9820. return 1;
  9821. }
  9822. return 0;
  9823. };
  9824. insort = function(a5, x5, lo, hi, cmp) {
  9825. var mid;
  9826. if (lo == null) {
  9827. lo = 0;
  9828. }
  9829. if (cmp == null) {
  9830. cmp = defaultCmp;
  9831. }
  9832. if (lo < 0) {
  9833. throw new Error("lo must be non-negative");
  9834. }
  9835. if (hi == null) {
  9836. hi = a5.length;
  9837. }
  9838. while (lo < hi) {
  9839. mid = floor((lo + hi) / 2);
  9840. if (cmp(x5, a5[mid]) < 0) {
  9841. hi = mid;
  9842. } else {
  9843. lo = mid + 1;
  9844. }
  9845. }
  9846. return [].splice.apply(a5, [lo, lo - lo].concat(x5)), x5;
  9847. };
  9848. heappush = function(array2, item, cmp) {
  9849. if (cmp == null) {
  9850. cmp = defaultCmp;
  9851. }
  9852. array2.push(item);
  9853. return _siftdown(array2, 0, array2.length - 1, cmp);
  9854. };
  9855. heappop = function(array2, cmp) {
  9856. var lastelt, returnitem;
  9857. if (cmp == null) {
  9858. cmp = defaultCmp;
  9859. }
  9860. lastelt = array2.pop();
  9861. if (array2.length) {
  9862. returnitem = array2[0];
  9863. array2[0] = lastelt;
  9864. _siftup(array2, 0, cmp);
  9865. } else {
  9866. returnitem = lastelt;
  9867. }
  9868. return returnitem;
  9869. };
  9870. heapreplace = function(array2, item, cmp) {
  9871. var returnitem;
  9872. if (cmp == null) {
  9873. cmp = defaultCmp;
  9874. }
  9875. returnitem = array2[0];
  9876. array2[0] = item;
  9877. _siftup(array2, 0, cmp);
  9878. return returnitem;
  9879. };
  9880. heappushpop = function(array2, item, cmp) {
  9881. var _ref;
  9882. if (cmp == null) {
  9883. cmp = defaultCmp;
  9884. }
  9885. if (array2.length && cmp(array2[0], item) < 0) {
  9886. _ref = [array2[0], item], item = _ref[0], array2[0] = _ref[1];
  9887. _siftup(array2, 0, cmp);
  9888. }
  9889. return item;
  9890. };
  9891. heapify = function(array2, cmp) {
  9892. var i6, _i, _j, _len, _ref, _ref1, _results, _results1;
  9893. if (cmp == null) {
  9894. cmp = defaultCmp;
  9895. }
  9896. _ref1 = function() {
  9897. _results1 = [];
  9898. for (var _j2 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
  9899. _results1.push(_j2);
  9900. }
  9901. return _results1;
  9902. }.apply(this).reverse();
  9903. _results = [];
  9904. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  9905. i6 = _ref1[_i];
  9906. _results.push(_siftup(array2, i6, cmp));
  9907. }
  9908. return _results;
  9909. };
  9910. updateItem = function(array2, item, cmp) {
  9911. var pos;
  9912. if (cmp == null) {
  9913. cmp = defaultCmp;
  9914. }
  9915. pos = array2.indexOf(item);
  9916. if (pos === -1) {
  9917. return;
  9918. }
  9919. _siftdown(array2, 0, pos, cmp);
  9920. return _siftup(array2, pos, cmp);
  9921. };
  9922. nlargest = function(array2, n5, cmp) {
  9923. var elem, result, _i, _len, _ref;
  9924. if (cmp == null) {
  9925. cmp = defaultCmp;
  9926. }
  9927. result = array2.slice(0, n5);
  9928. if (!result.length) {
  9929. return result;
  9930. }
  9931. heapify(result, cmp);
  9932. _ref = array2.slice(n5);
  9933. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  9934. elem = _ref[_i];
  9935. heappushpop(result, elem, cmp);
  9936. }
  9937. return result.sort(cmp).reverse();
  9938. };
  9939. nsmallest = function(array2, n5, cmp) {
  9940. var elem, i6, los, result, _i, _j, _len, _ref, _ref1, _results;
  9941. if (cmp == null) {
  9942. cmp = defaultCmp;
  9943. }
  9944. if (n5 * 10 <= array2.length) {
  9945. result = array2.slice(0, n5).sort(cmp);
  9946. if (!result.length) {
  9947. return result;
  9948. }
  9949. los = result[result.length - 1];
  9950. _ref = array2.slice(n5);
  9951. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  9952. elem = _ref[_i];
  9953. if (cmp(elem, los) < 0) {
  9954. insort(result, elem, 0, null, cmp);
  9955. result.pop();
  9956. los = result[result.length - 1];
  9957. }
  9958. }
  9959. return result;
  9960. }
  9961. heapify(array2, cmp);
  9962. _results = [];
  9963. for (i6 = _j = 0, _ref1 = min(n5, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i6 = 0 <= _ref1 ? ++_j : --_j) {
  9964. _results.push(heappop(array2, cmp));
  9965. }
  9966. return _results;
  9967. };
  9968. _siftdown = function(array2, startpos, pos, cmp) {
  9969. var newitem, parent, parentpos;
  9970. if (cmp == null) {
  9971. cmp = defaultCmp;
  9972. }
  9973. newitem = array2[pos];
  9974. while (pos > startpos) {
  9975. parentpos = pos - 1 >> 1;
  9976. parent = array2[parentpos];
  9977. if (cmp(newitem, parent) < 0) {
  9978. array2[pos] = parent;
  9979. pos = parentpos;
  9980. continue;
  9981. }
  9982. break;
  9983. }
  9984. return array2[pos] = newitem;
  9985. };
  9986. _siftup = function(array2, pos, cmp) {
  9987. var childpos, endpos, newitem, rightpos, startpos;
  9988. if (cmp == null) {
  9989. cmp = defaultCmp;
  9990. }
  9991. endpos = array2.length;
  9992. startpos = pos;
  9993. newitem = array2[pos];
  9994. childpos = 2 * pos + 1;
  9995. while (childpos < endpos) {
  9996. rightpos = childpos + 1;
  9997. if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) {
  9998. childpos = rightpos;
  9999. }
  10000. array2[pos] = array2[childpos];
  10001. pos = childpos;
  10002. childpos = 2 * pos + 1;
  10003. }
  10004. array2[pos] = newitem;
  10005. return _siftdown(array2, startpos, pos, cmp);
  10006. };
  10007. Heap = function() {
  10008. Heap2.push = heappush;
  10009. Heap2.pop = heappop;
  10010. Heap2.replace = heapreplace;
  10011. Heap2.pushpop = heappushpop;
  10012. Heap2.heapify = heapify;
  10013. Heap2.updateItem = updateItem;
  10014. Heap2.nlargest = nlargest;
  10015. Heap2.nsmallest = nsmallest;
  10016. function Heap2(cmp) {
  10017. this.cmp = cmp != null ? cmp : defaultCmp;
  10018. this.nodes = [];
  10019. }
  10020. Heap2.prototype.push = function(x5) {
  10021. return heappush(this.nodes, x5, this.cmp);
  10022. };
  10023. Heap2.prototype.pop = function() {
  10024. return heappop(this.nodes, this.cmp);
  10025. };
  10026. Heap2.prototype.peek = function() {
  10027. return this.nodes[0];
  10028. };
  10029. Heap2.prototype.contains = function(x5) {
  10030. return this.nodes.indexOf(x5) !== -1;
  10031. };
  10032. Heap2.prototype.replace = function(x5) {
  10033. return heapreplace(this.nodes, x5, this.cmp);
  10034. };
  10035. Heap2.prototype.pushpop = function(x5) {
  10036. return heappushpop(this.nodes, x5, this.cmp);
  10037. };
  10038. Heap2.prototype.heapify = function() {
  10039. return heapify(this.nodes, this.cmp);
  10040. };
  10041. Heap2.prototype.updateItem = function(x5) {
  10042. return updateItem(this.nodes, x5, this.cmp);
  10043. };
  10044. Heap2.prototype.clear = function() {
  10045. return this.nodes = [];
  10046. };
  10047. Heap2.prototype.empty = function() {
  10048. return this.nodes.length === 0;
  10049. };
  10050. Heap2.prototype.size = function() {
  10051. return this.nodes.length;
  10052. };
  10053. Heap2.prototype.clone = function() {
  10054. var heap;
  10055. heap = new Heap2();
  10056. heap.nodes = this.nodes.slice(0);
  10057. return heap;
  10058. };
  10059. Heap2.prototype.toArray = function() {
  10060. return this.nodes.slice(0);
  10061. };
  10062. Heap2.prototype.insert = Heap2.prototype.push;
  10063. Heap2.prototype.top = Heap2.prototype.peek;
  10064. Heap2.prototype.front = Heap2.prototype.peek;
  10065. Heap2.prototype.has = Heap2.prototype.contains;
  10066. Heap2.prototype.copy = Heap2.prototype.clone;
  10067. return Heap2;
  10068. }();
  10069. (function(root, factory) {
  10070. if (typeof define === "function" && define.amd) {
  10071. return define([], factory);
  10072. } else if (typeof exports === "object") {
  10073. return module.exports = factory();
  10074. } else {
  10075. return root.Heap = factory();
  10076. }
  10077. })(this, function() {
  10078. return Heap;
  10079. });
  10080. }).call(exports);
  10081. }
  10082. });
  10083. // ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js
  10084. var require_heap2 = __commonJS({
  10085. "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js"(exports, module) {
  10086. "use strict";
  10087. module.exports = require_heap();
  10088. }
  10089. });
  10090. // ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js
  10091. var require_difflib = __commonJS({
  10092. "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js"(exports) {
  10093. "use strict";
  10094. (function() {
  10095. var Differ, Heap, IS_CHARACTER_JUNK, IS_LINE_JUNK, SequenceMatcher, _any, _arrayCmp, _calculateRatio, _countLeading, _formatRangeContext, _formatRangeUnified, _has, assert, contextDiff, floor, getCloseMatches, max, min, ndiff, restore, unifiedDiff, indexOf = [].indexOf;
  10096. ({ floor, max, min } = Math);
  10097. Heap = require_heap2();
  10098. assert = __require("assert");
  10099. _calculateRatio = function(matches, length) {
  10100. if (length) {
  10101. return 2 * matches / length;
  10102. } else {
  10103. return 1;
  10104. }
  10105. };
  10106. _arrayCmp = function(a5, b5) {
  10107. var i6, l5, la, lb, ref;
  10108. [la, lb] = [a5.length, b5.length];
  10109. for (i6 = l5 = 0, ref = min(la, lb); 0 <= ref ? l5 < ref : l5 > ref; i6 = 0 <= ref ? ++l5 : --l5) {
  10110. if (a5[i6] < b5[i6]) {
  10111. return -1;
  10112. }
  10113. if (a5[i6] > b5[i6]) {
  10114. return 1;
  10115. }
  10116. }
  10117. return la - lb;
  10118. };
  10119. _has = function(obj, key) {
  10120. return Object.prototype.hasOwnProperty.call(obj, key);
  10121. };
  10122. _any = function(items) {
  10123. var item, l5, len;
  10124. for (l5 = 0, len = items.length; l5 < len; l5++) {
  10125. item = items[l5];
  10126. if (item) {
  10127. return true;
  10128. }
  10129. }
  10130. return false;
  10131. };
  10132. SequenceMatcher = class SequenceMatcher {
  10133. /*
  10134. SequenceMatcher is a flexible class for comparing pairs of sequences of
  10135. any type, so long as the sequence elements are hashable. The basic
  10136. algorithm predates, and is a little fancier than, an algorithm
  10137. published in the late 1980's by Ratcliff and Obershelp under the
  10138. hyperbolic name "gestalt pattern matching". The basic idea is to find
  10139. the longest contiguous matching subsequence that contains no "junk"
  10140. elements (R-O doesn't address junk). The same idea is then applied
  10141. recursively to the pieces of the sequences to the left and to the right
  10142. of the matching subsequence. This does not yield minimal edit
  10143. sequences, but does tend to yield matches that "look right" to people.
  10144. SequenceMatcher tries to compute a "human-friendly diff" between two
  10145. sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
  10146. longest *contiguous* & junk-free matching subsequence. That's what
  10147. catches peoples' eyes. The Windows(tm) windiff has another interesting
  10148. notion, pairing up elements that appear uniquely in each sequence.
  10149. That, and the method here, appear to yield more intuitive difference
  10150. reports than does diff. This method appears to be the least vulnerable
  10151. to synching up on blocks of "junk lines", though (like blank lines in
  10152. ordinary text files, or maybe "<P>" lines in HTML files). That may be
  10153. because this is the only method of the 3 that has a *concept* of
  10154. "junk" <wink>.
  10155. Example, comparing two strings, and considering blanks to be "junk":
  10156. >>> isjunk = (c) -> c is ' '
  10157. >>> s = new SequenceMatcher(isjunk,
  10158. 'private Thread currentThread;',
  10159. 'private volatile Thread currentThread;')
  10160. .ratio() returns a float in [0, 1], measuring the "similarity" of the
  10161. sequences. As a rule of thumb, a .ratio() value over 0.6 means the
  10162. sequences are close matches:
  10163. >>> s.ratio().toPrecision(3)
  10164. '0.866'
  10165. If you're only interested in where the sequences match,
  10166. .getMatchingBlocks() is handy:
  10167. >>> for [a, b, size] in s.getMatchingBlocks()
  10168. ... console.log("a[#{a}] and b[#{b}] match for #{size} elements");
  10169. a[0] and b[0] match for 8 elements
  10170. a[8] and b[17] match for 21 elements
  10171. a[29] and b[38] match for 0 elements
  10172. Note that the last tuple returned by .get_matching_blocks() is always a
  10173. dummy, (len(a), len(b), 0), and this is the only case in which the last
  10174. tuple element (number of elements matched) is 0.
  10175. If you want to know how to change the first sequence into the second,
  10176. use .get_opcodes():
  10177. >>> for [op, a1, a2, b1, b2] in s.getOpcodes()
  10178. ... console.log "#{op} a[#{a1}:#{a2}] b[#{b1}:#{b2}]"
  10179. equal a[0:8] b[0:8]
  10180. insert a[8:8] b[8:17]
  10181. equal a[8:29] b[17:38]
  10182. See the Differ class for a fancy human-friendly file differencer, which
  10183. uses SequenceMatcher both to compare sequences of lines, and to compare
  10184. sequences of characters within similar (near-matching) lines.
  10185. See also function getCloseMatches() in this module, which shows how
  10186. simple code building on SequenceMatcher can be used to do useful work.
  10187. Timing: Basic R-O is cubic time worst case and quadratic time expected
  10188. case. SequenceMatcher is quadratic time for the worst case and has
  10189. expected-case behavior dependent in a complicated way on how many
  10190. elements the sequences have in common; best case time is linear.
  10191. Methods:
  10192. constructor(isjunk=null, a='', b='')
  10193. Construct a SequenceMatcher.
  10194. setSeqs(a, b)
  10195. Set the two sequences to be compared.
  10196. setSeq1(a)
  10197. Set the first sequence to be compared.
  10198. setSeq2(b)
  10199. Set the second sequence to be compared.
  10200. findLongestMatch(alo, ahi, blo, bhi)
  10201. Find longest matching block in a[alo:ahi] and b[blo:bhi].
  10202. getMatchingBlocks()
  10203. Return list of triples describing matching subsequences.
  10204. getOpcodes()
  10205. Return list of 5-tuples describing how to turn a into b.
  10206. ratio()
  10207. Return a measure of the sequences' similarity (float in [0,1]).
  10208. quickRatio()
  10209. Return an upper bound on .ratio() relatively quickly.
  10210. realQuickRatio()
  10211. Return an upper bound on ratio() very quickly.
  10212. */
  10213. constructor(isjunk1, a5 = "", b5 = "", autojunk = true) {
  10214. this.isjunk = isjunk1;
  10215. this.autojunk = autojunk;
  10216. this.a = this.b = null;
  10217. this.setSeqs(a5, b5);
  10218. }
  10219. setSeqs(a5, b5) {
  10220. this.setSeq1(a5);
  10221. return this.setSeq2(b5);
  10222. }
  10223. setSeq1(a5) {
  10224. if (a5 === this.a) {
  10225. return;
  10226. }
  10227. this.a = a5;
  10228. return this.matchingBlocks = this.opcodes = null;
  10229. }
  10230. setSeq2(b5) {
  10231. if (b5 === this.b) {
  10232. return;
  10233. }
  10234. this.b = b5;
  10235. this.matchingBlocks = this.opcodes = null;
  10236. this.fullbcount = null;
  10237. return this._chainB();
  10238. }
  10239. // For each element x in b, set b2j[x] to a list of the indices in
  10240. // b where x appears; the indices are in increasing order; note that
  10241. // the number of times x appears in b is b2j[x].length ...
  10242. // when @isjunk is defined, junk elements don't show up in this
  10243. // map at all, which stops the central findLongestMatch method
  10244. // from starting any matching block at a junk element ...
  10245. // also creates the fast isbjunk function ...
  10246. // b2j also does not contain entries for "popular" elements, meaning
  10247. // elements that account for more than 1 + 1% of the total elements, and
  10248. // when the sequence is reasonably large (>= 200 elements); this can
  10249. // be viewed as an adaptive notion of semi-junk, and yields an enormous
  10250. // speedup when, e.g., comparing program files with hundreds of
  10251. // instances of "return null;" ...
  10252. // note that this is only called when b changes; so for cross-product
  10253. // kinds of matches, it's best to call setSeq2 once, then setSeq1
  10254. // repeatedly
  10255. _chainB() {
  10256. var b5, b2j, elt, i6, indices, isjunk, junk, l5, len, n5, ntest, popular;
  10257. b5 = this.b;
  10258. this.b2j = b2j = /* @__PURE__ */ new Map();
  10259. for (i6 = l5 = 0, len = b5.length; l5 < len; i6 = ++l5) {
  10260. elt = b5[i6];
  10261. if (!b2j.has(elt)) {
  10262. b2j.set(elt, []);
  10263. }
  10264. indices = b2j.get(elt);
  10265. indices.push(i6);
  10266. }
  10267. junk = /* @__PURE__ */ new Map();
  10268. isjunk = this.isjunk;
  10269. if (isjunk) {
  10270. b2j.forEach(function(idxs, elt2) {
  10271. if (isjunk(elt2)) {
  10272. junk.set(elt2, true);
  10273. return b2j.delete(elt2);
  10274. }
  10275. });
  10276. }
  10277. popular = /* @__PURE__ */ new Map();
  10278. n5 = b5.length;
  10279. if (this.autojunk && n5 >= 200) {
  10280. ntest = floor(n5 / 100) + 1;
  10281. b2j.forEach(function(idxs, elt2) {
  10282. if (idxs.length > ntest) {
  10283. popular.set(elt2, true);
  10284. return b2j.delete(elt2);
  10285. }
  10286. });
  10287. }
  10288. this.isbjunk = function(b6) {
  10289. return junk.has(b6);
  10290. };
  10291. return this.isbpopular = function(b6) {
  10292. return popular.has(b6);
  10293. };
  10294. }
  10295. findLongestMatch(alo, ahi, blo, bhi) {
  10296. var a5, b5, b2j, besti, bestj, bestsize, i6, isbjunk, j5, j2len, jlist, k5, l5, len, m6, newj2len, ref, ref1;
  10297. [a5, b5, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk];
  10298. [besti, bestj, bestsize] = [alo, blo, 0];
  10299. j2len = {};
  10300. for (i6 = l5 = ref = alo, ref1 = ahi; ref <= ref1 ? l5 < ref1 : l5 > ref1; i6 = ref <= ref1 ? ++l5 : --l5) {
  10301. newj2len = {};
  10302. jlist = [];
  10303. if (b2j.has(a5[i6])) {
  10304. jlist = b2j.get(a5[i6]);
  10305. }
  10306. for (m6 = 0, len = jlist.length; m6 < len; m6++) {
  10307. j5 = jlist[m6];
  10308. if (j5 < blo) {
  10309. continue;
  10310. }
  10311. if (j5 >= bhi) {
  10312. break;
  10313. }
  10314. k5 = newj2len[j5] = (j2len[j5 - 1] || 0) + 1;
  10315. if (k5 > bestsize) {
  10316. [besti, bestj, bestsize] = [i6 - k5 + 1, j5 - k5 + 1, k5];
  10317. }
  10318. }
  10319. j2len = newj2len;
  10320. }
  10321. while (besti > alo && bestj > blo && !isbjunk(b5[bestj - 1]) && a5[besti - 1] === b5[bestj - 1]) {
  10322. [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
  10323. }
  10324. while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b5[bestj + bestsize]) && a5[besti + bestsize] === b5[bestj + bestsize]) {
  10325. bestsize++;
  10326. }
  10327. while (besti > alo && bestj > blo && isbjunk(b5[bestj - 1]) && a5[besti - 1] === b5[bestj - 1]) {
  10328. [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
  10329. }
  10330. while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b5[bestj + bestsize]) && a5[besti + bestsize] === b5[bestj + bestsize]) {
  10331. bestsize++;
  10332. }
  10333. return [besti, bestj, bestsize];
  10334. }
  10335. getMatchingBlocks() {
  10336. var ahi, alo, bhi, blo, i6, i1, i22, j5, j1, j22, k5, k1, k22, l5, la, lb, len, matchingBlocks, nonAdjacent, queue, x5;
  10337. if (this.matchingBlocks) {
  10338. return this.matchingBlocks;
  10339. }
  10340. [la, lb] = [this.a.length, this.b.length];
  10341. queue = [[0, la, 0, lb]];
  10342. matchingBlocks = [];
  10343. while (queue.length) {
  10344. [alo, ahi, blo, bhi] = queue.pop();
  10345. [i6, j5, k5] = x5 = this.findLongestMatch(alo, ahi, blo, bhi);
  10346. if (k5) {
  10347. matchingBlocks.push(x5);
  10348. if (alo < i6 && blo < j5) {
  10349. queue.push([alo, i6, blo, j5]);
  10350. }
  10351. if (i6 + k5 < ahi && j5 + k5 < bhi) {
  10352. queue.push([i6 + k5, ahi, j5 + k5, bhi]);
  10353. }
  10354. }
  10355. }
  10356. matchingBlocks.sort(_arrayCmp);
  10357. i1 = j1 = k1 = 0;
  10358. nonAdjacent = [];
  10359. for (l5 = 0, len = matchingBlocks.length; l5 < len; l5++) {
  10360. [i22, j22, k22] = matchingBlocks[l5];
  10361. if (i1 + k1 === i22 && j1 + k1 === j22) {
  10362. k1 += k22;
  10363. } else {
  10364. if (k1) {
  10365. nonAdjacent.push([i1, j1, k1]);
  10366. }
  10367. [i1, j1, k1] = [i22, j22, k22];
  10368. }
  10369. }
  10370. if (k1) {
  10371. nonAdjacent.push([i1, j1, k1]);
  10372. }
  10373. nonAdjacent.push([la, lb, 0]);
  10374. return this.matchingBlocks = nonAdjacent;
  10375. }
  10376. getOpcodes() {
  10377. var ai, answer, bj, i6, j5, l5, len, ref, size, tag;
  10378. if (this.opcodes) {
  10379. return this.opcodes;
  10380. }
  10381. i6 = j5 = 0;
  10382. this.opcodes = answer = [];
  10383. ref = this.getMatchingBlocks();
  10384. for (l5 = 0, len = ref.length; l5 < len; l5++) {
  10385. [ai, bj, size] = ref[l5];
  10386. tag = "";
  10387. if (i6 < ai && j5 < bj) {
  10388. tag = "replace";
  10389. } else if (i6 < ai) {
  10390. tag = "delete";
  10391. } else if (j5 < bj) {
  10392. tag = "insert";
  10393. }
  10394. if (tag) {
  10395. answer.push([tag, i6, ai, j5, bj]);
  10396. }
  10397. [i6, j5] = [ai + size, bj + size];
  10398. if (size) {
  10399. answer.push(["equal", ai, i6, bj, j5]);
  10400. }
  10401. }
  10402. return answer;
  10403. }
  10404. getGroupedOpcodes(n5 = 3) {
  10405. var codes, group, groups, i1, i22, j1, j22, l5, len, nn, tag;
  10406. codes = this.getOpcodes();
  10407. if (!codes.length) {
  10408. codes = [["equal", 0, 1, 0, 1]];
  10409. }
  10410. if (codes[0][0] === "equal") {
  10411. [tag, i1, i22, j1, j22] = codes[0];
  10412. codes[0] = [tag, max(i1, i22 - n5), i22, max(j1, j22 - n5), j22];
  10413. }
  10414. if (codes[codes.length - 1][0] === "equal") {
  10415. [tag, i1, i22, j1, j22] = codes[codes.length - 1];
  10416. codes[codes.length - 1] = [tag, i1, min(i22, i1 + n5), j1, min(j22, j1 + n5)];
  10417. }
  10418. nn = n5 + n5;
  10419. groups = [];
  10420. group = [];
  10421. for (l5 = 0, len = codes.length; l5 < len; l5++) {
  10422. [tag, i1, i22, j1, j22] = codes[l5];
  10423. if (tag === "equal" && i22 - i1 > nn) {
  10424. group.push([tag, i1, min(i22, i1 + n5), j1, min(j22, j1 + n5)]);
  10425. groups.push(group);
  10426. group = [];
  10427. [i1, j1] = [max(i1, i22 - n5), max(j1, j22 - n5)];
  10428. }
  10429. group.push([tag, i1, i22, j1, j22]);
  10430. }
  10431. if (group.length && !(group.length === 1 && group[0][0] === "equal")) {
  10432. groups.push(group);
  10433. }
  10434. return groups;
  10435. }
  10436. ratio() {
  10437. var l5, len, match2, matches, ref;
  10438. matches = 0;
  10439. ref = this.getMatchingBlocks();
  10440. for (l5 = 0, len = ref.length; l5 < len; l5++) {
  10441. match2 = ref[l5];
  10442. matches += match2[2];
  10443. }
  10444. return _calculateRatio(matches, this.a.length + this.b.length);
  10445. }
  10446. quickRatio() {
  10447. var avail, elt, fullbcount, l5, len, len1, m6, matches, numb, ref, ref1;
  10448. if (!this.fullbcount) {
  10449. this.fullbcount = fullbcount = {};
  10450. ref = this.b;
  10451. for (l5 = 0, len = ref.length; l5 < len; l5++) {
  10452. elt = ref[l5];
  10453. fullbcount[elt] = (fullbcount[elt] || 0) + 1;
  10454. }
  10455. }
  10456. fullbcount = this.fullbcount;
  10457. avail = {};
  10458. matches = 0;
  10459. ref1 = this.a;
  10460. for (m6 = 0, len1 = ref1.length; m6 < len1; m6++) {
  10461. elt = ref1[m6];
  10462. if (_has(avail, elt)) {
  10463. numb = avail[elt];
  10464. } else {
  10465. numb = fullbcount[elt] || 0;
  10466. }
  10467. avail[elt] = numb - 1;
  10468. if (numb > 0) {
  10469. matches++;
  10470. }
  10471. }
  10472. return _calculateRatio(matches, this.a.length + this.b.length);
  10473. }
  10474. realQuickRatio() {
  10475. var la, lb;
  10476. [la, lb] = [this.a.length, this.b.length];
  10477. return _calculateRatio(min(la, lb), la + lb);
  10478. }
  10479. };
  10480. getCloseMatches = function(word, possibilities, n5 = 3, cutoff = 0.6) {
  10481. var l5, len, len1, m6, result, results, s6, score, x5;
  10482. if (!(n5 > 0)) {
  10483. throw new Error(`n must be > 0: (${n5})`);
  10484. }
  10485. if (!(0 <= cutoff && cutoff <= 1)) {
  10486. throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`);
  10487. }
  10488. result = [];
  10489. s6 = new SequenceMatcher();
  10490. s6.setSeq2(word);
  10491. for (l5 = 0, len = possibilities.length; l5 < len; l5++) {
  10492. x5 = possibilities[l5];
  10493. s6.setSeq1(x5);
  10494. if (s6.realQuickRatio() >= cutoff && s6.quickRatio() >= cutoff && s6.ratio() >= cutoff) {
  10495. result.push([s6.ratio(), x5]);
  10496. }
  10497. }
  10498. result = Heap.nlargest(result, n5, _arrayCmp);
  10499. results = [];
  10500. for (m6 = 0, len1 = result.length; m6 < len1; m6++) {
  10501. [score, x5] = result[m6];
  10502. results.push(x5);
  10503. }
  10504. return results;
  10505. };
  10506. _countLeading = function(line, ch) {
  10507. var i6, n5;
  10508. [i6, n5] = [0, line.length];
  10509. while (i6 < n5 && line[i6] === ch) {
  10510. i6++;
  10511. }
  10512. return i6;
  10513. };
  10514. Differ = class Differ {
  10515. /*
  10516. Differ is a class for comparing sequences of lines of text, and
  10517. producing human-readable differences or deltas. Differ uses
  10518. SequenceMatcher both to compare sequences of lines, and to compare
  10519. sequences of characters within similar (near-matching) lines.
  10520. Each line of a Differ delta begins with a two-letter code:
  10521. '- ' line unique to sequence 1
  10522. '+ ' line unique to sequence 2
  10523. ' ' line common to both sequences
  10524. '? ' line not present in either input sequence
  10525. Lines beginning with '? ' attempt to guide the eye to intraline
  10526. differences, and were not present in either input sequence. These lines
  10527. can be confusing if the sequences contain tab characters.
  10528. Note that Differ makes no claim to produce a *minimal* diff. To the
  10529. contrary, minimal diffs are often counter-intuitive, because they synch
  10530. up anywhere possible, sometimes accidental matches 100 pages apart.
  10531. Restricting synch points to contiguous matches preserves some notion of
  10532. locality, at the occasional cost of producing a longer diff.
  10533. Example: Comparing two texts.
  10534. >>> text1 = ['1. Beautiful is better than ugly.\n',
  10535. ... '2. Explicit is better than implicit.\n',
  10536. ... '3. Simple is better than complex.\n',
  10537. ... '4. Complex is better than complicated.\n']
  10538. >>> text1.length
  10539. 4
  10540. >>> text2 = ['1. Beautiful is better than ugly.\n',
  10541. ... '3. Simple is better than complex.\n',
  10542. ... '4. Complicated is better than complex.\n',
  10543. ... '5. Flat is better than nested.\n']
  10544. Next we instantiate a Differ object:
  10545. >>> d = new Differ()
  10546. Note that when instantiating a Differ object we may pass functions to
  10547. filter out line and character 'junk'.
  10548. Finally, we compare the two:
  10549. >>> result = d.compare(text1, text2)
  10550. [ ' 1. Beautiful is better than ugly.\n',
  10551. '- 2. Explicit is better than implicit.\n',
  10552. '- 3. Simple is better than complex.\n',
  10553. '+ 3. Simple is better than complex.\n',
  10554. '? ++\n',
  10555. '- 4. Complex is better than complicated.\n',
  10556. '? ^ ---- ^\n',
  10557. '+ 4. Complicated is better than complex.\n',
  10558. '? ++++ ^ ^\n',
  10559. '+ 5. Flat is better than nested.\n' ]
  10560. Methods:
  10561. constructor(linejunk=null, charjunk=null)
  10562. Construct a text differencer, with optional filters.
  10563. compare(a, b)
  10564. Compare two sequences of lines; generate the resulting delta.
  10565. */
  10566. constructor(linejunk1, charjunk1) {
  10567. this.linejunk = linejunk1;
  10568. this.charjunk = charjunk1;
  10569. }
  10570. /*
  10571. Construct a text differencer, with optional filters.
  10572. The two optional keyword parameters are for filter functions:
  10573. - `linejunk`: A function that should accept a single string argument,
  10574. and return true iff the string is junk. The module-level function
  10575. `IS_LINE_JUNK` may be used to filter out lines without visible
  10576. characters, except for at most one splat ('#'). It is recommended
  10577. to leave linejunk null.
  10578. - `charjunk`: A function that should accept a string of length 1. The
  10579. module-level function `IS_CHARACTER_JUNK` may be used to filter out
  10580. whitespace characters (a blank or tab; **note**: bad idea to include
  10581. newline in this!). Use of IS_CHARACTER_JUNK is recommended.
  10582. */
  10583. compare(a5, b5) {
  10584. var ahi, alo, bhi, blo, cruncher, g5, l5, len, len1, line, lines, m6, ref, tag;
  10585. cruncher = new SequenceMatcher(this.linejunk, a5, b5);
  10586. lines = [];
  10587. ref = cruncher.getOpcodes();
  10588. for (l5 = 0, len = ref.length; l5 < len; l5++) {
  10589. [tag, alo, ahi, blo, bhi] = ref[l5];
  10590. switch (tag) {
  10591. case "replace":
  10592. g5 = this._fancyReplace(a5, alo, ahi, b5, blo, bhi);
  10593. break;
  10594. case "delete":
  10595. g5 = this._dump("-", a5, alo, ahi);
  10596. break;
  10597. case "insert":
  10598. g5 = this._dump("+", b5, blo, bhi);
  10599. break;
  10600. case "equal":
  10601. g5 = this._dump(" ", a5, alo, ahi);
  10602. break;
  10603. default:
  10604. throw new Error(`unknow tag (${tag})`);
  10605. }
  10606. for (m6 = 0, len1 = g5.length; m6 < len1; m6++) {
  10607. line = g5[m6];
  10608. lines.push(line);
  10609. }
  10610. }
  10611. return lines;
  10612. }
  10613. _dump(tag, x5, lo, hi) {
  10614. var i6, l5, ref, ref1, results;
  10615. results = [];
  10616. for (i6 = l5 = ref = lo, ref1 = hi; ref <= ref1 ? l5 < ref1 : l5 > ref1; i6 = ref <= ref1 ? ++l5 : --l5) {
  10617. results.push(`${tag} ${x5[i6]}`);
  10618. }
  10619. return results;
  10620. }
  10621. _plainReplace(a5, alo, ahi, b5, blo, bhi) {
  10622. var first, g5, l5, len, len1, line, lines, m6, ref, second;
  10623. assert(alo < ahi && blo < bhi);
  10624. if (bhi - blo < ahi - alo) {
  10625. first = this._dump("+", b5, blo, bhi);
  10626. second = this._dump("-", a5, alo, ahi);
  10627. } else {
  10628. first = this._dump("-", a5, alo, ahi);
  10629. second = this._dump("+", b5, blo, bhi);
  10630. }
  10631. lines = [];
  10632. ref = [first, second];
  10633. for (l5 = 0, len = ref.length; l5 < len; l5++) {
  10634. g5 = ref[l5];
  10635. for (m6 = 0, len1 = g5.length; m6 < len1; m6++) {
  10636. line = g5[m6];
  10637. lines.push(line);
  10638. }
  10639. }
  10640. return lines;
  10641. }
  10642. _fancyReplace(a5, alo, ahi, b5, blo, bhi) {
  10643. var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i6, j5, l5, la, lb, len, len1, len2, len3, len4, line, lines, m6, o5, p5, q5, r6, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t6, tag;
  10644. [bestRatio, cutoff] = [0.74, 0.75];
  10645. cruncher = new SequenceMatcher(this.charjunk);
  10646. [eqi, eqj] = [
  10647. null,
  10648. null
  10649. // 1st indices of equal lines (if any)
  10650. ];
  10651. lines = [];
  10652. for (j5 = l5 = ref = blo, ref1 = bhi; ref <= ref1 ? l5 < ref1 : l5 > ref1; j5 = ref <= ref1 ? ++l5 : --l5) {
  10653. bj = b5[j5];
  10654. cruncher.setSeq2(bj);
  10655. for (i6 = m6 = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m6 < ref3 : m6 > ref3; i6 = ref2 <= ref3 ? ++m6 : --m6) {
  10656. ai = a5[i6];
  10657. if (ai === bj) {
  10658. if (eqi === null) {
  10659. [eqi, eqj] = [i6, j5];
  10660. }
  10661. continue;
  10662. }
  10663. cruncher.setSeq1(ai);
  10664. if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) {
  10665. [bestRatio, besti, bestj] = [cruncher.ratio(), i6, j5];
  10666. }
  10667. }
  10668. }
  10669. if (bestRatio < cutoff) {
  10670. if (eqi === null) {
  10671. ref4 = this._plainReplace(a5, alo, ahi, b5, blo, bhi);
  10672. for (o5 = 0, len = ref4.length; o5 < len; o5++) {
  10673. line = ref4[o5];
  10674. lines.push(line);
  10675. }
  10676. return lines;
  10677. }
  10678. [besti, bestj, bestRatio] = [eqi, eqj, 1];
  10679. } else {
  10680. eqi = null;
  10681. }
  10682. ref5 = this._fancyHelper(a5, alo, besti, b5, blo, bestj);
  10683. for (p5 = 0, len1 = ref5.length; p5 < len1; p5++) {
  10684. line = ref5[p5];
  10685. lines.push(line);
  10686. }
  10687. [aelt, belt] = [a5[besti], b5[bestj]];
  10688. if (eqi === null) {
  10689. atags = btags = "";
  10690. cruncher.setSeqs(aelt, belt);
  10691. ref6 = cruncher.getOpcodes();
  10692. for (q5 = 0, len2 = ref6.length; q5 < len2; q5++) {
  10693. [tag, ai1, ai2, bj1, bj2] = ref6[q5];
  10694. [la, lb] = [ai2 - ai1, bj2 - bj1];
  10695. switch (tag) {
  10696. case "replace":
  10697. atags += Array(la + 1).join("^");
  10698. btags += Array(lb + 1).join("^");
  10699. break;
  10700. case "delete":
  10701. atags += Array(la + 1).join("-");
  10702. break;
  10703. case "insert":
  10704. btags += Array(lb + 1).join("+");
  10705. break;
  10706. case "equal":
  10707. atags += Array(la + 1).join(" ");
  10708. btags += Array(lb + 1).join(" ");
  10709. break;
  10710. default:
  10711. throw new Error(`unknow tag (${tag})`);
  10712. }
  10713. }
  10714. ref7 = this._qformat(aelt, belt, atags, btags);
  10715. for (r6 = 0, len3 = ref7.length; r6 < len3; r6++) {
  10716. line = ref7[r6];
  10717. lines.push(line);
  10718. }
  10719. } else {
  10720. lines.push(" " + aelt);
  10721. }
  10722. ref8 = this._fancyHelper(a5, besti + 1, ahi, b5, bestj + 1, bhi);
  10723. for (t6 = 0, len4 = ref8.length; t6 < len4; t6++) {
  10724. line = ref8[t6];
  10725. lines.push(line);
  10726. }
  10727. return lines;
  10728. }
  10729. _fancyHelper(a5, alo, ahi, b5, blo, bhi) {
  10730. var g5;
  10731. g5 = [];
  10732. if (alo < ahi) {
  10733. if (blo < bhi) {
  10734. g5 = this._fancyReplace(a5, alo, ahi, b5, blo, bhi);
  10735. } else {
  10736. g5 = this._dump("-", a5, alo, ahi);
  10737. }
  10738. } else if (blo < bhi) {
  10739. g5 = this._dump("+", b5, blo, bhi);
  10740. }
  10741. return g5;
  10742. }
  10743. _qformat(aline, bline, atags, btags) {
  10744. var common, lines;
  10745. lines = [];
  10746. common = min(_countLeading(aline, " "), _countLeading(bline, " "));
  10747. common = min(common, _countLeading(atags.slice(0, common), " "));
  10748. common = min(common, _countLeading(btags.slice(0, common), " "));
  10749. atags = atags.slice(common).replace(/\s+$/, "");
  10750. btags = btags.slice(common).replace(/\s+$/, "");
  10751. lines.push("- " + aline);
  10752. if (atags.length) {
  10753. lines.push(`? ${Array(common + 1).join(" ")}${atags}
  10754. `);
  10755. }
  10756. lines.push("+ " + bline);
  10757. if (btags.length) {
  10758. lines.push(`? ${Array(common + 1).join(" ")}${btags}
  10759. `);
  10760. }
  10761. return lines;
  10762. }
  10763. };
  10764. IS_LINE_JUNK = function(line, pat = /^\s*#?\s*$/) {
  10765. return pat.test(line);
  10766. };
  10767. IS_CHARACTER_JUNK = function(ch, ws = " ") {
  10768. return indexOf.call(ws, ch) >= 0;
  10769. };
  10770. _formatRangeUnified = function(start, stop) {
  10771. var beginning, length;
  10772. beginning = start + 1;
  10773. length = stop - start;
  10774. if (length === 1) {
  10775. return `${beginning}`;
  10776. }
  10777. if (!length) {
  10778. beginning--;
  10779. }
  10780. return `${beginning},${length}`;
  10781. };
  10782. unifiedDiff = function(a5, b5, { fromfile, tofile, fromfiledate, tofiledate, n: n5, lineterm } = {}) {
  10783. var file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l5, last, len, len1, len2, len3, len4, line, lines, m6, o5, p5, q5, ref, ref1, ref2, ref3, started, tag, todate;
  10784. if (fromfile == null) {
  10785. fromfile = "";
  10786. }
  10787. if (tofile == null) {
  10788. tofile = "";
  10789. }
  10790. if (fromfiledate == null) {
  10791. fromfiledate = "";
  10792. }
  10793. if (tofiledate == null) {
  10794. tofiledate = "";
  10795. }
  10796. if (n5 == null) {
  10797. n5 = 3;
  10798. }
  10799. if (lineterm == null) {
  10800. lineterm = "\n";
  10801. }
  10802. lines = [];
  10803. started = false;
  10804. ref = new SequenceMatcher(null, a5, b5).getGroupedOpcodes();
  10805. for (l5 = 0, len = ref.length; l5 < len; l5++) {
  10806. group = ref[l5];
  10807. if (!started) {
  10808. started = true;
  10809. fromdate = fromfiledate ? ` ${fromfiledate}` : "";
  10810. todate = tofiledate ? ` ${tofiledate}` : "";
  10811. lines.push(`--- ${fromfile}${fromdate}${lineterm}`);
  10812. lines.push(`+++ ${tofile}${todate}${lineterm}`);
  10813. }
  10814. [first, last] = [group[0], group[group.length - 1]];
  10815. file1Range = _formatRangeUnified(first[1], last[2]);
  10816. file2Range = _formatRangeUnified(first[3], last[4]);
  10817. lines.push(`@@ -${file1Range} +${file2Range} @@${lineterm}`);
  10818. for (m6 = 0, len1 = group.length; m6 < len1; m6++) {
  10819. [tag, i1, i22, j1, j22] = group[m6];
  10820. if (tag === "equal") {
  10821. ref1 = a5.slice(i1, i22);
  10822. for (o5 = 0, len2 = ref1.length; o5 < len2; o5++) {
  10823. line = ref1[o5];
  10824. lines.push(" " + line);
  10825. }
  10826. continue;
  10827. }
  10828. if (tag === "replace" || tag === "delete") {
  10829. ref2 = a5.slice(i1, i22);
  10830. for (p5 = 0, len3 = ref2.length; p5 < len3; p5++) {
  10831. line = ref2[p5];
  10832. lines.push("-" + line);
  10833. }
  10834. }
  10835. if (tag === "replace" || tag === "insert") {
  10836. ref3 = b5.slice(j1, j22);
  10837. for (q5 = 0, len4 = ref3.length; q5 < len4; q5++) {
  10838. line = ref3[q5];
  10839. lines.push("+" + line);
  10840. }
  10841. }
  10842. }
  10843. }
  10844. return lines;
  10845. };
  10846. _formatRangeContext = function(start, stop) {
  10847. var beginning, length;
  10848. beginning = start + 1;
  10849. length = stop - start;
  10850. if (!length) {
  10851. beginning--;
  10852. }
  10853. if (length <= 1) {
  10854. return `${beginning}`;
  10855. }
  10856. return `${beginning},${beginning + length - 1}`;
  10857. };
  10858. contextDiff = function(a5, b5, { fromfile, tofile, fromfiledate, tofiledate, n: n5, lineterm } = {}) {
  10859. var _3, file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l5, last, len, len1, len2, len3, len4, line, lines, m6, o5, p5, prefix2, q5, ref, ref1, ref2, started, tag, todate;
  10860. if (fromfile == null) {
  10861. fromfile = "";
  10862. }
  10863. if (tofile == null) {
  10864. tofile = "";
  10865. }
  10866. if (fromfiledate == null) {
  10867. fromfiledate = "";
  10868. }
  10869. if (tofiledate == null) {
  10870. tofiledate = "";
  10871. }
  10872. if (n5 == null) {
  10873. n5 = 3;
  10874. }
  10875. if (lineterm == null) {
  10876. lineterm = "\n";
  10877. }
  10878. prefix2 = {
  10879. insert: "+ ",
  10880. delete: "- ",
  10881. replace: "! ",
  10882. equal: " "
  10883. };
  10884. started = false;
  10885. lines = [];
  10886. ref = new SequenceMatcher(null, a5, b5).getGroupedOpcodes();
  10887. for (l5 = 0, len = ref.length; l5 < len; l5++) {
  10888. group = ref[l5];
  10889. if (!started) {
  10890. started = true;
  10891. fromdate = fromfiledate ? ` ${fromfiledate}` : "";
  10892. todate = tofiledate ? ` ${tofiledate}` : "";
  10893. lines.push(`*** ${fromfile}${fromdate}${lineterm}`);
  10894. lines.push(`--- ${tofile}${todate}${lineterm}`);
  10895. [first, last] = [group[0], group[group.length - 1]];
  10896. lines.push("***************" + lineterm);
  10897. file1Range = _formatRangeContext(first[1], last[2]);
  10898. lines.push(`*** ${file1Range} ****${lineterm}`);
  10899. if (_any(function() {
  10900. var len12, m7, results;
  10901. results = [];
  10902. for (m7 = 0, len12 = group.length; m7 < len12; m7++) {
  10903. [tag, _3, _3, _3, _3] = group[m7];
  10904. results.push(tag === "replace" || tag === "delete");
  10905. }
  10906. return results;
  10907. }())) {
  10908. for (m6 = 0, len1 = group.length; m6 < len1; m6++) {
  10909. [tag, i1, i22, _3, _3] = group[m6];
  10910. if (tag !== "insert") {
  10911. ref1 = a5.slice(i1, i22);
  10912. for (o5 = 0, len2 = ref1.length; o5 < len2; o5++) {
  10913. line = ref1[o5];
  10914. lines.push(prefix2[tag] + line);
  10915. }
  10916. }
  10917. }
  10918. }
  10919. file2Range = _formatRangeContext(first[3], last[4]);
  10920. lines.push(`--- ${file2Range} ----${lineterm}`);
  10921. if (_any(function() {
  10922. var len32, p6, results;
  10923. results = [];
  10924. for (p6 = 0, len32 = group.length; p6 < len32; p6++) {
  10925. [tag, _3, _3, _3, _3] = group[p6];
  10926. results.push(tag === "replace" || tag === "insert");
  10927. }
  10928. return results;
  10929. }())) {
  10930. for (p5 = 0, len3 = group.length; p5 < len3; p5++) {
  10931. [tag, _3, _3, j1, j22] = group[p5];
  10932. if (tag !== "delete") {
  10933. ref2 = b5.slice(j1, j22);
  10934. for (q5 = 0, len4 = ref2.length; q5 < len4; q5++) {
  10935. line = ref2[q5];
  10936. lines.push(prefix2[tag] + line);
  10937. }
  10938. }
  10939. }
  10940. }
  10941. }
  10942. }
  10943. return lines;
  10944. };
  10945. ndiff = function(a5, b5, linejunk, charjunk = IS_CHARACTER_JUNK) {
  10946. return new Differ(linejunk, charjunk).compare(a5, b5);
  10947. };
  10948. restore = function(delta, which) {
  10949. var l5, len, line, lines, prefixes2, ref, tag;
  10950. tag = {
  10951. 1: "- ",
  10952. 2: "+ "
  10953. }[which];
  10954. if (!tag) {
  10955. throw new Error(`unknow delta choice (must be 1 or 2): ${which}`);
  10956. }
  10957. prefixes2 = [" ", tag];
  10958. lines = [];
  10959. for (l5 = 0, len = delta.length; l5 < len; l5++) {
  10960. line = delta[l5];
  10961. if (ref = line.slice(0, 2), indexOf.call(prefixes2, ref) >= 0) {
  10962. lines.push(line.slice(2));
  10963. }
  10964. }
  10965. return lines;
  10966. };
  10967. exports._arrayCmp = _arrayCmp;
  10968. exports.SequenceMatcher = SequenceMatcher;
  10969. exports.getCloseMatches = getCloseMatches;
  10970. exports._countLeading = _countLeading;
  10971. exports.Differ = Differ;
  10972. exports.IS_LINE_JUNK = IS_LINE_JUNK;
  10973. exports.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK;
  10974. exports._formatRangeUnified = _formatRangeUnified;
  10975. exports.unifiedDiff = unifiedDiff;
  10976. exports._formatRangeContext = _formatRangeContext;
  10977. exports.contextDiff = contextDiff;
  10978. exports.ndiff = ndiff;
  10979. exports.restore = restore;
  10980. }).call(exports);
  10981. }
  10982. });
  10983. // ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js
  10984. var require_difflib2 = __commonJS({
  10985. "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js"(exports, module) {
  10986. "use strict";
  10987. module.exports = require_difflib();
  10988. }
  10989. });
  10990. // ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js
  10991. var require_util = __commonJS({
  10992. "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js"(exports, module) {
  10993. "use strict";
  10994. var extendedTypeOf = function(obj) {
  10995. const result = typeof obj;
  10996. if (obj == null) {
  10997. return "null";
  10998. } else if (result === "object" && obj.constructor === Array) {
  10999. return "array";
  11000. } else if (result === "object" && obj instanceof Date) {
  11001. return "date";
  11002. } else {
  11003. return result;
  11004. }
  11005. };
  11006. var roundObj = function(data, precision) {
  11007. const type = typeof data;
  11008. if (type === "array") {
  11009. return data.map((x5) => roundObj(x5, precision));
  11010. } else if (type === "object") {
  11011. for (const key in data) {
  11012. data[key] = roundObj(data[key], precision);
  11013. }
  11014. return data;
  11015. } else if (type === "number" && Number.isFinite(data) && !Number.isInteger(data)) {
  11016. return +data.toFixed(precision);
  11017. } else {
  11018. return data;
  11019. }
  11020. };
  11021. module.exports = { extendedTypeOf, roundObj };
  11022. }
  11023. });
  11024. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js
  11025. var require_styles = __commonJS({
  11026. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js"(exports, module) {
  11027. "use strict";
  11028. var styles3 = {};
  11029. module["exports"] = styles3;
  11030. var codes = {
  11031. reset: [0, 0],
  11032. bold: [1, 22],
  11033. dim: [2, 22],
  11034. italic: [3, 23],
  11035. underline: [4, 24],
  11036. inverse: [7, 27],
  11037. hidden: [8, 28],
  11038. strikethrough: [9, 29],
  11039. black: [30, 39],
  11040. red: [31, 39],
  11041. green: [32, 39],
  11042. yellow: [33, 39],
  11043. blue: [34, 39],
  11044. magenta: [35, 39],
  11045. cyan: [36, 39],
  11046. white: [37, 39],
  11047. gray: [90, 39],
  11048. grey: [90, 39],
  11049. brightRed: [91, 39],
  11050. brightGreen: [92, 39],
  11051. brightYellow: [93, 39],
  11052. brightBlue: [94, 39],
  11053. brightMagenta: [95, 39],
  11054. brightCyan: [96, 39],
  11055. brightWhite: [97, 39],
  11056. bgBlack: [40, 49],
  11057. bgRed: [41, 49],
  11058. bgGreen: [42, 49],
  11059. bgYellow: [43, 49],
  11060. bgBlue: [44, 49],
  11061. bgMagenta: [45, 49],
  11062. bgCyan: [46, 49],
  11063. bgWhite: [47, 49],
  11064. bgGray: [100, 49],
  11065. bgGrey: [100, 49],
  11066. bgBrightRed: [101, 49],
  11067. bgBrightGreen: [102, 49],
  11068. bgBrightYellow: [103, 49],
  11069. bgBrightBlue: [104, 49],
  11070. bgBrightMagenta: [105, 49],
  11071. bgBrightCyan: [106, 49],
  11072. bgBrightWhite: [107, 49],
  11073. // legacy styles for colors pre v1.0.0
  11074. blackBG: [40, 49],
  11075. redBG: [41, 49],
  11076. greenBG: [42, 49],
  11077. yellowBG: [43, 49],
  11078. blueBG: [44, 49],
  11079. magentaBG: [45, 49],
  11080. cyanBG: [46, 49],
  11081. whiteBG: [47, 49]
  11082. };
  11083. Object.keys(codes).forEach(function(key) {
  11084. var val2 = codes[key];
  11085. var style = styles3[key] = [];
  11086. style.open = "\x1B[" + val2[0] + "m";
  11087. style.close = "\x1B[" + val2[1] + "m";
  11088. });
  11089. }
  11090. });
  11091. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js
  11092. var require_has_flag = __commonJS({
  11093. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js"(exports, module) {
  11094. "use strict";
  11095. module.exports = function(flag, argv) {
  11096. argv = argv || process.argv;
  11097. var terminatorPos = argv.indexOf("--");
  11098. var prefix2 = /^-{1,2}/.test(flag) ? "" : "--";
  11099. var pos = argv.indexOf(prefix2 + flag);
  11100. return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
  11101. };
  11102. }
  11103. });
  11104. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js
  11105. var require_supports_colors = __commonJS({
  11106. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js"(exports, module) {
  11107. "use strict";
  11108. var os3 = __require("os");
  11109. var hasFlag2 = require_has_flag();
  11110. var env4 = process.env;
  11111. var forceColor = void 0;
  11112. if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false")) {
  11113. forceColor = false;
  11114. } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
  11115. forceColor = true;
  11116. }
  11117. if ("FORCE_COLOR" in env4) {
  11118. forceColor = env4.FORCE_COLOR.length === 0 || parseInt(env4.FORCE_COLOR, 10) !== 0;
  11119. }
  11120. function translateLevel2(level) {
  11121. if (level === 0) {
  11122. return false;
  11123. }
  11124. return {
  11125. level,
  11126. hasBasic: true,
  11127. has256: level >= 2,
  11128. has16m: level >= 3
  11129. };
  11130. }
  11131. function supportsColor2(stream) {
  11132. if (forceColor === false) {
  11133. return 0;
  11134. }
  11135. if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
  11136. return 3;
  11137. }
  11138. if (hasFlag2("color=256")) {
  11139. return 2;
  11140. }
  11141. if (stream && !stream.isTTY && forceColor !== true) {
  11142. return 0;
  11143. }
  11144. var min = forceColor ? 1 : 0;
  11145. if (process.platform === "win32") {
  11146. var osRelease = os3.release().split(".");
  11147. if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  11148. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  11149. }
  11150. return 1;
  11151. }
  11152. if ("CI" in env4) {
  11153. if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
  11154. return sign in env4;
  11155. }) || env4.CI_NAME === "codeship") {
  11156. return 1;
  11157. }
  11158. return min;
  11159. }
  11160. if ("TEAMCITY_VERSION" in env4) {
  11161. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env4.TEAMCITY_VERSION) ? 1 : 0;
  11162. }
  11163. if ("TERM_PROGRAM" in env4) {
  11164. var version = parseInt((env4.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
  11165. switch (env4.TERM_PROGRAM) {
  11166. case "iTerm.app":
  11167. return version >= 3 ? 3 : 2;
  11168. case "Hyper":
  11169. return 3;
  11170. case "Apple_Terminal":
  11171. return 2;
  11172. }
  11173. }
  11174. if (/-256(color)?$/i.test(env4.TERM)) {
  11175. return 2;
  11176. }
  11177. if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env4.TERM)) {
  11178. return 1;
  11179. }
  11180. if ("COLORTERM" in env4) {
  11181. return 1;
  11182. }
  11183. if (env4.TERM === "dumb") {
  11184. return min;
  11185. }
  11186. return min;
  11187. }
  11188. function getSupportLevel(stream) {
  11189. var level = supportsColor2(stream);
  11190. return translateLevel2(level);
  11191. }
  11192. module.exports = {
  11193. supportsColor: getSupportLevel,
  11194. stdout: getSupportLevel(process.stdout),
  11195. stderr: getSupportLevel(process.stderr)
  11196. };
  11197. }
  11198. });
  11199. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js
  11200. var require_trap = __commonJS({
  11201. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js"(exports, module) {
  11202. "use strict";
  11203. module["exports"] = function runTheTrap(text, options) {
  11204. var result = "";
  11205. text = text || "Run the trap, drop the bass";
  11206. text = text.split("");
  11207. var trap = {
  11208. a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"],
  11209. b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"],
  11210. c: ["\xA9", "\u023B", "\u03FE"],
  11211. d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"],
  11212. e: [
  11213. "\xCB",
  11214. "\u0115",
  11215. "\u018E",
  11216. "\u0258",
  11217. "\u03A3",
  11218. "\u03BE",
  11219. "\u04BC",
  11220. "\u0A6C"
  11221. ],
  11222. f: ["\u04FA"],
  11223. g: ["\u0262"],
  11224. h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"],
  11225. i: ["\u0F0F"],
  11226. j: ["\u0134"],
  11227. k: ["\u0138", "\u04A0", "\u04C3", "\u051E"],
  11228. l: ["\u0139"],
  11229. m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"],
  11230. n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"],
  11231. o: [
  11232. "\xD8",
  11233. "\xF5",
  11234. "\xF8",
  11235. "\u01FE",
  11236. "\u0298",
  11237. "\u047A",
  11238. "\u05DD",
  11239. "\u06DD",
  11240. "\u0E4F"
  11241. ],
  11242. p: ["\u01F7", "\u048E"],
  11243. q: ["\u09CD"],
  11244. r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"],
  11245. s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"],
  11246. t: ["\u0141", "\u0166", "\u0373"],
  11247. u: ["\u01B1", "\u054D"],
  11248. v: ["\u05D8"],
  11249. w: ["\u0428", "\u0460", "\u047C", "\u0D70"],
  11250. x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"],
  11251. y: ["\xA5", "\u04B0", "\u04CB"],
  11252. z: ["\u01B5", "\u0240"]
  11253. };
  11254. text.forEach(function(c5) {
  11255. c5 = c5.toLowerCase();
  11256. var chars = trap[c5] || [" "];
  11257. var rand = Math.floor(Math.random() * chars.length);
  11258. if (typeof trap[c5] !== "undefined") {
  11259. result += trap[c5][rand];
  11260. } else {
  11261. result += c5;
  11262. }
  11263. });
  11264. return result;
  11265. };
  11266. }
  11267. });
  11268. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js
  11269. var require_zalgo = __commonJS({
  11270. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js"(exports, module) {
  11271. "use strict";
  11272. module["exports"] = function zalgo(text, options) {
  11273. text = text || " he is here ";
  11274. var soul = {
  11275. "up": [
  11276. "\u030D",
  11277. "\u030E",
  11278. "\u0304",
  11279. "\u0305",
  11280. "\u033F",
  11281. "\u0311",
  11282. "\u0306",
  11283. "\u0310",
  11284. "\u0352",
  11285. "\u0357",
  11286. "\u0351",
  11287. "\u0307",
  11288. "\u0308",
  11289. "\u030A",
  11290. "\u0342",
  11291. "\u0313",
  11292. "\u0308",
  11293. "\u034A",
  11294. "\u034B",
  11295. "\u034C",
  11296. "\u0303",
  11297. "\u0302",
  11298. "\u030C",
  11299. "\u0350",
  11300. "\u0300",
  11301. "\u0301",
  11302. "\u030B",
  11303. "\u030F",
  11304. "\u0312",
  11305. "\u0313",
  11306. "\u0314",
  11307. "\u033D",
  11308. "\u0309",
  11309. "\u0363",
  11310. "\u0364",
  11311. "\u0365",
  11312. "\u0366",
  11313. "\u0367",
  11314. "\u0368",
  11315. "\u0369",
  11316. "\u036A",
  11317. "\u036B",
  11318. "\u036C",
  11319. "\u036D",
  11320. "\u036E",
  11321. "\u036F",
  11322. "\u033E",
  11323. "\u035B",
  11324. "\u0346",
  11325. "\u031A"
  11326. ],
  11327. "down": [
  11328. "\u0316",
  11329. "\u0317",
  11330. "\u0318",
  11331. "\u0319",
  11332. "\u031C",
  11333. "\u031D",
  11334. "\u031E",
  11335. "\u031F",
  11336. "\u0320",
  11337. "\u0324",
  11338. "\u0325",
  11339. "\u0326",
  11340. "\u0329",
  11341. "\u032A",
  11342. "\u032B",
  11343. "\u032C",
  11344. "\u032D",
  11345. "\u032E",
  11346. "\u032F",
  11347. "\u0330",
  11348. "\u0331",
  11349. "\u0332",
  11350. "\u0333",
  11351. "\u0339",
  11352. "\u033A",
  11353. "\u033B",
  11354. "\u033C",
  11355. "\u0345",
  11356. "\u0347",
  11357. "\u0348",
  11358. "\u0349",
  11359. "\u034D",
  11360. "\u034E",
  11361. "\u0353",
  11362. "\u0354",
  11363. "\u0355",
  11364. "\u0356",
  11365. "\u0359",
  11366. "\u035A",
  11367. "\u0323"
  11368. ],
  11369. "mid": [
  11370. "\u0315",
  11371. "\u031B",
  11372. "\u0300",
  11373. "\u0301",
  11374. "\u0358",
  11375. "\u0321",
  11376. "\u0322",
  11377. "\u0327",
  11378. "\u0328",
  11379. "\u0334",
  11380. "\u0335",
  11381. "\u0336",
  11382. "\u035C",
  11383. "\u035D",
  11384. "\u035E",
  11385. "\u035F",
  11386. "\u0360",
  11387. "\u0362",
  11388. "\u0338",
  11389. "\u0337",
  11390. "\u0361",
  11391. " \u0489"
  11392. ]
  11393. };
  11394. var all = [].concat(soul.up, soul.down, soul.mid);
  11395. function randomNumber(range) {
  11396. var r6 = Math.floor(Math.random() * range);
  11397. return r6;
  11398. }
  11399. function isChar(character) {
  11400. var bool = false;
  11401. all.filter(function(i6) {
  11402. bool = i6 === character;
  11403. });
  11404. return bool;
  11405. }
  11406. function heComes(text2, options2) {
  11407. var result = "";
  11408. var counts;
  11409. var l5;
  11410. options2 = options2 || {};
  11411. options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true;
  11412. options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true;
  11413. options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true;
  11414. options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi";
  11415. text2 = text2.split("");
  11416. for (l5 in text2) {
  11417. if (isChar(l5)) {
  11418. continue;
  11419. }
  11420. result = result + text2[l5];
  11421. counts = { "up": 0, "down": 0, "mid": 0 };
  11422. switch (options2.size) {
  11423. case "mini":
  11424. counts.up = randomNumber(8);
  11425. counts.mid = randomNumber(2);
  11426. counts.down = randomNumber(8);
  11427. break;
  11428. case "maxi":
  11429. counts.up = randomNumber(16) + 3;
  11430. counts.mid = randomNumber(4) + 1;
  11431. counts.down = randomNumber(64) + 3;
  11432. break;
  11433. default:
  11434. counts.up = randomNumber(8) + 1;
  11435. counts.mid = randomNumber(6) / 2;
  11436. counts.down = randomNumber(8) + 1;
  11437. break;
  11438. }
  11439. var arr = ["up", "mid", "down"];
  11440. for (var d5 in arr) {
  11441. var index6 = arr[d5];
  11442. for (var i6 = 0; i6 <= counts[index6]; i6++) {
  11443. if (options2[index6]) {
  11444. result = result + soul[index6][randomNumber(soul[index6].length)];
  11445. }
  11446. }
  11447. }
  11448. }
  11449. return result;
  11450. }
  11451. return heComes(text, options);
  11452. };
  11453. }
  11454. });
  11455. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js
  11456. var require_america = __commonJS({
  11457. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js"(exports, module) {
  11458. "use strict";
  11459. module["exports"] = function(colors) {
  11460. return function(letter, i6, exploded) {
  11461. if (letter === " ") return letter;
  11462. switch (i6 % 3) {
  11463. case 0:
  11464. return colors.red(letter);
  11465. case 1:
  11466. return colors.white(letter);
  11467. case 2:
  11468. return colors.blue(letter);
  11469. }
  11470. };
  11471. };
  11472. }
  11473. });
  11474. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js
  11475. var require_zebra = __commonJS({
  11476. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js"(exports, module) {
  11477. "use strict";
  11478. module["exports"] = function(colors) {
  11479. return function(letter, i6, exploded) {
  11480. return i6 % 2 === 0 ? letter : colors.inverse(letter);
  11481. };
  11482. };
  11483. }
  11484. });
  11485. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js
  11486. var require_rainbow = __commonJS({
  11487. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js"(exports, module) {
  11488. "use strict";
  11489. module["exports"] = function(colors) {
  11490. var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
  11491. return function(letter, i6, exploded) {
  11492. if (letter === " ") {
  11493. return letter;
  11494. } else {
  11495. return colors[rainbowColors[i6++ % rainbowColors.length]](letter);
  11496. }
  11497. };
  11498. };
  11499. }
  11500. });
  11501. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js
  11502. var require_random = __commonJS({
  11503. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js"(exports, module) {
  11504. "use strict";
  11505. module["exports"] = function(colors) {
  11506. var available = [
  11507. "underline",
  11508. "inverse",
  11509. "grey",
  11510. "yellow",
  11511. "red",
  11512. "green",
  11513. "blue",
  11514. "white",
  11515. "cyan",
  11516. "magenta",
  11517. "brightYellow",
  11518. "brightRed",
  11519. "brightGreen",
  11520. "brightBlue",
  11521. "brightWhite",
  11522. "brightCyan",
  11523. "brightMagenta"
  11524. ];
  11525. return function(letter, i6, exploded) {
  11526. return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter);
  11527. };
  11528. };
  11529. }
  11530. });
  11531. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js
  11532. var require_colors = __commonJS({
  11533. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js"(exports, module) {
  11534. "use strict";
  11535. var colors = {};
  11536. module["exports"] = colors;
  11537. colors.themes = {};
  11538. var util2 = __require("util");
  11539. var ansiStyles2 = colors.styles = require_styles();
  11540. var defineProps = Object.defineProperties;
  11541. var newLineRegex = new RegExp(/[\r\n]+/g);
  11542. colors.supportsColor = require_supports_colors().supportsColor;
  11543. if (typeof colors.enabled === "undefined") {
  11544. colors.enabled = colors.supportsColor() !== false;
  11545. }
  11546. colors.enable = function() {
  11547. colors.enabled = true;
  11548. };
  11549. colors.disable = function() {
  11550. colors.enabled = false;
  11551. };
  11552. colors.stripColors = colors.strip = function(str) {
  11553. return ("" + str).replace(/\x1B\[\d+m/g, "");
  11554. };
  11555. var stylize = colors.stylize = function stylize2(str, style) {
  11556. if (!colors.enabled) {
  11557. return str + "";
  11558. }
  11559. var styleMap = ansiStyles2[style];
  11560. if (!styleMap && style in colors) {
  11561. return colors[style](str);
  11562. }
  11563. return styleMap.open + str + styleMap.close;
  11564. };
  11565. var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
  11566. var escapeStringRegexp = function(str) {
  11567. if (typeof str !== "string") {
  11568. throw new TypeError("Expected a string");
  11569. }
  11570. return str.replace(matchOperatorsRe, "\\$&");
  11571. };
  11572. function build(_styles) {
  11573. var builder = function builder2() {
  11574. return applyStyle2.apply(builder2, arguments);
  11575. };
  11576. builder._styles = _styles;
  11577. builder.__proto__ = proto2;
  11578. return builder;
  11579. }
  11580. var styles3 = function() {
  11581. var ret = {};
  11582. ansiStyles2.grey = ansiStyles2.gray;
  11583. Object.keys(ansiStyles2).forEach(function(key) {
  11584. ansiStyles2[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles2[key].close), "g");
  11585. ret[key] = {
  11586. get: function() {
  11587. return build(this._styles.concat(key));
  11588. }
  11589. };
  11590. });
  11591. return ret;
  11592. }();
  11593. var proto2 = defineProps(function colors2() {
  11594. }, styles3);
  11595. function applyStyle2() {
  11596. var args = Array.prototype.slice.call(arguments);
  11597. var str = args.map(function(arg) {
  11598. if (arg != null && arg.constructor === String) {
  11599. return arg;
  11600. } else {
  11601. return util2.inspect(arg);
  11602. }
  11603. }).join(" ");
  11604. if (!colors.enabled || !str) {
  11605. return str;
  11606. }
  11607. var newLinesPresent = str.indexOf("\n") != -1;
  11608. var nestedStyles = this._styles;
  11609. var i6 = nestedStyles.length;
  11610. while (i6--) {
  11611. var code = ansiStyles2[nestedStyles[i6]];
  11612. str = code.open + str.replace(code.closeRe, code.open) + code.close;
  11613. if (newLinesPresent) {
  11614. str = str.replace(newLineRegex, function(match2) {
  11615. return code.close + match2 + code.open;
  11616. });
  11617. }
  11618. }
  11619. return str;
  11620. }
  11621. colors.setTheme = function(theme) {
  11622. if (typeof theme === "string") {
  11623. console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");
  11624. return;
  11625. }
  11626. for (var style in theme) {
  11627. (function(style2) {
  11628. colors[style2] = function(str) {
  11629. if (typeof theme[style2] === "object") {
  11630. var out = str;
  11631. for (var i6 in theme[style2]) {
  11632. out = colors[theme[style2][i6]](out);
  11633. }
  11634. return out;
  11635. }
  11636. return colors[theme[style2]](str);
  11637. };
  11638. })(style);
  11639. }
  11640. };
  11641. function init2() {
  11642. var ret = {};
  11643. Object.keys(styles3).forEach(function(name) {
  11644. ret[name] = {
  11645. get: function() {
  11646. return build([name]);
  11647. }
  11648. };
  11649. });
  11650. return ret;
  11651. }
  11652. var sequencer = function sequencer2(map3, str) {
  11653. var exploded = str.split("");
  11654. exploded = exploded.map(map3);
  11655. return exploded.join("");
  11656. };
  11657. colors.trap = require_trap();
  11658. colors.zalgo = require_zalgo();
  11659. colors.maps = {};
  11660. colors.maps.america = require_america()(colors);
  11661. colors.maps.zebra = require_zebra()(colors);
  11662. colors.maps.rainbow = require_rainbow()(colors);
  11663. colors.maps.random = require_random()(colors);
  11664. for (map2 in colors.maps) {
  11665. (function(map3) {
  11666. colors[map3] = function(str) {
  11667. return sequencer(colors.maps[map3], str);
  11668. };
  11669. })(map2);
  11670. }
  11671. var map2;
  11672. defineProps(colors, init2());
  11673. }
  11674. });
  11675. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js
  11676. var require_safe = __commonJS({
  11677. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js"(exports, module) {
  11678. "use strict";
  11679. var colors = require_colors();
  11680. module["exports"] = colors;
  11681. }
  11682. });
  11683. // ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js
  11684. var require_colorize = __commonJS({
  11685. "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js"(exports, module) {
  11686. "use strict";
  11687. var color = require_safe();
  11688. var { extendedTypeOf } = require_util();
  11689. var Theme = {
  11690. " "(s6) {
  11691. return s6;
  11692. },
  11693. "+": color.green,
  11694. "-": color.red
  11695. };
  11696. var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) {
  11697. let subvalue;
  11698. const prefix2 = key ? `${key}: ` : "";
  11699. const subindent = indent + " ";
  11700. const outputElisions = (n5) => {
  11701. const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions;
  11702. if (n5 < maxElisions) {
  11703. for (let i6 = 0; i6 < n5; i6++) {
  11704. output(" ", subindent + "...");
  11705. }
  11706. } else {
  11707. output(" ", subindent + `... (${n5} entries)`);
  11708. }
  11709. };
  11710. switch (extendedTypeOf(diff2)) {
  11711. case "object":
  11712. if ("__old" in diff2 && "__new" in diff2 && Object.keys(diff2).length === 2) {
  11713. subcolorizeToCallback(options, key, diff2.__old, output, "-", indent);
  11714. return subcolorizeToCallback(options, key, diff2.__new, output, "+", indent);
  11715. } else {
  11716. output(color2, `${indent}${prefix2}{`);
  11717. for (const subkey of Object.keys(diff2)) {
  11718. let m6;
  11719. subvalue = diff2[subkey];
  11720. if (m6 = subkey.match(/^(.*)__deleted$/)) {
  11721. subcolorizeToCallback(options, m6[1], subvalue, output, "-", subindent);
  11722. } else if (m6 = subkey.match(/^(.*)__added$/)) {
  11723. subcolorizeToCallback(options, m6[1], subvalue, output, "+", subindent);
  11724. } else {
  11725. subcolorizeToCallback(options, subkey, subvalue, output, color2, subindent);
  11726. }
  11727. }
  11728. return output(color2, `${indent}}`);
  11729. }
  11730. case "array": {
  11731. output(color2, `${indent}${prefix2}[`);
  11732. let looksLikeDiff = true;
  11733. for (const item of diff2) {
  11734. if (extendedTypeOf(item) !== "array" || !(item.length === 2 || item.length === 1 && item[0] === " ") || !(typeof item[0] === "string") || item[0].length !== 1 || ![" ", "-", "+", "~"].includes(item[0])) {
  11735. looksLikeDiff = false;
  11736. }
  11737. }
  11738. if (looksLikeDiff) {
  11739. let op;
  11740. let elisionCount = 0;
  11741. for ([op, subvalue] of diff2) {
  11742. if (op === " " && subvalue == null) {
  11743. elisionCount++;
  11744. } else {
  11745. if (elisionCount > 0) {
  11746. outputElisions(elisionCount);
  11747. }
  11748. elisionCount = 0;
  11749. if (![" ", "~", "+", "-"].includes(op)) {
  11750. throw new Error(`Unexpected op '${op}' in ${JSON.stringify(diff2, null, 2)}`);
  11751. }
  11752. if (op === "~") {
  11753. op = " ";
  11754. }
  11755. subcolorizeToCallback(options, "", subvalue, output, op, subindent);
  11756. }
  11757. }
  11758. if (elisionCount > 0) {
  11759. outputElisions(elisionCount);
  11760. }
  11761. } else {
  11762. for (subvalue of diff2) {
  11763. subcolorizeToCallback(options, "", subvalue, output, color2, subindent);
  11764. }
  11765. }
  11766. return output(color2, `${indent}]`);
  11767. }
  11768. default:
  11769. if (diff2 === 0 || diff2 === null || diff2 === false || diff2 === "" || diff2) {
  11770. return output(color2, indent + prefix2 + JSON.stringify(diff2));
  11771. }
  11772. }
  11773. };
  11774. var colorizeToCallback = (diff2, options, output) => subcolorizeToCallback(options, "", diff2, output, " ", "");
  11775. var colorizeToArray = function(diff2, options = {}) {
  11776. const output = [];
  11777. colorizeToCallback(diff2, options, (color2, line) => output.push(`${color2}${line}`));
  11778. return output;
  11779. };
  11780. var colorize = function(diff2, options = {}) {
  11781. const output = [];
  11782. colorizeToCallback(diff2, options, function(color2, line) {
  11783. if (options.color != null ? options.color : true) {
  11784. return output.push(((options.theme != null ? options.theme[color2] : void 0) != null ? options.theme != null ? options.theme[color2] : void 0 : Theme[color2])(`${color2}${line}`) + "\n");
  11785. } else {
  11786. return output.push(`${color2}${line}
  11787. `);
  11788. }
  11789. });
  11790. return output.join("");
  11791. };
  11792. module.exports = { colorize, colorizeToArray, colorizeToCallback };
  11793. }
  11794. });
  11795. // ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js
  11796. var require_lib = __commonJS({
  11797. "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js"(exports, module) {
  11798. "use strict";
  11799. var { SequenceMatcher } = require_difflib2();
  11800. var { extendedTypeOf, roundObj } = require_util();
  11801. var { colorize, colorizeToCallback } = require_colorize();
  11802. var JsonDiff = class {
  11803. constructor(options) {
  11804. options.outputKeys = options.outputKeys || [];
  11805. options.excludeKeys = options.excludeKeys || [];
  11806. this.options = options;
  11807. }
  11808. isScalar(obj) {
  11809. return typeof obj !== "object" || obj === null;
  11810. }
  11811. objectDiff(obj1, obj2) {
  11812. let result = {};
  11813. let score = 0;
  11814. let equal = true;
  11815. for (const [key, value] of Object.entries(obj1)) {
  11816. if (!this.options.outputNewOnly) {
  11817. const postfix = "__deleted";
  11818. if (!(key in obj2) && !this.options.excludeKeys.includes(key)) {
  11819. result[`${key}${postfix}`] = value;
  11820. score -= 30;
  11821. equal = false;
  11822. }
  11823. }
  11824. }
  11825. for (const [key, value] of Object.entries(obj2)) {
  11826. const postfix = !this.options.outputNewOnly ? "__added" : "";
  11827. if (!(key in obj1) && !this.options.excludeKeys.includes(key)) {
  11828. result[`${key}${postfix}`] = value;
  11829. score -= 30;
  11830. equal = false;
  11831. }
  11832. }
  11833. for (const [key, value1] of Object.entries(obj1)) {
  11834. if (key in obj2) {
  11835. if (this.options.excludeKeys.includes(key)) {
  11836. continue;
  11837. }
  11838. score += 20;
  11839. const value2 = obj2[key];
  11840. const change = this.diff(value1, value2);
  11841. if (!change.equal) {
  11842. result[key] = change.result;
  11843. equal = false;
  11844. } else if (this.options.full || this.options.outputKeys.includes(key)) {
  11845. result[key] = value1;
  11846. }
  11847. score += Math.min(20, Math.max(-10, change.score / 5));
  11848. }
  11849. }
  11850. if (equal) {
  11851. score = 100 * Math.max(Object.keys(obj1).length, 0.5);
  11852. if (!this.options.full) {
  11853. result = void 0;
  11854. }
  11855. } else {
  11856. score = Math.max(0, score);
  11857. }
  11858. return { score, result, equal };
  11859. }
  11860. findMatchingObject(item, index6, fuzzyOriginals) {
  11861. let bestMatch = null;
  11862. for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) {
  11863. if (key !== "__next") {
  11864. const indexDistance = Math.abs(matchIndex - index6);
  11865. if (extendedTypeOf(item) === extendedTypeOf(candidate)) {
  11866. const { score } = this.diff(item, candidate);
  11867. if (!bestMatch || score > bestMatch.score || score === bestMatch.score && indexDistance < bestMatch.indexDistance) {
  11868. bestMatch = { score, key, indexDistance };
  11869. }
  11870. }
  11871. }
  11872. }
  11873. return bestMatch;
  11874. }
  11875. scalarize(array2, originals, fuzzyOriginals) {
  11876. const fuzzyMatches = [];
  11877. if (fuzzyOriginals) {
  11878. const keyScores = {};
  11879. for (let index6 = 0; index6 < array2.length; index6++) {
  11880. const item = array2[index6];
  11881. if (this.isScalar(item)) {
  11882. continue;
  11883. }
  11884. const bestMatch = this.findMatchingObject(item, index6, fuzzyOriginals);
  11885. if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) {
  11886. keyScores[bestMatch.key] = { score: bestMatch.score, index: index6 };
  11887. }
  11888. }
  11889. for (const [key, match2] of Object.entries(keyScores)) {
  11890. fuzzyMatches[match2.index] = key;
  11891. }
  11892. }
  11893. const result = [];
  11894. for (let index6 = 0; index6 < array2.length; index6++) {
  11895. const item = array2[index6];
  11896. if (this.isScalar(item)) {
  11897. result.push(item);
  11898. } else {
  11899. const key = fuzzyMatches[index6] || "__$!SCALAR" + originals.__next++;
  11900. originals[key] = { item, index: index6 };
  11901. result.push(key);
  11902. }
  11903. }
  11904. return result;
  11905. }
  11906. isScalarized(item, originals) {
  11907. return typeof item === "string" && item in originals;
  11908. }
  11909. descalarize(item, originals) {
  11910. if (this.isScalarized(item, originals)) {
  11911. return originals[item].item;
  11912. } else {
  11913. return item;
  11914. }
  11915. }
  11916. arrayDiff(obj1, obj2) {
  11917. const originals1 = { __next: 1 };
  11918. const seq1 = this.scalarize(obj1, originals1);
  11919. const originals2 = { __next: originals1.__next };
  11920. const seq2 = this.scalarize(obj2, originals2, originals1);
  11921. if (this.options.sort) {
  11922. seq1.sort();
  11923. seq2.sort();
  11924. }
  11925. const opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes();
  11926. let result = [];
  11927. let score = 0;
  11928. let equal = true;
  11929. for (const [op, i1, i22, j1, j22] of opcodes) {
  11930. let i6, j5;
  11931. let asc, end;
  11932. let asc1, end1;
  11933. let asc2, end2;
  11934. if (!(op === "equal" || this.options.keysOnly && op === "replace")) {
  11935. equal = false;
  11936. }
  11937. switch (op) {
  11938. case "equal":
  11939. for (i6 = i1, end = i22, asc = i1 <= end; asc ? i6 < end : i6 > end; asc ? i6++ : i6--) {
  11940. const item = seq1[i6];
  11941. if (this.isScalarized(item, originals1)) {
  11942. if (!this.isScalarized(item, originals2)) {
  11943. throw new Error(
  11944. `internal bug: isScalarized(item, originals1) != isScalarized(item, originals2) for item ${JSON.stringify(
  11945. item
  11946. )}`
  11947. );
  11948. }
  11949. const item1 = this.descalarize(item, originals1);
  11950. const item2 = this.descalarize(item, originals2);
  11951. const change = this.diff(item1, item2);
  11952. if (!change.equal) {
  11953. result.push(["~", change.result]);
  11954. equal = false;
  11955. } else {
  11956. if (this.options.full || this.options.keepUnchangedValues) {
  11957. result.push([" ", item1]);
  11958. } else {
  11959. result.push([" "]);
  11960. }
  11961. }
  11962. } else {
  11963. if (this.options.full || this.options.keepUnchangedValues) {
  11964. result.push([" ", item]);
  11965. } else {
  11966. result.push([" "]);
  11967. }
  11968. }
  11969. score += 10;
  11970. }
  11971. break;
  11972. case "delete":
  11973. for (i6 = i1, end1 = i22, asc1 = i1 <= end1; asc1 ? i6 < end1 : i6 > end1; asc1 ? i6++ : i6--) {
  11974. result.push(["-", this.descalarize(seq1[i6], originals1)]);
  11975. score -= 5;
  11976. }
  11977. break;
  11978. case "insert":
  11979. for (j5 = j1, end2 = j22, asc2 = j1 <= end2; asc2 ? j5 < end2 : j5 > end2; asc2 ? j5++ : j5--) {
  11980. result.push(["+", this.descalarize(seq2[j5], originals2)]);
  11981. score -= 5;
  11982. }
  11983. break;
  11984. case "replace":
  11985. if (!this.options.keysOnly) {
  11986. let asc3, end3;
  11987. let asc4, end4;
  11988. for (i6 = i1, end3 = i22, asc3 = i1 <= end3; asc3 ? i6 < end3 : i6 > end3; asc3 ? i6++ : i6--) {
  11989. result.push(["-", this.descalarize(seq1[i6], originals1)]);
  11990. score -= 5;
  11991. }
  11992. for (j5 = j1, end4 = j22, asc4 = j1 <= end4; asc4 ? j5 < end4 : j5 > end4; asc4 ? j5++ : j5--) {
  11993. result.push(["+", this.descalarize(seq2[j5], originals2)]);
  11994. score -= 5;
  11995. }
  11996. } else {
  11997. let asc5, end5;
  11998. for (i6 = i1, end5 = i22, asc5 = i1 <= end5; asc5 ? i6 < end5 : i6 > end5; asc5 ? i6++ : i6--) {
  11999. const change = this.diff(
  12000. this.descalarize(seq1[i6], originals1),
  12001. this.descalarize(seq2[i6 - i1 + j1], originals2)
  12002. );
  12003. if (!change.equal) {
  12004. result.push(["~", change.result]);
  12005. equal = false;
  12006. } else {
  12007. result.push([" "]);
  12008. }
  12009. }
  12010. }
  12011. break;
  12012. }
  12013. }
  12014. if (equal || opcodes.length === 0) {
  12015. if (!this.options.full) {
  12016. result = void 0;
  12017. } else {
  12018. result = obj1;
  12019. }
  12020. score = 100;
  12021. } else {
  12022. score = Math.max(0, score);
  12023. }
  12024. return { score, result, equal };
  12025. }
  12026. diff(obj1, obj2) {
  12027. const type1 = extendedTypeOf(obj1);
  12028. const type2 = extendedTypeOf(obj2);
  12029. if (type1 === type2) {
  12030. switch (type1) {
  12031. case "object":
  12032. return this.objectDiff(obj1, obj2);
  12033. case "array":
  12034. return this.arrayDiff(obj1, obj2);
  12035. }
  12036. }
  12037. let score = 100;
  12038. let result = obj1;
  12039. let equal;
  12040. if (!this.options.keysOnly) {
  12041. if (type1 === "date" && type2 === "date") {
  12042. equal = obj1.getTime() === obj2.getTime();
  12043. } else {
  12044. equal = obj1 === obj2;
  12045. }
  12046. if (!equal) {
  12047. score = 0;
  12048. if (this.options.outputNewOnly) {
  12049. result = obj2;
  12050. } else {
  12051. result = { __old: obj1, __new: obj2 };
  12052. }
  12053. } else if (!this.options.full) {
  12054. result = void 0;
  12055. }
  12056. } else {
  12057. equal = true;
  12058. result = void 0;
  12059. }
  12060. return { score, result, equal };
  12061. }
  12062. };
  12063. function diff2(obj1, obj2, options = {}) {
  12064. if (options.precision !== void 0) {
  12065. obj1 = roundObj(obj1, options.precision);
  12066. obj2 = roundObj(obj2, options.precision);
  12067. }
  12068. return new JsonDiff(options).diff(obj1, obj2).result;
  12069. }
  12070. function diffString(obj1, obj2, options = {}) {
  12071. return colorize(diff2(obj1, obj2, options), options);
  12072. }
  12073. module.exports = { diff: diff2, diffString, colorize, colorizeToCallback };
  12074. }
  12075. });
  12076. // src/jsonDiffer.js
  12077. function diffSchemasOrTables(left, right) {
  12078. left = JSON.parse(JSON.stringify(left));
  12079. right = JSON.parse(JSON.stringify(right));
  12080. const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  12081. const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  12082. const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  12083. return { added, deleted };
  12084. }
  12085. function diffIndPolicies(left, right) {
  12086. left = JSON.parse(JSON.stringify(left));
  12087. right = JSON.parse(JSON.stringify(right));
  12088. const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  12089. const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  12090. const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  12091. return { added, deleted };
  12092. }
  12093. function diffColumns(left, right) {
  12094. left = JSON.parse(JSON.stringify(left));
  12095. right = JSON.parse(JSON.stringify(right));
  12096. const result = (0, import_json_diff.diff)(left, right) ?? {};
  12097. const alteredTables = Object.fromEntries(
  12098. Object.entries(result).filter((it) => {
  12099. return !(it[0].includes("__added") || it[0].includes("__deleted"));
  12100. }).map((tableEntry) => {
  12101. const deletedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
  12102. return it[0].endsWith("__deleted");
  12103. }).map((it) => {
  12104. return it[1];
  12105. });
  12106. const addedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
  12107. return it[0].endsWith("__added");
  12108. }).map((it) => {
  12109. return it[1];
  12110. });
  12111. tableEntry[1].columns = {
  12112. added: addedColumns,
  12113. deleted: deletedColumns
  12114. };
  12115. const table6 = left[tableEntry[0]];
  12116. return [
  12117. tableEntry[0],
  12118. { name: table6.name, schema: table6.schema, ...tableEntry[1] }
  12119. ];
  12120. })
  12121. );
  12122. return alteredTables;
  12123. }
  12124. function diffPolicies(left, right) {
  12125. left = JSON.parse(JSON.stringify(left));
  12126. right = JSON.parse(JSON.stringify(right));
  12127. const result = (0, import_json_diff.diff)(left, right) ?? {};
  12128. const alteredTables = Object.fromEntries(
  12129. Object.entries(result).filter((it) => {
  12130. return !(it[0].includes("__added") || it[0].includes("__deleted"));
  12131. }).map((tableEntry) => {
  12132. const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
  12133. return it[0].endsWith("__deleted");
  12134. }).map((it) => {
  12135. return it[1];
  12136. });
  12137. const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
  12138. return it[0].endsWith("__added");
  12139. }).map((it) => {
  12140. return it[1];
  12141. });
  12142. tableEntry[1].policies = {
  12143. added: addedPolicies,
  12144. deleted: deletedPolicies
  12145. };
  12146. const table6 = left[tableEntry[0]];
  12147. return [
  12148. tableEntry[0],
  12149. { name: table6.name, schema: table6.schema, ...tableEntry[1] }
  12150. ];
  12151. })
  12152. );
  12153. return alteredTables;
  12154. }
  12155. function applyJsonDiff(json1, json2) {
  12156. json1 = JSON.parse(JSON.stringify(json1));
  12157. json2 = JSON.parse(JSON.stringify(json2));
  12158. const rawDiff = (0, import_json_diff.diff)(json1, json2);
  12159. const difference = JSON.parse(JSON.stringify(rawDiff || {}));
  12160. difference.schemas = difference.schemas || {};
  12161. difference.tables = difference.tables || {};
  12162. difference.enums = difference.enums || {};
  12163. difference.sequences = difference.sequences || {};
  12164. difference.roles = difference.roles || {};
  12165. difference.policies = difference.policies || {};
  12166. difference.views = difference.views || {};
  12167. const schemaKeys = Object.keys(difference.schemas);
  12168. for (let key of schemaKeys) {
  12169. if (key.endsWith("__added") || key.endsWith("__deleted")) {
  12170. delete difference.schemas[key];
  12171. continue;
  12172. }
  12173. }
  12174. const tableKeys = Object.keys(difference.tables);
  12175. for (let key of tableKeys) {
  12176. if (key.endsWith("__added") || key.endsWith("__deleted")) {
  12177. delete difference.tables[key];
  12178. continue;
  12179. }
  12180. const table6 = json1.tables[key];
  12181. difference.tables[key] = {
  12182. name: table6.name,
  12183. schema: table6.schema,
  12184. ...difference.tables[key]
  12185. };
  12186. }
  12187. for (let [tableKey2, tableValue] of Object.entries(difference.tables)) {
  12188. const table6 = difference.tables[tableKey2];
  12189. const columns = tableValue.columns || {};
  12190. const columnKeys = Object.keys(columns);
  12191. for (let key of columnKeys) {
  12192. if (key.endsWith("__added") || key.endsWith("__deleted")) {
  12193. delete table6.columns[key];
  12194. continue;
  12195. }
  12196. }
  12197. if (Object.keys(columns).length === 0) {
  12198. delete table6["columns"];
  12199. }
  12200. if ("name" in table6 && "schema" in table6 && Object.keys(table6).length === 2) {
  12201. delete difference.tables[tableKey2];
  12202. }
  12203. }
  12204. const enumsEntries = Object.entries(difference.enums);
  12205. const alteredEnums = enumsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
  12206. const enumEntry = json1.enums[it[0]];
  12207. const { name, schema: schema6, values } = enumEntry;
  12208. const sequence = mapArraysDiff(values, it[1].values);
  12209. const addedValues = sequence.filter((it2) => it2.type === "added").map((it2) => {
  12210. return {
  12211. before: it2.before,
  12212. value: it2.value
  12213. };
  12214. });
  12215. const deletedValues = sequence.filter((it2) => it2.type === "removed").map((it2) => it2.value);
  12216. return { name, schema: schema6, addedValues, deletedValues };
  12217. });
  12218. const sequencesEntries = Object.entries(difference.sequences);
  12219. const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
  12220. return json2.sequences[it[0]];
  12221. });
  12222. const rolesEntries = Object.entries(difference.roles);
  12223. const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
  12224. return json2.roles[it[0]];
  12225. });
  12226. const policiesEntries = Object.entries(difference.policies);
  12227. const alteredPolicies = policiesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
  12228. return json2.policies[it[0]];
  12229. });
  12230. const viewsEntries = Object.entries(difference.views);
  12231. const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
  12232. ([nameWithSchema, view5]) => {
  12233. const deletedWithOption = view5.with__deleted;
  12234. const addedWithOption = view5.with__added;
  12235. const deletedWith = Object.fromEntries(
  12236. Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
  12237. return [key.replace("__deleted", ""), value];
  12238. })
  12239. );
  12240. const addedWith = Object.fromEntries(
  12241. Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
  12242. return [key.replace("__added", ""), value];
  12243. })
  12244. );
  12245. const alterWith = Object.fromEntries(
  12246. Object.entries(view5.with || {}).filter(
  12247. (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
  12248. ).map(
  12249. (it) => {
  12250. return [it[0], it[1].__new];
  12251. }
  12252. )
  12253. );
  12254. const alteredSchema = view5.schema;
  12255. const alteredDefinition = view5.definition;
  12256. const alteredExisting = view5.isExisting;
  12257. const addedTablespace = view5.tablespace__added;
  12258. const droppedTablespace = view5.tablespace__deleted;
  12259. const alterTablespaceTo = view5.tablespace;
  12260. let alteredTablespace;
  12261. if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
  12262. if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
  12263. if (alterTablespaceTo) alteredTablespace = alterTablespaceTo;
  12264. const addedUsing = view5.using__added;
  12265. const droppedUsing = view5.using__deleted;
  12266. const alterUsingTo = view5.using;
  12267. let alteredUsing;
  12268. if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
  12269. if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
  12270. if (alterUsingTo) alteredUsing = alterUsingTo;
  12271. const alteredMeta = view5.meta;
  12272. return Object.fromEntries(
  12273. Object.entries({
  12274. name: json2.views[nameWithSchema].name,
  12275. schema: json2.views[nameWithSchema].schema,
  12276. // pg
  12277. deletedWithOption,
  12278. addedWithOption,
  12279. deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
  12280. addedWith: Object.keys(addedWith).length ? addedWith : void 0,
  12281. alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
  12282. alteredSchema,
  12283. alteredTablespace,
  12284. alteredUsing,
  12285. // mysql
  12286. alteredMeta,
  12287. // common
  12288. alteredDefinition,
  12289. alteredExisting
  12290. }).filter(([_3, value]) => value !== void 0)
  12291. );
  12292. }
  12293. );
  12294. const alteredTablesWithColumns = Object.values(difference.tables).map(
  12295. (table6) => {
  12296. return findAlternationsInTable(table6);
  12297. }
  12298. );
  12299. return {
  12300. alteredTablesWithColumns,
  12301. alteredEnums,
  12302. alteredSequences,
  12303. alteredRoles,
  12304. alteredViews,
  12305. alteredPolicies
  12306. };
  12307. }
  12308. var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
  12309. var init_jsonDiffer = __esm({
  12310. "src/jsonDiffer.js"() {
  12311. "use strict";
  12312. "use-strict";
  12313. import_json_diff = __toESM(require_lib());
  12314. mapArraysDiff = (source, diff2) => {
  12315. const sequence = [];
  12316. let sourceIndex = 0;
  12317. for (let i6 = 0; i6 < diff2.length; i6++) {
  12318. const it = diff2[i6];
  12319. if (it.length === 1) {
  12320. sequence.push({ type: "same", value: source[sourceIndex] });
  12321. sourceIndex += 1;
  12322. } else {
  12323. if (it[0] === "-") {
  12324. sequence.push({ type: "removed", value: it[1] });
  12325. } else {
  12326. sequence.push({ type: "added", value: it[1], before: "" });
  12327. }
  12328. }
  12329. }
  12330. const result = sequence.reverse().reduce(
  12331. (acc, it) => {
  12332. if (it.type === "same") {
  12333. acc.prev = it.value;
  12334. }
  12335. if (it.type === "added" && acc.prev) {
  12336. it.before = acc.prev;
  12337. }
  12338. acc.result.push(it);
  12339. return acc;
  12340. },
  12341. { result: [] }
  12342. );
  12343. return result.result.reverse();
  12344. };
  12345. findAlternationsInTable = (table6) => {
  12346. const columns = table6.columns ?? {};
  12347. const altered = Object.keys(columns).filter((it) => !(it.includes("__deleted") || it.includes("__added"))).map((it) => {
  12348. return { name: it, ...columns[it] };
  12349. });
  12350. const deletedIndexes = Object.fromEntries(
  12351. Object.entries(table6.indexes__deleted || {}).concat(
  12352. Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__deleted"))
  12353. ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
  12354. );
  12355. const addedIndexes = Object.fromEntries(
  12356. Object.entries(table6.indexes__added || {}).concat(
  12357. Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__added"))
  12358. ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
  12359. );
  12360. const alteredIndexes = Object.fromEntries(
  12361. Object.entries(table6.indexes || {}).filter((it) => {
  12362. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  12363. })
  12364. );
  12365. const deletedPolicies = Object.fromEntries(
  12366. Object.entries(table6.policies__deleted || {}).concat(
  12367. Object.entries(table6.policies || {}).filter((it) => it[0].includes("__deleted"))
  12368. ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
  12369. );
  12370. const addedPolicies = Object.fromEntries(
  12371. Object.entries(table6.policies__added || {}).concat(
  12372. Object.entries(table6.policies || {}).filter((it) => it[0].includes("__added"))
  12373. ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
  12374. );
  12375. const alteredPolicies = Object.fromEntries(
  12376. Object.entries(table6.policies || {}).filter((it) => {
  12377. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  12378. })
  12379. );
  12380. const deletedForeignKeys = Object.fromEntries(
  12381. Object.entries(table6.foreignKeys__deleted || {}).concat(
  12382. Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
  12383. ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
  12384. );
  12385. const addedForeignKeys = Object.fromEntries(
  12386. Object.entries(table6.foreignKeys__added || {}).concat(
  12387. Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__added"))
  12388. ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
  12389. );
  12390. const alteredForeignKeys = Object.fromEntries(
  12391. Object.entries(table6.foreignKeys || {}).filter(
  12392. (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted")
  12393. ).map((entry) => [entry[0], entry[1]])
  12394. );
  12395. const addedCompositePKs = Object.fromEntries(
  12396. Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
  12397. return it[0].endsWith("__added");
  12398. })
  12399. );
  12400. const deletedCompositePKs = Object.fromEntries(
  12401. Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
  12402. return it[0].endsWith("__deleted");
  12403. })
  12404. );
  12405. const alteredCompositePKs = Object.fromEntries(
  12406. Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
  12407. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  12408. })
  12409. );
  12410. const addedUniqueConstraints = Object.fromEntries(
  12411. Object.entries(table6.uniqueConstraints || {}).filter((it) => {
  12412. return it[0].endsWith("__added");
  12413. })
  12414. );
  12415. const deletedUniqueConstraints = Object.fromEntries(
  12416. Object.entries(table6.uniqueConstraints || {}).filter((it) => {
  12417. return it[0].endsWith("__deleted");
  12418. })
  12419. );
  12420. const alteredUniqueConstraints = Object.fromEntries(
  12421. Object.entries(table6.uniqueConstraints || {}).filter((it) => {
  12422. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  12423. })
  12424. );
  12425. const addedCheckConstraints = Object.fromEntries(
  12426. Object.entries(table6.checkConstraints || {}).filter((it) => {
  12427. return it[0].endsWith("__added");
  12428. })
  12429. );
  12430. const deletedCheckConstraints = Object.fromEntries(
  12431. Object.entries(table6.checkConstraints || {}).filter((it) => {
  12432. return it[0].endsWith("__deleted");
  12433. })
  12434. );
  12435. const alteredCheckConstraints = Object.fromEntries(
  12436. Object.entries(table6.checkConstraints || {}).filter((it) => {
  12437. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  12438. })
  12439. );
  12440. const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
  12441. return {
  12442. name: table6.name,
  12443. schema: table6.schema || "",
  12444. altered: mappedAltered,
  12445. addedIndexes,
  12446. deletedIndexes,
  12447. alteredIndexes,
  12448. addedForeignKeys,
  12449. deletedForeignKeys,
  12450. alteredForeignKeys,
  12451. addedCompositePKs,
  12452. deletedCompositePKs,
  12453. alteredCompositePKs,
  12454. addedUniqueConstraints,
  12455. deletedUniqueConstraints,
  12456. alteredUniqueConstraints,
  12457. deletedPolicies,
  12458. addedPolicies,
  12459. alteredPolicies,
  12460. addedCheckConstraints,
  12461. deletedCheckConstraints,
  12462. alteredCheckConstraints
  12463. };
  12464. };
  12465. alternationsInColumn = (column6) => {
  12466. const altered = [column6];
  12467. const result = altered.filter((it) => {
  12468. if ("type" in it && it.type.__old.replace(" (", "(") === it.type.__new.replace(" (", "(")) {
  12469. return false;
  12470. }
  12471. return true;
  12472. }).map((it) => {
  12473. if (typeof it.name !== "string" && "__old" in it.name) {
  12474. return {
  12475. ...it,
  12476. name: { type: "changed", old: it.name.__old, new: it.name.__new }
  12477. };
  12478. }
  12479. return it;
  12480. }).map((it) => {
  12481. if ("type" in it) {
  12482. return {
  12483. ...it,
  12484. type: { type: "changed", old: it.type.__old, new: it.type.__new }
  12485. };
  12486. }
  12487. return it;
  12488. }).map((it) => {
  12489. if ("default" in it) {
  12490. return {
  12491. ...it,
  12492. default: {
  12493. type: "changed",
  12494. old: it.default.__old,
  12495. new: it.default.__new
  12496. }
  12497. };
  12498. }
  12499. if ("default__added" in it) {
  12500. const { default__added, ...others } = it;
  12501. return {
  12502. ...others,
  12503. default: { type: "added", value: it.default__added }
  12504. };
  12505. }
  12506. if ("default__deleted" in it) {
  12507. const { default__deleted, ...others } = it;
  12508. return {
  12509. ...others,
  12510. default: { type: "deleted", value: it.default__deleted }
  12511. };
  12512. }
  12513. return it;
  12514. }).map((it) => {
  12515. if ("generated" in it) {
  12516. if ("as" in it.generated && "type" in it.generated) {
  12517. return {
  12518. ...it,
  12519. generated: {
  12520. type: "changed",
  12521. old: { as: it.generated.as.__old, type: it.generated.type.__old },
  12522. new: { as: it.generated.as.__new, type: it.generated.type.__new }
  12523. }
  12524. };
  12525. } else if ("as" in it.generated) {
  12526. return {
  12527. ...it,
  12528. generated: {
  12529. type: "changed",
  12530. old: { as: it.generated.as.__old },
  12531. new: { as: it.generated.as.__new }
  12532. }
  12533. };
  12534. } else {
  12535. return {
  12536. ...it,
  12537. generated: {
  12538. type: "changed",
  12539. old: { as: it.generated.type.__old },
  12540. new: { as: it.generated.type.__new }
  12541. }
  12542. };
  12543. }
  12544. }
  12545. if ("generated__added" in it) {
  12546. const { generated__added, ...others } = it;
  12547. return {
  12548. ...others,
  12549. generated: { type: "added", value: it.generated__added }
  12550. };
  12551. }
  12552. if ("generated__deleted" in it) {
  12553. const { generated__deleted, ...others } = it;
  12554. return {
  12555. ...others,
  12556. generated: { type: "deleted", value: it.generated__deleted }
  12557. };
  12558. }
  12559. return it;
  12560. }).map((it) => {
  12561. if ("identity" in it) {
  12562. return {
  12563. ...it,
  12564. identity: {
  12565. type: "changed",
  12566. old: it.identity.__old,
  12567. new: it.identity.__new
  12568. }
  12569. };
  12570. }
  12571. if ("identity__added" in it) {
  12572. const { identity__added, ...others } = it;
  12573. return {
  12574. ...others,
  12575. identity: { type: "added", value: it.identity__added }
  12576. };
  12577. }
  12578. if ("identity__deleted" in it) {
  12579. const { identity__deleted, ...others } = it;
  12580. return {
  12581. ...others,
  12582. identity: { type: "deleted", value: it.identity__deleted }
  12583. };
  12584. }
  12585. return it;
  12586. }).map((it) => {
  12587. if ("notNull" in it) {
  12588. return {
  12589. ...it,
  12590. notNull: {
  12591. type: "changed",
  12592. old: it.notNull.__old,
  12593. new: it.notNull.__new
  12594. }
  12595. };
  12596. }
  12597. if ("notNull__added" in it) {
  12598. const { notNull__added, ...others } = it;
  12599. return {
  12600. ...others,
  12601. notNull: { type: "added", value: it.notNull__added }
  12602. };
  12603. }
  12604. if ("notNull__deleted" in it) {
  12605. const { notNull__deleted, ...others } = it;
  12606. return {
  12607. ...others,
  12608. notNull: { type: "deleted", value: it.notNull__deleted }
  12609. };
  12610. }
  12611. return it;
  12612. }).map((it) => {
  12613. if ("primaryKey" in it) {
  12614. return {
  12615. ...it,
  12616. primaryKey: {
  12617. type: "changed",
  12618. old: it.primaryKey.__old,
  12619. new: it.primaryKey.__new
  12620. }
  12621. };
  12622. }
  12623. if ("primaryKey__added" in it) {
  12624. const { notNull__added, ...others } = it;
  12625. return {
  12626. ...others,
  12627. primaryKey: { type: "added", value: it.primaryKey__added }
  12628. };
  12629. }
  12630. if ("primaryKey__deleted" in it) {
  12631. const { notNull__deleted, ...others } = it;
  12632. return {
  12633. ...others,
  12634. primaryKey: { type: "deleted", value: it.primaryKey__deleted }
  12635. };
  12636. }
  12637. return it;
  12638. }).map((it) => {
  12639. if ("typeSchema" in it) {
  12640. return {
  12641. ...it,
  12642. typeSchema: {
  12643. type: "changed",
  12644. old: it.typeSchema.__old,
  12645. new: it.typeSchema.__new
  12646. }
  12647. };
  12648. }
  12649. if ("typeSchema__added" in it) {
  12650. const { typeSchema__added, ...others } = it;
  12651. return {
  12652. ...others,
  12653. typeSchema: { type: "added", value: it.typeSchema__added }
  12654. };
  12655. }
  12656. if ("typeSchema__deleted" in it) {
  12657. const { typeSchema__deleted, ...others } = it;
  12658. return {
  12659. ...others,
  12660. typeSchema: { type: "deleted", value: it.typeSchema__deleted }
  12661. };
  12662. }
  12663. return it;
  12664. }).map((it) => {
  12665. if ("onUpdate" in it) {
  12666. return {
  12667. ...it,
  12668. onUpdate: {
  12669. type: "changed",
  12670. old: it.onUpdate.__old,
  12671. new: it.onUpdate.__new
  12672. }
  12673. };
  12674. }
  12675. if ("onUpdate__added" in it) {
  12676. const { onUpdate__added, ...others } = it;
  12677. return {
  12678. ...others,
  12679. onUpdate: { type: "added", value: it.onUpdate__added }
  12680. };
  12681. }
  12682. if ("onUpdate__deleted" in it) {
  12683. const { onUpdate__deleted, ...others } = it;
  12684. return {
  12685. ...others,
  12686. onUpdate: { type: "deleted", value: it.onUpdate__deleted }
  12687. };
  12688. }
  12689. return it;
  12690. }).map((it) => {
  12691. if ("autoincrement" in it) {
  12692. return {
  12693. ...it,
  12694. autoincrement: {
  12695. type: "changed",
  12696. old: it.autoincrement.__old,
  12697. new: it.autoincrement.__new
  12698. }
  12699. };
  12700. }
  12701. if ("autoincrement__added" in it) {
  12702. const { autoincrement__added, ...others } = it;
  12703. return {
  12704. ...others,
  12705. autoincrement: { type: "added", value: it.autoincrement__added }
  12706. };
  12707. }
  12708. if ("autoincrement__deleted" in it) {
  12709. const { autoincrement__deleted, ...others } = it;
  12710. return {
  12711. ...others,
  12712. autoincrement: { type: "deleted", value: it.autoincrement__deleted }
  12713. };
  12714. }
  12715. return it;
  12716. }).map((it) => {
  12717. if ("" in it) {
  12718. return {
  12719. ...it,
  12720. autoincrement: {
  12721. type: "changed",
  12722. old: it.autoincrement.__old,
  12723. new: it.autoincrement.__new
  12724. }
  12725. };
  12726. }
  12727. if ("autoincrement__added" in it) {
  12728. const { autoincrement__added, ...others } = it;
  12729. return {
  12730. ...others,
  12731. autoincrement: { type: "added", value: it.autoincrement__added }
  12732. };
  12733. }
  12734. if ("autoincrement__deleted" in it) {
  12735. const { autoincrement__deleted, ...others } = it;
  12736. return {
  12737. ...others,
  12738. autoincrement: { type: "deleted", value: it.autoincrement__deleted }
  12739. };
  12740. }
  12741. return it;
  12742. }).filter(Boolean);
  12743. return result[0];
  12744. };
  12745. }
  12746. });
  12747. // src/sqlgenerator.ts
  12748. function fromJson(statements, dialect6, action, json2) {
  12749. const result = statements.flatMap((statement) => {
  12750. const filtered = convertors.filter((it) => {
  12751. return it.can(statement, dialect6);
  12752. });
  12753. const convertor = filtered.length === 1 ? filtered[0] : void 0;
  12754. if (!convertor) {
  12755. return "";
  12756. }
  12757. return convertor.convert(statement, json2, action);
  12758. }).filter((it) => it !== "");
  12759. return result;
  12760. }
  12761. var parseType, Convertor, PgCreateRoleConvertor, PgDropRoleConvertor, PgRenameRoleConvertor, PgAlterRoleConvertor, PgCreatePolicyConvertor, PgDropPolicyConvertor, PgRenamePolicyConvertor, PgAlterPolicyConvertor, PgCreateIndPolicyConvertor, PgDropIndPolicyConvertor, PgRenameIndPolicyConvertor, PgAlterIndPolicyConvertor, PgEnableRlsConvertor, PgDisableRlsConvertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SingleStoreCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, SingleStoreAlterTableAddUniqueConstraintConvertor, SingleStoreAlterTableDropUniqueConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SingleStoreDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, SingleStoreRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SingleStoreAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SingleStoreAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SingleStoreAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor, SingleStoreAlterTableAddPk, SingleStoreAlterTableDropPk, SingleStoreModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSingleStoreIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SingleStoreDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, SingleStoreRecreateTableConvertor, convertors;
  12762. var init_sqlgenerator = __esm({
  12763. "src/sqlgenerator.ts"() {
  12764. "use strict";
  12765. init_migrate();
  12766. init_mysqlSchema();
  12767. init_pgSchema();
  12768. init_singlestoreSchema();
  12769. init_sqliteSchema();
  12770. init_utils();
  12771. parseType = (schemaPrefix, type) => {
  12772. const pgNativeTypes = [
  12773. "uuid",
  12774. "smallint",
  12775. "integer",
  12776. "bigint",
  12777. "boolean",
  12778. "text",
  12779. "varchar",
  12780. "serial",
  12781. "bigserial",
  12782. "decimal",
  12783. "numeric",
  12784. "real",
  12785. "json",
  12786. "jsonb",
  12787. "time",
  12788. "time with time zone",
  12789. "time without time zone",
  12790. "time",
  12791. "timestamp",
  12792. "timestamp with time zone",
  12793. "timestamp without time zone",
  12794. "date",
  12795. "interval",
  12796. "bigint",
  12797. "bigserial",
  12798. "double precision",
  12799. "interval year",
  12800. "interval month",
  12801. "interval day",
  12802. "interval hour",
  12803. "interval minute",
  12804. "interval second",
  12805. "interval year to month",
  12806. "interval day to hour",
  12807. "interval day to minute",
  12808. "interval day to second",
  12809. "interval hour to minute",
  12810. "interval hour to second",
  12811. "interval minute to second",
  12812. "char",
  12813. "vector",
  12814. "geometry",
  12815. "halfvec",
  12816. "sparsevec",
  12817. "bit"
  12818. ];
  12819. const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
  12820. const arrayDefinition = (type.match(arrayDefinitionRegex) ?? []).join("");
  12821. const withoutArrayDefinition = type.replace(arrayDefinitionRegex, "");
  12822. return pgNativeTypes.some((it) => type.startsWith(it)) ? `${withoutArrayDefinition}${arrayDefinition}` : `${schemaPrefix}"${withoutArrayDefinition}"${arrayDefinition}`;
  12823. };
  12824. Convertor = class {
  12825. };
  12826. PgCreateRoleConvertor = class extends Convertor {
  12827. can(statement, dialect6) {
  12828. return statement.type === "create_role" && dialect6 === "postgresql";
  12829. }
  12830. convert(statement) {
  12831. return `CREATE ROLE "${statement.name}"${statement.values.createDb || statement.values.createRole || !statement.values.inherit ? ` WITH${statement.values.createDb ? " CREATEDB" : ""}${statement.values.createRole ? " CREATEROLE" : ""}${statement.values.inherit ? "" : " NOINHERIT"}` : ""};`;
  12832. }
  12833. };
  12834. PgDropRoleConvertor = class extends Convertor {
  12835. can(statement, dialect6) {
  12836. return statement.type === "drop_role" && dialect6 === "postgresql";
  12837. }
  12838. convert(statement) {
  12839. return `DROP ROLE "${statement.name}";`;
  12840. }
  12841. };
  12842. PgRenameRoleConvertor = class extends Convertor {
  12843. can(statement, dialect6) {
  12844. return statement.type === "rename_role" && dialect6 === "postgresql";
  12845. }
  12846. convert(statement) {
  12847. return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`;
  12848. }
  12849. };
  12850. PgAlterRoleConvertor = class extends Convertor {
  12851. can(statement, dialect6) {
  12852. return statement.type === "alter_role" && dialect6 === "postgresql";
  12853. }
  12854. convert(statement) {
  12855. return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`;
  12856. }
  12857. };
  12858. PgCreatePolicyConvertor = class extends Convertor {
  12859. can(statement, dialect6) {
  12860. return statement.type === "create_policy" && dialect6 === "postgresql";
  12861. }
  12862. convert(statement) {
  12863. const policy5 = statement.data;
  12864. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  12865. const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
  12866. const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
  12867. const policyToPart = policy5.to?.map(
  12868. (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"`
  12869. ).join(", ");
  12870. return `CREATE POLICY "${policy5.name}" ON ${tableNameWithSchema} AS ${policy5.as?.toUpperCase()} FOR ${policy5.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
  12871. }
  12872. };
  12873. PgDropPolicyConvertor = class extends Convertor {
  12874. can(statement, dialect6) {
  12875. return statement.type === "drop_policy" && dialect6 === "postgresql";
  12876. }
  12877. convert(statement) {
  12878. const policy5 = statement.data;
  12879. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  12880. return `DROP POLICY "${policy5.name}" ON ${tableNameWithSchema} CASCADE;`;
  12881. }
  12882. };
  12883. PgRenamePolicyConvertor = class extends Convertor {
  12884. can(statement, dialect6) {
  12885. return statement.type === "rename_policy" && dialect6 === "postgresql";
  12886. }
  12887. convert(statement) {
  12888. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  12889. return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`;
  12890. }
  12891. };
  12892. PgAlterPolicyConvertor = class extends Convertor {
  12893. can(statement, dialect6) {
  12894. return statement.type === "alter_policy" && dialect6 === "postgresql";
  12895. }
  12896. convert(statement, _dialect, action) {
  12897. const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.newData) : PgSquasher.unsquashPolicy(statement.newData);
  12898. const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.oldData) : PgSquasher.unsquashPolicy(statement.oldData);
  12899. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  12900. const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
  12901. const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : "";
  12902. return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
  12903. }
  12904. };
  12905. PgCreateIndPolicyConvertor = class extends Convertor {
  12906. can(statement, dialect6) {
  12907. return statement.type === "create_ind_policy" && dialect6 === "postgresql";
  12908. }
  12909. convert(statement) {
  12910. const policy5 = statement.data;
  12911. const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
  12912. const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
  12913. const policyToPart = policy5.to?.map(
  12914. (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"`
  12915. ).join(", ");
  12916. return `CREATE POLICY "${policy5.name}" ON ${policy5.on} AS ${policy5.as?.toUpperCase()} FOR ${policy5.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
  12917. }
  12918. };
  12919. PgDropIndPolicyConvertor = class extends Convertor {
  12920. can(statement, dialect6) {
  12921. return statement.type === "drop_ind_policy" && dialect6 === "postgresql";
  12922. }
  12923. convert(statement) {
  12924. const policy5 = statement.data;
  12925. return `DROP POLICY "${policy5.name}" ON ${policy5.on} CASCADE;`;
  12926. }
  12927. };
  12928. PgRenameIndPolicyConvertor = class extends Convertor {
  12929. can(statement, dialect6) {
  12930. return statement.type === "rename_ind_policy" && dialect6 === "postgresql";
  12931. }
  12932. convert(statement) {
  12933. return `ALTER POLICY "${statement.oldName}" ON ${statement.tableKey} RENAME TO "${statement.newName}";`;
  12934. }
  12935. };
  12936. PgAlterIndPolicyConvertor = class extends Convertor {
  12937. can(statement, dialect6) {
  12938. return statement.type === "alter_ind_policy" && dialect6 === "postgresql";
  12939. }
  12940. convert(statement) {
  12941. const newPolicy = statement.newData;
  12942. const oldPolicy = statement.oldData;
  12943. const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
  12944. const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : "";
  12945. return `ALTER POLICY "${oldPolicy.name}" ON ${oldPolicy.on} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
  12946. }
  12947. };
  12948. PgEnableRlsConvertor = class extends Convertor {
  12949. can(statement, dialect6) {
  12950. return statement.type === "enable_rls" && dialect6 === "postgresql";
  12951. }
  12952. convert(statement) {
  12953. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  12954. return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`;
  12955. }
  12956. };
  12957. PgDisableRlsConvertor = class extends Convertor {
  12958. can(statement, dialect6) {
  12959. return statement.type === "disable_rls" && dialect6 === "postgresql";
  12960. }
  12961. convert(statement) {
  12962. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  12963. return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`;
  12964. }
  12965. };
  12966. PgCreateTableConvertor = class extends Convertor {
  12967. can(statement, dialect6) {
  12968. return statement.type === "create_table" && dialect6 === "postgresql";
  12969. }
  12970. convert(st) {
  12971. const { tableName, schema: schema6, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st;
  12972. let statement = "";
  12973. const name = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  12974. statement += `CREATE TABLE ${name} (
  12975. `;
  12976. for (let i6 = 0; i6 < columns.length; i6++) {
  12977. const column6 = columns[i6];
  12978. const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
  12979. const notNullStatement = column6.notNull && !column6.identity ? " NOT NULL" : "";
  12980. const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
  12981. const uniqueConstraint6 = column6.isUnique ? ` CONSTRAINT "${column6.uniqueName}" UNIQUE${column6.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : "";
  12982. const schemaPrefix = column6.typeSchema && column6.typeSchema !== "public" ? `"${column6.typeSchema}".` : "";
  12983. const type = parseType(schemaPrefix, column6.type);
  12984. const generated = column6.generated;
  12985. const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : "";
  12986. const unsquashedIdentity = column6.identity ? PgSquasher.unsquashIdentity(column6.identity) : void 0;
  12987. const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
  12988. const identity = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
  12989. statement += ` "${column6.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint6}${identity}`;
  12990. statement += i6 === columns.length - 1 ? "" : ",\n";
  12991. }
  12992. if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
  12993. statement += ",\n";
  12994. const compositePK6 = PgSquasher.unsquashPK(compositePKs[0]);
  12995. statement += ` CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK6.columns.join(`","`)}")`;
  12996. }
  12997. if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
  12998. for (const uniqueConstraint6 of uniqueConstraints) {
  12999. statement += ",\n";
  13000. const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint6);
  13001. statement += ` CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`;
  13002. }
  13003. }
  13004. if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
  13005. for (const checkConstraint5 of checkConstraints) {
  13006. statement += ",\n";
  13007. const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint5);
  13008. statement += ` CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`;
  13009. }
  13010. }
  13011. statement += `
  13012. );`;
  13013. statement += `
  13014. `;
  13015. const enableRls = new PgEnableRlsConvertor().convert({
  13016. type: "enable_rls",
  13017. tableName,
  13018. schema: schema6
  13019. });
  13020. return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []];
  13021. }
  13022. };
  13023. MySqlCreateTableConvertor = class extends Convertor {
  13024. can(statement, dialect6) {
  13025. return statement.type === "create_table" && dialect6 === "mysql";
  13026. }
  13027. convert(st) {
  13028. const {
  13029. tableName,
  13030. columns,
  13031. schema: schema6,
  13032. checkConstraints,
  13033. compositePKs,
  13034. uniqueConstraints,
  13035. internals
  13036. } = st;
  13037. let statement = "";
  13038. statement += `CREATE TABLE \`${tableName}\` (
  13039. `;
  13040. for (let i6 = 0; i6 < columns.length; i6++) {
  13041. const column6 = columns[i6];
  13042. const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
  13043. const notNullStatement = column6.notNull ? " NOT NULL" : "";
  13044. const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
  13045. const onUpdateStatement = column6.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  13046. const autoincrementStatement = column6.autoincrement ? " AUTO_INCREMENT" : "";
  13047. const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS (${column6.generated?.as}) ${column6.generated?.type.toUpperCase()}` : "";
  13048. statement += ` \`${column6.name}\` ${column6.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`;
  13049. statement += i6 === columns.length - 1 ? "" : ",\n";
  13050. }
  13051. if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
  13052. statement += ",\n";
  13053. const compositePK6 = MySqlSquasher.unsquashPK(compositePKs[0]);
  13054. statement += ` CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
  13055. }
  13056. if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
  13057. for (const uniqueConstraint6 of uniqueConstraints) {
  13058. statement += ",\n";
  13059. const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint6);
  13060. const uniqueString = unsquashedUnique.columns.map((it) => {
  13061. return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
  13062. }).join(",");
  13063. statement += ` CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
  13064. }
  13065. }
  13066. if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
  13067. for (const checkConstraint5 of checkConstraints) {
  13068. statement += ",\n";
  13069. const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint5);
  13070. statement += ` CONSTRAINT \`${unsquashedCheck.name}\` CHECK(${unsquashedCheck.value})`;
  13071. }
  13072. }
  13073. statement += `
  13074. );`;
  13075. statement += `
  13076. `;
  13077. return statement;
  13078. }
  13079. };
  13080. SingleStoreCreateTableConvertor = class extends Convertor {
  13081. can(statement, dialect6) {
  13082. return statement.type === "create_table" && dialect6 === "singlestore";
  13083. }
  13084. convert(st) {
  13085. const {
  13086. tableName,
  13087. columns,
  13088. schema: schema6,
  13089. compositePKs,
  13090. uniqueConstraints,
  13091. internals
  13092. } = st;
  13093. let statement = "";
  13094. statement += `CREATE TABLE \`${tableName}\` (
  13095. `;
  13096. for (let i6 = 0; i6 < columns.length; i6++) {
  13097. const column6 = columns[i6];
  13098. const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
  13099. const notNullStatement = column6.notNull ? " NOT NULL" : "";
  13100. const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
  13101. const onUpdateStatement = column6.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  13102. const autoincrementStatement = column6.autoincrement ? " AUTO_INCREMENT" : "";
  13103. const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS (${column6.generated?.as}) ${column6.generated?.type.toUpperCase()}` : "";
  13104. statement += ` \`${column6.name}\` ${column6.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`;
  13105. statement += i6 === columns.length - 1 ? "" : ",\n";
  13106. }
  13107. if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
  13108. statement += ",\n";
  13109. const compositePK6 = SingleStoreSquasher.unsquashPK(compositePKs[0]);
  13110. statement += ` CONSTRAINT \`${compositePK6.name}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
  13111. }
  13112. if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
  13113. for (const uniqueConstraint6 of uniqueConstraints) {
  13114. statement += ",\n";
  13115. const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint6);
  13116. const uniqueString = unsquashedUnique.columns.map((it) => {
  13117. return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
  13118. }).join(",");
  13119. statement += ` CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
  13120. }
  13121. }
  13122. statement += `
  13123. );`;
  13124. statement += `
  13125. `;
  13126. return statement;
  13127. }
  13128. };
  13129. SQLiteCreateTableConvertor = class extends Convertor {
  13130. can(statement, dialect6) {
  13131. return statement.type === "sqlite_create_table" && (dialect6 === "sqlite" || dialect6 === "turso");
  13132. }
  13133. convert(st) {
  13134. const {
  13135. tableName,
  13136. columns,
  13137. referenceData,
  13138. compositePKs,
  13139. uniqueConstraints,
  13140. checkConstraints
  13141. } = st;
  13142. let statement = "";
  13143. statement += `CREATE TABLE \`${tableName}\` (
  13144. `;
  13145. for (let i6 = 0; i6 < columns.length; i6++) {
  13146. const column6 = columns[i6];
  13147. const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
  13148. const notNullStatement = column6.notNull ? " NOT NULL" : "";
  13149. const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
  13150. const autoincrementStatement = column6.autoincrement ? " AUTOINCREMENT" : "";
  13151. const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS ${column6.generated.as} ${column6.generated.type.toUpperCase()}` : "";
  13152. statement += " ";
  13153. statement += `\`${column6.name}\` ${column6.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`;
  13154. statement += i6 === columns.length - 1 ? "" : ",\n";
  13155. }
  13156. compositePKs.forEach((it) => {
  13157. statement += ",\n ";
  13158. statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`;
  13159. });
  13160. for (let i6 = 0; i6 < referenceData.length; i6++) {
  13161. const {
  13162. name,
  13163. tableFrom,
  13164. tableTo,
  13165. columnsFrom,
  13166. columnsTo,
  13167. onDelete,
  13168. onUpdate
  13169. } = referenceData[i6];
  13170. const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
  13171. const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
  13172. const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
  13173. const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
  13174. statement += ",";
  13175. statement += "\n ";
  13176. statement += `FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onUpdateStatement}${onDeleteStatement}`;
  13177. }
  13178. if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
  13179. for (const uniqueConstraint6 of uniqueConstraints) {
  13180. statement += ",\n";
  13181. const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint6);
  13182. statement += ` CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`;
  13183. }
  13184. }
  13185. if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
  13186. for (const check of checkConstraints) {
  13187. statement += ",\n";
  13188. const { value, name } = SQLiteSquasher.unsquashCheck(check);
  13189. statement += ` CONSTRAINT "${name}" CHECK(${value})`;
  13190. }
  13191. }
  13192. statement += `
  13193. `;
  13194. statement += `);`;
  13195. statement += `
  13196. `;
  13197. return statement;
  13198. }
  13199. };
  13200. PgCreateViewConvertor = class extends Convertor {
  13201. can(statement, dialect6) {
  13202. return statement.type === "create_view" && dialect6 === "postgresql";
  13203. }
  13204. convert(st) {
  13205. const { definition, name: viewName, schema: schema6, with: withOption, materialized, withNoData, tablespace, using } = st;
  13206. const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`;
  13207. let statement = materialized ? `CREATE MATERIALIZED VIEW ${name}` : `CREATE VIEW ${name}`;
  13208. if (using) statement += ` USING "${using}"`;
  13209. const options = [];
  13210. if (withOption) {
  13211. statement += ` WITH (`;
  13212. Object.entries(withOption).forEach(([key, value]) => {
  13213. if (typeof value === "undefined") return;
  13214. options.push(`${key.snake_case()} = ${value}`);
  13215. });
  13216. statement += options.join(", ");
  13217. statement += `)`;
  13218. }
  13219. if (tablespace) statement += ` TABLESPACE ${tablespace}`;
  13220. statement += ` AS (${definition})`;
  13221. if (withNoData) statement += ` WITH NO DATA`;
  13222. statement += `;`;
  13223. return statement;
  13224. }
  13225. };
  13226. MySqlCreateViewConvertor = class extends Convertor {
  13227. can(statement, dialect6) {
  13228. return statement.type === "mysql_create_view" && dialect6 === "mysql";
  13229. }
  13230. convert(st) {
  13231. const { definition, name, algorithm, sqlSecurity, withCheckOption, replace } = st;
  13232. let statement = `CREATE `;
  13233. statement += replace ? `OR REPLACE ` : "";
  13234. statement += algorithm ? `ALGORITHM = ${algorithm}
  13235. ` : "";
  13236. statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
  13237. ` : "";
  13238. statement += `VIEW \`${name}\` AS (${definition})`;
  13239. statement += withCheckOption ? `
  13240. WITH ${withCheckOption} CHECK OPTION` : "";
  13241. statement += ";";
  13242. return statement;
  13243. }
  13244. };
  13245. SqliteCreateViewConvertor = class extends Convertor {
  13246. can(statement, dialect6) {
  13247. return statement.type === "sqlite_create_view" && (dialect6 === "sqlite" || dialect6 === "turso");
  13248. }
  13249. convert(st) {
  13250. const { definition, name } = st;
  13251. return `CREATE VIEW \`${name}\` AS ${definition};`;
  13252. }
  13253. };
  13254. PgDropViewConvertor = class extends Convertor {
  13255. can(statement, dialect6) {
  13256. return statement.type === "drop_view" && dialect6 === "postgresql";
  13257. }
  13258. convert(st) {
  13259. const { name: viewName, schema: schema6, materialized } = st;
  13260. const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`;
  13261. return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name};`;
  13262. }
  13263. };
  13264. MySqlDropViewConvertor = class extends Convertor {
  13265. can(statement, dialect6) {
  13266. return statement.type === "drop_view" && dialect6 === "mysql";
  13267. }
  13268. convert(st) {
  13269. const { name } = st;
  13270. return `DROP VIEW \`${name}\`;`;
  13271. }
  13272. };
  13273. SqliteDropViewConvertor = class extends Convertor {
  13274. can(statement, dialect6) {
  13275. return statement.type === "drop_view" && (dialect6 === "sqlite" || dialect6 === "turso");
  13276. }
  13277. convert(st) {
  13278. const { name } = st;
  13279. return `DROP VIEW \`${name}\`;`;
  13280. }
  13281. };
  13282. MySqlAlterViewConvertor = class extends Convertor {
  13283. can(statement, dialect6) {
  13284. return statement.type === "alter_mysql_view" && dialect6 === "mysql";
  13285. }
  13286. convert(st) {
  13287. const { name, algorithm, definition, sqlSecurity, withCheckOption } = st;
  13288. let statement = `ALTER `;
  13289. statement += algorithm ? `ALGORITHM = ${algorithm}
  13290. ` : "";
  13291. statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
  13292. ` : "";
  13293. statement += `VIEW \`${name}\` AS ${definition}`;
  13294. statement += withCheckOption ? `
  13295. WITH ${withCheckOption} CHECK OPTION` : "";
  13296. statement += ";";
  13297. return statement;
  13298. }
  13299. };
  13300. PgRenameViewConvertor = class extends Convertor {
  13301. can(statement, dialect6) {
  13302. return statement.type === "rename_view" && dialect6 === "postgresql";
  13303. }
  13304. convert(st) {
  13305. const { nameFrom: from, nameTo: to, schema: schema6, materialized } = st;
  13306. const nameFrom = `"${schema6}"."${from}"`;
  13307. return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
  13308. }
  13309. };
  13310. MySqlRenameViewConvertor = class extends Convertor {
  13311. can(statement, dialect6) {
  13312. return statement.type === "rename_view" && dialect6 === "mysql";
  13313. }
  13314. convert(st) {
  13315. const { nameFrom: from, nameTo: to } = st;
  13316. return `RENAME TABLE \`${from}\` TO \`${to}\`;`;
  13317. }
  13318. };
  13319. PgAlterViewSchemaConvertor = class extends Convertor {
  13320. can(statement, dialect6) {
  13321. return statement.type === "alter_view_alter_schema" && dialect6 === "postgresql";
  13322. }
  13323. convert(st) {
  13324. const { fromSchema, toSchema, name, materialized } = st;
  13325. const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name}" SET SCHEMA "${toSchema}";`;
  13326. return statement;
  13327. }
  13328. };
  13329. PgAlterViewAddWithOptionConvertor = class extends Convertor {
  13330. can(statement, dialect6) {
  13331. return statement.type === "alter_view_add_with_option" && dialect6 === "postgresql";
  13332. }
  13333. convert(st) {
  13334. const { schema: schema6, with: withOption, name, materialized } = st;
  13335. let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" SET (`;
  13336. const options = [];
  13337. Object.entries(withOption).forEach(([key, value]) => {
  13338. options.push(`${key.snake_case()} = ${value}`);
  13339. });
  13340. statement += options.join(", ");
  13341. statement += `);`;
  13342. return statement;
  13343. }
  13344. };
  13345. PgAlterViewDropWithOptionConvertor = class extends Convertor {
  13346. can(statement, dialect6) {
  13347. return statement.type === "alter_view_drop_with_option" && dialect6 === "postgresql";
  13348. }
  13349. convert(st) {
  13350. const { schema: schema6, name, materialized, with: withOptions } = st;
  13351. let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" RESET (`;
  13352. const options = [];
  13353. Object.entries(withOptions).forEach(([key, value]) => {
  13354. options.push(`${key.snake_case()}`);
  13355. });
  13356. statement += options.join(", ");
  13357. statement += ");";
  13358. return statement;
  13359. }
  13360. };
  13361. PgAlterViewAlterTablespaceConvertor = class extends Convertor {
  13362. can(statement, dialect6) {
  13363. return statement.type === "alter_view_alter_tablespace" && dialect6 === "postgresql";
  13364. }
  13365. convert(st) {
  13366. const { schema: schema6, name, toTablespace } = st;
  13367. const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET TABLESPACE ${toTablespace};`;
  13368. return statement;
  13369. }
  13370. };
  13371. PgAlterViewAlterUsingConvertor = class extends Convertor {
  13372. can(statement, dialect6) {
  13373. return statement.type === "alter_view_alter_using" && dialect6 === "postgresql";
  13374. }
  13375. convert(st) {
  13376. const { schema: schema6, name, toUsing } = st;
  13377. const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET ACCESS METHOD "${toUsing}";`;
  13378. return statement;
  13379. }
  13380. };
  13381. PgAlterTableAlterColumnSetGenerated = class extends Convertor {
  13382. can(statement, dialect6) {
  13383. return statement.type === "alter_table_alter_column_set_identity" && dialect6 === "postgresql";
  13384. }
  13385. convert(statement) {
  13386. const { identity, tableName, columnName, schema: schema6 } = statement;
  13387. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  13388. const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
  13389. const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
  13390. const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
  13391. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" ADD${identityStatement};`;
  13392. }
  13393. };
  13394. PgAlterTableAlterColumnDropGenerated = class extends Convertor {
  13395. can(statement, dialect6) {
  13396. return statement.type === "alter_table_alter_column_drop_identity" && dialect6 === "postgresql";
  13397. }
  13398. convert(statement) {
  13399. const { tableName, columnName, schema: schema6 } = statement;
  13400. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  13401. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP IDENTITY;`;
  13402. }
  13403. };
  13404. PgAlterTableAlterColumnAlterGenerated = class extends Convertor {
  13405. can(statement, dialect6) {
  13406. return statement.type === "alter_table_alter_column_change_identity" && dialect6 === "postgresql";
  13407. }
  13408. convert(statement) {
  13409. const { identity, oldIdentity, tableName, columnName, schema: schema6 } = statement;
  13410. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  13411. const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
  13412. const unsquashedOldIdentity = PgSquasher.unsquashIdentity(oldIdentity);
  13413. const statementsToReturn = [];
  13414. if (unsquashedOldIdentity.type !== unsquashedIdentity.type) {
  13415. statementsToReturn.push(
  13416. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"};`
  13417. );
  13418. }
  13419. if (unsquashedOldIdentity.minValue !== unsquashedIdentity.minValue) {
  13420. statementsToReturn.push(
  13421. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MINVALUE ${unsquashedIdentity.minValue};`
  13422. );
  13423. }
  13424. if (unsquashedOldIdentity.maxValue !== unsquashedIdentity.maxValue) {
  13425. statementsToReturn.push(
  13426. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MAXVALUE ${unsquashedIdentity.maxValue};`
  13427. );
  13428. }
  13429. if (unsquashedOldIdentity.increment !== unsquashedIdentity.increment) {
  13430. statementsToReturn.push(
  13431. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET INCREMENT BY ${unsquashedIdentity.increment};`
  13432. );
  13433. }
  13434. if (unsquashedOldIdentity.startWith !== unsquashedIdentity.startWith) {
  13435. statementsToReturn.push(
  13436. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET START WITH ${unsquashedIdentity.startWith};`
  13437. );
  13438. }
  13439. if (unsquashedOldIdentity.cache !== unsquashedIdentity.cache) {
  13440. statementsToReturn.push(
  13441. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET CACHE ${unsquashedIdentity.cache};`
  13442. );
  13443. }
  13444. if (unsquashedOldIdentity.cycle !== unsquashedIdentity.cycle) {
  13445. statementsToReturn.push(
  13446. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET ${unsquashedIdentity.cycle ? `CYCLE` : "NO CYCLE"};`
  13447. );
  13448. }
  13449. return statementsToReturn;
  13450. }
  13451. };
  13452. PgAlterTableAddUniqueConstraintConvertor = class extends Convertor {
  13453. can(statement, dialect6) {
  13454. return statement.type === "create_unique_constraint" && dialect6 === "postgresql";
  13455. }
  13456. convert(statement) {
  13457. const unsquashed = PgSquasher.unsquashUnique(statement.data);
  13458. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  13459. return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" UNIQUE${unsquashed.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashed.columns.join('","')}");`;
  13460. }
  13461. };
  13462. PgAlterTableDropUniqueConstraintConvertor = class extends Convertor {
  13463. can(statement, dialect6) {
  13464. return statement.type === "delete_unique_constraint" && dialect6 === "postgresql";
  13465. }
  13466. convert(statement) {
  13467. const unsquashed = PgSquasher.unsquashUnique(statement.data);
  13468. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  13469. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${unsquashed.name}";`;
  13470. }
  13471. };
  13472. PgAlterTableAddCheckConstraintConvertor = class extends Convertor {
  13473. can(statement, dialect6) {
  13474. return statement.type === "create_check_constraint" && dialect6 === "postgresql";
  13475. }
  13476. convert(statement) {
  13477. const unsquashed = PgSquasher.unsquashCheck(statement.data);
  13478. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  13479. return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" CHECK (${unsquashed.value});`;
  13480. }
  13481. };
  13482. PgAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
  13483. can(statement, dialect6) {
  13484. return statement.type === "delete_check_constraint" && dialect6 === "postgresql";
  13485. }
  13486. convert(statement) {
  13487. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  13488. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
  13489. }
  13490. };
  13491. MySQLAlterTableAddUniqueConstraintConvertor = class extends Convertor {
  13492. can(statement, dialect6) {
  13493. return statement.type === "create_unique_constraint" && dialect6 === "mysql";
  13494. }
  13495. convert(statement) {
  13496. const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
  13497. return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
  13498. }
  13499. };
  13500. MySQLAlterTableDropUniqueConstraintConvertor = class extends Convertor {
  13501. can(statement, dialect6) {
  13502. return statement.type === "delete_unique_constraint" && dialect6 === "mysql";
  13503. }
  13504. convert(statement) {
  13505. const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
  13506. return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
  13507. }
  13508. };
  13509. MySqlAlterTableAddCheckConstraintConvertor = class extends Convertor {
  13510. can(statement, dialect6) {
  13511. return statement.type === "create_check_constraint" && dialect6 === "mysql";
  13512. }
  13513. convert(statement) {
  13514. const unsquashed = MySqlSquasher.unsquashCheck(statement.data);
  13515. const { tableName } = statement;
  13516. return `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` CHECK (${unsquashed.value});`;
  13517. }
  13518. };
  13519. SingleStoreAlterTableAddUniqueConstraintConvertor = class extends Convertor {
  13520. can(statement, dialect6) {
  13521. return statement.type === "create_unique_constraint" && dialect6 === "singlestore";
  13522. }
  13523. convert(statement) {
  13524. const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
  13525. return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
  13526. }
  13527. };
  13528. SingleStoreAlterTableDropUniqueConstraintConvertor = class extends Convertor {
  13529. can(statement, dialect6) {
  13530. return statement.type === "delete_unique_constraint" && dialect6 === "singlestore";
  13531. }
  13532. convert(statement) {
  13533. const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
  13534. return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
  13535. }
  13536. };
  13537. MySqlAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
  13538. can(statement, dialect6) {
  13539. return statement.type === "delete_check_constraint" && dialect6 === "mysql";
  13540. }
  13541. convert(statement) {
  13542. const { tableName } = statement;
  13543. return `ALTER TABLE \`${tableName}\` DROP CONSTRAINT \`${statement.constraintName}\`;`;
  13544. }
  13545. };
  13546. CreatePgSequenceConvertor = class extends Convertor {
  13547. can(statement, dialect6) {
  13548. return statement.type === "create_sequence" && dialect6 === "postgresql";
  13549. }
  13550. convert(st) {
  13551. const { name, values, schema: schema6 } = st;
  13552. const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  13553. return `CREATE SEQUENCE ${sequenceWithSchema}${values.increment ? ` INCREMENT BY ${values.increment}` : ""}${values.minValue ? ` MINVALUE ${values.minValue}` : ""}${values.maxValue ? ` MAXVALUE ${values.maxValue}` : ""}${values.startWith ? ` START WITH ${values.startWith}` : ""}${values.cache ? ` CACHE ${values.cache}` : ""}${values.cycle ? ` CYCLE` : ""};`;
  13554. }
  13555. };
  13556. DropPgSequenceConvertor = class extends Convertor {
  13557. can(statement, dialect6) {
  13558. return statement.type === "drop_sequence" && dialect6 === "postgresql";
  13559. }
  13560. convert(st) {
  13561. const { name, schema: schema6 } = st;
  13562. const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  13563. return `DROP SEQUENCE ${sequenceWithSchema};`;
  13564. }
  13565. };
  13566. RenamePgSequenceConvertor = class extends Convertor {
  13567. can(statement, dialect6) {
  13568. return statement.type === "rename_sequence" && dialect6 === "postgresql";
  13569. }
  13570. convert(st) {
  13571. const { nameFrom, nameTo, schema: schema6 } = st;
  13572. const sequenceWithSchemaFrom = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`;
  13573. const sequenceWithSchemaTo = schema6 ? `"${schema6}"."${nameTo}"` : `"${nameTo}"`;
  13574. return `ALTER SEQUENCE ${sequenceWithSchemaFrom} RENAME TO "${nameTo}";`;
  13575. }
  13576. };
  13577. MovePgSequenceConvertor = class extends Convertor {
  13578. can(statement, dialect6) {
  13579. return statement.type === "move_sequence" && dialect6 === "postgresql";
  13580. }
  13581. convert(st) {
  13582. const { schemaFrom, schemaTo, name } = st;
  13583. const sequenceWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
  13584. const seqSchemaTo = schemaTo ? `"${schemaTo}"` : `public`;
  13585. return `ALTER SEQUENCE ${sequenceWithSchema} SET SCHEMA ${seqSchemaTo};`;
  13586. }
  13587. };
  13588. AlterPgSequenceConvertor = class extends Convertor {
  13589. can(statement, dialect6) {
  13590. return statement.type === "alter_sequence" && dialect6 === "postgresql";
  13591. }
  13592. convert(st) {
  13593. const { name, schema: schema6, values } = st;
  13594. const { increment, minValue, maxValue, startWith, cache: cache5, cycle } = values;
  13595. const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  13596. return `ALTER SEQUENCE ${sequenceWithSchema}${increment ? ` INCREMENT BY ${increment}` : ""}${minValue ? ` MINVALUE ${minValue}` : ""}${maxValue ? ` MAXVALUE ${maxValue}` : ""}${startWith ? ` START WITH ${startWith}` : ""}${cache5 ? ` CACHE ${cache5}` : ""}${cycle ? ` CYCLE` : ""};`;
  13597. }
  13598. };
  13599. CreateTypeEnumConvertor = class extends Convertor {
  13600. can(statement) {
  13601. return statement.type === "create_type_enum";
  13602. }
  13603. convert(st) {
  13604. const { name, values, schema: schema6 } = st;
  13605. const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  13606. let valuesStatement = "(";
  13607. valuesStatement += values.map((it) => `'${escapeSingleQuotes(it)}'`).join(", ");
  13608. valuesStatement += ")";
  13609. let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`;
  13610. return statement;
  13611. }
  13612. };
  13613. DropTypeEnumConvertor = class extends Convertor {
  13614. can(statement) {
  13615. return statement.type === "drop_type_enum";
  13616. }
  13617. convert(st) {
  13618. const { name, schema: schema6 } = st;
  13619. const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  13620. let statement = `DROP TYPE ${enumNameWithSchema};`;
  13621. return statement;
  13622. }
  13623. };
  13624. AlterTypeAddValueConvertor = class extends Convertor {
  13625. can(statement) {
  13626. return statement.type === "alter_type_add_value";
  13627. }
  13628. convert(st) {
  13629. const { name, schema: schema6, value, before } = st;
  13630. const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  13631. return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`;
  13632. }
  13633. };
  13634. AlterTypeSetSchemaConvertor = class extends Convertor {
  13635. can(statement) {
  13636. return statement.type === "move_type_enum";
  13637. }
  13638. convert(st) {
  13639. const { name, schemaFrom, schemaTo } = st;
  13640. const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
  13641. return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`;
  13642. }
  13643. };
  13644. AlterRenameTypeConvertor = class extends Convertor {
  13645. can(statement) {
  13646. return statement.type === "rename_type_enum";
  13647. }
  13648. convert(st) {
  13649. const { nameTo, nameFrom, schema: schema6 } = st;
  13650. const enumNameWithSchema = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`;
  13651. return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`;
  13652. }
  13653. };
  13654. AlterTypeDropValueConvertor = class extends Convertor {
  13655. can(statement) {
  13656. return statement.type === "alter_type_drop_value";
  13657. }
  13658. convert(st) {
  13659. const { columnsWithEnum, name, newValues, enumSchema: enumSchema4 } = st;
  13660. const statements = [];
  13661. for (const withEnum of columnsWithEnum) {
  13662. const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
  13663. statements.push(
  13664. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
  13665. );
  13666. if (withEnum.default) {
  13667. statements.push(
  13668. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::text;`
  13669. );
  13670. }
  13671. }
  13672. statements.push(new DropTypeEnumConvertor().convert({ name, schema: enumSchema4, type: "drop_type_enum" }));
  13673. statements.push(new CreateTypeEnumConvertor().convert({
  13674. name,
  13675. schema: enumSchema4,
  13676. values: newValues,
  13677. type: "create_type_enum"
  13678. }));
  13679. for (const withEnum of columnsWithEnum) {
  13680. const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
  13681. const parsedType = parseType(`"${enumSchema4}".`, withEnum.columnType);
  13682. if (withEnum.default) {
  13683. statements.push(
  13684. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::${parsedType};`
  13685. );
  13686. }
  13687. statements.push(
  13688. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE ${parsedType} USING "${withEnum.column}"::${parsedType};`
  13689. );
  13690. }
  13691. return statements;
  13692. }
  13693. };
  13694. PgDropTableConvertor = class extends Convertor {
  13695. can(statement, dialect6) {
  13696. return statement.type === "drop_table" && dialect6 === "postgresql";
  13697. }
  13698. convert(statement, _d2, action) {
  13699. const { tableName, schema: schema6, policies } = statement;
  13700. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  13701. const dropPolicyConvertor = new PgDropPolicyConvertor();
  13702. const droppedPolicies = policies?.map((p5) => {
  13703. return dropPolicyConvertor.convert({
  13704. type: "drop_policy",
  13705. tableName,
  13706. data: action === "push" ? PgSquasher.unsquashPolicyPush(p5) : PgSquasher.unsquashPolicy(p5),
  13707. schema: schema6
  13708. });
  13709. }) ?? [];
  13710. return [
  13711. ...droppedPolicies,
  13712. `DROP TABLE ${tableNameWithSchema} CASCADE;`
  13713. ];
  13714. }
  13715. };
  13716. MySQLDropTableConvertor = class extends Convertor {
  13717. can(statement, dialect6) {
  13718. return statement.type === "drop_table" && dialect6 === "mysql";
  13719. }
  13720. convert(statement) {
  13721. const { tableName } = statement;
  13722. return `DROP TABLE \`${tableName}\`;`;
  13723. }
  13724. };
  13725. SingleStoreDropTableConvertor = class extends Convertor {
  13726. can(statement, dialect6) {
  13727. return statement.type === "drop_table" && dialect6 === "singlestore";
  13728. }
  13729. convert(statement) {
  13730. const { tableName } = statement;
  13731. return `DROP TABLE \`${tableName}\`;`;
  13732. }
  13733. };
  13734. SQLiteDropTableConvertor = class extends Convertor {
  13735. can(statement, dialect6) {
  13736. return statement.type === "drop_table" && (dialect6 === "sqlite" || dialect6 === "turso");
  13737. }
  13738. convert(statement) {
  13739. const { tableName } = statement;
  13740. return `DROP TABLE \`${tableName}\`;`;
  13741. }
  13742. };
  13743. PgRenameTableConvertor = class extends Convertor {
  13744. can(statement, dialect6) {
  13745. return statement.type === "rename_table" && dialect6 === "postgresql";
  13746. }
  13747. convert(statement) {
  13748. const { tableNameFrom, tableNameTo, toSchema, fromSchema } = statement;
  13749. const from = fromSchema ? `"${fromSchema}"."${tableNameFrom}"` : `"${tableNameFrom}"`;
  13750. const to = `"${tableNameTo}"`;
  13751. return `ALTER TABLE ${from} RENAME TO ${to};`;
  13752. }
  13753. };
  13754. SqliteRenameTableConvertor = class extends Convertor {
  13755. can(statement, dialect6) {
  13756. return statement.type === "rename_table" && (dialect6 === "sqlite" || dialect6 === "turso");
  13757. }
  13758. convert(statement) {
  13759. const { tableNameFrom, tableNameTo } = statement;
  13760. return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
  13761. }
  13762. };
  13763. MySqlRenameTableConvertor = class extends Convertor {
  13764. can(statement, dialect6) {
  13765. return statement.type === "rename_table" && dialect6 === "mysql";
  13766. }
  13767. convert(statement) {
  13768. const { tableNameFrom, tableNameTo } = statement;
  13769. return `RENAME TABLE \`${tableNameFrom}\` TO \`${tableNameTo}\`;`;
  13770. }
  13771. };
  13772. SingleStoreRenameTableConvertor = class extends Convertor {
  13773. can(statement, dialect6) {
  13774. return statement.type === "rename_table" && dialect6 === "singlestore";
  13775. }
  13776. convert(statement) {
  13777. const { tableNameFrom, tableNameTo } = statement;
  13778. return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
  13779. }
  13780. };
  13781. PgAlterTableRenameColumnConvertor = class extends Convertor {
  13782. can(statement, dialect6) {
  13783. return statement.type === "alter_table_rename_column" && dialect6 === "postgresql";
  13784. }
  13785. convert(statement) {
  13786. const { tableName, oldColumnName, newColumnName, schema: schema6 } = statement;
  13787. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  13788. return `ALTER TABLE ${tableNameWithSchema} RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
  13789. }
  13790. };
  13791. MySqlAlterTableRenameColumnConvertor = class extends Convertor {
  13792. can(statement, dialect6) {
  13793. return statement.type === "alter_table_rename_column" && dialect6 === "mysql";
  13794. }
  13795. convert(statement) {
  13796. const { tableName, oldColumnName, newColumnName } = statement;
  13797. return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`;
  13798. }
  13799. };
  13800. SingleStoreAlterTableRenameColumnConvertor = class extends Convertor {
  13801. can(statement, dialect6) {
  13802. return statement.type === "alter_table_rename_column" && dialect6 === "singlestore";
  13803. }
  13804. convert(statement) {
  13805. const { tableName, oldColumnName, newColumnName } = statement;
  13806. return `ALTER TABLE \`${tableName}\` CHANGE \`${oldColumnName}\` \`${newColumnName}\`;`;
  13807. }
  13808. };
  13809. SQLiteAlterTableRenameColumnConvertor = class extends Convertor {
  13810. can(statement, dialect6) {
  13811. return statement.type === "alter_table_rename_column" && (dialect6 === "sqlite" || dialect6 === "turso");
  13812. }
  13813. convert(statement) {
  13814. const { tableName, oldColumnName, newColumnName } = statement;
  13815. return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
  13816. }
  13817. };
  13818. PgAlterTableDropColumnConvertor = class extends Convertor {
  13819. can(statement, dialect6) {
  13820. return statement.type === "alter_table_drop_column" && dialect6 === "postgresql";
  13821. }
  13822. convert(statement) {
  13823. const { tableName, columnName, schema: schema6 } = statement;
  13824. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  13825. return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN "${columnName}";`;
  13826. }
  13827. };
  13828. MySqlAlterTableDropColumnConvertor = class extends Convertor {
  13829. can(statement, dialect6) {
  13830. return statement.type === "alter_table_drop_column" && dialect6 === "mysql";
  13831. }
  13832. convert(statement) {
  13833. const { tableName, columnName } = statement;
  13834. return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
  13835. }
  13836. };
  13837. SingleStoreAlterTableDropColumnConvertor = class extends Convertor {
  13838. can(statement, dialect6) {
  13839. return statement.type === "alter_table_drop_column" && dialect6 === "singlestore";
  13840. }
  13841. convert(statement) {
  13842. const { tableName, columnName } = statement;
  13843. return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
  13844. }
  13845. };
  13846. SQLiteAlterTableDropColumnConvertor = class extends Convertor {
  13847. can(statement, dialect6) {
  13848. return statement.type === "alter_table_drop_column" && (dialect6 === "sqlite" || dialect6 === "turso");
  13849. }
  13850. convert(statement) {
  13851. const { tableName, columnName } = statement;
  13852. return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
  13853. }
  13854. };
  13855. PgAlterTableAddColumnConvertor = class extends Convertor {
  13856. can(statement, dialect6) {
  13857. return statement.type === "alter_table_add_column" && dialect6 === "postgresql";
  13858. }
  13859. convert(statement) {
  13860. const { tableName, column: column6, schema: schema6 } = statement;
  13861. const { name, type, notNull, generated, primaryKey, identity } = column6;
  13862. const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : "";
  13863. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  13864. const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
  13865. const schemaPrefix = column6.typeSchema && column6.typeSchema !== "public" ? `"${column6.typeSchema}".` : "";
  13866. const fixedType = parseType(schemaPrefix, column6.type);
  13867. const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
  13868. const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0;
  13869. const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
  13870. const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
  13871. const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : "";
  13872. return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN "${name}" ${fixedType}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${identityStatement};`;
  13873. }
  13874. };
  13875. MySqlAlterTableAddColumnConvertor = class extends Convertor {
  13876. can(statement, dialect6) {
  13877. return statement.type === "alter_table_add_column" && dialect6 === "mysql";
  13878. }
  13879. convert(statement) {
  13880. const { tableName, column: column6 } = statement;
  13881. const {
  13882. name,
  13883. type,
  13884. notNull,
  13885. primaryKey,
  13886. autoincrement,
  13887. onUpdate,
  13888. generated
  13889. } = column6;
  13890. const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
  13891. const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
  13892. const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
  13893. const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
  13894. const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
  13895. const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) ${generated?.type.toUpperCase()}` : "";
  13896. return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}${onUpdateStatement};`;
  13897. }
  13898. };
  13899. SingleStoreAlterTableAddColumnConvertor = class extends Convertor {
  13900. can(statement, dialect6) {
  13901. return statement.type === "alter_table_add_column" && dialect6 === "singlestore";
  13902. }
  13903. convert(statement) {
  13904. const { tableName, column: column6 } = statement;
  13905. const {
  13906. name,
  13907. type,
  13908. notNull,
  13909. primaryKey,
  13910. autoincrement,
  13911. onUpdate,
  13912. generated
  13913. } = column6;
  13914. const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
  13915. const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
  13916. const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
  13917. const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
  13918. const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
  13919. const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) ${generated?.type.toUpperCase()}` : "";
  13920. return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${notNullStatement}${onUpdateStatement}${generatedStatement};`;
  13921. }
  13922. };
  13923. SQLiteAlterTableAddColumnConvertor = class extends Convertor {
  13924. can(statement, dialect6) {
  13925. return statement.type === "sqlite_alter_table_add_column" && (dialect6 === "sqlite" || dialect6 === "turso");
  13926. }
  13927. convert(statement) {
  13928. const { tableName, column: column6, referenceData } = statement;
  13929. const { name, type, notNull, primaryKey, generated } = column6;
  13930. const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
  13931. const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
  13932. const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
  13933. const referenceAsObject = referenceData ? SQLiteSquasher.unsquashFK(referenceData) : void 0;
  13934. const referenceStatement = `${referenceAsObject ? ` REFERENCES ${referenceAsObject.tableTo}(${referenceAsObject.columnsTo})` : ""}`;
  13935. const generatedStatement = generated ? ` GENERATED ALWAYS AS ${generated.as} ${generated.type.toUpperCase()}` : "";
  13936. return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${referenceStatement};`;
  13937. }
  13938. };
  13939. PgAlterTableAlterColumnSetTypeConvertor = class extends Convertor {
  13940. can(statement, dialect6) {
  13941. return statement.type === "pg_alter_table_alter_column_set_type" && dialect6 === "postgresql";
  13942. }
  13943. convert(statement) {
  13944. const { tableName, columnName, newDataType, schema: schema6, oldDataType, columnDefault, typeSchema } = statement;
  13945. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  13946. const statements = [];
  13947. const type = parseType(`"${typeSchema}".`, newDataType.name);
  13948. if (!oldDataType.isEnum && !newDataType.isEnum) {
  13949. statements.push(
  13950. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
  13951. );
  13952. if (columnDefault) {
  13953. statements.push(
  13954. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
  13955. );
  13956. }
  13957. }
  13958. if (oldDataType.isEnum && !newDataType.isEnum) {
  13959. statements.push(
  13960. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
  13961. );
  13962. if (columnDefault) {
  13963. statements.push(
  13964. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
  13965. );
  13966. }
  13967. }
  13968. if (!oldDataType.isEnum && newDataType.isEnum) {
  13969. if (columnDefault) {
  13970. statements.push(
  13971. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault}::${type};`
  13972. );
  13973. }
  13974. statements.push(
  13975. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::${type};`
  13976. );
  13977. }
  13978. if (oldDataType.isEnum && newDataType.isEnum) {
  13979. const alterType = `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::text::${type};`;
  13980. if (newDataType.name !== oldDataType.name && columnDefault) {
  13981. statements.push(
  13982. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`,
  13983. alterType,
  13984. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
  13985. );
  13986. } else {
  13987. statements.push(alterType);
  13988. }
  13989. }
  13990. return statements;
  13991. }
  13992. };
  13993. PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor {
  13994. can(statement, dialect6) {
  13995. return statement.type === "alter_table_alter_column_set_default" && dialect6 === "postgresql";
  13996. }
  13997. convert(statement) {
  13998. const { tableName, columnName, schema: schema6 } = statement;
  13999. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  14000. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${statement.newDefaultValue};`;
  14001. }
  14002. };
  14003. PgAlterTableAlterColumnDropDefaultConvertor = class extends Convertor {
  14004. can(statement, dialect6) {
  14005. return statement.type === "alter_table_alter_column_drop_default" && dialect6 === "postgresql";
  14006. }
  14007. convert(statement) {
  14008. const { tableName, columnName, schema: schema6 } = statement;
  14009. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  14010. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`;
  14011. }
  14012. };
  14013. PgAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
  14014. can(statement, dialect6) {
  14015. return statement.type === "alter_table_alter_column_drop_generated" && dialect6 === "postgresql";
  14016. }
  14017. convert(statement) {
  14018. const { tableName, columnName, schema: schema6 } = statement;
  14019. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  14020. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP EXPRESSION;`;
  14021. }
  14022. };
  14023. PgAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
  14024. can(statement, dialect6) {
  14025. return statement.type === "alter_table_alter_column_set_generated" && dialect6 === "postgresql";
  14026. }
  14027. convert(statement) {
  14028. const {
  14029. tableName,
  14030. columnName,
  14031. schema: schema6,
  14032. columnNotNull: notNull,
  14033. columnDefault,
  14034. columnOnUpdate,
  14035. columnAutoIncrement,
  14036. columnPk,
  14037. columnGenerated
  14038. } = statement;
  14039. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  14040. const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
  14041. schema: schema6,
  14042. tableName,
  14043. column: {
  14044. name: columnName,
  14045. type: statement.newDataType,
  14046. notNull,
  14047. default: columnDefault,
  14048. onUpdate: columnOnUpdate,
  14049. autoincrement: columnAutoIncrement,
  14050. primaryKey: columnPk,
  14051. generated: columnGenerated
  14052. },
  14053. type: "alter_table_add_column"
  14054. });
  14055. return [
  14056. `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
  14057. addColumnStatement
  14058. ];
  14059. }
  14060. };
  14061. PgAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
  14062. can(statement, dialect6) {
  14063. return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "postgresql";
  14064. }
  14065. convert(statement) {
  14066. const {
  14067. tableName,
  14068. columnName,
  14069. schema: schema6,
  14070. columnNotNull: notNull,
  14071. columnDefault,
  14072. columnOnUpdate,
  14073. columnAutoIncrement,
  14074. columnPk,
  14075. columnGenerated
  14076. } = statement;
  14077. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  14078. const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
  14079. schema: schema6,
  14080. tableName,
  14081. column: {
  14082. name: columnName,
  14083. type: statement.newDataType,
  14084. notNull,
  14085. default: columnDefault,
  14086. onUpdate: columnOnUpdate,
  14087. autoincrement: columnAutoIncrement,
  14088. primaryKey: columnPk,
  14089. generated: columnGenerated
  14090. },
  14091. type: "alter_table_add_column"
  14092. });
  14093. return [
  14094. `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
  14095. addColumnStatement
  14096. ];
  14097. }
  14098. };
  14099. SqliteAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
  14100. can(statement, dialect6) {
  14101. return statement.type === "alter_table_alter_column_drop_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
  14102. }
  14103. convert(statement) {
  14104. const {
  14105. tableName,
  14106. columnName,
  14107. schema: schema6,
  14108. columnDefault,
  14109. columnOnUpdate,
  14110. columnAutoIncrement,
  14111. columnPk,
  14112. columnGenerated,
  14113. columnNotNull
  14114. } = statement;
  14115. const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
  14116. {
  14117. tableName,
  14118. column: {
  14119. name: columnName,
  14120. type: statement.newDataType,
  14121. notNull: columnNotNull,
  14122. default: columnDefault,
  14123. onUpdate: columnOnUpdate,
  14124. autoincrement: columnAutoIncrement,
  14125. primaryKey: columnPk,
  14126. generated: columnGenerated
  14127. },
  14128. type: "sqlite_alter_table_add_column"
  14129. }
  14130. );
  14131. const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
  14132. tableName,
  14133. columnName,
  14134. schema: schema6,
  14135. type: "alter_table_drop_column"
  14136. });
  14137. return [dropColumnStatement, addColumnStatement];
  14138. }
  14139. };
  14140. SqliteAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
  14141. can(statement, dialect6) {
  14142. return statement.type === "alter_table_alter_column_set_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
  14143. }
  14144. convert(statement) {
  14145. const {
  14146. tableName,
  14147. columnName,
  14148. schema: schema6,
  14149. columnNotNull: notNull,
  14150. columnDefault,
  14151. columnOnUpdate,
  14152. columnAutoIncrement,
  14153. columnPk,
  14154. columnGenerated
  14155. } = statement;
  14156. const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
  14157. {
  14158. tableName,
  14159. column: {
  14160. name: columnName,
  14161. type: statement.newDataType,
  14162. notNull,
  14163. default: columnDefault,
  14164. onUpdate: columnOnUpdate,
  14165. autoincrement: columnAutoIncrement,
  14166. primaryKey: columnPk,
  14167. generated: columnGenerated
  14168. },
  14169. type: "sqlite_alter_table_add_column"
  14170. }
  14171. );
  14172. const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
  14173. tableName,
  14174. columnName,
  14175. schema: schema6,
  14176. type: "alter_table_drop_column"
  14177. });
  14178. return [dropColumnStatement, addColumnStatement];
  14179. }
  14180. };
  14181. SqliteAlterTableAlterColumnAlterGeneratedConvertor = class extends Convertor {
  14182. can(statement, dialect6) {
  14183. return statement.type === "alter_table_alter_column_alter_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
  14184. }
  14185. convert(statement) {
  14186. const {
  14187. tableName,
  14188. columnName,
  14189. schema: schema6,
  14190. columnNotNull,
  14191. columnDefault,
  14192. columnOnUpdate,
  14193. columnAutoIncrement,
  14194. columnPk,
  14195. columnGenerated
  14196. } = statement;
  14197. const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
  14198. {
  14199. tableName,
  14200. column: {
  14201. name: columnName,
  14202. type: statement.newDataType,
  14203. notNull: columnNotNull,
  14204. default: columnDefault,
  14205. onUpdate: columnOnUpdate,
  14206. autoincrement: columnAutoIncrement,
  14207. primaryKey: columnPk,
  14208. generated: columnGenerated
  14209. },
  14210. type: "sqlite_alter_table_add_column"
  14211. }
  14212. );
  14213. const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
  14214. tableName,
  14215. columnName,
  14216. schema: schema6,
  14217. type: "alter_table_drop_column"
  14218. });
  14219. return [dropColumnStatement, addColumnStatement];
  14220. }
  14221. };
  14222. MySqlAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
  14223. can(statement, dialect6) {
  14224. return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "mysql";
  14225. }
  14226. convert(statement) {
  14227. const {
  14228. tableName,
  14229. columnName,
  14230. schema: schema6,
  14231. columnNotNull: notNull,
  14232. columnDefault,
  14233. columnOnUpdate,
  14234. columnAutoIncrement,
  14235. columnPk,
  14236. columnGenerated
  14237. } = statement;
  14238. const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``;
  14239. const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({
  14240. schema: schema6,
  14241. tableName,
  14242. column: {
  14243. name: columnName,
  14244. type: statement.newDataType,
  14245. notNull,
  14246. default: columnDefault,
  14247. onUpdate: columnOnUpdate,
  14248. autoincrement: columnAutoIncrement,
  14249. primaryKey: columnPk,
  14250. generated: columnGenerated
  14251. },
  14252. type: "alter_table_add_column"
  14253. });
  14254. return [
  14255. `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
  14256. addColumnStatement
  14257. ];
  14258. }
  14259. };
  14260. MySqlAlterTableAddPk = class extends Convertor {
  14261. can(statement, dialect6) {
  14262. return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "mysql";
  14263. }
  14264. convert(statement) {
  14265. return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
  14266. }
  14267. };
  14268. MySqlAlterTableDropPk = class extends Convertor {
  14269. can(statement, dialect6) {
  14270. return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "mysql";
  14271. }
  14272. convert(statement) {
  14273. return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
  14274. }
  14275. };
  14276. LibSQLModifyColumn = class extends Convertor {
  14277. can(statement, dialect6) {
  14278. return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") && dialect6 === "turso";
  14279. }
  14280. convert(statement, json2) {
  14281. const { tableName, columnName } = statement;
  14282. let columnType = ``;
  14283. let columnDefault = "";
  14284. let columnNotNull = "";
  14285. const sqlStatements = [];
  14286. const indexes = [];
  14287. for (const table6 of Object.values(json2.tables)) {
  14288. for (const index6 of Object.values(table6.indexes)) {
  14289. const unsquashed = SQLiteSquasher.unsquashIdx(index6);
  14290. sqlStatements.push(`DROP INDEX "${unsquashed.name}";`);
  14291. indexes.push({ ...unsquashed, tableName: table6.name });
  14292. }
  14293. }
  14294. switch (statement.type) {
  14295. case "alter_table_alter_column_set_type":
  14296. columnType = ` ${statement.newDataType}`;
  14297. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14298. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14299. break;
  14300. case "alter_table_alter_column_drop_notnull":
  14301. columnType = ` ${statement.newDataType}`;
  14302. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14303. columnNotNull = "";
  14304. break;
  14305. case "alter_table_alter_column_set_notnull":
  14306. columnType = ` ${statement.newDataType}`;
  14307. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14308. columnNotNull = ` NOT NULL`;
  14309. break;
  14310. case "alter_table_alter_column_set_default":
  14311. columnType = ` ${statement.newDataType}`;
  14312. columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
  14313. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14314. break;
  14315. case "alter_table_alter_column_drop_default":
  14316. columnType = ` ${statement.newDataType}`;
  14317. columnDefault = "";
  14318. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14319. break;
  14320. }
  14321. columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
  14322. sqlStatements.push(
  14323. `ALTER TABLE \`${tableName}\` ALTER COLUMN "${columnName}" TO "${columnName}"${columnType}${columnNotNull}${columnDefault};`
  14324. );
  14325. for (const index6 of indexes) {
  14326. const indexPart = index6.isUnique ? "UNIQUE INDEX" : "INDEX";
  14327. const whereStatement = index6.where ? ` WHERE ${index6.where}` : "";
  14328. const uniqueString = index6.columns.map((it) => `\`${it}\``).join(",");
  14329. const tableName2 = index6.tableName;
  14330. sqlStatements.push(
  14331. `CREATE ${indexPart} \`${index6.name}\` ON \`${tableName2}\` (${uniqueString})${whereStatement};`
  14332. );
  14333. }
  14334. return sqlStatements;
  14335. }
  14336. };
  14337. MySqlModifyColumn = class extends Convertor {
  14338. can(statement, dialect6) {
  14339. return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "mysql";
  14340. }
  14341. convert(statement) {
  14342. const { tableName, columnName } = statement;
  14343. let columnType = ``;
  14344. let columnDefault = "";
  14345. let columnNotNull = "";
  14346. let columnOnUpdate = "";
  14347. let columnAutoincrement = "";
  14348. let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
  14349. let columnGenerated = "";
  14350. if (statement.type === "alter_table_alter_column_drop_notnull") {
  14351. columnType = ` ${statement.newDataType}`;
  14352. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14353. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14354. columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14355. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14356. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  14357. columnNotNull = ` NOT NULL`;
  14358. columnType = ` ${statement.newDataType}`;
  14359. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14360. columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14361. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14362. } else if (statement.type === "alter_table_alter_column_drop_on_update") {
  14363. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14364. columnType = ` ${statement.newDataType}`;
  14365. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14366. columnOnUpdate = "";
  14367. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14368. } else if (statement.type === "alter_table_alter_column_set_on_update") {
  14369. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14370. columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
  14371. columnType = ` ${statement.newDataType}`;
  14372. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14373. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14374. } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
  14375. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14376. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14377. columnType = ` ${statement.newDataType}`;
  14378. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14379. columnAutoincrement = " AUTO_INCREMENT";
  14380. } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
  14381. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14382. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14383. columnType = ` ${statement.newDataType}`;
  14384. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14385. columnAutoincrement = "";
  14386. } else if (statement.type === "alter_table_alter_column_set_default") {
  14387. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14388. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14389. columnType = ` ${statement.newDataType}`;
  14390. columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
  14391. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14392. } else if (statement.type === "alter_table_alter_column_drop_default") {
  14393. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14394. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14395. columnType = ` ${statement.newDataType}`;
  14396. columnDefault = "";
  14397. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14398. } else if (statement.type === "alter_table_alter_column_set_generated") {
  14399. columnType = ` ${statement.newDataType}`;
  14400. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14401. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14402. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14403. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14404. if (statement.columnGenerated?.type === "virtual") {
  14405. return [
  14406. new MySqlAlterTableDropColumnConvertor().convert({
  14407. type: "alter_table_drop_column",
  14408. tableName: statement.tableName,
  14409. columnName: statement.columnName,
  14410. schema: statement.schema
  14411. }),
  14412. new MySqlAlterTableAddColumnConvertor().convert({
  14413. tableName,
  14414. column: {
  14415. name: columnName,
  14416. type: statement.newDataType,
  14417. notNull: statement.columnNotNull,
  14418. default: statement.columnDefault,
  14419. onUpdate: statement.columnOnUpdate,
  14420. autoincrement: statement.columnAutoIncrement,
  14421. primaryKey: statement.columnPk,
  14422. generated: statement.columnGenerated
  14423. },
  14424. schema: statement.schema,
  14425. type: "alter_table_add_column"
  14426. })
  14427. ];
  14428. } else {
  14429. columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
  14430. }
  14431. } else if (statement.type === "alter_table_alter_column_drop_generated") {
  14432. columnType = ` ${statement.newDataType}`;
  14433. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14434. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14435. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14436. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14437. if (statement.oldColumn?.generated?.type === "virtual") {
  14438. return [
  14439. new MySqlAlterTableDropColumnConvertor().convert({
  14440. type: "alter_table_drop_column",
  14441. tableName: statement.tableName,
  14442. columnName: statement.columnName,
  14443. schema: statement.schema
  14444. }),
  14445. new MySqlAlterTableAddColumnConvertor().convert({
  14446. tableName,
  14447. column: {
  14448. name: columnName,
  14449. type: statement.newDataType,
  14450. notNull: statement.columnNotNull,
  14451. default: statement.columnDefault,
  14452. onUpdate: statement.columnOnUpdate,
  14453. autoincrement: statement.columnAutoIncrement,
  14454. primaryKey: statement.columnPk,
  14455. generated: statement.columnGenerated
  14456. },
  14457. schema: statement.schema,
  14458. type: "alter_table_add_column"
  14459. })
  14460. ];
  14461. }
  14462. } else {
  14463. columnType = ` ${statement.newDataType}`;
  14464. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14465. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14466. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14467. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14468. columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
  14469. }
  14470. columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
  14471. return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnGenerated}${columnNotNull}${columnDefault}${columnOnUpdate};`;
  14472. }
  14473. };
  14474. SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
  14475. can(statement, dialect6) {
  14476. return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "singlestore";
  14477. }
  14478. convert(statement) {
  14479. const {
  14480. tableName,
  14481. columnName,
  14482. schema: schema6,
  14483. columnNotNull: notNull,
  14484. columnDefault,
  14485. columnOnUpdate,
  14486. columnAutoIncrement,
  14487. columnPk,
  14488. columnGenerated
  14489. } = statement;
  14490. const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``;
  14491. const addColumnStatement = new SingleStoreAlterTableAddColumnConvertor().convert({
  14492. schema: schema6,
  14493. tableName,
  14494. column: {
  14495. name: columnName,
  14496. type: statement.newDataType,
  14497. notNull,
  14498. default: columnDefault,
  14499. onUpdate: columnOnUpdate,
  14500. autoincrement: columnAutoIncrement,
  14501. primaryKey: columnPk,
  14502. generated: columnGenerated
  14503. },
  14504. type: "alter_table_add_column"
  14505. });
  14506. return [
  14507. `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
  14508. addColumnStatement
  14509. ];
  14510. }
  14511. };
  14512. SingleStoreAlterTableAddPk = class extends Convertor {
  14513. can(statement, dialect6) {
  14514. return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "singlestore";
  14515. }
  14516. convert(statement) {
  14517. return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
  14518. }
  14519. };
  14520. SingleStoreAlterTableDropPk = class extends Convertor {
  14521. can(statement, dialect6) {
  14522. return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "singlestore";
  14523. }
  14524. convert(statement) {
  14525. return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
  14526. }
  14527. };
  14528. SingleStoreModifyColumn = class extends Convertor {
  14529. can(statement, dialect6) {
  14530. return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "singlestore";
  14531. }
  14532. convert(statement) {
  14533. const { tableName, columnName } = statement;
  14534. let columnType = ``;
  14535. let columnDefault = "";
  14536. let columnNotNull = "";
  14537. let columnOnUpdate = "";
  14538. let columnAutoincrement = "";
  14539. let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
  14540. let columnGenerated = "";
  14541. if (statement.type === "alter_table_alter_column_drop_notnull") {
  14542. columnType = ` ${statement.newDataType}`;
  14543. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14544. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14545. columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14546. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14547. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  14548. columnNotNull = ` NOT NULL`;
  14549. columnType = ` ${statement.newDataType}`;
  14550. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14551. columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14552. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14553. } else if (statement.type === "alter_table_alter_column_drop_on_update") {
  14554. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14555. columnType = ` ${statement.newDataType}`;
  14556. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14557. columnOnUpdate = "";
  14558. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14559. } else if (statement.type === "alter_table_alter_column_set_on_update") {
  14560. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14561. columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
  14562. columnType = ` ${statement.newDataType}`;
  14563. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14564. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14565. } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
  14566. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14567. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14568. columnType = ` ${statement.newDataType}`;
  14569. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14570. columnAutoincrement = " AUTO_INCREMENT";
  14571. } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
  14572. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14573. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14574. columnType = ` ${statement.newDataType}`;
  14575. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14576. columnAutoincrement = "";
  14577. } else if (statement.type === "alter_table_alter_column_set_default") {
  14578. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14579. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14580. columnType = ` ${statement.newDataType}`;
  14581. columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
  14582. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14583. } else if (statement.type === "alter_table_alter_column_drop_default") {
  14584. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14585. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14586. columnType = ` ${statement.newDataType}`;
  14587. columnDefault = "";
  14588. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14589. } else if (statement.type === "alter_table_alter_column_set_generated") {
  14590. columnType = ` ${statement.newDataType}`;
  14591. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14592. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14593. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14594. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14595. if (statement.columnGenerated?.type === "virtual") {
  14596. return [
  14597. new SingleStoreAlterTableDropColumnConvertor().convert({
  14598. type: "alter_table_drop_column",
  14599. tableName: statement.tableName,
  14600. columnName: statement.columnName,
  14601. schema: statement.schema
  14602. }),
  14603. new SingleStoreAlterTableAddColumnConvertor().convert({
  14604. tableName,
  14605. column: {
  14606. name: columnName,
  14607. type: statement.newDataType,
  14608. notNull: statement.columnNotNull,
  14609. default: statement.columnDefault,
  14610. onUpdate: statement.columnOnUpdate,
  14611. autoincrement: statement.columnAutoIncrement,
  14612. primaryKey: statement.columnPk,
  14613. generated: statement.columnGenerated
  14614. },
  14615. schema: statement.schema,
  14616. type: "alter_table_add_column"
  14617. })
  14618. ];
  14619. } else {
  14620. columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
  14621. }
  14622. } else if (statement.type === "alter_table_alter_column_drop_generated") {
  14623. columnType = ` ${statement.newDataType}`;
  14624. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14625. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14626. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14627. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14628. if (statement.oldColumn?.generated?.type === "virtual") {
  14629. return [
  14630. new SingleStoreAlterTableDropColumnConvertor().convert({
  14631. type: "alter_table_drop_column",
  14632. tableName: statement.tableName,
  14633. columnName: statement.columnName,
  14634. schema: statement.schema
  14635. }),
  14636. new SingleStoreAlterTableAddColumnConvertor().convert({
  14637. tableName,
  14638. column: {
  14639. name: columnName,
  14640. type: statement.newDataType,
  14641. notNull: statement.columnNotNull,
  14642. default: statement.columnDefault,
  14643. onUpdate: statement.columnOnUpdate,
  14644. autoincrement: statement.columnAutoIncrement,
  14645. primaryKey: statement.columnPk,
  14646. generated: statement.columnGenerated
  14647. },
  14648. schema: statement.schema,
  14649. type: "alter_table_add_column"
  14650. })
  14651. ];
  14652. }
  14653. } else {
  14654. columnType = ` ${statement.newDataType}`;
  14655. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  14656. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  14657. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  14658. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  14659. columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
  14660. }
  14661. columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
  14662. return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnNotNull}${columnDefault}${columnOnUpdate}${columnGenerated};`;
  14663. }
  14664. };
  14665. PgAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
  14666. can(statement, dialect6) {
  14667. return statement.type === "create_composite_pk" && dialect6 === "postgresql";
  14668. }
  14669. convert(statement) {
  14670. const { name, columns } = PgSquasher.unsquashPK(statement.data);
  14671. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  14672. return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.constraintName}" PRIMARY KEY("${columns.join('","')}");`;
  14673. }
  14674. };
  14675. PgAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
  14676. can(statement, dialect6) {
  14677. return statement.type === "delete_composite_pk" && dialect6 === "postgresql";
  14678. }
  14679. convert(statement) {
  14680. const { name, columns } = PgSquasher.unsquashPK(statement.data);
  14681. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  14682. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
  14683. }
  14684. };
  14685. PgAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
  14686. can(statement, dialect6) {
  14687. return statement.type === "alter_composite_pk" && dialect6 === "postgresql";
  14688. }
  14689. convert(statement) {
  14690. const { name, columns } = PgSquasher.unsquashPK(statement.old);
  14691. const { name: newName, columns: newColumns } = PgSquasher.unsquashPK(
  14692. statement.new
  14693. );
  14694. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  14695. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.oldConstraintName}";
  14696. ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.newConstraintName}" PRIMARY KEY("${newColumns.join('","')}");`;
  14697. }
  14698. };
  14699. MySqlAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
  14700. can(statement, dialect6) {
  14701. return statement.type === "create_composite_pk" && dialect6 === "mysql";
  14702. }
  14703. convert(statement) {
  14704. const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
  14705. return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY(\`${columns.join("`,`")}\`);`;
  14706. }
  14707. };
  14708. MySqlAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
  14709. can(statement, dialect6) {
  14710. return statement.type === "delete_composite_pk" && dialect6 === "mysql";
  14711. }
  14712. convert(statement) {
  14713. const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
  14714. return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY;`;
  14715. }
  14716. };
  14717. MySqlAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
  14718. can(statement, dialect6) {
  14719. return statement.type === "alter_composite_pk" && dialect6 === "mysql";
  14720. }
  14721. convert(statement) {
  14722. const { name, columns } = MySqlSquasher.unsquashPK(statement.old);
  14723. const { name: newName, columns: newColumns } = MySqlSquasher.unsquashPK(
  14724. statement.new
  14725. );
  14726. return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY, ADD PRIMARY KEY(\`${newColumns.join("`,`")}\`);`;
  14727. }
  14728. };
  14729. PgAlterTableAlterColumnSetPrimaryKeyConvertor = class extends Convertor {
  14730. can(statement, dialect6) {
  14731. return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "postgresql";
  14732. }
  14733. convert(statement) {
  14734. const { tableName, columnName } = statement;
  14735. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  14736. return `ALTER TABLE ${tableNameWithSchema} ADD PRIMARY KEY ("${columnName}");`;
  14737. }
  14738. };
  14739. PgAlterTableAlterColumnDropPrimaryKeyConvertor = class extends Convertor {
  14740. can(statement, dialect6) {
  14741. return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "postgresql";
  14742. }
  14743. convert(statement) {
  14744. const { tableName, columnName, schema: schema6 } = statement;
  14745. return `/*
  14746. Unfortunately in current drizzle-kit version we can't automatically get name for primary key.
  14747. We are working on making it available!
  14748. Meanwhile you can:
  14749. 1. Check pk name in your database, by running
  14750. SELECT constraint_name FROM information_schema.table_constraints
  14751. WHERE table_schema = '${typeof schema6 === "undefined" || schema6 === "" ? "public" : schema6}'
  14752. AND table_name = '${tableName}'
  14753. AND constraint_type = 'PRIMARY KEY';
  14754. 2. Uncomment code below and paste pk name manually
  14755. Hope to release this update as soon as possible
  14756. */
  14757. -- ALTER TABLE "${tableName}" DROP CONSTRAINT "<constraint_name>";`;
  14758. }
  14759. };
  14760. PgAlterTableAlterColumnSetNotNullConvertor = class extends Convertor {
  14761. can(statement, dialect6) {
  14762. return statement.type === "alter_table_alter_column_set_notnull" && dialect6 === "postgresql";
  14763. }
  14764. convert(statement) {
  14765. const { tableName, columnName } = statement;
  14766. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  14767. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET NOT NULL;`;
  14768. }
  14769. };
  14770. PgAlterTableAlterColumnDropNotNullConvertor = class extends Convertor {
  14771. can(statement, dialect6) {
  14772. return statement.type === "alter_table_alter_column_drop_notnull" && dialect6 === "postgresql";
  14773. }
  14774. convert(statement) {
  14775. const { tableName, columnName } = statement;
  14776. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  14777. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP NOT NULL;`;
  14778. }
  14779. };
  14780. PgCreateForeignKeyConvertor = class extends Convertor {
  14781. can(statement, dialect6) {
  14782. return statement.type === "create_reference" && dialect6 === "postgresql";
  14783. }
  14784. convert(statement) {
  14785. const {
  14786. name,
  14787. tableFrom,
  14788. tableTo,
  14789. columnsFrom,
  14790. columnsTo,
  14791. onDelete,
  14792. onUpdate,
  14793. schemaTo
  14794. } = PgSquasher.unsquashFK(statement.data);
  14795. const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
  14796. const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
  14797. const fromColumnsString = columnsFrom.map((it) => `"${it}"`).join(",");
  14798. const toColumnsString = columnsTo.map((it) => `"${it}"`).join(",");
  14799. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
  14800. const tableToNameWithSchema = schemaTo ? `"${schemaTo}"."${tableTo}"` : `"${tableTo}"`;
  14801. const alterStatement = `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
  14802. return alterStatement;
  14803. }
  14804. };
  14805. LibSQLCreateForeignKeyConvertor = class extends Convertor {
  14806. can(statement, dialect6) {
  14807. return statement.type === "create_reference" && dialect6 === "turso";
  14808. }
  14809. convert(statement, json2, action) {
  14810. const { columnsFrom, columnsTo, tableFrom, onDelete, onUpdate, tableTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
  14811. const { columnDefault, columnNotNull, columnType } = statement;
  14812. const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
  14813. const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
  14814. const columnsDefaultValue = columnDefault ? ` DEFAULT ${columnDefault}` : "";
  14815. const columnNotNullValue = columnNotNull ? ` NOT NULL` : "";
  14816. const columnTypeValue = columnType ? ` ${columnType}` : "";
  14817. const columnFrom = columnsFrom[0];
  14818. const columnTo = columnsTo[0];
  14819. return `ALTER TABLE \`${tableFrom}\` ALTER COLUMN "${columnFrom}" TO "${columnFrom}"${columnTypeValue}${columnNotNullValue}${columnsDefaultValue} REFERENCES ${tableTo}(${columnTo})${onDeleteStatement}${onUpdateStatement};`;
  14820. }
  14821. };
  14822. MySqlCreateForeignKeyConvertor = class extends Convertor {
  14823. can(statement, dialect6) {
  14824. return statement.type === "create_reference" && dialect6 === "mysql";
  14825. }
  14826. convert(statement) {
  14827. const {
  14828. name,
  14829. tableFrom,
  14830. tableTo,
  14831. columnsFrom,
  14832. columnsTo,
  14833. onDelete,
  14834. onUpdate
  14835. } = MySqlSquasher.unsquashFK(statement.data);
  14836. const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
  14837. const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
  14838. const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
  14839. const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
  14840. return `ALTER TABLE \`${tableFrom}\` ADD CONSTRAINT \`${name}\` FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
  14841. }
  14842. };
  14843. PgAlterForeignKeyConvertor = class extends Convertor {
  14844. can(statement, dialect6) {
  14845. return statement.type === "alter_reference" && dialect6 === "postgresql";
  14846. }
  14847. convert(statement) {
  14848. const newFk = PgSquasher.unsquashFK(statement.data);
  14849. const oldFk = PgSquasher.unsquashFK(statement.oldFkey);
  14850. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
  14851. let sql = `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${oldFk.name}";
  14852. `;
  14853. const onDeleteStatement = newFk.onDelete ? ` ON DELETE ${newFk.onDelete}` : "";
  14854. const onUpdateStatement = newFk.onUpdate ? ` ON UPDATE ${newFk.onUpdate}` : "";
  14855. const fromColumnsString = newFk.columnsFrom.map((it) => `"${it}"`).join(",");
  14856. const toColumnsString = newFk.columnsTo.map((it) => `"${it}"`).join(",");
  14857. const tableFromNameWithSchema = oldFk.schemaTo ? `"${oldFk.schemaTo}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
  14858. const tableToNameWithSchema = newFk.schemaTo ? `"${newFk.schemaTo}"."${newFk.tableFrom}"` : `"${newFk.tableFrom}"`;
  14859. const alterStatement = `ALTER TABLE ${tableFromNameWithSchema} ADD CONSTRAINT "${newFk.name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
  14860. sql += alterStatement;
  14861. return sql;
  14862. }
  14863. };
  14864. PgDeleteForeignKeyConvertor = class extends Convertor {
  14865. can(statement, dialect6) {
  14866. return statement.type === "delete_reference" && dialect6 === "postgresql";
  14867. }
  14868. convert(statement) {
  14869. const tableFrom = statement.tableName;
  14870. const { name } = PgSquasher.unsquashFK(statement.data);
  14871. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
  14872. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${name}";
  14873. `;
  14874. }
  14875. };
  14876. MySqlDeleteForeignKeyConvertor = class extends Convertor {
  14877. can(statement, dialect6) {
  14878. return statement.type === "delete_reference" && dialect6 === "mysql";
  14879. }
  14880. convert(statement) {
  14881. const tableFrom = statement.tableName;
  14882. const { name } = MySqlSquasher.unsquashFK(statement.data);
  14883. return `ALTER TABLE \`${tableFrom}\` DROP FOREIGN KEY \`${name}\`;
  14884. `;
  14885. }
  14886. };
  14887. CreatePgIndexConvertor = class extends Convertor {
  14888. can(statement, dialect6) {
  14889. return statement.type === "create_index_pg" && dialect6 === "postgresql";
  14890. }
  14891. convert(statement) {
  14892. const {
  14893. name,
  14894. columns,
  14895. isUnique,
  14896. concurrently,
  14897. with: withMap,
  14898. method,
  14899. where
  14900. } = statement.data;
  14901. const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
  14902. const value = columns.map(
  14903. (it) => `${it.isExpression ? it.expression : `"${it.expression}"`}${it.opclass ? ` ${it.opclass}` : it.asc ? "" : " DESC"}${it.asc && it.nulls && it.nulls === "last" || it.opclass ? "" : ` NULLS ${it.nulls.toUpperCase()}`}`
  14904. ).join(",");
  14905. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  14906. function reverseLogic(mappedWith) {
  14907. let reversedString = "";
  14908. for (const key in mappedWith) {
  14909. if (mappedWith.hasOwnProperty(key)) {
  14910. reversedString += `${key}=${mappedWith[key]},`;
  14911. }
  14912. }
  14913. reversedString = reversedString.slice(0, -1);
  14914. return reversedString;
  14915. }
  14916. return `CREATE ${indexPart}${concurrently ? " CONCURRENTLY" : ""} "${name}" ON ${tableNameWithSchema} USING ${method} (${value})${Object.keys(withMap).length !== 0 ? ` WITH (${reverseLogic(withMap)})` : ""}${where ? ` WHERE ${where}` : ""};`;
  14917. }
  14918. };
  14919. CreateMySqlIndexConvertor = class extends Convertor {
  14920. can(statement, dialect6) {
  14921. return statement.type === "create_index" && dialect6 === "mysql";
  14922. }
  14923. convert(statement) {
  14924. const { name, columns, isUnique } = MySqlSquasher.unsquashIdx(
  14925. statement.data
  14926. );
  14927. const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
  14928. const uniqueString = columns.map((it) => {
  14929. return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
  14930. }).join(",");
  14931. return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`;
  14932. }
  14933. };
  14934. CreateSingleStoreIndexConvertor = class extends Convertor {
  14935. can(statement, dialect6) {
  14936. return statement.type === "create_index" && dialect6 === "singlestore";
  14937. }
  14938. convert(statement) {
  14939. const { name, columns, isUnique } = SingleStoreSquasher.unsquashIdx(
  14940. statement.data
  14941. );
  14942. const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
  14943. const uniqueString = columns.map((it) => {
  14944. return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
  14945. }).join(",");
  14946. return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`;
  14947. }
  14948. };
  14949. CreateSqliteIndexConvertor = class extends Convertor {
  14950. can(statement, dialect6) {
  14951. return statement.type === "create_index" && (dialect6 === "sqlite" || dialect6 === "turso");
  14952. }
  14953. convert(statement) {
  14954. const { name, columns, isUnique, where } = SQLiteSquasher.unsquashIdx(
  14955. statement.data
  14956. );
  14957. const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
  14958. const whereStatement = where ? ` WHERE ${where}` : "";
  14959. const uniqueString = columns.map((it) => {
  14960. return statement.internal?.indexes ? statement.internal?.indexes[name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
  14961. }).join(",");
  14962. return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString})${whereStatement};`;
  14963. }
  14964. };
  14965. PgDropIndexConvertor = class extends Convertor {
  14966. can(statement, dialect6) {
  14967. return statement.type === "drop_index" && dialect6 === "postgresql";
  14968. }
  14969. convert(statement) {
  14970. const { schema: schema6 } = statement;
  14971. const { name } = PgSquasher.unsquashIdx(statement.data);
  14972. const indexNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  14973. return `DROP INDEX ${indexNameWithSchema};`;
  14974. }
  14975. };
  14976. PgCreateSchemaConvertor = class extends Convertor {
  14977. can(statement, dialect6) {
  14978. return statement.type === "create_schema" && dialect6 === "postgresql";
  14979. }
  14980. convert(statement) {
  14981. const { name } = statement;
  14982. return `CREATE SCHEMA "${name}";
  14983. `;
  14984. }
  14985. };
  14986. PgRenameSchemaConvertor = class extends Convertor {
  14987. can(statement, dialect6) {
  14988. return statement.type === "rename_schema" && dialect6 === "postgresql";
  14989. }
  14990. convert(statement) {
  14991. const { from, to } = statement;
  14992. return `ALTER SCHEMA "${from}" RENAME TO "${to}";
  14993. `;
  14994. }
  14995. };
  14996. PgDropSchemaConvertor = class extends Convertor {
  14997. can(statement, dialect6) {
  14998. return statement.type === "drop_schema" && dialect6 === "postgresql";
  14999. }
  15000. convert(statement) {
  15001. const { name } = statement;
  15002. return `DROP SCHEMA "${name}";
  15003. `;
  15004. }
  15005. };
  15006. PgAlterTableSetSchemaConvertor = class extends Convertor {
  15007. can(statement, dialect6) {
  15008. return statement.type === "alter_table_set_schema" && dialect6 === "postgresql";
  15009. }
  15010. convert(statement) {
  15011. const { tableName, schemaFrom, schemaTo } = statement;
  15012. return `ALTER TABLE "${schemaFrom}"."${tableName}" SET SCHEMA "${schemaTo}";
  15013. `;
  15014. }
  15015. };
  15016. PgAlterTableSetNewSchemaConvertor = class extends Convertor {
  15017. can(statement, dialect6) {
  15018. return statement.type === "alter_table_set_new_schema" && dialect6 === "postgresql";
  15019. }
  15020. convert(statement) {
  15021. const { tableName, to, from } = statement;
  15022. const tableNameWithSchema = from ? `"${from}"."${tableName}"` : `"${tableName}"`;
  15023. return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA "${to}";
  15024. `;
  15025. }
  15026. };
  15027. PgAlterTableRemoveFromSchemaConvertor = class extends Convertor {
  15028. can(statement, dialect6) {
  15029. return statement.type === "alter_table_remove_from_schema" && dialect6 === "postgresql";
  15030. }
  15031. convert(statement) {
  15032. const { tableName, schema: schema6 } = statement;
  15033. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  15034. return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA public;
  15035. `;
  15036. }
  15037. };
  15038. SqliteDropIndexConvertor = class extends Convertor {
  15039. can(statement, dialect6) {
  15040. return statement.type === "drop_index" && (dialect6 === "sqlite" || dialect6 === "turso");
  15041. }
  15042. convert(statement) {
  15043. const { name } = PgSquasher.unsquashIdx(statement.data);
  15044. return `DROP INDEX \`${name}\`;`;
  15045. }
  15046. };
  15047. MySqlDropIndexConvertor = class extends Convertor {
  15048. can(statement, dialect6) {
  15049. return statement.type === "drop_index" && dialect6 === "mysql";
  15050. }
  15051. convert(statement) {
  15052. const { name } = MySqlSquasher.unsquashIdx(statement.data);
  15053. return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
  15054. }
  15055. };
  15056. SingleStoreDropIndexConvertor = class extends Convertor {
  15057. can(statement, dialect6) {
  15058. return statement.type === "drop_index" && dialect6 === "singlestore";
  15059. }
  15060. convert(statement) {
  15061. const { name } = SingleStoreSquasher.unsquashIdx(statement.data);
  15062. return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
  15063. }
  15064. };
  15065. SQLiteRecreateTableConvertor = class extends Convertor {
  15066. can(statement, dialect6) {
  15067. return statement.type === "recreate_table" && dialect6 === "sqlite";
  15068. }
  15069. convert(statement) {
  15070. const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
  15071. const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
  15072. const newTableName = `__new_${tableName}`;
  15073. const sqlStatements = [];
  15074. sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
  15075. const mappedCheckConstraints = checkConstraints.map(
  15076. (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `'${newTableName}'.`)
  15077. );
  15078. sqlStatements.push(
  15079. new SQLiteCreateTableConvertor().convert({
  15080. type: "sqlite_create_table",
  15081. tableName: newTableName,
  15082. columns,
  15083. referenceData,
  15084. compositePKs,
  15085. checkConstraints: mappedCheckConstraints
  15086. })
  15087. );
  15088. sqlStatements.push(
  15089. `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
  15090. );
  15091. sqlStatements.push(
  15092. new SQLiteDropTableConvertor().convert({
  15093. type: "drop_table",
  15094. tableName,
  15095. schema: ""
  15096. })
  15097. );
  15098. sqlStatements.push(
  15099. new SqliteRenameTableConvertor().convert({
  15100. fromSchema: "",
  15101. tableNameFrom: newTableName,
  15102. tableNameTo: tableName,
  15103. toSchema: "",
  15104. type: "rename_table"
  15105. })
  15106. );
  15107. sqlStatements.push(`PRAGMA foreign_keys=ON;`);
  15108. return sqlStatements;
  15109. }
  15110. };
  15111. LibSQLRecreateTableConvertor = class extends Convertor {
  15112. can(statement, dialect6) {
  15113. return statement.type === "recreate_table" && dialect6 === "turso";
  15114. }
  15115. convert(statement) {
  15116. const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
  15117. const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
  15118. const newTableName = `__new_${tableName}`;
  15119. const sqlStatements = [];
  15120. const mappedCheckConstraints = checkConstraints.map(
  15121. (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
  15122. );
  15123. sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
  15124. sqlStatements.push(
  15125. new SQLiteCreateTableConvertor().convert({
  15126. type: "sqlite_create_table",
  15127. tableName: newTableName,
  15128. columns,
  15129. referenceData,
  15130. compositePKs,
  15131. checkConstraints: mappedCheckConstraints
  15132. })
  15133. );
  15134. sqlStatements.push(
  15135. `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
  15136. );
  15137. sqlStatements.push(
  15138. new SQLiteDropTableConvertor().convert({
  15139. type: "drop_table",
  15140. tableName,
  15141. schema: ""
  15142. })
  15143. );
  15144. sqlStatements.push(
  15145. new SqliteRenameTableConvertor().convert({
  15146. fromSchema: "",
  15147. tableNameFrom: newTableName,
  15148. tableNameTo: tableName,
  15149. toSchema: "",
  15150. type: "rename_table"
  15151. })
  15152. );
  15153. sqlStatements.push(`PRAGMA foreign_keys=ON;`);
  15154. return sqlStatements;
  15155. }
  15156. };
  15157. SingleStoreRecreateTableConvertor = class extends Convertor {
  15158. can(statement, dialect6) {
  15159. return statement.type === "singlestore_recreate_table" && dialect6 === "singlestore";
  15160. }
  15161. convert(statement) {
  15162. const { tableName, columns, compositePKs, uniqueConstraints } = statement;
  15163. const columnNames = columns.map((it) => `\`${it.name}\``).join(", ");
  15164. const newTableName = `__new_${tableName}`;
  15165. const sqlStatements = [];
  15166. sqlStatements.push(
  15167. new SingleStoreCreateTableConvertor().convert({
  15168. type: "create_table",
  15169. tableName: newTableName,
  15170. columns,
  15171. compositePKs,
  15172. uniqueConstraints,
  15173. schema: ""
  15174. })
  15175. );
  15176. sqlStatements.push(
  15177. `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
  15178. );
  15179. sqlStatements.push(
  15180. new SingleStoreDropTableConvertor().convert({
  15181. type: "drop_table",
  15182. tableName,
  15183. schema: ""
  15184. })
  15185. );
  15186. sqlStatements.push(
  15187. new SingleStoreRenameTableConvertor().convert({
  15188. fromSchema: "",
  15189. tableNameFrom: newTableName,
  15190. tableNameTo: tableName,
  15191. toSchema: "",
  15192. type: "rename_table"
  15193. })
  15194. );
  15195. return sqlStatements;
  15196. }
  15197. };
  15198. convertors = [];
  15199. convertors.push(new PgCreateTableConvertor());
  15200. convertors.push(new MySqlCreateTableConvertor());
  15201. convertors.push(new SingleStoreCreateTableConvertor());
  15202. convertors.push(new SingleStoreRecreateTableConvertor());
  15203. convertors.push(new SQLiteCreateTableConvertor());
  15204. convertors.push(new SQLiteRecreateTableConvertor());
  15205. convertors.push(new LibSQLRecreateTableConvertor());
  15206. convertors.push(new PgCreateViewConvertor());
  15207. convertors.push(new PgDropViewConvertor());
  15208. convertors.push(new PgRenameViewConvertor());
  15209. convertors.push(new PgAlterViewSchemaConvertor());
  15210. convertors.push(new PgAlterViewAddWithOptionConvertor());
  15211. convertors.push(new PgAlterViewDropWithOptionConvertor());
  15212. convertors.push(new PgAlterViewAlterTablespaceConvertor());
  15213. convertors.push(new PgAlterViewAlterUsingConvertor());
  15214. convertors.push(new MySqlCreateViewConvertor());
  15215. convertors.push(new MySqlDropViewConvertor());
  15216. convertors.push(new MySqlRenameViewConvertor());
  15217. convertors.push(new MySqlAlterViewConvertor());
  15218. convertors.push(new SqliteCreateViewConvertor());
  15219. convertors.push(new SqliteDropViewConvertor());
  15220. convertors.push(new CreateTypeEnumConvertor());
  15221. convertors.push(new DropTypeEnumConvertor());
  15222. convertors.push(new AlterTypeAddValueConvertor());
  15223. convertors.push(new AlterTypeSetSchemaConvertor());
  15224. convertors.push(new AlterRenameTypeConvertor());
  15225. convertors.push(new AlterTypeDropValueConvertor());
  15226. convertors.push(new CreatePgSequenceConvertor());
  15227. convertors.push(new DropPgSequenceConvertor());
  15228. convertors.push(new RenamePgSequenceConvertor());
  15229. convertors.push(new MovePgSequenceConvertor());
  15230. convertors.push(new AlterPgSequenceConvertor());
  15231. convertors.push(new PgDropTableConvertor());
  15232. convertors.push(new MySQLDropTableConvertor());
  15233. convertors.push(new SingleStoreDropTableConvertor());
  15234. convertors.push(new SQLiteDropTableConvertor());
  15235. convertors.push(new PgRenameTableConvertor());
  15236. convertors.push(new MySqlRenameTableConvertor());
  15237. convertors.push(new SingleStoreRenameTableConvertor());
  15238. convertors.push(new SqliteRenameTableConvertor());
  15239. convertors.push(new PgAlterTableRenameColumnConvertor());
  15240. convertors.push(new MySqlAlterTableRenameColumnConvertor());
  15241. convertors.push(new SingleStoreAlterTableRenameColumnConvertor());
  15242. convertors.push(new SQLiteAlterTableRenameColumnConvertor());
  15243. convertors.push(new PgAlterTableDropColumnConvertor());
  15244. convertors.push(new MySqlAlterTableDropColumnConvertor());
  15245. convertors.push(new SingleStoreAlterTableDropColumnConvertor());
  15246. convertors.push(new SQLiteAlterTableDropColumnConvertor());
  15247. convertors.push(new PgAlterTableAddColumnConvertor());
  15248. convertors.push(new MySqlAlterTableAddColumnConvertor());
  15249. convertors.push(new SingleStoreAlterTableAddColumnConvertor());
  15250. convertors.push(new SQLiteAlterTableAddColumnConvertor());
  15251. convertors.push(new PgAlterTableAlterColumnSetTypeConvertor());
  15252. convertors.push(new PgAlterTableAddUniqueConstraintConvertor());
  15253. convertors.push(new PgAlterTableDropUniqueConstraintConvertor());
  15254. convertors.push(new PgAlterTableAddCheckConstraintConvertor());
  15255. convertors.push(new PgAlterTableDeleteCheckConstraintConvertor());
  15256. convertors.push(new MySqlAlterTableAddCheckConstraintConvertor());
  15257. convertors.push(new MySqlAlterTableDeleteCheckConstraintConvertor());
  15258. convertors.push(new MySQLAlterTableAddUniqueConstraintConvertor());
  15259. convertors.push(new MySQLAlterTableDropUniqueConstraintConvertor());
  15260. convertors.push(new SingleStoreAlterTableAddUniqueConstraintConvertor());
  15261. convertors.push(new SingleStoreAlterTableDropUniqueConstraintConvertor());
  15262. convertors.push(new CreatePgIndexConvertor());
  15263. convertors.push(new CreateMySqlIndexConvertor());
  15264. convertors.push(new CreateSingleStoreIndexConvertor());
  15265. convertors.push(new CreateSqliteIndexConvertor());
  15266. convertors.push(new PgDropIndexConvertor());
  15267. convertors.push(new SqliteDropIndexConvertor());
  15268. convertors.push(new MySqlDropIndexConvertor());
  15269. convertors.push(new SingleStoreDropIndexConvertor());
  15270. convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
  15271. convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
  15272. convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
  15273. convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
  15274. convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
  15275. convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
  15276. convertors.push(new PgAlterPolicyConvertor());
  15277. convertors.push(new PgCreatePolicyConvertor());
  15278. convertors.push(new PgDropPolicyConvertor());
  15279. convertors.push(new PgRenamePolicyConvertor());
  15280. convertors.push(new PgAlterIndPolicyConvertor());
  15281. convertors.push(new PgCreateIndPolicyConvertor());
  15282. convertors.push(new PgDropIndPolicyConvertor());
  15283. convertors.push(new PgRenameIndPolicyConvertor());
  15284. convertors.push(new PgEnableRlsConvertor());
  15285. convertors.push(new PgDisableRlsConvertor());
  15286. convertors.push(new PgDropRoleConvertor());
  15287. convertors.push(new PgAlterRoleConvertor());
  15288. convertors.push(new PgCreateRoleConvertor());
  15289. convertors.push(new PgRenameRoleConvertor());
  15290. convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
  15291. convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
  15292. convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
  15293. convertors.push(new MySqlAlterTableAlterColumnAlterrGeneratedConvertor());
  15294. convertors.push(new SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor());
  15295. convertors.push(new SqliteAlterTableAlterColumnDropGeneratedConvertor());
  15296. convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor());
  15297. convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor());
  15298. convertors.push(new MySqlModifyColumn());
  15299. convertors.push(new LibSQLModifyColumn());
  15300. convertors.push(new SingleStoreModifyColumn());
  15301. convertors.push(new PgCreateForeignKeyConvertor());
  15302. convertors.push(new MySqlCreateForeignKeyConvertor());
  15303. convertors.push(new PgAlterForeignKeyConvertor());
  15304. convertors.push(new PgDeleteForeignKeyConvertor());
  15305. convertors.push(new MySqlDeleteForeignKeyConvertor());
  15306. convertors.push(new PgCreateSchemaConvertor());
  15307. convertors.push(new PgRenameSchemaConvertor());
  15308. convertors.push(new PgDropSchemaConvertor());
  15309. convertors.push(new PgAlterTableSetSchemaConvertor());
  15310. convertors.push(new PgAlterTableSetNewSchemaConvertor());
  15311. convertors.push(new PgAlterTableRemoveFromSchemaConvertor());
  15312. convertors.push(new LibSQLCreateForeignKeyConvertor());
  15313. convertors.push(new PgAlterTableAlterColumnDropGenerated());
  15314. convertors.push(new PgAlterTableAlterColumnSetGenerated());
  15315. convertors.push(new PgAlterTableAlterColumnAlterGenerated());
  15316. convertors.push(new PgAlterTableCreateCompositePrimaryKeyConvertor());
  15317. convertors.push(new PgAlterTableDeleteCompositePrimaryKeyConvertor());
  15318. convertors.push(new PgAlterTableAlterCompositePrimaryKeyConvertor());
  15319. convertors.push(new MySqlAlterTableDeleteCompositePrimaryKeyConvertor());
  15320. convertors.push(new MySqlAlterTableDropPk());
  15321. convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
  15322. convertors.push(new MySqlAlterTableAddPk());
  15323. convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
  15324. convertors.push(new SingleStoreAlterTableDropPk());
  15325. convertors.push(new SingleStoreAlterTableAddPk());
  15326. https: `
  15327. create table users (
  15328. id int,
  15329. name character varying(128)
  15330. );
  15331. create type venum as enum('one', 'two', 'three');
  15332. alter table users add column typed venum;
  15333. insert into users(id, name, typed) values (1, 'name1', 'one');
  15334. insert into users(id, name, typed) values (2, 'name2', 'two');
  15335. insert into users(id, name, typed) values (3, 'name3', 'three');
  15336. alter type venum rename to __venum;
  15337. create type venum as enum ('one', 'two', 'three', 'four', 'five');
  15338. ALTER TABLE users ALTER COLUMN typed TYPE venum USING typed::text::venum;
  15339. insert into users(id, name, typed) values (4, 'name4', 'four');
  15340. insert into users(id, name, typed) values (5, 'name5', 'five');
  15341. drop type __venum;
  15342. `;
  15343. }
  15344. });
  15345. // src/cli/commands/sqlitePushUtils.ts
  15346. var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn;
  15347. var init_sqlitePushUtils = __esm({
  15348. "src/cli/commands/sqlitePushUtils.ts"() {
  15349. "use strict";
  15350. init_source();
  15351. init_sqliteSchema();
  15352. init_sqlgenerator();
  15353. init_utils();
  15354. _moveDataStatements = (tableName, json, dataLoss = false) => {
  15355. const statements = [];
  15356. const newTableName = `__new_${tableName}`;
  15357. const tableColumns = Object.values(json.tables[tableName].columns);
  15358. const referenceData = Object.values(json.tables[tableName].foreignKeys);
  15359. const compositePKs = Object.values(
  15360. json.tables[tableName].compositePrimaryKeys
  15361. ).map((it) => SQLiteSquasher.unsquashPK(it));
  15362. const checkConstraints = Object.values(json.tables[tableName].checkConstraints);
  15363. const mappedCheckConstraints = checkConstraints.map(
  15364. (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
  15365. );
  15366. const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
  15367. statements.push(
  15368. new SQLiteCreateTableConvertor().convert({
  15369. type: "sqlite_create_table",
  15370. tableName: newTableName,
  15371. columns: tableColumns,
  15372. referenceData: fks,
  15373. compositePKs,
  15374. checkConstraints: mappedCheckConstraints
  15375. })
  15376. );
  15377. if (!dataLoss) {
  15378. const columns = Object.keys(json.tables[tableName].columns).map(
  15379. (c5) => `"${c5}"`
  15380. );
  15381. statements.push(
  15382. `INSERT INTO \`${newTableName}\`(${columns.join(
  15383. ", "
  15384. )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;`
  15385. );
  15386. }
  15387. statements.push(
  15388. new SQLiteDropTableConvertor().convert({
  15389. type: "drop_table",
  15390. tableName,
  15391. schema: ""
  15392. })
  15393. );
  15394. statements.push(
  15395. new SqliteRenameTableConvertor().convert({
  15396. fromSchema: "",
  15397. tableNameFrom: newTableName,
  15398. tableNameTo: tableName,
  15399. toSchema: "",
  15400. type: "rename_table"
  15401. })
  15402. );
  15403. for (const idx of Object.values(json.tables[tableName].indexes)) {
  15404. statements.push(
  15405. new CreateSqliteIndexConvertor().convert({
  15406. type: "create_index",
  15407. tableName,
  15408. schema: "",
  15409. data: idx
  15410. })
  15411. );
  15412. }
  15413. return statements;
  15414. };
  15415. getOldTableName = (tableName, meta) => {
  15416. for (const key of Object.keys(meta.tables)) {
  15417. const value = meta.tables[key];
  15418. if (`"${tableName}"` === value) {
  15419. return key.substring(1, key.length - 1);
  15420. }
  15421. }
  15422. return tableName;
  15423. };
  15424. getNewTableName = (tableName, meta) => {
  15425. if (typeof meta.tables[`"${tableName}"`] !== "undefined") {
  15426. return meta.tables[`"${tableName}"`].substring(
  15427. 1,
  15428. meta.tables[`"${tableName}"`].length - 1
  15429. );
  15430. }
  15431. return tableName;
  15432. };
  15433. logSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
  15434. let shouldAskForApprove = false;
  15435. const statementsToExecute = [];
  15436. const infoToPrint = [];
  15437. const tablesToRemove = [];
  15438. const columnsToRemove = [];
  15439. const schemasToRemove = [];
  15440. const tablesToTruncate = [];
  15441. for (const statement of statements) {
  15442. if (statement.type === "drop_table") {
  15443. const res = await connection.query(
  15444. `select count(*) as count from \`${statement.tableName}\``
  15445. );
  15446. const count = Number(res[0].count);
  15447. if (count > 0) {
  15448. infoToPrint.push(
  15449. `\xB7 You're about to delete ${source_default.underline(
  15450. statement.tableName
  15451. )} table with ${count} items`
  15452. );
  15453. tablesToRemove.push(statement.tableName);
  15454. shouldAskForApprove = true;
  15455. }
  15456. const fromJsonStatement = fromJson([statement], "sqlite", "push");
  15457. statementsToExecute.push(
  15458. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  15459. );
  15460. } else if (statement.type === "alter_table_drop_column") {
  15461. const tableName = statement.tableName;
  15462. const columnName = statement.columnName;
  15463. const res = await connection.query(
  15464. `select count(\`${tableName}\`.\`${columnName}\`) as count from \`${tableName}\``
  15465. );
  15466. const count = Number(res[0].count);
  15467. if (count > 0) {
  15468. infoToPrint.push(
  15469. `\xB7 You're about to delete ${source_default.underline(
  15470. columnName
  15471. )} column in ${tableName} table with ${count} items`
  15472. );
  15473. columnsToRemove.push(`${tableName}_${statement.columnName}`);
  15474. shouldAskForApprove = true;
  15475. }
  15476. const fromJsonStatement = fromJson([statement], "sqlite", "push");
  15477. statementsToExecute.push(
  15478. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  15479. );
  15480. } else if (statement.type === "sqlite_alter_table_add_column" && (statement.column.notNull && !statement.column.default)) {
  15481. const tableName = statement.tableName;
  15482. const columnName = statement.column.name;
  15483. const res = await connection.query(
  15484. `select count(*) as count from \`${tableName}\``
  15485. );
  15486. const count = Number(res[0].count);
  15487. if (count > 0) {
  15488. infoToPrint.push(
  15489. `\xB7 You're about to add not-null ${source_default.underline(
  15490. columnName
  15491. )} column without default value, which contains ${count} items`
  15492. );
  15493. tablesToTruncate.push(tableName);
  15494. statementsToExecute.push(`delete from ${tableName};`);
  15495. shouldAskForApprove = true;
  15496. }
  15497. const fromJsonStatement = fromJson([statement], "sqlite", "push");
  15498. statementsToExecute.push(
  15499. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  15500. );
  15501. } else if (statement.type === "recreate_table") {
  15502. const tableName = statement.tableName;
  15503. const oldTableName = getOldTableName(tableName, meta);
  15504. let dataLoss = false;
  15505. const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
  15506. const currentColumnNames = Object.keys(json2.tables[tableName].columns);
  15507. const { removedColumns, addedColumns } = findAddedAndRemoved(
  15508. prevColumnNames,
  15509. currentColumnNames
  15510. );
  15511. if (removedColumns.length) {
  15512. for (const removedColumn of removedColumns) {
  15513. const res = await connection.query(
  15514. `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
  15515. );
  15516. const count = Number(res[0].count);
  15517. if (count > 0) {
  15518. infoToPrint.push(
  15519. `\xB7 You're about to delete ${source_default.underline(
  15520. removedColumn
  15521. )} column in ${tableName} table with ${count} items`
  15522. );
  15523. columnsToRemove.push(removedColumn);
  15524. shouldAskForApprove = true;
  15525. }
  15526. }
  15527. }
  15528. if (addedColumns.length) {
  15529. for (const addedColumn of addedColumns) {
  15530. const [res] = await connection.query(
  15531. `select count(*) as count from \`${tableName}\``
  15532. );
  15533. const columnConf = json2.tables[tableName].columns[addedColumn];
  15534. const count = Number(res.count);
  15535. if (count > 0 && columnConf.notNull && !columnConf.default) {
  15536. dataLoss = true;
  15537. infoToPrint.push(
  15538. `\xB7 You're about to add not-null ${source_default.underline(
  15539. addedColumn
  15540. )} column without default value to table, which contains ${count} items`
  15541. );
  15542. shouldAskForApprove = true;
  15543. tablesToTruncate.push(tableName);
  15544. statementsToExecute.push(`DELETE FROM \`${tableName}\`;`);
  15545. }
  15546. }
  15547. }
  15548. const tablesReferencingCurrent = [];
  15549. for (const table6 of Object.values(json2.tables)) {
  15550. const tablesRefs = Object.values(json2.tables[table6.name].foreignKeys).filter((t6) => SQLiteSquasher.unsquashPushFK(t6).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
  15551. tablesReferencingCurrent.push(...tablesRefs);
  15552. }
  15553. if (!tablesReferencingCurrent.length) {
  15554. statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
  15555. continue;
  15556. }
  15557. const [{ foreign_keys: pragmaState }] = await connection.query(`PRAGMA foreign_keys;`);
  15558. if (pragmaState) {
  15559. statementsToExecute.push(`PRAGMA foreign_keys=OFF;`);
  15560. }
  15561. statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
  15562. if (pragmaState) {
  15563. statementsToExecute.push(`PRAGMA foreign_keys=ON;`);
  15564. }
  15565. } else {
  15566. const fromJsonStatement = fromJson([statement], "sqlite", "push");
  15567. statementsToExecute.push(
  15568. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  15569. );
  15570. }
  15571. }
  15572. return {
  15573. statementsToExecute,
  15574. shouldAskForApprove,
  15575. infoToPrint,
  15576. columnsToRemove: [...new Set(columnsToRemove)],
  15577. schemasToRemove: [...new Set(schemasToRemove)],
  15578. tablesToTruncate: [...new Set(tablesToTruncate)],
  15579. tablesToRemove: [...new Set(tablesToRemove)]
  15580. };
  15581. };
  15582. }
  15583. });
  15584. // src/jsonStatements.ts
  15585. var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSingleStoreCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateRoleJson, prepareAlterRoleJson, prepareDropRoleJson, prepareRenameRoleJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, prepareRenamePolicyJsons, prepareRenameIndPolicyJsons, prepareCreatePolicyJsons, prepareCreateIndPolicyJsons, prepareDropPolicyJsons, prepareDropIndPolicyJsons, prepareAlterPolicyJson, prepareAlterIndPolicyJson, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
  15586. var init_jsonStatements = __esm({
  15587. "src/jsonStatements.ts"() {
  15588. "use strict";
  15589. init_source();
  15590. init_sqlitePushUtils();
  15591. init_views();
  15592. init_mysqlSchema();
  15593. init_pgSchema();
  15594. init_singlestoreSchema();
  15595. init_sqliteSchema();
  15596. preparePgCreateTableJson = (table6, json2) => {
  15597. const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table6;
  15598. const tableKey2 = `${schema6 || "public"}.${name}`;
  15599. const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
  15600. return {
  15601. type: "create_table",
  15602. tableName: name,
  15603. schema: schema6,
  15604. columns: Object.values(columns),
  15605. compositePKs: Object.values(compositePrimaryKeys),
  15606. compositePkName,
  15607. uniqueConstraints: Object.values(uniqueConstraints),
  15608. policies: Object.values(policies),
  15609. checkConstraints: Object.values(checkConstraints),
  15610. isRLSEnabled: isRLSEnabled ?? false
  15611. };
  15612. };
  15613. prepareMySqlCreateTableJson = (table6, json2, internals) => {
  15614. const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table6;
  15615. return {
  15616. type: "create_table",
  15617. tableName: name,
  15618. schema: schema6,
  15619. columns: Object.values(columns),
  15620. compositePKs: Object.values(compositePrimaryKeys),
  15621. compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[MySqlSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
  15622. uniqueConstraints: Object.values(uniqueConstraints),
  15623. internals,
  15624. checkConstraints: Object.values(checkConstraints)
  15625. };
  15626. };
  15627. prepareSingleStoreCreateTableJson = (table6, json2, internals) => {
  15628. const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints } = table6;
  15629. return {
  15630. type: "create_table",
  15631. tableName: name,
  15632. schema: schema6,
  15633. columns: Object.values(columns),
  15634. compositePKs: Object.values(compositePrimaryKeys),
  15635. compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[SingleStoreSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
  15636. uniqueConstraints: Object.values(uniqueConstraints),
  15637. internals
  15638. };
  15639. };
  15640. prepareSQLiteCreateTable = (table6, action) => {
  15641. const { name, columns, uniqueConstraints, checkConstraints } = table6;
  15642. const references2 = Object.values(table6.foreignKeys);
  15643. const composites = Object.values(table6.compositePrimaryKeys).map(
  15644. (it) => SQLiteSquasher.unsquashPK(it)
  15645. );
  15646. const fks = references2.map(
  15647. (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
  15648. );
  15649. return {
  15650. type: "sqlite_create_table",
  15651. tableName: name,
  15652. columns: Object.values(columns),
  15653. referenceData: fks,
  15654. compositePKs: composites,
  15655. uniqueConstraints: Object.values(uniqueConstraints),
  15656. checkConstraints: Object.values(checkConstraints)
  15657. };
  15658. };
  15659. prepareDropTableJson = (table6) => {
  15660. return {
  15661. type: "drop_table",
  15662. tableName: table6.name,
  15663. schema: table6.schema,
  15664. policies: table6.policies ? Object.values(table6.policies) : []
  15665. };
  15666. };
  15667. prepareRenameTableJson = (tableFrom, tableTo) => {
  15668. return {
  15669. type: "rename_table",
  15670. fromSchema: tableTo.schema,
  15671. toSchema: tableTo.schema,
  15672. tableNameFrom: tableFrom.name,
  15673. tableNameTo: tableTo.name
  15674. };
  15675. };
  15676. prepareCreateEnumJson = (name, schema6, values) => {
  15677. return {
  15678. type: "create_type_enum",
  15679. name,
  15680. schema: schema6,
  15681. values
  15682. };
  15683. };
  15684. prepareAddValuesToEnumJson = (name, schema6, values) => {
  15685. return values.map((it) => {
  15686. return {
  15687. type: "alter_type_add_value",
  15688. name,
  15689. schema: schema6,
  15690. value: it.value,
  15691. before: it.before
  15692. };
  15693. });
  15694. };
  15695. prepareDropEnumValues = (name, schema6, removedValues, json2) => {
  15696. if (!removedValues.length) return [];
  15697. const affectedColumns = [];
  15698. for (const tableKey2 in json2.tables) {
  15699. const table6 = json2.tables[tableKey2];
  15700. for (const columnKey in table6.columns) {
  15701. const column6 = table6.columns[columnKey];
  15702. const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
  15703. const parsedColumnType = column6.type.replace(arrayDefinitionRegex, "");
  15704. if (parsedColumnType === name && column6.typeSchema === schema6) {
  15705. affectedColumns.push({
  15706. tableSchema: table6.schema,
  15707. table: table6.name,
  15708. column: column6.name,
  15709. columnType: column6.type,
  15710. default: column6.default
  15711. });
  15712. }
  15713. }
  15714. }
  15715. return [{
  15716. type: "alter_type_drop_value",
  15717. name,
  15718. enumSchema: schema6,
  15719. deletedValues: removedValues,
  15720. newValues: json2.enums[`${schema6}.${name}`].values,
  15721. columnsWithEnum: affectedColumns
  15722. }];
  15723. };
  15724. prepareDropEnumJson = (name, schema6) => {
  15725. return {
  15726. type: "drop_type_enum",
  15727. name,
  15728. schema: schema6
  15729. };
  15730. };
  15731. prepareMoveEnumJson = (name, schemaFrom, schemaTo) => {
  15732. return {
  15733. type: "move_type_enum",
  15734. name,
  15735. schemaFrom,
  15736. schemaTo
  15737. };
  15738. };
  15739. prepareRenameEnumJson = (nameFrom, nameTo, schema6) => {
  15740. return {
  15741. type: "rename_type_enum",
  15742. nameFrom,
  15743. nameTo,
  15744. schema: schema6
  15745. };
  15746. };
  15747. prepareCreateSequenceJson = (seq) => {
  15748. const values = PgSquasher.unsquashSequence(seq.values);
  15749. return {
  15750. type: "create_sequence",
  15751. name: seq.name,
  15752. schema: seq.schema,
  15753. values
  15754. };
  15755. };
  15756. prepareAlterSequenceJson = (seq) => {
  15757. const values = PgSquasher.unsquashSequence(seq.values);
  15758. return [
  15759. {
  15760. type: "alter_sequence",
  15761. schema: seq.schema,
  15762. name: seq.name,
  15763. values
  15764. }
  15765. ];
  15766. };
  15767. prepareDropSequenceJson = (name, schema6) => {
  15768. return {
  15769. type: "drop_sequence",
  15770. name,
  15771. schema: schema6
  15772. };
  15773. };
  15774. prepareMoveSequenceJson = (name, schemaFrom, schemaTo) => {
  15775. return {
  15776. type: "move_sequence",
  15777. name,
  15778. schemaFrom,
  15779. schemaTo
  15780. };
  15781. };
  15782. prepareRenameSequenceJson = (nameFrom, nameTo, schema6) => {
  15783. return {
  15784. type: "rename_sequence",
  15785. nameFrom,
  15786. nameTo,
  15787. schema: schema6
  15788. };
  15789. };
  15790. prepareCreateRoleJson = (role) => {
  15791. return {
  15792. type: "create_role",
  15793. name: role.name,
  15794. values: {
  15795. createDb: role.createDb,
  15796. createRole: role.createRole,
  15797. inherit: role.inherit
  15798. }
  15799. };
  15800. };
  15801. prepareAlterRoleJson = (role) => {
  15802. return {
  15803. type: "alter_role",
  15804. name: role.name,
  15805. values: {
  15806. createDb: role.createDb,
  15807. createRole: role.createRole,
  15808. inherit: role.inherit
  15809. }
  15810. };
  15811. };
  15812. prepareDropRoleJson = (name) => {
  15813. return {
  15814. type: "drop_role",
  15815. name
  15816. };
  15817. };
  15818. prepareRenameRoleJson = (nameFrom, nameTo) => {
  15819. return {
  15820. type: "rename_role",
  15821. nameFrom,
  15822. nameTo
  15823. };
  15824. };
  15825. prepareCreateSchemasJson = (values) => {
  15826. return values.map((it) => {
  15827. return {
  15828. type: "create_schema",
  15829. name: it
  15830. };
  15831. });
  15832. };
  15833. prepareRenameSchemasJson = (values) => {
  15834. return values.map((it) => {
  15835. return {
  15836. type: "rename_schema",
  15837. from: it.from,
  15838. to: it.to
  15839. };
  15840. });
  15841. };
  15842. prepareDeleteSchemasJson = (values) => {
  15843. return values.map((it) => {
  15844. return {
  15845. type: "drop_schema",
  15846. name: it
  15847. };
  15848. });
  15849. };
  15850. prepareRenameColumns = (tableName, schema6, pairs) => {
  15851. return pairs.map((it) => {
  15852. return {
  15853. type: "alter_table_rename_column",
  15854. tableName,
  15855. oldColumnName: it.from.name,
  15856. newColumnName: it.to.name,
  15857. schema: schema6
  15858. };
  15859. });
  15860. };
  15861. _prepareDropColumns = (taleName, schema6, columns) => {
  15862. return columns.map((it) => {
  15863. return {
  15864. type: "alter_table_drop_column",
  15865. tableName: taleName,
  15866. columnName: it.name,
  15867. schema: schema6
  15868. };
  15869. });
  15870. };
  15871. _prepareAddColumns = (tableName, schema6, columns) => {
  15872. return columns.map((it) => {
  15873. return {
  15874. type: "alter_table_add_column",
  15875. tableName,
  15876. column: it,
  15877. schema: schema6
  15878. };
  15879. });
  15880. };
  15881. _prepareSqliteAddColumns = (tableName, columns, referenceData) => {
  15882. const unsquashed = referenceData.map((addedFkValue) => SQLiteSquasher.unsquashFK(addedFkValue));
  15883. return columns.map((it) => {
  15884. const columnsWithReference = unsquashed.find((t6) => t6.columnsFrom.includes(it.name));
  15885. if (it.generated?.type === "stored") {
  15886. warning(
  15887. `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
  15888. );
  15889. return void 0;
  15890. }
  15891. return {
  15892. type: "sqlite_alter_table_add_column",
  15893. tableName,
  15894. column: it,
  15895. referenceData: columnsWithReference ? SQLiteSquasher.squashFK(columnsWithReference) : void 0
  15896. };
  15897. }).filter(Boolean);
  15898. };
  15899. prepareAlterColumnsMysql = (tableName, schema6, columns, json1, json2, action) => {
  15900. let statements = [];
  15901. let dropPkStatements = [];
  15902. let setPkStatements = [];
  15903. for (const column6 of columns) {
  15904. const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
  15905. const table6 = json2.tables[tableName];
  15906. const snapshotColumn = table6.columns[columnName];
  15907. const columnType = snapshotColumn.type;
  15908. const columnDefault = snapshotColumn.default;
  15909. const columnOnUpdate = "onUpdate" in snapshotColumn ? snapshotColumn.onUpdate : void 0;
  15910. const columnNotNull = table6.columns[columnName].notNull;
  15911. const columnAutoIncrement = "autoincrement" in snapshotColumn ? snapshotColumn.autoincrement ?? false : false;
  15912. const columnPk = table6.columns[columnName].primaryKey;
  15913. if (column6.autoincrement?.type === "added") {
  15914. statements.push({
  15915. type: "alter_table_alter_column_set_autoincrement",
  15916. tableName,
  15917. columnName,
  15918. schema: schema6,
  15919. newDataType: columnType,
  15920. columnDefault,
  15921. columnOnUpdate,
  15922. columnNotNull,
  15923. columnAutoIncrement,
  15924. columnPk
  15925. });
  15926. }
  15927. if (column6.autoincrement?.type === "changed") {
  15928. const type = column6.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
  15929. statements.push({
  15930. type,
  15931. tableName,
  15932. columnName,
  15933. schema: schema6,
  15934. newDataType: columnType,
  15935. columnDefault,
  15936. columnOnUpdate,
  15937. columnNotNull,
  15938. columnAutoIncrement,
  15939. columnPk
  15940. });
  15941. }
  15942. if (column6.autoincrement?.type === "deleted") {
  15943. statements.push({
  15944. type: "alter_table_alter_column_drop_autoincrement",
  15945. tableName,
  15946. columnName,
  15947. schema: schema6,
  15948. newDataType: columnType,
  15949. columnDefault,
  15950. columnOnUpdate,
  15951. columnNotNull,
  15952. columnAutoIncrement,
  15953. columnPk
  15954. });
  15955. }
  15956. }
  15957. for (const column6 of columns) {
  15958. const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
  15959. const columnType = json2.tables[tableName].columns[columnName].type;
  15960. const columnDefault = json2.tables[tableName].columns[columnName].default;
  15961. const columnGenerated = json2.tables[tableName].columns[columnName].generated;
  15962. const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate;
  15963. const columnNotNull = json2.tables[tableName].columns[columnName].notNull;
  15964. const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement;
  15965. const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
  15966. const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
  15967. if (typeof column6.name !== "string") {
  15968. statements.push({
  15969. type: "alter_table_rename_column",
  15970. tableName,
  15971. oldColumnName: column6.name.old,
  15972. newColumnName: column6.name.new,
  15973. schema: schema6
  15974. });
  15975. }
  15976. if (column6.type?.type === "changed") {
  15977. statements.push({
  15978. type: "alter_table_alter_column_set_type",
  15979. tableName,
  15980. columnName,
  15981. newDataType: column6.type.new,
  15982. oldDataType: column6.type.old,
  15983. schema: schema6,
  15984. columnDefault,
  15985. columnOnUpdate,
  15986. columnNotNull,
  15987. columnAutoIncrement,
  15988. columnPk,
  15989. columnGenerated
  15990. });
  15991. }
  15992. if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
  15993. dropPkStatements.push({
  15994. ////
  15995. type: "alter_table_alter_column_drop_pk",
  15996. tableName,
  15997. columnName,
  15998. schema: schema6
  15999. });
  16000. }
  16001. if (column6.default?.type === "added") {
  16002. statements.push({
  16003. type: "alter_table_alter_column_set_default",
  16004. tableName,
  16005. columnName,
  16006. newDefaultValue: column6.default.value,
  16007. schema: schema6,
  16008. columnOnUpdate,
  16009. columnNotNull,
  16010. columnAutoIncrement,
  16011. newDataType: columnType,
  16012. columnPk
  16013. });
  16014. }
  16015. if (column6.default?.type === "changed") {
  16016. statements.push({
  16017. type: "alter_table_alter_column_set_default",
  16018. tableName,
  16019. columnName,
  16020. newDefaultValue: column6.default.new,
  16021. oldDefaultValue: column6.default.old,
  16022. schema: schema6,
  16023. columnOnUpdate,
  16024. columnNotNull,
  16025. columnAutoIncrement,
  16026. newDataType: columnType,
  16027. columnPk
  16028. });
  16029. }
  16030. if (column6.default?.type === "deleted") {
  16031. statements.push({
  16032. type: "alter_table_alter_column_drop_default",
  16033. tableName,
  16034. columnName,
  16035. schema: schema6,
  16036. columnDefault,
  16037. columnOnUpdate,
  16038. columnNotNull,
  16039. columnAutoIncrement,
  16040. newDataType: columnType,
  16041. columnPk
  16042. });
  16043. }
  16044. if (column6.notNull?.type === "added") {
  16045. statements.push({
  16046. type: "alter_table_alter_column_set_notnull",
  16047. tableName,
  16048. columnName,
  16049. schema: schema6,
  16050. newDataType: columnType,
  16051. columnDefault,
  16052. columnOnUpdate,
  16053. columnNotNull,
  16054. columnAutoIncrement,
  16055. columnPk
  16056. });
  16057. }
  16058. if (column6.notNull?.type === "changed") {
  16059. const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
  16060. statements.push({
  16061. type,
  16062. tableName,
  16063. columnName,
  16064. schema: schema6,
  16065. newDataType: columnType,
  16066. columnDefault,
  16067. columnOnUpdate,
  16068. columnNotNull,
  16069. columnAutoIncrement,
  16070. columnPk
  16071. });
  16072. }
  16073. if (column6.notNull?.type === "deleted") {
  16074. statements.push({
  16075. type: "alter_table_alter_column_drop_notnull",
  16076. tableName,
  16077. columnName,
  16078. schema: schema6,
  16079. newDataType: columnType,
  16080. columnDefault,
  16081. columnOnUpdate,
  16082. columnNotNull,
  16083. columnAutoIncrement,
  16084. columnPk
  16085. });
  16086. }
  16087. if (column6.generated?.type === "added") {
  16088. if (columnGenerated?.type === "virtual") {
  16089. warning(
  16090. `You are trying to add virtual generated constraint to ${source_default.blue(
  16091. columnName
  16092. )} column. As MySQL docs mention: "Nongenerated columns can be altered to stored but not virtual generated columns". We will drop an existing column and add it with a virtual generated statement. This means that the data previously stored in this column will be wiped, and new data will be generated on each read for this column
  16093. `
  16094. );
  16095. }
  16096. statements.push({
  16097. type: "alter_table_alter_column_set_generated",
  16098. tableName,
  16099. columnName,
  16100. schema: schema6,
  16101. newDataType: columnType,
  16102. columnDefault,
  16103. columnOnUpdate,
  16104. columnNotNull,
  16105. columnAutoIncrement,
  16106. columnPk,
  16107. columnGenerated
  16108. });
  16109. }
  16110. if (column6.generated?.type === "changed" && action !== "push") {
  16111. statements.push({
  16112. type: "alter_table_alter_column_alter_generated",
  16113. tableName,
  16114. columnName,
  16115. schema: schema6,
  16116. newDataType: columnType,
  16117. columnDefault,
  16118. columnOnUpdate,
  16119. columnNotNull,
  16120. columnAutoIncrement,
  16121. columnPk,
  16122. columnGenerated
  16123. });
  16124. }
  16125. if (column6.generated?.type === "deleted") {
  16126. if (columnGenerated?.type === "virtual") {
  16127. warning(
  16128. `You are trying to remove virtual generated constraint from ${source_default.blue(
  16129. columnName
  16130. )} column. As MySQL docs mention: "Stored but not virtual generated columns can be altered to nongenerated columns. The stored generated values become the values of the nongenerated column". We will drop an existing column and add it without a virtual generated statement. This means that this column will have no data after migration
  16131. `
  16132. );
  16133. }
  16134. statements.push({
  16135. type: "alter_table_alter_column_drop_generated",
  16136. tableName,
  16137. columnName,
  16138. schema: schema6,
  16139. newDataType: columnType,
  16140. columnDefault,
  16141. columnOnUpdate,
  16142. columnNotNull,
  16143. columnAutoIncrement,
  16144. columnPk,
  16145. columnGenerated,
  16146. oldColumn: json1.tables[tableName].columns[columnName]
  16147. });
  16148. }
  16149. if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
  16150. const wasAutoincrement = statements.filter(
  16151. (it) => it.type === "alter_table_alter_column_set_autoincrement"
  16152. );
  16153. if (wasAutoincrement.length === 0) {
  16154. setPkStatements.push({
  16155. type: "alter_table_alter_column_set_pk",
  16156. tableName,
  16157. schema: schema6,
  16158. columnName
  16159. });
  16160. }
  16161. }
  16162. if (column6.onUpdate?.type === "added") {
  16163. statements.push({
  16164. type: "alter_table_alter_column_set_on_update",
  16165. tableName,
  16166. columnName,
  16167. schema: schema6,
  16168. newDataType: columnType,
  16169. columnDefault,
  16170. columnOnUpdate,
  16171. columnNotNull,
  16172. columnAutoIncrement,
  16173. columnPk
  16174. });
  16175. }
  16176. if (column6.onUpdate?.type === "deleted") {
  16177. statements.push({
  16178. type: "alter_table_alter_column_drop_on_update",
  16179. tableName,
  16180. columnName,
  16181. schema: schema6,
  16182. newDataType: columnType,
  16183. columnDefault,
  16184. columnOnUpdate,
  16185. columnNotNull,
  16186. columnAutoIncrement,
  16187. columnPk
  16188. });
  16189. }
  16190. }
  16191. return [...dropPkStatements, ...setPkStatements, ...statements];
  16192. };
  16193. preparePgAlterColumns = (_tableName, schema6, columns, json2, json1, action) => {
  16194. const tableKey2 = `${schema6 || "public"}.${_tableName}`;
  16195. let statements = [];
  16196. let dropPkStatements = [];
  16197. let setPkStatements = [];
  16198. for (const column6 of columns) {
  16199. const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
  16200. const tableName = json2.tables[tableKey2].name;
  16201. const columnType = json2.tables[tableKey2].columns[columnName].type;
  16202. const columnDefault = json2.tables[tableKey2].columns[columnName].default;
  16203. const columnGenerated = json2.tables[tableKey2].columns[columnName].generated;
  16204. const columnOnUpdate = json2.tables[tableKey2].columns[columnName].onUpdate;
  16205. const columnNotNull = json2.tables[tableKey2].columns[columnName].notNull;
  16206. const columnAutoIncrement = json2.tables[tableKey2].columns[columnName].autoincrement;
  16207. const columnPk = json2.tables[tableKey2].columns[columnName].primaryKey;
  16208. const typeSchema = json2.tables[tableKey2].columns[columnName].typeSchema;
  16209. const json1ColumnTypeSchema = json1.tables[tableKey2].columns[columnName].typeSchema;
  16210. const compositePk = json2.tables[tableKey2].compositePrimaryKeys[`${tableName}_${columnName}`];
  16211. if (typeof column6.name !== "string") {
  16212. statements.push({
  16213. type: "alter_table_rename_column",
  16214. tableName,
  16215. oldColumnName: column6.name.old,
  16216. newColumnName: column6.name.new,
  16217. schema: schema6
  16218. });
  16219. }
  16220. if (column6.type?.type === "changed") {
  16221. const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
  16222. const parsedNewColumnType = column6.type.new.replace(arrayDefinitionRegex, "");
  16223. const parsedOldColumnType = column6.type.old.replace(arrayDefinitionRegex, "");
  16224. const isNewTypeIsEnum = json2.enums[`${typeSchema}.${parsedNewColumnType}`];
  16225. const isOldTypeIsEnum = json1.enums[`${json1ColumnTypeSchema}.${parsedOldColumnType}`];
  16226. statements.push({
  16227. type: "pg_alter_table_alter_column_set_type",
  16228. tableName,
  16229. columnName,
  16230. typeSchema,
  16231. newDataType: {
  16232. name: column6.type.new,
  16233. isEnum: isNewTypeIsEnum ? true : false
  16234. },
  16235. oldDataType: {
  16236. name: column6.type.old,
  16237. isEnum: isOldTypeIsEnum ? true : false
  16238. },
  16239. schema: schema6,
  16240. columnDefault,
  16241. columnOnUpdate,
  16242. columnNotNull,
  16243. columnAutoIncrement,
  16244. columnPk
  16245. });
  16246. }
  16247. if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
  16248. dropPkStatements.push({
  16249. ////
  16250. type: "alter_table_alter_column_drop_pk",
  16251. tableName,
  16252. columnName,
  16253. schema: schema6
  16254. });
  16255. }
  16256. if (column6.default?.type === "added") {
  16257. statements.push({
  16258. type: "alter_table_alter_column_set_default",
  16259. tableName,
  16260. columnName,
  16261. newDefaultValue: column6.default.value,
  16262. schema: schema6,
  16263. columnOnUpdate,
  16264. columnNotNull,
  16265. columnAutoIncrement,
  16266. newDataType: columnType,
  16267. columnPk
  16268. });
  16269. }
  16270. if (column6.default?.type === "changed") {
  16271. statements.push({
  16272. type: "alter_table_alter_column_set_default",
  16273. tableName,
  16274. columnName,
  16275. newDefaultValue: column6.default.new,
  16276. oldDefaultValue: column6.default.old,
  16277. schema: schema6,
  16278. columnOnUpdate,
  16279. columnNotNull,
  16280. columnAutoIncrement,
  16281. newDataType: columnType,
  16282. columnPk
  16283. });
  16284. }
  16285. if (column6.default?.type === "deleted") {
  16286. statements.push({
  16287. type: "alter_table_alter_column_drop_default",
  16288. tableName,
  16289. columnName,
  16290. schema: schema6,
  16291. columnDefault,
  16292. columnOnUpdate,
  16293. columnNotNull,
  16294. columnAutoIncrement,
  16295. newDataType: columnType,
  16296. columnPk
  16297. });
  16298. }
  16299. if (column6.notNull?.type === "added") {
  16300. statements.push({
  16301. type: "alter_table_alter_column_set_notnull",
  16302. tableName,
  16303. columnName,
  16304. schema: schema6,
  16305. newDataType: columnType,
  16306. columnDefault,
  16307. columnOnUpdate,
  16308. columnNotNull,
  16309. columnAutoIncrement,
  16310. columnPk
  16311. });
  16312. }
  16313. if (column6.notNull?.type === "changed") {
  16314. const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
  16315. statements.push({
  16316. type,
  16317. tableName,
  16318. columnName,
  16319. schema: schema6,
  16320. newDataType: columnType,
  16321. columnDefault,
  16322. columnOnUpdate,
  16323. columnNotNull,
  16324. columnAutoIncrement,
  16325. columnPk
  16326. });
  16327. }
  16328. if (column6.notNull?.type === "deleted") {
  16329. statements.push({
  16330. type: "alter_table_alter_column_drop_notnull",
  16331. tableName,
  16332. columnName,
  16333. schema: schema6,
  16334. newDataType: columnType,
  16335. columnDefault,
  16336. columnOnUpdate,
  16337. columnNotNull,
  16338. columnAutoIncrement,
  16339. columnPk
  16340. });
  16341. }
  16342. if (column6.identity?.type === "added") {
  16343. statements.push({
  16344. type: "alter_table_alter_column_set_identity",
  16345. tableName,
  16346. columnName,
  16347. schema: schema6,
  16348. identity: column6.identity.value
  16349. });
  16350. }
  16351. if (column6.identity?.type === "changed") {
  16352. statements.push({
  16353. type: "alter_table_alter_column_change_identity",
  16354. tableName,
  16355. columnName,
  16356. schema: schema6,
  16357. identity: column6.identity.new,
  16358. oldIdentity: column6.identity.old
  16359. });
  16360. }
  16361. if (column6.identity?.type === "deleted") {
  16362. statements.push({
  16363. type: "alter_table_alter_column_drop_identity",
  16364. tableName,
  16365. columnName,
  16366. schema: schema6
  16367. });
  16368. }
  16369. if (column6.generated?.type === "added") {
  16370. statements.push({
  16371. type: "alter_table_alter_column_set_generated",
  16372. tableName,
  16373. columnName,
  16374. schema: schema6,
  16375. newDataType: columnType,
  16376. columnDefault,
  16377. columnOnUpdate,
  16378. columnNotNull,
  16379. columnAutoIncrement,
  16380. columnPk,
  16381. columnGenerated
  16382. });
  16383. }
  16384. if (column6.generated?.type === "changed" && action !== "push") {
  16385. statements.push({
  16386. type: "alter_table_alter_column_alter_generated",
  16387. tableName,
  16388. columnName,
  16389. schema: schema6,
  16390. newDataType: columnType,
  16391. columnDefault,
  16392. columnOnUpdate,
  16393. columnNotNull,
  16394. columnAutoIncrement,
  16395. columnPk,
  16396. columnGenerated
  16397. });
  16398. }
  16399. if (column6.generated?.type === "deleted") {
  16400. statements.push({
  16401. type: "alter_table_alter_column_drop_generated",
  16402. tableName,
  16403. columnName,
  16404. schema: schema6,
  16405. newDataType: columnType,
  16406. columnDefault,
  16407. columnOnUpdate,
  16408. columnNotNull,
  16409. columnAutoIncrement,
  16410. columnPk,
  16411. columnGenerated
  16412. });
  16413. }
  16414. if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
  16415. const wasAutoincrement = statements.filter(
  16416. (it) => it.type === "alter_table_alter_column_set_autoincrement"
  16417. );
  16418. if (wasAutoincrement.length === 0) {
  16419. setPkStatements.push({
  16420. type: "alter_table_alter_column_set_pk",
  16421. tableName,
  16422. schema: schema6,
  16423. columnName
  16424. });
  16425. }
  16426. }
  16427. if (column6.onUpdate?.type === "added") {
  16428. statements.push({
  16429. type: "alter_table_alter_column_set_on_update",
  16430. tableName,
  16431. columnName,
  16432. schema: schema6,
  16433. newDataType: columnType,
  16434. columnDefault,
  16435. columnOnUpdate,
  16436. columnNotNull,
  16437. columnAutoIncrement,
  16438. columnPk
  16439. });
  16440. }
  16441. if (column6.onUpdate?.type === "deleted") {
  16442. statements.push({
  16443. type: "alter_table_alter_column_drop_on_update",
  16444. tableName,
  16445. columnName,
  16446. schema: schema6,
  16447. newDataType: columnType,
  16448. columnDefault,
  16449. columnOnUpdate,
  16450. columnNotNull,
  16451. columnAutoIncrement,
  16452. columnPk
  16453. });
  16454. }
  16455. }
  16456. return [...dropPkStatements, ...setPkStatements, ...statements];
  16457. };
  16458. prepareSqliteAlterColumns = (tableName, schema6, columns, json2) => {
  16459. let statements = [];
  16460. let dropPkStatements = [];
  16461. let setPkStatements = [];
  16462. for (const column6 of columns) {
  16463. const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
  16464. const columnType = json2.tables[tableName].columns[columnName].type;
  16465. const columnDefault = json2.tables[tableName].columns[columnName].default;
  16466. const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate;
  16467. const columnNotNull = json2.tables[tableName].columns[columnName].notNull;
  16468. const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement;
  16469. const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
  16470. const columnGenerated = json2.tables[tableName].columns[columnName].generated;
  16471. const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
  16472. if (column6.autoincrement?.type === "added") {
  16473. statements.push({
  16474. type: "alter_table_alter_column_set_autoincrement",
  16475. tableName,
  16476. columnName,
  16477. schema: schema6,
  16478. newDataType: columnType,
  16479. columnDefault,
  16480. columnOnUpdate,
  16481. columnNotNull,
  16482. columnAutoIncrement,
  16483. columnPk
  16484. });
  16485. }
  16486. if (column6.autoincrement?.type === "changed") {
  16487. const type = column6.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
  16488. statements.push({
  16489. type,
  16490. tableName,
  16491. columnName,
  16492. schema: schema6,
  16493. newDataType: columnType,
  16494. columnDefault,
  16495. columnOnUpdate,
  16496. columnNotNull,
  16497. columnAutoIncrement,
  16498. columnPk
  16499. });
  16500. }
  16501. if (column6.autoincrement?.type === "deleted") {
  16502. statements.push({
  16503. type: "alter_table_alter_column_drop_autoincrement",
  16504. tableName,
  16505. columnName,
  16506. schema: schema6,
  16507. newDataType: columnType,
  16508. columnDefault,
  16509. columnOnUpdate,
  16510. columnNotNull,
  16511. columnAutoIncrement,
  16512. columnPk
  16513. });
  16514. }
  16515. if (typeof column6.name !== "string") {
  16516. statements.push({
  16517. type: "alter_table_rename_column",
  16518. tableName,
  16519. oldColumnName: column6.name.old,
  16520. newColumnName: column6.name.new,
  16521. schema: schema6
  16522. });
  16523. }
  16524. if (column6.type?.type === "changed") {
  16525. statements.push({
  16526. type: "alter_table_alter_column_set_type",
  16527. tableName,
  16528. columnName,
  16529. newDataType: column6.type.new,
  16530. oldDataType: column6.type.old,
  16531. schema: schema6,
  16532. columnDefault,
  16533. columnOnUpdate,
  16534. columnNotNull,
  16535. columnAutoIncrement,
  16536. columnPk
  16537. });
  16538. }
  16539. if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
  16540. dropPkStatements.push({
  16541. ////
  16542. type: "alter_table_alter_column_drop_pk",
  16543. tableName,
  16544. columnName,
  16545. schema: schema6
  16546. });
  16547. }
  16548. if (column6.default?.type === "added") {
  16549. statements.push({
  16550. type: "alter_table_alter_column_set_default",
  16551. tableName,
  16552. columnName,
  16553. newDefaultValue: column6.default.value,
  16554. schema: schema6,
  16555. columnOnUpdate,
  16556. columnNotNull,
  16557. columnAutoIncrement,
  16558. newDataType: columnType,
  16559. columnPk
  16560. });
  16561. }
  16562. if (column6.default?.type === "changed") {
  16563. statements.push({
  16564. type: "alter_table_alter_column_set_default",
  16565. tableName,
  16566. columnName,
  16567. newDefaultValue: column6.default.new,
  16568. oldDefaultValue: column6.default.old,
  16569. schema: schema6,
  16570. columnOnUpdate,
  16571. columnNotNull,
  16572. columnAutoIncrement,
  16573. newDataType: columnType,
  16574. columnPk
  16575. });
  16576. }
  16577. if (column6.default?.type === "deleted") {
  16578. statements.push({
  16579. type: "alter_table_alter_column_drop_default",
  16580. tableName,
  16581. columnName,
  16582. schema: schema6,
  16583. columnDefault,
  16584. columnOnUpdate,
  16585. columnNotNull,
  16586. columnAutoIncrement,
  16587. newDataType: columnType,
  16588. columnPk
  16589. });
  16590. }
  16591. if (column6.notNull?.type === "added") {
  16592. statements.push({
  16593. type: "alter_table_alter_column_set_notnull",
  16594. tableName,
  16595. columnName,
  16596. schema: schema6,
  16597. newDataType: columnType,
  16598. columnDefault,
  16599. columnOnUpdate,
  16600. columnNotNull,
  16601. columnAutoIncrement,
  16602. columnPk
  16603. });
  16604. }
  16605. if (column6.notNull?.type === "changed") {
  16606. const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
  16607. statements.push({
  16608. type,
  16609. tableName,
  16610. columnName,
  16611. schema: schema6,
  16612. newDataType: columnType,
  16613. columnDefault,
  16614. columnOnUpdate,
  16615. columnNotNull,
  16616. columnAutoIncrement,
  16617. columnPk
  16618. });
  16619. }
  16620. if (column6.notNull?.type === "deleted") {
  16621. statements.push({
  16622. type: "alter_table_alter_column_drop_notnull",
  16623. tableName,
  16624. columnName,
  16625. schema: schema6,
  16626. newDataType: columnType,
  16627. columnDefault,
  16628. columnOnUpdate,
  16629. columnNotNull,
  16630. columnAutoIncrement,
  16631. columnPk
  16632. });
  16633. }
  16634. if (column6.generated?.type === "added") {
  16635. if (columnGenerated?.type === "virtual") {
  16636. statements.push({
  16637. type: "alter_table_alter_column_set_generated",
  16638. tableName,
  16639. columnName,
  16640. schema: schema6,
  16641. newDataType: columnType,
  16642. columnDefault,
  16643. columnOnUpdate,
  16644. columnNotNull,
  16645. columnAutoIncrement,
  16646. columnPk,
  16647. columnGenerated
  16648. });
  16649. } else {
  16650. warning(
  16651. `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
  16652. );
  16653. }
  16654. }
  16655. if (column6.generated?.type === "changed") {
  16656. if (columnGenerated?.type === "virtual") {
  16657. statements.push({
  16658. type: "alter_table_alter_column_alter_generated",
  16659. tableName,
  16660. columnName,
  16661. schema: schema6,
  16662. newDataType: columnType,
  16663. columnDefault,
  16664. columnOnUpdate,
  16665. columnNotNull,
  16666. columnAutoIncrement,
  16667. columnPk,
  16668. columnGenerated
  16669. });
  16670. } else {
  16671. warning(
  16672. `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
  16673. );
  16674. }
  16675. }
  16676. if (column6.generated?.type === "deleted") {
  16677. statements.push({
  16678. type: "alter_table_alter_column_drop_generated",
  16679. tableName,
  16680. columnName,
  16681. schema: schema6,
  16682. newDataType: columnType,
  16683. columnDefault,
  16684. columnOnUpdate,
  16685. columnNotNull,
  16686. columnAutoIncrement,
  16687. columnPk,
  16688. columnGenerated
  16689. });
  16690. }
  16691. if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
  16692. const wasAutoincrement = statements.filter(
  16693. (it) => it.type === "alter_table_alter_column_set_autoincrement"
  16694. );
  16695. if (wasAutoincrement.length === 0) {
  16696. setPkStatements.push({
  16697. type: "alter_table_alter_column_set_pk",
  16698. tableName,
  16699. schema: schema6,
  16700. columnName
  16701. });
  16702. }
  16703. }
  16704. if (column6.onUpdate?.type === "added") {
  16705. statements.push({
  16706. type: "alter_table_alter_column_set_on_update",
  16707. tableName,
  16708. columnName,
  16709. schema: schema6,
  16710. newDataType: columnType,
  16711. columnDefault,
  16712. columnOnUpdate,
  16713. columnNotNull,
  16714. columnAutoIncrement,
  16715. columnPk
  16716. });
  16717. }
  16718. if (column6.onUpdate?.type === "deleted") {
  16719. statements.push({
  16720. type: "alter_table_alter_column_drop_on_update",
  16721. tableName,
  16722. columnName,
  16723. schema: schema6,
  16724. newDataType: columnType,
  16725. columnDefault,
  16726. columnOnUpdate,
  16727. columnNotNull,
  16728. columnAutoIncrement,
  16729. columnPk
  16730. });
  16731. }
  16732. }
  16733. return [...dropPkStatements, ...setPkStatements, ...statements];
  16734. };
  16735. prepareRenamePolicyJsons = (tableName, schema6, renames) => {
  16736. return renames.map((it) => {
  16737. return {
  16738. type: "rename_policy",
  16739. tableName,
  16740. oldName: it.from.name,
  16741. newName: it.to.name,
  16742. schema: schema6
  16743. };
  16744. });
  16745. };
  16746. prepareRenameIndPolicyJsons = (renames) => {
  16747. return renames.map((it) => {
  16748. return {
  16749. type: "rename_ind_policy",
  16750. tableKey: it.from.on,
  16751. oldName: it.from.name,
  16752. newName: it.to.name
  16753. };
  16754. });
  16755. };
  16756. prepareCreatePolicyJsons = (tableName, schema6, policies) => {
  16757. return policies.map((it) => {
  16758. return {
  16759. type: "create_policy",
  16760. tableName,
  16761. data: it,
  16762. schema: schema6
  16763. };
  16764. });
  16765. };
  16766. prepareCreateIndPolicyJsons = (policies) => {
  16767. return policies.map((it) => {
  16768. return {
  16769. type: "create_ind_policy",
  16770. tableName: it.on,
  16771. data: it
  16772. };
  16773. });
  16774. };
  16775. prepareDropPolicyJsons = (tableName, schema6, policies) => {
  16776. return policies.map((it) => {
  16777. return {
  16778. type: "drop_policy",
  16779. tableName,
  16780. data: it,
  16781. schema: schema6
  16782. };
  16783. });
  16784. };
  16785. prepareDropIndPolicyJsons = (policies) => {
  16786. return policies.map((it) => {
  16787. return {
  16788. type: "drop_ind_policy",
  16789. tableName: it.on,
  16790. data: it
  16791. };
  16792. });
  16793. };
  16794. prepareAlterPolicyJson = (tableName, schema6, oldPolicy, newPolicy) => {
  16795. return {
  16796. type: "alter_policy",
  16797. tableName,
  16798. oldData: oldPolicy,
  16799. newData: newPolicy,
  16800. schema: schema6
  16801. };
  16802. };
  16803. prepareAlterIndPolicyJson = (oldPolicy, newPolicy) => {
  16804. return {
  16805. type: "alter_ind_policy",
  16806. oldData: oldPolicy,
  16807. newData: newPolicy
  16808. };
  16809. };
  16810. preparePgCreateIndexesJson = (tableName, schema6, indexes, fullSchema, action) => {
  16811. if (action === "push") {
  16812. return Object.values(indexes).map((indexData) => {
  16813. const unsquashedIndex = PgSquasher.unsquashIdxPush(indexData);
  16814. const data = fullSchema.tables[`${schema6 === "" ? "public" : schema6}.${tableName}`].indexes[unsquashedIndex.name];
  16815. return {
  16816. type: "create_index_pg",
  16817. tableName,
  16818. data,
  16819. schema: schema6
  16820. };
  16821. });
  16822. }
  16823. return Object.values(indexes).map((indexData) => {
  16824. return {
  16825. type: "create_index_pg",
  16826. tableName,
  16827. data: PgSquasher.unsquashIdx(indexData),
  16828. schema: schema6
  16829. };
  16830. });
  16831. };
  16832. prepareCreateIndexesJson = (tableName, schema6, indexes, internal) => {
  16833. return Object.values(indexes).map((indexData) => {
  16834. return {
  16835. type: "create_index",
  16836. tableName,
  16837. data: indexData,
  16838. schema: schema6,
  16839. internal
  16840. };
  16841. });
  16842. };
  16843. prepareCreateReferencesJson = (tableName, schema6, foreignKeys) => {
  16844. return Object.values(foreignKeys).map((fkData) => {
  16845. return {
  16846. type: "create_reference",
  16847. tableName,
  16848. data: fkData,
  16849. schema: schema6
  16850. };
  16851. });
  16852. };
  16853. prepareLibSQLCreateReferencesJson = (tableName, schema6, foreignKeys, json2, action) => {
  16854. return Object.values(foreignKeys).map((fkData) => {
  16855. const { columnsFrom, tableFrom, columnsTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
  16856. let isMulticolumn = false;
  16857. if (columnsFrom.length > 1 || columnsTo.length > 1) {
  16858. isMulticolumn = true;
  16859. return {
  16860. type: "create_reference",
  16861. tableName,
  16862. data: fkData,
  16863. schema: schema6,
  16864. isMulticolumn
  16865. };
  16866. }
  16867. const columnFrom = columnsFrom[0];
  16868. const {
  16869. notNull: columnNotNull,
  16870. default: columnDefault,
  16871. type: columnType
  16872. } = json2.tables[tableFrom].columns[columnFrom];
  16873. return {
  16874. type: "create_reference",
  16875. tableName,
  16876. data: fkData,
  16877. schema: schema6,
  16878. columnNotNull,
  16879. columnDefault,
  16880. columnType
  16881. };
  16882. });
  16883. };
  16884. prepareDropReferencesJson = (tableName, schema6, foreignKeys) => {
  16885. return Object.values(foreignKeys).map((fkData) => {
  16886. return {
  16887. type: "delete_reference",
  16888. tableName,
  16889. data: fkData,
  16890. schema: schema6
  16891. };
  16892. });
  16893. };
  16894. prepareLibSQLDropReferencesJson = (tableName, schema6, foreignKeys, json2, meta, action) => {
  16895. const statements = Object.values(foreignKeys).map((fkData) => {
  16896. const { columnsFrom, tableFrom, columnsTo, name, tableTo, onDelete, onUpdate } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
  16897. const keys = Object.keys(json2.tables[tableName].columns);
  16898. const filtered = columnsFrom.filter((it) => keys.includes(it));
  16899. const fullDrop = filtered.length === 0;
  16900. if (fullDrop) return;
  16901. let isMulticolumn = false;
  16902. if (columnsFrom.length > 1 || columnsTo.length > 1) {
  16903. isMulticolumn = true;
  16904. return {
  16905. type: "delete_reference",
  16906. tableName,
  16907. data: fkData,
  16908. schema: schema6,
  16909. isMulticolumn
  16910. };
  16911. }
  16912. const columnFrom = columnsFrom[0];
  16913. const newTableName = getNewTableName(tableFrom, meta);
  16914. const {
  16915. notNull: columnNotNull,
  16916. default: columnDefault,
  16917. type: columnType
  16918. } = json2.tables[newTableName].columns[columnFrom];
  16919. const fkToSquash = {
  16920. columnsFrom,
  16921. columnsTo,
  16922. name,
  16923. tableFrom: newTableName,
  16924. tableTo,
  16925. onDelete,
  16926. onUpdate
  16927. };
  16928. const foreignKey = action === "push" ? SQLiteSquasher.squashPushFK(fkToSquash) : SQLiteSquasher.squashFK(fkToSquash);
  16929. return {
  16930. type: "delete_reference",
  16931. tableName,
  16932. data: foreignKey,
  16933. schema: schema6,
  16934. columnNotNull,
  16935. columnDefault,
  16936. columnType
  16937. };
  16938. });
  16939. return statements.filter((it) => it);
  16940. };
  16941. prepareAlterReferencesJson = (tableName, schema6, foreignKeys) => {
  16942. const stmts = [];
  16943. Object.values(foreignKeys).map((val2) => {
  16944. stmts.push({
  16945. type: "delete_reference",
  16946. tableName,
  16947. schema: schema6,
  16948. data: val2.__old
  16949. });
  16950. stmts.push({
  16951. type: "create_reference",
  16952. tableName,
  16953. schema: schema6,
  16954. data: val2.__new
  16955. });
  16956. });
  16957. return stmts;
  16958. };
  16959. prepareDropIndexesJson = (tableName, schema6, indexes) => {
  16960. return Object.values(indexes).map((indexData) => {
  16961. return {
  16962. type: "drop_index",
  16963. tableName,
  16964. data: indexData,
  16965. schema: schema6
  16966. };
  16967. });
  16968. };
  16969. prepareAddCompositePrimaryKeySqlite = (tableName, pks) => {
  16970. return Object.values(pks).map((it) => {
  16971. return {
  16972. type: "create_composite_pk",
  16973. tableName,
  16974. data: it
  16975. };
  16976. });
  16977. };
  16978. prepareDeleteCompositePrimaryKeySqlite = (tableName, pks) => {
  16979. return Object.values(pks).map((it) => {
  16980. return {
  16981. type: "delete_composite_pk",
  16982. tableName,
  16983. data: it
  16984. };
  16985. });
  16986. };
  16987. prepareAlterCompositePrimaryKeySqlite = (tableName, pks) => {
  16988. return Object.values(pks).map((it) => {
  16989. return {
  16990. type: "alter_composite_pk",
  16991. tableName,
  16992. old: it.__old,
  16993. new: it.__new
  16994. };
  16995. });
  16996. };
  16997. prepareAddCompositePrimaryKeyPg = (tableName, schema6, pks, json2) => {
  16998. return Object.values(pks).map((it) => {
  16999. const unsquashed = PgSquasher.unsquashPK(it);
  17000. return {
  17001. type: "create_composite_pk",
  17002. tableName,
  17003. data: it,
  17004. schema: schema6,
  17005. constraintName: PgSquasher.unsquashPK(it).name
  17006. };
  17007. });
  17008. };
  17009. prepareDeleteCompositePrimaryKeyPg = (tableName, schema6, pks, json1) => {
  17010. return Object.values(pks).map((it) => {
  17011. return {
  17012. type: "delete_composite_pk",
  17013. tableName,
  17014. data: it,
  17015. schema: schema6,
  17016. constraintName: PgSquasher.unsquashPK(it).name
  17017. };
  17018. });
  17019. };
  17020. prepareAlterCompositePrimaryKeyPg = (tableName, schema6, pks, json1, json2) => {
  17021. return Object.values(pks).map((it) => {
  17022. return {
  17023. type: "alter_composite_pk",
  17024. tableName,
  17025. old: it.__old,
  17026. new: it.__new,
  17027. schema: schema6,
  17028. oldConstraintName: PgSquasher.unsquashPK(it.__old).name,
  17029. newConstraintName: PgSquasher.unsquashPK(it.__new).name
  17030. };
  17031. });
  17032. };
  17033. prepareAddUniqueConstraintPg = (tableName, schema6, unqs) => {
  17034. return Object.values(unqs).map((it) => {
  17035. return {
  17036. type: "create_unique_constraint",
  17037. tableName,
  17038. data: it,
  17039. schema: schema6
  17040. };
  17041. });
  17042. };
  17043. prepareDeleteUniqueConstraintPg = (tableName, schema6, unqs) => {
  17044. return Object.values(unqs).map((it) => {
  17045. return {
  17046. type: "delete_unique_constraint",
  17047. tableName,
  17048. data: it,
  17049. schema: schema6
  17050. };
  17051. });
  17052. };
  17053. prepareAddCheckConstraint = (tableName, schema6, check) => {
  17054. return Object.values(check).map((it) => {
  17055. return {
  17056. type: "create_check_constraint",
  17057. tableName,
  17058. data: it,
  17059. schema: schema6
  17060. };
  17061. });
  17062. };
  17063. prepareDeleteCheckConstraint = (tableName, schema6, check) => {
  17064. return Object.values(check).map((it) => {
  17065. return {
  17066. type: "delete_check_constraint",
  17067. tableName,
  17068. constraintName: PgSquasher.unsquashCheck(it).name,
  17069. schema: schema6
  17070. };
  17071. });
  17072. };
  17073. prepareAddCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
  17074. const res = [];
  17075. for (const it of Object.values(pks)) {
  17076. const unsquashed = MySqlSquasher.unsquashPK(it);
  17077. if (unsquashed.columns.length === 1 && json1.tables[tableName]?.columns[unsquashed.columns[0]]?.primaryKey) {
  17078. continue;
  17079. }
  17080. res.push({
  17081. type: "create_composite_pk",
  17082. tableName,
  17083. data: it,
  17084. constraintName: unsquashed.name
  17085. });
  17086. }
  17087. return res;
  17088. };
  17089. prepareDeleteCompositePrimaryKeyMySql = (tableName, pks, json1) => {
  17090. return Object.values(pks).map((it) => {
  17091. const unsquashed = MySqlSquasher.unsquashPK(it);
  17092. return {
  17093. type: "delete_composite_pk",
  17094. tableName,
  17095. data: it
  17096. };
  17097. });
  17098. };
  17099. prepareAlterCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
  17100. return Object.values(pks).map((it) => {
  17101. return {
  17102. type: "alter_composite_pk",
  17103. tableName,
  17104. old: it.__old,
  17105. new: it.__new,
  17106. oldConstraintName: json1.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__old).name].name,
  17107. newConstraintName: json2.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__new).name].name
  17108. };
  17109. });
  17110. };
  17111. preparePgCreateViewJson = (name, schema6, definition, materialized, withNoData = false, withOption, using, tablespace) => {
  17112. return {
  17113. type: "create_view",
  17114. name,
  17115. schema: schema6,
  17116. definition,
  17117. with: withOption,
  17118. materialized,
  17119. withNoData,
  17120. using,
  17121. tablespace
  17122. };
  17123. };
  17124. prepareMySqlCreateViewJson = (name, definition, meta, replace = false) => {
  17125. const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
  17126. return {
  17127. type: "mysql_create_view",
  17128. name,
  17129. definition,
  17130. algorithm,
  17131. sqlSecurity,
  17132. withCheckOption,
  17133. replace
  17134. };
  17135. };
  17136. prepareSqliteCreateViewJson = (name, definition) => {
  17137. return {
  17138. type: "sqlite_create_view",
  17139. name,
  17140. definition
  17141. };
  17142. };
  17143. prepareDropViewJson = (name, schema6, materialized) => {
  17144. const resObject = { name, type: "drop_view" };
  17145. if (schema6) resObject["schema"] = schema6;
  17146. if (materialized) resObject["materialized"] = materialized;
  17147. return resObject;
  17148. };
  17149. prepareRenameViewJson = (to, from, schema6, materialized) => {
  17150. const resObject = {
  17151. type: "rename_view",
  17152. nameTo: to,
  17153. nameFrom: from
  17154. };
  17155. if (schema6) resObject["schema"] = schema6;
  17156. if (materialized) resObject["materialized"] = materialized;
  17157. return resObject;
  17158. };
  17159. preparePgAlterViewAlterSchemaJson = (to, from, name, materialized) => {
  17160. const returnObject = {
  17161. type: "alter_view_alter_schema",
  17162. fromSchema: from,
  17163. toSchema: to,
  17164. name
  17165. };
  17166. if (materialized) returnObject["materialized"] = materialized;
  17167. return returnObject;
  17168. };
  17169. preparePgAlterViewAddWithOptionJson = (name, schema6, materialized, withOption) => {
  17170. return {
  17171. type: "alter_view_add_with_option",
  17172. name,
  17173. schema: schema6,
  17174. materialized,
  17175. with: withOption
  17176. };
  17177. };
  17178. preparePgAlterViewDropWithOptionJson = (name, schema6, materialized, withOption) => {
  17179. return {
  17180. type: "alter_view_drop_with_option",
  17181. name,
  17182. schema: schema6,
  17183. materialized,
  17184. with: withOption
  17185. };
  17186. };
  17187. preparePgAlterViewAlterTablespaceJson = (name, schema6, materialized, to) => {
  17188. return {
  17189. type: "alter_view_alter_tablespace",
  17190. name,
  17191. schema: schema6,
  17192. materialized,
  17193. toTablespace: to
  17194. };
  17195. };
  17196. preparePgAlterViewAlterUsingJson = (name, schema6, materialized, to) => {
  17197. return {
  17198. type: "alter_view_alter_using",
  17199. name,
  17200. schema: schema6,
  17201. materialized,
  17202. toUsing: to
  17203. };
  17204. };
  17205. prepareMySqlAlterView = (view5) => {
  17206. return { type: "alter_mysql_view", ...view5 };
  17207. };
  17208. }
  17209. });
  17210. // src/statementCombiner.ts
  17211. var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements, prepareSingleStoreRecreateTable, singleStoreCombineStatements;
  17212. var init_statementCombiner = __esm({
  17213. "src/statementCombiner.ts"() {
  17214. "use strict";
  17215. init_jsonStatements();
  17216. init_sqliteSchema();
  17217. prepareLibSQLRecreateTable = (table6, action) => {
  17218. const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6;
  17219. const composites = Object.values(table6.compositePrimaryKeys).map(
  17220. (it) => SQLiteSquasher.unsquashPK(it)
  17221. );
  17222. const references2 = Object.values(table6.foreignKeys);
  17223. const fks = references2.map(
  17224. (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
  17225. );
  17226. const statements = [
  17227. {
  17228. type: "recreate_table",
  17229. tableName: name,
  17230. columns: Object.values(columns),
  17231. compositePKs: composites,
  17232. referenceData: fks,
  17233. uniqueConstraints: Object.values(uniqueConstraints),
  17234. checkConstraints: Object.values(checkConstraints)
  17235. }
  17236. ];
  17237. if (Object.keys(indexes).length) {
  17238. statements.push(...prepareCreateIndexesJson(name, "", indexes));
  17239. }
  17240. return statements;
  17241. };
  17242. prepareSQLiteRecreateTable = (table6, action) => {
  17243. const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6;
  17244. const composites = Object.values(table6.compositePrimaryKeys).map(
  17245. (it) => SQLiteSquasher.unsquashPK(it)
  17246. );
  17247. const references2 = Object.values(table6.foreignKeys);
  17248. const fks = references2.map(
  17249. (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
  17250. );
  17251. const statements = [
  17252. {
  17253. type: "recreate_table",
  17254. tableName: name,
  17255. columns: Object.values(columns),
  17256. compositePKs: composites,
  17257. referenceData: fks,
  17258. uniqueConstraints: Object.values(uniqueConstraints),
  17259. checkConstraints: Object.values(checkConstraints)
  17260. }
  17261. ];
  17262. if (Object.keys(indexes).length) {
  17263. statements.push(...prepareCreateIndexesJson(name, "", indexes));
  17264. }
  17265. return statements;
  17266. };
  17267. libSQLCombineStatements = (statements, json2, action) => {
  17268. const newStatements = {};
  17269. for (const statement of statements) {
  17270. if (statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
  17271. const tableName2 = statement.tableName;
  17272. const statementsForTable2 = newStatements[tableName2];
  17273. if (!statementsForTable2) {
  17274. newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17275. continue;
  17276. }
  17277. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17278. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17279. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17280. if (wasRename) {
  17281. newStatements[tableName2].push(...preparedStatements);
  17282. } else {
  17283. newStatements[tableName2] = preparedStatements;
  17284. }
  17285. continue;
  17286. }
  17287. continue;
  17288. }
  17289. if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") {
  17290. const { tableName: tableName2, columnName, columnPk } = statement;
  17291. const columnIsPartOfForeignKey = Object.values(
  17292. json2.tables[tableName2].foreignKeys
  17293. ).some((it) => {
  17294. const unsquashFk = action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it);
  17295. return unsquashFk.columnsFrom.includes(columnName);
  17296. });
  17297. const statementsForTable2 = newStatements[tableName2];
  17298. if (!statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
  17299. newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17300. continue;
  17301. }
  17302. if (statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
  17303. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17304. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17305. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17306. if (wasRename) {
  17307. newStatements[tableName2].push(...preparedStatements);
  17308. } else {
  17309. newStatements[tableName2] = preparedStatements;
  17310. }
  17311. }
  17312. continue;
  17313. }
  17314. if (statementsForTable2 && !(columnIsPartOfForeignKey || columnPk)) {
  17315. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17316. newStatements[tableName2].push(statement);
  17317. }
  17318. continue;
  17319. }
  17320. newStatements[tableName2] = [statement];
  17321. continue;
  17322. }
  17323. if (statement.type === "create_reference") {
  17324. const tableName2 = statement.tableName;
  17325. const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
  17326. const statementsForTable2 = newStatements[tableName2];
  17327. if (!statementsForTable2) {
  17328. newStatements[tableName2] = statement.isMulticolumn ? prepareLibSQLRecreateTable(json2.tables[tableName2], action) : [statement];
  17329. continue;
  17330. }
  17331. if (!statement.isMulticolumn && statementsForTable2.some(
  17332. (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
  17333. )) {
  17334. continue;
  17335. }
  17336. if (statement.isMulticolumn) {
  17337. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17338. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17339. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17340. if (wasRename) {
  17341. newStatements[tableName2].push(...preparedStatements);
  17342. } else {
  17343. newStatements[tableName2] = preparedStatements;
  17344. }
  17345. continue;
  17346. }
  17347. continue;
  17348. }
  17349. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17350. newStatements[tableName2].push(statement);
  17351. }
  17352. continue;
  17353. }
  17354. if (statement.type === "delete_reference") {
  17355. const tableName2 = statement.tableName;
  17356. const statementsForTable2 = newStatements[tableName2];
  17357. if (!statementsForTable2) {
  17358. newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17359. continue;
  17360. }
  17361. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17362. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17363. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17364. if (wasRename) {
  17365. newStatements[tableName2].push(...preparedStatements);
  17366. } else {
  17367. newStatements[tableName2] = preparedStatements;
  17368. }
  17369. continue;
  17370. }
  17371. continue;
  17372. }
  17373. if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
  17374. const tableName2 = statement.tableName;
  17375. const statementsForTable2 = newStatements[tableName2];
  17376. if (!statementsForTable2) {
  17377. newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17378. continue;
  17379. }
  17380. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17381. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17382. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  17383. if (wasRename) {
  17384. newStatements[tableName2].push(...preparedStatements);
  17385. } else {
  17386. newStatements[tableName2] = preparedStatements;
  17387. }
  17388. continue;
  17389. }
  17390. continue;
  17391. }
  17392. const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
  17393. const statementsForTable = newStatements[tableName];
  17394. if (!statementsForTable) {
  17395. newStatements[tableName] = [statement];
  17396. continue;
  17397. }
  17398. if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
  17399. newStatements[tableName].push(statement);
  17400. }
  17401. }
  17402. const combinedStatements = Object.values(newStatements).flat();
  17403. const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
  17404. const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
  17405. const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
  17406. return [...renamedTables, ...renamedColumns, ...rest];
  17407. };
  17408. sqliteCombineStatements = (statements, json2, action) => {
  17409. const newStatements = {};
  17410. for (const statement of statements) {
  17411. if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "delete_reference" || statement.type === "alter_reference" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
  17412. const tableName2 = statement.tableName;
  17413. const statementsForTable2 = newStatements[tableName2];
  17414. if (!statementsForTable2) {
  17415. newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  17416. continue;
  17417. }
  17418. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17419. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17420. const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  17421. if (wasRename) {
  17422. newStatements[tableName2].push(...preparedStatements);
  17423. } else {
  17424. newStatements[tableName2] = preparedStatements;
  17425. }
  17426. continue;
  17427. }
  17428. continue;
  17429. }
  17430. if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
  17431. const tableName2 = statement.tableName;
  17432. const statementsForTable2 = newStatements[tableName2];
  17433. if (!statementsForTable2) {
  17434. newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  17435. continue;
  17436. }
  17437. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17438. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17439. const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  17440. if (wasRename) {
  17441. newStatements[tableName2].push(...preparedStatements);
  17442. } else {
  17443. newStatements[tableName2] = preparedStatements;
  17444. }
  17445. continue;
  17446. }
  17447. continue;
  17448. }
  17449. if (statement.type === "create_reference") {
  17450. const tableName2 = statement.tableName;
  17451. const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
  17452. const statementsForTable2 = newStatements[tableName2];
  17453. if (!statementsForTable2) {
  17454. newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  17455. continue;
  17456. }
  17457. if (data.columnsFrom.length === 1 && statementsForTable2.some(
  17458. (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
  17459. )) {
  17460. continue;
  17461. }
  17462. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17463. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17464. const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  17465. if (wasRename) {
  17466. newStatements[tableName2].push(...preparedStatements);
  17467. } else {
  17468. newStatements[tableName2] = preparedStatements;
  17469. }
  17470. continue;
  17471. }
  17472. continue;
  17473. }
  17474. const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
  17475. const statementsForTable = newStatements[tableName];
  17476. if (!statementsForTable) {
  17477. newStatements[tableName] = [statement];
  17478. continue;
  17479. }
  17480. if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
  17481. newStatements[tableName].push(statement);
  17482. }
  17483. }
  17484. const combinedStatements = Object.values(newStatements).flat();
  17485. const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
  17486. const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
  17487. const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
  17488. return [...renamedTables, ...renamedColumns, ...rest];
  17489. };
  17490. prepareSingleStoreRecreateTable = (table6) => {
  17491. const { name, columns, uniqueConstraints, indexes, compositePrimaryKeys } = table6;
  17492. const composites = Object.values(compositePrimaryKeys);
  17493. const statements = [
  17494. {
  17495. type: "singlestore_recreate_table",
  17496. tableName: name,
  17497. columns: Object.values(columns),
  17498. compositePKs: composites,
  17499. uniqueConstraints: Object.values(uniqueConstraints)
  17500. }
  17501. ];
  17502. if (Object.keys(indexes).length) {
  17503. statements.push(...prepareCreateIndexesJson(name, "", indexes));
  17504. }
  17505. return statements;
  17506. };
  17507. singleStoreCombineStatements = (statements, json2) => {
  17508. const newStatements = {};
  17509. for (const statement of statements) {
  17510. if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk") {
  17511. const tableName2 = statement.tableName;
  17512. const statementsForTable2 = newStatements[tableName2];
  17513. if (!statementsForTable2) {
  17514. newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  17515. continue;
  17516. }
  17517. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17518. const wasRename = statementsForTable2.some(
  17519. ({ type }) => type === "rename_table" || type === "alter_table_rename_column"
  17520. );
  17521. const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  17522. if (wasRename) {
  17523. newStatements[tableName2].push(...preparedStatements);
  17524. } else {
  17525. newStatements[tableName2] = preparedStatements;
  17526. }
  17527. continue;
  17528. }
  17529. continue;
  17530. }
  17531. if ((statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_default") && statement.columnNotNull) {
  17532. const tableName2 = statement.tableName;
  17533. const statementsForTable2 = newStatements[tableName2];
  17534. if (!statementsForTable2) {
  17535. newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  17536. continue;
  17537. }
  17538. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17539. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17540. const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  17541. if (wasRename) {
  17542. newStatements[tableName2].push(...preparedStatements);
  17543. } else {
  17544. newStatements[tableName2] = preparedStatements;
  17545. }
  17546. continue;
  17547. }
  17548. continue;
  17549. }
  17550. if (statement.type === "alter_table_add_column" && statement.column.primaryKey) {
  17551. const tableName2 = statement.tableName;
  17552. const statementsForTable2 = newStatements[tableName2];
  17553. if (!statementsForTable2) {
  17554. newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  17555. continue;
  17556. }
  17557. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  17558. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  17559. const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  17560. if (wasRename) {
  17561. newStatements[tableName2].push(...preparedStatements);
  17562. } else {
  17563. newStatements[tableName2] = preparedStatements;
  17564. }
  17565. continue;
  17566. }
  17567. continue;
  17568. }
  17569. const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
  17570. const statementsForTable = newStatements[tableName];
  17571. if (!statementsForTable) {
  17572. newStatements[tableName] = [statement];
  17573. continue;
  17574. }
  17575. if (!statementsForTable.some(({ type }) => type === "singlestore_recreate_table")) {
  17576. newStatements[tableName].push(statement);
  17577. }
  17578. }
  17579. const combinedStatements = Object.values(newStatements).flat();
  17580. const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
  17581. const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
  17582. const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
  17583. return [...renamedTables, ...renamedColumns, ...rest];
  17584. };
  17585. }
  17586. });
  17587. // src/snapshotsDiffer.ts
  17588. var snapshotsDiffer_exports = {};
  17589. __export(snapshotsDiffer_exports, {
  17590. alteredPgViewSchema: () => alteredPgViewSchema,
  17591. alteredTableScheme: () => alteredTableScheme,
  17592. applyLibSQLSnapshotsDiff: () => applyLibSQLSnapshotsDiff,
  17593. applyMysqlSnapshotsDiff: () => applyMysqlSnapshotsDiff,
  17594. applyPgSnapshotsDiff: () => applyPgSnapshotsDiff,
  17595. applySingleStoreSnapshotsDiff: () => applySingleStoreSnapshotsDiff,
  17596. applySqliteSnapshotsDiff: () => applySqliteSnapshotsDiff,
  17597. diffResultScheme: () => diffResultScheme,
  17598. diffResultSchemeMysql: () => diffResultSchemeMysql,
  17599. diffResultSchemeSQLite: () => diffResultSchemeSQLite,
  17600. diffResultSchemeSingleStore: () => diffResultSchemeSingleStore,
  17601. makePatched: () => makePatched,
  17602. makeSelfOrPatched: () => makeSelfOrPatched
  17603. });
  17604. var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema3, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSingleStore, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySingleStoreSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
  17605. var init_snapshotsDiffer = __esm({
  17606. "src/snapshotsDiffer.ts"() {
  17607. "use strict";
  17608. init_esm();
  17609. init_jsonDiffer();
  17610. init_sqlgenerator();
  17611. init_jsonStatements();
  17612. init_global();
  17613. init_mysqlSchema();
  17614. init_pgSchema();
  17615. init_singlestoreSchema();
  17616. init_sqliteSchema();
  17617. init_statementCombiner();
  17618. init_utils();
  17619. makeChanged = (schema6) => {
  17620. return objectType({
  17621. type: enumType(["changed"]),
  17622. old: schema6,
  17623. new: schema6
  17624. });
  17625. };
  17626. makeSelfOrChanged = (schema6) => {
  17627. return unionType([
  17628. schema6,
  17629. objectType({
  17630. type: enumType(["changed"]),
  17631. old: schema6,
  17632. new: schema6
  17633. })
  17634. ]);
  17635. };
  17636. makePatched = (schema6) => {
  17637. return unionType([
  17638. objectType({
  17639. type: literalType("added"),
  17640. value: schema6
  17641. }),
  17642. objectType({
  17643. type: literalType("deleted"),
  17644. value: schema6
  17645. }),
  17646. objectType({
  17647. type: literalType("changed"),
  17648. old: schema6,
  17649. new: schema6
  17650. })
  17651. ]);
  17652. };
  17653. makeSelfOrPatched = (schema6) => {
  17654. return unionType([
  17655. objectType({
  17656. type: literalType("none"),
  17657. value: schema6
  17658. }),
  17659. objectType({
  17660. type: literalType("added"),
  17661. value: schema6
  17662. }),
  17663. objectType({
  17664. type: literalType("deleted"),
  17665. value: schema6
  17666. }),
  17667. objectType({
  17668. type: literalType("changed"),
  17669. old: schema6,
  17670. new: schema6
  17671. })
  17672. ]);
  17673. };
  17674. columnSchema = objectType({
  17675. name: stringType(),
  17676. type: stringType(),
  17677. typeSchema: stringType().optional(),
  17678. primaryKey: booleanType().optional(),
  17679. default: anyType().optional(),
  17680. notNull: booleanType().optional(),
  17681. // should it be optional? should if be here?
  17682. autoincrement: booleanType().optional(),
  17683. onUpdate: booleanType().optional(),
  17684. isUnique: anyType().optional(),
  17685. uniqueName: stringType().optional(),
  17686. nullsNotDistinct: booleanType().optional(),
  17687. generated: objectType({
  17688. as: stringType(),
  17689. type: enumType(["stored", "virtual"]).default("stored")
  17690. }).optional(),
  17691. identity: stringType().optional()
  17692. }).strict();
  17693. alteredColumnSchema = objectType({
  17694. name: makeSelfOrChanged(stringType()),
  17695. type: makeChanged(stringType()).optional(),
  17696. default: makePatched(anyType()).optional(),
  17697. primaryKey: makePatched(booleanType()).optional(),
  17698. notNull: makePatched(booleanType()).optional(),
  17699. typeSchema: makePatched(stringType()).optional(),
  17700. onUpdate: makePatched(booleanType()).optional(),
  17701. autoincrement: makePatched(booleanType()).optional(),
  17702. generated: makePatched(
  17703. objectType({
  17704. as: stringType(),
  17705. type: enumType(["stored", "virtual"]).default("stored")
  17706. })
  17707. ).optional(),
  17708. identity: makePatched(stringType()).optional()
  17709. }).strict();
  17710. enumSchema3 = objectType({
  17711. name: stringType(),
  17712. schema: stringType(),
  17713. values: arrayType(stringType())
  17714. }).strict();
  17715. changedEnumSchema = objectType({
  17716. name: stringType(),
  17717. schema: stringType(),
  17718. addedValues: objectType({
  17719. before: stringType(),
  17720. value: stringType()
  17721. }).array(),
  17722. deletedValues: arrayType(stringType())
  17723. }).strict();
  17724. tableScheme = objectType({
  17725. name: stringType(),
  17726. schema: stringType().default(""),
  17727. columns: recordType(stringType(), columnSchema),
  17728. indexes: recordType(stringType(), stringType()),
  17729. foreignKeys: recordType(stringType(), stringType()),
  17730. compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
  17731. uniqueConstraints: recordType(stringType(), stringType()).default({}),
  17732. policies: recordType(stringType(), stringType()).default({}),
  17733. checkConstraints: recordType(stringType(), stringType()).default({}),
  17734. isRLSEnabled: booleanType().default(false)
  17735. }).strict();
  17736. alteredTableScheme = objectType({
  17737. name: stringType(),
  17738. schema: stringType(),
  17739. altered: alteredColumnSchema.array(),
  17740. addedIndexes: recordType(stringType(), stringType()),
  17741. deletedIndexes: recordType(stringType(), stringType()),
  17742. alteredIndexes: recordType(
  17743. stringType(),
  17744. objectType({
  17745. __new: stringType(),
  17746. __old: stringType()
  17747. }).strict()
  17748. ),
  17749. addedForeignKeys: recordType(stringType(), stringType()),
  17750. deletedForeignKeys: recordType(stringType(), stringType()),
  17751. alteredForeignKeys: recordType(
  17752. stringType(),
  17753. objectType({
  17754. __new: stringType(),
  17755. __old: stringType()
  17756. }).strict()
  17757. ),
  17758. addedCompositePKs: recordType(stringType(), stringType()),
  17759. deletedCompositePKs: recordType(stringType(), stringType()),
  17760. alteredCompositePKs: recordType(
  17761. stringType(),
  17762. objectType({
  17763. __new: stringType(),
  17764. __old: stringType()
  17765. })
  17766. ),
  17767. addedUniqueConstraints: recordType(stringType(), stringType()),
  17768. deletedUniqueConstraints: recordType(stringType(), stringType()),
  17769. alteredUniqueConstraints: recordType(
  17770. stringType(),
  17771. objectType({
  17772. __new: stringType(),
  17773. __old: stringType()
  17774. })
  17775. ),
  17776. addedPolicies: recordType(stringType(), stringType()),
  17777. deletedPolicies: recordType(stringType(), stringType()),
  17778. alteredPolicies: recordType(
  17779. stringType(),
  17780. objectType({
  17781. __new: stringType(),
  17782. __old: stringType()
  17783. })
  17784. ),
  17785. addedCheckConstraints: recordType(
  17786. stringType(),
  17787. stringType()
  17788. ),
  17789. deletedCheckConstraints: recordType(
  17790. stringType(),
  17791. stringType()
  17792. ),
  17793. alteredCheckConstraints: recordType(
  17794. stringType(),
  17795. objectType({
  17796. __new: stringType(),
  17797. __old: stringType()
  17798. })
  17799. )
  17800. }).strict();
  17801. alteredViewCommon = objectType({
  17802. name: stringType(),
  17803. alteredDefinition: objectType({
  17804. __old: stringType(),
  17805. __new: stringType()
  17806. }).strict().optional(),
  17807. alteredExisting: objectType({
  17808. __old: booleanType(),
  17809. __new: booleanType()
  17810. }).strict().optional()
  17811. });
  17812. alteredPgViewSchema = alteredViewCommon.merge(
  17813. objectType({
  17814. schema: stringType(),
  17815. deletedWithOption: mergedViewWithOption2.optional(),
  17816. addedWithOption: mergedViewWithOption2.optional(),
  17817. addedWith: mergedViewWithOption2.optional(),
  17818. deletedWith: mergedViewWithOption2.optional(),
  17819. alteredWith: mergedViewWithOption2.optional(),
  17820. alteredSchema: objectType({
  17821. __old: stringType(),
  17822. __new: stringType()
  17823. }).strict().optional(),
  17824. alteredTablespace: objectType({
  17825. __old: stringType(),
  17826. __new: stringType()
  17827. }).strict().optional(),
  17828. alteredUsing: objectType({
  17829. __old: stringType(),
  17830. __new: stringType()
  17831. }).strict().optional()
  17832. }).strict()
  17833. );
  17834. alteredMySqlViewSchema = alteredViewCommon.merge(
  17835. objectType({
  17836. alteredMeta: objectType({
  17837. __old: stringType(),
  17838. __new: stringType()
  17839. }).strict().optional()
  17840. }).strict()
  17841. );
  17842. diffResultScheme = objectType({
  17843. alteredTablesWithColumns: alteredTableScheme.array(),
  17844. alteredEnums: changedEnumSchema.array(),
  17845. alteredSequences: sequenceSquashed2.array(),
  17846. alteredRoles: roleSchema2.array(),
  17847. alteredPolicies: policySquashed2.array(),
  17848. alteredViews: alteredPgViewSchema.array()
  17849. }).strict();
  17850. diffResultSchemeMysql = objectType({
  17851. alteredTablesWithColumns: alteredTableScheme.array(),
  17852. alteredEnums: neverType().array(),
  17853. alteredViews: alteredMySqlViewSchema.array()
  17854. });
  17855. diffResultSchemeSingleStore = objectType({
  17856. alteredTablesWithColumns: alteredTableScheme.array(),
  17857. alteredEnums: neverType().array()
  17858. });
  17859. diffResultSchemeSQLite = objectType({
  17860. alteredTablesWithColumns: alteredTableScheme.array(),
  17861. alteredEnums: neverType().array(),
  17862. alteredViews: alteredViewCommon.array()
  17863. });
  17864. schemaChangeFor = (table6, renamedSchemas) => {
  17865. for (let ren of renamedSchemas) {
  17866. if (table6.schema === ren.from.name) {
  17867. return { key: `${ren.to.name}.${table6.name}`, schema: ren.to.name };
  17868. }
  17869. }
  17870. return {
  17871. key: `${table6.schema || "public"}.${table6.name}`,
  17872. schema: table6.schema
  17873. };
  17874. };
  17875. nameChangeFor = (table6, renamed) => {
  17876. for (let ren of renamed) {
  17877. if (table6.name === ren.from.name) {
  17878. return { name: ren.to.name };
  17879. }
  17880. }
  17881. return {
  17882. name: table6.name
  17883. };
  17884. };
  17885. nameSchemaChangeFor = (table6, renamedTables) => {
  17886. for (let ren of renamedTables) {
  17887. if (table6.name === ren.from.name && table6.schema === ren.from.schema) {
  17888. return {
  17889. key: `${ren.to.schema || "public"}.${ren.to.name}`,
  17890. name: ren.to.name,
  17891. schema: ren.to.schema
  17892. };
  17893. }
  17894. }
  17895. return {
  17896. key: `${table6.schema || "public"}.${table6.name}`,
  17897. name: table6.name,
  17898. schema: table6.schema
  17899. };
  17900. };
  17901. columnChangeFor = (column6, renamedColumns) => {
  17902. for (let ren of renamedColumns) {
  17903. if (column6 === ren.from.name) {
  17904. return ren.to.name;
  17905. }
  17906. }
  17907. return column6;
  17908. };
  17909. applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, indPolicyResolver2, roleResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
  17910. const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas);
  17911. const {
  17912. created: createdSchemas,
  17913. deleted: deletedSchemas,
  17914. renamed: renamedSchemas
  17915. } = await schemasResolver2({
  17916. created: schemasDiff.added.map((it) => ({ name: it })),
  17917. deleted: schemasDiff.deleted.map((it) => ({ name: it }))
  17918. });
  17919. const schemasPatchedSnap1 = copy(json1);
  17920. schemasPatchedSnap1.tables = mapEntries(
  17921. schemasPatchedSnap1.tables,
  17922. (_3, it) => {
  17923. const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
  17924. it.schema = schema6;
  17925. return [key, it];
  17926. }
  17927. );
  17928. schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => {
  17929. const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
  17930. it.schema = schema6;
  17931. return [key, it];
  17932. });
  17933. const enumsDiff = diffSchemasOrTables(schemasPatchedSnap1.enums, json2.enums);
  17934. const {
  17935. created: createdEnums,
  17936. deleted: deletedEnums,
  17937. renamed: renamedEnums,
  17938. moved: movedEnums
  17939. } = await enumsResolver2({
  17940. created: enumsDiff.added,
  17941. deleted: enumsDiff.deleted
  17942. });
  17943. schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => {
  17944. const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedEnums);
  17945. it.name = name;
  17946. it.schema = schema6;
  17947. return [key, it];
  17948. });
  17949. const columnTypesChangeMap = renamedEnums.reduce(
  17950. (acc, it) => {
  17951. acc[`${it.from.schema}.${it.from.name}`] = {
  17952. nameFrom: it.from.name,
  17953. nameTo: it.to.name,
  17954. schemaFrom: it.from.schema,
  17955. schemaTo: it.to.schema
  17956. };
  17957. return acc;
  17958. },
  17959. {}
  17960. );
  17961. const columnTypesMovesMap = movedEnums.reduce(
  17962. (acc, it) => {
  17963. acc[`${it.schemaFrom}.${it.name}`] = {
  17964. nameFrom: it.name,
  17965. nameTo: it.name,
  17966. schemaFrom: it.schemaFrom,
  17967. schemaTo: it.schemaTo
  17968. };
  17969. return acc;
  17970. },
  17971. {}
  17972. );
  17973. schemasPatchedSnap1.tables = mapEntries(
  17974. schemasPatchedSnap1.tables,
  17975. (tableKey2, tableValue) => {
  17976. const patchedColumns = mapValues(tableValue.columns, (column6) => {
  17977. const key = `${column6.typeSchema || "public"}.${column6.type}`;
  17978. const change = columnTypesChangeMap[key] || columnTypesMovesMap[key];
  17979. if (change) {
  17980. column6.type = change.nameTo;
  17981. column6.typeSchema = change.schemaTo;
  17982. }
  17983. return column6;
  17984. });
  17985. tableValue.columns = patchedColumns;
  17986. return [tableKey2, tableValue];
  17987. }
  17988. );
  17989. schemasPatchedSnap1.sequences = mapEntries(
  17990. schemasPatchedSnap1.sequences,
  17991. (_3, it) => {
  17992. const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
  17993. it.schema = schema6;
  17994. return [key, it];
  17995. }
  17996. );
  17997. const sequencesDiff = diffSchemasOrTables(
  17998. schemasPatchedSnap1.sequences,
  17999. json2.sequences
  18000. );
  18001. const {
  18002. created: createdSequences,
  18003. deleted: deletedSequences,
  18004. renamed: renamedSequences,
  18005. moved: movedSequences
  18006. } = await sequencesResolver2({
  18007. created: sequencesDiff.added,
  18008. deleted: sequencesDiff.deleted
  18009. });
  18010. schemasPatchedSnap1.sequences = mapEntries(
  18011. schemasPatchedSnap1.sequences,
  18012. (_3, it) => {
  18013. const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedSequences);
  18014. it.name = name;
  18015. it.schema = schema6;
  18016. return [key, it];
  18017. }
  18018. );
  18019. const sequencesChangeMap = renamedSequences.reduce(
  18020. (acc, it) => {
  18021. acc[`${it.from.schema}.${it.from.name}`] = {
  18022. nameFrom: it.from.name,
  18023. nameTo: it.to.name,
  18024. schemaFrom: it.from.schema,
  18025. schemaTo: it.to.schema
  18026. };
  18027. return acc;
  18028. },
  18029. {}
  18030. );
  18031. const sequencesMovesMap = movedSequences.reduce(
  18032. (acc, it) => {
  18033. acc[`${it.schemaFrom}.${it.name}`] = {
  18034. nameFrom: it.name,
  18035. nameTo: it.name,
  18036. schemaFrom: it.schemaFrom,
  18037. schemaTo: it.schemaTo
  18038. };
  18039. return acc;
  18040. },
  18041. {}
  18042. );
  18043. schemasPatchedSnap1.tables = mapEntries(
  18044. schemasPatchedSnap1.tables,
  18045. (tableKey2, tableValue) => {
  18046. const patchedColumns = mapValues(tableValue.columns, (column6) => {
  18047. const key = `${column6.typeSchema || "public"}.${column6.type}`;
  18048. const change = sequencesChangeMap[key] || sequencesMovesMap[key];
  18049. if (change) {
  18050. column6.type = change.nameTo;
  18051. column6.typeSchema = change.schemaTo;
  18052. }
  18053. return column6;
  18054. });
  18055. tableValue.columns = patchedColumns;
  18056. return [tableKey2, tableValue];
  18057. }
  18058. );
  18059. const rolesDiff = diffSchemasOrTables(
  18060. schemasPatchedSnap1.roles,
  18061. json2.roles
  18062. );
  18063. const {
  18064. created: createdRoles,
  18065. deleted: deletedRoles,
  18066. renamed: renamedRoles
  18067. } = await roleResolver2({
  18068. created: rolesDiff.added,
  18069. deleted: rolesDiff.deleted
  18070. });
  18071. schemasPatchedSnap1.roles = mapEntries(
  18072. schemasPatchedSnap1.roles,
  18073. (_3, it) => {
  18074. const { name } = nameChangeFor(it, renamedRoles);
  18075. it.name = name;
  18076. return [name, it];
  18077. }
  18078. );
  18079. const rolesChangeMap = renamedRoles.reduce(
  18080. (acc, it) => {
  18081. acc[it.from.name] = {
  18082. nameFrom: it.from.name,
  18083. nameTo: it.to.name
  18084. };
  18085. return acc;
  18086. },
  18087. {}
  18088. );
  18089. schemasPatchedSnap1.roles = mapEntries(
  18090. schemasPatchedSnap1.roles,
  18091. (roleKey, roleValue) => {
  18092. const key = roleKey;
  18093. const change = rolesChangeMap[key];
  18094. if (change) {
  18095. roleValue.name = change.nameTo;
  18096. }
  18097. return [roleKey, roleValue];
  18098. }
  18099. );
  18100. const tablesDiff = diffSchemasOrTables(
  18101. schemasPatchedSnap1.tables,
  18102. json2.tables
  18103. );
  18104. const {
  18105. created: createdTables,
  18106. deleted: deletedTables,
  18107. moved: movedTables,
  18108. renamed: renamedTables
  18109. // renamed or moved
  18110. } = await tablesResolver2({
  18111. created: tablesDiff.added,
  18112. deleted: tablesDiff.deleted
  18113. });
  18114. const tablesPatchedSnap1 = copy(schemasPatchedSnap1);
  18115. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  18116. const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedTables);
  18117. it.name = name;
  18118. it.schema = schema6;
  18119. return [key, it];
  18120. });
  18121. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  18122. const columnRenames = [];
  18123. const columnCreates = [];
  18124. const columnDeletes = [];
  18125. for (let entry of Object.values(res)) {
  18126. const { renamed, created: created2, deleted: deleted2 } = await columnsResolver2({
  18127. tableName: entry.name,
  18128. schema: entry.schema,
  18129. deleted: entry.columns.deleted,
  18130. created: entry.columns.added
  18131. });
  18132. if (created2.length > 0) {
  18133. columnCreates.push({
  18134. table: entry.name,
  18135. schema: entry.schema,
  18136. columns: created2
  18137. });
  18138. }
  18139. if (deleted2.length > 0) {
  18140. columnDeletes.push({
  18141. table: entry.name,
  18142. schema: entry.schema,
  18143. columns: deleted2
  18144. });
  18145. }
  18146. if (renamed.length > 0) {
  18147. columnRenames.push({
  18148. table: entry.name,
  18149. schema: entry.schema,
  18150. renames: renamed
  18151. });
  18152. }
  18153. }
  18154. const columnRenamesDict = columnRenames.reduce(
  18155. (acc, it) => {
  18156. acc[`${it.schema || "public"}.${it.table}`] = it.renames;
  18157. return acc;
  18158. },
  18159. {}
  18160. );
  18161. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  18162. columnsPatchedSnap1.tables = mapEntries(
  18163. columnsPatchedSnap1.tables,
  18164. (tableKey2, tableValue) => {
  18165. const patchedColumns = mapKeys(
  18166. tableValue.columns,
  18167. (columnKey, column6) => {
  18168. const rens = columnRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
  18169. const newName = columnChangeFor(columnKey, rens);
  18170. column6.name = newName;
  18171. return newName;
  18172. }
  18173. );
  18174. tableValue.columns = patchedColumns;
  18175. return [tableKey2, tableValue];
  18176. }
  18177. );
  18178. const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables);
  18179. const policyRenames = [];
  18180. const policyCreates = [];
  18181. const policyDeletes = [];
  18182. for (let entry of Object.values(policyRes)) {
  18183. const { renamed, created: created2, deleted: deleted2 } = await policyResolver2({
  18184. tableName: entry.name,
  18185. schema: entry.schema,
  18186. deleted: entry.policies.deleted.map(
  18187. action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy
  18188. ),
  18189. created: entry.policies.added.map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
  18190. });
  18191. if (created2.length > 0) {
  18192. policyCreates.push({
  18193. table: entry.name,
  18194. schema: entry.schema,
  18195. columns: created2
  18196. });
  18197. }
  18198. if (deleted2.length > 0) {
  18199. policyDeletes.push({
  18200. table: entry.name,
  18201. schema: entry.schema,
  18202. columns: deleted2
  18203. });
  18204. }
  18205. if (renamed.length > 0) {
  18206. policyRenames.push({
  18207. table: entry.name,
  18208. schema: entry.schema,
  18209. renames: renamed
  18210. });
  18211. }
  18212. }
  18213. const policyRenamesDict = columnRenames.reduce(
  18214. (acc, it) => {
  18215. acc[`${it.schema || "public"}.${it.table}`] = it.renames;
  18216. return acc;
  18217. },
  18218. {}
  18219. );
  18220. const policyPatchedSnap1 = copy(tablesPatchedSnap1);
  18221. policyPatchedSnap1.tables = mapEntries(
  18222. policyPatchedSnap1.tables,
  18223. (tableKey2, tableValue) => {
  18224. const patchedPolicies = mapKeys(
  18225. tableValue.policies,
  18226. (policyKey, policy5) => {
  18227. const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
  18228. const newName = columnChangeFor(policyKey, rens);
  18229. const unsquashedPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(policy5) : PgSquasher.unsquashPolicy(policy5);
  18230. unsquashedPolicy.name = newName;
  18231. policy5 = PgSquasher.squashPolicy(unsquashedPolicy);
  18232. return newName;
  18233. }
  18234. );
  18235. tableValue.policies = patchedPolicies;
  18236. return [tableKey2, tableValue];
  18237. }
  18238. );
  18239. const indPolicyRes = diffIndPolicies(policyPatchedSnap1.policies, json2.policies);
  18240. const indPolicyCreates = [];
  18241. const indPolicyDeletes = [];
  18242. const { renamed: indPolicyRenames, created, deleted } = await indPolicyResolver2({
  18243. deleted: indPolicyRes.deleted.map(
  18244. (t6) => action === "push" ? PgSquasher.unsquashPolicyPush(t6.values) : PgSquasher.unsquashPolicy(t6.values)
  18245. ),
  18246. created: indPolicyRes.added.map(
  18247. (t6) => action === "push" ? PgSquasher.unsquashPolicyPush(t6.values) : PgSquasher.unsquashPolicy(t6.values)
  18248. )
  18249. });
  18250. if (created.length > 0) {
  18251. indPolicyCreates.push({
  18252. policies: created
  18253. });
  18254. }
  18255. if (deleted.length > 0) {
  18256. indPolicyDeletes.push({
  18257. policies: deleted
  18258. });
  18259. }
  18260. const indPolicyRenamesDict = indPolicyRenames.reduce(
  18261. (acc, it) => {
  18262. acc[it.from.name] = {
  18263. nameFrom: it.from.name,
  18264. nameTo: it.to.name
  18265. };
  18266. return acc;
  18267. },
  18268. {}
  18269. );
  18270. const indPolicyPatchedSnap1 = copy(policyPatchedSnap1);
  18271. indPolicyPatchedSnap1.policies = mapEntries(
  18272. indPolicyPatchedSnap1.policies,
  18273. (policyKey, policyValue) => {
  18274. const key = policyKey;
  18275. const change = indPolicyRenamesDict[key];
  18276. if (change) {
  18277. policyValue.name = change.nameTo;
  18278. }
  18279. return [policyKey, policyValue];
  18280. }
  18281. );
  18282. const viewsDiff = diffSchemasOrTables(indPolicyPatchedSnap1.views, json2.views);
  18283. const {
  18284. created: createdViews,
  18285. deleted: deletedViews,
  18286. renamed: renamedViews,
  18287. moved: movedViews
  18288. } = await viewsResolver2({
  18289. created: viewsDiff.added,
  18290. deleted: viewsDiff.deleted
  18291. });
  18292. const renamesViewDic = {};
  18293. renamedViews.forEach((it) => {
  18294. renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
  18295. });
  18296. const movedViewDic = {};
  18297. movedViews.forEach((it) => {
  18298. movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
  18299. });
  18300. const viewsPatchedSnap1 = copy(policyPatchedSnap1);
  18301. viewsPatchedSnap1.views = mapEntries(
  18302. viewsPatchedSnap1.views,
  18303. (viewKey, viewValue) => {
  18304. const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
  18305. const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
  18306. if (rename) {
  18307. viewValue.name = rename.to;
  18308. viewKey = `${viewValue.schema}.${viewValue.name}`;
  18309. }
  18310. if (moved) viewKey = `${moved.to}.${viewValue.name}`;
  18311. return [viewKey, viewValue];
  18312. }
  18313. );
  18314. const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
  18315. const typedResult = diffResultScheme.parse(diffResult);
  18316. const jsonStatements = [];
  18317. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  18318. return preparePgCreateIndexesJson(
  18319. it.name,
  18320. it.schema,
  18321. it.indexes,
  18322. curFull,
  18323. action
  18324. );
  18325. }).flat();
  18326. const jsonDropTables = deletedTables.map((it) => {
  18327. return prepareDropTableJson(it);
  18328. });
  18329. const jsonRenameTables = renamedTables.map((it) => {
  18330. return prepareRenameTableJson(it.from, it.to);
  18331. });
  18332. const alteredTables = typedResult.alteredTablesWithColumns;
  18333. const jsonRenameColumnsStatements = [];
  18334. const jsonDropColumnsStatemets = [];
  18335. const jsonAddColumnsStatemets = [];
  18336. for (let it of columnRenames) {
  18337. jsonRenameColumnsStatements.push(
  18338. ...prepareRenameColumns(it.table, it.schema, it.renames)
  18339. );
  18340. }
  18341. for (let it of columnDeletes) {
  18342. jsonDropColumnsStatemets.push(
  18343. ..._prepareDropColumns(it.table, it.schema, it.columns)
  18344. );
  18345. }
  18346. for (let it of columnCreates) {
  18347. jsonAddColumnsStatemets.push(
  18348. ..._prepareAddColumns(it.table, it.schema, it.columns)
  18349. );
  18350. }
  18351. const jsonAddedCompositePKs = [];
  18352. const jsonDeletedCompositePKs = [];
  18353. const jsonAlteredCompositePKs = [];
  18354. const jsonAddedUniqueConstraints = [];
  18355. const jsonDeletedUniqueConstraints = [];
  18356. const jsonAlteredUniqueConstraints = [];
  18357. const jsonSetTableSchemas = [];
  18358. if (movedTables) {
  18359. for (let it of movedTables) {
  18360. jsonSetTableSchemas.push({
  18361. type: "alter_table_set_schema",
  18362. tableName: it.name,
  18363. schemaFrom: it.schemaFrom || "public",
  18364. schemaTo: it.schemaTo || "public"
  18365. });
  18366. }
  18367. }
  18368. const jsonDeletedCheckConstraints = [];
  18369. const jsonCreatedCheckConstraints = [];
  18370. for (let it of alteredTables) {
  18371. let addedColumns;
  18372. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  18373. const addedPkColumns = it.addedCompositePKs[addedPkName];
  18374. addedColumns = PgSquasher.unsquashPK(addedPkColumns);
  18375. }
  18376. let deletedColumns;
  18377. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  18378. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  18379. deletedColumns = PgSquasher.unsquashPK(deletedPkColumns);
  18380. }
  18381. const doPerformDeleteAndCreate = JSON.stringify(addedColumns ?? {}) !== JSON.stringify(deletedColumns ?? {});
  18382. let addedCompositePKs = [];
  18383. let deletedCompositePKs = [];
  18384. let alteredCompositePKs = [];
  18385. if (doPerformDeleteAndCreate) {
  18386. addedCompositePKs = prepareAddCompositePrimaryKeyPg(
  18387. it.name,
  18388. it.schema,
  18389. it.addedCompositePKs,
  18390. curFull
  18391. );
  18392. deletedCompositePKs = prepareDeleteCompositePrimaryKeyPg(
  18393. it.name,
  18394. it.schema,
  18395. it.deletedCompositePKs,
  18396. prevFull
  18397. );
  18398. }
  18399. alteredCompositePKs = prepareAlterCompositePrimaryKeyPg(
  18400. it.name,
  18401. it.schema,
  18402. it.alteredCompositePKs,
  18403. prevFull,
  18404. curFull
  18405. );
  18406. let addedUniqueConstraints = [];
  18407. let deletedUniqueConstraints = [];
  18408. let alteredUniqueConstraints = [];
  18409. let createCheckConstraints = [];
  18410. let deleteCheckConstraints = [];
  18411. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  18412. it.name,
  18413. it.schema,
  18414. it.addedUniqueConstraints
  18415. );
  18416. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  18417. it.name,
  18418. it.schema,
  18419. it.deletedUniqueConstraints
  18420. );
  18421. if (it.alteredUniqueConstraints) {
  18422. const added = {};
  18423. const deleted2 = {};
  18424. for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
  18425. added[k5] = it.alteredUniqueConstraints[k5].__new;
  18426. deleted2[k5] = it.alteredUniqueConstraints[k5].__old;
  18427. }
  18428. addedUniqueConstraints.push(
  18429. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  18430. );
  18431. deletedUniqueConstraints.push(
  18432. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted2)
  18433. );
  18434. }
  18435. createCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  18436. deleteCheckConstraints = prepareDeleteCheckConstraint(
  18437. it.name,
  18438. it.schema,
  18439. it.deletedCheckConstraints
  18440. );
  18441. if (it.alteredCheckConstraints && action !== "push") {
  18442. const added = {};
  18443. const deleted2 = {};
  18444. for (const k5 of Object.keys(it.alteredCheckConstraints)) {
  18445. added[k5] = it.alteredCheckConstraints[k5].__new;
  18446. deleted2[k5] = it.alteredCheckConstraints[k5].__old;
  18447. }
  18448. createCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  18449. deleteCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted2));
  18450. }
  18451. jsonCreatedCheckConstraints.push(...createCheckConstraints);
  18452. jsonDeletedCheckConstraints.push(...deleteCheckConstraints);
  18453. jsonAddedCompositePKs.push(...addedCompositePKs);
  18454. jsonDeletedCompositePKs.push(...deletedCompositePKs);
  18455. jsonAlteredCompositePKs.push(...alteredCompositePKs);
  18456. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  18457. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  18458. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  18459. }
  18460. const rColumns = jsonRenameColumnsStatements.map((it) => {
  18461. const tableName = it.tableName;
  18462. const schema6 = it.schema;
  18463. return {
  18464. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  18465. to: { schema: schema6, table: tableName, column: it.newColumnName }
  18466. };
  18467. });
  18468. const jsonTableAlternations = alteredTables.map((it) => {
  18469. return preparePgAlterColumns(
  18470. it.name,
  18471. it.schema,
  18472. it.altered,
  18473. json2,
  18474. json1,
  18475. action
  18476. );
  18477. }).flat();
  18478. const jsonCreateIndexesFoAlteredTables = alteredTables.map((it) => {
  18479. return preparePgCreateIndexesJson(
  18480. it.name,
  18481. it.schema,
  18482. it.addedIndexes || {},
  18483. curFull,
  18484. action
  18485. );
  18486. }).flat();
  18487. const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
  18488. return prepareDropIndexesJson(
  18489. it.name,
  18490. it.schema,
  18491. it.deletedIndexes || {}
  18492. );
  18493. }).flat();
  18494. const jsonCreatePoliciesStatements = [];
  18495. const jsonDropPoliciesStatements = [];
  18496. const jsonAlterPoliciesStatements = [];
  18497. const jsonRenamePoliciesStatements = [];
  18498. const jsonRenameIndPoliciesStatements = [];
  18499. const jsonCreateIndPoliciesStatements = [];
  18500. const jsonDropIndPoliciesStatements = [];
  18501. const jsonAlterIndPoliciesStatements = [];
  18502. const jsonEnableRLSStatements = [];
  18503. const jsonDisableRLSStatements = [];
  18504. for (let it of indPolicyRenames) {
  18505. jsonRenameIndPoliciesStatements.push(
  18506. ...prepareRenameIndPolicyJsons([it])
  18507. );
  18508. }
  18509. for (const it of indPolicyCreates) {
  18510. jsonCreateIndPoliciesStatements.push(
  18511. ...prepareCreateIndPolicyJsons(
  18512. it.policies
  18513. )
  18514. );
  18515. }
  18516. for (const it of indPolicyDeletes) {
  18517. jsonDropIndPoliciesStatements.push(
  18518. ...prepareDropIndPolicyJsons(
  18519. it.policies
  18520. )
  18521. );
  18522. }
  18523. typedResult.alteredPolicies.forEach(({ values }) => {
  18524. const policy5 = action === "push" ? PgSquasher.unsquashPolicyPush(values) : PgSquasher.unsquashPolicy(values);
  18525. const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json2.policies[policy5.name].values);
  18526. const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json1.policies[policy5.name].values);
  18527. if (newPolicy.as !== oldPolicy.as) {
  18528. jsonDropIndPoliciesStatements.push(
  18529. ...prepareDropIndPolicyJsons(
  18530. [oldPolicy]
  18531. )
  18532. );
  18533. jsonCreateIndPoliciesStatements.push(
  18534. ...prepareCreateIndPolicyJsons(
  18535. [newPolicy]
  18536. )
  18537. );
  18538. return;
  18539. }
  18540. if (newPolicy.for !== oldPolicy.for) {
  18541. jsonDropIndPoliciesStatements.push(
  18542. ...prepareDropIndPolicyJsons(
  18543. [oldPolicy]
  18544. )
  18545. );
  18546. jsonCreateIndPoliciesStatements.push(
  18547. ...prepareCreateIndPolicyJsons(
  18548. [newPolicy]
  18549. )
  18550. );
  18551. return;
  18552. }
  18553. jsonAlterIndPoliciesStatements.push(
  18554. prepareAlterIndPolicyJson(
  18555. oldPolicy,
  18556. newPolicy
  18557. )
  18558. );
  18559. });
  18560. for (let it of policyRenames) {
  18561. jsonRenamePoliciesStatements.push(
  18562. ...prepareRenamePolicyJsons(it.table, it.schema, it.renames)
  18563. );
  18564. }
  18565. for (const it of policyCreates) {
  18566. jsonCreatePoliciesStatements.push(
  18567. ...prepareCreatePolicyJsons(
  18568. it.table,
  18569. it.schema,
  18570. it.columns
  18571. )
  18572. );
  18573. }
  18574. for (const it of policyDeletes) {
  18575. jsonDropPoliciesStatements.push(
  18576. ...prepareDropPolicyJsons(
  18577. it.table,
  18578. it.schema,
  18579. it.columns
  18580. )
  18581. );
  18582. }
  18583. alteredTables.forEach((it) => {
  18584. Object.keys(it.alteredPolicies).forEach((policyName) => {
  18585. const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__new) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new);
  18586. const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__old) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old);
  18587. if (newPolicy.as !== oldPolicy.as) {
  18588. jsonDropPoliciesStatements.push(
  18589. ...prepareDropPolicyJsons(
  18590. it.name,
  18591. it.schema,
  18592. [oldPolicy]
  18593. )
  18594. );
  18595. jsonCreatePoliciesStatements.push(
  18596. ...prepareCreatePolicyJsons(
  18597. it.name,
  18598. it.schema,
  18599. [newPolicy]
  18600. )
  18601. );
  18602. return;
  18603. }
  18604. if (newPolicy.for !== oldPolicy.for) {
  18605. jsonDropPoliciesStatements.push(
  18606. ...prepareDropPolicyJsons(
  18607. it.name,
  18608. it.schema,
  18609. [oldPolicy]
  18610. )
  18611. );
  18612. jsonCreatePoliciesStatements.push(
  18613. ...prepareCreatePolicyJsons(
  18614. it.name,
  18615. it.schema,
  18616. [newPolicy]
  18617. )
  18618. );
  18619. return;
  18620. }
  18621. jsonAlterPoliciesStatements.push(
  18622. prepareAlterPolicyJson(
  18623. it.name,
  18624. it.schema,
  18625. it.alteredPolicies[policyName].__old,
  18626. it.alteredPolicies[policyName].__new
  18627. )
  18628. );
  18629. });
  18630. for (const table6 of Object.values(json2.tables)) {
  18631. const policiesInCurrentState = Object.keys(table6.policies);
  18632. const tableInPreviousState = columnsPatchedSnap1.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
  18633. const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
  18634. if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table6.isRLSEnabled) {
  18635. jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
  18636. }
  18637. if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table6.isRLSEnabled) {
  18638. jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
  18639. }
  18640. const wasRlsEnabled = tableInPreviousState ? tableInPreviousState.isRLSEnabled : false;
  18641. if (table6.isRLSEnabled !== wasRlsEnabled) {
  18642. if (table6.isRLSEnabled) {
  18643. jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
  18644. } else if (!table6.isRLSEnabled && policiesInCurrentState.length === 0) {
  18645. jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
  18646. }
  18647. }
  18648. }
  18649. for (const table6 of Object.values(columnsPatchedSnap1.tables)) {
  18650. const tableInCurrentState = json2.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
  18651. if (tableInCurrentState === void 0 && !table6.isRLSEnabled) {
  18652. jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
  18653. }
  18654. }
  18655. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  18656. (current, item) => {
  18657. current[item] = it.alteredIndexes[item].__old;
  18658. return current;
  18659. },
  18660. {}
  18661. );
  18662. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  18663. (current, item) => {
  18664. current[item] = it.alteredIndexes[item].__new;
  18665. return current;
  18666. },
  18667. {}
  18668. );
  18669. jsonCreateIndexesFoAlteredTables.push(
  18670. ...preparePgCreateIndexesJson(
  18671. it.name,
  18672. it.schema,
  18673. createdIndexes || {},
  18674. curFull,
  18675. action
  18676. )
  18677. );
  18678. jsonDropIndexesForAllAlteredTables.push(
  18679. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  18680. );
  18681. });
  18682. const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
  18683. return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
  18684. }).flat();
  18685. const jsonReferencesForAlteredTables = alteredTables.map((it) => {
  18686. const forAdded = prepareCreateReferencesJson(
  18687. it.name,
  18688. it.schema,
  18689. it.addedForeignKeys
  18690. );
  18691. const forAltered = prepareDropReferencesJson(
  18692. it.name,
  18693. it.schema,
  18694. it.deletedForeignKeys
  18695. );
  18696. const alteredFKs = prepareAlterReferencesJson(
  18697. it.name,
  18698. it.schema,
  18699. it.alteredForeignKeys
  18700. );
  18701. return [...forAdded, ...forAltered, ...alteredFKs];
  18702. }).flat();
  18703. const jsonCreatedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
  18704. (t6) => t6.type === "create_reference"
  18705. );
  18706. const jsonDroppedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
  18707. (t6) => t6.type === "delete_reference"
  18708. );
  18709. const createEnums = createdEnums.map((it) => {
  18710. return prepareCreateEnumJson(it.name, it.schema, it.values);
  18711. }) ?? [];
  18712. const dropEnums = deletedEnums.map((it) => {
  18713. return prepareDropEnumJson(it.name, it.schema);
  18714. });
  18715. const moveEnums = movedEnums.map((it) => {
  18716. return prepareMoveEnumJson(it.name, it.schemaFrom, it.schemaTo);
  18717. });
  18718. const renameEnums = renamedEnums.map((it) => {
  18719. return prepareRenameEnumJson(it.from.name, it.to.name, it.to.schema);
  18720. });
  18721. const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => {
  18722. return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues);
  18723. }).flat() ?? [];
  18724. const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => {
  18725. return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull);
  18726. }).flat() ?? [];
  18727. const createSequences = createdSequences.map((it) => {
  18728. return prepareCreateSequenceJson(it);
  18729. }) ?? [];
  18730. const dropSequences = deletedSequences.map((it) => {
  18731. return prepareDropSequenceJson(it.name, it.schema);
  18732. });
  18733. const moveSequences = movedSequences.map((it) => {
  18734. return prepareMoveSequenceJson(it.name, it.schemaFrom, it.schemaTo);
  18735. });
  18736. const renameSequences = renamedSequences.map((it) => {
  18737. return prepareRenameSequenceJson(it.from.name, it.to.name, it.to.schema);
  18738. });
  18739. const jsonAlterSequences = typedResult.alteredSequences.map((it) => {
  18740. return prepareAlterSequenceJson(it);
  18741. }).flat() ?? [];
  18742. const createRoles = createdRoles.map((it) => {
  18743. return prepareCreateRoleJson(it);
  18744. }) ?? [];
  18745. const dropRoles = deletedRoles.map((it) => {
  18746. return prepareDropRoleJson(it.name);
  18747. });
  18748. const renameRoles = renamedRoles.map((it) => {
  18749. return prepareRenameRoleJson(it.from.name, it.to.name);
  18750. });
  18751. const jsonAlterRoles = typedResult.alteredRoles.map((it) => {
  18752. return prepareAlterRoleJson(it);
  18753. }).flat() ?? [];
  18754. const createSchemas = prepareCreateSchemasJson(
  18755. createdSchemas.map((it) => it.name)
  18756. );
  18757. const renameSchemas = prepareRenameSchemasJson(
  18758. renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name }))
  18759. );
  18760. const dropSchemas = prepareDeleteSchemasJson(
  18761. deletedSchemas.map((it) => it.name)
  18762. );
  18763. const createTables = createdTables.map((it) => {
  18764. return preparePgCreateTableJson(it, curFull);
  18765. });
  18766. jsonCreatePoliciesStatements.push(...[].concat(
  18767. ...createdTables.map(
  18768. (it) => prepareCreatePolicyJsons(
  18769. it.name,
  18770. it.schema,
  18771. Object.values(it.policies).map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
  18772. )
  18773. )
  18774. ));
  18775. const createViews = [];
  18776. const dropViews = [];
  18777. const renameViews = [];
  18778. const alterViews = [];
  18779. createViews.push(
  18780. ...createdViews.filter((it) => !it.isExisting).map((it) => {
  18781. return preparePgCreateViewJson(
  18782. it.name,
  18783. it.schema,
  18784. it.definition,
  18785. it.materialized,
  18786. it.withNoData,
  18787. it.with,
  18788. it.using,
  18789. it.tablespace
  18790. );
  18791. })
  18792. );
  18793. dropViews.push(
  18794. ...deletedViews.filter((it) => !it.isExisting).map((it) => {
  18795. return prepareDropViewJson(it.name, it.schema, it.materialized);
  18796. })
  18797. );
  18798. renameViews.push(
  18799. ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
  18800. return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
  18801. })
  18802. );
  18803. alterViews.push(
  18804. ...movedViews.filter(
  18805. (it) => !json2.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
  18806. ).map((it) => {
  18807. return preparePgAlterViewAlterSchemaJson(
  18808. it.schemaTo,
  18809. it.schemaFrom,
  18810. it.name,
  18811. json2.views[`${it.schemaTo}.${it.name}`].materialized
  18812. );
  18813. })
  18814. );
  18815. const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[`${it.schema}.${it.name}`].isExisting);
  18816. for (const alteredView of alteredViews) {
  18817. const viewKey = `${alteredView.schema}.${alteredView.name}`;
  18818. const { materialized, with: withOption, definition, withNoData, using, tablespace } = json2.views[viewKey];
  18819. if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
  18820. dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
  18821. createViews.push(
  18822. preparePgCreateViewJson(
  18823. alteredView.name,
  18824. alteredView.schema,
  18825. definition,
  18826. materialized,
  18827. withNoData,
  18828. withOption,
  18829. using,
  18830. tablespace
  18831. )
  18832. );
  18833. continue;
  18834. }
  18835. if (alteredView.addedWithOption) {
  18836. alterViews.push(
  18837. preparePgAlterViewAddWithOptionJson(
  18838. alteredView.name,
  18839. alteredView.schema,
  18840. materialized,
  18841. alteredView.addedWithOption
  18842. )
  18843. );
  18844. }
  18845. if (alteredView.deletedWithOption) {
  18846. alterViews.push(
  18847. preparePgAlterViewDropWithOptionJson(
  18848. alteredView.name,
  18849. alteredView.schema,
  18850. materialized,
  18851. alteredView.deletedWithOption
  18852. )
  18853. );
  18854. }
  18855. if (alteredView.addedWith) {
  18856. alterViews.push(
  18857. preparePgAlterViewAddWithOptionJson(
  18858. alteredView.name,
  18859. alteredView.schema,
  18860. materialized,
  18861. alteredView.addedWith
  18862. )
  18863. );
  18864. }
  18865. if (alteredView.deletedWith) {
  18866. alterViews.push(
  18867. preparePgAlterViewDropWithOptionJson(
  18868. alteredView.name,
  18869. alteredView.schema,
  18870. materialized,
  18871. alteredView.deletedWith
  18872. )
  18873. );
  18874. }
  18875. if (alteredView.alteredWith) {
  18876. alterViews.push(
  18877. preparePgAlterViewAddWithOptionJson(
  18878. alteredView.name,
  18879. alteredView.schema,
  18880. materialized,
  18881. alteredView.alteredWith
  18882. )
  18883. );
  18884. }
  18885. if (alteredView.alteredTablespace) {
  18886. alterViews.push(
  18887. preparePgAlterViewAlterTablespaceJson(
  18888. alteredView.name,
  18889. alteredView.schema,
  18890. materialized,
  18891. alteredView.alteredTablespace.__new
  18892. )
  18893. );
  18894. }
  18895. if (alteredView.alteredUsing) {
  18896. alterViews.push(
  18897. preparePgAlterViewAlterUsingJson(
  18898. alteredView.name,
  18899. alteredView.schema,
  18900. materialized,
  18901. alteredView.alteredUsing.__new
  18902. )
  18903. );
  18904. }
  18905. }
  18906. jsonStatements.push(...createSchemas);
  18907. jsonStatements.push(...renameSchemas);
  18908. jsonStatements.push(...createEnums);
  18909. jsonStatements.push(...moveEnums);
  18910. jsonStatements.push(...renameEnums);
  18911. jsonStatements.push(...jsonAlterEnumsWithAddedValues);
  18912. jsonStatements.push(...createSequences);
  18913. jsonStatements.push(...moveSequences);
  18914. jsonStatements.push(...renameSequences);
  18915. jsonStatements.push(...jsonAlterSequences);
  18916. jsonStatements.push(...renameRoles);
  18917. jsonStatements.push(...dropRoles);
  18918. jsonStatements.push(...createRoles);
  18919. jsonStatements.push(...jsonAlterRoles);
  18920. jsonStatements.push(...createTables);
  18921. jsonStatements.push(...jsonEnableRLSStatements);
  18922. jsonStatements.push(...jsonDisableRLSStatements);
  18923. jsonStatements.push(...dropViews);
  18924. jsonStatements.push(...renameViews);
  18925. jsonStatements.push(...alterViews);
  18926. jsonStatements.push(...jsonDropTables);
  18927. jsonStatements.push(...jsonSetTableSchemas);
  18928. jsonStatements.push(...jsonRenameTables);
  18929. jsonStatements.push(...jsonRenameColumnsStatements);
  18930. jsonStatements.push(...jsonDeletedUniqueConstraints);
  18931. jsonStatements.push(...jsonDeletedCheckConstraints);
  18932. jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
  18933. jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
  18934. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  18935. jsonStatements.push(...jsonDeletedCompositePKs);
  18936. jsonStatements.push(...jsonTableAlternations);
  18937. jsonStatements.push(...jsonAddedCompositePKs);
  18938. jsonStatements.push(...jsonAddColumnsStatemets);
  18939. jsonStatements.push(...jsonCreateReferencesForCreatedTables);
  18940. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  18941. jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
  18942. jsonStatements.push(...jsonCreateIndexesFoAlteredTables);
  18943. jsonStatements.push(...jsonDropColumnsStatemets);
  18944. jsonStatements.push(...jsonAlteredCompositePKs);
  18945. jsonStatements.push(...jsonAddedUniqueConstraints);
  18946. jsonStatements.push(...jsonCreatedCheckConstraints);
  18947. jsonStatements.push(...jsonAlteredUniqueConstraints);
  18948. jsonStatements.push(...createViews);
  18949. jsonStatements.push(...jsonRenamePoliciesStatements);
  18950. jsonStatements.push(...jsonDropPoliciesStatements);
  18951. jsonStatements.push(...jsonCreatePoliciesStatements);
  18952. jsonStatements.push(...jsonAlterPoliciesStatements);
  18953. jsonStatements.push(...jsonRenameIndPoliciesStatements);
  18954. jsonStatements.push(...jsonDropIndPoliciesStatements);
  18955. jsonStatements.push(...jsonCreateIndPoliciesStatements);
  18956. jsonStatements.push(...jsonAlterIndPoliciesStatements);
  18957. jsonStatements.push(...dropEnums);
  18958. jsonStatements.push(...dropSequences);
  18959. jsonStatements.push(...dropSchemas);
  18960. const filteredJsonStatements = jsonStatements.filter((st) => {
  18961. if (st.type === "alter_table_alter_column_drop_notnull") {
  18962. if (jsonStatements.find(
  18963. (it) => it.type === "alter_table_alter_column_drop_identity" && it.tableName === st.tableName && it.schema === st.schema
  18964. )) {
  18965. return false;
  18966. }
  18967. }
  18968. if (st.type === "alter_table_alter_column_set_notnull") {
  18969. if (jsonStatements.find(
  18970. (it) => it.type === "alter_table_alter_column_set_identity" && it.tableName === st.tableName && it.schema === st.schema
  18971. )) {
  18972. return false;
  18973. }
  18974. }
  18975. return true;
  18976. });
  18977. const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => {
  18978. if (st.type === "alter_type_add_value") {
  18979. if (filteredJsonStatements.find(
  18980. (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.enumSchema === st.schema
  18981. )) {
  18982. return false;
  18983. }
  18984. }
  18985. return true;
  18986. });
  18987. const filteredEnums2JsonStatements = filteredEnumsJsonStatements.filter((st) => {
  18988. if (st.type === "alter_table_alter_column_set_default") {
  18989. if (filteredEnumsJsonStatements.find(
  18990. (it) => it.type === "pg_alter_table_alter_column_set_type" && it.columnDefault === st.newDefaultValue && it.columnName === st.columnName && it.tableName === st.tableName && it.schema === st.schema
  18991. )) {
  18992. return false;
  18993. }
  18994. if (filteredEnumsJsonStatements.find(
  18995. (it) => it.type === "alter_type_drop_value" && it.columnsWithEnum.find(
  18996. (column6) => column6.default === st.newDefaultValue && column6.column === st.columnName && column6.table === st.tableName && column6.tableSchema === st.schema
  18997. )
  18998. )) {
  18999. return false;
  19000. }
  19001. }
  19002. return true;
  19003. });
  19004. const sqlStatements = fromJson(filteredEnums2JsonStatements, "postgresql", action);
  19005. const uniqueSqlStatements = [];
  19006. sqlStatements.forEach((ss) => {
  19007. if (!uniqueSqlStatements.includes(ss)) {
  19008. uniqueSqlStatements.push(ss);
  19009. }
  19010. });
  19011. const rSchemas = renamedSchemas.map((it) => ({
  19012. from: it.from.name,
  19013. to: it.to.name
  19014. }));
  19015. const rTables = renamedTables.map((it) => {
  19016. return { from: it.from, to: it.to };
  19017. });
  19018. const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
  19019. return {
  19020. statements: filteredEnums2JsonStatements,
  19021. sqlStatements: uniqueSqlStatements,
  19022. _meta
  19023. };
  19024. };
  19025. applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
  19026. for (const tableName in json1.tables) {
  19027. const table6 = json1.tables[tableName];
  19028. for (const indexName2 in table6.indexes) {
  19029. const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName2]);
  19030. if (index6.isUnique) {
  19031. table6.uniqueConstraints[indexName2] = MySqlSquasher.squashUnique({
  19032. name: index6.name,
  19033. columns: index6.columns
  19034. });
  19035. delete json1.tables[tableName].indexes[index6.name];
  19036. }
  19037. }
  19038. }
  19039. for (const tableName in json2.tables) {
  19040. const table6 = json2.tables[tableName];
  19041. for (const indexName2 in table6.indexes) {
  19042. const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName2]);
  19043. if (index6.isUnique) {
  19044. table6.uniqueConstraints[indexName2] = MySqlSquasher.squashUnique({
  19045. name: index6.name,
  19046. columns: index6.columns
  19047. });
  19048. delete json2.tables[tableName].indexes[index6.name];
  19049. }
  19050. }
  19051. }
  19052. const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
  19053. const {
  19054. created: createdTables,
  19055. deleted: deletedTables,
  19056. renamed: renamedTables
  19057. // renamed or moved
  19058. } = await tablesResolver2({
  19059. created: tablesDiff.added,
  19060. deleted: tablesDiff.deleted
  19061. });
  19062. const tablesPatchedSnap1 = copy(json1);
  19063. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  19064. const { name } = nameChangeFor(it, renamedTables);
  19065. it.name = name;
  19066. return [name, it];
  19067. });
  19068. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  19069. const columnRenames = [];
  19070. const columnCreates = [];
  19071. const columnDeletes = [];
  19072. for (let entry of Object.values(res)) {
  19073. const { renamed, created, deleted } = await columnsResolver2({
  19074. tableName: entry.name,
  19075. schema: entry.schema,
  19076. deleted: entry.columns.deleted,
  19077. created: entry.columns.added
  19078. });
  19079. if (created.length > 0) {
  19080. columnCreates.push({
  19081. table: entry.name,
  19082. columns: created
  19083. });
  19084. }
  19085. if (deleted.length > 0) {
  19086. columnDeletes.push({
  19087. table: entry.name,
  19088. columns: deleted
  19089. });
  19090. }
  19091. if (renamed.length > 0) {
  19092. columnRenames.push({
  19093. table: entry.name,
  19094. renames: renamed
  19095. });
  19096. }
  19097. }
  19098. const columnRenamesDict = columnRenames.reduce(
  19099. (acc, it) => {
  19100. acc[it.table] = it.renames;
  19101. return acc;
  19102. },
  19103. {}
  19104. );
  19105. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  19106. columnsPatchedSnap1.tables = mapEntries(
  19107. columnsPatchedSnap1.tables,
  19108. (tableKey2, tableValue) => {
  19109. const patchedColumns = mapKeys(
  19110. tableValue.columns,
  19111. (columnKey, column6) => {
  19112. const rens = columnRenamesDict[tableValue.name] || [];
  19113. const newName = columnChangeFor(columnKey, rens);
  19114. column6.name = newName;
  19115. return newName;
  19116. }
  19117. );
  19118. tableValue.columns = patchedColumns;
  19119. return [tableKey2, tableValue];
  19120. }
  19121. );
  19122. const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
  19123. const {
  19124. created: createdViews,
  19125. deleted: deletedViews,
  19126. renamed: renamedViews
  19127. // renamed or moved
  19128. } = await viewsResolver2({
  19129. created: viewsDiff.added,
  19130. deleted: viewsDiff.deleted
  19131. });
  19132. const renamesViewDic = {};
  19133. renamedViews.forEach((it) => {
  19134. renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
  19135. });
  19136. const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
  19137. viewsPatchedSnap1.views = mapEntries(
  19138. viewsPatchedSnap1.views,
  19139. (viewKey, viewValue) => {
  19140. const rename = renamesViewDic[viewValue.name];
  19141. if (rename) {
  19142. viewValue.name = rename.to;
  19143. viewKey = rename.to;
  19144. }
  19145. return [viewKey, viewValue];
  19146. }
  19147. );
  19148. const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
  19149. const typedResult = diffResultSchemeMysql.parse(diffResult);
  19150. const jsonStatements = [];
  19151. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  19152. return prepareCreateIndexesJson(
  19153. it.name,
  19154. it.schema,
  19155. it.indexes,
  19156. curFull.internal
  19157. );
  19158. }).flat();
  19159. const jsonDropTables = deletedTables.map((it) => {
  19160. return prepareDropTableJson(it);
  19161. });
  19162. const jsonRenameTables = renamedTables.map((it) => {
  19163. return prepareRenameTableJson(it.from, it.to);
  19164. });
  19165. const alteredTables = typedResult.alteredTablesWithColumns;
  19166. const jsonAddedCompositePKs = [];
  19167. const jsonDeletedCompositePKs = [];
  19168. const jsonAlteredCompositePKs = [];
  19169. const jsonAddedUniqueConstraints = [];
  19170. const jsonDeletedUniqueConstraints = [];
  19171. const jsonAlteredUniqueConstraints = [];
  19172. const jsonCreatedCheckConstraints = [];
  19173. const jsonDeletedCheckConstraints = [];
  19174. const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
  19175. const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
  19176. const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
  19177. alteredTables.forEach((it) => {
  19178. let addedColumns = [];
  19179. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  19180. const addedPkColumns = it.addedCompositePKs[addedPkName];
  19181. addedColumns = MySqlSquasher.unsquashPK(addedPkColumns).columns;
  19182. }
  19183. let deletedColumns = [];
  19184. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  19185. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  19186. deletedColumns = MySqlSquasher.unsquashPK(deletedPkColumns).columns;
  19187. }
  19188. const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
  19189. let addedCompositePKs = [];
  19190. let deletedCompositePKs = [];
  19191. let alteredCompositePKs = [];
  19192. addedCompositePKs = prepareAddCompositePrimaryKeyMySql(
  19193. it.name,
  19194. it.addedCompositePKs,
  19195. prevFull,
  19196. curFull
  19197. );
  19198. deletedCompositePKs = prepareDeleteCompositePrimaryKeyMySql(
  19199. it.name,
  19200. it.deletedCompositePKs,
  19201. prevFull
  19202. );
  19203. alteredCompositePKs = prepareAlterCompositePrimaryKeyMySql(
  19204. it.name,
  19205. it.alteredCompositePKs,
  19206. prevFull,
  19207. curFull
  19208. );
  19209. let addedUniqueConstraints = [];
  19210. let deletedUniqueConstraints = [];
  19211. let alteredUniqueConstraints = [];
  19212. let createdCheckConstraints = [];
  19213. let deletedCheckConstraints = [];
  19214. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  19215. it.name,
  19216. it.schema,
  19217. it.addedUniqueConstraints
  19218. );
  19219. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  19220. it.name,
  19221. it.schema,
  19222. it.deletedUniqueConstraints
  19223. );
  19224. if (it.alteredUniqueConstraints) {
  19225. const added = {};
  19226. const deleted = {};
  19227. for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
  19228. added[k5] = it.alteredUniqueConstraints[k5].__new;
  19229. deleted[k5] = it.alteredUniqueConstraints[k5].__old;
  19230. }
  19231. addedUniqueConstraints.push(
  19232. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  19233. );
  19234. deletedUniqueConstraints.push(
  19235. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  19236. );
  19237. }
  19238. createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  19239. deletedCheckConstraints = prepareDeleteCheckConstraint(
  19240. it.name,
  19241. it.schema,
  19242. it.deletedCheckConstraints
  19243. );
  19244. if (it.alteredCheckConstraints && action !== "push") {
  19245. const added = {};
  19246. const deleted = {};
  19247. for (const k5 of Object.keys(it.alteredCheckConstraints)) {
  19248. added[k5] = it.alteredCheckConstraints[k5].__new;
  19249. deleted[k5] = it.alteredCheckConstraints[k5].__old;
  19250. }
  19251. createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  19252. deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
  19253. }
  19254. jsonAddedCompositePKs.push(...addedCompositePKs);
  19255. jsonDeletedCompositePKs.push(...deletedCompositePKs);
  19256. jsonAlteredCompositePKs.push(...alteredCompositePKs);
  19257. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  19258. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  19259. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  19260. jsonCreatedCheckConstraints.push(...createdCheckConstraints);
  19261. jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
  19262. });
  19263. const rColumns = jsonRenameColumnsStatements.map((it) => {
  19264. const tableName = it.tableName;
  19265. const schema6 = it.schema;
  19266. return {
  19267. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  19268. to: { schema: schema6, table: tableName, column: it.newColumnName }
  19269. };
  19270. });
  19271. const jsonTableAlternations = alteredTables.map((it) => {
  19272. return prepareAlterColumnsMysql(
  19273. it.name,
  19274. it.schema,
  19275. it.altered,
  19276. json1,
  19277. json2,
  19278. action
  19279. );
  19280. }).flat();
  19281. const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
  19282. return prepareCreateIndexesJson(
  19283. it.name,
  19284. it.schema,
  19285. it.addedIndexes || {},
  19286. curFull.internal
  19287. );
  19288. }).flat();
  19289. const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
  19290. return prepareDropIndexesJson(
  19291. it.name,
  19292. it.schema,
  19293. it.deletedIndexes || {}
  19294. );
  19295. }).flat();
  19296. alteredTables.forEach((it) => {
  19297. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  19298. (current, item) => {
  19299. current[item] = it.alteredIndexes[item].__old;
  19300. return current;
  19301. },
  19302. {}
  19303. );
  19304. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  19305. (current, item) => {
  19306. current[item] = it.alteredIndexes[item].__new;
  19307. return current;
  19308. },
  19309. {}
  19310. );
  19311. jsonCreateIndexesForAllAlteredTables.push(
  19312. ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
  19313. );
  19314. jsonDropIndexesForAllAlteredTables.push(
  19315. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  19316. );
  19317. });
  19318. const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
  19319. return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
  19320. }).flat();
  19321. const jsonReferencesForAllAlteredTables = alteredTables.map((it) => {
  19322. const forAdded = prepareCreateReferencesJson(
  19323. it.name,
  19324. it.schema,
  19325. it.addedForeignKeys
  19326. );
  19327. const forAltered = prepareDropReferencesJson(
  19328. it.name,
  19329. it.schema,
  19330. it.deletedForeignKeys
  19331. );
  19332. const alteredFKs = prepareAlterReferencesJson(
  19333. it.name,
  19334. it.schema,
  19335. it.alteredForeignKeys
  19336. );
  19337. return [...forAdded, ...forAltered, ...alteredFKs];
  19338. }).flat();
  19339. const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  19340. (t6) => t6.type === "create_reference"
  19341. );
  19342. const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  19343. (t6) => t6.type === "delete_reference"
  19344. );
  19345. const jsonMySqlCreateTables = createdTables.map((it) => {
  19346. return prepareMySqlCreateTableJson(
  19347. it,
  19348. curFull,
  19349. curFull.internal
  19350. );
  19351. });
  19352. const createViews = [];
  19353. const dropViews = [];
  19354. const renameViews = [];
  19355. const alterViews = [];
  19356. createViews.push(
  19357. ...createdViews.filter((it) => !it.isExisting).map((it) => {
  19358. return prepareMySqlCreateViewJson(
  19359. it.name,
  19360. it.definition,
  19361. it.meta
  19362. );
  19363. })
  19364. );
  19365. dropViews.push(
  19366. ...deletedViews.filter((it) => !it.isExisting).map((it) => {
  19367. return prepareDropViewJson(it.name);
  19368. })
  19369. );
  19370. renameViews.push(
  19371. ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
  19372. return prepareRenameViewJson(it.to.name, it.from.name);
  19373. })
  19374. );
  19375. const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
  19376. for (const alteredView of alteredViews) {
  19377. const { definition, meta } = json2.views[alteredView.name];
  19378. if (alteredView.alteredExisting) {
  19379. dropViews.push(prepareDropViewJson(alteredView.name));
  19380. createViews.push(
  19381. prepareMySqlCreateViewJson(
  19382. alteredView.name,
  19383. definition,
  19384. meta
  19385. )
  19386. );
  19387. continue;
  19388. }
  19389. if (alteredView.alteredDefinition && action !== "push") {
  19390. createViews.push(
  19391. prepareMySqlCreateViewJson(
  19392. alteredView.name,
  19393. definition,
  19394. meta,
  19395. true
  19396. )
  19397. );
  19398. continue;
  19399. }
  19400. if (alteredView.alteredMeta) {
  19401. const view5 = curFull["views"][alteredView.name];
  19402. alterViews.push(
  19403. prepareMySqlAlterView(view5)
  19404. );
  19405. }
  19406. }
  19407. jsonStatements.push(...jsonMySqlCreateTables);
  19408. jsonStatements.push(...jsonDropTables);
  19409. jsonStatements.push(...jsonRenameTables);
  19410. jsonStatements.push(...jsonRenameColumnsStatements);
  19411. jsonStatements.push(...dropViews);
  19412. jsonStatements.push(...renameViews);
  19413. jsonStatements.push(...alterViews);
  19414. jsonStatements.push(...jsonDeletedUniqueConstraints);
  19415. jsonStatements.push(...jsonDeletedCheckConstraints);
  19416. jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
  19417. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  19418. jsonStatements.push(...jsonDeletedCompositePKs);
  19419. jsonStatements.push(...jsonTableAlternations);
  19420. jsonStatements.push(...jsonAddedCompositePKs);
  19421. jsonStatements.push(...jsonAddColumnsStatemets);
  19422. jsonStatements.push(...jsonAddedUniqueConstraints);
  19423. jsonStatements.push(...jsonDeletedUniqueConstraints);
  19424. jsonStatements.push(...jsonCreateReferencesForCreatedTables);
  19425. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  19426. jsonStatements.push(...jsonCreatedCheckConstraints);
  19427. jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
  19428. jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
  19429. jsonStatements.push(...jsonDropColumnsStatemets);
  19430. jsonStatements.push(...jsonAlteredCompositePKs);
  19431. jsonStatements.push(...createViews);
  19432. jsonStatements.push(...jsonAlteredUniqueConstraints);
  19433. const sqlStatements = fromJson(jsonStatements, "mysql");
  19434. const uniqueSqlStatements = [];
  19435. sqlStatements.forEach((ss) => {
  19436. if (!uniqueSqlStatements.includes(ss)) {
  19437. uniqueSqlStatements.push(ss);
  19438. }
  19439. });
  19440. const rTables = renamedTables.map((it) => {
  19441. return { from: it.from, to: it.to };
  19442. });
  19443. const _meta = prepareMigrationMeta([], rTables, rColumns);
  19444. return {
  19445. statements: jsonStatements,
  19446. sqlStatements: uniqueSqlStatements,
  19447. _meta
  19448. };
  19449. };
  19450. applySingleStoreSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
  19451. for (const tableName in json1.tables) {
  19452. const table6 = json1.tables[tableName];
  19453. for (const indexName2 in table6.indexes) {
  19454. const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName2]);
  19455. if (index6.isUnique) {
  19456. table6.uniqueConstraints[indexName2] = SingleStoreSquasher.squashUnique({
  19457. name: index6.name,
  19458. columns: index6.columns
  19459. });
  19460. delete json1.tables[tableName].indexes[index6.name];
  19461. }
  19462. }
  19463. }
  19464. for (const tableName in json2.tables) {
  19465. const table6 = json2.tables[tableName];
  19466. for (const indexName2 in table6.indexes) {
  19467. const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName2]);
  19468. if (index6.isUnique) {
  19469. table6.uniqueConstraints[indexName2] = SingleStoreSquasher.squashUnique({
  19470. name: index6.name,
  19471. columns: index6.columns
  19472. });
  19473. delete json2.tables[tableName].indexes[index6.name];
  19474. }
  19475. }
  19476. }
  19477. const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
  19478. const {
  19479. created: createdTables,
  19480. deleted: deletedTables,
  19481. renamed: renamedTables
  19482. // renamed or moved
  19483. } = await tablesResolver2({
  19484. created: tablesDiff.added,
  19485. deleted: tablesDiff.deleted
  19486. });
  19487. const tablesPatchedSnap1 = copy(json1);
  19488. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  19489. const { name } = nameChangeFor(it, renamedTables);
  19490. it.name = name;
  19491. return [name, it];
  19492. });
  19493. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  19494. const columnRenames = [];
  19495. const columnCreates = [];
  19496. const columnDeletes = [];
  19497. for (let entry of Object.values(res)) {
  19498. const { renamed, created, deleted } = await columnsResolver2({
  19499. tableName: entry.name,
  19500. schema: entry.schema,
  19501. deleted: entry.columns.deleted,
  19502. created: entry.columns.added
  19503. });
  19504. if (created.length > 0) {
  19505. columnCreates.push({
  19506. table: entry.name,
  19507. columns: created
  19508. });
  19509. }
  19510. if (deleted.length > 0) {
  19511. columnDeletes.push({
  19512. table: entry.name,
  19513. columns: deleted
  19514. });
  19515. }
  19516. if (renamed.length > 0) {
  19517. columnRenames.push({
  19518. table: entry.name,
  19519. renames: renamed
  19520. });
  19521. }
  19522. }
  19523. const columnRenamesDict = columnRenames.reduce(
  19524. (acc, it) => {
  19525. acc[it.table] = it.renames;
  19526. return acc;
  19527. },
  19528. {}
  19529. );
  19530. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  19531. columnsPatchedSnap1.tables = mapEntries(
  19532. columnsPatchedSnap1.tables,
  19533. (tableKey2, tableValue) => {
  19534. const patchedColumns = mapKeys(
  19535. tableValue.columns,
  19536. (columnKey, column6) => {
  19537. const rens = columnRenamesDict[tableValue.name] || [];
  19538. const newName = columnChangeFor(columnKey, rens);
  19539. column6.name = newName;
  19540. return newName;
  19541. }
  19542. );
  19543. tableValue.columns = patchedColumns;
  19544. return [tableKey2, tableValue];
  19545. }
  19546. );
  19547. const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
  19548. const typedResult = diffResultSchemeSingleStore.parse(diffResult);
  19549. const jsonStatements = [];
  19550. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  19551. return prepareCreateIndexesJson(
  19552. it.name,
  19553. it.schema,
  19554. it.indexes,
  19555. curFull.internal
  19556. );
  19557. }).flat();
  19558. const jsonDropTables = deletedTables.map((it) => {
  19559. return prepareDropTableJson(it);
  19560. });
  19561. const jsonRenameTables = renamedTables.map((it) => {
  19562. return prepareRenameTableJson(it.from, it.to);
  19563. });
  19564. const alteredTables = typedResult.alteredTablesWithColumns;
  19565. const jsonAddedCompositePKs = [];
  19566. const jsonAddedUniqueConstraints = [];
  19567. const jsonDeletedUniqueConstraints = [];
  19568. const jsonAlteredUniqueConstraints = [];
  19569. const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
  19570. const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
  19571. const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
  19572. alteredTables.forEach((it) => {
  19573. let addedColumns = [];
  19574. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  19575. const addedPkColumns = it.addedCompositePKs[addedPkName];
  19576. addedColumns = SingleStoreSquasher.unsquashPK(addedPkColumns).columns;
  19577. }
  19578. let deletedColumns = [];
  19579. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  19580. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  19581. deletedColumns = SingleStoreSquasher.unsquashPK(deletedPkColumns).columns;
  19582. }
  19583. const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
  19584. let addedUniqueConstraints = [];
  19585. let deletedUniqueConstraints = [];
  19586. let alteredUniqueConstraints = [];
  19587. let createdCheckConstraints = [];
  19588. let deletedCheckConstraints = [];
  19589. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  19590. it.name,
  19591. it.schema,
  19592. it.addedUniqueConstraints
  19593. );
  19594. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  19595. it.name,
  19596. it.schema,
  19597. it.deletedUniqueConstraints
  19598. );
  19599. if (it.alteredUniqueConstraints) {
  19600. const added = {};
  19601. const deleted = {};
  19602. for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
  19603. added[k5] = it.alteredUniqueConstraints[k5].__new;
  19604. deleted[k5] = it.alteredUniqueConstraints[k5].__old;
  19605. }
  19606. addedUniqueConstraints.push(
  19607. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  19608. );
  19609. deletedUniqueConstraints.push(
  19610. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  19611. );
  19612. }
  19613. createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  19614. deletedCheckConstraints = prepareDeleteCheckConstraint(
  19615. it.name,
  19616. it.schema,
  19617. it.deletedCheckConstraints
  19618. );
  19619. if (it.alteredCheckConstraints && action !== "push") {
  19620. const added = {};
  19621. const deleted = {};
  19622. for (const k5 of Object.keys(it.alteredCheckConstraints)) {
  19623. added[k5] = it.alteredCheckConstraints[k5].__new;
  19624. deleted[k5] = it.alteredCheckConstraints[k5].__old;
  19625. }
  19626. createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  19627. deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
  19628. }
  19629. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  19630. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  19631. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  19632. });
  19633. const rColumns = jsonRenameColumnsStatements.map((it) => {
  19634. const tableName = it.tableName;
  19635. const schema6 = it.schema;
  19636. return {
  19637. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  19638. to: { schema: schema6, table: tableName, column: it.newColumnName }
  19639. };
  19640. });
  19641. const jsonTableAlternations = alteredTables.map((it) => {
  19642. return prepareAlterColumnsMysql(
  19643. it.name,
  19644. it.schema,
  19645. it.altered,
  19646. json1,
  19647. json2,
  19648. action
  19649. );
  19650. }).flat();
  19651. const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
  19652. return prepareCreateIndexesJson(
  19653. it.name,
  19654. it.schema,
  19655. it.addedIndexes || {},
  19656. curFull.internal
  19657. );
  19658. }).flat();
  19659. const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
  19660. return prepareDropIndexesJson(
  19661. it.name,
  19662. it.schema,
  19663. it.deletedIndexes || {}
  19664. );
  19665. }).flat();
  19666. alteredTables.forEach((it) => {
  19667. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  19668. (current, item) => {
  19669. current[item] = it.alteredIndexes[item].__old;
  19670. return current;
  19671. },
  19672. {}
  19673. );
  19674. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  19675. (current, item) => {
  19676. current[item] = it.alteredIndexes[item].__new;
  19677. return current;
  19678. },
  19679. {}
  19680. );
  19681. jsonCreateIndexesForAllAlteredTables.push(
  19682. ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
  19683. );
  19684. jsonDropIndexesForAllAlteredTables.push(
  19685. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  19686. );
  19687. });
  19688. const jsonSingleStoreCreateTables = createdTables.map((it) => {
  19689. return prepareSingleStoreCreateTableJson(
  19690. it,
  19691. curFull,
  19692. curFull.internal
  19693. );
  19694. });
  19695. jsonStatements.push(...jsonSingleStoreCreateTables);
  19696. jsonStatements.push(...jsonDropTables);
  19697. jsonStatements.push(...jsonRenameTables);
  19698. jsonStatements.push(...jsonRenameColumnsStatements);
  19699. jsonStatements.push(...jsonDeletedUniqueConstraints);
  19700. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  19701. jsonStatements.push(...jsonTableAlternations);
  19702. jsonStatements.push(...jsonAddedCompositePKs);
  19703. jsonStatements.push(...jsonAddedUniqueConstraints);
  19704. jsonStatements.push(...jsonDeletedUniqueConstraints);
  19705. jsonStatements.push(...jsonAddColumnsStatemets);
  19706. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  19707. jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
  19708. jsonStatements.push(...jsonDropColumnsStatemets);
  19709. jsonStatements.push(...jsonAddedCompositePKs);
  19710. jsonStatements.push(...jsonAlteredUniqueConstraints);
  19711. const combinedJsonStatements = singleStoreCombineStatements(jsonStatements, json2);
  19712. const sqlStatements = fromJson(combinedJsonStatements, "singlestore");
  19713. const uniqueSqlStatements = [];
  19714. sqlStatements.forEach((ss) => {
  19715. if (!uniqueSqlStatements.includes(ss)) {
  19716. uniqueSqlStatements.push(ss);
  19717. }
  19718. });
  19719. const rTables = renamedTables.map((it) => {
  19720. return { from: it.from, to: it.to };
  19721. });
  19722. const _meta = prepareMigrationMeta([], rTables, rColumns);
  19723. return {
  19724. statements: combinedJsonStatements,
  19725. sqlStatements: uniqueSqlStatements,
  19726. _meta
  19727. };
  19728. };
  19729. applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
  19730. const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
  19731. const {
  19732. created: createdTables,
  19733. deleted: deletedTables,
  19734. renamed: renamedTables
  19735. } = await tablesResolver2({
  19736. created: tablesDiff.added,
  19737. deleted: tablesDiff.deleted
  19738. });
  19739. const tablesPatchedSnap1 = copy(json1);
  19740. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  19741. const { name } = nameChangeFor(it, renamedTables);
  19742. it.name = name;
  19743. return [name, it];
  19744. });
  19745. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  19746. const columnRenames = [];
  19747. const columnCreates = [];
  19748. const columnDeletes = [];
  19749. for (let entry of Object.values(res)) {
  19750. const { renamed, created, deleted } = await columnsResolver2({
  19751. tableName: entry.name,
  19752. schema: entry.schema,
  19753. deleted: entry.columns.deleted,
  19754. created: entry.columns.added
  19755. });
  19756. if (created.length > 0) {
  19757. columnCreates.push({
  19758. table: entry.name,
  19759. columns: created
  19760. });
  19761. }
  19762. if (deleted.length > 0) {
  19763. columnDeletes.push({
  19764. table: entry.name,
  19765. columns: deleted
  19766. });
  19767. }
  19768. if (renamed.length > 0) {
  19769. columnRenames.push({
  19770. table: entry.name,
  19771. renames: renamed
  19772. });
  19773. }
  19774. }
  19775. const columnRenamesDict = columnRenames.reduce(
  19776. (acc, it) => {
  19777. acc[it.table] = it.renames;
  19778. return acc;
  19779. },
  19780. {}
  19781. );
  19782. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  19783. columnsPatchedSnap1.tables = mapEntries(
  19784. columnsPatchedSnap1.tables,
  19785. (tableKey2, tableValue) => {
  19786. const patchedColumns = mapKeys(
  19787. tableValue.columns,
  19788. (columnKey, column6) => {
  19789. const rens = columnRenamesDict[tableValue.name] || [];
  19790. const newName = columnChangeFor(columnKey, rens);
  19791. column6.name = newName;
  19792. return newName;
  19793. }
  19794. );
  19795. tableValue.columns = patchedColumns;
  19796. return [tableKey2, tableValue];
  19797. }
  19798. );
  19799. const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
  19800. const {
  19801. created: createdViews,
  19802. deleted: deletedViews,
  19803. renamed: renamedViews
  19804. // renamed or moved
  19805. } = await viewsResolver2({
  19806. created: viewsDiff.added,
  19807. deleted: viewsDiff.deleted
  19808. });
  19809. const renamesViewDic = {};
  19810. renamedViews.forEach((it) => {
  19811. renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
  19812. });
  19813. const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
  19814. viewsPatchedSnap1.views = mapEntries(
  19815. viewsPatchedSnap1.views,
  19816. (viewKey, viewValue) => {
  19817. const rename = renamesViewDic[viewValue.name];
  19818. if (rename) {
  19819. viewValue.name = rename.to;
  19820. }
  19821. return [viewKey, viewValue];
  19822. }
  19823. );
  19824. const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
  19825. const typedResult = diffResultSchemeSQLite.parse(diffResult);
  19826. const tablesMap = {};
  19827. typedResult.alteredTablesWithColumns.forEach((obj) => {
  19828. tablesMap[obj.name] = obj;
  19829. });
  19830. const jsonCreateTables = createdTables.map((it) => {
  19831. return prepareSQLiteCreateTable(it, action);
  19832. });
  19833. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  19834. return prepareCreateIndexesJson(
  19835. it.name,
  19836. it.schema,
  19837. it.indexes,
  19838. curFull.internal
  19839. );
  19840. }).flat();
  19841. const jsonDropTables = deletedTables.map((it) => {
  19842. return prepareDropTableJson(it);
  19843. });
  19844. const jsonRenameTables = renamedTables.map((it) => {
  19845. return prepareRenameTableJson(it.from, it.to);
  19846. });
  19847. const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
  19848. const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
  19849. const jsonAddColumnsStatemets = columnCreates.map((it) => {
  19850. return _prepareSqliteAddColumns(
  19851. it.table,
  19852. it.columns,
  19853. tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
  19854. );
  19855. }).flat();
  19856. const allAltered = typedResult.alteredTablesWithColumns;
  19857. const jsonAddedCompositePKs = [];
  19858. const jsonDeletedCompositePKs = [];
  19859. const jsonAlteredCompositePKs = [];
  19860. const jsonAddedUniqueConstraints = [];
  19861. const jsonDeletedUniqueConstraints = [];
  19862. const jsonAlteredUniqueConstraints = [];
  19863. const jsonDeletedCheckConstraints = [];
  19864. const jsonCreatedCheckConstraints = [];
  19865. allAltered.forEach((it) => {
  19866. let addedColumns = [];
  19867. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  19868. const addedPkColumns = it.addedCompositePKs[addedPkName];
  19869. addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
  19870. }
  19871. let deletedColumns = [];
  19872. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  19873. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  19874. deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
  19875. }
  19876. const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
  19877. let addedCompositePKs = [];
  19878. let deletedCompositePKs = [];
  19879. let alteredCompositePKs = [];
  19880. if (doPerformDeleteAndCreate) {
  19881. addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
  19882. it.name,
  19883. it.addedCompositePKs
  19884. );
  19885. deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
  19886. it.name,
  19887. it.deletedCompositePKs
  19888. );
  19889. }
  19890. alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
  19891. it.name,
  19892. it.alteredCompositePKs
  19893. );
  19894. let addedUniqueConstraints = [];
  19895. let deletedUniqueConstraints = [];
  19896. let alteredUniqueConstraints = [];
  19897. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  19898. it.name,
  19899. it.schema,
  19900. it.addedUniqueConstraints
  19901. );
  19902. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  19903. it.name,
  19904. it.schema,
  19905. it.deletedUniqueConstraints
  19906. );
  19907. if (it.alteredUniqueConstraints) {
  19908. const added = {};
  19909. const deleted = {};
  19910. for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
  19911. added[k5] = it.alteredUniqueConstraints[k5].__new;
  19912. deleted[k5] = it.alteredUniqueConstraints[k5].__old;
  19913. }
  19914. addedUniqueConstraints.push(
  19915. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  19916. );
  19917. deletedUniqueConstraints.push(
  19918. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  19919. );
  19920. }
  19921. let createdCheckConstraints = [];
  19922. let deletedCheckConstraints = [];
  19923. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  19924. it.name,
  19925. it.schema,
  19926. it.addedUniqueConstraints
  19927. );
  19928. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  19929. it.name,
  19930. it.schema,
  19931. it.deletedUniqueConstraints
  19932. );
  19933. if (it.alteredUniqueConstraints) {
  19934. const added = {};
  19935. const deleted = {};
  19936. for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
  19937. added[k5] = it.alteredUniqueConstraints[k5].__new;
  19938. deleted[k5] = it.alteredUniqueConstraints[k5].__old;
  19939. }
  19940. addedUniqueConstraints.push(
  19941. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  19942. );
  19943. deletedUniqueConstraints.push(
  19944. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  19945. );
  19946. }
  19947. createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  19948. deletedCheckConstraints = prepareDeleteCheckConstraint(
  19949. it.name,
  19950. it.schema,
  19951. it.deletedCheckConstraints
  19952. );
  19953. if (it.alteredCheckConstraints && action !== "push") {
  19954. const added = {};
  19955. const deleted = {};
  19956. for (const k5 of Object.keys(it.alteredCheckConstraints)) {
  19957. added[k5] = it.alteredCheckConstraints[k5].__new;
  19958. deleted[k5] = it.alteredCheckConstraints[k5].__old;
  19959. }
  19960. createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  19961. deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
  19962. }
  19963. jsonAddedCompositePKs.push(...addedCompositePKs);
  19964. jsonDeletedCompositePKs.push(...deletedCompositePKs);
  19965. jsonAlteredCompositePKs.push(...alteredCompositePKs);
  19966. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  19967. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  19968. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  19969. jsonCreatedCheckConstraints.push(...createdCheckConstraints);
  19970. jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
  19971. });
  19972. const rColumns = jsonRenameColumnsStatements.map((it) => {
  19973. const tableName = it.tableName;
  19974. const schema6 = it.schema;
  19975. return {
  19976. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  19977. to: { schema: schema6, table: tableName, column: it.newColumnName }
  19978. };
  19979. });
  19980. const jsonTableAlternations = allAltered.map((it) => {
  19981. return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
  19982. }).flat();
  19983. const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
  19984. return prepareCreateIndexesJson(
  19985. it.name,
  19986. it.schema,
  19987. it.addedIndexes || {},
  19988. curFull.internal
  19989. );
  19990. }).flat();
  19991. const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
  19992. return prepareDropIndexesJson(
  19993. it.name,
  19994. it.schema,
  19995. it.deletedIndexes || {}
  19996. );
  19997. }).flat();
  19998. allAltered.forEach((it) => {
  19999. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  20000. (current, item) => {
  20001. current[item] = it.alteredIndexes[item].__old;
  20002. return current;
  20003. },
  20004. {}
  20005. );
  20006. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  20007. (current, item) => {
  20008. current[item] = it.alteredIndexes[item].__new;
  20009. return current;
  20010. },
  20011. {}
  20012. );
  20013. jsonCreateIndexesForAllAlteredTables.push(
  20014. ...prepareCreateIndexesJson(
  20015. it.name,
  20016. it.schema,
  20017. createdIndexes || {},
  20018. curFull.internal
  20019. )
  20020. );
  20021. jsonDropIndexesForAllAlteredTables.push(
  20022. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  20023. );
  20024. });
  20025. const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
  20026. const forAdded = prepareCreateReferencesJson(
  20027. it.name,
  20028. it.schema,
  20029. it.addedForeignKeys
  20030. );
  20031. const forAltered = prepareDropReferencesJson(
  20032. it.name,
  20033. it.schema,
  20034. it.deletedForeignKeys
  20035. );
  20036. const alteredFKs = prepareAlterReferencesJson(
  20037. it.name,
  20038. it.schema,
  20039. it.alteredForeignKeys
  20040. );
  20041. return [...forAdded, ...forAltered, ...alteredFKs];
  20042. }).flat();
  20043. const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  20044. (t6) => t6.type === "create_reference"
  20045. );
  20046. const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  20047. (t6) => t6.type === "delete_reference"
  20048. );
  20049. const createViews = [];
  20050. const dropViews = [];
  20051. createViews.push(
  20052. ...createdViews.filter((it) => !it.isExisting).map((it) => {
  20053. return prepareSqliteCreateViewJson(
  20054. it.name,
  20055. it.definition
  20056. );
  20057. })
  20058. );
  20059. dropViews.push(
  20060. ...deletedViews.filter((it) => !it.isExisting).map((it) => {
  20061. return prepareDropViewJson(it.name);
  20062. })
  20063. );
  20064. dropViews.push(
  20065. ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
  20066. return prepareDropViewJson(it.from.name);
  20067. })
  20068. );
  20069. createViews.push(
  20070. ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
  20071. return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
  20072. })
  20073. );
  20074. const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
  20075. for (const alteredView of alteredViews) {
  20076. const { definition } = json2.views[alteredView.name];
  20077. if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
  20078. dropViews.push(prepareDropViewJson(alteredView.name));
  20079. createViews.push(
  20080. prepareSqliteCreateViewJson(
  20081. alteredView.name,
  20082. definition
  20083. )
  20084. );
  20085. }
  20086. }
  20087. const jsonStatements = [];
  20088. jsonStatements.push(...jsonCreateTables);
  20089. jsonStatements.push(...jsonDropTables);
  20090. jsonStatements.push(...jsonRenameTables);
  20091. jsonStatements.push(...jsonRenameColumnsStatements);
  20092. jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
  20093. jsonStatements.push(...jsonDeletedCheckConstraints);
  20094. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  20095. jsonStatements.push(...jsonDeletedCompositePKs);
  20096. jsonStatements.push(...jsonTableAlternations);
  20097. jsonStatements.push(...jsonAddedCompositePKs);
  20098. jsonStatements.push(...jsonAddColumnsStatemets);
  20099. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  20100. jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
  20101. jsonStatements.push(...jsonCreatedCheckConstraints);
  20102. jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
  20103. jsonStatements.push(...jsonDropColumnsStatemets);
  20104. jsonStatements.push(...jsonAlteredCompositePKs);
  20105. jsonStatements.push(...jsonAlteredUniqueConstraints);
  20106. jsonStatements.push(...dropViews);
  20107. jsonStatements.push(...createViews);
  20108. const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action);
  20109. const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
  20110. const uniqueSqlStatements = [];
  20111. sqlStatements.forEach((ss) => {
  20112. if (!uniqueSqlStatements.includes(ss)) {
  20113. uniqueSqlStatements.push(ss);
  20114. }
  20115. });
  20116. const rTables = renamedTables.map((it) => {
  20117. return { from: it.from, to: it.to };
  20118. });
  20119. const _meta = prepareMigrationMeta([], rTables, rColumns);
  20120. return {
  20121. statements: combinedJsonStatements,
  20122. sqlStatements: uniqueSqlStatements,
  20123. _meta
  20124. };
  20125. };
  20126. applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
  20127. const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
  20128. const {
  20129. created: createdTables,
  20130. deleted: deletedTables,
  20131. renamed: renamedTables
  20132. } = await tablesResolver2({
  20133. created: tablesDiff.added,
  20134. deleted: tablesDiff.deleted
  20135. });
  20136. const tablesPatchedSnap1 = copy(json1);
  20137. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  20138. const { name } = nameChangeFor(it, renamedTables);
  20139. it.name = name;
  20140. return [name, it];
  20141. });
  20142. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  20143. const columnRenames = [];
  20144. const columnCreates = [];
  20145. const columnDeletes = [];
  20146. for (let entry of Object.values(res)) {
  20147. const { renamed, created, deleted } = await columnsResolver2({
  20148. tableName: entry.name,
  20149. schema: entry.schema,
  20150. deleted: entry.columns.deleted,
  20151. created: entry.columns.added
  20152. });
  20153. if (created.length > 0) {
  20154. columnCreates.push({
  20155. table: entry.name,
  20156. columns: created
  20157. });
  20158. }
  20159. if (deleted.length > 0) {
  20160. columnDeletes.push({
  20161. table: entry.name,
  20162. columns: deleted
  20163. });
  20164. }
  20165. if (renamed.length > 0) {
  20166. columnRenames.push({
  20167. table: entry.name,
  20168. renames: renamed
  20169. });
  20170. }
  20171. }
  20172. const columnRenamesDict = columnRenames.reduce(
  20173. (acc, it) => {
  20174. acc[it.table] = it.renames;
  20175. return acc;
  20176. },
  20177. {}
  20178. );
  20179. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  20180. columnsPatchedSnap1.tables = mapEntries(
  20181. columnsPatchedSnap1.tables,
  20182. (tableKey2, tableValue) => {
  20183. const patchedColumns = mapKeys(
  20184. tableValue.columns,
  20185. (columnKey, column6) => {
  20186. const rens = columnRenamesDict[tableValue.name] || [];
  20187. const newName = columnChangeFor(columnKey, rens);
  20188. column6.name = newName;
  20189. return newName;
  20190. }
  20191. );
  20192. tableValue.columns = patchedColumns;
  20193. return [tableKey2, tableValue];
  20194. }
  20195. );
  20196. const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
  20197. const {
  20198. created: createdViews,
  20199. deleted: deletedViews,
  20200. renamed: renamedViews
  20201. // renamed or moved
  20202. } = await viewsResolver2({
  20203. created: viewsDiff.added,
  20204. deleted: viewsDiff.deleted
  20205. });
  20206. const renamesViewDic = {};
  20207. renamedViews.forEach((it) => {
  20208. renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
  20209. });
  20210. const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
  20211. viewsPatchedSnap1.views = mapEntries(
  20212. viewsPatchedSnap1.views,
  20213. (viewKey, viewValue) => {
  20214. const rename = renamesViewDic[viewValue.name];
  20215. if (rename) {
  20216. viewValue.name = rename.to;
  20217. }
  20218. return [viewKey, viewValue];
  20219. }
  20220. );
  20221. const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
  20222. const typedResult = diffResultSchemeSQLite.parse(diffResult);
  20223. const tablesMap = {};
  20224. typedResult.alteredTablesWithColumns.forEach((obj) => {
  20225. tablesMap[obj.name] = obj;
  20226. });
  20227. const jsonCreateTables = createdTables.map((it) => {
  20228. return prepareSQLiteCreateTable(it, action);
  20229. });
  20230. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  20231. return prepareCreateIndexesJson(
  20232. it.name,
  20233. it.schema,
  20234. it.indexes,
  20235. curFull.internal
  20236. );
  20237. }).flat();
  20238. const jsonDropTables = deletedTables.map((it) => {
  20239. return prepareDropTableJson(it);
  20240. });
  20241. const jsonRenameTables = renamedTables.map((it) => {
  20242. return prepareRenameTableJson(it.from, it.to);
  20243. });
  20244. const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
  20245. const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
  20246. const jsonAddColumnsStatemets = columnCreates.map((it) => {
  20247. return _prepareSqliteAddColumns(
  20248. it.table,
  20249. it.columns,
  20250. tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
  20251. );
  20252. }).flat();
  20253. const rColumns = jsonRenameColumnsStatements.map((it) => {
  20254. const tableName = it.tableName;
  20255. const schema6 = it.schema;
  20256. return {
  20257. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  20258. to: { schema: schema6, table: tableName, column: it.newColumnName }
  20259. };
  20260. });
  20261. const rTables = renamedTables.map((it) => {
  20262. return { from: it.from, to: it.to };
  20263. });
  20264. const _meta = prepareMigrationMeta([], rTables, rColumns);
  20265. const allAltered = typedResult.alteredTablesWithColumns;
  20266. const jsonAddedCompositePKs = [];
  20267. const jsonDeletedCompositePKs = [];
  20268. const jsonAlteredCompositePKs = [];
  20269. const jsonAddedUniqueConstraints = [];
  20270. const jsonDeletedUniqueConstraints = [];
  20271. const jsonAlteredUniqueConstraints = [];
  20272. const jsonDeletedCheckConstraints = [];
  20273. const jsonCreatedCheckConstraints = [];
  20274. allAltered.forEach((it) => {
  20275. let addedColumns = [];
  20276. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  20277. const addedPkColumns = it.addedCompositePKs[addedPkName];
  20278. addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
  20279. }
  20280. let deletedColumns = [];
  20281. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  20282. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  20283. deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
  20284. }
  20285. const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
  20286. let addedCompositePKs = [];
  20287. let deletedCompositePKs = [];
  20288. let alteredCompositePKs = [];
  20289. if (doPerformDeleteAndCreate) {
  20290. addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
  20291. it.name,
  20292. it.addedCompositePKs
  20293. );
  20294. deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
  20295. it.name,
  20296. it.deletedCompositePKs
  20297. );
  20298. }
  20299. alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
  20300. it.name,
  20301. it.alteredCompositePKs
  20302. );
  20303. let addedUniqueConstraints = [];
  20304. let deletedUniqueConstraints = [];
  20305. let alteredUniqueConstraints = [];
  20306. let createdCheckConstraints = [];
  20307. let deletedCheckConstraints = [];
  20308. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  20309. it.name,
  20310. it.schema,
  20311. it.addedUniqueConstraints
  20312. );
  20313. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  20314. it.name,
  20315. it.schema,
  20316. it.deletedUniqueConstraints
  20317. );
  20318. if (it.alteredUniqueConstraints) {
  20319. const added = {};
  20320. const deleted = {};
  20321. for (const k5 of Object.keys(it.alteredUniqueConstraints)) {
  20322. added[k5] = it.alteredUniqueConstraints[k5].__new;
  20323. deleted[k5] = it.alteredUniqueConstraints[k5].__old;
  20324. }
  20325. addedUniqueConstraints.push(
  20326. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  20327. );
  20328. deletedUniqueConstraints.push(
  20329. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  20330. );
  20331. }
  20332. createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  20333. deletedCheckConstraints = prepareDeleteCheckConstraint(
  20334. it.name,
  20335. it.schema,
  20336. it.deletedCheckConstraints
  20337. );
  20338. if (it.alteredCheckConstraints && action !== "push") {
  20339. const added = {};
  20340. const deleted = {};
  20341. for (const k5 of Object.keys(it.alteredCheckConstraints)) {
  20342. added[k5] = it.alteredCheckConstraints[k5].__new;
  20343. deleted[k5] = it.alteredCheckConstraints[k5].__old;
  20344. }
  20345. createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  20346. deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
  20347. }
  20348. jsonAddedCompositePKs.push(...addedCompositePKs);
  20349. jsonDeletedCompositePKs.push(...deletedCompositePKs);
  20350. jsonAlteredCompositePKs.push(...alteredCompositePKs);
  20351. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  20352. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  20353. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  20354. jsonCreatedCheckConstraints.push(...createdCheckConstraints);
  20355. jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
  20356. });
  20357. const jsonTableAlternations = allAltered.map((it) => {
  20358. return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
  20359. }).flat();
  20360. const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
  20361. return prepareCreateIndexesJson(
  20362. it.name,
  20363. it.schema,
  20364. it.addedIndexes || {},
  20365. curFull.internal
  20366. );
  20367. }).flat();
  20368. const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
  20369. return prepareDropIndexesJson(
  20370. it.name,
  20371. it.schema,
  20372. it.deletedIndexes || {}
  20373. );
  20374. }).flat();
  20375. allAltered.forEach((it) => {
  20376. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  20377. (current, item) => {
  20378. current[item] = it.alteredIndexes[item].__old;
  20379. return current;
  20380. },
  20381. {}
  20382. );
  20383. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  20384. (current, item) => {
  20385. current[item] = it.alteredIndexes[item].__new;
  20386. return current;
  20387. },
  20388. {}
  20389. );
  20390. jsonCreateIndexesForAllAlteredTables.push(
  20391. ...prepareCreateIndexesJson(
  20392. it.name,
  20393. it.schema,
  20394. createdIndexes || {},
  20395. curFull.internal
  20396. )
  20397. );
  20398. jsonDropIndexesForAllAlteredTables.push(
  20399. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  20400. );
  20401. });
  20402. const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
  20403. const forAdded = prepareLibSQLCreateReferencesJson(
  20404. it.name,
  20405. it.schema,
  20406. it.addedForeignKeys,
  20407. json2,
  20408. action
  20409. );
  20410. const forAltered = prepareLibSQLDropReferencesJson(
  20411. it.name,
  20412. it.schema,
  20413. it.deletedForeignKeys,
  20414. json2,
  20415. _meta,
  20416. action
  20417. );
  20418. const alteredFKs = prepareAlterReferencesJson(it.name, it.schema, it.alteredForeignKeys);
  20419. return [...forAdded, ...forAltered, ...alteredFKs];
  20420. }).flat();
  20421. const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  20422. (t6) => t6.type === "create_reference"
  20423. );
  20424. const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  20425. (t6) => t6.type === "delete_reference"
  20426. );
  20427. const createViews = [];
  20428. const dropViews = [];
  20429. createViews.push(
  20430. ...createdViews.filter((it) => !it.isExisting).map((it) => {
  20431. return prepareSqliteCreateViewJson(
  20432. it.name,
  20433. it.definition
  20434. );
  20435. })
  20436. );
  20437. dropViews.push(
  20438. ...deletedViews.filter((it) => !it.isExisting).map((it) => {
  20439. return prepareDropViewJson(it.name);
  20440. })
  20441. );
  20442. dropViews.push(
  20443. ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
  20444. return prepareDropViewJson(it.from.name);
  20445. })
  20446. );
  20447. createViews.push(
  20448. ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
  20449. return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
  20450. })
  20451. );
  20452. const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
  20453. for (const alteredView of alteredViews) {
  20454. const { definition } = json2.views[alteredView.name];
  20455. if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
  20456. dropViews.push(prepareDropViewJson(alteredView.name));
  20457. createViews.push(
  20458. prepareSqliteCreateViewJson(
  20459. alteredView.name,
  20460. definition
  20461. )
  20462. );
  20463. }
  20464. }
  20465. const jsonStatements = [];
  20466. jsonStatements.push(...jsonCreateTables);
  20467. jsonStatements.push(...jsonDropTables);
  20468. jsonStatements.push(...jsonRenameTables);
  20469. jsonStatements.push(...jsonRenameColumnsStatements);
  20470. jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
  20471. jsonStatements.push(...jsonDeletedCheckConstraints);
  20472. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  20473. jsonStatements.push(...jsonDeletedCompositePKs);
  20474. jsonStatements.push(...jsonTableAlternations);
  20475. jsonStatements.push(...jsonAddedCompositePKs);
  20476. jsonStatements.push(...jsonAddColumnsStatemets);
  20477. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  20478. jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
  20479. jsonStatements.push(...jsonCreatedCheckConstraints);
  20480. jsonStatements.push(...dropViews);
  20481. jsonStatements.push(...createViews);
  20482. jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
  20483. jsonStatements.push(...jsonDropColumnsStatemets);
  20484. jsonStatements.push(...jsonAlteredCompositePKs);
  20485. jsonStatements.push(...jsonAlteredUniqueConstraints);
  20486. const combinedJsonStatements = libSQLCombineStatements(jsonStatements, json2, action);
  20487. const sqlStatements = fromJson(
  20488. combinedJsonStatements,
  20489. "turso",
  20490. action,
  20491. json2
  20492. );
  20493. const uniqueSqlStatements = [];
  20494. sqlStatements.forEach((ss) => {
  20495. if (!uniqueSqlStatements.includes(ss)) {
  20496. uniqueSqlStatements.push(ss);
  20497. }
  20498. });
  20499. return {
  20500. statements: combinedJsonStatements,
  20501. sqlStatements: uniqueSqlStatements,
  20502. _meta
  20503. };
  20504. };
  20505. }
  20506. });
  20507. // src/utils/words.ts
  20508. var init_words = __esm({
  20509. "src/utils/words.ts"() {
  20510. "use strict";
  20511. }
  20512. });
  20513. // src/schemaValidator.ts
  20514. var dialects, dialect4, commonSquashedSchema, commonSchema;
  20515. var init_schemaValidator = __esm({
  20516. "src/schemaValidator.ts"() {
  20517. "use strict";
  20518. init_esm();
  20519. init_mysqlSchema();
  20520. init_pgSchema();
  20521. init_singlestoreSchema();
  20522. init_sqliteSchema();
  20523. dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore", "gel"];
  20524. dialect4 = enumType(dialects);
  20525. commonSquashedSchema = unionType([
  20526. pgSchemaSquashed,
  20527. mysqlSchemaSquashed,
  20528. SQLiteSchemaSquashed,
  20529. singlestoreSchemaSquashed
  20530. ]);
  20531. commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]);
  20532. }
  20533. });
  20534. // src/cli/validations/common.ts
  20535. var sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, casingTypes, casingType, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema;
  20536. var init_common = __esm({
  20537. "src/cli/validations/common.ts"() {
  20538. "use strict";
  20539. init_esm();
  20540. init_schemaValidator();
  20541. init_outputs();
  20542. sqliteDriversLiterals = [
  20543. literalType("d1-http"),
  20544. literalType("expo"),
  20545. literalType("durable-sqlite")
  20546. ];
  20547. postgresqlDriversLiterals = [
  20548. literalType("aws-data-api"),
  20549. literalType("pglite")
  20550. ];
  20551. prefixes = [
  20552. "index",
  20553. "timestamp",
  20554. "supabase",
  20555. "unix",
  20556. "none"
  20557. ];
  20558. prefix = enumType(prefixes);
  20559. {
  20560. const _3 = "";
  20561. }
  20562. casingTypes = ["snake_case", "camelCase"];
  20563. casingType = enumType(casingTypes);
  20564. sqliteDriver = unionType(sqliteDriversLiterals);
  20565. postgresDriver = unionType(postgresqlDriversLiterals);
  20566. driver = unionType([sqliteDriver, postgresDriver]);
  20567. configMigrations = objectType({
  20568. table: stringType().optional(),
  20569. schema: stringType().optional(),
  20570. prefix: prefix.optional().default("index")
  20571. }).optional();
  20572. configCommonSchema = objectType({
  20573. dialect: dialect4,
  20574. schema: unionType([stringType(), stringType().array()]).optional(),
  20575. out: stringType().optional(),
  20576. breakpoints: booleanType().optional().default(true),
  20577. verbose: booleanType().optional().default(false),
  20578. driver: driver.optional(),
  20579. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  20580. schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
  20581. migrations: configMigrations,
  20582. dbCredentials: anyType().optional(),
  20583. casing: casingType.optional(),
  20584. sql: booleanType().default(true)
  20585. }).passthrough();
  20586. casing = unionType([literalType("camel"), literalType("preserve")]).default(
  20587. "camel"
  20588. );
  20589. introspectParams = objectType({
  20590. schema: unionType([stringType(), stringType().array()]).optional(),
  20591. out: stringType().optional().default("./drizzle"),
  20592. breakpoints: booleanType().default(true),
  20593. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  20594. schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
  20595. introspect: objectType({
  20596. casing
  20597. }).default({ casing: "camel" })
  20598. });
  20599. configIntrospectCliSchema = objectType({
  20600. schema: unionType([stringType(), stringType().array()]).optional(),
  20601. out: stringType().optional().default("./drizzle"),
  20602. breakpoints: booleanType().default(true),
  20603. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  20604. schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
  20605. introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default(
  20606. "camel"
  20607. )
  20608. });
  20609. configGenerateSchema = objectType({
  20610. schema: unionType([stringType(), stringType().array()]),
  20611. out: stringType().optional().default("./drizzle"),
  20612. breakpoints: booleanType().default(true)
  20613. });
  20614. configPushSchema = objectType({
  20615. dialect: dialect4,
  20616. schema: unionType([stringType(), stringType().array()]),
  20617. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  20618. schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
  20619. verbose: booleanType().default(false),
  20620. strict: booleanType().default(false),
  20621. out: stringType().optional()
  20622. });
  20623. }
  20624. });
  20625. // src/cli/validations/outputs.ts
  20626. var withStyle;
  20627. var init_outputs = __esm({
  20628. "src/cli/validations/outputs.ts"() {
  20629. "use strict";
  20630. init_source();
  20631. init_common();
  20632. withStyle = {
  20633. error: (str) => `${source_default.red(`${source_default.white.bgRed(" Invalid input ")} ${str}`)}`,
  20634. warning: (str) => `${source_default.white.bgGray(" Warning ")} ${str}`,
  20635. errorWarning: (str) => `${source_default.red(`${source_default.white.bgRed(" Warning ")} ${str}`)}`,
  20636. fullWarning: (str) => `${source_default.black.bgYellow(" Warning ")} ${source_default.bold(str)}`,
  20637. suggestion: (str) => `${source_default.white.bgGray(" Suggestion ")} ${str}`,
  20638. info: (str) => `${source_default.grey(str)}`
  20639. };
  20640. }
  20641. });
  20642. // src/cli/commands/migrate.ts
  20643. var import_hanji2, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, roleResolver, policyResolver, indPolicyResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
  20644. var init_migrate = __esm({
  20645. "src/cli/commands/migrate.ts"() {
  20646. "use strict";
  20647. init_migrationPreparator();
  20648. init_source();
  20649. import_hanji2 = __toESM(require_hanji());
  20650. init_singlestoreSchema();
  20651. init_mysqlSchema();
  20652. init_pgSchema();
  20653. init_sqliteSchema();
  20654. init_snapshotsDiffer();
  20655. init_utils();
  20656. init_words();
  20657. init_outputs();
  20658. init_views();
  20659. schemasResolver = async (input) => {
  20660. try {
  20661. const { created, deleted, renamed } = await promptSchemasConflict(
  20662. input.created,
  20663. input.deleted
  20664. );
  20665. return { created, deleted, renamed };
  20666. } catch (e6) {
  20667. console.error(e6);
  20668. throw e6;
  20669. }
  20670. };
  20671. tablesResolver = async (input) => {
  20672. try {
  20673. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  20674. input.created,
  20675. input.deleted,
  20676. "table"
  20677. );
  20678. return {
  20679. created,
  20680. deleted,
  20681. moved,
  20682. renamed
  20683. };
  20684. } catch (e6) {
  20685. console.error(e6);
  20686. throw e6;
  20687. }
  20688. };
  20689. viewsResolver = async (input) => {
  20690. try {
  20691. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  20692. input.created,
  20693. input.deleted,
  20694. "view"
  20695. );
  20696. return {
  20697. created,
  20698. deleted,
  20699. moved,
  20700. renamed
  20701. };
  20702. } catch (e6) {
  20703. console.error(e6);
  20704. throw e6;
  20705. }
  20706. };
  20707. mySqlViewsResolver = async (input) => {
  20708. try {
  20709. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  20710. input.created,
  20711. input.deleted,
  20712. "view"
  20713. );
  20714. return {
  20715. created,
  20716. deleted,
  20717. moved,
  20718. renamed
  20719. };
  20720. } catch (e6) {
  20721. console.error(e6);
  20722. throw e6;
  20723. }
  20724. };
  20725. sqliteViewsResolver = async (input) => {
  20726. try {
  20727. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  20728. input.created,
  20729. input.deleted,
  20730. "view"
  20731. );
  20732. return {
  20733. created,
  20734. deleted,
  20735. moved,
  20736. renamed
  20737. };
  20738. } catch (e6) {
  20739. console.error(e6);
  20740. throw e6;
  20741. }
  20742. };
  20743. sequencesResolver = async (input) => {
  20744. try {
  20745. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  20746. input.created,
  20747. input.deleted,
  20748. "sequence"
  20749. );
  20750. return {
  20751. created,
  20752. deleted,
  20753. moved,
  20754. renamed
  20755. };
  20756. } catch (e6) {
  20757. console.error(e6);
  20758. throw e6;
  20759. }
  20760. };
  20761. roleResolver = async (input) => {
  20762. const result = await promptNamedConflict(
  20763. input.created,
  20764. input.deleted,
  20765. "role"
  20766. );
  20767. return {
  20768. created: result.created,
  20769. deleted: result.deleted,
  20770. renamed: result.renamed
  20771. };
  20772. };
  20773. policyResolver = async (input) => {
  20774. const result = await promptColumnsConflicts(
  20775. input.tableName,
  20776. input.created,
  20777. input.deleted
  20778. );
  20779. return {
  20780. tableName: input.tableName,
  20781. schema: input.schema,
  20782. created: result.created,
  20783. deleted: result.deleted,
  20784. renamed: result.renamed
  20785. };
  20786. };
  20787. indPolicyResolver = async (input) => {
  20788. const result = await promptNamedConflict(
  20789. input.created,
  20790. input.deleted,
  20791. "policy"
  20792. );
  20793. return {
  20794. created: result.created,
  20795. deleted: result.deleted,
  20796. renamed: result.renamed
  20797. };
  20798. };
  20799. enumsResolver = async (input) => {
  20800. try {
  20801. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  20802. input.created,
  20803. input.deleted,
  20804. "enum"
  20805. );
  20806. return {
  20807. created,
  20808. deleted,
  20809. moved,
  20810. renamed
  20811. };
  20812. } catch (e6) {
  20813. console.error(e6);
  20814. throw e6;
  20815. }
  20816. };
  20817. columnsResolver = async (input) => {
  20818. const result = await promptColumnsConflicts(
  20819. input.tableName,
  20820. input.created,
  20821. input.deleted
  20822. );
  20823. return {
  20824. tableName: input.tableName,
  20825. schema: input.schema,
  20826. created: result.created,
  20827. deleted: result.deleted,
  20828. renamed: result.renamed
  20829. };
  20830. };
  20831. promptColumnsConflicts = async (tableName, newColumns, missingColumns) => {
  20832. if (newColumns.length === 0 || missingColumns.length === 0) {
  20833. return { created: newColumns, renamed: [], deleted: missingColumns };
  20834. }
  20835. const result = {
  20836. created: [],
  20837. renamed: [],
  20838. deleted: []
  20839. };
  20840. let index6 = 0;
  20841. let leftMissing = [...missingColumns];
  20842. do {
  20843. const created = newColumns[index6];
  20844. const renames = leftMissing.map((it) => {
  20845. return { from: it, to: created };
  20846. });
  20847. const promptData = [created, ...renames];
  20848. const { status, data } = await (0, import_hanji2.render)(
  20849. new ResolveColumnSelect(tableName, created, promptData)
  20850. );
  20851. if (status === "aborted") {
  20852. console.error("ERROR");
  20853. process.exit(1);
  20854. }
  20855. if (isRenamePromptItem(data)) {
  20856. console.log(
  20857. `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
  20858. "column will be renamed"
  20859. )}`
  20860. );
  20861. result.renamed.push(data);
  20862. delete leftMissing[leftMissing.indexOf(data.from)];
  20863. leftMissing = leftMissing.filter(Boolean);
  20864. } else {
  20865. console.log(
  20866. `${source_default.green("+")} ${data.name} ${source_default.gray(
  20867. "column will be created"
  20868. )}`
  20869. );
  20870. result.created.push(created);
  20871. }
  20872. index6 += 1;
  20873. } while (index6 < newColumns.length);
  20874. console.log(
  20875. source_default.gray(`--- all columns conflicts in ${tableName} table resolved ---
  20876. `)
  20877. );
  20878. result.deleted.push(...leftMissing);
  20879. return result;
  20880. };
  20881. promptNamedConflict = async (newItems, missingItems, entity) => {
  20882. if (missingItems.length === 0 || newItems.length === 0) {
  20883. return {
  20884. created: newItems,
  20885. renamed: [],
  20886. deleted: missingItems
  20887. };
  20888. }
  20889. const result = { created: [], renamed: [], deleted: [] };
  20890. let index6 = 0;
  20891. let leftMissing = [...missingItems];
  20892. do {
  20893. const created = newItems[index6];
  20894. const renames = leftMissing.map((it) => {
  20895. return { from: it, to: created };
  20896. });
  20897. const promptData = [created, ...renames];
  20898. const { status, data } = await (0, import_hanji2.render)(
  20899. new ResolveSelectNamed(created, promptData, entity)
  20900. );
  20901. if (status === "aborted") {
  20902. console.error("ERROR");
  20903. process.exit(1);
  20904. }
  20905. if (isRenamePromptItem(data)) {
  20906. console.log(
  20907. `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
  20908. `${entity} will be renamed/moved`
  20909. )}`
  20910. );
  20911. if (data.from.name !== data.to.name) {
  20912. result.renamed.push(data);
  20913. }
  20914. delete leftMissing[leftMissing.indexOf(data.from)];
  20915. leftMissing = leftMissing.filter(Boolean);
  20916. } else {
  20917. console.log(
  20918. `${source_default.green("+")} ${data.name} ${source_default.gray(
  20919. `${entity} will be created`
  20920. )}`
  20921. );
  20922. result.created.push(created);
  20923. }
  20924. index6 += 1;
  20925. } while (index6 < newItems.length);
  20926. console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
  20927. `));
  20928. result.deleted.push(...leftMissing);
  20929. return result;
  20930. };
  20931. promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
  20932. if (missingItems.length === 0 || newItems.length === 0) {
  20933. return {
  20934. created: newItems,
  20935. renamed: [],
  20936. moved: [],
  20937. deleted: missingItems
  20938. };
  20939. }
  20940. const result = { created: [], renamed: [], moved: [], deleted: [] };
  20941. let index6 = 0;
  20942. let leftMissing = [...missingItems];
  20943. do {
  20944. const created = newItems[index6];
  20945. const renames = leftMissing.map((it) => {
  20946. return { from: it, to: created };
  20947. });
  20948. const promptData = [created, ...renames];
  20949. const { status, data } = await (0, import_hanji2.render)(
  20950. new ResolveSelect(created, promptData, entity)
  20951. );
  20952. if (status === "aborted") {
  20953. console.error("ERROR");
  20954. process.exit(1);
  20955. }
  20956. if (isRenamePromptItem(data)) {
  20957. const schemaFromPrefix = !data.from.schema || data.from.schema === "public" ? "" : `${data.from.schema}.`;
  20958. const schemaToPrefix = !data.to.schema || data.to.schema === "public" ? "" : `${data.to.schema}.`;
  20959. console.log(
  20960. `${source_default.yellow("~")} ${schemaFromPrefix}${data.from.name} \u203A ${schemaToPrefix}${data.to.name} ${source_default.gray(
  20961. `${entity} will be renamed/moved`
  20962. )}`
  20963. );
  20964. if (data.from.name !== data.to.name) {
  20965. result.renamed.push(data);
  20966. }
  20967. if (data.from.schema !== data.to.schema) {
  20968. result.moved.push({
  20969. name: data.from.name,
  20970. schemaFrom: data.from.schema || "public",
  20971. schemaTo: data.to.schema || "public"
  20972. });
  20973. }
  20974. delete leftMissing[leftMissing.indexOf(data.from)];
  20975. leftMissing = leftMissing.filter(Boolean);
  20976. } else {
  20977. console.log(
  20978. `${source_default.green("+")} ${data.name} ${source_default.gray(
  20979. `${entity} will be created`
  20980. )}`
  20981. );
  20982. result.created.push(created);
  20983. }
  20984. index6 += 1;
  20985. } while (index6 < newItems.length);
  20986. console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
  20987. `));
  20988. result.deleted.push(...leftMissing);
  20989. return result;
  20990. };
  20991. promptSchemasConflict = async (newSchemas, missingSchemas) => {
  20992. if (missingSchemas.length === 0 || newSchemas.length === 0) {
  20993. return { created: newSchemas, renamed: [], deleted: missingSchemas };
  20994. }
  20995. const result = {
  20996. created: [],
  20997. renamed: [],
  20998. deleted: []
  20999. };
  21000. let index6 = 0;
  21001. let leftMissing = [...missingSchemas];
  21002. do {
  21003. const created = newSchemas[index6];
  21004. const renames = leftMissing.map((it) => {
  21005. return { from: it, to: created };
  21006. });
  21007. const promptData = [created, ...renames];
  21008. const { status, data } = await (0, import_hanji2.render)(
  21009. new ResolveSchemasSelect(created, promptData)
  21010. );
  21011. if (status === "aborted") {
  21012. console.error("ERROR");
  21013. process.exit(1);
  21014. }
  21015. if (isRenamePromptItem(data)) {
  21016. console.log(
  21017. `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
  21018. "schema will be renamed"
  21019. )}`
  21020. );
  21021. result.renamed.push(data);
  21022. delete leftMissing[leftMissing.indexOf(data.from)];
  21023. leftMissing = leftMissing.filter(Boolean);
  21024. } else {
  21025. console.log(
  21026. `${source_default.green("+")} ${data.name} ${source_default.gray(
  21027. "schema will be created"
  21028. )}`
  21029. );
  21030. result.created.push(created);
  21031. }
  21032. index6 += 1;
  21033. } while (index6 < newSchemas.length);
  21034. console.log(source_default.gray("--- all schemas conflicts resolved ---\n"));
  21035. result.deleted.push(...leftMissing);
  21036. return result;
  21037. };
  21038. BREAKPOINT = "--> statement-breakpoint\n";
  21039. }
  21040. });
  21041. // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js
  21042. var posixClasses, braceEscape, regexpEscape, rangesToString, parseClass;
  21043. var init_brace_expressions = __esm({
  21044. "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js"() {
  21045. "use strict";
  21046. posixClasses = {
  21047. "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
  21048. "[:alpha:]": ["\\p{L}\\p{Nl}", true],
  21049. "[:ascii:]": ["\\x00-\\x7f", false],
  21050. "[:blank:]": ["\\p{Zs}\\t", true],
  21051. "[:cntrl:]": ["\\p{Cc}", true],
  21052. "[:digit:]": ["\\p{Nd}", true],
  21053. "[:graph:]": ["\\p{Z}\\p{C}", true, true],
  21054. "[:lower:]": ["\\p{Ll}", true],
  21055. "[:print:]": ["\\p{C}", true],
  21056. "[:punct:]": ["\\p{P}", true],
  21057. "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
  21058. "[:upper:]": ["\\p{Lu}", true],
  21059. "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
  21060. "[:xdigit:]": ["A-Fa-f0-9", false]
  21061. };
  21062. braceEscape = (s6) => s6.replace(/[[\]\\-]/g, "\\$&");
  21063. regexpEscape = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  21064. rangesToString = (ranges) => ranges.join("");
  21065. parseClass = (glob2, position) => {
  21066. const pos = position;
  21067. if (glob2.charAt(pos) !== "[") {
  21068. throw new Error("not in a brace expression");
  21069. }
  21070. const ranges = [];
  21071. const negs = [];
  21072. let i6 = pos + 1;
  21073. let sawStart = false;
  21074. let uflag = false;
  21075. let escaping = false;
  21076. let negate2 = false;
  21077. let endPos = pos;
  21078. let rangeStart = "";
  21079. WHILE: while (i6 < glob2.length) {
  21080. const c5 = glob2.charAt(i6);
  21081. if ((c5 === "!" || c5 === "^") && i6 === pos + 1) {
  21082. negate2 = true;
  21083. i6++;
  21084. continue;
  21085. }
  21086. if (c5 === "]" && sawStart && !escaping) {
  21087. endPos = i6 + 1;
  21088. break;
  21089. }
  21090. sawStart = true;
  21091. if (c5 === "\\") {
  21092. if (!escaping) {
  21093. escaping = true;
  21094. i6++;
  21095. continue;
  21096. }
  21097. }
  21098. if (c5 === "[" && !escaping) {
  21099. for (const [cls, [unip, u5, neg]] of Object.entries(posixClasses)) {
  21100. if (glob2.startsWith(cls, i6)) {
  21101. if (rangeStart) {
  21102. return ["$.", false, glob2.length - pos, true];
  21103. }
  21104. i6 += cls.length;
  21105. if (neg)
  21106. negs.push(unip);
  21107. else
  21108. ranges.push(unip);
  21109. uflag = uflag || u5;
  21110. continue WHILE;
  21111. }
  21112. }
  21113. }
  21114. escaping = false;
  21115. if (rangeStart) {
  21116. if (c5 > rangeStart) {
  21117. ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c5));
  21118. } else if (c5 === rangeStart) {
  21119. ranges.push(braceEscape(c5));
  21120. }
  21121. rangeStart = "";
  21122. i6++;
  21123. continue;
  21124. }
  21125. if (glob2.startsWith("-]", i6 + 1)) {
  21126. ranges.push(braceEscape(c5 + "-"));
  21127. i6 += 2;
  21128. continue;
  21129. }
  21130. if (glob2.startsWith("-", i6 + 1)) {
  21131. rangeStart = c5;
  21132. i6 += 2;
  21133. continue;
  21134. }
  21135. ranges.push(braceEscape(c5));
  21136. i6++;
  21137. }
  21138. if (endPos < i6) {
  21139. return ["", false, 0, false];
  21140. }
  21141. if (!ranges.length && !negs.length) {
  21142. return ["$.", false, glob2.length - pos, true];
  21143. }
  21144. if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate2) {
  21145. const r6 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  21146. return [regexpEscape(r6), false, endPos - pos, false];
  21147. }
  21148. const sranges = "[" + (negate2 ? "^" : "") + rangesToString(ranges) + "]";
  21149. const snegs = "[" + (negate2 ? "" : "^") + rangesToString(negs) + "]";
  21150. const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
  21151. return [comb, uflag, endPos - pos, true];
  21152. };
  21153. }
  21154. });
  21155. // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js
  21156. var escape;
  21157. var init_escape = __esm({
  21158. "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js"() {
  21159. "use strict";
  21160. escape = (s6, { windowsPathsNoEscape = false } = {}) => {
  21161. return windowsPathsNoEscape ? s6.replace(/[?*()[\]]/g, "[$&]") : s6.replace(/[?*()[\]\\]/g, "\\$&");
  21162. };
  21163. }
  21164. });
  21165. // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js
  21166. var unescape2;
  21167. var init_unescape = __esm({
  21168. "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js"() {
  21169. "use strict";
  21170. unescape2 = (s6, { windowsPathsNoEscape = false } = {}) => {
  21171. return windowsPathsNoEscape ? s6.replace(/\[([^\/\\])\]/g, "$1") : s6.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
  21172. };
  21173. }
  21174. });
  21175. // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js
  21176. var import_brace_expansion, minimatch, starDotExtRE, starDotExtTest, starDotExtTestDot, starDotExtTestNocase, starDotExtTestNocaseDot, starDotStarRE, starDotStarTest, starDotStarTestDot, dotStarRE, dotStarTest, starRE, starTest, starTestDot, qmarksRE, qmarksTestNocase, qmarksTestNocaseDot, qmarksTestDot, qmarksTest, qmarksTestNoExt, qmarksTestNoExtDot, defaultPlatform, path, sep, GLOBSTAR, plTypes, qmark, star, twoStarDot, twoStarNoDot, charSet, reSpecials, addPatternStartSet, filter, ext, defaults, braceExpand, MAX_PATTERN_LENGTH, assertValidPattern, makeRe, match, globUnescape, globMagic, regExpEscape, Minimatch;
  21177. var init_mjs = __esm({
  21178. "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js"() {
  21179. "use strict";
  21180. import_brace_expansion = __toESM(require_brace_expansion(), 1);
  21181. init_brace_expressions();
  21182. init_escape();
  21183. init_unescape();
  21184. init_escape();
  21185. init_unescape();
  21186. minimatch = (p5, pattern, options = {}) => {
  21187. assertValidPattern(pattern);
  21188. if (!options.nocomment && pattern.charAt(0) === "#") {
  21189. return false;
  21190. }
  21191. return new Minimatch(pattern, options).match(p5);
  21192. };
  21193. starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  21194. starDotExtTest = (ext2) => (f7) => !f7.startsWith(".") && f7.endsWith(ext2);
  21195. starDotExtTestDot = (ext2) => (f7) => f7.endsWith(ext2);
  21196. starDotExtTestNocase = (ext2) => {
  21197. ext2 = ext2.toLowerCase();
  21198. return (f7) => !f7.startsWith(".") && f7.toLowerCase().endsWith(ext2);
  21199. };
  21200. starDotExtTestNocaseDot = (ext2) => {
  21201. ext2 = ext2.toLowerCase();
  21202. return (f7) => f7.toLowerCase().endsWith(ext2);
  21203. };
  21204. starDotStarRE = /^\*+\.\*+$/;
  21205. starDotStarTest = (f7) => !f7.startsWith(".") && f7.includes(".");
  21206. starDotStarTestDot = (f7) => f7 !== "." && f7 !== ".." && f7.includes(".");
  21207. dotStarRE = /^\.\*+$/;
  21208. dotStarTest = (f7) => f7 !== "." && f7 !== ".." && f7.startsWith(".");
  21209. starRE = /^\*+$/;
  21210. starTest = (f7) => f7.length !== 0 && !f7.startsWith(".");
  21211. starTestDot = (f7) => f7.length !== 0 && f7 !== "." && f7 !== "..";
  21212. qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  21213. qmarksTestNocase = ([$0, ext2 = ""]) => {
  21214. const noext = qmarksTestNoExt([$0]);
  21215. if (!ext2)
  21216. return noext;
  21217. ext2 = ext2.toLowerCase();
  21218. return (f7) => noext(f7) && f7.toLowerCase().endsWith(ext2);
  21219. };
  21220. qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
  21221. const noext = qmarksTestNoExtDot([$0]);
  21222. if (!ext2)
  21223. return noext;
  21224. ext2 = ext2.toLowerCase();
  21225. return (f7) => noext(f7) && f7.toLowerCase().endsWith(ext2);
  21226. };
  21227. qmarksTestDot = ([$0, ext2 = ""]) => {
  21228. const noext = qmarksTestNoExtDot([$0]);
  21229. return !ext2 ? noext : (f7) => noext(f7) && f7.endsWith(ext2);
  21230. };
  21231. qmarksTest = ([$0, ext2 = ""]) => {
  21232. const noext = qmarksTestNoExt([$0]);
  21233. return !ext2 ? noext : (f7) => noext(f7) && f7.endsWith(ext2);
  21234. };
  21235. qmarksTestNoExt = ([$0]) => {
  21236. const len = $0.length;
  21237. return (f7) => f7.length === len && !f7.startsWith(".");
  21238. };
  21239. qmarksTestNoExtDot = ([$0]) => {
  21240. const len = $0.length;
  21241. return (f7) => f7.length === len && f7 !== "." && f7 !== "..";
  21242. };
  21243. defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
  21244. path = {
  21245. win32: { sep: "\\" },
  21246. posix: { sep: "/" }
  21247. };
  21248. sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
  21249. minimatch.sep = sep;
  21250. GLOBSTAR = Symbol("globstar **");
  21251. minimatch.GLOBSTAR = GLOBSTAR;
  21252. plTypes = {
  21253. "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
  21254. "?": { open: "(?:", close: ")?" },
  21255. "+": { open: "(?:", close: ")+" },
  21256. "*": { open: "(?:", close: ")*" },
  21257. "@": { open: "(?:", close: ")" }
  21258. };
  21259. qmark = "[^/]";
  21260. star = qmark + "*?";
  21261. twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
  21262. twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
  21263. charSet = (s6) => s6.split("").reduce((set, c5) => {
  21264. set[c5] = true;
  21265. return set;
  21266. }, {});
  21267. reSpecials = charSet("().*{}+?[]^$\\!");
  21268. addPatternStartSet = charSet("[.(");
  21269. filter = (pattern, options = {}) => (p5) => minimatch(p5, pattern, options);
  21270. minimatch.filter = filter;
  21271. ext = (a5, b5 = {}) => Object.assign({}, a5, b5);
  21272. defaults = (def) => {
  21273. if (!def || typeof def !== "object" || !Object.keys(def).length) {
  21274. return minimatch;
  21275. }
  21276. const orig = minimatch;
  21277. const m6 = (p5, pattern, options = {}) => orig(p5, pattern, ext(def, options));
  21278. return Object.assign(m6, {
  21279. Minimatch: class Minimatch extends orig.Minimatch {
  21280. constructor(pattern, options = {}) {
  21281. super(pattern, ext(def, options));
  21282. }
  21283. static defaults(options) {
  21284. return orig.defaults(ext(def, options)).Minimatch;
  21285. }
  21286. },
  21287. unescape: (s6, options = {}) => orig.unescape(s6, ext(def, options)),
  21288. escape: (s6, options = {}) => orig.escape(s6, ext(def, options)),
  21289. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  21290. defaults: (options) => orig.defaults(ext(def, options)),
  21291. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  21292. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  21293. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  21294. sep: orig.sep,
  21295. GLOBSTAR
  21296. });
  21297. };
  21298. minimatch.defaults = defaults;
  21299. braceExpand = (pattern, options = {}) => {
  21300. assertValidPattern(pattern);
  21301. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  21302. return [pattern];
  21303. }
  21304. return (0, import_brace_expansion.default)(pattern);
  21305. };
  21306. minimatch.braceExpand = braceExpand;
  21307. MAX_PATTERN_LENGTH = 1024 * 64;
  21308. assertValidPattern = (pattern) => {
  21309. if (typeof pattern !== "string") {
  21310. throw new TypeError("invalid pattern");
  21311. }
  21312. if (pattern.length > MAX_PATTERN_LENGTH) {
  21313. throw new TypeError("pattern is too long");
  21314. }
  21315. };
  21316. makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  21317. minimatch.makeRe = makeRe;
  21318. match = (list, pattern, options = {}) => {
  21319. const mm = new Minimatch(pattern, options);
  21320. list = list.filter((f7) => mm.match(f7));
  21321. if (mm.options.nonull && !list.length) {
  21322. list.push(pattern);
  21323. }
  21324. return list;
  21325. };
  21326. minimatch.match = match;
  21327. globUnescape = (s6) => s6.replace(/\\(.)/g, "$1");
  21328. globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  21329. regExpEscape = (s6) => s6.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  21330. Minimatch = class {
  21331. constructor(pattern, options = {}) {
  21332. __publicField(this, "options");
  21333. __publicField(this, "set");
  21334. __publicField(this, "pattern");
  21335. __publicField(this, "windowsPathsNoEscape");
  21336. __publicField(this, "nonegate");
  21337. __publicField(this, "negate");
  21338. __publicField(this, "comment");
  21339. __publicField(this, "empty");
  21340. __publicField(this, "preserveMultipleSlashes");
  21341. __publicField(this, "partial");
  21342. __publicField(this, "globSet");
  21343. __publicField(this, "globParts");
  21344. __publicField(this, "nocase");
  21345. __publicField(this, "isWindows");
  21346. __publicField(this, "platform");
  21347. __publicField(this, "windowsNoMagicRoot");
  21348. __publicField(this, "regexp");
  21349. assertValidPattern(pattern);
  21350. options = options || {};
  21351. this.options = options;
  21352. this.pattern = pattern;
  21353. this.platform = options.platform || defaultPlatform;
  21354. this.isWindows = this.platform === "win32";
  21355. this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  21356. if (this.windowsPathsNoEscape) {
  21357. this.pattern = this.pattern.replace(/\\/g, "/");
  21358. }
  21359. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  21360. this.regexp = null;
  21361. this.negate = false;
  21362. this.nonegate = !!options.nonegate;
  21363. this.comment = false;
  21364. this.empty = false;
  21365. this.partial = !!options.partial;
  21366. this.nocase = !!this.options.nocase;
  21367. this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
  21368. this.globSet = [];
  21369. this.globParts = [];
  21370. this.set = [];
  21371. this.make();
  21372. }
  21373. hasMagic() {
  21374. if (this.options.magicalBraces && this.set.length > 1) {
  21375. return true;
  21376. }
  21377. for (const pattern of this.set) {
  21378. for (const part of pattern) {
  21379. if (typeof part !== "string")
  21380. return true;
  21381. }
  21382. }
  21383. return false;
  21384. }
  21385. debug(..._3) {
  21386. }
  21387. make() {
  21388. const pattern = this.pattern;
  21389. const options = this.options;
  21390. if (!options.nocomment && pattern.charAt(0) === "#") {
  21391. this.comment = true;
  21392. return;
  21393. }
  21394. if (!pattern) {
  21395. this.empty = true;
  21396. return;
  21397. }
  21398. this.parseNegate();
  21399. this.globSet = [...new Set(this.braceExpand())];
  21400. if (options.debug) {
  21401. this.debug = (...args) => console.error(...args);
  21402. }
  21403. this.debug(this.pattern, this.globSet);
  21404. const rawGlobParts = this.globSet.map((s6) => this.slashSplit(s6));
  21405. this.globParts = this.preprocess(rawGlobParts);
  21406. this.debug(this.pattern, this.globParts);
  21407. let set = this.globParts.map((s6, _3, __) => {
  21408. if (this.isWindows && this.windowsNoMagicRoot) {
  21409. const isUNC = s6[0] === "" && s6[1] === "" && (s6[2] === "?" || !globMagic.test(s6[2])) && !globMagic.test(s6[3]);
  21410. const isDrive = /^[a-z]:/i.test(s6[0]);
  21411. if (isUNC) {
  21412. return [...s6.slice(0, 4), ...s6.slice(4).map((ss) => this.parse(ss))];
  21413. } else if (isDrive) {
  21414. return [s6[0], ...s6.slice(1).map((ss) => this.parse(ss))];
  21415. }
  21416. }
  21417. return s6.map((ss) => this.parse(ss));
  21418. });
  21419. this.debug(this.pattern, set);
  21420. this.set = set.filter((s6) => s6.indexOf(false) === -1);
  21421. if (this.isWindows) {
  21422. for (let i6 = 0; i6 < this.set.length; i6++) {
  21423. const p5 = this.set[i6];
  21424. if (p5[0] === "" && p5[1] === "" && this.globParts[i6][2] === "?" && typeof p5[3] === "string" && /^[a-z]:$/i.test(p5[3])) {
  21425. p5[2] = "?";
  21426. }
  21427. }
  21428. }
  21429. this.debug(this.pattern, this.set);
  21430. }
  21431. // various transforms to equivalent pattern sets that are
  21432. // faster to process in a filesystem walk. The goal is to
  21433. // eliminate what we can, and push all ** patterns as far
  21434. // to the right as possible, even if it increases the number
  21435. // of patterns that we have to process.
  21436. preprocess(globParts) {
  21437. if (this.options.noglobstar) {
  21438. for (let i6 = 0; i6 < globParts.length; i6++) {
  21439. for (let j5 = 0; j5 < globParts[i6].length; j5++) {
  21440. if (globParts[i6][j5] === "**") {
  21441. globParts[i6][j5] = "*";
  21442. }
  21443. }
  21444. }
  21445. }
  21446. const { optimizationLevel = 1 } = this.options;
  21447. if (optimizationLevel >= 2) {
  21448. globParts = this.firstPhasePreProcess(globParts);
  21449. globParts = this.secondPhasePreProcess(globParts);
  21450. } else if (optimizationLevel >= 1) {
  21451. globParts = this.levelOneOptimize(globParts);
  21452. } else {
  21453. globParts = this.adjascentGlobstarOptimize(globParts);
  21454. }
  21455. return globParts;
  21456. }
  21457. // just get rid of adjascent ** portions
  21458. adjascentGlobstarOptimize(globParts) {
  21459. return globParts.map((parts) => {
  21460. let gs = -1;
  21461. while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
  21462. let i6 = gs;
  21463. while (parts[i6 + 1] === "**") {
  21464. i6++;
  21465. }
  21466. if (i6 !== gs) {
  21467. parts.splice(gs, i6 - gs);
  21468. }
  21469. }
  21470. return parts;
  21471. });
  21472. }
  21473. // get rid of adjascent ** and resolve .. portions
  21474. levelOneOptimize(globParts) {
  21475. return globParts.map((parts) => {
  21476. parts = parts.reduce((set, part) => {
  21477. const prev = set[set.length - 1];
  21478. if (part === "**" && prev === "**") {
  21479. return set;
  21480. }
  21481. if (part === "..") {
  21482. if (prev && prev !== ".." && prev !== "." && prev !== "**") {
  21483. set.pop();
  21484. return set;
  21485. }
  21486. }
  21487. set.push(part);
  21488. return set;
  21489. }, []);
  21490. return parts.length === 0 ? [""] : parts;
  21491. });
  21492. }
  21493. levelTwoFileOptimize(parts) {
  21494. if (!Array.isArray(parts)) {
  21495. parts = this.slashSplit(parts);
  21496. }
  21497. let didSomething = false;
  21498. do {
  21499. didSomething = false;
  21500. if (!this.preserveMultipleSlashes) {
  21501. for (let i6 = 1; i6 < parts.length - 1; i6++) {
  21502. const p5 = parts[i6];
  21503. if (i6 === 1 && p5 === "" && parts[0] === "")
  21504. continue;
  21505. if (p5 === "." || p5 === "") {
  21506. didSomething = true;
  21507. parts.splice(i6, 1);
  21508. i6--;
  21509. }
  21510. }
  21511. if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
  21512. didSomething = true;
  21513. parts.pop();
  21514. }
  21515. }
  21516. let dd = 0;
  21517. while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
  21518. const p5 = parts[dd - 1];
  21519. if (p5 && p5 !== "." && p5 !== ".." && p5 !== "**") {
  21520. didSomething = true;
  21521. parts.splice(dd - 1, 2);
  21522. dd -= 2;
  21523. }
  21524. }
  21525. } while (didSomething);
  21526. return parts.length === 0 ? [""] : parts;
  21527. }
  21528. // First phase: single-pattern processing
  21529. // <pre> is 1 or more portions
  21530. // <rest> is 1 or more portions
  21531. // <p> is any portion other than ., .., '', or **
  21532. // <e> is . or ''
  21533. //
  21534. // **/.. is *brutal* for filesystem walking performance, because
  21535. // it effectively resets the recursive walk each time it occurs,
  21536. // and ** cannot be reduced out by a .. pattern part like a regexp
  21537. // or most strings (other than .., ., and '') can be.
  21538. //
  21539. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  21540. // <pre>/<e>/<rest> -> <pre>/<rest>
  21541. // <pre>/<p>/../<rest> -> <pre>/<rest>
  21542. // **/**/<rest> -> **/<rest>
  21543. //
  21544. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  21545. // this WOULD be allowed if ** did follow symlinks, or * didn't
  21546. firstPhasePreProcess(globParts) {
  21547. let didSomething = false;
  21548. do {
  21549. didSomething = false;
  21550. for (let parts of globParts) {
  21551. let gs = -1;
  21552. while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
  21553. let gss = gs;
  21554. while (parts[gss + 1] === "**") {
  21555. gss++;
  21556. }
  21557. if (gss > gs) {
  21558. parts.splice(gs + 1, gss - gs);
  21559. }
  21560. let next = parts[gs + 1];
  21561. const p5 = parts[gs + 2];
  21562. const p22 = parts[gs + 3];
  21563. if (next !== "..")
  21564. continue;
  21565. if (!p5 || p5 === "." || p5 === ".." || !p22 || p22 === "." || p22 === "..") {
  21566. continue;
  21567. }
  21568. didSomething = true;
  21569. parts.splice(gs, 1);
  21570. const other = parts.slice(0);
  21571. other[gs] = "**";
  21572. globParts.push(other);
  21573. gs--;
  21574. }
  21575. if (!this.preserveMultipleSlashes) {
  21576. for (let i6 = 1; i6 < parts.length - 1; i6++) {
  21577. const p5 = parts[i6];
  21578. if (i6 === 1 && p5 === "" && parts[0] === "")
  21579. continue;
  21580. if (p5 === "." || p5 === "") {
  21581. didSomething = true;
  21582. parts.splice(i6, 1);
  21583. i6--;
  21584. }
  21585. }
  21586. if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
  21587. didSomething = true;
  21588. parts.pop();
  21589. }
  21590. }
  21591. let dd = 0;
  21592. while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
  21593. const p5 = parts[dd - 1];
  21594. if (p5 && p5 !== "." && p5 !== ".." && p5 !== "**") {
  21595. didSomething = true;
  21596. const needDot = dd === 1 && parts[dd + 1] === "**";
  21597. const splin = needDot ? ["."] : [];
  21598. parts.splice(dd - 1, 2, ...splin);
  21599. if (parts.length === 0)
  21600. parts.push("");
  21601. dd -= 2;
  21602. }
  21603. }
  21604. }
  21605. } while (didSomething);
  21606. return globParts;
  21607. }
  21608. // second phase: multi-pattern dedupes
  21609. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  21610. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  21611. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  21612. //
  21613. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  21614. // ^-- not valid because ** doens't follow symlinks
  21615. secondPhasePreProcess(globParts) {
  21616. for (let i6 = 0; i6 < globParts.length - 1; i6++) {
  21617. for (let j5 = i6 + 1; j5 < globParts.length; j5++) {
  21618. const matched = this.partsMatch(globParts[i6], globParts[j5], !this.preserveMultipleSlashes);
  21619. if (!matched)
  21620. continue;
  21621. globParts[i6] = matched;
  21622. globParts[j5] = [];
  21623. }
  21624. }
  21625. return globParts.filter((gs) => gs.length);
  21626. }
  21627. partsMatch(a5, b5, emptyGSMatch = false) {
  21628. let ai = 0;
  21629. let bi = 0;
  21630. let result = [];
  21631. let which = "";
  21632. while (ai < a5.length && bi < b5.length) {
  21633. if (a5[ai] === b5[bi]) {
  21634. result.push(which === "b" ? b5[bi] : a5[ai]);
  21635. ai++;
  21636. bi++;
  21637. } else if (emptyGSMatch && a5[ai] === "**" && b5[bi] === a5[ai + 1]) {
  21638. result.push(a5[ai]);
  21639. ai++;
  21640. } else if (emptyGSMatch && b5[bi] === "**" && a5[ai] === b5[bi + 1]) {
  21641. result.push(b5[bi]);
  21642. bi++;
  21643. } else if (a5[ai] === "*" && b5[bi] && (this.options.dot || !b5[bi].startsWith(".")) && b5[bi] !== "**") {
  21644. if (which === "b")
  21645. return false;
  21646. which = "a";
  21647. result.push(a5[ai]);
  21648. ai++;
  21649. bi++;
  21650. } else if (b5[bi] === "*" && a5[ai] && (this.options.dot || !a5[ai].startsWith(".")) && a5[ai] !== "**") {
  21651. if (which === "a")
  21652. return false;
  21653. which = "b";
  21654. result.push(b5[bi]);
  21655. ai++;
  21656. bi++;
  21657. } else {
  21658. return false;
  21659. }
  21660. }
  21661. return a5.length === b5.length && result;
  21662. }
  21663. parseNegate() {
  21664. if (this.nonegate)
  21665. return;
  21666. const pattern = this.pattern;
  21667. let negate2 = false;
  21668. let negateOffset = 0;
  21669. for (let i6 = 0; i6 < pattern.length && pattern.charAt(i6) === "!"; i6++) {
  21670. negate2 = !negate2;
  21671. negateOffset++;
  21672. }
  21673. if (negateOffset)
  21674. this.pattern = pattern.slice(negateOffset);
  21675. this.negate = negate2;
  21676. }
  21677. // set partial to true to test if, for example,
  21678. // "/a/b" matches the start of "/*/b/*/d"
  21679. // Partial means, if you run out of file before you run
  21680. // out of pattern, then that's fine, as long as all
  21681. // the parts match.
  21682. matchOne(file, pattern, partial = false) {
  21683. const options = this.options;
  21684. if (this.isWindows) {
  21685. const fileUNC = file[0] === "" && file[1] === "" && file[2] === "?" && typeof file[3] === "string" && /^[a-z]:$/i.test(file[3]);
  21686. const patternUNC = pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
  21687. if (fileUNC && patternUNC) {
  21688. const fd = file[3];
  21689. const pd = pattern[3];
  21690. if (fd.toLowerCase() === pd.toLowerCase()) {
  21691. file[3] = pd;
  21692. }
  21693. } else if (patternUNC && typeof file[0] === "string") {
  21694. const pd = pattern[3];
  21695. const fd = file[0];
  21696. if (pd.toLowerCase() === fd.toLowerCase()) {
  21697. pattern[3] = fd;
  21698. pattern = pattern.slice(3);
  21699. }
  21700. } else if (fileUNC && typeof pattern[0] === "string") {
  21701. const fd = file[3];
  21702. if (fd.toLowerCase() === pattern[0].toLowerCase()) {
  21703. pattern[0] = fd;
  21704. file = file.slice(3);
  21705. }
  21706. }
  21707. }
  21708. const { optimizationLevel = 1 } = this.options;
  21709. if (optimizationLevel >= 2) {
  21710. file = this.levelTwoFileOptimize(file);
  21711. }
  21712. this.debug("matchOne", this, { file, pattern });
  21713. this.debug("matchOne", file.length, pattern.length);
  21714. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  21715. this.debug("matchOne loop");
  21716. var p5 = pattern[pi];
  21717. var f7 = file[fi];
  21718. this.debug(pattern, p5, f7);
  21719. if (p5 === false) {
  21720. return false;
  21721. }
  21722. if (p5 === GLOBSTAR) {
  21723. this.debug("GLOBSTAR", [pattern, p5, f7]);
  21724. var fr = fi;
  21725. var pr = pi + 1;
  21726. if (pr === pl) {
  21727. this.debug("** at the end");
  21728. for (; fi < fl; fi++) {
  21729. if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
  21730. return false;
  21731. }
  21732. return true;
  21733. }
  21734. while (fr < fl) {
  21735. var swallowee = file[fr];
  21736. this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
  21737. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  21738. this.debug("globstar found match!", fr, fl, swallowee);
  21739. return true;
  21740. } else {
  21741. if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
  21742. this.debug("dot detected!", file, fr, pattern, pr);
  21743. break;
  21744. }
  21745. this.debug("globstar swallow a segment, and continue");
  21746. fr++;
  21747. }
  21748. }
  21749. if (partial) {
  21750. this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
  21751. if (fr === fl) {
  21752. return true;
  21753. }
  21754. }
  21755. return false;
  21756. }
  21757. let hit;
  21758. if (typeof p5 === "string") {
  21759. hit = f7 === p5;
  21760. this.debug("string match", p5, f7, hit);
  21761. } else {
  21762. hit = p5.test(f7);
  21763. this.debug("pattern match", p5, f7, hit);
  21764. }
  21765. if (!hit)
  21766. return false;
  21767. }
  21768. if (fi === fl && pi === pl) {
  21769. return true;
  21770. } else if (fi === fl) {
  21771. return partial;
  21772. } else if (pi === pl) {
  21773. return fi === fl - 1 && file[fi] === "";
  21774. } else {
  21775. throw new Error("wtf?");
  21776. }
  21777. }
  21778. braceExpand() {
  21779. return braceExpand(this.pattern, this.options);
  21780. }
  21781. parse(pattern) {
  21782. assertValidPattern(pattern);
  21783. const options = this.options;
  21784. if (pattern === "**")
  21785. return GLOBSTAR;
  21786. if (pattern === "")
  21787. return "";
  21788. let m6;
  21789. let fastTest = null;
  21790. if (m6 = pattern.match(starRE)) {
  21791. fastTest = options.dot ? starTestDot : starTest;
  21792. } else if (m6 = pattern.match(starDotExtRE)) {
  21793. fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m6[1]);
  21794. } else if (m6 = pattern.match(qmarksRE)) {
  21795. fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m6);
  21796. } else if (m6 = pattern.match(starDotStarRE)) {
  21797. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  21798. } else if (m6 = pattern.match(dotStarRE)) {
  21799. fastTest = dotStarTest;
  21800. }
  21801. let re = "";
  21802. let hasMagic = false;
  21803. let escaping = false;
  21804. const patternListStack = [];
  21805. const negativeLists = [];
  21806. let stateChar = false;
  21807. let uflag = false;
  21808. let pl;
  21809. let dotTravAllowed = pattern.charAt(0) === ".";
  21810. let dotFileAllowed = options.dot || dotTravAllowed;
  21811. const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  21812. const subPatternStart = (p5) => p5.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  21813. const clearStateChar = () => {
  21814. if (stateChar) {
  21815. switch (stateChar) {
  21816. case "*":
  21817. re += star;
  21818. hasMagic = true;
  21819. break;
  21820. case "?":
  21821. re += qmark;
  21822. hasMagic = true;
  21823. break;
  21824. default:
  21825. re += "\\" + stateChar;
  21826. break;
  21827. }
  21828. this.debug("clearStateChar %j %j", stateChar, re);
  21829. stateChar = false;
  21830. }
  21831. };
  21832. for (let i6 = 0, c5; i6 < pattern.length && (c5 = pattern.charAt(i6)); i6++) {
  21833. this.debug("%s %s %s %j", pattern, i6, re, c5);
  21834. if (escaping) {
  21835. if (c5 === "/") {
  21836. return false;
  21837. }
  21838. if (reSpecials[c5]) {
  21839. re += "\\";
  21840. }
  21841. re += c5;
  21842. escaping = false;
  21843. continue;
  21844. }
  21845. switch (c5) {
  21846. // Should already be path-split by now.
  21847. /* c8 ignore start */
  21848. case "/": {
  21849. return false;
  21850. }
  21851. /* c8 ignore stop */
  21852. case "\\":
  21853. clearStateChar();
  21854. escaping = true;
  21855. continue;
  21856. // the various stateChar values
  21857. // for the "extglob" stuff.
  21858. case "?":
  21859. case "*":
  21860. case "+":
  21861. case "@":
  21862. case "!":
  21863. this.debug("%s %s %s %j <-- stateChar", pattern, i6, re, c5);
  21864. this.debug("call clearStateChar %j", stateChar);
  21865. clearStateChar();
  21866. stateChar = c5;
  21867. if (options.noext)
  21868. clearStateChar();
  21869. continue;
  21870. case "(": {
  21871. if (!stateChar) {
  21872. re += "\\(";
  21873. continue;
  21874. }
  21875. const plEntry = {
  21876. type: stateChar,
  21877. start: i6 - 1,
  21878. reStart: re.length,
  21879. open: plTypes[stateChar].open,
  21880. close: plTypes[stateChar].close
  21881. };
  21882. this.debug(this.pattern, " ", plEntry);
  21883. patternListStack.push(plEntry);
  21884. re += plEntry.open;
  21885. if (plEntry.start === 0 && plEntry.type !== "!") {
  21886. dotTravAllowed = true;
  21887. re += subPatternStart(pattern.slice(i6 + 1));
  21888. }
  21889. this.debug("plType %j %j", stateChar, re);
  21890. stateChar = false;
  21891. continue;
  21892. }
  21893. case ")": {
  21894. const plEntry = patternListStack[patternListStack.length - 1];
  21895. if (!plEntry) {
  21896. re += "\\)";
  21897. continue;
  21898. }
  21899. patternListStack.pop();
  21900. clearStateChar();
  21901. hasMagic = true;
  21902. pl = plEntry;
  21903. re += pl.close;
  21904. if (pl.type === "!") {
  21905. negativeLists.push(Object.assign(pl, { reEnd: re.length }));
  21906. }
  21907. continue;
  21908. }
  21909. case "|": {
  21910. const plEntry = patternListStack[patternListStack.length - 1];
  21911. if (!plEntry) {
  21912. re += "\\|";
  21913. continue;
  21914. }
  21915. clearStateChar();
  21916. re += "|";
  21917. if (plEntry.start === 0 && plEntry.type !== "!") {
  21918. dotTravAllowed = true;
  21919. re += subPatternStart(pattern.slice(i6 + 1));
  21920. }
  21921. continue;
  21922. }
  21923. // these are mostly the same in regexp and glob
  21924. case "[":
  21925. clearStateChar();
  21926. const [src, needUflag, consumed, magic] = parseClass(pattern, i6);
  21927. if (consumed) {
  21928. re += src;
  21929. uflag = uflag || needUflag;
  21930. i6 += consumed - 1;
  21931. hasMagic = hasMagic || magic;
  21932. } else {
  21933. re += "\\[";
  21934. }
  21935. continue;
  21936. case "]":
  21937. re += "\\" + c5;
  21938. continue;
  21939. default:
  21940. clearStateChar();
  21941. re += regExpEscape(c5);
  21942. break;
  21943. }
  21944. }
  21945. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  21946. let tail;
  21947. tail = re.slice(pl.reStart + pl.open.length);
  21948. this.debug(this.pattern, "setting tail", re, pl);
  21949. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => {
  21950. if (!$2) {
  21951. $2 = "\\";
  21952. }
  21953. return $1 + $1 + $2 + "|";
  21954. });
  21955. this.debug("tail=%j\n %s", tail, tail, pl, re);
  21956. const t6 = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
  21957. hasMagic = true;
  21958. re = re.slice(0, pl.reStart) + t6 + "\\(" + tail;
  21959. }
  21960. clearStateChar();
  21961. if (escaping) {
  21962. re += "\\\\";
  21963. }
  21964. const addPatternStart = addPatternStartSet[re.charAt(0)];
  21965. for (let n5 = negativeLists.length - 1; n5 > -1; n5--) {
  21966. const nl = negativeLists[n5];
  21967. const nlBefore = re.slice(0, nl.reStart);
  21968. const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  21969. let nlAfter = re.slice(nl.reEnd);
  21970. const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
  21971. const closeParensBefore = nlBefore.split(")").length;
  21972. const openParensBefore = nlBefore.split("(").length - closeParensBefore;
  21973. let cleanAfter = nlAfter;
  21974. for (let i6 = 0; i6 < openParensBefore; i6++) {
  21975. cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
  21976. }
  21977. nlAfter = cleanAfter;
  21978. const dollar = nlAfter === "" ? "(?:$|\\/)" : "";
  21979. re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  21980. }
  21981. if (re !== "" && hasMagic) {
  21982. re = "(?=.)" + re;
  21983. }
  21984. if (addPatternStart) {
  21985. re = patternStart() + re;
  21986. }
  21987. if (options.nocase && !hasMagic && !options.nocaseMagicOnly) {
  21988. hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
  21989. }
  21990. if (!hasMagic) {
  21991. return globUnescape(re);
  21992. }
  21993. const flags = (options.nocase ? "i" : "") + (uflag ? "u" : "");
  21994. try {
  21995. const ext2 = fastTest ? {
  21996. _glob: pattern,
  21997. _src: re,
  21998. test: fastTest
  21999. } : {
  22000. _glob: pattern,
  22001. _src: re
  22002. };
  22003. return Object.assign(new RegExp("^" + re + "$", flags), ext2);
  22004. } catch (er) {
  22005. this.debug("invalid regexp", er);
  22006. return new RegExp("$.");
  22007. }
  22008. }
  22009. makeRe() {
  22010. if (this.regexp || this.regexp === false)
  22011. return this.regexp;
  22012. const set = this.set;
  22013. if (!set.length) {
  22014. this.regexp = false;
  22015. return this.regexp;
  22016. }
  22017. const options = this.options;
  22018. const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
  22019. const flags = options.nocase ? "i" : "";
  22020. let re = set.map((pattern) => {
  22021. const pp = pattern.map((p5) => typeof p5 === "string" ? regExpEscape(p5) : p5 === GLOBSTAR ? GLOBSTAR : p5._src);
  22022. pp.forEach((p5, i6) => {
  22023. const next = pp[i6 + 1];
  22024. const prev = pp[i6 - 1];
  22025. if (p5 !== GLOBSTAR || prev === GLOBSTAR) {
  22026. return;
  22027. }
  22028. if (prev === void 0) {
  22029. if (next !== void 0 && next !== GLOBSTAR) {
  22030. pp[i6 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
  22031. } else {
  22032. pp[i6] = twoStar;
  22033. }
  22034. } else if (next === void 0) {
  22035. pp[i6 - 1] = prev + "(?:\\/|" + twoStar + ")?";
  22036. } else if (next !== GLOBSTAR) {
  22037. pp[i6 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
  22038. pp[i6 + 1] = GLOBSTAR;
  22039. }
  22040. });
  22041. return pp.filter((p5) => p5 !== GLOBSTAR).join("/");
  22042. }).join("|");
  22043. re = "^(?:" + re + ")$";
  22044. if (this.negate)
  22045. re = "^(?!" + re + ").*$";
  22046. try {
  22047. this.regexp = new RegExp(re, flags);
  22048. } catch (ex) {
  22049. this.regexp = false;
  22050. }
  22051. return this.regexp;
  22052. }
  22053. slashSplit(p5) {
  22054. if (this.preserveMultipleSlashes) {
  22055. return p5.split("/");
  22056. } else if (this.isWindows && /^\/\/[^\/]+/.test(p5)) {
  22057. return ["", ...p5.split(/\/+/)];
  22058. } else {
  22059. return p5.split(/\/+/);
  22060. }
  22061. }
  22062. match(f7, partial = this.partial) {
  22063. this.debug("match", f7, this.pattern);
  22064. if (this.comment) {
  22065. return false;
  22066. }
  22067. if (this.empty) {
  22068. return f7 === "";
  22069. }
  22070. if (f7 === "/" && partial) {
  22071. return true;
  22072. }
  22073. const options = this.options;
  22074. if (this.isWindows) {
  22075. f7 = f7.split("\\").join("/");
  22076. }
  22077. const ff = this.slashSplit(f7);
  22078. this.debug(this.pattern, "split", ff);
  22079. const set = this.set;
  22080. this.debug(this.pattern, "set", set);
  22081. let filename = ff[ff.length - 1];
  22082. if (!filename) {
  22083. for (let i6 = ff.length - 2; !filename && i6 >= 0; i6--) {
  22084. filename = ff[i6];
  22085. }
  22086. }
  22087. for (let i6 = 0; i6 < set.length; i6++) {
  22088. const pattern = set[i6];
  22089. let file = ff;
  22090. if (options.matchBase && pattern.length === 1) {
  22091. file = [filename];
  22092. }
  22093. const hit = this.matchOne(file, pattern, partial);
  22094. if (hit) {
  22095. if (options.flipNegate) {
  22096. return true;
  22097. }
  22098. return !this.negate;
  22099. }
  22100. }
  22101. if (options.flipNegate) {
  22102. return false;
  22103. }
  22104. return this.negate;
  22105. }
  22106. static defaults(def) {
  22107. return minimatch.defaults(def).Minimatch;
  22108. }
  22109. };
  22110. minimatch.Minimatch = Minimatch;
  22111. minimatch.escape = escape;
  22112. minimatch.unescape = unescape2;
  22113. }
  22114. });
  22115. // src/extensions/vector.ts
  22116. var vectorOps;
  22117. var init_vector = __esm({
  22118. "src/extensions/vector.ts"() {
  22119. "use strict";
  22120. vectorOps = [
  22121. "vector_l2_ops",
  22122. "vector_ip_ops",
  22123. "vector_cosine_ops",
  22124. "vector_l1_ops",
  22125. "bit_hamming_ops",
  22126. "bit_jaccard_ops",
  22127. "halfvec_l2_ops",
  22128. "sparsevec_l2_ops"
  22129. ];
  22130. }
  22131. });
  22132. // src/serializer/utils.ts
  22133. import { CasingCache, toCamelCase, toSnakeCase } from "drizzle-orm/casing";
  22134. function getColumnCasing(column6, casing2) {
  22135. if (!column6.name) return "";
  22136. return !column6.keyAsName || casing2 === void 0 ? column6.name : casing2 === "camelCase" ? toCamelCase(column6.name) : toSnakeCase(column6.name);
  22137. }
  22138. var sqlToStr;
  22139. var init_utils2 = __esm({
  22140. "src/serializer/utils.ts"() {
  22141. "use strict";
  22142. sqlToStr = (sql, casing2) => {
  22143. return sql.toQuery({
  22144. escapeName: () => {
  22145. throw new Error("we don't support params for `sql` default values");
  22146. },
  22147. escapeParam: () => {
  22148. throw new Error("we don't support params for `sql` default values");
  22149. },
  22150. escapeString: () => {
  22151. throw new Error("we don't support params for `sql` default values");
  22152. },
  22153. casing: new CasingCache(casing2)
  22154. }).sql;
  22155. };
  22156. }
  22157. });
  22158. // src/serializer/pgSerializer.ts
  22159. import { getTableName, is, SQL } from "drizzle-orm";
  22160. import {
  22161. getMaterializedViewConfig,
  22162. getTableConfig,
  22163. getViewConfig,
  22164. PgArray,
  22165. PgColumn,
  22166. PgDialect,
  22167. PgEnumColumn,
  22168. PgRole,
  22169. PgView as PgView2,
  22170. uniqueKeyName
  22171. } from "drizzle-orm/pg-core";
  22172. function stringFromIdentityProperty(field) {
  22173. return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : String(field);
  22174. }
  22175. function maxRangeForIdentityBasedOn(columnType) {
  22176. return columnType === "integer" ? "2147483647" : columnType === "bigint" ? "9223372036854775807" : "32767";
  22177. }
  22178. function minRangeForIdentityBasedOn(columnType) {
  22179. return columnType === "integer" ? "-2147483648" : columnType === "bigint" ? "-9223372036854775808" : "-32768";
  22180. }
  22181. function stringFromDatabaseIdentityProperty(field) {
  22182. return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
  22183. }
  22184. function buildArrayString(array2, sqlType) {
  22185. sqlType = sqlType.split("[")[0];
  22186. const values = array2.map((value) => {
  22187. if (typeof value === "number" || typeof value === "bigint") {
  22188. return value.toString();
  22189. } else if (typeof value === "boolean") {
  22190. return value ? "true" : "false";
  22191. } else if (Array.isArray(value)) {
  22192. return buildArrayString(value, sqlType);
  22193. } else if (value instanceof Date) {
  22194. if (sqlType === "date") {
  22195. return `"${value.toISOString().split("T")[0]}"`;
  22196. } else if (sqlType === "timestamp") {
  22197. return `"${value.toISOString().replace("T", " ").slice(0, 23)}"`;
  22198. } else {
  22199. return `"${value.toISOString()}"`;
  22200. }
  22201. } else if (typeof value === "object") {
  22202. return `"${JSON.stringify(value).replaceAll('"', '\\"')}"`;
  22203. }
  22204. return `"${value}"`;
  22205. }).join(",");
  22206. return `{${values}}`;
  22207. }
  22208. function prepareRoles(entities) {
  22209. let useRoles = false;
  22210. const includeRoles = [];
  22211. const excludeRoles = [];
  22212. if (entities && entities.roles) {
  22213. if (typeof entities.roles === "object") {
  22214. if (entities.roles.provider) {
  22215. if (entities.roles.provider === "supabase") {
  22216. excludeRoles.push(...[
  22217. "anon",
  22218. "authenticator",
  22219. "authenticated",
  22220. "service_role",
  22221. "supabase_auth_admin",
  22222. "supabase_storage_admin",
  22223. "dashboard_user",
  22224. "supabase_admin"
  22225. ]);
  22226. } else if (entities.roles.provider === "neon") {
  22227. excludeRoles.push(...["authenticated", "anonymous"]);
  22228. }
  22229. }
  22230. if (entities.roles.include) {
  22231. includeRoles.push(...entities.roles.include);
  22232. }
  22233. if (entities.roles.exclude) {
  22234. excludeRoles.push(...entities.roles.exclude);
  22235. }
  22236. } else {
  22237. useRoles = entities.roles;
  22238. }
  22239. }
  22240. return { useRoles, includeRoles, excludeRoles };
  22241. }
  22242. var indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn, getColumnsInfoQuery;
  22243. var init_pgSerializer = __esm({
  22244. "src/serializer/pgSerializer.ts"() {
  22245. "use strict";
  22246. init_source();
  22247. init_vector();
  22248. init_outputs();
  22249. init_utils();
  22250. init_utils2();
  22251. indexName = (tableName, columns) => {
  22252. return `${tableName}_${columns.join("_")}_index`;
  22253. };
  22254. generatePgSnapshot = (tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter) => {
  22255. const dialect6 = new PgDialect({ casing: casing2 });
  22256. const result = {};
  22257. const resultViews = {};
  22258. const sequencesToReturn = {};
  22259. const rolesToReturn = {};
  22260. const policiesToReturn = {};
  22261. const indexesInSchema = {};
  22262. for (const table6 of tables) {
  22263. const checksInTable = {};
  22264. const {
  22265. name: tableName,
  22266. columns,
  22267. indexes,
  22268. foreignKeys,
  22269. checks,
  22270. schema: schema6,
  22271. primaryKeys,
  22272. uniqueConstraints,
  22273. policies: policies2,
  22274. enableRLS
  22275. } = getTableConfig(table6);
  22276. if (schemaFilter && !schemaFilter.includes(schema6 ?? "public")) {
  22277. continue;
  22278. }
  22279. const columnsObject = {};
  22280. const indexesObject = {};
  22281. const checksObject = {};
  22282. const foreignKeysObject = {};
  22283. const primaryKeysObject = {};
  22284. const uniqueConstraintObject = {};
  22285. const policiesObject = {};
  22286. columns.forEach((column6) => {
  22287. const name = getColumnCasing(column6, casing2);
  22288. const notNull = column6.notNull;
  22289. const primaryKey = column6.primary;
  22290. const sqlTypeLowered = column6.getSQLType().toLowerCase();
  22291. const getEnumSchema = (column7) => {
  22292. while (is(column7, PgArray)) {
  22293. column7 = column7.baseColumn;
  22294. }
  22295. return is(column7, PgEnumColumn) ? column7.enum.schema || "public" : void 0;
  22296. };
  22297. const typeSchema = getEnumSchema(column6);
  22298. const generated = column6.generated;
  22299. const identity = column6.generatedIdentity;
  22300. const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
  22301. const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column6.columnType) : "1");
  22302. const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column6.getSQLType()));
  22303. const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
  22304. const cache5 = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
  22305. const columnToSet = {
  22306. name,
  22307. type: column6.getSQLType(),
  22308. typeSchema,
  22309. primaryKey,
  22310. notNull,
  22311. generated: generated ? {
  22312. as: is(generated.as, SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  22313. type: "stored"
  22314. } : void 0,
  22315. identity: identity ? {
  22316. type: identity.type,
  22317. name: identity.sequenceName ?? `${tableName}_${name}_seq`,
  22318. schema: schema6 ?? "public",
  22319. increment,
  22320. startWith,
  22321. minValue,
  22322. maxValue,
  22323. cache: cache5,
  22324. cycle: identity?.sequenceOptions?.cycle ?? false
  22325. } : void 0
  22326. };
  22327. if (column6.isUnique) {
  22328. const existingUnique = uniqueConstraintObject[column6.uniqueName];
  22329. if (typeof existingUnique !== "undefined") {
  22330. console.log(
  22331. `
  22332. ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
  22333. tableName
  22334. )} table.
  22335. The unique constraint ${source_default.underline.blue(
  22336. column6.uniqueName
  22337. )} on the ${source_default.underline.blue(
  22338. name
  22339. )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
  22340. existingUnique.columns.join(",")
  22341. )} columns
  22342. `)}`
  22343. );
  22344. process.exit(1);
  22345. }
  22346. uniqueConstraintObject[column6.uniqueName] = {
  22347. name: column6.uniqueName,
  22348. nullsNotDistinct: column6.uniqueType === "not distinct",
  22349. columns: [columnToSet.name]
  22350. };
  22351. }
  22352. if (column6.default !== void 0) {
  22353. if (is(column6.default, SQL)) {
  22354. columnToSet.default = sqlToStr(column6.default, casing2);
  22355. } else {
  22356. if (typeof column6.default === "string") {
  22357. columnToSet.default = `'${escapeSingleQuotes(column6.default)}'`;
  22358. } else {
  22359. if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
  22360. columnToSet.default = `'${JSON.stringify(column6.default)}'::${sqlTypeLowered}`;
  22361. } else if (column6.default instanceof Date) {
  22362. if (sqlTypeLowered === "date") {
  22363. columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
  22364. } else if (sqlTypeLowered === "timestamp") {
  22365. columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  22366. } else {
  22367. columnToSet.default = `'${column6.default.toISOString()}'`;
  22368. }
  22369. } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column6.default)) {
  22370. columnToSet.default = `'${buildArrayString(column6.default, sqlTypeLowered)}'`;
  22371. } else {
  22372. columnToSet.default = column6.default;
  22373. }
  22374. }
  22375. }
  22376. }
  22377. columnsObject[name] = columnToSet;
  22378. });
  22379. primaryKeys.map((pk) => {
  22380. const originalColumnNames = pk.columns.map((c5) => c5.name);
  22381. const columnNames = pk.columns.map((c5) => getColumnCasing(c5, casing2));
  22382. let name = pk.getName();
  22383. if (casing2 !== void 0) {
  22384. for (let i6 = 0; i6 < originalColumnNames.length; i6++) {
  22385. name = name.replace(originalColumnNames[i6], columnNames[i6]);
  22386. }
  22387. }
  22388. primaryKeysObject[name] = {
  22389. name,
  22390. columns: columnNames
  22391. };
  22392. });
  22393. uniqueConstraints?.map((unq) => {
  22394. const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2));
  22395. const name = unq.name ?? uniqueKeyName(table6, columnNames);
  22396. const existingUnique = uniqueConstraintObject[name];
  22397. if (typeof existingUnique !== "undefined") {
  22398. console.log(
  22399. `
  22400. ${withStyle.errorWarning(
  22401. `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table.
  22402. The unique constraint ${source_default.underline.blue(name)} on the ${source_default.underline.blue(
  22403. columnNames.join(",")
  22404. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
  22405. `
  22406. )}`
  22407. );
  22408. process.exit(1);
  22409. }
  22410. uniqueConstraintObject[name] = {
  22411. name: unq.name,
  22412. nullsNotDistinct: unq.nullsNotDistinct,
  22413. columns: columnNames
  22414. };
  22415. });
  22416. const fks = foreignKeys.map((fk5) => {
  22417. const tableFrom = tableName;
  22418. const onDelete = fk5.onDelete;
  22419. const onUpdate = fk5.onUpdate;
  22420. const reference = fk5.reference();
  22421. const tableTo = getTableName(reference.foreignTable);
  22422. const schemaTo = getTableConfig(reference.foreignTable).schema;
  22423. const originalColumnsFrom = reference.columns.map((it) => it.name);
  22424. const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
  22425. const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
  22426. const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
  22427. let name = fk5.getName();
  22428. if (casing2 !== void 0) {
  22429. for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) {
  22430. name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]);
  22431. }
  22432. for (let i6 = 0; i6 < originalColumnsTo.length; i6++) {
  22433. name = name.replace(originalColumnsTo[i6], columnsTo[i6]);
  22434. }
  22435. }
  22436. return {
  22437. name,
  22438. tableFrom,
  22439. tableTo,
  22440. schemaTo,
  22441. columnsFrom,
  22442. columnsTo,
  22443. onDelete,
  22444. onUpdate
  22445. };
  22446. });
  22447. fks.forEach((it) => {
  22448. foreignKeysObject[it.name] = it;
  22449. });
  22450. indexes.forEach((value) => {
  22451. const columns2 = value.config.columns;
  22452. let indexColumnNames = [];
  22453. columns2.forEach((it) => {
  22454. if (is(it, SQL)) {
  22455. if (typeof value.config.name === "undefined") {
  22456. console.log(
  22457. `
  22458. ${withStyle.errorWarning(
  22459. `Please specify an index name in ${getTableName(value.config.table)} table that has "${dialect6.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.`
  22460. )}`
  22461. );
  22462. process.exit(1);
  22463. }
  22464. }
  22465. it = it;
  22466. const name2 = getColumnCasing(it, casing2);
  22467. if (!is(it, SQL) && it.type === "PgVector" && typeof it.indexConfig.opClass === "undefined") {
  22468. console.log(
  22469. `
  22470. ${withStyle.errorWarning(
  22471. `You are specifying an index on the ${source_default.blueBright(
  22472. name2
  22473. )} column inside the ${source_default.blueBright(
  22474. tableName
  22475. )} table with the ${source_default.blueBright(
  22476. "vector"
  22477. )} type without specifying an operator class. Vector extension doesn't have a default operator class, so you need to specify one of the available options. Here is a list of available op classes for the vector extension: [${vectorOps.map((it2) => `${source_default.underline(`${it2}`)}`).join(", ")}].
  22478. You can specify it using current syntax: ${source_default.underline(
  22479. `index("${value.config.name}").using("${value.config.method}", table.${name2}.op("${vectorOps[0]}"))`
  22480. )}
  22481. You can check the "pg_vector" docs for more info: https://github.com/pgvector/pgvector?tab=readme-ov-file#indexing
  22482. `
  22483. )}`
  22484. );
  22485. process.exit(1);
  22486. }
  22487. indexColumnNames.push(name2);
  22488. });
  22489. const name = value.config.name ? value.config.name : indexName(tableName, indexColumnNames);
  22490. let indexColumns = columns2.map(
  22491. (it) => {
  22492. if (is(it, SQL)) {
  22493. return {
  22494. expression: dialect6.sqlToQuery(it, "indexes").sql,
  22495. asc: true,
  22496. isExpression: true,
  22497. nulls: "last"
  22498. };
  22499. } else {
  22500. it = it;
  22501. return {
  22502. expression: getColumnCasing(it, casing2),
  22503. isExpression: false,
  22504. asc: it.indexConfig?.order === "asc",
  22505. nulls: it.indexConfig?.nulls ? it.indexConfig?.nulls : it.indexConfig?.order === "desc" ? "first" : "last",
  22506. opclass: it.indexConfig?.opClass
  22507. };
  22508. }
  22509. }
  22510. );
  22511. if (typeof indexesInSchema[schema6 ?? "public"] !== "undefined") {
  22512. if (indexesInSchema[schema6 ?? "public"].includes(name)) {
  22513. console.log(
  22514. `
  22515. ${withStyle.errorWarning(
  22516. `We've found duplicated index name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue(
  22517. tableName
  22518. )} table or the table with the duplicated index name`
  22519. )}`
  22520. );
  22521. process.exit(1);
  22522. }
  22523. indexesInSchema[schema6 ?? "public"].push(name);
  22524. } else {
  22525. indexesInSchema[schema6 ?? "public"] = [name];
  22526. }
  22527. indexesObject[name] = {
  22528. name,
  22529. columns: indexColumns,
  22530. isUnique: value.config.unique ?? false,
  22531. where: value.config.where ? dialect6.sqlToQuery(value.config.where).sql : void 0,
  22532. concurrently: value.config.concurrently ?? false,
  22533. method: value.config.method ?? "btree",
  22534. with: value.config.with ?? {}
  22535. };
  22536. });
  22537. policies2.forEach((policy5) => {
  22538. const mappedTo = [];
  22539. if (!policy5.to) {
  22540. mappedTo.push("public");
  22541. } else {
  22542. if (policy5.to && typeof policy5.to === "string") {
  22543. mappedTo.push(policy5.to);
  22544. } else if (policy5.to && is(policy5.to, PgRole)) {
  22545. mappedTo.push(policy5.to.name);
  22546. } else if (policy5.to && Array.isArray(policy5.to)) {
  22547. policy5.to.forEach((it) => {
  22548. if (typeof it === "string") {
  22549. mappedTo.push(it);
  22550. } else if (is(it, PgRole)) {
  22551. mappedTo.push(it.name);
  22552. }
  22553. });
  22554. }
  22555. }
  22556. if (policiesObject[policy5.name] !== void 0) {
  22557. console.log(
  22558. `
  22559. ${withStyle.errorWarning(
  22560. `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
  22561. policy5.name
  22562. )} name`
  22563. )}`
  22564. );
  22565. process.exit(1);
  22566. }
  22567. policiesObject[policy5.name] = {
  22568. name: policy5.name,
  22569. as: policy5.as?.toUpperCase() ?? "PERMISSIVE",
  22570. for: policy5.for?.toUpperCase() ?? "ALL",
  22571. to: mappedTo.sort(),
  22572. using: is(policy5.using, SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
  22573. withCheck: is(policy5.withCheck, SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
  22574. };
  22575. });
  22576. checks.forEach((check) => {
  22577. const checkName = check.name;
  22578. if (typeof checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] !== "undefined") {
  22579. if (checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].includes(check.name)) {
  22580. console.log(
  22581. `
  22582. ${withStyle.errorWarning(
  22583. `We've found duplicated check constraint name across ${source_default.underline.blue(
  22584. schema6 ?? "public"
  22585. )} schema in ${source_default.underline.blue(
  22586. tableName
  22587. )}. Please rename your check constraint in either the ${source_default.underline.blue(
  22588. tableName
  22589. )} table or the table with the duplicated check contraint name`
  22590. )}`
  22591. );
  22592. process.exit(1);
  22593. }
  22594. checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].push(checkName);
  22595. } else {
  22596. checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] = [check.name];
  22597. }
  22598. checksObject[checkName] = {
  22599. name: checkName,
  22600. value: dialect6.sqlToQuery(check.value).sql
  22601. };
  22602. });
  22603. const tableKey2 = `${schema6 ?? "public"}.${tableName}`;
  22604. result[tableKey2] = {
  22605. name: tableName,
  22606. schema: schema6 ?? "",
  22607. columns: columnsObject,
  22608. indexes: indexesObject,
  22609. foreignKeys: foreignKeysObject,
  22610. compositePrimaryKeys: primaryKeysObject,
  22611. uniqueConstraints: uniqueConstraintObject,
  22612. policies: policiesObject,
  22613. checkConstraints: checksObject,
  22614. isRLSEnabled: enableRLS
  22615. };
  22616. }
  22617. for (const policy5 of policies) {
  22618. if (!policy5._linkedTable) {
  22619. console.log(
  22620. `
  22621. ${withStyle.errorWarning(
  22622. `"Policy ${policy5.name} was skipped because it was not linked to any table. You should either include the policy in a table or use .link() on the policy to link it to any table you have. For more information, please check:`
  22623. )}`
  22624. );
  22625. continue;
  22626. }
  22627. const tableConfig = getTableConfig(policy5._linkedTable);
  22628. const tableKey2 = `${tableConfig.schema ?? "public"}.${tableConfig.name}`;
  22629. const mappedTo = [];
  22630. if (!policy5.to) {
  22631. mappedTo.push("public");
  22632. } else {
  22633. if (policy5.to && typeof policy5.to === "string") {
  22634. mappedTo.push(policy5.to);
  22635. } else if (policy5.to && is(policy5.to, PgRole)) {
  22636. mappedTo.push(policy5.to.name);
  22637. } else if (policy5.to && Array.isArray(policy5.to)) {
  22638. policy5.to.forEach((it) => {
  22639. if (typeof it === "string") {
  22640. mappedTo.push(it);
  22641. } else if (is(it, PgRole)) {
  22642. mappedTo.push(it.name);
  22643. }
  22644. });
  22645. }
  22646. }
  22647. if (result[tableKey2]?.policies[policy5.name] !== void 0 || policiesToReturn[policy5.name] !== void 0) {
  22648. console.log(
  22649. `
  22650. ${withStyle.errorWarning(
  22651. `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
  22652. policy5.name
  22653. )} name`
  22654. )}`
  22655. );
  22656. process.exit(1);
  22657. }
  22658. const mappedPolicy = {
  22659. name: policy5.name,
  22660. as: policy5.as?.toUpperCase() ?? "PERMISSIVE",
  22661. for: policy5.for?.toUpperCase() ?? "ALL",
  22662. to: mappedTo.sort(),
  22663. using: is(policy5.using, SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
  22664. withCheck: is(policy5.withCheck, SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
  22665. };
  22666. if (result[tableKey2]) {
  22667. result[tableKey2].policies[policy5.name] = mappedPolicy;
  22668. } else {
  22669. policiesToReturn[policy5.name] = {
  22670. ...mappedPolicy,
  22671. schema: tableConfig.schema ?? "public",
  22672. on: `"${tableConfig.schema ?? "public"}"."${tableConfig.name}"`
  22673. };
  22674. }
  22675. }
  22676. for (const sequence of sequences) {
  22677. const name = sequence.seqName;
  22678. if (typeof sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] === "undefined") {
  22679. const increment = stringFromIdentityProperty(sequence?.seqOptions?.increment) ?? "1";
  22680. const minValue = stringFromIdentityProperty(sequence?.seqOptions?.minValue) ?? (parseFloat(increment) < 0 ? "-9223372036854775808" : "1");
  22681. const maxValue = stringFromIdentityProperty(sequence?.seqOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : "9223372036854775807");
  22682. const startWith = stringFromIdentityProperty(sequence?.seqOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
  22683. const cache5 = stringFromIdentityProperty(sequence?.seqOptions?.cache) ?? "1";
  22684. sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] = {
  22685. name,
  22686. schema: sequence.schema ?? "public",
  22687. increment,
  22688. startWith,
  22689. minValue,
  22690. maxValue,
  22691. cache: cache5,
  22692. cycle: sequence.seqOptions?.cycle ?? false
  22693. };
  22694. } else {
  22695. }
  22696. }
  22697. for (const role of roles) {
  22698. if (!role._existing) {
  22699. rolesToReturn[role.name] = {
  22700. name: role.name,
  22701. createDb: role.createDb === void 0 ? false : role.createDb,
  22702. createRole: role.createRole === void 0 ? false : role.createRole,
  22703. inherit: role.inherit === void 0 ? true : role.inherit
  22704. };
  22705. }
  22706. }
  22707. const combinedViews = [...views, ...matViews];
  22708. for (const view5 of combinedViews) {
  22709. let viewName;
  22710. let schema6;
  22711. let query;
  22712. let selectedFields;
  22713. let isExisting;
  22714. let withOption;
  22715. let tablespace;
  22716. let using;
  22717. let withNoData;
  22718. let materialized = false;
  22719. if (is(view5, PgView2)) {
  22720. ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption } = getViewConfig(view5));
  22721. } else {
  22722. ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = getMaterializedViewConfig(view5));
  22723. materialized = true;
  22724. }
  22725. const viewSchema = schema6 ?? "public";
  22726. const viewKey = `${viewSchema}.${viewName}`;
  22727. const columnsObject = {};
  22728. const uniqueConstraintObject = {};
  22729. const existingView = resultViews[viewKey];
  22730. if (typeof existingView !== "undefined") {
  22731. console.log(
  22732. `
  22733. ${withStyle.errorWarning(
  22734. `We've found duplicated view name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your view`
  22735. )}`
  22736. );
  22737. process.exit(1);
  22738. }
  22739. for (const key in selectedFields) {
  22740. if (is(selectedFields[key], PgColumn)) {
  22741. const column6 = selectedFields[key];
  22742. const notNull = column6.notNull;
  22743. const primaryKey = column6.primary;
  22744. const sqlTypeLowered = column6.getSQLType().toLowerCase();
  22745. const typeSchema = is(column6, PgEnumColumn) ? column6.enum.schema || "public" : void 0;
  22746. const generated = column6.generated;
  22747. const identity = column6.generatedIdentity;
  22748. const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
  22749. const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column6.columnType) : "1");
  22750. const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column6.getSQLType()));
  22751. const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
  22752. const cache5 = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
  22753. const columnToSet = {
  22754. name: column6.name,
  22755. type: column6.getSQLType(),
  22756. typeSchema,
  22757. primaryKey,
  22758. notNull,
  22759. generated: generated ? {
  22760. as: is(generated.as, SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  22761. type: "stored"
  22762. } : void 0,
  22763. identity: identity ? {
  22764. type: identity.type,
  22765. name: identity.sequenceName ?? `${viewName}_${column6.name}_seq`,
  22766. schema: schema6 ?? "public",
  22767. increment,
  22768. startWith,
  22769. minValue,
  22770. maxValue,
  22771. cache: cache5,
  22772. cycle: identity?.sequenceOptions?.cycle ?? false
  22773. } : void 0
  22774. };
  22775. if (column6.isUnique) {
  22776. const existingUnique = uniqueConstraintObject[column6.uniqueName];
  22777. if (typeof existingUnique !== "undefined") {
  22778. console.log(
  22779. `
  22780. ${withStyle.errorWarning(
  22781. `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table.
  22782. The unique constraint ${source_default.underline.blue(column6.uniqueName)} on the ${source_default.underline.blue(
  22783. column6.name
  22784. )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
  22785. `
  22786. )}`
  22787. );
  22788. process.exit(1);
  22789. }
  22790. uniqueConstraintObject[column6.uniqueName] = {
  22791. name: column6.uniqueName,
  22792. nullsNotDistinct: column6.uniqueType === "not distinct",
  22793. columns: [columnToSet.name]
  22794. };
  22795. }
  22796. if (column6.default !== void 0) {
  22797. if (is(column6.default, SQL)) {
  22798. columnToSet.default = sqlToStr(column6.default, casing2);
  22799. } else {
  22800. if (typeof column6.default === "string") {
  22801. columnToSet.default = `'${column6.default}'`;
  22802. } else {
  22803. if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
  22804. columnToSet.default = `'${JSON.stringify(column6.default)}'::${sqlTypeLowered}`;
  22805. } else if (column6.default instanceof Date) {
  22806. if (sqlTypeLowered === "date") {
  22807. columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
  22808. } else if (sqlTypeLowered === "timestamp") {
  22809. columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  22810. } else {
  22811. columnToSet.default = `'${column6.default.toISOString()}'`;
  22812. }
  22813. } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column6.default)) {
  22814. columnToSet.default = `'${buildArrayString(column6.default, sqlTypeLowered)}'`;
  22815. } else {
  22816. columnToSet.default = column6.default;
  22817. }
  22818. }
  22819. }
  22820. }
  22821. columnsObject[column6.name] = columnToSet;
  22822. }
  22823. }
  22824. resultViews[viewKey] = {
  22825. columns: columnsObject,
  22826. definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
  22827. name: viewName,
  22828. schema: viewSchema,
  22829. isExisting,
  22830. with: withOption,
  22831. withNoData,
  22832. materialized,
  22833. tablespace,
  22834. using
  22835. };
  22836. }
  22837. const enumsToReturn = enums.reduce((map2, obj) => {
  22838. const enumSchema4 = obj.schema || "public";
  22839. const key = `${enumSchema4}.${obj.enumName}`;
  22840. map2[key] = {
  22841. name: obj.enumName,
  22842. schema: enumSchema4,
  22843. values: obj.enumValues
  22844. };
  22845. return map2;
  22846. }, {});
  22847. const schemasObject = Object.fromEntries(
  22848. schemas.filter((it) => {
  22849. if (schemaFilter) {
  22850. return schemaFilter.includes(it.schemaName) && it.schemaName !== "public";
  22851. } else {
  22852. return it.schemaName !== "public";
  22853. }
  22854. }).map((it) => [it.schemaName, it.schemaName])
  22855. );
  22856. return {
  22857. version: "7",
  22858. dialect: "postgresql",
  22859. tables: result,
  22860. enums: enumsToReturn,
  22861. schemas: schemasObject,
  22862. sequences: sequencesToReturn,
  22863. roles: rolesToReturn,
  22864. policies: policiesToReturn,
  22865. views: resultViews,
  22866. _meta: {
  22867. schemas: {},
  22868. tables: {},
  22869. columns: {}
  22870. }
  22871. };
  22872. };
  22873. trimChar = (str, char) => {
  22874. let start = 0;
  22875. let end = str.length;
  22876. while (start < end && str[start] === char) ++start;
  22877. while (end > start && str[end - 1] === char) --end;
  22878. return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
  22879. };
  22880. fromDatabase = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => {
  22881. const result = {};
  22882. const views = {};
  22883. const policies = {};
  22884. const internals = { tables: {} };
  22885. const where = schemaFilters.map((t6) => `n.nspname = '${t6}'`).join(" or ");
  22886. const allTables = await db.query(
  22887. `SELECT
  22888. n.nspname AS table_schema,
  22889. c.relname AS table_name,
  22890. CASE
  22891. WHEN c.relkind = 'r' THEN 'table'
  22892. WHEN c.relkind = 'v' THEN 'view'
  22893. WHEN c.relkind = 'm' THEN 'materialized_view'
  22894. END AS type,
  22895. c.relrowsecurity AS rls_enabled
  22896. FROM
  22897. pg_catalog.pg_class c
  22898. JOIN
  22899. pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  22900. WHERE
  22901. c.relkind IN ('r', 'v', 'm')
  22902. ${where === "" ? "" : ` AND ${where}`};`
  22903. );
  22904. const schemas = new Set(allTables.map((it) => it.table_schema));
  22905. schemas.delete("public");
  22906. const allSchemas = await db.query(`select s.nspname as table_schema
  22907. from pg_catalog.pg_namespace s
  22908. join pg_catalog.pg_user u on u.usesysid = s.nspowner
  22909. where nspname not in ('information_schema', 'pg_catalog', 'public')
  22910. and nspname not like 'pg_toast%'
  22911. and nspname not like 'pg_temp_%'
  22912. order by table_schema;`);
  22913. allSchemas.forEach((item) => {
  22914. if (schemaFilters.includes(item.table_schema)) {
  22915. schemas.add(item.table_schema);
  22916. }
  22917. });
  22918. let columnsCount = 0;
  22919. let indexesCount = 0;
  22920. let foreignKeysCount = 0;
  22921. let tableCount = 0;
  22922. let checksCount = 0;
  22923. let viewsCount = 0;
  22924. const sequencesToReturn = {};
  22925. const seqWhere = schemaFilters.map((t6) => `schemaname = '${t6}'`).join(" or ");
  22926. const allSequences = await db.query(
  22927. `select schemaname, sequencename, start_value, min_value, max_value, increment_by, cycle, cache_size from pg_sequences as seq${seqWhere === "" ? "" : ` WHERE ${seqWhere}`};`
  22928. );
  22929. for (const dbSeq of allSequences) {
  22930. const schemaName = dbSeq.schemaname;
  22931. const sequenceName = dbSeq.sequencename;
  22932. const startValue = stringFromDatabaseIdentityProperty(dbSeq.start_value);
  22933. const minValue = stringFromDatabaseIdentityProperty(dbSeq.min_value);
  22934. const maxValue = stringFromDatabaseIdentityProperty(dbSeq.max_value);
  22935. const incrementBy = stringFromDatabaseIdentityProperty(dbSeq.increment_by);
  22936. const cycle = dbSeq.cycle;
  22937. const cacheSize = stringFromDatabaseIdentityProperty(dbSeq.cache_size);
  22938. const key = `${schemaName}.${sequenceName}`;
  22939. sequencesToReturn[key] = {
  22940. name: sequenceName,
  22941. schema: schemaName,
  22942. startWith: startValue,
  22943. minValue,
  22944. maxValue,
  22945. increment: incrementBy,
  22946. cycle,
  22947. cache: cacheSize
  22948. };
  22949. }
  22950. const whereEnums = schemaFilters.map((t6) => `n.nspname = '${t6}'`).join(" or ");
  22951. const allEnums = await db.query(
  22952. `select n.nspname as enum_schema,
  22953. t.typname as enum_name,
  22954. e.enumlabel as enum_value,
  22955. e.enumsortorder as sort_order
  22956. from pg_type t
  22957. join pg_enum e on t.oid = e.enumtypid
  22958. join pg_catalog.pg_namespace n ON n.oid = t.typnamespace
  22959. ${whereEnums === "" ? "" : ` WHERE ${whereEnums}`}
  22960. order by enum_schema, enum_name, sort_order;`
  22961. );
  22962. const enumsToReturn = {};
  22963. for (const dbEnum of allEnums) {
  22964. const enumName = dbEnum.enum_name;
  22965. const enumValue = dbEnum.enum_value;
  22966. const enumSchema4 = dbEnum.enum_schema || "public";
  22967. const key = `${enumSchema4}.${enumName}`;
  22968. if (enumsToReturn[key] !== void 0 && enumsToReturn[key] !== null) {
  22969. enumsToReturn[key].values.push(enumValue);
  22970. } else {
  22971. enumsToReturn[key] = {
  22972. name: enumName,
  22973. values: [enumValue],
  22974. schema: enumSchema4
  22975. };
  22976. }
  22977. }
  22978. if (progressCallback) {
  22979. progressCallback("enums", Object.keys(enumsToReturn).length, "done");
  22980. }
  22981. const allRoles = await db.query(
  22982. `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;`
  22983. );
  22984. const rolesToReturn = {};
  22985. const preparedRoles = prepareRoles(entities);
  22986. if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) {
  22987. for (const dbRole of allRoles) {
  22988. if (preparedRoles.useRoles) {
  22989. rolesToReturn[dbRole.rolname] = {
  22990. createDb: dbRole.rolcreatedb,
  22991. createRole: dbRole.rolcreatedb,
  22992. inherit: dbRole.rolinherit,
  22993. name: dbRole.rolname
  22994. };
  22995. } else {
  22996. if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0) continue;
  22997. if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
  22998. if (preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
  22999. if (!preparedRoles.includeRoles.includes(dbRole.rolname)) continue;
  23000. rolesToReturn[dbRole.rolname] = {
  23001. createDb: dbRole.rolcreatedb,
  23002. createRole: dbRole.rolcreaterole,
  23003. inherit: dbRole.rolinherit,
  23004. name: dbRole.rolname
  23005. };
  23006. }
  23007. }
  23008. }
  23009. const schemasForLinkedPoliciesInSchema = Object.values(tsSchema?.policies ?? {}).map((it) => it.schema);
  23010. const wherePolicies = [...schemaFilters, ...schemasForLinkedPoliciesInSchema].map((t6) => `schemaname = '${t6}'`).join(" or ");
  23011. const policiesByTable = {};
  23012. const allPolicies = await db.query(`SELECT schemaname, tablename, policyname as name, permissive as "as", roles as to, cmd as for, qual as using, with_check as "withCheck" FROM pg_policies${wherePolicies === "" ? "" : ` WHERE ${wherePolicies}`};`);
  23013. for (const dbPolicy of allPolicies) {
  23014. const { tablename, schemaname, to, withCheck, using, ...rest } = dbPolicy;
  23015. const tableForPolicy = policiesByTable[`${schemaname}.${tablename}`];
  23016. const parsedTo = typeof to === "string" ? to.slice(1, -1).split(",") : to;
  23017. const parsedWithCheck = withCheck === null ? void 0 : withCheck;
  23018. const parsedUsing = using === null ? void 0 : using;
  23019. if (tableForPolicy) {
  23020. tableForPolicy[dbPolicy.name] = { ...rest, to: parsedTo };
  23021. } else {
  23022. policiesByTable[`${schemaname}.${tablename}`] = {
  23023. [dbPolicy.name]: { ...rest, to: parsedTo, withCheck: parsedWithCheck, using: parsedUsing }
  23024. };
  23025. }
  23026. if (tsSchema?.policies[dbPolicy.name]) {
  23027. policies[dbPolicy.name] = {
  23028. ...rest,
  23029. to: parsedTo,
  23030. withCheck: parsedWithCheck,
  23031. using: parsedUsing,
  23032. on: tsSchema?.policies[dbPolicy.name].on
  23033. };
  23034. }
  23035. }
  23036. if (progressCallback) {
  23037. progressCallback(
  23038. "policies",
  23039. Object.values(policiesByTable).reduce((total, innerRecord) => {
  23040. return total + Object.keys(innerRecord).length;
  23041. }, 0),
  23042. "done"
  23043. );
  23044. }
  23045. const sequencesInColumns = [];
  23046. const all = allTables.filter((it) => it.type === "table").map((row) => {
  23047. return new Promise(async (res, rej) => {
  23048. const tableName = row.table_name;
  23049. if (!tablesFilter(tableName)) return res("");
  23050. tableCount += 1;
  23051. const tableSchema = row.table_schema;
  23052. try {
  23053. const columnToReturn = {};
  23054. const indexToReturn = {};
  23055. const foreignKeysToReturn = {};
  23056. const primaryKeys = {};
  23057. const uniqueConstrains = {};
  23058. const checkConstraints = {};
  23059. const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
  23060. const tableConstraints = await db.query(
  23061. `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
  23062. FROM information_schema.table_constraints tc
  23063. JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
  23064. JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
  23065. AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
  23066. WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
  23067. );
  23068. const tableChecks = await db.query(`SELECT
  23069. tc.constraint_name,
  23070. tc.constraint_type,
  23071. pg_get_constraintdef(con.oid) AS constraint_definition
  23072. FROM
  23073. information_schema.table_constraints AS tc
  23074. JOIN pg_constraint AS con
  23075. ON tc.constraint_name = con.conname
  23076. AND con.conrelid = (
  23077. SELECT oid
  23078. FROM pg_class
  23079. WHERE relname = tc.table_name
  23080. AND relnamespace = (
  23081. SELECT oid
  23082. FROM pg_namespace
  23083. WHERE nspname = tc.constraint_schema
  23084. )
  23085. )
  23086. WHERE
  23087. tc.table_name = '${tableName}'
  23088. AND tc.constraint_schema = '${tableSchema}'
  23089. AND tc.constraint_type = 'CHECK'
  23090. AND con.contype = 'c';`);
  23091. columnsCount += tableResponse.length;
  23092. if (progressCallback) {
  23093. progressCallback("columns", columnsCount, "fetching");
  23094. }
  23095. const tableForeignKeys = await db.query(
  23096. `SELECT
  23097. con.contype AS constraint_type,
  23098. nsp.nspname AS constraint_schema,
  23099. con.conname AS constraint_name,
  23100. rel.relname AS table_name,
  23101. att.attname AS column_name,
  23102. fnsp.nspname AS foreign_table_schema,
  23103. frel.relname AS foreign_table_name,
  23104. fatt.attname AS foreign_column_name,
  23105. CASE con.confupdtype
  23106. WHEN 'a' THEN 'NO ACTION'
  23107. WHEN 'r' THEN 'RESTRICT'
  23108. WHEN 'n' THEN 'SET NULL'
  23109. WHEN 'c' THEN 'CASCADE'
  23110. WHEN 'd' THEN 'SET DEFAULT'
  23111. END AS update_rule,
  23112. CASE con.confdeltype
  23113. WHEN 'a' THEN 'NO ACTION'
  23114. WHEN 'r' THEN 'RESTRICT'
  23115. WHEN 'n' THEN 'SET NULL'
  23116. WHEN 'c' THEN 'CASCADE'
  23117. WHEN 'd' THEN 'SET DEFAULT'
  23118. END AS delete_rule
  23119. FROM
  23120. pg_catalog.pg_constraint con
  23121. JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
  23122. JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
  23123. LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
  23124. AND att.attrelid = con.conrelid
  23125. LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
  23126. LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
  23127. LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
  23128. AND fatt.attrelid = con.confrelid
  23129. WHERE
  23130. nsp.nspname = '${tableSchema}'
  23131. AND rel.relname = '${tableName}'
  23132. AND con.contype IN ('f');`
  23133. );
  23134. foreignKeysCount += tableForeignKeys.length;
  23135. if (progressCallback) {
  23136. progressCallback("fks", foreignKeysCount, "fetching");
  23137. }
  23138. for (const fk5 of tableForeignKeys) {
  23139. const columnFrom = fk5.column_name;
  23140. const tableTo = fk5.foreign_table_name;
  23141. const columnTo = fk5.foreign_column_name;
  23142. const schemaTo = fk5.foreign_table_schema;
  23143. const foreignKeyName = fk5.constraint_name;
  23144. const onUpdate = fk5.update_rule?.toLowerCase();
  23145. const onDelete = fk5.delete_rule?.toLowerCase();
  23146. if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
  23147. foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
  23148. foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
  23149. } else {
  23150. foreignKeysToReturn[foreignKeyName] = {
  23151. name: foreignKeyName,
  23152. tableFrom: tableName,
  23153. tableTo,
  23154. schemaTo,
  23155. columnsFrom: [columnFrom],
  23156. columnsTo: [columnTo],
  23157. onDelete,
  23158. onUpdate
  23159. };
  23160. }
  23161. foreignKeysToReturn[foreignKeyName].columnsFrom = [
  23162. ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
  23163. ];
  23164. foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
  23165. }
  23166. const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
  23167. for (const unqs of uniqueConstrainsRows) {
  23168. const columnName = unqs.column_name;
  23169. const constraintName = unqs.constraint_name;
  23170. if (typeof uniqueConstrains[constraintName] !== "undefined") {
  23171. uniqueConstrains[constraintName].columns.push(columnName);
  23172. } else {
  23173. uniqueConstrains[constraintName] = {
  23174. columns: [columnName],
  23175. nullsNotDistinct: false,
  23176. name: constraintName
  23177. };
  23178. }
  23179. }
  23180. checksCount += tableChecks.length;
  23181. if (progressCallback) {
  23182. progressCallback("checks", checksCount, "fetching");
  23183. }
  23184. for (const checks of tableChecks) {
  23185. let checkValue = checks.constraint_definition;
  23186. const constraintName = checks.constraint_name;
  23187. checkValue = checkValue.replace(/^CHECK\s*\(\(/, "").replace(/\)\)\s*$/, "");
  23188. checkConstraints[constraintName] = {
  23189. name: constraintName,
  23190. value: checkValue
  23191. };
  23192. }
  23193. for (const columnResponse of tableResponse) {
  23194. const columnName = columnResponse.column_name;
  23195. const columnAdditionalDT = columnResponse.additional_dt;
  23196. const columnDimensions = columnResponse.array_dimensions;
  23197. const enumType2 = columnResponse.enum_name;
  23198. let columnType = columnResponse.data_type;
  23199. const typeSchema = columnResponse.type_schema;
  23200. const defaultValueRes = columnResponse.column_default;
  23201. const isGenerated = columnResponse.is_generated === "ALWAYS";
  23202. const generationExpression = columnResponse.generation_expression;
  23203. const isIdentity = columnResponse.is_identity === "YES";
  23204. const identityGeneration = columnResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
  23205. const identityStart = columnResponse.identity_start;
  23206. const identityIncrement = columnResponse.identity_increment;
  23207. const identityMaximum = columnResponse.identity_maximum;
  23208. const identityMinimum = columnResponse.identity_minimum;
  23209. const identityCycle = columnResponse.identity_cycle === "YES";
  23210. const identityName = columnResponse.seq_name;
  23211. const primaryKey = tableConstraints.filter(
  23212. (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
  23213. );
  23214. const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
  23215. if (cprimaryKey.length > 1) {
  23216. const tableCompositePkName = await db.query(
  23217. `SELECT conname AS primary_key
  23218. FROM pg_constraint join pg_class on (pg_class.oid = conrelid)
  23219. WHERE contype = 'p'
  23220. AND connamespace = $1::regnamespace
  23221. AND pg_class.relname = $2;`,
  23222. [tableSchema, tableName]
  23223. );
  23224. primaryKeys[tableCompositePkName[0].primary_key] = {
  23225. name: tableCompositePkName[0].primary_key,
  23226. columns: cprimaryKey.map((c5) => c5.column_name)
  23227. };
  23228. }
  23229. let columnTypeMapped = columnType;
  23230. if (columnAdditionalDT === "ARRAY") {
  23231. if (typeof internals.tables[tableName] === "undefined") {
  23232. internals.tables[tableName] = {
  23233. columns: {
  23234. [columnName]: {
  23235. isArray: true,
  23236. dimensions: columnDimensions,
  23237. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  23238. }
  23239. }
  23240. };
  23241. } else {
  23242. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  23243. internals.tables[tableName].columns[columnName] = {
  23244. isArray: true,
  23245. dimensions: columnDimensions,
  23246. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  23247. };
  23248. }
  23249. }
  23250. }
  23251. const defaultValue = defaultForColumn(columnResponse, internals, tableName);
  23252. if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
  23253. if (typeof internals.tables[tableName] === "undefined") {
  23254. internals.tables[tableName] = {
  23255. columns: {
  23256. [columnName]: {
  23257. isDefaultAnExpression: true
  23258. }
  23259. }
  23260. };
  23261. } else {
  23262. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  23263. internals.tables[tableName].columns[columnName] = {
  23264. isDefaultAnExpression: true
  23265. };
  23266. } else {
  23267. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  23268. }
  23269. }
  23270. }
  23271. const isSerial = columnType === "serial";
  23272. if (columnTypeMapped.startsWith("numeric(")) {
  23273. columnTypeMapped = columnTypeMapped.replace(",", ", ");
  23274. }
  23275. if (columnAdditionalDT === "ARRAY") {
  23276. for (let i6 = 1; i6 < Number(columnDimensions); i6++) {
  23277. columnTypeMapped += "[]";
  23278. }
  23279. }
  23280. columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
  23281. columnTypeMapped = trimChar(columnTypeMapped, '"');
  23282. columnToReturn[columnName] = {
  23283. name: columnName,
  23284. type: (
  23285. // filter vectors, but in future we should filter any extension that was installed by user
  23286. columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
  23287. ),
  23288. typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
  23289. primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
  23290. // default: isSerial ? undefined : defaultValue,
  23291. notNull: columnResponse.is_nullable === "NO",
  23292. generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
  23293. identity: isIdentity ? {
  23294. type: identityGeneration,
  23295. name: identityName,
  23296. increment: stringFromDatabaseIdentityProperty(identityIncrement),
  23297. minValue: stringFromDatabaseIdentityProperty(identityMinimum),
  23298. maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
  23299. startWith: stringFromDatabaseIdentityProperty(identityStart),
  23300. cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${tableSchema}.${identityName}`]?.cache ? sequencesToReturn[`${tableSchema}.${identityName}`]?.cache : void 0,
  23301. cycle: identityCycle,
  23302. schema: tableSchema
  23303. } : void 0
  23304. };
  23305. if (identityName && typeof identityName === "string") {
  23306. delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
  23307. delete sequencesToReturn[identityName];
  23308. }
  23309. if (!isSerial && typeof defaultValue !== "undefined") {
  23310. columnToReturn[columnName].default = defaultValue;
  23311. }
  23312. }
  23313. const dbIndexes = await db.query(
  23314. `SELECT DISTINCT ON (t.relname, ic.relname, k.i) t.relname as table_name, ic.relname AS indexname,
  23315. k.i AS index_order,
  23316. i.indisunique as is_unique,
  23317. am.amname as method,
  23318. ic.reloptions as with,
  23319. coalesce(a.attname, pg_get_indexdef(i.indexrelid, k.i, false)) AS column_name,
  23320. CASE
  23321. WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1
  23322. ELSE 0
  23323. END AS is_expression,
  23324. i.indoption[k.i-1] & 1 = 1 AS descending,
  23325. i.indoption[k.i-1] & 2 = 2 AS nulls_first,
  23326. pg_get_expr(
  23327. i.indpred,
  23328. i.indrelid
  23329. ) as where,
  23330. opc.opcname
  23331. FROM pg_class t
  23332. LEFT JOIN pg_index i ON t.oid = i.indrelid
  23333. LEFT JOIN pg_class ic ON ic.oid = i.indexrelid
  23334. CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i)
  23335. LEFT JOIN pg_attribute AS a
  23336. ON i.indrelid = a.attrelid AND k.attnum = a.attnum
  23337. JOIN pg_namespace c on c.oid = t.relnamespace
  23338. LEFT JOIN pg_am AS am ON ic.relam = am.oid
  23339. JOIN pg_opclass opc ON opc.oid = ANY(i.indclass)
  23340. WHERE
  23341. c.nspname = '${tableSchema}' AND
  23342. t.relname = '${tableName}';`
  23343. );
  23344. const dbIndexFromConstraint = await db.query(
  23345. `SELECT
  23346. idx.indexrelname AS index_name,
  23347. idx.relname AS table_name,
  23348. schemaname,
  23349. CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
  23350. FROM
  23351. pg_stat_user_indexes idx
  23352. LEFT JOIN
  23353. pg_constraint con ON con.conindid = idx.indexrelid
  23354. WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
  23355. group by index_name, table_name,schemaname, generated_by_constraint;`
  23356. );
  23357. const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
  23358. (it) => it.index_name
  23359. );
  23360. for (const dbIndex of dbIndexes) {
  23361. const indexName2 = dbIndex.indexname;
  23362. const indexColumnName = dbIndex.column_name;
  23363. const indexIsUnique = dbIndex.is_unique;
  23364. const indexMethod = dbIndex.method;
  23365. const indexWith = dbIndex.with;
  23366. const indexWhere = dbIndex.where;
  23367. const opclass = dbIndex.opcname;
  23368. const isExpression = dbIndex.is_expression === 1;
  23369. const desc = dbIndex.descending;
  23370. const nullsFirst = dbIndex.nulls_first;
  23371. const mappedWith = {};
  23372. if (indexWith !== null) {
  23373. indexWith.forEach((it) => {
  23374. const splitted = it.split("=");
  23375. mappedWith[splitted[0]] = splitted[1];
  23376. });
  23377. }
  23378. if (idxsInConsteraint.includes(indexName2)) continue;
  23379. if (typeof indexToReturn[indexName2] !== "undefined") {
  23380. indexToReturn[indexName2].columns.push({
  23381. expression: indexColumnName,
  23382. asc: !desc,
  23383. nulls: nullsFirst ? "first" : "last",
  23384. opclass,
  23385. isExpression
  23386. });
  23387. } else {
  23388. indexToReturn[indexName2] = {
  23389. name: indexName2,
  23390. columns: [
  23391. {
  23392. expression: indexColumnName,
  23393. asc: !desc,
  23394. nulls: nullsFirst ? "first" : "last",
  23395. opclass,
  23396. isExpression
  23397. }
  23398. ],
  23399. isUnique: indexIsUnique,
  23400. // should not be a part of diff detects
  23401. concurrently: false,
  23402. method: indexMethod,
  23403. where: indexWhere === null ? void 0 : indexWhere,
  23404. with: mappedWith
  23405. };
  23406. }
  23407. }
  23408. indexesCount += Object.keys(indexToReturn).length;
  23409. if (progressCallback) {
  23410. progressCallback("indexes", indexesCount, "fetching");
  23411. }
  23412. result[`${tableSchema}.${tableName}`] = {
  23413. name: tableName,
  23414. schema: tableSchema !== "public" ? tableSchema : "",
  23415. columns: columnToReturn,
  23416. indexes: indexToReturn,
  23417. foreignKeys: foreignKeysToReturn,
  23418. compositePrimaryKeys: primaryKeys,
  23419. uniqueConstraints: uniqueConstrains,
  23420. checkConstraints,
  23421. policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {},
  23422. isRLSEnabled: row.rls_enabled
  23423. };
  23424. } catch (e6) {
  23425. rej(e6);
  23426. return;
  23427. }
  23428. res("");
  23429. });
  23430. });
  23431. if (progressCallback) {
  23432. progressCallback("tables", tableCount, "done");
  23433. }
  23434. for await (const _3 of all) {
  23435. }
  23436. const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
  23437. return new Promise(async (res, rej) => {
  23438. const viewName = row.table_name;
  23439. if (!tablesFilter(viewName)) return res("");
  23440. tableCount += 1;
  23441. const viewSchema = row.table_schema;
  23442. try {
  23443. const columnToReturn = {};
  23444. const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
  23445. for (const viewResponse of viewResponses) {
  23446. const columnName = viewResponse.column_name;
  23447. const columnAdditionalDT = viewResponse.additional_dt;
  23448. const columnDimensions = viewResponse.array_dimensions;
  23449. const enumType2 = viewResponse.enum_name;
  23450. let columnType = viewResponse.data_type;
  23451. const typeSchema = viewResponse.type_schema;
  23452. const isGenerated = viewResponse.is_generated === "ALWAYS";
  23453. const generationExpression = viewResponse.generation_expression;
  23454. const isIdentity = viewResponse.is_identity === "YES";
  23455. const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
  23456. const identityStart = viewResponse.identity_start;
  23457. const identityIncrement = viewResponse.identity_increment;
  23458. const identityMaximum = viewResponse.identity_maximum;
  23459. const identityMinimum = viewResponse.identity_minimum;
  23460. const identityCycle = viewResponse.identity_cycle === "YES";
  23461. const identityName = viewResponse.seq_name;
  23462. const defaultValueRes = viewResponse.column_default;
  23463. const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
  23464. let columnTypeMapped = columnType;
  23465. if (columnAdditionalDT === "ARRAY") {
  23466. if (typeof internals.tables[viewName] === "undefined") {
  23467. internals.tables[viewName] = {
  23468. columns: {
  23469. [columnName]: {
  23470. isArray: true,
  23471. dimensions: columnDimensions,
  23472. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  23473. }
  23474. }
  23475. };
  23476. } else {
  23477. if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
  23478. internals.tables[viewName].columns[columnName] = {
  23479. isArray: true,
  23480. dimensions: columnDimensions,
  23481. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  23482. };
  23483. }
  23484. }
  23485. }
  23486. const defaultValue = defaultForColumn(viewResponse, internals, viewName);
  23487. if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
  23488. if (typeof internals.tables[viewName] === "undefined") {
  23489. internals.tables[viewName] = {
  23490. columns: {
  23491. [columnName]: {
  23492. isDefaultAnExpression: true
  23493. }
  23494. }
  23495. };
  23496. } else {
  23497. if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
  23498. internals.tables[viewName].columns[columnName] = {
  23499. isDefaultAnExpression: true
  23500. };
  23501. } else {
  23502. internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
  23503. }
  23504. }
  23505. }
  23506. const isSerial = columnType === "serial";
  23507. if (columnTypeMapped.startsWith("numeric(")) {
  23508. columnTypeMapped = columnTypeMapped.replace(",", ", ");
  23509. }
  23510. if (columnAdditionalDT === "ARRAY") {
  23511. for (let i6 = 1; i6 < Number(columnDimensions); i6++) {
  23512. columnTypeMapped += "[]";
  23513. }
  23514. }
  23515. columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
  23516. columnTypeMapped = trimChar(columnTypeMapped, '"');
  23517. columnToReturn[columnName] = {
  23518. name: columnName,
  23519. type: (
  23520. // filter vectors, but in future we should filter any extension that was installed by user
  23521. columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
  23522. ),
  23523. typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
  23524. primaryKey,
  23525. notNull: viewResponse.is_nullable === "NO",
  23526. generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
  23527. identity: isIdentity ? {
  23528. type: identityGeneration,
  23529. name: identityName,
  23530. increment: stringFromDatabaseIdentityProperty(identityIncrement),
  23531. minValue: stringFromDatabaseIdentityProperty(identityMinimum),
  23532. maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
  23533. startWith: stringFromDatabaseIdentityProperty(identityStart),
  23534. cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${viewSchema}.${identityName}`]?.cache ? sequencesToReturn[`${viewSchema}.${identityName}`]?.cache : void 0,
  23535. cycle: identityCycle,
  23536. schema: viewSchema
  23537. } : void 0
  23538. };
  23539. if (identityName) {
  23540. delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
  23541. delete sequencesToReturn[identityName];
  23542. }
  23543. if (!isSerial && typeof defaultValue !== "undefined") {
  23544. columnToReturn[columnName].default = defaultValue;
  23545. }
  23546. }
  23547. const [viewInfo] = await db.query(`
  23548. SELECT
  23549. c.relname AS view_name,
  23550. n.nspname AS schema_name,
  23551. pg_get_viewdef(c.oid, true) AS definition,
  23552. ts.spcname AS tablespace_name,
  23553. c.reloptions AS options,
  23554. pg_tablespace_location(ts.oid) AS location
  23555. FROM
  23556. pg_class c
  23557. JOIN
  23558. pg_namespace n ON c.relnamespace = n.oid
  23559. LEFT JOIN
  23560. pg_tablespace ts ON c.reltablespace = ts.oid
  23561. WHERE
  23562. (c.relkind = 'm' OR c.relkind = 'v')
  23563. AND n.nspname = '${viewSchema}'
  23564. AND c.relname = '${viewName}';`);
  23565. const resultWith = {};
  23566. if (viewInfo.options) {
  23567. viewInfo.options.forEach((pair) => {
  23568. const splitted = pair.split("=");
  23569. const key = splitted[0];
  23570. const value = splitted[1];
  23571. if (value === "true") {
  23572. resultWith[key] = true;
  23573. } else if (value === "false") {
  23574. resultWith[key] = false;
  23575. } else if (!isNaN(Number(value))) {
  23576. resultWith[key] = Number(value);
  23577. } else {
  23578. resultWith[key] = value;
  23579. }
  23580. });
  23581. }
  23582. const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
  23583. const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
  23584. const materialized = row.type === "materialized_view";
  23585. views[`${viewSchema}.${viewName}`] = {
  23586. name: viewName,
  23587. schema: viewSchema,
  23588. columns: columnToReturn,
  23589. isExisting: false,
  23590. definition,
  23591. materialized,
  23592. with: withOption,
  23593. tablespace: viewInfo.tablespace_name ?? void 0
  23594. };
  23595. } catch (e6) {
  23596. rej(e6);
  23597. return;
  23598. }
  23599. res("");
  23600. });
  23601. });
  23602. viewsCount = allViews.length;
  23603. for await (const _3 of allViews) {
  23604. }
  23605. if (progressCallback) {
  23606. progressCallback("columns", columnsCount, "done");
  23607. progressCallback("indexes", indexesCount, "done");
  23608. progressCallback("fks", foreignKeysCount, "done");
  23609. progressCallback("checks", checksCount, "done");
  23610. progressCallback("views", viewsCount, "done");
  23611. }
  23612. const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
  23613. return {
  23614. version: "7",
  23615. dialect: "postgresql",
  23616. tables: result,
  23617. enums: enumsToReturn,
  23618. schemas: schemasObject,
  23619. sequences: sequencesToReturn,
  23620. roles: rolesToReturn,
  23621. policies,
  23622. views,
  23623. _meta: {
  23624. schemas: {},
  23625. tables: {},
  23626. columns: {}
  23627. },
  23628. internal: internals
  23629. };
  23630. };
  23631. defaultForColumn = (column6, internals, tableName) => {
  23632. const columnName = column6.column_name;
  23633. const isArray = internals?.tables[tableName]?.columns[columnName]?.isArray ?? false;
  23634. if (column6.column_default === null || column6.column_default === void 0 || column6.data_type === "serial" || column6.data_type === "smallserial" || column6.data_type === "bigserial") {
  23635. return void 0;
  23636. }
  23637. if (column6.column_default.endsWith("[]")) {
  23638. column6.column_default = column6.column_default.slice(0, -2);
  23639. }
  23640. column6.column_default = column6.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
  23641. const columnDefaultAsString = column6.column_default.toString();
  23642. if (isArray) {
  23643. return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
  23644. if (["integer", "smallint", "bigint", "double precision", "real"].includes(column6.data_type.slice(0, -2))) {
  23645. return value;
  23646. } else if (column6.data_type.startsWith("timestamp")) {
  23647. return `${value}`;
  23648. } else if (column6.data_type.slice(0, -2) === "interval") {
  23649. return value.replaceAll('"', `"`);
  23650. } else if (column6.data_type.slice(0, -2) === "boolean") {
  23651. return value === "t" ? "true" : "false";
  23652. } else if (["json", "jsonb"].includes(column6.data_type.slice(0, -2))) {
  23653. return JSON.stringify(JSON.stringify(JSON.parse(JSON.parse(value)), null, 0));
  23654. } else {
  23655. return `"${value}"`;
  23656. }
  23657. }).join(",")}}'`;
  23658. }
  23659. if (["integer", "smallint", "bigint", "double precision", "real"].includes(column6.data_type)) {
  23660. if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
  23661. return Number(columnDefaultAsString);
  23662. } else {
  23663. if (typeof internals.tables[tableName] === "undefined") {
  23664. internals.tables[tableName] = {
  23665. columns: {
  23666. [columnName]: {
  23667. isDefaultAnExpression: true
  23668. }
  23669. }
  23670. };
  23671. } else {
  23672. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  23673. internals.tables[tableName].columns[columnName] = {
  23674. isDefaultAnExpression: true
  23675. };
  23676. } else {
  23677. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  23678. }
  23679. }
  23680. return columnDefaultAsString;
  23681. }
  23682. } else if (column6.data_type.includes("numeric")) {
  23683. return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
  23684. } else if (column6.data_type === "json" || column6.data_type === "jsonb") {
  23685. const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
  23686. return `'${jsonWithoutSpaces}'::${column6.data_type}`;
  23687. } else if (column6.data_type === "boolean") {
  23688. return column6.column_default === "true";
  23689. } else if (columnDefaultAsString === "NULL") {
  23690. return `NULL`;
  23691. } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
  23692. return columnDefaultAsString;
  23693. } else {
  23694. return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
  23695. }
  23696. };
  23697. getColumnsInfoQuery = ({ schema: schema6, table: table6, db }) => {
  23698. return db.query(
  23699. `SELECT
  23700. a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name
  23701. a.attname AS column_name, -- Column name
  23702. CASE
  23703. WHEN NOT a.attisdropped THEN
  23704. CASE
  23705. WHEN a.attnotnull THEN 'NO'
  23706. ELSE 'YES'
  23707. END
  23708. ELSE NULL
  23709. END AS is_nullable, -- NULL or NOT NULL constraint
  23710. a.attndims AS array_dimensions, -- Array dimensions
  23711. CASE
  23712. WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
  23713. AND EXISTS (
  23714. SELECT FROM pg_attrdef ad
  23715. WHERE ad.adrelid = a.attrelid
  23716. AND ad.adnum = a.attnum
  23717. AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
  23718. || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
  23719. )
  23720. THEN CASE a.atttypid
  23721. WHEN 'int'::regtype THEN 'serial'
  23722. WHEN 'int8'::regtype THEN 'bigserial'
  23723. WHEN 'int2'::regtype THEN 'smallserial'
  23724. END
  23725. ELSE format_type(a.atttypid, a.atttypmod)
  23726. END AS data_type, -- Column data type
  23727. -- ns.nspname AS type_schema, -- Schema name
  23728. pg_get_serial_sequence('"${schema6}"."${table6}"', a.attname)::regclass AS seq_name, -- Serial sequence (if any)
  23729. c.column_default, -- Column default value
  23730. c.data_type AS additional_dt, -- Data type from information_schema
  23731. c.udt_name AS enum_name, -- Enum type (if applicable)
  23732. c.is_generated, -- Is it a generated column?
  23733. c.generation_expression, -- Generation expression (if generated)
  23734. c.is_identity, -- Is it an identity column?
  23735. c.identity_generation, -- Identity generation strategy (ALWAYS or BY DEFAULT)
  23736. c.identity_start, -- Start value of identity column
  23737. c.identity_increment, -- Increment for identity column
  23738. c.identity_maximum, -- Maximum value for identity column
  23739. c.identity_minimum, -- Minimum value for identity column
  23740. c.identity_cycle, -- Does the identity column cycle?
  23741. enum_ns.nspname AS type_schema -- Schema of the enum type
  23742. FROM
  23743. pg_attribute a
  23744. JOIN
  23745. pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info
  23746. JOIN
  23747. pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info
  23748. LEFT JOIN
  23749. information_schema.columns c ON c.column_name = a.attname
  23750. AND c.table_schema = ns.nspname
  23751. AND c.table_name = cls.relname -- Match schema and table/view name
  23752. LEFT JOIN
  23753. pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info
  23754. LEFT JOIN
  23755. pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema
  23756. WHERE
  23757. a.attnum > 0 -- Valid column numbers only
  23758. AND NOT a.attisdropped -- Skip dropped columns
  23759. AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m')
  23760. AND ns.nspname = '${schema6}' -- Filter by schema
  23761. AND cls.relname = '${table6}' -- Filter by table name
  23762. ORDER BY
  23763. a.attnum; -- Order by column number`
  23764. );
  23765. };
  23766. }
  23767. });
  23768. // src/cli/selector-ui.ts
  23769. var import_hanji4, Select;
  23770. var init_selector_ui = __esm({
  23771. "src/cli/selector-ui.ts"() {
  23772. "use strict";
  23773. init_source();
  23774. import_hanji4 = __toESM(require_hanji());
  23775. Select = class extends import_hanji4.Prompt {
  23776. constructor(items) {
  23777. super();
  23778. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  23779. this.on("detach", (terminal) => terminal.toggleCursor("show"));
  23780. this.data = new import_hanji4.SelectState(
  23781. items.map((it) => ({ label: it, value: `${it}-value` }))
  23782. );
  23783. this.data.bind(this);
  23784. }
  23785. render(status) {
  23786. if (status === "submitted" || status === "aborted") return "";
  23787. let text = ``;
  23788. this.data.items.forEach((it, idx) => {
  23789. text += idx === this.data.selectedIdx ? `${source_default.green("\u276F " + it.label)}` : ` ${it.label}`;
  23790. text += idx != this.data.items.length - 1 ? "\n" : "";
  23791. });
  23792. return text;
  23793. }
  23794. result() {
  23795. return {
  23796. index: this.data.selectedIdx,
  23797. value: this.data.items[this.data.selectedIdx].value
  23798. };
  23799. }
  23800. };
  23801. }
  23802. });
  23803. // src/serializer/sqliteSerializer.ts
  23804. import { getTableName as getTableName2, is as is2, SQL as SQL2 } from "drizzle-orm";
  23805. import {
  23806. getTableConfig as getTableConfig2,
  23807. getViewConfig as getViewConfig2,
  23808. SQLiteBaseInteger,
  23809. SQLiteColumn,
  23810. SQLiteSyncDialect,
  23811. uniqueKeyName as uniqueKeyName2
  23812. } from "drizzle-orm/sqlite-core";
  23813. function mapSqlToSqliteType(sqlType) {
  23814. const lowered = sqlType.toLowerCase();
  23815. if ([
  23816. "int",
  23817. "integer",
  23818. "integer auto_increment",
  23819. "tinyint",
  23820. "smallint",
  23821. "mediumint",
  23822. "bigint",
  23823. "unsigned big int",
  23824. "int2",
  23825. "int8"
  23826. ].some((it) => lowered.startsWith(it))) {
  23827. return "integer";
  23828. } else if ([
  23829. "character",
  23830. "varchar",
  23831. "varying character",
  23832. "national varying character",
  23833. "nchar",
  23834. "native character",
  23835. "nvarchar",
  23836. "text",
  23837. "clob"
  23838. ].some((it) => lowered.startsWith(it))) {
  23839. const match2 = lowered.match(/\d+/);
  23840. if (match2) {
  23841. return `text(${match2[0]})`;
  23842. }
  23843. return "text";
  23844. } else if (lowered.startsWith("blob")) {
  23845. return "blob";
  23846. } else if (["real", "double", "double precision", "float"].some((it) => lowered.startsWith(it))) {
  23847. return "real";
  23848. } else {
  23849. return "numeric";
  23850. }
  23851. }
  23852. function extractGeneratedColumns(input) {
  23853. const columns = {};
  23854. const lines = input.split(/,\s*(?![^()]*\))/);
  23855. for (const line of lines) {
  23856. if (line.includes("GENERATED ALWAYS AS")) {
  23857. const parts = line.trim().split(/\s+/);
  23858. const columnName = parts[0].replace(/[`'"]/g, "");
  23859. const expression = line.substring(line.indexOf("("), line.indexOf(")") + 1).trim();
  23860. const typeIndex = parts.findIndex((part) => part.match(/(stored|virtual)/i));
  23861. let type = "virtual";
  23862. if (typeIndex !== -1) {
  23863. type = parts[typeIndex].replace(/[^a-z]/gi, "").toLowerCase();
  23864. }
  23865. columns[columnName] = {
  23866. columnName,
  23867. expression,
  23868. type
  23869. };
  23870. }
  23871. }
  23872. return columns;
  23873. }
  23874. function filterIgnoredTablesByField(fieldName) {
  23875. return `${fieldName} != '__drizzle_migrations'
  23876. AND ${fieldName} NOT LIKE '\\_cf\\_%' ESCAPE '\\'
  23877. AND ${fieldName} NOT LIKE '\\_litestream\\_%' ESCAPE '\\'
  23878. AND ${fieldName} NOT LIKE 'libsql\\_%' ESCAPE '\\'
  23879. AND ${fieldName} NOT LIKE 'sqlite\\_%' ESCAPE '\\'`;
  23880. }
  23881. var generateSqliteSnapshot, fromDatabase2;
  23882. var init_sqliteSerializer = __esm({
  23883. "src/serializer/sqliteSerializer.ts"() {
  23884. "use strict";
  23885. init_source();
  23886. init_outputs();
  23887. init_utils();
  23888. init_utils2();
  23889. generateSqliteSnapshot = (tables, views, casing2) => {
  23890. const dialect6 = new SQLiteSyncDialect({ casing: casing2 });
  23891. const result = {};
  23892. const resultViews = {};
  23893. const internal = { indexes: {} };
  23894. for (const table6 of tables) {
  23895. const columnsObject = {};
  23896. const indexesObject = {};
  23897. const foreignKeysObject = {};
  23898. const primaryKeysObject = {};
  23899. const uniqueConstraintObject = {};
  23900. const checkConstraintObject = {};
  23901. const checksInTable = {};
  23902. const {
  23903. name: tableName,
  23904. columns,
  23905. indexes,
  23906. checks,
  23907. foreignKeys: tableForeignKeys,
  23908. primaryKeys,
  23909. uniqueConstraints
  23910. } = getTableConfig2(table6);
  23911. columns.forEach((column6) => {
  23912. const name = getColumnCasing(column6, casing2);
  23913. const notNull = column6.notNull;
  23914. const primaryKey = column6.primary;
  23915. const generated = column6.generated;
  23916. const columnToSet = {
  23917. name,
  23918. type: column6.getSQLType(),
  23919. primaryKey,
  23920. notNull,
  23921. autoincrement: is2(column6, SQLiteBaseInteger) ? column6.autoIncrement : false,
  23922. generated: generated ? {
  23923. as: is2(generated.as, SQL2) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
  23924. type: generated.mode ?? "virtual"
  23925. } : void 0
  23926. };
  23927. if (column6.default !== void 0) {
  23928. if (is2(column6.default, SQL2)) {
  23929. columnToSet.default = sqlToStr(column6.default, casing2);
  23930. } else {
  23931. columnToSet.default = typeof column6.default === "string" ? `'${escapeSingleQuotes(column6.default)}'` : typeof column6.default === "object" || Array.isArray(column6.default) ? `'${JSON.stringify(column6.default)}'` : column6.default;
  23932. }
  23933. }
  23934. columnsObject[name] = columnToSet;
  23935. if (column6.isUnique) {
  23936. const existingUnique = indexesObject[column6.uniqueName];
  23937. if (typeof existingUnique !== "undefined") {
  23938. console.log(
  23939. `
  23940. ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
  23941. tableName
  23942. )} table.
  23943. The unique constraint ${source_default.underline.blue(
  23944. column6.uniqueName
  23945. )} on the ${source_default.underline.blue(
  23946. name
  23947. )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  23948. existingUnique.columns.join(",")
  23949. )} columns
  23950. `)}`
  23951. );
  23952. process.exit(1);
  23953. }
  23954. indexesObject[column6.uniqueName] = {
  23955. name: column6.uniqueName,
  23956. columns: [columnToSet.name],
  23957. isUnique: true
  23958. };
  23959. }
  23960. });
  23961. const foreignKeys = tableForeignKeys.map((fk5) => {
  23962. const tableFrom = tableName;
  23963. const onDelete = fk5.onDelete ?? "no action";
  23964. const onUpdate = fk5.onUpdate ?? "no action";
  23965. const reference = fk5.reference();
  23966. const referenceFT = reference.foreignTable;
  23967. const tableTo = getTableName2(referenceFT);
  23968. const originalColumnsFrom = reference.columns.map((it) => it.name);
  23969. const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
  23970. const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
  23971. const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
  23972. let name = fk5.getName();
  23973. if (casing2 !== void 0) {
  23974. for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) {
  23975. name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]);
  23976. }
  23977. for (let i6 = 0; i6 < originalColumnsTo.length; i6++) {
  23978. name = name.replace(originalColumnsTo[i6], columnsTo[i6]);
  23979. }
  23980. }
  23981. return {
  23982. name,
  23983. tableFrom,
  23984. tableTo,
  23985. columnsFrom,
  23986. columnsTo,
  23987. onDelete,
  23988. onUpdate
  23989. };
  23990. });
  23991. foreignKeys.forEach((it) => {
  23992. foreignKeysObject[it.name] = it;
  23993. });
  23994. indexes.forEach((value) => {
  23995. const columns2 = value.config.columns;
  23996. const name = value.config.name;
  23997. let indexColumns = columns2.map((it) => {
  23998. if (is2(it, SQL2)) {
  23999. const sql = dialect6.sqlToQuery(it, "indexes").sql;
  24000. if (typeof internal.indexes[name] === "undefined") {
  24001. internal.indexes[name] = {
  24002. columns: {
  24003. [sql]: {
  24004. isExpression: true
  24005. }
  24006. }
  24007. };
  24008. } else {
  24009. if (typeof internal.indexes[name]?.columns[sql] === "undefined") {
  24010. internal.indexes[name].columns[sql] = {
  24011. isExpression: true
  24012. };
  24013. } else {
  24014. internal.indexes[name].columns[sql].isExpression = true;
  24015. }
  24016. }
  24017. return sql;
  24018. } else {
  24019. return getColumnCasing(it, casing2);
  24020. }
  24021. });
  24022. let where = void 0;
  24023. if (value.config.where !== void 0) {
  24024. if (is2(value.config.where, SQL2)) {
  24025. where = dialect6.sqlToQuery(value.config.where).sql;
  24026. }
  24027. }
  24028. indexesObject[name] = {
  24029. name,
  24030. columns: indexColumns,
  24031. isUnique: value.config.unique ?? false,
  24032. where
  24033. };
  24034. });
  24035. uniqueConstraints?.map((unq) => {
  24036. const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2));
  24037. const name = unq.name ?? uniqueKeyName2(table6, columnNames);
  24038. const existingUnique = indexesObject[name];
  24039. if (typeof existingUnique !== "undefined") {
  24040. console.log(
  24041. `
  24042. ${withStyle.errorWarning(
  24043. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  24044. tableName
  24045. )} table.
  24046. The unique constraint ${source_default.underline.blue(
  24047. name
  24048. )} on the ${source_default.underline.blue(
  24049. columnNames.join(",")
  24050. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  24051. existingUnique.columns.join(",")
  24052. )} columns
  24053. `
  24054. )}`
  24055. );
  24056. process.exit(1);
  24057. }
  24058. indexesObject[name] = {
  24059. name: unq.name,
  24060. columns: columnNames,
  24061. isUnique: true
  24062. };
  24063. });
  24064. primaryKeys.forEach((it) => {
  24065. if (it.columns.length > 1) {
  24066. const originalColumnNames = it.columns.map((c5) => c5.name);
  24067. const columnNames = it.columns.map((c5) => getColumnCasing(c5, casing2));
  24068. let name = it.getName();
  24069. if (casing2 !== void 0) {
  24070. for (let i6 = 0; i6 < originalColumnNames.length; i6++) {
  24071. name = name.replace(originalColumnNames[i6], columnNames[i6]);
  24072. }
  24073. }
  24074. primaryKeysObject[name] = {
  24075. columns: columnNames,
  24076. name
  24077. };
  24078. } else {
  24079. columnsObject[getColumnCasing(it.columns[0], casing2)].primaryKey = true;
  24080. }
  24081. });
  24082. checks.forEach((check) => {
  24083. const checkName = check.name;
  24084. if (typeof checksInTable[tableName] !== "undefined") {
  24085. if (checksInTable[tableName].includes(check.name)) {
  24086. console.log(
  24087. `
  24088. ${withStyle.errorWarning(
  24089. `We've found duplicated check constraint name in ${source_default.underline.blue(
  24090. tableName
  24091. )}. Please rename your check constraint in the ${source_default.underline.blue(
  24092. tableName
  24093. )} table`
  24094. )}`
  24095. );
  24096. process.exit(1);
  24097. }
  24098. checksInTable[tableName].push(checkName);
  24099. } else {
  24100. checksInTable[tableName] = [check.name];
  24101. }
  24102. checkConstraintObject[checkName] = {
  24103. name: checkName,
  24104. value: dialect6.sqlToQuery(check.value).sql
  24105. };
  24106. });
  24107. result[tableName] = {
  24108. name: tableName,
  24109. columns: columnsObject,
  24110. indexes: indexesObject,
  24111. foreignKeys: foreignKeysObject,
  24112. compositePrimaryKeys: primaryKeysObject,
  24113. uniqueConstraints: uniqueConstraintObject,
  24114. checkConstraints: checkConstraintObject
  24115. };
  24116. }
  24117. for (const view5 of views) {
  24118. const { name, isExisting, selectedFields, query, schema: schema6 } = getViewConfig2(view5);
  24119. const columnsObject = {};
  24120. const existingView = resultViews[name];
  24121. if (typeof existingView !== "undefined") {
  24122. console.log(
  24123. `
  24124. ${withStyle.errorWarning(
  24125. `We've found duplicated view name across ${source_default.underline.blue(
  24126. schema6 ?? "public"
  24127. )} schema. Please rename your view`
  24128. )}`
  24129. );
  24130. process.exit(1);
  24131. }
  24132. for (const key in selectedFields) {
  24133. if (is2(selectedFields[key], SQLiteColumn)) {
  24134. const column6 = selectedFields[key];
  24135. const notNull = column6.notNull;
  24136. const primaryKey = column6.primary;
  24137. const generated = column6.generated;
  24138. const columnToSet = {
  24139. name: column6.name,
  24140. type: column6.getSQLType(),
  24141. primaryKey,
  24142. notNull,
  24143. autoincrement: is2(column6, SQLiteBaseInteger) ? column6.autoIncrement : false,
  24144. generated: generated ? {
  24145. as: is2(generated.as, SQL2) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
  24146. type: generated.mode ?? "virtual"
  24147. } : void 0
  24148. };
  24149. if (column6.default !== void 0) {
  24150. if (is2(column6.default, SQL2)) {
  24151. columnToSet.default = sqlToStr(column6.default, casing2);
  24152. } else {
  24153. columnToSet.default = typeof column6.default === "string" ? `'${column6.default}'` : typeof column6.default === "object" || Array.isArray(column6.default) ? `'${JSON.stringify(column6.default)}'` : column6.default;
  24154. }
  24155. }
  24156. columnsObject[column6.name] = columnToSet;
  24157. }
  24158. }
  24159. resultViews[name] = {
  24160. columns: columnsObject,
  24161. name,
  24162. isExisting,
  24163. definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql
  24164. };
  24165. }
  24166. return {
  24167. version: "6",
  24168. dialect: "sqlite",
  24169. tables: result,
  24170. views: resultViews,
  24171. enums: {},
  24172. _meta: {
  24173. tables: {},
  24174. columns: {}
  24175. },
  24176. internal
  24177. };
  24178. };
  24179. fromDatabase2 = async (db, tablesFilter = (table6) => true, progressCallback) => {
  24180. const result = {};
  24181. const resultViews = {};
  24182. const columns = await db.query(`SELECT
  24183. m.name as "tableName",
  24184. p.name as "columnName",
  24185. p.type as "columnType",
  24186. p."notnull" as "notNull",
  24187. p.dflt_value as "defaultValue",
  24188. p.pk as pk,
  24189. p.hidden as hidden,
  24190. m.sql,
  24191. m.type as type
  24192. FROM sqlite_master AS m
  24193. JOIN pragma_table_xinfo(m.name) AS p
  24194. WHERE (m.type = 'table' OR m.type = 'view')
  24195. AND ${filterIgnoredTablesByField("m.tbl_name")};`);
  24196. const tablesWithSeq = [];
  24197. const seq = await db.query(`SELECT
  24198. *
  24199. FROM sqlite_master
  24200. WHERE sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*'
  24201. AND ${filterIgnoredTablesByField("tbl_name")};`);
  24202. for (const s6 of seq) {
  24203. tablesWithSeq.push(s6.name);
  24204. }
  24205. let columnsCount = 0;
  24206. let tablesCount = /* @__PURE__ */ new Set();
  24207. let indexesCount = 0;
  24208. let foreignKeysCount = 0;
  24209. let checksCount = 0;
  24210. let viewsCount = 0;
  24211. const tableToPk = {};
  24212. let tableToGeneratedColumnsInfo = {};
  24213. for (const column6 of columns) {
  24214. if (!tablesFilter(column6.tableName)) continue;
  24215. if (column6.type !== "view") {
  24216. columnsCount += 1;
  24217. }
  24218. if (progressCallback) {
  24219. progressCallback("columns", columnsCount, "fetching");
  24220. }
  24221. const tableName = column6.tableName;
  24222. tablesCount.add(tableName);
  24223. if (progressCallback) {
  24224. progressCallback("tables", tablesCount.size, "fetching");
  24225. }
  24226. const columnName = column6.columnName;
  24227. const isNotNull = column6.notNull === 1;
  24228. const columnType = column6.columnType;
  24229. const isPrimary = column6.pk !== 0;
  24230. const columnDefault = column6.defaultValue;
  24231. const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
  24232. if (isPrimary) {
  24233. if (typeof tableToPk[tableName] === "undefined") {
  24234. tableToPk[tableName] = [columnName];
  24235. } else {
  24236. tableToPk[tableName].push(columnName);
  24237. }
  24238. }
  24239. const table6 = result[tableName];
  24240. if (column6.hidden === 2 || column6.hidden === 3) {
  24241. if (typeof tableToGeneratedColumnsInfo[column6.tableName] === "undefined") {
  24242. tableToGeneratedColumnsInfo[column6.tableName] = extractGeneratedColumns(
  24243. column6.sql
  24244. );
  24245. }
  24246. }
  24247. const newColumn = {
  24248. default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
  24249. columnDefault
  24250. ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : `(${columnDefault})`,
  24251. autoincrement: isAutoincrement,
  24252. name: columnName,
  24253. type: mapSqlToSqliteType(columnType),
  24254. primaryKey: false,
  24255. notNull: isNotNull,
  24256. generated: tableToGeneratedColumnsInfo[tableName] && tableToGeneratedColumnsInfo[tableName][columnName] ? {
  24257. type: tableToGeneratedColumnsInfo[tableName][columnName].type,
  24258. as: tableToGeneratedColumnsInfo[tableName][columnName].expression
  24259. } : void 0
  24260. };
  24261. if (!table6) {
  24262. result[tableName] = {
  24263. name: tableName,
  24264. columns: {
  24265. [columnName]: newColumn
  24266. },
  24267. compositePrimaryKeys: {},
  24268. indexes: {},
  24269. foreignKeys: {},
  24270. uniqueConstraints: {},
  24271. checkConstraints: {}
  24272. };
  24273. } else {
  24274. result[tableName].columns[columnName] = newColumn;
  24275. }
  24276. }
  24277. for (const [key, value] of Object.entries(tableToPk)) {
  24278. if (value.length > 1) {
  24279. result[key].compositePrimaryKeys = {
  24280. [`${key}_${value.join("_")}_pk`]: {
  24281. columns: value,
  24282. name: `${key}_${value.join("_")}_pk`
  24283. }
  24284. };
  24285. } else if (value.length === 1) {
  24286. result[key].columns[value[0]].primaryKey = true;
  24287. } else {
  24288. }
  24289. }
  24290. if (progressCallback) {
  24291. progressCallback("columns", columnsCount, "done");
  24292. progressCallback("tables", tablesCount.size, "done");
  24293. }
  24294. try {
  24295. const fks = await db.query(`SELECT
  24296. m.name as "tableFrom",
  24297. f.id as "id",
  24298. f."table" as "tableTo",
  24299. f."from",
  24300. f."to",
  24301. f."on_update" as "onUpdate",
  24302. f."on_delete" as "onDelete",
  24303. f.seq as "seq"
  24304. FROM
  24305. sqlite_master m,
  24306. pragma_foreign_key_list(m.name) as f
  24307. WHERE ${filterIgnoredTablesByField("m.tbl_name")};`);
  24308. const fkByTableName = {};
  24309. for (const fkRow of fks) {
  24310. foreignKeysCount += 1;
  24311. if (progressCallback) {
  24312. progressCallback("fks", foreignKeysCount, "fetching");
  24313. }
  24314. const tableName = fkRow.tableFrom;
  24315. const columnName = fkRow.from;
  24316. const refTableName = fkRow.tableTo;
  24317. const refColumnName = fkRow.to;
  24318. const updateRule = fkRow.onUpdate;
  24319. const deleteRule = fkRow.onDelete;
  24320. const sequence = fkRow.seq;
  24321. const id = fkRow.id;
  24322. const tableInResult = result[tableName];
  24323. if (typeof tableInResult === "undefined") continue;
  24324. if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
  24325. fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
  24326. fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
  24327. } else {
  24328. fkByTableName[`${tableName}_${id}`] = {
  24329. name: "",
  24330. tableFrom: tableName,
  24331. tableTo: refTableName,
  24332. columnsFrom: [columnName],
  24333. columnsTo: [refColumnName],
  24334. onDelete: deleteRule?.toLowerCase(),
  24335. onUpdate: updateRule?.toLowerCase()
  24336. };
  24337. }
  24338. const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
  24339. const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
  24340. fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
  24341. "_"
  24342. )}_${refTableName}_${columnsTo.join("_")}_fk`;
  24343. }
  24344. for (const idx of Object.keys(fkByTableName)) {
  24345. const value = fkByTableName[idx];
  24346. result[value.tableFrom].foreignKeys[value.name] = value;
  24347. }
  24348. } catch (e6) {
  24349. }
  24350. if (progressCallback) {
  24351. progressCallback("fks", foreignKeysCount, "done");
  24352. }
  24353. const idxs = await db.query(`SELECT
  24354. m.tbl_name as tableName,
  24355. il.name as indexName,
  24356. ii.name as columnName,
  24357. il.[unique] as isUnique,
  24358. il.seq as seq
  24359. FROM
  24360. sqlite_master AS m,
  24361. pragma_index_list(m.name) AS il,
  24362. pragma_index_info(il.name) AS ii
  24363. WHERE
  24364. m.type = 'table'
  24365. AND il.name NOT LIKE 'sqlite\\_autoindex\\_%' ESCAPE '\\'
  24366. AND ${filterIgnoredTablesByField("m.tbl_name")};`);
  24367. for (const idxRow of idxs) {
  24368. const tableName = idxRow.tableName;
  24369. const constraintName = idxRow.indexName;
  24370. const columnName = idxRow.columnName;
  24371. const isUnique = idxRow.isUnique === 1;
  24372. const tableInResult = result[tableName];
  24373. if (typeof tableInResult === "undefined") continue;
  24374. indexesCount += 1;
  24375. if (progressCallback) {
  24376. progressCallback("indexes", indexesCount, "fetching");
  24377. }
  24378. if (typeof tableInResult.indexes[constraintName] !== "undefined" && columnName) {
  24379. tableInResult.indexes[constraintName].columns.push(columnName);
  24380. } else {
  24381. tableInResult.indexes[constraintName] = {
  24382. name: constraintName,
  24383. columns: columnName ? [columnName] : [],
  24384. isUnique
  24385. };
  24386. }
  24387. }
  24388. if (progressCallback) {
  24389. progressCallback("indexes", indexesCount, "done");
  24390. progressCallback("enums", 0, "done");
  24391. }
  24392. const views = await db.query(
  24393. `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
  24394. );
  24395. viewsCount = views.length;
  24396. if (progressCallback) {
  24397. progressCallback("views", viewsCount, "fetching");
  24398. }
  24399. for (const view5 of views) {
  24400. const viewName = view5["view_name"];
  24401. const sql = view5["sql"];
  24402. const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
  24403. const match2 = sql.match(regex);
  24404. if (!match2) {
  24405. console.log("Could not process view");
  24406. process.exit(1);
  24407. }
  24408. const viewDefinition = match2[1];
  24409. const columns2 = result[viewName].columns;
  24410. delete result[viewName];
  24411. resultViews[viewName] = {
  24412. columns: columns2,
  24413. isExisting: false,
  24414. name: viewName,
  24415. definition: viewDefinition
  24416. };
  24417. }
  24418. if (progressCallback) {
  24419. progressCallback("views", viewsCount, "done");
  24420. }
  24421. const namedCheckPattern = /CONSTRAINT\s*["']?(\w+)["']?\s*CHECK\s*\((.*?)\)/gi;
  24422. const unnamedCheckPattern = /CHECK\s*\((.*?)\)/gi;
  24423. let checkCounter = 0;
  24424. const checkConstraints = {};
  24425. const checks = await db.query(`SELECT
  24426. name as "tableName",
  24427. sql as "sql"
  24428. FROM sqlite_master
  24429. WHERE type = 'table'
  24430. AND ${filterIgnoredTablesByField("tbl_name")};`);
  24431. for (const check of checks) {
  24432. if (!tablesFilter(check.tableName)) continue;
  24433. const { tableName, sql } = check;
  24434. let namedChecks = [...sql.matchAll(namedCheckPattern)];
  24435. if (namedChecks.length > 0) {
  24436. namedChecks.forEach(([_3, checkName, checkValue]) => {
  24437. checkConstraints[checkName] = {
  24438. name: checkName,
  24439. value: checkValue.trim()
  24440. };
  24441. });
  24442. } else {
  24443. let unnamedChecks = [...sql.matchAll(unnamedCheckPattern)];
  24444. unnamedChecks.forEach(([_3, checkValue]) => {
  24445. let checkName = `${tableName}_check_${++checkCounter}`;
  24446. checkConstraints[checkName] = {
  24447. name: checkName,
  24448. value: checkValue.trim()
  24449. };
  24450. });
  24451. }
  24452. checksCount += Object.values(checkConstraints).length;
  24453. if (progressCallback) {
  24454. progressCallback("checks", checksCount, "fetching");
  24455. }
  24456. const table6 = result[tableName];
  24457. if (!table6) {
  24458. result[tableName] = {
  24459. name: tableName,
  24460. columns: {},
  24461. compositePrimaryKeys: {},
  24462. indexes: {},
  24463. foreignKeys: {},
  24464. uniqueConstraints: {},
  24465. checkConstraints
  24466. };
  24467. } else {
  24468. result[tableName].checkConstraints = checkConstraints;
  24469. }
  24470. }
  24471. if (progressCallback) {
  24472. progressCallback("checks", checksCount, "done");
  24473. }
  24474. return {
  24475. version: "6",
  24476. dialect: "sqlite",
  24477. tables: result,
  24478. views: resultViews,
  24479. enums: {},
  24480. _meta: {
  24481. tables: {},
  24482. columns: {}
  24483. }
  24484. };
  24485. };
  24486. }
  24487. });
  24488. // src/extensions/getTablesFilterByExtensions.ts
  24489. var getTablesFilterByExtensions;
  24490. var init_getTablesFilterByExtensions = __esm({
  24491. "src/extensions/getTablesFilterByExtensions.ts"() {
  24492. "use strict";
  24493. getTablesFilterByExtensions = ({
  24494. extensionsFilters,
  24495. dialect: dialect6
  24496. }) => {
  24497. if (extensionsFilters) {
  24498. if (extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
  24499. return ["!geography_columns", "!geometry_columns", "!spatial_ref_sys"];
  24500. }
  24501. }
  24502. return [];
  24503. };
  24504. }
  24505. });
  24506. // src/serializer/mysqlSerializer.ts
  24507. import { getTableName as getTableName3, is as is3, SQL as SQL3 } from "drizzle-orm";
  24508. import {
  24509. getTableConfig as getTableConfig3,
  24510. getViewConfig as getViewConfig3,
  24511. MySqlColumn,
  24512. MySqlDialect,
  24513. uniqueKeyName as uniqueKeyName3
  24514. } from "drizzle-orm/mysql-core";
  24515. function clearDefaults(defaultValue, collate) {
  24516. if (typeof collate === "undefined" || collate === null) {
  24517. collate = `utf8mb4`;
  24518. }
  24519. let resultDefault = defaultValue;
  24520. collate = `_${collate}`;
  24521. if (defaultValue.startsWith(collate)) {
  24522. resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
  24523. if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
  24524. return `('${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}')`;
  24525. } else {
  24526. return `'${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}'`;
  24527. }
  24528. } else {
  24529. return `(${resultDefault})`;
  24530. }
  24531. }
  24532. var handleEnumType, generateMySqlSnapshot, fromDatabase3;
  24533. var init_mysqlSerializer = __esm({
  24534. "src/serializer/mysqlSerializer.ts"() {
  24535. "use strict";
  24536. init_source();
  24537. init_outputs();
  24538. init_utils();
  24539. init_utils2();
  24540. handleEnumType = (type) => {
  24541. let str = type.split("(")[1];
  24542. str = str.substring(0, str.length - 1);
  24543. const values = str.split(",").map((v6) => `'${escapeSingleQuotes(v6.substring(1, v6.length - 1))}'`);
  24544. return `enum(${values.join(",")})`;
  24545. };
  24546. generateMySqlSnapshot = (tables, views, casing2) => {
  24547. const dialect6 = new MySqlDialect({ casing: casing2 });
  24548. const result = {};
  24549. const resultViews = {};
  24550. const internal = { tables: {}, indexes: {} };
  24551. for (const table6 of tables) {
  24552. const {
  24553. name: tableName,
  24554. columns,
  24555. indexes,
  24556. foreignKeys,
  24557. schema: schema6,
  24558. checks,
  24559. primaryKeys,
  24560. uniqueConstraints
  24561. } = getTableConfig3(table6);
  24562. const columnsObject = {};
  24563. const indexesObject = {};
  24564. const foreignKeysObject = {};
  24565. const primaryKeysObject = {};
  24566. const uniqueConstraintObject = {};
  24567. const checkConstraintObject = {};
  24568. let checksInTable = {};
  24569. columns.forEach((column6) => {
  24570. const name = getColumnCasing(column6, casing2);
  24571. const notNull = column6.notNull;
  24572. const sqlType = column6.getSQLType();
  24573. const sqlTypeLowered = sqlType.toLowerCase();
  24574. const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
  24575. const generated = column6.generated;
  24576. const columnToSet = {
  24577. name,
  24578. type: sqlType.startsWith("enum") ? handleEnumType(sqlType) : sqlType,
  24579. primaryKey: false,
  24580. // If field is autoincrement it's notNull by default
  24581. // notNull: autoIncrement ? true : notNull,
  24582. notNull,
  24583. autoincrement: autoIncrement,
  24584. onUpdate: column6.hasOnUpdateNow,
  24585. generated: generated ? {
  24586. as: is3(generated.as, SQL3) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  24587. type: generated.mode ?? "stored"
  24588. } : void 0
  24589. };
  24590. if (column6.primary) {
  24591. primaryKeysObject[`${tableName}_${name}`] = {
  24592. name: `${tableName}_${name}`,
  24593. columns: [name]
  24594. };
  24595. }
  24596. if (column6.isUnique) {
  24597. const existingUnique = uniqueConstraintObject[column6.uniqueName];
  24598. if (typeof existingUnique !== "undefined") {
  24599. console.log(
  24600. `
  24601. ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
  24602. tableName
  24603. )} table.
  24604. The unique constraint ${source_default.underline.blue(
  24605. column6.uniqueName
  24606. )} on the ${source_default.underline.blue(
  24607. name
  24608. )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  24609. existingUnique.columns.join(",")
  24610. )} columns
  24611. `)}`
  24612. );
  24613. process.exit(1);
  24614. }
  24615. uniqueConstraintObject[column6.uniqueName] = {
  24616. name: column6.uniqueName,
  24617. columns: [columnToSet.name]
  24618. };
  24619. }
  24620. if (column6.default !== void 0) {
  24621. if (is3(column6.default, SQL3)) {
  24622. columnToSet.default = sqlToStr(column6.default, casing2);
  24623. } else {
  24624. if (typeof column6.default === "string") {
  24625. columnToSet.default = `'${escapeSingleQuotes(column6.default)}'`;
  24626. } else {
  24627. if (sqlTypeLowered === "json") {
  24628. columnToSet.default = `'${JSON.stringify(column6.default)}'`;
  24629. } else if (column6.default instanceof Date) {
  24630. if (sqlTypeLowered === "date") {
  24631. columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
  24632. } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
  24633. columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  24634. }
  24635. } else {
  24636. columnToSet.default = column6.default;
  24637. }
  24638. }
  24639. if (["blob", "text", "json"].includes(column6.getSQLType())) {
  24640. columnToSet.default = `(${columnToSet.default})`;
  24641. }
  24642. }
  24643. }
  24644. columnsObject[name] = columnToSet;
  24645. });
  24646. primaryKeys.map((pk) => {
  24647. const originalColumnNames = pk.columns.map((c5) => c5.name);
  24648. const columnNames = pk.columns.map((c5) => getColumnCasing(c5, casing2));
  24649. let name = pk.getName();
  24650. if (casing2 !== void 0) {
  24651. for (let i6 = 0; i6 < originalColumnNames.length; i6++) {
  24652. name = name.replace(originalColumnNames[i6], columnNames[i6]);
  24653. }
  24654. }
  24655. primaryKeysObject[name] = {
  24656. name,
  24657. columns: columnNames
  24658. };
  24659. for (const column6 of pk.columns) {
  24660. columnsObject[getColumnCasing(column6, casing2)].notNull = true;
  24661. }
  24662. });
  24663. uniqueConstraints?.map((unq) => {
  24664. const columnNames = unq.columns.map((c5) => getColumnCasing(c5, casing2));
  24665. const name = unq.name ?? uniqueKeyName3(table6, columnNames);
  24666. const existingUnique = uniqueConstraintObject[name];
  24667. if (typeof existingUnique !== "undefined") {
  24668. console.log(
  24669. `
  24670. ${withStyle.errorWarning(
  24671. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  24672. tableName
  24673. )} table.
  24674. The unique constraint ${source_default.underline.blue(
  24675. name
  24676. )} on the ${source_default.underline.blue(
  24677. columnNames.join(",")
  24678. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  24679. existingUnique.columns.join(",")
  24680. )} columns
  24681. `
  24682. )}`
  24683. );
  24684. process.exit(1);
  24685. }
  24686. uniqueConstraintObject[name] = {
  24687. name: unq.name,
  24688. columns: columnNames
  24689. };
  24690. });
  24691. const fks = foreignKeys.map((fk5) => {
  24692. const tableFrom = tableName;
  24693. const onDelete = fk5.onDelete ?? "no action";
  24694. const onUpdate = fk5.onUpdate ?? "no action";
  24695. const reference = fk5.reference();
  24696. const referenceFT = reference.foreignTable;
  24697. const tableTo = getTableName3(referenceFT);
  24698. const originalColumnsFrom = reference.columns.map((it) => it.name);
  24699. const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
  24700. const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
  24701. const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
  24702. let name = fk5.getName();
  24703. if (casing2 !== void 0) {
  24704. for (let i6 = 0; i6 < originalColumnsFrom.length; i6++) {
  24705. name = name.replace(originalColumnsFrom[i6], columnsFrom[i6]);
  24706. }
  24707. for (let i6 = 0; i6 < originalColumnsTo.length; i6++) {
  24708. name = name.replace(originalColumnsTo[i6], columnsTo[i6]);
  24709. }
  24710. }
  24711. return {
  24712. name,
  24713. tableFrom,
  24714. tableTo,
  24715. columnsFrom,
  24716. columnsTo,
  24717. onDelete,
  24718. onUpdate
  24719. };
  24720. });
  24721. fks.forEach((it) => {
  24722. foreignKeysObject[it.name] = it;
  24723. });
  24724. indexes.forEach((value) => {
  24725. const columns2 = value.config.columns;
  24726. const name = value.config.name;
  24727. let indexColumns = columns2.map((it) => {
  24728. if (is3(it, SQL3)) {
  24729. const sql = dialect6.sqlToQuery(it, "indexes").sql;
  24730. if (typeof internal.indexes[name] === "undefined") {
  24731. internal.indexes[name] = {
  24732. columns: {
  24733. [sql]: {
  24734. isExpression: true
  24735. }
  24736. }
  24737. };
  24738. } else {
  24739. if (typeof internal.indexes[name]?.columns[sql] === "undefined") {
  24740. internal.indexes[name].columns[sql] = {
  24741. isExpression: true
  24742. };
  24743. } else {
  24744. internal.indexes[name].columns[sql].isExpression = true;
  24745. }
  24746. }
  24747. return sql;
  24748. } else {
  24749. return `${getColumnCasing(it, casing2)}`;
  24750. }
  24751. });
  24752. if (value.config.unique) {
  24753. if (typeof uniqueConstraintObject[name] !== "undefined") {
  24754. console.log(
  24755. `
  24756. ${withStyle.errorWarning(
  24757. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  24758. tableName
  24759. )} table.
  24760. The unique index ${source_default.underline.blue(
  24761. name
  24762. )} on the ${source_default.underline.blue(
  24763. indexColumns.join(",")
  24764. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  24765. uniqueConstraintObject[name].columns.join(",")
  24766. )} columns
  24767. `
  24768. )}`
  24769. );
  24770. process.exit(1);
  24771. }
  24772. } else {
  24773. if (typeof foreignKeysObject[name] !== "undefined") {
  24774. console.log(
  24775. `
  24776. ${withStyle.errorWarning(
  24777. `In MySQL, when creating a foreign key, an index is automatically generated with the same name as the foreign key constraint.
  24778. We have encountered a collision between the index name on columns ${source_default.underline.blue(
  24779. indexColumns.join(",")
  24780. )} and the foreign key on columns ${source_default.underline.blue(
  24781. foreignKeysObject[name].columnsFrom.join(",")
  24782. )}. Please change either the index name or the foreign key name. For more information, please refer to https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html
  24783. `
  24784. )}`
  24785. );
  24786. process.exit(1);
  24787. }
  24788. }
  24789. indexesObject[name] = {
  24790. name,
  24791. columns: indexColumns,
  24792. isUnique: value.config.unique ?? false,
  24793. using: value.config.using,
  24794. algorithm: value.config.algorithm,
  24795. lock: value.config.lock
  24796. };
  24797. });
  24798. checks.forEach((check) => {
  24799. check;
  24800. const checkName = check.name;
  24801. if (typeof checksInTable[tableName] !== "undefined") {
  24802. if (checksInTable[tableName].includes(check.name)) {
  24803. console.log(
  24804. `
  24805. ${withStyle.errorWarning(
  24806. `We've found duplicated check constraint name in ${source_default.underline.blue(
  24807. tableName
  24808. )}. Please rename your check constraint in the ${source_default.underline.blue(
  24809. tableName
  24810. )} table`
  24811. )}`
  24812. );
  24813. process.exit(1);
  24814. }
  24815. checksInTable[tableName].push(checkName);
  24816. } else {
  24817. checksInTable[tableName] = [check.name];
  24818. }
  24819. checkConstraintObject[checkName] = {
  24820. name: checkName,
  24821. value: dialect6.sqlToQuery(check.value).sql
  24822. };
  24823. });
  24824. if (!schema6) {
  24825. result[tableName] = {
  24826. name: tableName,
  24827. columns: columnsObject,
  24828. indexes: indexesObject,
  24829. foreignKeys: foreignKeysObject,
  24830. compositePrimaryKeys: primaryKeysObject,
  24831. uniqueConstraints: uniqueConstraintObject,
  24832. checkConstraint: checkConstraintObject
  24833. };
  24834. }
  24835. }
  24836. for (const view5 of views) {
  24837. const {
  24838. isExisting,
  24839. name,
  24840. query,
  24841. schema: schema6,
  24842. selectedFields,
  24843. algorithm,
  24844. sqlSecurity,
  24845. withCheckOption
  24846. } = getViewConfig3(view5);
  24847. const columnsObject = {};
  24848. const existingView = resultViews[name];
  24849. if (typeof existingView !== "undefined") {
  24850. console.log(
  24851. `
  24852. ${withStyle.errorWarning(
  24853. `We've found duplicated view name across ${source_default.underline.blue(
  24854. schema6 ?? "public"
  24855. )} schema. Please rename your view`
  24856. )}`
  24857. );
  24858. process.exit(1);
  24859. }
  24860. for (const key in selectedFields) {
  24861. if (is3(selectedFields[key], MySqlColumn)) {
  24862. const column6 = selectedFields[key];
  24863. const notNull = column6.notNull;
  24864. const sqlTypeLowered = column6.getSQLType().toLowerCase();
  24865. const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
  24866. const generated = column6.generated;
  24867. const columnToSet = {
  24868. name: column6.name,
  24869. type: column6.getSQLType(),
  24870. primaryKey: false,
  24871. // If field is autoincrement it's notNull by default
  24872. // notNull: autoIncrement ? true : notNull,
  24873. notNull,
  24874. autoincrement: autoIncrement,
  24875. onUpdate: column6.hasOnUpdateNow,
  24876. generated: generated ? {
  24877. as: is3(generated.as, SQL3) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  24878. type: generated.mode ?? "stored"
  24879. } : void 0
  24880. };
  24881. if (column6.default !== void 0) {
  24882. if (is3(column6.default, SQL3)) {
  24883. columnToSet.default = sqlToStr(column6.default, casing2);
  24884. } else {
  24885. if (typeof column6.default === "string") {
  24886. columnToSet.default = `'${column6.default}'`;
  24887. } else {
  24888. if (sqlTypeLowered === "json") {
  24889. columnToSet.default = `'${JSON.stringify(column6.default)}'`;
  24890. } else if (column6.default instanceof Date) {
  24891. if (sqlTypeLowered === "date") {
  24892. columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
  24893. } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
  24894. columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  24895. }
  24896. } else {
  24897. columnToSet.default = column6.default;
  24898. }
  24899. }
  24900. if (["blob", "text", "json"].includes(column6.getSQLType())) {
  24901. columnToSet.default = `(${columnToSet.default})`;
  24902. }
  24903. }
  24904. }
  24905. columnsObject[column6.name] = columnToSet;
  24906. }
  24907. }
  24908. resultViews[name] = {
  24909. columns: columnsObject,
  24910. name,
  24911. isExisting,
  24912. definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
  24913. withCheckOption,
  24914. algorithm: algorithm ?? "undefined",
  24915. // set default values
  24916. sqlSecurity: sqlSecurity ?? "definer"
  24917. // set default values
  24918. };
  24919. }
  24920. return {
  24921. version: "5",
  24922. dialect: "mysql",
  24923. tables: result,
  24924. views: resultViews,
  24925. _meta: {
  24926. tables: {},
  24927. columns: {}
  24928. },
  24929. internal
  24930. };
  24931. };
  24932. fromDatabase3 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
  24933. const result = {};
  24934. const internals = { tables: {}, indexes: {} };
  24935. const columns = await db.query(`select * from information_schema.columns
  24936. where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
  24937. order by table_name, ordinal_position;`);
  24938. const response = columns;
  24939. const schemas = [];
  24940. let columnsCount = 0;
  24941. let tablesCount = /* @__PURE__ */ new Set();
  24942. let indexesCount = 0;
  24943. let foreignKeysCount = 0;
  24944. let checksCount = 0;
  24945. let viewsCount = 0;
  24946. const idxs = await db.query(
  24947. `select * from INFORMATION_SCHEMA.STATISTICS
  24948. WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
  24949. );
  24950. const idxRows = idxs;
  24951. for (const column6 of response) {
  24952. if (!tablesFilter(column6["TABLE_NAME"])) continue;
  24953. columnsCount += 1;
  24954. if (progressCallback) {
  24955. progressCallback("columns", columnsCount, "fetching");
  24956. }
  24957. const schema6 = column6["TABLE_SCHEMA"];
  24958. const tableName = column6["TABLE_NAME"];
  24959. tablesCount.add(`${schema6}.${tableName}`);
  24960. if (progressCallback) {
  24961. progressCallback("columns", tablesCount.size, "fetching");
  24962. }
  24963. const columnName = column6["COLUMN_NAME"];
  24964. const isNullable = column6["IS_NULLABLE"] === "YES";
  24965. const dataType = column6["DATA_TYPE"];
  24966. const columnType = column6["COLUMN_TYPE"];
  24967. const isPrimary = column6["COLUMN_KEY"] === "PRI";
  24968. const columnDefault = column6["COLUMN_DEFAULT"];
  24969. const collation = column6["CHARACTER_SET_NAME"];
  24970. const geenratedExpression = column6["GENERATION_EXPRESSION"];
  24971. let columnExtra = column6["EXTRA"];
  24972. let isAutoincrement = false;
  24973. let isDefaultAnExpression = false;
  24974. if (typeof column6["EXTRA"] !== "undefined") {
  24975. columnExtra = column6["EXTRA"];
  24976. isAutoincrement = column6["EXTRA"] === "auto_increment";
  24977. isDefaultAnExpression = column6["EXTRA"].includes("DEFAULT_GENERATED");
  24978. }
  24979. if (schema6 !== inputSchema) {
  24980. schemas.push(schema6);
  24981. }
  24982. const table6 = result[tableName];
  24983. let changedType = columnType;
  24984. if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
  24985. const uniqueIdx = idxRows.filter(
  24986. (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
  24987. );
  24988. if (uniqueIdx && uniqueIdx.length === 1) {
  24989. changedType = columnType.replace("bigint unsigned", "serial");
  24990. }
  24991. }
  24992. if (columnType.includes("decimal(10,0)")) {
  24993. changedType = columnType.replace("decimal(10,0)", "decimal");
  24994. }
  24995. let onUpdate = void 0;
  24996. if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
  24997. onUpdate = true;
  24998. }
  24999. const newColumn = {
  25000. default: columnDefault === null || columnDefault === void 0 ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${escapeSingleQuotes(columnDefault)}'`,
  25001. autoincrement: isAutoincrement,
  25002. name: columnName,
  25003. type: changedType,
  25004. primaryKey: false,
  25005. notNull: !isNullable,
  25006. onUpdate,
  25007. generated: geenratedExpression ? {
  25008. as: geenratedExpression,
  25009. type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
  25010. } : void 0
  25011. };
  25012. if (isDefaultAnExpression) {
  25013. if (typeof internals.tables[tableName] === "undefined") {
  25014. internals.tables[tableName] = {
  25015. columns: {
  25016. [columnName]: {
  25017. isDefaultAnExpression: true
  25018. }
  25019. }
  25020. };
  25021. } else {
  25022. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  25023. internals.tables[tableName].columns[columnName] = {
  25024. isDefaultAnExpression: true
  25025. };
  25026. } else {
  25027. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  25028. }
  25029. }
  25030. }
  25031. if (!table6) {
  25032. result[tableName] = {
  25033. name: tableName,
  25034. columns: {
  25035. [columnName]: newColumn
  25036. },
  25037. compositePrimaryKeys: {},
  25038. indexes: {},
  25039. foreignKeys: {},
  25040. uniqueConstraints: {},
  25041. checkConstraint: {}
  25042. };
  25043. } else {
  25044. result[tableName].columns[columnName] = newColumn;
  25045. }
  25046. }
  25047. const tablePks = await db.query(
  25048. `SELECT table_name, column_name, ordinal_position
  25049. FROM information_schema.table_constraints t
  25050. LEFT JOIN information_schema.key_column_usage k
  25051. USING(constraint_name,table_schema,table_name)
  25052. WHERE t.constraint_type='PRIMARY KEY'
  25053. and table_name != '__drizzle_migrations'
  25054. AND t.table_schema = '${inputSchema}'
  25055. ORDER BY ordinal_position`
  25056. );
  25057. const tableToPk = {};
  25058. const tableToPkRows = tablePks;
  25059. for (const tableToPkRow of tableToPkRows) {
  25060. const tableName = tableToPkRow["TABLE_NAME"];
  25061. const columnName = tableToPkRow["COLUMN_NAME"];
  25062. const position = tableToPkRow["ordinal_position"];
  25063. if (typeof result[tableName] === "undefined") {
  25064. continue;
  25065. }
  25066. if (typeof tableToPk[tableName] === "undefined") {
  25067. tableToPk[tableName] = [columnName];
  25068. } else {
  25069. tableToPk[tableName].push(columnName);
  25070. }
  25071. }
  25072. for (const [key, value] of Object.entries(tableToPk)) {
  25073. result[key].compositePrimaryKeys = {
  25074. [`${key}_${value.join("_")}`]: {
  25075. name: `${key}_${value.join("_")}`,
  25076. columns: value
  25077. }
  25078. };
  25079. }
  25080. if (progressCallback) {
  25081. progressCallback("columns", columnsCount, "done");
  25082. progressCallback("tables", tablesCount.size, "done");
  25083. }
  25084. try {
  25085. const fks = await db.query(
  25086. `SELECT
  25087. kcu.TABLE_SCHEMA,
  25088. kcu.TABLE_NAME,
  25089. kcu.CONSTRAINT_NAME,
  25090. kcu.COLUMN_NAME,
  25091. kcu.REFERENCED_TABLE_SCHEMA,
  25092. kcu.REFERENCED_TABLE_NAME,
  25093. kcu.REFERENCED_COLUMN_NAME,
  25094. rc.UPDATE_RULE,
  25095. rc.DELETE_RULE
  25096. FROM
  25097. INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
  25098. LEFT JOIN
  25099. information_schema.referential_constraints rc
  25100. ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
  25101. WHERE kcu.TABLE_SCHEMA = '${inputSchema}' AND kcu.CONSTRAINT_NAME != 'PRIMARY'
  25102. AND kcu.REFERENCED_TABLE_NAME IS NOT NULL;`
  25103. );
  25104. const fkRows = fks;
  25105. for (const fkRow of fkRows) {
  25106. foreignKeysCount += 1;
  25107. if (progressCallback) {
  25108. progressCallback("fks", foreignKeysCount, "fetching");
  25109. }
  25110. const tableSchema = fkRow["TABLE_SCHEMA"];
  25111. const tableName = fkRow["TABLE_NAME"];
  25112. const constraintName = fkRow["CONSTRAINT_NAME"];
  25113. const columnName = fkRow["COLUMN_NAME"];
  25114. const refTableSchema = fkRow["REFERENCED_TABLE_SCHEMA"];
  25115. const refTableName = fkRow["REFERENCED_TABLE_NAME"];
  25116. const refColumnName = fkRow["REFERENCED_COLUMN_NAME"];
  25117. const updateRule = fkRow["UPDATE_RULE"];
  25118. const deleteRule = fkRow["DELETE_RULE"];
  25119. const tableInResult = result[tableName];
  25120. if (typeof tableInResult === "undefined") continue;
  25121. if (typeof tableInResult.foreignKeys[constraintName] !== "undefined") {
  25122. tableInResult.foreignKeys[constraintName].columnsFrom.push(columnName);
  25123. tableInResult.foreignKeys[constraintName].columnsTo.push(
  25124. refColumnName
  25125. );
  25126. } else {
  25127. tableInResult.foreignKeys[constraintName] = {
  25128. name: constraintName,
  25129. tableFrom: tableName,
  25130. tableTo: refTableName,
  25131. columnsFrom: [columnName],
  25132. columnsTo: [refColumnName],
  25133. onDelete: deleteRule?.toLowerCase(),
  25134. onUpdate: updateRule?.toLowerCase()
  25135. };
  25136. }
  25137. tableInResult.foreignKeys[constraintName].columnsFrom = [
  25138. ...new Set(tableInResult.foreignKeys[constraintName].columnsFrom)
  25139. ];
  25140. tableInResult.foreignKeys[constraintName].columnsTo = [
  25141. ...new Set(tableInResult.foreignKeys[constraintName].columnsTo)
  25142. ];
  25143. }
  25144. } catch (e6) {
  25145. }
  25146. if (progressCallback) {
  25147. progressCallback("fks", foreignKeysCount, "done");
  25148. }
  25149. for (const idxRow of idxRows) {
  25150. const tableSchema = idxRow["TABLE_SCHEMA"];
  25151. const tableName = idxRow["TABLE_NAME"];
  25152. const constraintName = idxRow["INDEX_NAME"];
  25153. const columnName = idxRow["COLUMN_NAME"];
  25154. const isUnique = idxRow["NON_UNIQUE"] === 0;
  25155. const tableInResult = result[tableName];
  25156. if (typeof tableInResult === "undefined") continue;
  25157. indexesCount += 1;
  25158. if (progressCallback) {
  25159. progressCallback("indexes", indexesCount, "fetching");
  25160. }
  25161. if (isUnique) {
  25162. if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
  25163. tableInResult.uniqueConstraints[constraintName].columns.push(
  25164. columnName
  25165. );
  25166. } else {
  25167. tableInResult.uniqueConstraints[constraintName] = {
  25168. name: constraintName,
  25169. columns: [columnName]
  25170. };
  25171. }
  25172. } else {
  25173. if (typeof tableInResult.foreignKeys[constraintName] === "undefined") {
  25174. if (typeof tableInResult.indexes[constraintName] !== "undefined") {
  25175. tableInResult.indexes[constraintName].columns.push(columnName);
  25176. } else {
  25177. tableInResult.indexes[constraintName] = {
  25178. name: constraintName,
  25179. columns: [columnName],
  25180. isUnique
  25181. };
  25182. }
  25183. }
  25184. }
  25185. }
  25186. const views = await db.query(
  25187. `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
  25188. );
  25189. const resultViews = {};
  25190. viewsCount = views.length;
  25191. if (progressCallback) {
  25192. progressCallback("views", viewsCount, "fetching");
  25193. }
  25194. for await (const view5 of views) {
  25195. const viewName = view5["TABLE_NAME"];
  25196. const definition = view5["VIEW_DEFINITION"];
  25197. const withCheckOption = view5["CHECK_OPTION"] === "NONE" ? void 0 : view5["CHECK_OPTION"].toLowerCase();
  25198. const sqlSecurity = view5["SECURITY_TYPE"].toLowerCase();
  25199. const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
  25200. const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
  25201. const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
  25202. const columns2 = result[viewName].columns;
  25203. delete result[viewName];
  25204. resultViews[viewName] = {
  25205. columns: columns2,
  25206. isExisting: false,
  25207. name: viewName,
  25208. algorithm,
  25209. definition,
  25210. sqlSecurity,
  25211. withCheckOption
  25212. };
  25213. }
  25214. if (progressCallback) {
  25215. progressCallback("indexes", indexesCount, "done");
  25216. progressCallback("enums", 0, "done");
  25217. progressCallback("views", viewsCount, "done");
  25218. }
  25219. const checkConstraints = await db.query(
  25220. `SELECT
  25221. tc.table_name,
  25222. tc.constraint_name,
  25223. cc.check_clause
  25224. FROM
  25225. information_schema.table_constraints tc
  25226. JOIN
  25227. information_schema.check_constraints cc
  25228. ON tc.constraint_name = cc.constraint_name
  25229. WHERE
  25230. tc.constraint_schema = '${inputSchema}'
  25231. AND
  25232. tc.constraint_type = 'CHECK';`
  25233. );
  25234. checksCount += checkConstraints.length;
  25235. if (progressCallback) {
  25236. progressCallback("checks", checksCount, "fetching");
  25237. }
  25238. for (const checkConstraintRow of checkConstraints) {
  25239. const constraintName = checkConstraintRow["CONSTRAINT_NAME"];
  25240. const constraintValue = checkConstraintRow["CHECK_CLAUSE"];
  25241. const tableName = checkConstraintRow["TABLE_NAME"];
  25242. const tableInResult = result[tableName];
  25243. tableInResult.checkConstraint[constraintName] = {
  25244. name: constraintName,
  25245. value: constraintValue
  25246. };
  25247. }
  25248. if (progressCallback) {
  25249. progressCallback("checks", checksCount, "done");
  25250. }
  25251. return {
  25252. version: "5",
  25253. dialect: "mysql",
  25254. tables: result,
  25255. views: resultViews,
  25256. _meta: {
  25257. tables: {},
  25258. columns: {}
  25259. },
  25260. internal: internals
  25261. };
  25262. };
  25263. }
  25264. });
  25265. // src/cli/validations/cli.ts
  25266. var cliConfigGenerate, pushParams, pullParams, configCheck, cliConfigCheck;
  25267. var init_cli = __esm({
  25268. "src/cli/validations/cli.ts"() {
  25269. "use strict";
  25270. init_esm();
  25271. init_schemaValidator();
  25272. init_common();
  25273. cliConfigGenerate = objectType({
  25274. dialect: dialect4.optional(),
  25275. schema: unionType([stringType(), stringType().array()]).optional(),
  25276. out: stringType().optional().default("./drizzle"),
  25277. config: stringType().optional(),
  25278. name: stringType().optional(),
  25279. prefix: prefix.optional(),
  25280. breakpoints: booleanType().optional().default(true),
  25281. custom: booleanType().optional().default(false)
  25282. }).strict();
  25283. pushParams = objectType({
  25284. dialect: dialect4,
  25285. casing: casingType.optional(),
  25286. schema: unionType([stringType(), stringType().array()]),
  25287. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  25288. schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
  25289. extensionsFilters: literalType("postgis").array().optional(),
  25290. verbose: booleanType().optional(),
  25291. strict: booleanType().optional(),
  25292. entities: objectType({
  25293. roles: booleanType().or(objectType({
  25294. provider: stringType().optional(),
  25295. include: stringType().array().optional(),
  25296. exclude: stringType().array().optional()
  25297. })).optional().default(false)
  25298. }).optional()
  25299. }).passthrough();
  25300. pullParams = objectType({
  25301. config: stringType().optional(),
  25302. dialect: dialect4,
  25303. out: stringType().optional().default("drizzle"),
  25304. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  25305. schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
  25306. extensionsFilters: literalType("postgis").array().optional(),
  25307. casing,
  25308. breakpoints: booleanType().optional().default(true),
  25309. migrations: objectType({
  25310. prefix: prefix.optional().default("index")
  25311. }).optional(),
  25312. entities: objectType({
  25313. roles: booleanType().or(objectType({
  25314. provider: stringType().optional(),
  25315. include: stringType().array().optional(),
  25316. exclude: stringType().array().optional()
  25317. })).optional().default(false)
  25318. }).optional()
  25319. }).passthrough();
  25320. configCheck = objectType({
  25321. dialect: dialect4.optional(),
  25322. out: stringType().optional()
  25323. });
  25324. cliConfigCheck = intersectionType(
  25325. objectType({
  25326. config: stringType().optional()
  25327. }),
  25328. configCheck
  25329. );
  25330. }
  25331. });
  25332. // src/cli/validations/gel.ts
  25333. var gelCredentials;
  25334. var init_gel = __esm({
  25335. "src/cli/validations/gel.ts"() {
  25336. "use strict";
  25337. init_esm();
  25338. init_views();
  25339. init_common();
  25340. gelCredentials = unionType([
  25341. objectType({
  25342. driver: undefinedType(),
  25343. host: stringType().min(1),
  25344. port: coerce.number().min(1).optional(),
  25345. user: stringType().min(1).optional(),
  25346. password: stringType().min(1).optional(),
  25347. database: stringType().min(1),
  25348. tlsSecurity: unionType([
  25349. literalType("insecure"),
  25350. literalType("no_host_verification"),
  25351. literalType("strict"),
  25352. literalType("default")
  25353. ]).optional()
  25354. }).transform((o5) => {
  25355. delete o5.driver;
  25356. return o5;
  25357. }),
  25358. objectType({
  25359. driver: undefinedType(),
  25360. url: stringType().min(1),
  25361. tlsSecurity: unionType([
  25362. literalType("insecure"),
  25363. literalType("no_host_verification"),
  25364. literalType("strict"),
  25365. literalType("default")
  25366. ]).optional()
  25367. }).transform((o5) => {
  25368. delete o5.driver;
  25369. return o5;
  25370. }),
  25371. objectType({
  25372. driver: undefinedType()
  25373. }).transform((o5) => {
  25374. return void 0;
  25375. })
  25376. ]);
  25377. }
  25378. });
  25379. // src/cli/validations/libsql.ts
  25380. var libSQLCredentials;
  25381. var init_libsql = __esm({
  25382. "src/cli/validations/libsql.ts"() {
  25383. "use strict";
  25384. init_esm();
  25385. init_views();
  25386. init_common();
  25387. libSQLCredentials = objectType({
  25388. url: stringType().min(1),
  25389. authToken: stringType().min(1).optional()
  25390. });
  25391. }
  25392. });
  25393. // src/cli/validations/mysql.ts
  25394. var mysqlCredentials;
  25395. var init_mysql = __esm({
  25396. "src/cli/validations/mysql.ts"() {
  25397. "use strict";
  25398. init_esm();
  25399. init_views();
  25400. init_common();
  25401. init_outputs();
  25402. mysqlCredentials = unionType([
  25403. objectType({
  25404. host: stringType().min(1),
  25405. port: coerce.number().min(1).optional(),
  25406. user: stringType().min(1).optional(),
  25407. password: stringType().min(1).optional(),
  25408. database: stringType().min(1),
  25409. ssl: unionType([
  25410. stringType(),
  25411. objectType({
  25412. pfx: stringType().optional(),
  25413. key: stringType().optional(),
  25414. passphrase: stringType().optional(),
  25415. cert: stringType().optional(),
  25416. ca: unionType([stringType(), stringType().array()]).optional(),
  25417. crl: unionType([stringType(), stringType().array()]).optional(),
  25418. ciphers: stringType().optional(),
  25419. rejectUnauthorized: booleanType().optional()
  25420. })
  25421. ]).optional()
  25422. }),
  25423. objectType({
  25424. url: stringType().min(1)
  25425. })
  25426. ]);
  25427. }
  25428. });
  25429. // src/cli/validations/postgres.ts
  25430. var postgresCredentials;
  25431. var init_postgres = __esm({
  25432. "src/cli/validations/postgres.ts"() {
  25433. "use strict";
  25434. init_esm();
  25435. init_views();
  25436. init_common();
  25437. postgresCredentials = unionType([
  25438. objectType({
  25439. driver: undefinedType(),
  25440. host: stringType().min(1),
  25441. port: coerce.number().min(1).optional(),
  25442. user: stringType().min(1).optional(),
  25443. password: stringType().min(1).optional(),
  25444. database: stringType().min(1),
  25445. ssl: unionType([
  25446. literalType("require"),
  25447. literalType("allow"),
  25448. literalType("prefer"),
  25449. literalType("verify-full"),
  25450. booleanType(),
  25451. objectType({}).passthrough()
  25452. ]).optional()
  25453. }).transform((o5) => {
  25454. delete o5.driver;
  25455. return o5;
  25456. }),
  25457. objectType({
  25458. driver: undefinedType(),
  25459. url: stringType().min(1)
  25460. }).transform((o5) => {
  25461. delete o5.driver;
  25462. return o5;
  25463. }),
  25464. objectType({
  25465. driver: literalType("aws-data-api"),
  25466. database: stringType().min(1),
  25467. secretArn: stringType().min(1),
  25468. resourceArn: stringType().min(1)
  25469. }),
  25470. objectType({
  25471. driver: literalType("pglite"),
  25472. url: stringType().min(1)
  25473. })
  25474. ]);
  25475. }
  25476. });
  25477. // src/cli/validations/singlestore.ts
  25478. var singlestoreCredentials;
  25479. var init_singlestore = __esm({
  25480. "src/cli/validations/singlestore.ts"() {
  25481. "use strict";
  25482. init_esm();
  25483. init_views();
  25484. init_common();
  25485. init_outputs();
  25486. singlestoreCredentials = unionType([
  25487. objectType({
  25488. host: stringType().min(1),
  25489. port: coerce.number().min(1).optional(),
  25490. user: stringType().min(1).optional(),
  25491. password: stringType().min(1).optional(),
  25492. database: stringType().min(1),
  25493. ssl: unionType([
  25494. stringType(),
  25495. objectType({
  25496. pfx: stringType().optional(),
  25497. key: stringType().optional(),
  25498. passphrase: stringType().optional(),
  25499. cert: stringType().optional(),
  25500. ca: unionType([stringType(), stringType().array()]).optional(),
  25501. crl: unionType([stringType(), stringType().array()]).optional(),
  25502. ciphers: stringType().optional(),
  25503. rejectUnauthorized: booleanType().optional()
  25504. })
  25505. ]).optional()
  25506. }),
  25507. objectType({
  25508. url: stringType().min(1)
  25509. })
  25510. ]);
  25511. }
  25512. });
  25513. // src/cli/validations/sqlite.ts
  25514. var sqliteCredentials;
  25515. var init_sqlite = __esm({
  25516. "src/cli/validations/sqlite.ts"() {
  25517. "use strict";
  25518. init_global();
  25519. init_esm();
  25520. init_views();
  25521. init_common();
  25522. sqliteCredentials = unionType([
  25523. objectType({
  25524. driver: literalType("turso"),
  25525. url: stringType().min(1),
  25526. authToken: stringType().min(1).optional()
  25527. }),
  25528. objectType({
  25529. driver: literalType("d1-http"),
  25530. accountId: stringType().min(1),
  25531. databaseId: stringType().min(1),
  25532. token: stringType().min(1)
  25533. }),
  25534. objectType({
  25535. driver: undefinedType(),
  25536. url: stringType().min(1)
  25537. }).transform((o5) => {
  25538. delete o5.driver;
  25539. return o5;
  25540. })
  25541. ]);
  25542. }
  25543. });
  25544. // src/cli/validations/studio.ts
  25545. var credentials, studioCliParams, studioConfig;
  25546. var init_studio = __esm({
  25547. "src/cli/validations/studio.ts"() {
  25548. "use strict";
  25549. init_esm();
  25550. init_schemaValidator();
  25551. init_common();
  25552. init_mysql();
  25553. init_postgres();
  25554. init_sqlite();
  25555. credentials = intersectionType(
  25556. postgresCredentials,
  25557. mysqlCredentials,
  25558. sqliteCredentials
  25559. );
  25560. studioCliParams = objectType({
  25561. port: coerce.number().optional().default(4983),
  25562. host: stringType().optional().default("127.0.0.1"),
  25563. config: stringType().optional()
  25564. });
  25565. studioConfig = objectType({
  25566. dialect: dialect4,
  25567. schema: unionType([stringType(), stringType().array()]).optional(),
  25568. casing: casingType.optional()
  25569. });
  25570. }
  25571. });
  25572. // src/cli/commands/_es5.ts
  25573. var es5_exports = {};
  25574. __export(es5_exports, {
  25575. default: () => es5_default
  25576. });
  25577. var _, es5_default;
  25578. var init_es5 = __esm({
  25579. "src/cli/commands/_es5.ts"() {
  25580. "use strict";
  25581. _ = "";
  25582. es5_default = _;
  25583. }
  25584. });
  25585. // src/cli/commands/utils.ts
  25586. var import_hanji7, assertES5, InMemoryMutex, registerMutex, tsxRegistered, ensureTsxRegistered, safeRegister, migrateConfig;
  25587. var init_utils3 = __esm({
  25588. "src/cli/commands/utils.ts"() {
  25589. "use strict";
  25590. import_hanji7 = __toESM(require_hanji());
  25591. init_esm();
  25592. init_getTablesFilterByExtensions();
  25593. init_global();
  25594. init_schemaValidator();
  25595. init_serializer();
  25596. init_cli();
  25597. init_common();
  25598. init_gel();
  25599. init_libsql();
  25600. init_mysql();
  25601. init_outputs();
  25602. init_postgres();
  25603. init_singlestore();
  25604. init_sqlite();
  25605. init_studio();
  25606. init_views();
  25607. assertES5 = async () => {
  25608. try {
  25609. await Promise.resolve().then(() => (init_es5(), es5_exports));
  25610. } catch (e6) {
  25611. if ("errors" in e6 && Array.isArray(e6.errors) && e6.errors.length > 0) {
  25612. const es5Error = e6.errors.filter((it) => it.text?.includes(`("es5") is not supported yet`)).length > 0;
  25613. if (es5Error) {
  25614. console.log(
  25615. error(
  25616. `Please change compilerOptions.target from 'es5' to 'es6' or above in your tsconfig.json`
  25617. )
  25618. );
  25619. process.exit(1);
  25620. }
  25621. }
  25622. console.error(e6);
  25623. process.exit(1);
  25624. }
  25625. };
  25626. InMemoryMutex = class {
  25627. constructor() {
  25628. this.lockPromise = null;
  25629. }
  25630. async withLock(fn) {
  25631. while (this.lockPromise) {
  25632. await this.lockPromise;
  25633. }
  25634. let resolveLock;
  25635. this.lockPromise = new Promise((resolve) => {
  25636. resolveLock = resolve;
  25637. });
  25638. try {
  25639. return await fn();
  25640. } finally {
  25641. this.lockPromise = null;
  25642. resolveLock();
  25643. }
  25644. }
  25645. };
  25646. registerMutex = new InMemoryMutex();
  25647. tsxRegistered = false;
  25648. ensureTsxRegistered = () => {
  25649. if (tsxRegistered) return;
  25650. const isBun = typeof globalThis.Bun !== "undefined";
  25651. const isDeno = typeof globalThis.Deno !== "undefined";
  25652. if (isBun || isDeno) {
  25653. tsxRegistered = true;
  25654. return;
  25655. }
  25656. const tsx = __require("tsx/cjs/api");
  25657. tsx.register();
  25658. tsxRegistered = true;
  25659. };
  25660. safeRegister = async (fn) => {
  25661. return registerMutex.withLock(async () => {
  25662. ensureTsxRegistered();
  25663. await assertES5();
  25664. return fn();
  25665. });
  25666. };
  25667. migrateConfig = objectType({
  25668. dialect: dialect4,
  25669. out: stringType().optional().default("drizzle"),
  25670. migrations: configMigrations
  25671. });
  25672. }
  25673. });
  25674. // src/serializer/pgImports.ts
  25675. import { is as is4 } from "drizzle-orm";
  25676. import {
  25677. isPgEnum,
  25678. isPgMaterializedView,
  25679. isPgSequence,
  25680. isPgView,
  25681. PgPolicy as PgPolicy2,
  25682. PgRole as PgRole2,
  25683. PgSchema as PgSchema7,
  25684. PgTable
  25685. } from "drizzle-orm/pg-core";
  25686. import { Relations } from "drizzle-orm/relations";
  25687. var prepareFromExports;
  25688. var init_pgImports = __esm({
  25689. "src/serializer/pgImports.ts"() {
  25690. "use strict";
  25691. init_utils3();
  25692. prepareFromExports = (exports) => {
  25693. const tables = [];
  25694. const enums = [];
  25695. const schemas = [];
  25696. const sequences = [];
  25697. const roles = [];
  25698. const policies = [];
  25699. const views = [];
  25700. const matViews = [];
  25701. const relations = [];
  25702. const i0values = Object.values(exports);
  25703. i0values.forEach((t6) => {
  25704. if (isPgEnum(t6)) {
  25705. enums.push(t6);
  25706. return;
  25707. }
  25708. if (is4(t6, PgTable)) {
  25709. tables.push(t6);
  25710. }
  25711. if (is4(t6, PgSchema7)) {
  25712. schemas.push(t6);
  25713. }
  25714. if (isPgView(t6)) {
  25715. views.push(t6);
  25716. }
  25717. if (isPgMaterializedView(t6)) {
  25718. matViews.push(t6);
  25719. }
  25720. if (isPgSequence(t6)) {
  25721. sequences.push(t6);
  25722. }
  25723. if (is4(t6, PgRole2)) {
  25724. roles.push(t6);
  25725. }
  25726. if (is4(t6, PgPolicy2)) {
  25727. policies.push(t6);
  25728. }
  25729. if (is4(t6, Relations)) {
  25730. relations.push(t6);
  25731. }
  25732. });
  25733. return { tables, enums, schemas, sequences, views, matViews, roles, policies, relations };
  25734. };
  25735. }
  25736. });
  25737. // src/serializer/singlestoreSerializer.ts
  25738. import { is as is5, SQL as SQL4 } from "drizzle-orm";
  25739. import {
  25740. getTableConfig as getTableConfig4,
  25741. SingleStoreDialect,
  25742. uniqueKeyName as uniqueKeyName4
  25743. } from "drizzle-orm/singlestore-core";
  25744. function clearDefaults2(defaultValue, collate) {
  25745. if (typeof collate === "undefined" || collate === null) {
  25746. collate = `utf8mb4`;
  25747. }
  25748. let resultDefault = defaultValue;
  25749. collate = `_${collate}`;
  25750. if (defaultValue.startsWith(collate)) {
  25751. resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
  25752. if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
  25753. return `('${resultDefault.substring(1, resultDefault.length - 1)}')`;
  25754. } else {
  25755. return `'${resultDefault}'`;
  25756. }
  25757. } else {
  25758. return `(${resultDefault})`;
  25759. }
  25760. }
  25761. var dialect5, generateSingleStoreSnapshot, fromDatabase4;
  25762. var init_singlestoreSerializer = __esm({
  25763. "src/serializer/singlestoreSerializer.ts"() {
  25764. "use strict";
  25765. init_source();
  25766. init_outputs();
  25767. init_utils2();
  25768. dialect5 = new SingleStoreDialect();
  25769. generateSingleStoreSnapshot = (tables, casing2) => {
  25770. const dialect6 = new SingleStoreDialect({ casing: casing2 });
  25771. const result = {};
  25772. const internal = { tables: {}, indexes: {} };
  25773. for (const table6 of tables) {
  25774. const {
  25775. name: tableName,
  25776. columns,
  25777. indexes,
  25778. schema: schema6,
  25779. primaryKeys,
  25780. uniqueConstraints
  25781. } = getTableConfig4(table6);
  25782. const columnsObject = {};
  25783. const indexesObject = {};
  25784. const primaryKeysObject = {};
  25785. const uniqueConstraintObject = {};
  25786. columns.forEach((column6) => {
  25787. const notNull = column6.notNull;
  25788. const sqlTypeLowered = column6.getSQLType().toLowerCase();
  25789. const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
  25790. const generated = column6.generated;
  25791. const columnToSet = {
  25792. name: column6.name,
  25793. type: column6.getSQLType(),
  25794. primaryKey: false,
  25795. // If field is autoincrement it's notNull by default
  25796. // notNull: autoIncrement ? true : notNull,
  25797. notNull,
  25798. autoincrement: autoIncrement,
  25799. onUpdate: column6.hasOnUpdateNow,
  25800. generated: generated ? {
  25801. as: is5(generated.as, SQL4) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  25802. type: generated.mode ?? "stored"
  25803. } : void 0
  25804. };
  25805. if (column6.primary) {
  25806. primaryKeysObject[`${tableName}_${column6.name}`] = {
  25807. name: `${tableName}_${column6.name}`,
  25808. columns: [column6.name]
  25809. };
  25810. }
  25811. if (column6.isUnique) {
  25812. const existingUnique = uniqueConstraintObject[column6.uniqueName];
  25813. if (typeof existingUnique !== "undefined") {
  25814. console.log(
  25815. `
  25816. ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
  25817. tableName
  25818. )} table.
  25819. The unique constraint ${source_default.underline.blue(
  25820. column6.uniqueName
  25821. )} on the ${source_default.underline.blue(
  25822. column6.name
  25823. )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  25824. existingUnique.columns.join(",")
  25825. )} columns
  25826. `)}`
  25827. );
  25828. process.exit(1);
  25829. }
  25830. uniqueConstraintObject[column6.uniqueName] = {
  25831. name: column6.uniqueName,
  25832. columns: [columnToSet.name]
  25833. };
  25834. }
  25835. if (column6.default !== void 0) {
  25836. if (is5(column6.default, SQL4)) {
  25837. columnToSet.default = sqlToStr(column6.default, casing2);
  25838. } else {
  25839. if (typeof column6.default === "string") {
  25840. columnToSet.default = `'${column6.default}'`;
  25841. } else {
  25842. if (sqlTypeLowered === "json" || Array.isArray(column6.default)) {
  25843. columnToSet.default = `'${JSON.stringify(column6.default)}'`;
  25844. } else if (column6.default instanceof Date) {
  25845. if (sqlTypeLowered === "date") {
  25846. columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
  25847. } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
  25848. columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  25849. }
  25850. } else {
  25851. columnToSet.default = column6.default;
  25852. }
  25853. }
  25854. }
  25855. }
  25856. columnsObject[column6.name] = columnToSet;
  25857. });
  25858. primaryKeys.map((pk) => {
  25859. const columnNames = pk.columns.map((c5) => c5.name);
  25860. primaryKeysObject[pk.getName()] = {
  25861. name: pk.getName(),
  25862. columns: columnNames
  25863. };
  25864. for (const column6 of pk.columns) {
  25865. columnsObject[column6.name].notNull = true;
  25866. }
  25867. });
  25868. uniqueConstraints?.map((unq) => {
  25869. const columnNames = unq.columns.map((c5) => c5.name);
  25870. const name = unq.name ?? uniqueKeyName4(table6, columnNames);
  25871. const existingUnique = uniqueConstraintObject[name];
  25872. if (typeof existingUnique !== "undefined") {
  25873. console.log(
  25874. `
  25875. ${withStyle.errorWarning(
  25876. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  25877. tableName
  25878. )} table.
  25879. The unique constraint ${source_default.underline.blue(
  25880. name
  25881. )} on the ${source_default.underline.blue(
  25882. columnNames.join(",")
  25883. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  25884. existingUnique.columns.join(",")
  25885. )} columns
  25886. `
  25887. )}`
  25888. );
  25889. process.exit(1);
  25890. }
  25891. uniqueConstraintObject[name] = {
  25892. name: unq.name,
  25893. columns: columnNames
  25894. };
  25895. });
  25896. indexes.forEach((value) => {
  25897. const columns2 = value.config.columns;
  25898. const name = value.config.name;
  25899. let indexColumns = columns2.map((it) => {
  25900. if (is5(it, SQL4)) {
  25901. const sql = dialect6.sqlToQuery(it, "indexes").sql;
  25902. if (typeof internal.indexes[name] === "undefined") {
  25903. internal.indexes[name] = {
  25904. columns: {
  25905. [sql]: {
  25906. isExpression: true
  25907. }
  25908. }
  25909. };
  25910. } else {
  25911. if (typeof internal.indexes[name]?.columns[sql] === "undefined") {
  25912. internal.indexes[name].columns[sql] = {
  25913. isExpression: true
  25914. };
  25915. } else {
  25916. internal.indexes[name].columns[sql].isExpression = true;
  25917. }
  25918. }
  25919. return sql;
  25920. } else {
  25921. return `${it.name}`;
  25922. }
  25923. });
  25924. if (value.config.unique) {
  25925. if (typeof uniqueConstraintObject[name] !== "undefined") {
  25926. console.log(
  25927. `
  25928. ${withStyle.errorWarning(
  25929. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  25930. tableName
  25931. )} table.
  25932. The unique index ${source_default.underline.blue(
  25933. name
  25934. )} on the ${source_default.underline.blue(
  25935. indexColumns.join(",")
  25936. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  25937. uniqueConstraintObject[name].columns.join(",")
  25938. )} columns
  25939. `
  25940. )}`
  25941. );
  25942. process.exit(1);
  25943. }
  25944. }
  25945. indexesObject[name] = {
  25946. name,
  25947. columns: indexColumns,
  25948. isUnique: value.config.unique ?? false,
  25949. using: value.config.using,
  25950. algorithm: value.config.algorithm,
  25951. lock: value.config.lock
  25952. };
  25953. });
  25954. if (!schema6) {
  25955. result[tableName] = {
  25956. name: tableName,
  25957. columns: columnsObject,
  25958. indexes: indexesObject,
  25959. compositePrimaryKeys: primaryKeysObject,
  25960. uniqueConstraints: uniqueConstraintObject
  25961. };
  25962. }
  25963. }
  25964. return {
  25965. version: "1",
  25966. dialect: "singlestore",
  25967. tables: result,
  25968. /* views: resultViews, */
  25969. _meta: {
  25970. tables: {},
  25971. columns: {}
  25972. },
  25973. internal
  25974. };
  25975. };
  25976. fromDatabase4 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
  25977. const result = {};
  25978. const internals = { tables: {}, indexes: {} };
  25979. const columns = await db.query(`select * from information_schema.columns
  25980. where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
  25981. order by table_name, ordinal_position;`);
  25982. const response = columns;
  25983. const schemas = [];
  25984. let columnsCount = 0;
  25985. let tablesCount = /* @__PURE__ */ new Set();
  25986. let indexesCount = 0;
  25987. const idxs = await db.query(
  25988. `select * from INFORMATION_SCHEMA.STATISTICS
  25989. WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
  25990. );
  25991. const idxRows = idxs;
  25992. for (const column6 of response) {
  25993. if (!tablesFilter(column6["TABLE_NAME"])) continue;
  25994. columnsCount += 1;
  25995. if (progressCallback) {
  25996. progressCallback("columns", columnsCount, "fetching");
  25997. }
  25998. const schema6 = column6["TABLE_SCHEMA"];
  25999. const tableName = column6["TABLE_NAME"];
  26000. tablesCount.add(`${schema6}.${tableName}`);
  26001. if (progressCallback) {
  26002. progressCallback("columns", tablesCount.size, "fetching");
  26003. }
  26004. const columnName = column6["COLUMN_NAME"];
  26005. const isNullable = column6["IS_NULLABLE"] === "YES";
  26006. const dataType = column6["DATA_TYPE"];
  26007. const columnType = column6["COLUMN_TYPE"];
  26008. const isPrimary = column6["COLUMN_KEY"] === "PRI";
  26009. let columnDefault = column6["COLUMN_DEFAULT"];
  26010. const collation = column6["CHARACTER_SET_NAME"];
  26011. const geenratedExpression = column6["GENERATION_EXPRESSION"];
  26012. let columnExtra = column6["EXTRA"];
  26013. let isAutoincrement = false;
  26014. let isDefaultAnExpression = false;
  26015. if (typeof column6["EXTRA"] !== "undefined") {
  26016. columnExtra = column6["EXTRA"];
  26017. isAutoincrement = column6["EXTRA"] === "auto_increment";
  26018. isDefaultAnExpression = column6["EXTRA"].includes("DEFAULT_GENERATED");
  26019. }
  26020. if (schema6 !== inputSchema) {
  26021. schemas.push(schema6);
  26022. }
  26023. const table6 = result[tableName];
  26024. let changedType = columnType;
  26025. if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
  26026. const uniqueIdx = idxRows.filter(
  26027. (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
  26028. );
  26029. if (uniqueIdx && uniqueIdx.length === 1) {
  26030. changedType = columnType.replace("bigint unsigned", "serial");
  26031. }
  26032. }
  26033. if (columnType.startsWith("bigint(") || columnType.startsWith("tinyint(") || columnType.startsWith("date(") || columnType.startsWith("int(") || columnType.startsWith("mediumint(") || columnType.startsWith("smallint(") || columnType.startsWith("text(") || columnType.startsWith("time(") || columnType.startsWith("year(")) {
  26034. changedType = columnType.replace(/\(\s*[^)]*\)$/, "");
  26035. }
  26036. if (columnType.includes("decimal(10,0)")) {
  26037. changedType = columnType.replace("decimal(10,0)", "decimal");
  26038. }
  26039. if (columnDefault?.endsWith(".")) {
  26040. columnDefault = columnDefault.slice(0, -1);
  26041. }
  26042. let onUpdate = void 0;
  26043. if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
  26044. onUpdate = true;
  26045. }
  26046. const newColumn = {
  26047. default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults2(columnDefault, collation) : columnDefault.startsWith("CURRENT_TIMESTAMP") ? "CURRENT_TIMESTAMP" : `'${columnDefault}'`,
  26048. autoincrement: isAutoincrement,
  26049. name: columnName,
  26050. type: changedType,
  26051. primaryKey: false,
  26052. notNull: !isNullable,
  26053. onUpdate,
  26054. generated: geenratedExpression ? {
  26055. as: geenratedExpression,
  26056. type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
  26057. } : void 0
  26058. };
  26059. if (isDefaultAnExpression) {
  26060. if (typeof internals.tables[tableName] === "undefined") {
  26061. internals.tables[tableName] = {
  26062. columns: {
  26063. [columnName]: {
  26064. isDefaultAnExpression: true
  26065. }
  26066. }
  26067. };
  26068. } else {
  26069. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  26070. internals.tables[tableName].columns[columnName] = {
  26071. isDefaultAnExpression: true
  26072. };
  26073. } else {
  26074. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  26075. }
  26076. }
  26077. }
  26078. if (!table6) {
  26079. result[tableName] = {
  26080. name: tableName,
  26081. columns: {
  26082. [columnName]: newColumn
  26083. },
  26084. compositePrimaryKeys: {},
  26085. indexes: {},
  26086. uniqueConstraints: {}
  26087. };
  26088. } else {
  26089. result[tableName].columns[columnName] = newColumn;
  26090. }
  26091. }
  26092. const tablePks = await db.query(
  26093. `SELECT table_name, column_name, ordinal_position
  26094. FROM information_schema.table_constraints t
  26095. LEFT JOIN information_schema.key_column_usage k
  26096. USING(constraint_name,table_schema,table_name)
  26097. WHERE t.constraint_type='UNIQUE'
  26098. and table_name != '__drizzle_migrations'
  26099. AND t.table_schema = '${inputSchema}'
  26100. ORDER BY ordinal_position`
  26101. );
  26102. const tableToPk = {};
  26103. const tableToPkRows = tablePks;
  26104. for (const tableToPkRow of tableToPkRows) {
  26105. const tableName = tableToPkRow["table_name"];
  26106. const columnName = tableToPkRow["column_name"];
  26107. const position = tableToPkRow["ordinal_position"];
  26108. if (typeof result[tableName] === "undefined") {
  26109. continue;
  26110. }
  26111. if (typeof tableToPk[tableName] === "undefined") {
  26112. tableToPk[tableName] = [columnName];
  26113. } else {
  26114. tableToPk[tableName].push(columnName);
  26115. }
  26116. }
  26117. for (const [key, value] of Object.entries(tableToPk)) {
  26118. result[key].compositePrimaryKeys = {
  26119. [`${key}_${value.join("_")}`]: {
  26120. name: `${key}_${value.join("_")}`,
  26121. columns: value
  26122. }
  26123. };
  26124. }
  26125. if (progressCallback) {
  26126. progressCallback("columns", columnsCount, "done");
  26127. progressCallback("tables", tablesCount.size, "done");
  26128. }
  26129. for (const idxRow of idxRows) {
  26130. const tableSchema = idxRow["TABLE_SCHEMA"];
  26131. const tableName = idxRow["TABLE_NAME"];
  26132. const constraintName = idxRow["INDEX_NAME"];
  26133. const columnName = idxRow["COLUMN_NAME"];
  26134. const isUnique = idxRow["NON_UNIQUE"] === 0;
  26135. const tableInResult = result[tableName];
  26136. if (typeof tableInResult === "undefined") continue;
  26137. indexesCount += 1;
  26138. if (progressCallback) {
  26139. progressCallback("indexes", indexesCount, "fetching");
  26140. }
  26141. if (isUnique) {
  26142. if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
  26143. tableInResult.uniqueConstraints[constraintName].columns.push(
  26144. columnName
  26145. );
  26146. } else {
  26147. tableInResult.uniqueConstraints[constraintName] = {
  26148. name: constraintName,
  26149. columns: [columnName]
  26150. };
  26151. }
  26152. }
  26153. }
  26154. if (progressCallback) {
  26155. progressCallback("indexes", indexesCount, "done");
  26156. progressCallback("enums", 0, "done");
  26157. }
  26158. return {
  26159. version: "1",
  26160. dialect: "singlestore",
  26161. tables: result,
  26162. /* views: resultViews, */
  26163. _meta: {
  26164. tables: {},
  26165. columns: {}
  26166. },
  26167. internal: internals
  26168. };
  26169. };
  26170. }
  26171. });
  26172. // ../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs
  26173. import { createServer as createServerHTTP } from "http";
  26174. import { Http2ServerRequest } from "http2";
  26175. import { Readable } from "stream";
  26176. import crypto2 from "crypto";
  26177. function writeFromReadableStream(stream, writable) {
  26178. if (stream.locked) {
  26179. throw new TypeError("ReadableStream is locked.");
  26180. } else if (writable.destroyed) {
  26181. stream.cancel();
  26182. return;
  26183. }
  26184. const reader = stream.getReader();
  26185. writable.on("close", cancel);
  26186. writable.on("error", cancel);
  26187. reader.read().then(flow, cancel);
  26188. return reader.closed.finally(() => {
  26189. writable.off("close", cancel);
  26190. writable.off("error", cancel);
  26191. });
  26192. function cancel(error2) {
  26193. reader.cancel(error2).catch(() => {
  26194. });
  26195. if (error2) {
  26196. writable.destroy(error2);
  26197. }
  26198. }
  26199. function onDrain() {
  26200. reader.read().then(flow, cancel);
  26201. }
  26202. function flow({ done, value }) {
  26203. try {
  26204. if (done) {
  26205. writable.end();
  26206. } else if (!writable.write(value)) {
  26207. writable.once("drain", onDrain);
  26208. } else {
  26209. return reader.read().then(flow, cancel);
  26210. }
  26211. } catch (e6) {
  26212. cancel(e6);
  26213. }
  26214. }
  26215. }
  26216. var RequestError, toRequestError, GlobalRequest, Request2, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, _body, _init, _a, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, webFetch, regBuffer, regContentType, handleRequestError, handleFetchError, handleResponseError, responseViaCache, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
  26217. var init_dist = __esm({
  26218. "../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs"() {
  26219. "use strict";
  26220. RequestError = class extends Error {
  26221. constructor(message, options) {
  26222. super(message, options);
  26223. this.name = "RequestError";
  26224. }
  26225. };
  26226. toRequestError = (e6) => {
  26227. if (e6 instanceof RequestError) {
  26228. return e6;
  26229. }
  26230. return new RequestError(e6.message, { cause: e6 });
  26231. };
  26232. GlobalRequest = global.Request;
  26233. Request2 = class extends GlobalRequest {
  26234. constructor(input, options) {
  26235. if (typeof input === "object" && getRequestCache in input) {
  26236. input = input[getRequestCache]();
  26237. }
  26238. if (typeof options?.body?.getReader !== "undefined") {
  26239. ;
  26240. options.duplex ??= "half";
  26241. }
  26242. super(input, options);
  26243. }
  26244. };
  26245. newRequestFromIncoming = (method, url, incoming, abortController) => {
  26246. const headerRecord = [];
  26247. const rawHeaders = incoming.rawHeaders;
  26248. for (let i6 = 0; i6 < rawHeaders.length; i6 += 2) {
  26249. const { [i6]: key, [i6 + 1]: value } = rawHeaders;
  26250. if (key.charCodeAt(0) !== /*:*/
  26251. 58) {
  26252. headerRecord.push([key, value]);
  26253. }
  26254. }
  26255. const init2 = {
  26256. method,
  26257. headers: headerRecord,
  26258. signal: abortController.signal
  26259. };
  26260. if (method === "TRACE") {
  26261. init2.method = "GET";
  26262. const req = new Request2(url, init2);
  26263. Object.defineProperty(req, "method", {
  26264. get() {
  26265. return "TRACE";
  26266. }
  26267. });
  26268. return req;
  26269. }
  26270. if (!(method === "GET" || method === "HEAD")) {
  26271. if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
  26272. init2.body = new ReadableStream({
  26273. start(controller) {
  26274. controller.enqueue(incoming.rawBody);
  26275. controller.close();
  26276. }
  26277. });
  26278. } else {
  26279. init2.body = Readable.toWeb(incoming);
  26280. }
  26281. }
  26282. return new Request2(url, init2);
  26283. };
  26284. getRequestCache = Symbol("getRequestCache");
  26285. requestCache = Symbol("requestCache");
  26286. incomingKey = Symbol("incomingKey");
  26287. urlKey = Symbol("urlKey");
  26288. abortControllerKey = Symbol("abortControllerKey");
  26289. getAbortController = Symbol("getAbortController");
  26290. requestPrototype = {
  26291. get method() {
  26292. return this[incomingKey].method || "GET";
  26293. },
  26294. get url() {
  26295. return this[urlKey];
  26296. },
  26297. [getAbortController]() {
  26298. this[getRequestCache]();
  26299. return this[abortControllerKey];
  26300. },
  26301. [getRequestCache]() {
  26302. this[abortControllerKey] ||= new AbortController();
  26303. return this[requestCache] ||= newRequestFromIncoming(
  26304. this.method,
  26305. this[urlKey],
  26306. this[incomingKey],
  26307. this[abortControllerKey]
  26308. );
  26309. }
  26310. };
  26311. [
  26312. "body",
  26313. "bodyUsed",
  26314. "cache",
  26315. "credentials",
  26316. "destination",
  26317. "headers",
  26318. "integrity",
  26319. "mode",
  26320. "redirect",
  26321. "referrer",
  26322. "referrerPolicy",
  26323. "signal",
  26324. "keepalive"
  26325. ].forEach((k5) => {
  26326. Object.defineProperty(requestPrototype, k5, {
  26327. get() {
  26328. return this[getRequestCache]()[k5];
  26329. }
  26330. });
  26331. });
  26332. ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k5) => {
  26333. Object.defineProperty(requestPrototype, k5, {
  26334. value: function() {
  26335. return this[getRequestCache]()[k5]();
  26336. }
  26337. });
  26338. });
  26339. Object.setPrototypeOf(requestPrototype, Request2.prototype);
  26340. newRequest = (incoming, defaultHostname) => {
  26341. const req = Object.create(requestPrototype);
  26342. req[incomingKey] = incoming;
  26343. const incomingUrl = incoming.url || "";
  26344. if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
  26345. (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
  26346. if (incoming instanceof Http2ServerRequest) {
  26347. throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
  26348. }
  26349. try {
  26350. const url2 = new URL(incomingUrl);
  26351. req[urlKey] = url2.href;
  26352. } catch (e6) {
  26353. throw new RequestError("Invalid absolute URL", { cause: e6 });
  26354. }
  26355. return req;
  26356. }
  26357. const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
  26358. if (!host) {
  26359. throw new RequestError("Missing host header");
  26360. }
  26361. let scheme;
  26362. if (incoming instanceof Http2ServerRequest) {
  26363. scheme = incoming.scheme;
  26364. if (!(scheme === "http" || scheme === "https")) {
  26365. throw new RequestError("Unsupported scheme");
  26366. }
  26367. } else {
  26368. scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
  26369. }
  26370. const url = new URL(`${scheme}://${host}${incomingUrl}`);
  26371. if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
  26372. throw new RequestError("Invalid host header");
  26373. }
  26374. req[urlKey] = url.href;
  26375. return req;
  26376. };
  26377. responseCache = Symbol("responseCache");
  26378. getResponseCache = Symbol("getResponseCache");
  26379. cacheKey = Symbol("cache");
  26380. GlobalResponse = global.Response;
  26381. Response2 = (_a = class {
  26382. constructor(body, init2) {
  26383. __privateAdd(this, _body);
  26384. __privateAdd(this, _init);
  26385. let headers;
  26386. __privateSet(this, _body, body);
  26387. if (init2 instanceof _a) {
  26388. const cachedGlobalResponse = init2[responseCache];
  26389. if (cachedGlobalResponse) {
  26390. __privateSet(this, _init, cachedGlobalResponse);
  26391. this[getResponseCache]();
  26392. return;
  26393. } else {
  26394. __privateSet(this, _init, __privateGet(init2, _init));
  26395. headers = new Headers(__privateGet(init2, _init).headers);
  26396. }
  26397. } else {
  26398. __privateSet(this, _init, init2);
  26399. }
  26400. if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
  26401. headers ||= init2?.headers || { "content-type": "text/plain; charset=UTF-8" };
  26402. this[cacheKey] = [init2?.status || 200, body, headers];
  26403. }
  26404. }
  26405. [getResponseCache]() {
  26406. delete this[cacheKey];
  26407. return this[responseCache] ||= new GlobalResponse(__privateGet(this, _body), __privateGet(this, _init));
  26408. }
  26409. get headers() {
  26410. const cache5 = this[cacheKey];
  26411. if (cache5) {
  26412. if (!(cache5[2] instanceof Headers)) {
  26413. cache5[2] = new Headers(cache5[2]);
  26414. }
  26415. return cache5[2];
  26416. }
  26417. return this[getResponseCache]().headers;
  26418. }
  26419. get status() {
  26420. return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
  26421. }
  26422. get ok() {
  26423. const status = this.status;
  26424. return status >= 200 && status < 300;
  26425. }
  26426. }, _body = new WeakMap(), _init = new WeakMap(), _a);
  26427. ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k5) => {
  26428. Object.defineProperty(Response2.prototype, k5, {
  26429. get() {
  26430. return this[getResponseCache]()[k5];
  26431. }
  26432. });
  26433. });
  26434. ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k5) => {
  26435. Object.defineProperty(Response2.prototype, k5, {
  26436. value: function() {
  26437. return this[getResponseCache]()[k5]();
  26438. }
  26439. });
  26440. });
  26441. Object.setPrototypeOf(Response2, GlobalResponse);
  26442. Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
  26443. buildOutgoingHttpHeaders = (headers) => {
  26444. const res = {};
  26445. if (!(headers instanceof Headers)) {
  26446. headers = new Headers(headers ?? void 0);
  26447. }
  26448. const cookies = [];
  26449. for (const [k5, v6] of headers) {
  26450. if (k5 === "set-cookie") {
  26451. cookies.push(v6);
  26452. } else {
  26453. res[k5] = v6;
  26454. }
  26455. }
  26456. if (cookies.length > 0) {
  26457. res["set-cookie"] = cookies;
  26458. }
  26459. res["content-type"] ??= "text/plain; charset=UTF-8";
  26460. return res;
  26461. };
  26462. X_ALREADY_SENT = "x-hono-already-sent";
  26463. webFetch = global.fetch;
  26464. if (typeof global.crypto === "undefined") {
  26465. global.crypto = crypto2;
  26466. }
  26467. global.fetch = (info2, init2) => {
  26468. init2 = {
  26469. // Disable compression handling so people can return the result of a fetch
  26470. // directly in the loader without messing with the Content-Encoding header.
  26471. compress: false,
  26472. ...init2
  26473. };
  26474. return webFetch(info2, init2);
  26475. };
  26476. regBuffer = /^no$/i;
  26477. regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
  26478. handleRequestError = () => new Response(null, {
  26479. status: 400
  26480. });
  26481. handleFetchError = (e6) => new Response(null, {
  26482. status: e6 instanceof Error && (e6.name === "TimeoutError" || e6.constructor.name === "TimeoutError") ? 504 : 500
  26483. });
  26484. handleResponseError = (e6, outgoing) => {
  26485. const err2 = e6 instanceof Error ? e6 : new Error("unknown error", { cause: e6 });
  26486. if (err2.code === "ERR_STREAM_PREMATURE_CLOSE") {
  26487. console.info("The user aborted a request.");
  26488. } else {
  26489. console.error(e6);
  26490. if (!outgoing.headersSent) {
  26491. outgoing.writeHead(500, { "Content-Type": "text/plain" });
  26492. }
  26493. outgoing.end(`Error: ${err2.message}`);
  26494. outgoing.destroy(err2);
  26495. }
  26496. };
  26497. responseViaCache = async (res, outgoing) => {
  26498. let [status, body, header] = res[cacheKey];
  26499. if (header instanceof Headers) {
  26500. header = buildOutgoingHttpHeaders(header);
  26501. }
  26502. if (typeof body === "string") {
  26503. header["Content-Length"] = Buffer.byteLength(body);
  26504. } else if (body instanceof Uint8Array) {
  26505. header["Content-Length"] = body.byteLength;
  26506. } else if (body instanceof Blob) {
  26507. header["Content-Length"] = body.size;
  26508. }
  26509. outgoing.writeHead(status, header);
  26510. if (typeof body === "string" || body instanceof Uint8Array) {
  26511. outgoing.end(body);
  26512. } else if (body instanceof Blob) {
  26513. outgoing.end(new Uint8Array(await body.arrayBuffer()));
  26514. } else {
  26515. return writeFromReadableStream(body, outgoing)?.catch(
  26516. (e6) => handleResponseError(e6, outgoing)
  26517. );
  26518. }
  26519. };
  26520. responseViaResponseObject = async (res, outgoing, options = {}) => {
  26521. if (res instanceof Promise) {
  26522. if (options.errorHandler) {
  26523. try {
  26524. res = await res;
  26525. } catch (err2) {
  26526. const errRes = await options.errorHandler(err2);
  26527. if (!errRes) {
  26528. return;
  26529. }
  26530. res = errRes;
  26531. }
  26532. } else {
  26533. res = await res.catch(handleFetchError);
  26534. }
  26535. }
  26536. if (cacheKey in res) {
  26537. return responseViaCache(res, outgoing);
  26538. }
  26539. const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
  26540. if (res.body) {
  26541. const {
  26542. "transfer-encoding": transferEncoding,
  26543. "content-encoding": contentEncoding,
  26544. "content-length": contentLength,
  26545. "x-accel-buffering": accelBuffering,
  26546. "content-type": contentType
  26547. } = resHeaderRecord;
  26548. if (transferEncoding || contentEncoding || contentLength || // nginx buffering variant
  26549. accelBuffering && regBuffer.test(accelBuffering) || !regContentType.test(contentType)) {
  26550. outgoing.writeHead(res.status, resHeaderRecord);
  26551. await writeFromReadableStream(res.body, outgoing);
  26552. } else {
  26553. const buffer = await res.arrayBuffer();
  26554. resHeaderRecord["content-length"] = buffer.byteLength;
  26555. outgoing.writeHead(res.status, resHeaderRecord);
  26556. outgoing.end(new Uint8Array(buffer));
  26557. }
  26558. } else if (resHeaderRecord[X_ALREADY_SENT]) {
  26559. } else {
  26560. outgoing.writeHead(res.status, resHeaderRecord);
  26561. outgoing.end();
  26562. }
  26563. };
  26564. getRequestListener = (fetchCallback, options = {}) => {
  26565. if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
  26566. Object.defineProperty(global, "Request", {
  26567. value: Request2
  26568. });
  26569. Object.defineProperty(global, "Response", {
  26570. value: Response2
  26571. });
  26572. }
  26573. return async (incoming, outgoing) => {
  26574. let res, req;
  26575. try {
  26576. req = newRequest(incoming, options.hostname);
  26577. outgoing.on("close", () => {
  26578. const abortController = req[abortControllerKey];
  26579. if (!abortController) {
  26580. return;
  26581. }
  26582. if (incoming.errored) {
  26583. req[abortControllerKey].abort(incoming.errored.toString());
  26584. } else if (!outgoing.writableFinished) {
  26585. req[abortControllerKey].abort("Client connection prematurely closed.");
  26586. }
  26587. });
  26588. res = fetchCallback(req, { incoming, outgoing });
  26589. if (cacheKey in res) {
  26590. return responseViaCache(res, outgoing);
  26591. }
  26592. } catch (e6) {
  26593. if (!res) {
  26594. if (options.errorHandler) {
  26595. res = await options.errorHandler(req ? e6 : toRequestError(e6));
  26596. if (!res) {
  26597. return;
  26598. }
  26599. } else if (!req) {
  26600. res = handleRequestError();
  26601. } else {
  26602. res = handleFetchError(e6);
  26603. }
  26604. } else {
  26605. return handleResponseError(e6, outgoing);
  26606. }
  26607. }
  26608. try {
  26609. return await responseViaResponseObject(res, outgoing, options);
  26610. } catch (e6) {
  26611. return handleResponseError(e6, outgoing);
  26612. }
  26613. };
  26614. };
  26615. createAdaptorServer = (options) => {
  26616. const fetchCallback = options.fetch;
  26617. const requestListener = getRequestListener(fetchCallback, {
  26618. hostname: options.hostname,
  26619. overrideGlobalObjects: options.overrideGlobalObjects
  26620. });
  26621. const createServer2 = options.createServer || createServerHTTP;
  26622. const server = createServer2(options.serverOptions || {}, requestListener);
  26623. return server;
  26624. };
  26625. serve = (options, listeningListener) => {
  26626. const server = createAdaptorServer(options);
  26627. server.listen(options?.port ?? 3e3, options.hostname, () => {
  26628. const serverInfo = server.address();
  26629. listeningListener && listeningListener(serverInfo);
  26630. });
  26631. return server;
  26632. };
  26633. }
  26634. });
  26635. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js
  26636. var splitPath, splitRoutingPath, extractGroupsFromPath, replaceGroupMarks, patternCache, getPattern, tryDecode, tryDecodeURI, getPath, getPathNoStrict, mergePath, checkOptionalParameter, _decodeURI, _getQueryParam, getQueryParam, getQueryParams, decodeURIComponent_;
  26637. var init_url = __esm({
  26638. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js"() {
  26639. "use strict";
  26640. splitPath = (path3) => {
  26641. const paths = path3.split("/");
  26642. if (paths[0] === "") {
  26643. paths.shift();
  26644. }
  26645. return paths;
  26646. };
  26647. splitRoutingPath = (routePath) => {
  26648. const { groups, path: path3 } = extractGroupsFromPath(routePath);
  26649. const paths = splitPath(path3);
  26650. return replaceGroupMarks(paths, groups);
  26651. };
  26652. extractGroupsFromPath = (path3) => {
  26653. const groups = [];
  26654. path3 = path3.replace(/\{[^}]+\}/g, (match2, index6) => {
  26655. const mark = `@${index6}`;
  26656. groups.push([mark, match2]);
  26657. return mark;
  26658. });
  26659. return { groups, path: path3 };
  26660. };
  26661. replaceGroupMarks = (paths, groups) => {
  26662. for (let i6 = groups.length - 1; i6 >= 0; i6--) {
  26663. const [mark] = groups[i6];
  26664. for (let j5 = paths.length - 1; j5 >= 0; j5--) {
  26665. if (paths[j5].includes(mark)) {
  26666. paths[j5] = paths[j5].replace(mark, groups[i6][1]);
  26667. break;
  26668. }
  26669. }
  26670. }
  26671. return paths;
  26672. };
  26673. patternCache = {};
  26674. getPattern = (label, next) => {
  26675. if (label === "*") {
  26676. return "*";
  26677. }
  26678. const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
  26679. if (match2) {
  26680. const cacheKey2 = `${label}#${next}`;
  26681. if (!patternCache[cacheKey2]) {
  26682. if (match2[2]) {
  26683. patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
  26684. } else {
  26685. patternCache[cacheKey2] = [label, match2[1], true];
  26686. }
  26687. }
  26688. return patternCache[cacheKey2];
  26689. }
  26690. return null;
  26691. };
  26692. tryDecode = (str, decoder) => {
  26693. try {
  26694. return decoder(str);
  26695. } catch {
  26696. return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
  26697. try {
  26698. return decoder(match2);
  26699. } catch {
  26700. return match2;
  26701. }
  26702. });
  26703. }
  26704. };
  26705. tryDecodeURI = (str) => tryDecode(str, decodeURI);
  26706. getPath = (request2) => {
  26707. const url = request2.url;
  26708. const start = url.indexOf("/", 8);
  26709. let i6 = start;
  26710. for (; i6 < url.length; i6++) {
  26711. const charCode = url.charCodeAt(i6);
  26712. if (charCode === 37) {
  26713. const queryIndex = url.indexOf("?", i6);
  26714. const path3 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
  26715. return tryDecodeURI(path3.includes("%25") ? path3.replace(/%25/g, "%2525") : path3);
  26716. } else if (charCode === 63) {
  26717. break;
  26718. }
  26719. }
  26720. return url.slice(start, i6);
  26721. };
  26722. getPathNoStrict = (request2) => {
  26723. const result = getPath(request2);
  26724. return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
  26725. };
  26726. mergePath = (base, sub, ...rest) => {
  26727. if (rest.length) {
  26728. sub = mergePath(sub, ...rest);
  26729. }
  26730. return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
  26731. };
  26732. checkOptionalParameter = (path3) => {
  26733. if (path3.charCodeAt(path3.length - 1) !== 63 || !path3.includes(":")) {
  26734. return null;
  26735. }
  26736. const segments = path3.split("/");
  26737. const results = [];
  26738. let basePath = "";
  26739. segments.forEach((segment) => {
  26740. if (segment !== "" && !/\:/.test(segment)) {
  26741. basePath += "/" + segment;
  26742. } else if (/\:/.test(segment)) {
  26743. if (/\?/.test(segment)) {
  26744. if (results.length === 0 && basePath === "") {
  26745. results.push("/");
  26746. } else {
  26747. results.push(basePath);
  26748. }
  26749. const optionalSegment = segment.replace("?", "");
  26750. basePath += "/" + optionalSegment;
  26751. results.push(basePath);
  26752. } else {
  26753. basePath += "/" + segment;
  26754. }
  26755. }
  26756. });
  26757. return results.filter((v6, i6, a5) => a5.indexOf(v6) === i6);
  26758. };
  26759. _decodeURI = (value) => {
  26760. if (!/[%+]/.test(value)) {
  26761. return value;
  26762. }
  26763. if (value.indexOf("+") !== -1) {
  26764. value = value.replace(/\+/g, " ");
  26765. }
  26766. return value.indexOf("%") !== -1 ? decodeURIComponent_(value) : value;
  26767. };
  26768. _getQueryParam = (url, key, multiple) => {
  26769. let encoded;
  26770. if (!multiple && key && !/[%+]/.test(key)) {
  26771. let keyIndex2 = url.indexOf(`?${key}`, 8);
  26772. if (keyIndex2 === -1) {
  26773. keyIndex2 = url.indexOf(`&${key}`, 8);
  26774. }
  26775. while (keyIndex2 !== -1) {
  26776. const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
  26777. if (trailingKeyCode === 61) {
  26778. const valueIndex = keyIndex2 + key.length + 2;
  26779. const endIndex = url.indexOf("&", valueIndex);
  26780. return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
  26781. } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
  26782. return "";
  26783. }
  26784. keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
  26785. }
  26786. encoded = /[%+]/.test(url);
  26787. if (!encoded) {
  26788. return void 0;
  26789. }
  26790. }
  26791. const results = {};
  26792. encoded ??= /[%+]/.test(url);
  26793. let keyIndex = url.indexOf("?", 8);
  26794. while (keyIndex !== -1) {
  26795. const nextKeyIndex = url.indexOf("&", keyIndex + 1);
  26796. let valueIndex = url.indexOf("=", keyIndex);
  26797. if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
  26798. valueIndex = -1;
  26799. }
  26800. let name = url.slice(
  26801. keyIndex + 1,
  26802. valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
  26803. );
  26804. if (encoded) {
  26805. name = _decodeURI(name);
  26806. }
  26807. keyIndex = nextKeyIndex;
  26808. if (name === "") {
  26809. continue;
  26810. }
  26811. let value;
  26812. if (valueIndex === -1) {
  26813. value = "";
  26814. } else {
  26815. value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
  26816. if (encoded) {
  26817. value = _decodeURI(value);
  26818. }
  26819. }
  26820. if (multiple) {
  26821. if (!(results[name] && Array.isArray(results[name]))) {
  26822. results[name] = [];
  26823. }
  26824. ;
  26825. results[name].push(value);
  26826. } else {
  26827. results[name] ??= value;
  26828. }
  26829. }
  26830. return key ? results[key] : results;
  26831. };
  26832. getQueryParam = _getQueryParam;
  26833. getQueryParams = (url, key) => {
  26834. return _getQueryParam(url, key, true);
  26835. };
  26836. decodeURIComponent_ = decodeURIComponent;
  26837. }
  26838. });
  26839. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js
  26840. var validCookieNameRegEx, validCookieValueRegEx, parse2;
  26841. var init_cookie = __esm({
  26842. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js"() {
  26843. "use strict";
  26844. init_url();
  26845. validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
  26846. validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
  26847. parse2 = (cookie, name) => {
  26848. if (name && cookie.indexOf(name) === -1) {
  26849. return {};
  26850. }
  26851. const pairs = cookie.trim().split(";");
  26852. const parsedCookie = {};
  26853. for (let pairStr of pairs) {
  26854. pairStr = pairStr.trim();
  26855. const valueStartPos = pairStr.indexOf("=");
  26856. if (valueStartPos === -1) {
  26857. continue;
  26858. }
  26859. const cookieName = pairStr.substring(0, valueStartPos).trim();
  26860. if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) {
  26861. continue;
  26862. }
  26863. let cookieValue = pairStr.substring(valueStartPos + 1).trim();
  26864. if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
  26865. cookieValue = cookieValue.slice(1, -1);
  26866. }
  26867. if (validCookieValueRegEx.test(cookieValue)) {
  26868. parsedCookie[cookieName] = decodeURIComponent_(cookieValue);
  26869. if (name) {
  26870. break;
  26871. }
  26872. }
  26873. }
  26874. return parsedCookie;
  26875. };
  26876. }
  26877. });
  26878. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js
  26879. var getCookie;
  26880. var init_cookie2 = __esm({
  26881. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js"() {
  26882. "use strict";
  26883. init_cookie();
  26884. getCookie = (c5, key, prefix2) => {
  26885. const cookie = c5.req.raw.headers.get("Cookie");
  26886. if (typeof key === "string") {
  26887. if (!cookie) {
  26888. return void 0;
  26889. }
  26890. let finalKey = key;
  26891. if (prefix2 === "secure") {
  26892. finalKey = "__Secure-" + key;
  26893. } else if (prefix2 === "host") {
  26894. finalKey = "__Host-" + key;
  26895. }
  26896. const obj2 = parse2(cookie, finalKey);
  26897. return obj2[finalKey];
  26898. }
  26899. if (!cookie) {
  26900. return {};
  26901. }
  26902. const obj = parse2(cookie);
  26903. return obj;
  26904. };
  26905. }
  26906. });
  26907. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js
  26908. var HTTPException;
  26909. var init_http_exception = __esm({
  26910. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js"() {
  26911. "use strict";
  26912. HTTPException = class extends Error {
  26913. constructor(status = 500, options) {
  26914. super(options?.message, { cause: options?.cause });
  26915. __publicField(this, "res");
  26916. __publicField(this, "status");
  26917. this.res = options?.res;
  26918. this.status = status;
  26919. }
  26920. getResponse() {
  26921. if (this.res) {
  26922. const newResponse = new Response(this.res.body, {
  26923. status: this.status,
  26924. headers: this.res.headers
  26925. });
  26926. return newResponse;
  26927. }
  26928. return new Response(this.message, {
  26929. status: this.status
  26930. });
  26931. }
  26932. };
  26933. }
  26934. });
  26935. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js
  26936. var init_crypto = __esm({
  26937. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js"() {
  26938. "use strict";
  26939. }
  26940. });
  26941. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js
  26942. var bufferToFormData;
  26943. var init_buffer = __esm({
  26944. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js"() {
  26945. "use strict";
  26946. init_crypto();
  26947. bufferToFormData = (arrayBuffer, contentType) => {
  26948. const response = new Response(arrayBuffer, {
  26949. headers: {
  26950. "Content-Type": contentType
  26951. }
  26952. });
  26953. return response.formData();
  26954. };
  26955. }
  26956. });
  26957. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js
  26958. var jsonRegex, multipartRegex, urlencodedRegex, validator;
  26959. var init_validator = __esm({
  26960. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js"() {
  26961. "use strict";
  26962. init_cookie2();
  26963. init_http_exception();
  26964. init_buffer();
  26965. jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
  26966. multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/;
  26967. urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
  26968. validator = (target, validationFunc) => {
  26969. return async (c5, next) => {
  26970. let value = {};
  26971. const contentType = c5.req.header("Content-Type");
  26972. switch (target) {
  26973. case "json":
  26974. if (!contentType || !jsonRegex.test(contentType)) {
  26975. break;
  26976. }
  26977. try {
  26978. value = await c5.req.json();
  26979. } catch {
  26980. const message = "Malformed JSON in request body";
  26981. throw new HTTPException(400, { message });
  26982. }
  26983. break;
  26984. case "form": {
  26985. if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) {
  26986. break;
  26987. }
  26988. let formData;
  26989. if (c5.req.bodyCache.formData) {
  26990. formData = await c5.req.bodyCache.formData;
  26991. } else {
  26992. try {
  26993. const arrayBuffer = await c5.req.arrayBuffer();
  26994. formData = await bufferToFormData(arrayBuffer, contentType);
  26995. c5.req.bodyCache.formData = formData;
  26996. } catch (e6) {
  26997. let message = "Malformed FormData request.";
  26998. message += e6 instanceof Error ? ` ${e6.message}` : ` ${String(e6)}`;
  26999. throw new HTTPException(400, { message });
  27000. }
  27001. }
  27002. const form = {};
  27003. formData.forEach((value2, key) => {
  27004. if (key.endsWith("[]")) {
  27005. ;
  27006. (form[key] ??= []).push(value2);
  27007. } else if (Array.isArray(form[key])) {
  27008. ;
  27009. form[key].push(value2);
  27010. } else if (key in form) {
  27011. form[key] = [form[key], value2];
  27012. } else {
  27013. form[key] = value2;
  27014. }
  27015. });
  27016. value = form;
  27017. break;
  27018. }
  27019. case "query":
  27020. value = Object.fromEntries(
  27021. Object.entries(c5.req.queries()).map(([k5, v6]) => {
  27022. return v6.length === 1 ? [k5, v6[0]] : [k5, v6];
  27023. })
  27024. );
  27025. break;
  27026. case "param":
  27027. value = c5.req.param();
  27028. break;
  27029. case "header":
  27030. value = c5.req.header();
  27031. break;
  27032. case "cookie":
  27033. value = getCookie(c5);
  27034. break;
  27035. }
  27036. const res = await validationFunc(value, c5);
  27037. if (res instanceof Response) {
  27038. return res;
  27039. }
  27040. c5.req.addValidatedData(target, res);
  27041. await next();
  27042. };
  27043. };
  27044. }
  27045. });
  27046. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js
  27047. var init_validator2 = __esm({
  27048. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js"() {
  27049. "use strict";
  27050. init_validator();
  27051. }
  27052. });
  27053. // ../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js
  27054. var zValidator;
  27055. var init_esm2 = __esm({
  27056. "../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js"() {
  27057. "use strict";
  27058. init_validator2();
  27059. zValidator = (target, schema6, hook) => (
  27060. // @ts-expect-error not typed well
  27061. validator(target, async (value, c5) => {
  27062. const result = await schema6.safeParseAsync(value);
  27063. if (hook) {
  27064. const hookResult = await hook({ data: value, ...result }, c5);
  27065. if (hookResult) {
  27066. if (hookResult instanceof Response) {
  27067. return hookResult;
  27068. }
  27069. if ("response" in hookResult) {
  27070. return hookResult.response;
  27071. }
  27072. }
  27073. }
  27074. if (!result.success) {
  27075. return c5.json(result, 400);
  27076. }
  27077. return result.data;
  27078. })
  27079. );
  27080. }
  27081. });
  27082. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js
  27083. var compose;
  27084. var init_compose = __esm({
  27085. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js"() {
  27086. "use strict";
  27087. compose = (middleware, onError, onNotFound) => {
  27088. return (context, next) => {
  27089. let index6 = -1;
  27090. return dispatch(0);
  27091. async function dispatch(i6) {
  27092. if (i6 <= index6) {
  27093. throw new Error("next() called multiple times");
  27094. }
  27095. index6 = i6;
  27096. let res;
  27097. let isError = false;
  27098. let handler;
  27099. if (middleware[i6]) {
  27100. handler = middleware[i6][0][0];
  27101. context.req.routeIndex = i6;
  27102. } else {
  27103. handler = i6 === middleware.length && next || void 0;
  27104. }
  27105. if (handler) {
  27106. try {
  27107. res = await handler(context, () => dispatch(i6 + 1));
  27108. } catch (err2) {
  27109. if (err2 instanceof Error && onError) {
  27110. context.error = err2;
  27111. res = await onError(err2, context);
  27112. isError = true;
  27113. } else {
  27114. throw err2;
  27115. }
  27116. }
  27117. } else {
  27118. if (context.finalized === false && onNotFound) {
  27119. res = await onNotFound(context);
  27120. }
  27121. }
  27122. if (res && (context.finalized === false || isError)) {
  27123. context.res = res;
  27124. }
  27125. return context;
  27126. }
  27127. };
  27128. };
  27129. }
  27130. });
  27131. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js
  27132. async function parseFormData(request2, options) {
  27133. const formData = await request2.formData();
  27134. if (formData) {
  27135. return convertFormDataToBodyData(formData, options);
  27136. }
  27137. return {};
  27138. }
  27139. function convertFormDataToBodyData(formData, options) {
  27140. const form = /* @__PURE__ */ Object.create(null);
  27141. formData.forEach((value, key) => {
  27142. const shouldParseAllValues = options.all || key.endsWith("[]");
  27143. if (!shouldParseAllValues) {
  27144. form[key] = value;
  27145. } else {
  27146. handleParsingAllValues(form, key, value);
  27147. }
  27148. });
  27149. if (options.dot) {
  27150. Object.entries(form).forEach(([key, value]) => {
  27151. const shouldParseDotValues = key.includes(".");
  27152. if (shouldParseDotValues) {
  27153. handleParsingNestedValues(form, key, value);
  27154. delete form[key];
  27155. }
  27156. });
  27157. }
  27158. return form;
  27159. }
  27160. var parseBody, handleParsingAllValues, handleParsingNestedValues;
  27161. var init_body = __esm({
  27162. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js"() {
  27163. "use strict";
  27164. init_request();
  27165. parseBody = async (request2, options = /* @__PURE__ */ Object.create(null)) => {
  27166. const { all = false, dot = false } = options;
  27167. const headers = request2 instanceof HonoRequest ? request2.raw.headers : request2.headers;
  27168. const contentType = headers.get("Content-Type");
  27169. if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
  27170. return parseFormData(request2, { all, dot });
  27171. }
  27172. return {};
  27173. };
  27174. handleParsingAllValues = (form, key, value) => {
  27175. if (form[key] !== void 0) {
  27176. if (Array.isArray(form[key])) {
  27177. ;
  27178. form[key].push(value);
  27179. } else {
  27180. form[key] = [form[key], value];
  27181. }
  27182. } else {
  27183. form[key] = value;
  27184. }
  27185. };
  27186. handleParsingNestedValues = (form, key, value) => {
  27187. let nestedForm = form;
  27188. const keys = key.split(".");
  27189. keys.forEach((key2, index6) => {
  27190. if (index6 === keys.length - 1) {
  27191. nestedForm[key2] = value;
  27192. } else {
  27193. if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
  27194. nestedForm[key2] = /* @__PURE__ */ Object.create(null);
  27195. }
  27196. nestedForm = nestedForm[key2];
  27197. }
  27198. });
  27199. };
  27200. }
  27201. });
  27202. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js
  27203. var tryDecodeURIComponent, _validatedData, _matchResult, _HonoRequest_instances, getDecodedParam_fn, getAllDecodedParams_fn, getParamValue_fn, _cachedBody, _a2, HonoRequest;
  27204. var init_request = __esm({
  27205. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js"() {
  27206. "use strict";
  27207. init_body();
  27208. init_url();
  27209. tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
  27210. HonoRequest = (_a2 = class {
  27211. constructor(request2, path3 = "/", matchResult = [[]]) {
  27212. __privateAdd(this, _HonoRequest_instances);
  27213. __publicField(this, "raw");
  27214. __privateAdd(this, _validatedData);
  27215. __privateAdd(this, _matchResult);
  27216. __publicField(this, "routeIndex", 0);
  27217. __publicField(this, "path");
  27218. __publicField(this, "bodyCache", {});
  27219. __privateAdd(this, _cachedBody, (key) => {
  27220. const { bodyCache, raw: raw2 } = this;
  27221. const cachedBody = bodyCache[key];
  27222. if (cachedBody) {
  27223. return cachedBody;
  27224. }
  27225. const anyCachedKey = Object.keys(bodyCache)[0];
  27226. if (anyCachedKey) {
  27227. return bodyCache[anyCachedKey].then((body) => {
  27228. if (anyCachedKey === "json") {
  27229. body = JSON.stringify(body);
  27230. }
  27231. return new Response(body)[key]();
  27232. });
  27233. }
  27234. return bodyCache[key] = raw2[key]();
  27235. });
  27236. this.raw = request2;
  27237. this.path = path3;
  27238. __privateSet(this, _matchResult, matchResult);
  27239. __privateSet(this, _validatedData, {});
  27240. }
  27241. param(key) {
  27242. return key ? __privateMethod(this, _HonoRequest_instances, getDecodedParam_fn).call(this, key) : __privateMethod(this, _HonoRequest_instances, getAllDecodedParams_fn).call(this);
  27243. }
  27244. query(key) {
  27245. return getQueryParam(this.url, key);
  27246. }
  27247. queries(key) {
  27248. return getQueryParams(this.url, key);
  27249. }
  27250. header(name) {
  27251. if (name) {
  27252. return this.raw.headers.get(name) ?? void 0;
  27253. }
  27254. const headerData = {};
  27255. this.raw.headers.forEach((value, key) => {
  27256. headerData[key] = value;
  27257. });
  27258. return headerData;
  27259. }
  27260. async parseBody(options) {
  27261. return this.bodyCache.parsedBody ??= await parseBody(this, options);
  27262. }
  27263. json() {
  27264. return __privateGet(this, _cachedBody).call(this, "json");
  27265. }
  27266. text() {
  27267. return __privateGet(this, _cachedBody).call(this, "text");
  27268. }
  27269. arrayBuffer() {
  27270. return __privateGet(this, _cachedBody).call(this, "arrayBuffer");
  27271. }
  27272. blob() {
  27273. return __privateGet(this, _cachedBody).call(this, "blob");
  27274. }
  27275. formData() {
  27276. return __privateGet(this, _cachedBody).call(this, "formData");
  27277. }
  27278. addValidatedData(target, data) {
  27279. __privateGet(this, _validatedData)[target] = data;
  27280. }
  27281. valid(target) {
  27282. return __privateGet(this, _validatedData)[target];
  27283. }
  27284. get url() {
  27285. return this.raw.url;
  27286. }
  27287. get method() {
  27288. return this.raw.method;
  27289. }
  27290. get matchedRoutes() {
  27291. return __privateGet(this, _matchResult)[0].map(([[, route]]) => route);
  27292. }
  27293. get routePath() {
  27294. return __privateGet(this, _matchResult)[0].map(([[, route]]) => route)[this.routeIndex].path;
  27295. }
  27296. }, _validatedData = new WeakMap(), _matchResult = new WeakMap(), _HonoRequest_instances = new WeakSet(), getDecodedParam_fn = function(key) {
  27297. const paramKey = __privateGet(this, _matchResult)[0][this.routeIndex][1][key];
  27298. const param = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, paramKey);
  27299. return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : void 0;
  27300. }, getAllDecodedParams_fn = function() {
  27301. const decoded = {};
  27302. const keys = Object.keys(__privateGet(this, _matchResult)[0][this.routeIndex][1]);
  27303. for (const key of keys) {
  27304. const value = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, __privateGet(this, _matchResult)[0][this.routeIndex][1][key]);
  27305. if (value && typeof value === "string") {
  27306. decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
  27307. }
  27308. }
  27309. return decoded;
  27310. }, getParamValue_fn = function(paramKey) {
  27311. return __privateGet(this, _matchResult)[1] ? __privateGet(this, _matchResult)[1][paramKey] : paramKey;
  27312. }, _cachedBody = new WeakMap(), _a2);
  27313. }
  27314. });
  27315. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js
  27316. var HtmlEscapedCallbackPhase, raw, resolveCallback;
  27317. var init_html = __esm({
  27318. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js"() {
  27319. "use strict";
  27320. HtmlEscapedCallbackPhase = {
  27321. Stringify: 1,
  27322. BeforeStream: 2,
  27323. Stream: 3
  27324. };
  27325. raw = (value, callbacks) => {
  27326. const escapedString = new String(value);
  27327. escapedString.isEscaped = true;
  27328. escapedString.callbacks = callbacks;
  27329. return escapedString;
  27330. };
  27331. resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
  27332. if (typeof str === "object" && !(str instanceof String)) {
  27333. if (!(str instanceof Promise)) {
  27334. str = str.toString();
  27335. }
  27336. if (str instanceof Promise) {
  27337. str = await str;
  27338. }
  27339. }
  27340. const callbacks = str.callbacks;
  27341. if (!callbacks?.length) {
  27342. return Promise.resolve(str);
  27343. }
  27344. if (buffer) {
  27345. buffer[0] += str;
  27346. } else {
  27347. buffer = [str];
  27348. }
  27349. const resStr = Promise.all(callbacks.map((c5) => c5({ phase, buffer, context }))).then(
  27350. (res) => Promise.all(
  27351. res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
  27352. ).then(() => buffer[0])
  27353. );
  27354. if (preserveCallbacks) {
  27355. return raw(await resStr, callbacks);
  27356. } else {
  27357. return resStr;
  27358. }
  27359. };
  27360. }
  27361. });
  27362. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js
  27363. var TEXT_PLAIN, setHeaders, _rawRequest, _req, _var, _status, _executionCtx, _headers, _preparedHeaders, _res, _isFresh, _layout, _renderer, _notFoundHandler, _matchResult2, _path, _Context_instances, newResponse_fn, _a3, Context;
  27364. var init_context = __esm({
  27365. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js"() {
  27366. "use strict";
  27367. init_request();
  27368. init_html();
  27369. TEXT_PLAIN = "text/plain; charset=UTF-8";
  27370. setHeaders = (headers, map2 = {}) => {
  27371. for (const key of Object.keys(map2)) {
  27372. headers.set(key, map2[key]);
  27373. }
  27374. return headers;
  27375. };
  27376. Context = (_a3 = class {
  27377. constructor(req, options) {
  27378. __privateAdd(this, _Context_instances);
  27379. __privateAdd(this, _rawRequest);
  27380. __privateAdd(this, _req);
  27381. __publicField(this, "env", {});
  27382. __privateAdd(this, _var);
  27383. __publicField(this, "finalized", false);
  27384. __publicField(this, "error");
  27385. __privateAdd(this, _status, 200);
  27386. __privateAdd(this, _executionCtx);
  27387. __privateAdd(this, _headers);
  27388. __privateAdd(this, _preparedHeaders);
  27389. __privateAdd(this, _res);
  27390. __privateAdd(this, _isFresh, true);
  27391. __privateAdd(this, _layout);
  27392. __privateAdd(this, _renderer);
  27393. __privateAdd(this, _notFoundHandler);
  27394. __privateAdd(this, _matchResult2);
  27395. __privateAdd(this, _path);
  27396. __publicField(this, "render", (...args) => {
  27397. __privateGet(this, _renderer) ?? __privateSet(this, _renderer, (content) => this.html(content));
  27398. return __privateGet(this, _renderer).call(this, ...args);
  27399. });
  27400. __publicField(this, "setLayout", (layout) => __privateSet(this, _layout, layout));
  27401. __publicField(this, "getLayout", () => __privateGet(this, _layout));
  27402. __publicField(this, "setRenderer", (renderer) => {
  27403. __privateSet(this, _renderer, renderer);
  27404. });
  27405. __publicField(this, "header", (name, value, options) => {
  27406. if (this.finalized) {
  27407. __privateSet(this, _res, new Response(__privateGet(this, _res).body, __privateGet(this, _res)));
  27408. }
  27409. if (value === void 0) {
  27410. if (__privateGet(this, _headers)) {
  27411. __privateGet(this, _headers).delete(name);
  27412. } else if (__privateGet(this, _preparedHeaders)) {
  27413. delete __privateGet(this, _preparedHeaders)[name.toLocaleLowerCase()];
  27414. }
  27415. if (this.finalized) {
  27416. this.res.headers.delete(name);
  27417. }
  27418. return;
  27419. }
  27420. if (options?.append) {
  27421. if (!__privateGet(this, _headers)) {
  27422. __privateSet(this, _isFresh, false);
  27423. __privateSet(this, _headers, new Headers(__privateGet(this, _preparedHeaders)));
  27424. __privateSet(this, _preparedHeaders, {});
  27425. }
  27426. __privateGet(this, _headers).append(name, value);
  27427. } else {
  27428. if (__privateGet(this, _headers)) {
  27429. __privateGet(this, _headers).set(name, value);
  27430. } else {
  27431. __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {});
  27432. __privateGet(this, _preparedHeaders)[name.toLowerCase()] = value;
  27433. }
  27434. }
  27435. if (this.finalized) {
  27436. if (options?.append) {
  27437. this.res.headers.append(name, value);
  27438. } else {
  27439. this.res.headers.set(name, value);
  27440. }
  27441. }
  27442. });
  27443. __publicField(this, "status", (status) => {
  27444. __privateSet(this, _isFresh, false);
  27445. __privateSet(this, _status, status);
  27446. });
  27447. __publicField(this, "set", (key, value) => {
  27448. __privateGet(this, _var) ?? __privateSet(this, _var, /* @__PURE__ */ new Map());
  27449. __privateGet(this, _var).set(key, value);
  27450. });
  27451. __publicField(this, "get", (key) => {
  27452. return __privateGet(this, _var) ? __privateGet(this, _var).get(key) : void 0;
  27453. });
  27454. __publicField(this, "newResponse", (...args) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, ...args));
  27455. __publicField(this, "body", (data, arg, headers) => {
  27456. return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg);
  27457. });
  27458. __publicField(this, "text", (text, arg, headers) => {
  27459. if (!__privateGet(this, _preparedHeaders)) {
  27460. if (__privateGet(this, _isFresh) && !headers && !arg) {
  27461. return new Response(text);
  27462. }
  27463. __privateSet(this, _preparedHeaders, {});
  27464. }
  27465. __privateGet(this, _preparedHeaders)["content-type"] = TEXT_PLAIN;
  27466. if (typeof arg === "number") {
  27467. return __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg, headers);
  27468. }
  27469. return __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg);
  27470. });
  27471. __publicField(this, "json", (object, arg, headers) => {
  27472. const body = JSON.stringify(object);
  27473. __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {});
  27474. __privateGet(this, _preparedHeaders)["content-type"] = "application/json";
  27475. return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, body, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, body, arg);
  27476. });
  27477. __publicField(this, "html", (html, arg, headers) => {
  27478. __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {});
  27479. __privateGet(this, _preparedHeaders)["content-type"] = "text/html; charset=UTF-8";
  27480. if (typeof html === "object") {
  27481. return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => {
  27482. return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, html2, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, html2, arg);
  27483. });
  27484. }
  27485. return typeof arg === "number" ? __privateMethod(this, _Context_instances, newResponse_fn).call(this, html, arg, headers) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, html, arg);
  27486. });
  27487. __publicField(this, "redirect", (location, status) => {
  27488. __privateGet(this, _headers) ?? __privateSet(this, _headers, new Headers());
  27489. __privateGet(this, _headers).set("Location", String(location));
  27490. return this.newResponse(null, status ?? 302);
  27491. });
  27492. __publicField(this, "notFound", () => {
  27493. __privateGet(this, _notFoundHandler) ?? __privateSet(this, _notFoundHandler, () => new Response());
  27494. return __privateGet(this, _notFoundHandler).call(this, this);
  27495. });
  27496. __privateSet(this, _rawRequest, req);
  27497. if (options) {
  27498. __privateSet(this, _executionCtx, options.executionCtx);
  27499. this.env = options.env;
  27500. __privateSet(this, _notFoundHandler, options.notFoundHandler);
  27501. __privateSet(this, _path, options.path);
  27502. __privateSet(this, _matchResult2, options.matchResult);
  27503. }
  27504. }
  27505. get req() {
  27506. __privateGet(this, _req) ?? __privateSet(this, _req, new HonoRequest(__privateGet(this, _rawRequest), __privateGet(this, _path), __privateGet(this, _matchResult2)));
  27507. return __privateGet(this, _req);
  27508. }
  27509. get event() {
  27510. if (__privateGet(this, _executionCtx) && "respondWith" in __privateGet(this, _executionCtx)) {
  27511. return __privateGet(this, _executionCtx);
  27512. } else {
  27513. throw Error("This context has no FetchEvent");
  27514. }
  27515. }
  27516. get executionCtx() {
  27517. if (__privateGet(this, _executionCtx)) {
  27518. return __privateGet(this, _executionCtx);
  27519. } else {
  27520. throw Error("This context has no ExecutionContext");
  27521. }
  27522. }
  27523. get res() {
  27524. __privateSet(this, _isFresh, false);
  27525. return __privateGet(this, _res) || __privateSet(this, _res, new Response("404 Not Found", { status: 404 }));
  27526. }
  27527. set res(_res2) {
  27528. __privateSet(this, _isFresh, false);
  27529. if (__privateGet(this, _res) && _res2) {
  27530. _res2 = new Response(_res2.body, _res2);
  27531. for (const [k5, v6] of __privateGet(this, _res).headers.entries()) {
  27532. if (k5 === "content-type") {
  27533. continue;
  27534. }
  27535. if (k5 === "set-cookie") {
  27536. const cookies = __privateGet(this, _res).headers.getSetCookie();
  27537. _res2.headers.delete("set-cookie");
  27538. for (const cookie of cookies) {
  27539. _res2.headers.append("set-cookie", cookie);
  27540. }
  27541. } else {
  27542. _res2.headers.set(k5, v6);
  27543. }
  27544. }
  27545. }
  27546. __privateSet(this, _res, _res2);
  27547. this.finalized = true;
  27548. }
  27549. get var() {
  27550. if (!__privateGet(this, _var)) {
  27551. return {};
  27552. }
  27553. return Object.fromEntries(__privateGet(this, _var));
  27554. }
  27555. }, _rawRequest = new WeakMap(), _req = new WeakMap(), _var = new WeakMap(), _status = new WeakMap(), _executionCtx = new WeakMap(), _headers = new WeakMap(), _preparedHeaders = new WeakMap(), _res = new WeakMap(), _isFresh = new WeakMap(), _layout = new WeakMap(), _renderer = new WeakMap(), _notFoundHandler = new WeakMap(), _matchResult2 = new WeakMap(), _path = new WeakMap(), _Context_instances = new WeakSet(), newResponse_fn = function(data, arg, headers) {
  27556. if (__privateGet(this, _isFresh) && !headers && !arg && __privateGet(this, _status) === 200) {
  27557. return new Response(data, {
  27558. headers: __privateGet(this, _preparedHeaders)
  27559. });
  27560. }
  27561. if (arg && typeof arg !== "number") {
  27562. const header = new Headers(arg.headers);
  27563. if (__privateGet(this, _headers)) {
  27564. __privateGet(this, _headers).forEach((v6, k5) => {
  27565. if (k5 === "set-cookie") {
  27566. header.append(k5, v6);
  27567. } else {
  27568. header.set(k5, v6);
  27569. }
  27570. });
  27571. }
  27572. const headers2 = setHeaders(header, __privateGet(this, _preparedHeaders));
  27573. return new Response(data, {
  27574. headers: headers2,
  27575. status: arg.status ?? __privateGet(this, _status)
  27576. });
  27577. }
  27578. const status = typeof arg === "number" ? arg : __privateGet(this, _status);
  27579. __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, {});
  27580. __privateGet(this, _headers) ?? __privateSet(this, _headers, new Headers());
  27581. setHeaders(__privateGet(this, _headers), __privateGet(this, _preparedHeaders));
  27582. if (__privateGet(this, _res)) {
  27583. __privateGet(this, _res).headers.forEach((v6, k5) => {
  27584. if (k5 === "set-cookie") {
  27585. __privateGet(this, _headers)?.append(k5, v6);
  27586. } else {
  27587. __privateGet(this, _headers)?.set(k5, v6);
  27588. }
  27589. });
  27590. setHeaders(__privateGet(this, _headers), __privateGet(this, _preparedHeaders));
  27591. }
  27592. headers ??= {};
  27593. for (const [k5, v6] of Object.entries(headers)) {
  27594. if (typeof v6 === "string") {
  27595. __privateGet(this, _headers).set(k5, v6);
  27596. } else {
  27597. __privateGet(this, _headers).delete(k5);
  27598. for (const v22 of v6) {
  27599. __privateGet(this, _headers).append(k5, v22);
  27600. }
  27601. }
  27602. }
  27603. return new Response(data, {
  27604. status,
  27605. headers: __privateGet(this, _headers)
  27606. });
  27607. }, _a3);
  27608. }
  27609. });
  27610. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js
  27611. var METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS, MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError;
  27612. var init_router = __esm({
  27613. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js"() {
  27614. "use strict";
  27615. METHOD_NAME_ALL = "ALL";
  27616. METHOD_NAME_ALL_LOWERCASE = "all";
  27617. METHODS = ["get", "post", "put", "delete", "options", "patch"];
  27618. MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
  27619. UnsupportedPathError = class extends Error {
  27620. };
  27621. }
  27622. });
  27623. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js
  27624. var COMPOSED_HANDLER;
  27625. var init_constants = __esm({
  27626. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js"() {
  27627. "use strict";
  27628. COMPOSED_HANDLER = "__COMPOSED_HANDLER";
  27629. }
  27630. });
  27631. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js
  27632. var notFoundHandler, errorHandler, _path2, _Hono_instances, clone_fn, _notFoundHandler2, addRoute_fn, handleError_fn, dispatch_fn, _a4, Hono;
  27633. var init_hono_base = __esm({
  27634. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js"() {
  27635. "use strict";
  27636. init_compose();
  27637. init_context();
  27638. init_router();
  27639. init_constants();
  27640. init_url();
  27641. notFoundHandler = (c5) => {
  27642. return c5.text("404 Not Found", 404);
  27643. };
  27644. errorHandler = (err2, c5) => {
  27645. if ("getResponse" in err2) {
  27646. return err2.getResponse();
  27647. }
  27648. console.error(err2);
  27649. return c5.text("Internal Server Error", 500);
  27650. };
  27651. Hono = (_a4 = class {
  27652. constructor(options = {}) {
  27653. __privateAdd(this, _Hono_instances);
  27654. __publicField(this, "get");
  27655. __publicField(this, "post");
  27656. __publicField(this, "put");
  27657. __publicField(this, "delete");
  27658. __publicField(this, "options");
  27659. __publicField(this, "patch");
  27660. __publicField(this, "all");
  27661. __publicField(this, "on");
  27662. __publicField(this, "use");
  27663. __publicField(this, "router");
  27664. __publicField(this, "getPath");
  27665. __publicField(this, "_basePath", "/");
  27666. __privateAdd(this, _path2, "/");
  27667. __publicField(this, "routes", []);
  27668. __privateAdd(this, _notFoundHandler2, notFoundHandler);
  27669. __publicField(this, "errorHandler", errorHandler);
  27670. __publicField(this, "onError", (handler) => {
  27671. this.errorHandler = handler;
  27672. return this;
  27673. });
  27674. __publicField(this, "notFound", (handler) => {
  27675. __privateSet(this, _notFoundHandler2, handler);
  27676. return this;
  27677. });
  27678. __publicField(this, "fetch", (request2, ...rest) => {
  27679. return __privateMethod(this, _Hono_instances, dispatch_fn).call(this, request2, rest[1], rest[0], request2.method);
  27680. });
  27681. __publicField(this, "request", (input, requestInit, Env, executionCtx) => {
  27682. if (input instanceof Request) {
  27683. return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
  27684. }
  27685. input = input.toString();
  27686. return this.fetch(
  27687. new Request(
  27688. /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
  27689. requestInit
  27690. ),
  27691. Env,
  27692. executionCtx
  27693. );
  27694. });
  27695. __publicField(this, "fire", () => {
  27696. addEventListener("fetch", (event) => {
  27697. event.respondWith(__privateMethod(this, _Hono_instances, dispatch_fn).call(this, event.request, event, void 0, event.request.method));
  27698. });
  27699. });
  27700. const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
  27701. allMethods.forEach((method) => {
  27702. this[method] = (args1, ...args) => {
  27703. if (typeof args1 === "string") {
  27704. __privateSet(this, _path2, args1);
  27705. } else {
  27706. __privateMethod(this, _Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), args1);
  27707. }
  27708. args.forEach((handler) => {
  27709. __privateMethod(this, _Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), handler);
  27710. });
  27711. return this;
  27712. };
  27713. });
  27714. this.on = (method, path3, ...handlers) => {
  27715. for (const p5 of [path3].flat()) {
  27716. __privateSet(this, _path2, p5);
  27717. for (const m6 of [method].flat()) {
  27718. handlers.map((handler) => {
  27719. __privateMethod(this, _Hono_instances, addRoute_fn).call(this, m6.toUpperCase(), __privateGet(this, _path2), handler);
  27720. });
  27721. }
  27722. }
  27723. return this;
  27724. };
  27725. this.use = (arg1, ...handlers) => {
  27726. if (typeof arg1 === "string") {
  27727. __privateSet(this, _path2, arg1);
  27728. } else {
  27729. __privateSet(this, _path2, "*");
  27730. handlers.unshift(arg1);
  27731. }
  27732. handlers.forEach((handler) => {
  27733. __privateMethod(this, _Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, __privateGet(this, _path2), handler);
  27734. });
  27735. return this;
  27736. };
  27737. const { strict, ...optionsWithoutStrict } = options;
  27738. Object.assign(this, optionsWithoutStrict);
  27739. this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
  27740. }
  27741. route(path3, app) {
  27742. const subApp = this.basePath(path3);
  27743. app.routes.map((r6) => {
  27744. var _a15;
  27745. let handler;
  27746. if (app.errorHandler === errorHandler) {
  27747. handler = r6.handler;
  27748. } else {
  27749. handler = async (c5, next) => (await compose([], app.errorHandler)(c5, () => r6.handler(c5, next))).res;
  27750. handler[COMPOSED_HANDLER] = r6.handler;
  27751. }
  27752. __privateMethod(_a15 = subApp, _Hono_instances, addRoute_fn).call(_a15, r6.method, r6.path, handler);
  27753. });
  27754. return this;
  27755. }
  27756. basePath(path3) {
  27757. const subApp = __privateMethod(this, _Hono_instances, clone_fn).call(this);
  27758. subApp._basePath = mergePath(this._basePath, path3);
  27759. return subApp;
  27760. }
  27761. mount(path3, applicationHandler, options) {
  27762. let replaceRequest;
  27763. let optionHandler;
  27764. if (options) {
  27765. if (typeof options === "function") {
  27766. optionHandler = options;
  27767. } else {
  27768. optionHandler = options.optionHandler;
  27769. if (options.replaceRequest === false) {
  27770. replaceRequest = (request2) => request2;
  27771. } else {
  27772. replaceRequest = options.replaceRequest;
  27773. }
  27774. }
  27775. }
  27776. const getOptions = optionHandler ? (c5) => {
  27777. const options2 = optionHandler(c5);
  27778. return Array.isArray(options2) ? options2 : [options2];
  27779. } : (c5) => {
  27780. let executionContext = void 0;
  27781. try {
  27782. executionContext = c5.executionCtx;
  27783. } catch {
  27784. }
  27785. return [c5.env, executionContext];
  27786. };
  27787. replaceRequest ||= (() => {
  27788. const mergedPath = mergePath(this._basePath, path3);
  27789. const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
  27790. return (request2) => {
  27791. const url = new URL(request2.url);
  27792. url.pathname = url.pathname.slice(pathPrefixLength) || "/";
  27793. return new Request(url, request2);
  27794. };
  27795. })();
  27796. const handler = async (c5, next) => {
  27797. const res = await applicationHandler(replaceRequest(c5.req.raw), ...getOptions(c5));
  27798. if (res) {
  27799. return res;
  27800. }
  27801. await next();
  27802. };
  27803. __privateMethod(this, _Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, mergePath(path3, "*"), handler);
  27804. return this;
  27805. }
  27806. }, _path2 = new WeakMap(), _Hono_instances = new WeakSet(), clone_fn = function() {
  27807. const clone2 = new Hono({
  27808. router: this.router,
  27809. getPath: this.getPath
  27810. });
  27811. clone2.errorHandler = this.errorHandler;
  27812. __privateSet(clone2, _notFoundHandler2, __privateGet(this, _notFoundHandler2));
  27813. clone2.routes = this.routes;
  27814. return clone2;
  27815. }, _notFoundHandler2 = new WeakMap(), addRoute_fn = function(method, path3, handler) {
  27816. method = method.toUpperCase();
  27817. path3 = mergePath(this._basePath, path3);
  27818. const r6 = { path: path3, method, handler };
  27819. this.router.add(method, path3, [handler, r6]);
  27820. this.routes.push(r6);
  27821. }, handleError_fn = function(err2, c5) {
  27822. if (err2 instanceof Error) {
  27823. return this.errorHandler(err2, c5);
  27824. }
  27825. throw err2;
  27826. }, dispatch_fn = function(request2, executionCtx, env4, method) {
  27827. if (method === "HEAD") {
  27828. return (async () => new Response(null, await __privateMethod(this, _Hono_instances, dispatch_fn).call(this, request2, executionCtx, env4, "GET")))();
  27829. }
  27830. const path3 = this.getPath(request2, { env: env4 });
  27831. const matchResult = this.router.match(method, path3);
  27832. const c5 = new Context(request2, {
  27833. path: path3,
  27834. matchResult,
  27835. env: env4,
  27836. executionCtx,
  27837. notFoundHandler: __privateGet(this, _notFoundHandler2)
  27838. });
  27839. if (matchResult[0].length === 1) {
  27840. let res;
  27841. try {
  27842. res = matchResult[0][0][0][0](c5, async () => {
  27843. c5.res = await __privateGet(this, _notFoundHandler2).call(this, c5);
  27844. });
  27845. } catch (err2) {
  27846. return __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5);
  27847. }
  27848. return res instanceof Promise ? res.then(
  27849. (resolved) => resolved || (c5.finalized ? c5.res : __privateGet(this, _notFoundHandler2).call(this, c5))
  27850. ).catch((err2) => __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5)) : res ?? __privateGet(this, _notFoundHandler2).call(this, c5);
  27851. }
  27852. const composed = compose(matchResult[0], this.errorHandler, __privateGet(this, _notFoundHandler2));
  27853. return (async () => {
  27854. try {
  27855. const context = await composed(c5);
  27856. if (!context.finalized) {
  27857. throw new Error(
  27858. "Context is not finalized. Did you forget to return a Response object or `await next()`?"
  27859. );
  27860. }
  27861. return context.res;
  27862. } catch (err2) {
  27863. return __privateMethod(this, _Hono_instances, handleError_fn).call(this, err2, c5);
  27864. }
  27865. })();
  27866. }, _a4);
  27867. }
  27868. });
  27869. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js
  27870. function compareKey(a5, b5) {
  27871. if (a5.length === 1) {
  27872. return b5.length === 1 ? a5 < b5 ? -1 : 1 : -1;
  27873. }
  27874. if (b5.length === 1) {
  27875. return 1;
  27876. }
  27877. if (a5 === ONLY_WILDCARD_REG_EXP_STR || a5 === TAIL_WILDCARD_REG_EXP_STR) {
  27878. return 1;
  27879. } else if (b5 === ONLY_WILDCARD_REG_EXP_STR || b5 === TAIL_WILDCARD_REG_EXP_STR) {
  27880. return -1;
  27881. }
  27882. if (a5 === LABEL_REG_EXP_STR) {
  27883. return 1;
  27884. } else if (b5 === LABEL_REG_EXP_STR) {
  27885. return -1;
  27886. }
  27887. return a5.length === b5.length ? a5 < b5 ? -1 : 1 : b5.length - a5.length;
  27888. }
  27889. var LABEL_REG_EXP_STR, ONLY_WILDCARD_REG_EXP_STR, TAIL_WILDCARD_REG_EXP_STR, PATH_ERROR, regExpMetaChars, _index, _varIndex, _children, _a5, Node;
  27890. var init_node = __esm({
  27891. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js"() {
  27892. "use strict";
  27893. LABEL_REG_EXP_STR = "[^/]+";
  27894. ONLY_WILDCARD_REG_EXP_STR = ".*";
  27895. TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
  27896. PATH_ERROR = Symbol();
  27897. regExpMetaChars = new Set(".\\+*[^]$()");
  27898. Node = (_a5 = class {
  27899. constructor() {
  27900. __privateAdd(this, _index);
  27901. __privateAdd(this, _varIndex);
  27902. __privateAdd(this, _children, /* @__PURE__ */ Object.create(null));
  27903. }
  27904. insert(tokens, index6, paramMap, context, pathErrorCheckOnly) {
  27905. if (tokens.length === 0) {
  27906. if (__privateGet(this, _index) !== void 0) {
  27907. throw PATH_ERROR;
  27908. }
  27909. if (pathErrorCheckOnly) {
  27910. return;
  27911. }
  27912. __privateSet(this, _index, index6);
  27913. return;
  27914. }
  27915. const [token, ...restTokens] = tokens;
  27916. const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
  27917. let node;
  27918. if (pattern) {
  27919. const name = pattern[1];
  27920. let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
  27921. if (name && pattern[2]) {
  27922. regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
  27923. if (/\((?!\?:)/.test(regexpStr)) {
  27924. throw PATH_ERROR;
  27925. }
  27926. }
  27927. node = __privateGet(this, _children)[regexpStr];
  27928. if (!node) {
  27929. if (Object.keys(__privateGet(this, _children)).some(
  27930. (k5) => k5 !== ONLY_WILDCARD_REG_EXP_STR && k5 !== TAIL_WILDCARD_REG_EXP_STR
  27931. )) {
  27932. throw PATH_ERROR;
  27933. }
  27934. if (pathErrorCheckOnly) {
  27935. return;
  27936. }
  27937. node = __privateGet(this, _children)[regexpStr] = new Node();
  27938. if (name !== "") {
  27939. __privateSet(node, _varIndex, context.varIndex++);
  27940. }
  27941. }
  27942. if (!pathErrorCheckOnly && name !== "") {
  27943. paramMap.push([name, __privateGet(node, _varIndex)]);
  27944. }
  27945. } else {
  27946. node = __privateGet(this, _children)[token];
  27947. if (!node) {
  27948. if (Object.keys(__privateGet(this, _children)).some(
  27949. (k5) => k5.length > 1 && k5 !== ONLY_WILDCARD_REG_EXP_STR && k5 !== TAIL_WILDCARD_REG_EXP_STR
  27950. )) {
  27951. throw PATH_ERROR;
  27952. }
  27953. if (pathErrorCheckOnly) {
  27954. return;
  27955. }
  27956. node = __privateGet(this, _children)[token] = new Node();
  27957. }
  27958. }
  27959. node.insert(restTokens, index6, paramMap, context, pathErrorCheckOnly);
  27960. }
  27961. buildRegExpStr() {
  27962. const childKeys = Object.keys(__privateGet(this, _children)).sort(compareKey);
  27963. const strList = childKeys.map((k5) => {
  27964. const c5 = __privateGet(this, _children)[k5];
  27965. return (typeof __privateGet(c5, _varIndex) === "number" ? `(${k5})@${__privateGet(c5, _varIndex)}` : regExpMetaChars.has(k5) ? `\\${k5}` : k5) + c5.buildRegExpStr();
  27966. });
  27967. if (typeof __privateGet(this, _index) === "number") {
  27968. strList.unshift(`#${__privateGet(this, _index)}`);
  27969. }
  27970. if (strList.length === 0) {
  27971. return "";
  27972. }
  27973. if (strList.length === 1) {
  27974. return strList[0];
  27975. }
  27976. return "(?:" + strList.join("|") + ")";
  27977. }
  27978. }, _index = new WeakMap(), _varIndex = new WeakMap(), _children = new WeakMap(), _a5);
  27979. }
  27980. });
  27981. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js
  27982. var _context, _root, _a6, Trie;
  27983. var init_trie = __esm({
  27984. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js"() {
  27985. "use strict";
  27986. init_node();
  27987. Trie = (_a6 = class {
  27988. constructor() {
  27989. __privateAdd(this, _context, { varIndex: 0 });
  27990. __privateAdd(this, _root, new Node());
  27991. }
  27992. insert(path3, index6, pathErrorCheckOnly) {
  27993. const paramAssoc = [];
  27994. const groups = [];
  27995. for (let i6 = 0; ; ) {
  27996. let replaced = false;
  27997. path3 = path3.replace(/\{[^}]+\}/g, (m6) => {
  27998. const mark = `@\\${i6}`;
  27999. groups[i6] = [mark, m6];
  28000. i6++;
  28001. replaced = true;
  28002. return mark;
  28003. });
  28004. if (!replaced) {
  28005. break;
  28006. }
  28007. }
  28008. const tokens = path3.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
  28009. for (let i6 = groups.length - 1; i6 >= 0; i6--) {
  28010. const [mark] = groups[i6];
  28011. for (let j5 = tokens.length - 1; j5 >= 0; j5--) {
  28012. if (tokens[j5].indexOf(mark) !== -1) {
  28013. tokens[j5] = tokens[j5].replace(mark, groups[i6][1]);
  28014. break;
  28015. }
  28016. }
  28017. }
  28018. __privateGet(this, _root).insert(tokens, index6, paramAssoc, __privateGet(this, _context), pathErrorCheckOnly);
  28019. return paramAssoc;
  28020. }
  28021. buildRegExp() {
  28022. let regexp = __privateGet(this, _root).buildRegExpStr();
  28023. if (regexp === "") {
  28024. return [/^$/, [], []];
  28025. }
  28026. let captureIndex = 0;
  28027. const indexReplacementMap = [];
  28028. const paramReplacementMap = [];
  28029. regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_3, handlerIndex, paramIndex) => {
  28030. if (handlerIndex !== void 0) {
  28031. indexReplacementMap[++captureIndex] = Number(handlerIndex);
  28032. return "$()";
  28033. }
  28034. if (paramIndex !== void 0) {
  28035. paramReplacementMap[Number(paramIndex)] = ++captureIndex;
  28036. return "";
  28037. }
  28038. return "";
  28039. });
  28040. return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
  28041. }
  28042. }, _context = new WeakMap(), _root = new WeakMap(), _a6);
  28043. }
  28044. });
  28045. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js
  28046. function buildWildcardRegExp(path3) {
  28047. return wildcardRegExpCache[path3] ??= new RegExp(
  28048. path3 === "*" ? "" : `^${path3.replace(
  28049. /\/\*$|([.\\+*[^\]$()])/g,
  28050. (_3, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
  28051. )}$`
  28052. );
  28053. }
  28054. function clearWildcardRegExpCache() {
  28055. wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
  28056. }
  28057. function buildMatcherFromPreprocessedRoutes(routes) {
  28058. const trie = new Trie();
  28059. const handlerData = [];
  28060. if (routes.length === 0) {
  28061. return nullMatcher;
  28062. }
  28063. const routesWithStaticPathFlag = routes.map(
  28064. (route) => [!/\*|\/:/.test(route[0]), ...route]
  28065. ).sort(
  28066. ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
  28067. );
  28068. const staticMap = /* @__PURE__ */ Object.create(null);
  28069. for (let i6 = 0, j5 = -1, len = routesWithStaticPathFlag.length; i6 < len; i6++) {
  28070. const [pathErrorCheckOnly, path3, handlers] = routesWithStaticPathFlag[i6];
  28071. if (pathErrorCheckOnly) {
  28072. staticMap[path3] = [handlers.map(([h6]) => [h6, /* @__PURE__ */ Object.create(null)]), emptyParam];
  28073. } else {
  28074. j5++;
  28075. }
  28076. let paramAssoc;
  28077. try {
  28078. paramAssoc = trie.insert(path3, j5, pathErrorCheckOnly);
  28079. } catch (e6) {
  28080. throw e6 === PATH_ERROR ? new UnsupportedPathError(path3) : e6;
  28081. }
  28082. if (pathErrorCheckOnly) {
  28083. continue;
  28084. }
  28085. handlerData[j5] = handlers.map(([h6, paramCount]) => {
  28086. const paramIndexMap = /* @__PURE__ */ Object.create(null);
  28087. paramCount -= 1;
  28088. for (; paramCount >= 0; paramCount--) {
  28089. const [key, value] = paramAssoc[paramCount];
  28090. paramIndexMap[key] = value;
  28091. }
  28092. return [h6, paramIndexMap];
  28093. });
  28094. }
  28095. const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
  28096. for (let i6 = 0, len = handlerData.length; i6 < len; i6++) {
  28097. for (let j5 = 0, len2 = handlerData[i6].length; j5 < len2; j5++) {
  28098. const map2 = handlerData[i6][j5]?.[1];
  28099. if (!map2) {
  28100. continue;
  28101. }
  28102. const keys = Object.keys(map2);
  28103. for (let k5 = 0, len3 = keys.length; k5 < len3; k5++) {
  28104. map2[keys[k5]] = paramReplacementMap[map2[keys[k5]]];
  28105. }
  28106. }
  28107. }
  28108. const handlerMap = [];
  28109. for (const i6 in indexReplacementMap) {
  28110. handlerMap[i6] = handlerData[indexReplacementMap[i6]];
  28111. }
  28112. return [regexp, handlerMap, staticMap];
  28113. }
  28114. function findMiddleware(middleware, path3) {
  28115. if (!middleware) {
  28116. return void 0;
  28117. }
  28118. for (const k5 of Object.keys(middleware).sort((a5, b5) => b5.length - a5.length)) {
  28119. if (buildWildcardRegExp(k5).test(path3)) {
  28120. return [...middleware[k5]];
  28121. }
  28122. }
  28123. return void 0;
  28124. }
  28125. var emptyParam, nullMatcher, wildcardRegExpCache, _middleware, _routes, _RegExpRouter_instances, buildAllMatchers_fn, buildMatcher_fn, _a7, RegExpRouter;
  28126. var init_router2 = __esm({
  28127. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js"() {
  28128. "use strict";
  28129. init_router();
  28130. init_url();
  28131. init_node();
  28132. init_trie();
  28133. emptyParam = [];
  28134. nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
  28135. wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
  28136. RegExpRouter = (_a7 = class {
  28137. constructor() {
  28138. __privateAdd(this, _RegExpRouter_instances);
  28139. __publicField(this, "name", "RegExpRouter");
  28140. __privateAdd(this, _middleware);
  28141. __privateAdd(this, _routes);
  28142. __privateSet(this, _middleware, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) });
  28143. __privateSet(this, _routes, { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) });
  28144. }
  28145. add(method, path3, handler) {
  28146. const middleware = __privateGet(this, _middleware);
  28147. const routes = __privateGet(this, _routes);
  28148. if (!middleware || !routes) {
  28149. throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
  28150. }
  28151. if (!middleware[method]) {
  28152. ;
  28153. [middleware, routes].forEach((handlerMap) => {
  28154. handlerMap[method] = /* @__PURE__ */ Object.create(null);
  28155. Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p5) => {
  28156. handlerMap[method][p5] = [...handlerMap[METHOD_NAME_ALL][p5]];
  28157. });
  28158. });
  28159. }
  28160. if (path3 === "/*") {
  28161. path3 = "*";
  28162. }
  28163. const paramCount = (path3.match(/\/:/g) || []).length;
  28164. if (/\*$/.test(path3)) {
  28165. const re = buildWildcardRegExp(path3);
  28166. if (method === METHOD_NAME_ALL) {
  28167. Object.keys(middleware).forEach((m6) => {
  28168. middleware[m6][path3] ||= findMiddleware(middleware[m6], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || [];
  28169. });
  28170. } else {
  28171. middleware[method][path3] ||= findMiddleware(middleware[method], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || [];
  28172. }
  28173. Object.keys(middleware).forEach((m6) => {
  28174. if (method === METHOD_NAME_ALL || method === m6) {
  28175. Object.keys(middleware[m6]).forEach((p5) => {
  28176. re.test(p5) && middleware[m6][p5].push([handler, paramCount]);
  28177. });
  28178. }
  28179. });
  28180. Object.keys(routes).forEach((m6) => {
  28181. if (method === METHOD_NAME_ALL || method === m6) {
  28182. Object.keys(routes[m6]).forEach(
  28183. (p5) => re.test(p5) && routes[m6][p5].push([handler, paramCount])
  28184. );
  28185. }
  28186. });
  28187. return;
  28188. }
  28189. const paths = checkOptionalParameter(path3) || [path3];
  28190. for (let i6 = 0, len = paths.length; i6 < len; i6++) {
  28191. const path22 = paths[i6];
  28192. Object.keys(routes).forEach((m6) => {
  28193. if (method === METHOD_NAME_ALL || method === m6) {
  28194. routes[m6][path22] ||= [
  28195. ...findMiddleware(middleware[m6], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || []
  28196. ];
  28197. routes[m6][path22].push([handler, paramCount - len + i6 + 1]);
  28198. }
  28199. });
  28200. }
  28201. }
  28202. match(method, path3) {
  28203. clearWildcardRegExpCache();
  28204. const matchers = __privateMethod(this, _RegExpRouter_instances, buildAllMatchers_fn).call(this);
  28205. this.match = (method2, path22) => {
  28206. const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
  28207. const staticMatch = matcher[2][path22];
  28208. if (staticMatch) {
  28209. return staticMatch;
  28210. }
  28211. const match2 = path22.match(matcher[0]);
  28212. if (!match2) {
  28213. return [[], emptyParam];
  28214. }
  28215. const index6 = match2.indexOf("", 1);
  28216. return [matcher[1][index6], match2];
  28217. };
  28218. return this.match(method, path3);
  28219. }
  28220. }, _middleware = new WeakMap(), _routes = new WeakMap(), _RegExpRouter_instances = new WeakSet(), buildAllMatchers_fn = function() {
  28221. const matchers = /* @__PURE__ */ Object.create(null);
  28222. Object.keys(__privateGet(this, _routes)).concat(Object.keys(__privateGet(this, _middleware))).forEach((method) => {
  28223. matchers[method] ||= __privateMethod(this, _RegExpRouter_instances, buildMatcher_fn).call(this, method);
  28224. });
  28225. __privateSet(this, _middleware, __privateSet(this, _routes, void 0));
  28226. return matchers;
  28227. }, buildMatcher_fn = function(method) {
  28228. const routes = [];
  28229. let hasOwnRoute = method === METHOD_NAME_ALL;
  28230. [__privateGet(this, _middleware), __privateGet(this, _routes)].forEach((r6) => {
  28231. const ownRoute = r6[method] ? Object.keys(r6[method]).map((path3) => [path3, r6[method][path3]]) : [];
  28232. if (ownRoute.length !== 0) {
  28233. hasOwnRoute ||= true;
  28234. routes.push(...ownRoute);
  28235. } else if (method !== METHOD_NAME_ALL) {
  28236. routes.push(
  28237. ...Object.keys(r6[METHOD_NAME_ALL]).map((path3) => [path3, r6[METHOD_NAME_ALL][path3]])
  28238. );
  28239. }
  28240. });
  28241. if (!hasOwnRoute) {
  28242. return null;
  28243. } else {
  28244. return buildMatcherFromPreprocessedRoutes(routes);
  28245. }
  28246. }, _a7);
  28247. }
  28248. });
  28249. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js
  28250. var init_reg_exp_router = __esm({
  28251. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js"() {
  28252. "use strict";
  28253. init_router2();
  28254. }
  28255. });
  28256. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js
  28257. var _routers, _routes2, _a8, SmartRouter;
  28258. var init_router3 = __esm({
  28259. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js"() {
  28260. "use strict";
  28261. init_router();
  28262. SmartRouter = (_a8 = class {
  28263. constructor(init2) {
  28264. __publicField(this, "name", "SmartRouter");
  28265. __privateAdd(this, _routers, []);
  28266. __privateAdd(this, _routes2, []);
  28267. __privateSet(this, _routers, init2.routers);
  28268. }
  28269. add(method, path3, handler) {
  28270. if (!__privateGet(this, _routes2)) {
  28271. throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
  28272. }
  28273. __privateGet(this, _routes2).push([method, path3, handler]);
  28274. }
  28275. match(method, path3) {
  28276. if (!__privateGet(this, _routes2)) {
  28277. throw new Error("Fatal error");
  28278. }
  28279. const routers = __privateGet(this, _routers);
  28280. const routes = __privateGet(this, _routes2);
  28281. const len = routers.length;
  28282. let i6 = 0;
  28283. let res;
  28284. for (; i6 < len; i6++) {
  28285. const router = routers[i6];
  28286. try {
  28287. for (let i22 = 0, len2 = routes.length; i22 < len2; i22++) {
  28288. router.add(...routes[i22]);
  28289. }
  28290. res = router.match(method, path3);
  28291. } catch (e6) {
  28292. if (e6 instanceof UnsupportedPathError) {
  28293. continue;
  28294. }
  28295. throw e6;
  28296. }
  28297. this.match = router.match.bind(router);
  28298. __privateSet(this, _routers, [router]);
  28299. __privateSet(this, _routes2, void 0);
  28300. break;
  28301. }
  28302. if (i6 === len) {
  28303. throw new Error("Fatal error");
  28304. }
  28305. this.name = `SmartRouter + ${this.activeRouter.name}`;
  28306. return res;
  28307. }
  28308. get activeRouter() {
  28309. if (__privateGet(this, _routes2) || __privateGet(this, _routers).length !== 1) {
  28310. throw new Error("No active router has been determined yet.");
  28311. }
  28312. return __privateGet(this, _routers)[0];
  28313. }
  28314. }, _routers = new WeakMap(), _routes2 = new WeakMap(), _a8);
  28315. }
  28316. });
  28317. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js
  28318. var init_smart_router = __esm({
  28319. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js"() {
  28320. "use strict";
  28321. init_router3();
  28322. }
  28323. });
  28324. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js
  28325. var emptyParams, _methods, _children2, _patterns, _order, _params, _Node_instances, getHandlerSets_fn, _a9, Node2;
  28326. var init_node2 = __esm({
  28327. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js"() {
  28328. "use strict";
  28329. init_router();
  28330. init_url();
  28331. emptyParams = /* @__PURE__ */ Object.create(null);
  28332. Node2 = (_a9 = class {
  28333. constructor(method, handler, children) {
  28334. __privateAdd(this, _Node_instances);
  28335. __privateAdd(this, _methods);
  28336. __privateAdd(this, _children2);
  28337. __privateAdd(this, _patterns);
  28338. __privateAdd(this, _order, 0);
  28339. __privateAdd(this, _params, emptyParams);
  28340. __privateSet(this, _children2, children || /* @__PURE__ */ Object.create(null));
  28341. __privateSet(this, _methods, []);
  28342. if (method && handler) {
  28343. const m6 = /* @__PURE__ */ Object.create(null);
  28344. m6[method] = { handler, possibleKeys: [], score: 0 };
  28345. __privateSet(this, _methods, [m6]);
  28346. }
  28347. __privateSet(this, _patterns, []);
  28348. }
  28349. insert(method, path3, handler) {
  28350. __privateSet(this, _order, ++__privateWrapper(this, _order)._);
  28351. let curNode = this;
  28352. const parts = splitRoutingPath(path3);
  28353. const possibleKeys = [];
  28354. for (let i6 = 0, len = parts.length; i6 < len; i6++) {
  28355. const p5 = parts[i6];
  28356. const nextP = parts[i6 + 1];
  28357. const pattern = getPattern(p5, nextP);
  28358. const key = Array.isArray(pattern) ? pattern[0] : p5;
  28359. if (Object.keys(__privateGet(curNode, _children2)).includes(key)) {
  28360. curNode = __privateGet(curNode, _children2)[key];
  28361. const pattern2 = getPattern(p5, nextP);
  28362. if (pattern2) {
  28363. possibleKeys.push(pattern2[1]);
  28364. }
  28365. continue;
  28366. }
  28367. __privateGet(curNode, _children2)[key] = new Node2();
  28368. if (pattern) {
  28369. __privateGet(curNode, _patterns).push(pattern);
  28370. possibleKeys.push(pattern[1]);
  28371. }
  28372. curNode = __privateGet(curNode, _children2)[key];
  28373. }
  28374. const m6 = /* @__PURE__ */ Object.create(null);
  28375. const handlerSet = {
  28376. handler,
  28377. possibleKeys: possibleKeys.filter((v6, i6, a5) => a5.indexOf(v6) === i6),
  28378. score: __privateGet(this, _order)
  28379. };
  28380. m6[method] = handlerSet;
  28381. __privateGet(curNode, _methods).push(m6);
  28382. return curNode;
  28383. }
  28384. search(method, path3) {
  28385. const handlerSets = [];
  28386. __privateSet(this, _params, emptyParams);
  28387. const curNode = this;
  28388. let curNodes = [curNode];
  28389. const parts = splitPath(path3);
  28390. const curNodesQueue = [];
  28391. for (let i6 = 0, len = parts.length; i6 < len; i6++) {
  28392. const part = parts[i6];
  28393. const isLast = i6 === len - 1;
  28394. const tempNodes = [];
  28395. for (let j5 = 0, len2 = curNodes.length; j5 < len2; j5++) {
  28396. const node = curNodes[j5];
  28397. const nextNode = __privateGet(node, _children2)[part];
  28398. if (nextNode) {
  28399. __privateSet(nextNode, _params, __privateGet(node, _params));
  28400. if (isLast) {
  28401. if (__privateGet(nextNode, _children2)["*"]) {
  28402. handlerSets.push(
  28403. ...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, __privateGet(nextNode, _children2)["*"], method, __privateGet(node, _params))
  28404. );
  28405. }
  28406. handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, nextNode, method, __privateGet(node, _params)));
  28407. } else {
  28408. tempNodes.push(nextNode);
  28409. }
  28410. }
  28411. for (let k5 = 0, len3 = __privateGet(node, _patterns).length; k5 < len3; k5++) {
  28412. const pattern = __privateGet(node, _patterns)[k5];
  28413. const params = __privateGet(node, _params) === emptyParams ? {} : { ...__privateGet(node, _params) };
  28414. if (pattern === "*") {
  28415. const astNode = __privateGet(node, _children2)["*"];
  28416. if (astNode) {
  28417. handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, astNode, method, __privateGet(node, _params)));
  28418. __privateSet(astNode, _params, params);
  28419. tempNodes.push(astNode);
  28420. }
  28421. continue;
  28422. }
  28423. if (part === "") {
  28424. continue;
  28425. }
  28426. const [key, name, matcher] = pattern;
  28427. const child = __privateGet(node, _children2)[key];
  28428. const restPathString = parts.slice(i6).join("/");
  28429. if (matcher instanceof RegExp) {
  28430. const m6 = matcher.exec(restPathString);
  28431. if (m6) {
  28432. params[name] = m6[0];
  28433. handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, child, method, __privateGet(node, _params), params));
  28434. if (Object.keys(__privateGet(child, _children2)).length) {
  28435. __privateSet(child, _params, params);
  28436. const componentCount = m6[0].match(/\//)?.length ?? 0;
  28437. const targetCurNodes = curNodesQueue[componentCount] ||= [];
  28438. targetCurNodes.push(child);
  28439. }
  28440. continue;
  28441. }
  28442. }
  28443. if (matcher === true || matcher.test(part)) {
  28444. params[name] = part;
  28445. if (isLast) {
  28446. handlerSets.push(...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, child, method, params, __privateGet(node, _params)));
  28447. if (__privateGet(child, _children2)["*"]) {
  28448. handlerSets.push(
  28449. ...__privateMethod(this, _Node_instances, getHandlerSets_fn).call(this, __privateGet(child, _children2)["*"], method, params, __privateGet(node, _params))
  28450. );
  28451. }
  28452. } else {
  28453. __privateSet(child, _params, params);
  28454. tempNodes.push(child);
  28455. }
  28456. }
  28457. }
  28458. }
  28459. curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
  28460. }
  28461. if (handlerSets.length > 1) {
  28462. handlerSets.sort((a5, b5) => {
  28463. return a5.score - b5.score;
  28464. });
  28465. }
  28466. return [handlerSets.map(({ handler, params }) => [handler, params])];
  28467. }
  28468. }, _methods = new WeakMap(), _children2 = new WeakMap(), _patterns = new WeakMap(), _order = new WeakMap(), _params = new WeakMap(), _Node_instances = new WeakSet(), getHandlerSets_fn = function(node, method, nodeParams, params) {
  28469. const handlerSets = [];
  28470. for (let i6 = 0, len = __privateGet(node, _methods).length; i6 < len; i6++) {
  28471. const m6 = __privateGet(node, _methods)[i6];
  28472. const handlerSet = m6[method] || m6[METHOD_NAME_ALL];
  28473. const processedSet = {};
  28474. if (handlerSet !== void 0) {
  28475. handlerSet.params = /* @__PURE__ */ Object.create(null);
  28476. handlerSets.push(handlerSet);
  28477. if (nodeParams !== emptyParams || params && params !== emptyParams) {
  28478. for (let i22 = 0, len2 = handlerSet.possibleKeys.length; i22 < len2; i22++) {
  28479. const key = handlerSet.possibleKeys[i22];
  28480. const processed = processedSet[handlerSet.score];
  28481. handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
  28482. processedSet[handlerSet.score] = true;
  28483. }
  28484. }
  28485. }
  28486. }
  28487. return handlerSets;
  28488. }, _a9);
  28489. }
  28490. });
  28491. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js
  28492. var _node, _a10, TrieRouter;
  28493. var init_router4 = __esm({
  28494. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js"() {
  28495. "use strict";
  28496. init_url();
  28497. init_node2();
  28498. TrieRouter = (_a10 = class {
  28499. constructor() {
  28500. __publicField(this, "name", "TrieRouter");
  28501. __privateAdd(this, _node);
  28502. __privateSet(this, _node, new Node2());
  28503. }
  28504. add(method, path3, handler) {
  28505. const results = checkOptionalParameter(path3);
  28506. if (results) {
  28507. for (let i6 = 0, len = results.length; i6 < len; i6++) {
  28508. __privateGet(this, _node).insert(method, results[i6], handler);
  28509. }
  28510. return;
  28511. }
  28512. __privateGet(this, _node).insert(method, path3, handler);
  28513. }
  28514. match(method, path3) {
  28515. return __privateGet(this, _node).search(method, path3);
  28516. }
  28517. }, _node = new WeakMap(), _a10);
  28518. }
  28519. });
  28520. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js
  28521. var init_trie_router = __esm({
  28522. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js"() {
  28523. "use strict";
  28524. init_router4();
  28525. }
  28526. });
  28527. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js
  28528. var Hono2;
  28529. var init_hono = __esm({
  28530. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js"() {
  28531. "use strict";
  28532. init_hono_base();
  28533. init_reg_exp_router();
  28534. init_smart_router();
  28535. init_trie_router();
  28536. Hono2 = class extends Hono {
  28537. constructor(options = {}) {
  28538. super(options);
  28539. this.router = options.router ?? new SmartRouter({
  28540. routers: [new RegExpRouter(), new TrieRouter()]
  28541. });
  28542. }
  28543. };
  28544. }
  28545. });
  28546. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js
  28547. var init_dist2 = __esm({
  28548. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js"() {
  28549. "use strict";
  28550. init_hono();
  28551. }
  28552. });
  28553. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js
  28554. var COMPRESSIBLE_CONTENT_TYPE_REGEX;
  28555. var init_compress = __esm({
  28556. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js"() {
  28557. "use strict";
  28558. COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
  28559. }
  28560. });
  28561. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js
  28562. var ENCODING_TYPES, cacheControlNoTransformRegExp, compress, shouldCompress, shouldTransform;
  28563. var init_compress2 = __esm({
  28564. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js"() {
  28565. "use strict";
  28566. init_compress();
  28567. ENCODING_TYPES = ["gzip", "deflate"];
  28568. cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i;
  28569. compress = (options) => {
  28570. const threshold = options?.threshold ?? 1024;
  28571. return async function compress2(ctx, next) {
  28572. await next();
  28573. const contentLength = ctx.res.headers.get("Content-Length");
  28574. if (ctx.res.headers.has("Content-Encoding") || ctx.res.headers.has("Transfer-Encoding") || ctx.req.method === "HEAD" || contentLength && Number(contentLength) < threshold || !shouldCompress(ctx.res) || !shouldTransform(ctx.res)) {
  28575. return;
  28576. }
  28577. const accepted = ctx.req.header("Accept-Encoding");
  28578. const encoding = options?.encoding ?? ENCODING_TYPES.find((encoding2) => accepted?.includes(encoding2));
  28579. if (!encoding || !ctx.res.body) {
  28580. return;
  28581. }
  28582. const stream = new CompressionStream(encoding);
  28583. ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res);
  28584. ctx.res.headers.delete("Content-Length");
  28585. ctx.res.headers.set("Content-Encoding", encoding);
  28586. };
  28587. };
  28588. shouldCompress = (res) => {
  28589. const type = res.headers.get("Content-Type");
  28590. return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type);
  28591. };
  28592. shouldTransform = (res) => {
  28593. const cacheControl = res.headers.get("Cache-Control");
  28594. return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl);
  28595. };
  28596. }
  28597. });
  28598. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js
  28599. var cors;
  28600. var init_cors = __esm({
  28601. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js"() {
  28602. "use strict";
  28603. cors = (options) => {
  28604. const defaults2 = {
  28605. origin: "*",
  28606. allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
  28607. allowHeaders: [],
  28608. exposeHeaders: []
  28609. };
  28610. const opts = {
  28611. ...defaults2,
  28612. ...options
  28613. };
  28614. const findAllowOrigin = ((optsOrigin) => {
  28615. if (typeof optsOrigin === "string") {
  28616. if (optsOrigin === "*") {
  28617. return () => optsOrigin;
  28618. } else {
  28619. return (origin) => optsOrigin === origin ? origin : null;
  28620. }
  28621. } else if (typeof optsOrigin === "function") {
  28622. return optsOrigin;
  28623. } else {
  28624. return (origin) => optsOrigin.includes(origin) ? origin : null;
  28625. }
  28626. })(opts.origin);
  28627. return async function cors2(c5, next) {
  28628. function set(key, value) {
  28629. c5.res.headers.set(key, value);
  28630. }
  28631. const allowOrigin = findAllowOrigin(c5.req.header("origin") || "", c5);
  28632. if (allowOrigin) {
  28633. set("Access-Control-Allow-Origin", allowOrigin);
  28634. }
  28635. if (opts.origin !== "*") {
  28636. const existingVary = c5.req.header("Vary");
  28637. if (existingVary) {
  28638. set("Vary", existingVary);
  28639. } else {
  28640. set("Vary", "Origin");
  28641. }
  28642. }
  28643. if (opts.credentials) {
  28644. set("Access-Control-Allow-Credentials", "true");
  28645. }
  28646. if (opts.exposeHeaders?.length) {
  28647. set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
  28648. }
  28649. if (c5.req.method === "OPTIONS") {
  28650. if (opts.maxAge != null) {
  28651. set("Access-Control-Max-Age", opts.maxAge.toString());
  28652. }
  28653. if (opts.allowMethods?.length) {
  28654. set("Access-Control-Allow-Methods", opts.allowMethods.join(","));
  28655. }
  28656. let headers = opts.allowHeaders;
  28657. if (!headers?.length) {
  28658. const requestHeaders = c5.req.header("Access-Control-Request-Headers");
  28659. if (requestHeaders) {
  28660. headers = requestHeaders.split(/\s*,\s*/);
  28661. }
  28662. }
  28663. if (headers?.length) {
  28664. set("Access-Control-Allow-Headers", headers.join(","));
  28665. c5.res.headers.append("Vary", "Access-Control-Request-Headers");
  28666. }
  28667. c5.res.headers.delete("Content-Length");
  28668. c5.res.headers.delete("Content-Type");
  28669. return new Response(null, {
  28670. headers: c5.res.headers,
  28671. status: 204,
  28672. statusText: "No Content"
  28673. });
  28674. }
  28675. await next();
  28676. };
  28677. };
  28678. }
  28679. });
  28680. // ../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js
  28681. function dataUriToBuffer(uri) {
  28682. if (!/^data:/i.test(uri)) {
  28683. throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
  28684. }
  28685. uri = uri.replace(/\r?\n/g, "");
  28686. const firstComma = uri.indexOf(",");
  28687. if (firstComma === -1 || firstComma <= 4) {
  28688. throw new TypeError("malformed data: URI");
  28689. }
  28690. const meta = uri.substring(5, firstComma).split(";");
  28691. let charset = "";
  28692. let base64 = false;
  28693. const type = meta[0] || "text/plain";
  28694. let typeFull = type;
  28695. for (let i6 = 1; i6 < meta.length; i6++) {
  28696. if (meta[i6] === "base64") {
  28697. base64 = true;
  28698. } else if (meta[i6]) {
  28699. typeFull += `;${meta[i6]}`;
  28700. if (meta[i6].indexOf("charset=") === 0) {
  28701. charset = meta[i6].substring(8);
  28702. }
  28703. }
  28704. }
  28705. if (!meta[0] && !charset.length) {
  28706. typeFull += ";charset=US-ASCII";
  28707. charset = "US-ASCII";
  28708. }
  28709. const encoding = base64 ? "base64" : "ascii";
  28710. const data = unescape(uri.substring(firstComma + 1));
  28711. const buffer = Buffer.from(data, encoding);
  28712. buffer.type = type;
  28713. buffer.typeFull = typeFull;
  28714. buffer.charset = charset;
  28715. return buffer;
  28716. }
  28717. var dist_default;
  28718. var init_dist3 = __esm({
  28719. "../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js"() {
  28720. "use strict";
  28721. dist_default = dataUriToBuffer;
  28722. }
  28723. });
  28724. // ../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js
  28725. var require_ponyfill_es2018 = __commonJS({
  28726. "../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports, module) {
  28727. "use strict";
  28728. (function(global2, factory) {
  28729. typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {}));
  28730. })(exports, function(exports2) {
  28731. "use strict";
  28732. function noop2() {
  28733. return void 0;
  28734. }
  28735. function typeIsObject(x5) {
  28736. return typeof x5 === "object" && x5 !== null || typeof x5 === "function";
  28737. }
  28738. const rethrowAssertionErrorRejection = noop2;
  28739. function setFunctionName(fn, name) {
  28740. try {
  28741. Object.defineProperty(fn, "name", {
  28742. value: name,
  28743. configurable: true
  28744. });
  28745. } catch (_a16) {
  28746. }
  28747. }
  28748. const originalPromise = Promise;
  28749. const originalPromiseThen = Promise.prototype.then;
  28750. const originalPromiseReject = Promise.reject.bind(originalPromise);
  28751. function newPromise(executor) {
  28752. return new originalPromise(executor);
  28753. }
  28754. function promiseResolvedWith(value) {
  28755. return newPromise((resolve) => resolve(value));
  28756. }
  28757. function promiseRejectedWith(reason) {
  28758. return originalPromiseReject(reason);
  28759. }
  28760. function PerformPromiseThen(promise, onFulfilled, onRejected) {
  28761. return originalPromiseThen.call(promise, onFulfilled, onRejected);
  28762. }
  28763. function uponPromise(promise, onFulfilled, onRejected) {
  28764. PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection);
  28765. }
  28766. function uponFulfillment(promise, onFulfilled) {
  28767. uponPromise(promise, onFulfilled);
  28768. }
  28769. function uponRejection(promise, onRejected) {
  28770. uponPromise(promise, void 0, onRejected);
  28771. }
  28772. function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
  28773. return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
  28774. }
  28775. function setPromiseIsHandledToTrue(promise) {
  28776. PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection);
  28777. }
  28778. let _queueMicrotask = (callback) => {
  28779. if (typeof queueMicrotask === "function") {
  28780. _queueMicrotask = queueMicrotask;
  28781. } else {
  28782. const resolvedPromise = promiseResolvedWith(void 0);
  28783. _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb);
  28784. }
  28785. return _queueMicrotask(callback);
  28786. };
  28787. function reflectCall(F3, V, args) {
  28788. if (typeof F3 !== "function") {
  28789. throw new TypeError("Argument is not a function");
  28790. }
  28791. return Function.prototype.apply.call(F3, V, args);
  28792. }
  28793. function promiseCall(F3, V, args) {
  28794. try {
  28795. return promiseResolvedWith(reflectCall(F3, V, args));
  28796. } catch (value) {
  28797. return promiseRejectedWith(value);
  28798. }
  28799. }
  28800. const QUEUE_MAX_ARRAY_SIZE = 16384;
  28801. class SimpleQueue {
  28802. constructor() {
  28803. this._cursor = 0;
  28804. this._size = 0;
  28805. this._front = {
  28806. _elements: [],
  28807. _next: void 0
  28808. };
  28809. this._back = this._front;
  28810. this._cursor = 0;
  28811. this._size = 0;
  28812. }
  28813. get length() {
  28814. return this._size;
  28815. }
  28816. // For exception safety, this method is structured in order:
  28817. // 1. Read state
  28818. // 2. Calculate required state mutations
  28819. // 3. Perform state mutations
  28820. push(element) {
  28821. const oldBack = this._back;
  28822. let newBack = oldBack;
  28823. if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
  28824. newBack = {
  28825. _elements: [],
  28826. _next: void 0
  28827. };
  28828. }
  28829. oldBack._elements.push(element);
  28830. if (newBack !== oldBack) {
  28831. this._back = newBack;
  28832. oldBack._next = newBack;
  28833. }
  28834. ++this._size;
  28835. }
  28836. // Like push(), shift() follows the read -> calculate -> mutate pattern for
  28837. // exception safety.
  28838. shift() {
  28839. const oldFront = this._front;
  28840. let newFront = oldFront;
  28841. const oldCursor = this._cursor;
  28842. let newCursor = oldCursor + 1;
  28843. const elements = oldFront._elements;
  28844. const element = elements[oldCursor];
  28845. if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
  28846. newFront = oldFront._next;
  28847. newCursor = 0;
  28848. }
  28849. --this._size;
  28850. this._cursor = newCursor;
  28851. if (oldFront !== newFront) {
  28852. this._front = newFront;
  28853. }
  28854. elements[oldCursor] = void 0;
  28855. return element;
  28856. }
  28857. // The tricky thing about forEach() is that it can be called
  28858. // re-entrantly. The queue may be mutated inside the callback. It is easy to
  28859. // see that push() within the callback has no negative effects since the end
  28860. // of the queue is checked for on every iteration. If shift() is called
  28861. // repeatedly within the callback then the next iteration may return an
  28862. // element that has been removed. In this case the callback will be called
  28863. // with undefined values until we either "catch up" with elements that still
  28864. // exist or reach the back of the queue.
  28865. forEach(callback) {
  28866. let i6 = this._cursor;
  28867. let node = this._front;
  28868. let elements = node._elements;
  28869. while (i6 !== elements.length || node._next !== void 0) {
  28870. if (i6 === elements.length) {
  28871. node = node._next;
  28872. elements = node._elements;
  28873. i6 = 0;
  28874. if (elements.length === 0) {
  28875. break;
  28876. }
  28877. }
  28878. callback(elements[i6]);
  28879. ++i6;
  28880. }
  28881. }
  28882. // Return the element that would be returned if shift() was called now,
  28883. // without modifying the queue.
  28884. peek() {
  28885. const front = this._front;
  28886. const cursor = this._cursor;
  28887. return front._elements[cursor];
  28888. }
  28889. }
  28890. const AbortSteps = Symbol("[[AbortSteps]]");
  28891. const ErrorSteps = Symbol("[[ErrorSteps]]");
  28892. const CancelSteps = Symbol("[[CancelSteps]]");
  28893. const PullSteps = Symbol("[[PullSteps]]");
  28894. const ReleaseSteps = Symbol("[[ReleaseSteps]]");
  28895. function ReadableStreamReaderGenericInitialize(reader, stream) {
  28896. reader._ownerReadableStream = stream;
  28897. stream._reader = reader;
  28898. if (stream._state === "readable") {
  28899. defaultReaderClosedPromiseInitialize(reader);
  28900. } else if (stream._state === "closed") {
  28901. defaultReaderClosedPromiseInitializeAsResolved(reader);
  28902. } else {
  28903. defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
  28904. }
  28905. }
  28906. function ReadableStreamReaderGenericCancel(reader, reason) {
  28907. const stream = reader._ownerReadableStream;
  28908. return ReadableStreamCancel(stream, reason);
  28909. }
  28910. function ReadableStreamReaderGenericRelease(reader) {
  28911. const stream = reader._ownerReadableStream;
  28912. if (stream._state === "readable") {
  28913. defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
  28914. } else {
  28915. defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
  28916. }
  28917. stream._readableStreamController[ReleaseSteps]();
  28918. stream._reader = void 0;
  28919. reader._ownerReadableStream = void 0;
  28920. }
  28921. function readerLockException(name) {
  28922. return new TypeError("Cannot " + name + " a stream using a released reader");
  28923. }
  28924. function defaultReaderClosedPromiseInitialize(reader) {
  28925. reader._closedPromise = newPromise((resolve, reject) => {
  28926. reader._closedPromise_resolve = resolve;
  28927. reader._closedPromise_reject = reject;
  28928. });
  28929. }
  28930. function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
  28931. defaultReaderClosedPromiseInitialize(reader);
  28932. defaultReaderClosedPromiseReject(reader, reason);
  28933. }
  28934. function defaultReaderClosedPromiseInitializeAsResolved(reader) {
  28935. defaultReaderClosedPromiseInitialize(reader);
  28936. defaultReaderClosedPromiseResolve(reader);
  28937. }
  28938. function defaultReaderClosedPromiseReject(reader, reason) {
  28939. if (reader._closedPromise_reject === void 0) {
  28940. return;
  28941. }
  28942. setPromiseIsHandledToTrue(reader._closedPromise);
  28943. reader._closedPromise_reject(reason);
  28944. reader._closedPromise_resolve = void 0;
  28945. reader._closedPromise_reject = void 0;
  28946. }
  28947. function defaultReaderClosedPromiseResetToRejected(reader, reason) {
  28948. defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
  28949. }
  28950. function defaultReaderClosedPromiseResolve(reader) {
  28951. if (reader._closedPromise_resolve === void 0) {
  28952. return;
  28953. }
  28954. reader._closedPromise_resolve(void 0);
  28955. reader._closedPromise_resolve = void 0;
  28956. reader._closedPromise_reject = void 0;
  28957. }
  28958. const NumberIsFinite = Number.isFinite || function(x5) {
  28959. return typeof x5 === "number" && isFinite(x5);
  28960. };
  28961. const MathTrunc = Math.trunc || function(v6) {
  28962. return v6 < 0 ? Math.ceil(v6) : Math.floor(v6);
  28963. };
  28964. function isDictionary(x5) {
  28965. return typeof x5 === "object" || typeof x5 === "function";
  28966. }
  28967. function assertDictionary(obj, context) {
  28968. if (obj !== void 0 && !isDictionary(obj)) {
  28969. throw new TypeError(`${context} is not an object.`);
  28970. }
  28971. }
  28972. function assertFunction(x5, context) {
  28973. if (typeof x5 !== "function") {
  28974. throw new TypeError(`${context} is not a function.`);
  28975. }
  28976. }
  28977. function isObject(x5) {
  28978. return typeof x5 === "object" && x5 !== null || typeof x5 === "function";
  28979. }
  28980. function assertObject(x5, context) {
  28981. if (!isObject(x5)) {
  28982. throw new TypeError(`${context} is not an object.`);
  28983. }
  28984. }
  28985. function assertRequiredArgument(x5, position, context) {
  28986. if (x5 === void 0) {
  28987. throw new TypeError(`Parameter ${position} is required in '${context}'.`);
  28988. }
  28989. }
  28990. function assertRequiredField(x5, field, context) {
  28991. if (x5 === void 0) {
  28992. throw new TypeError(`${field} is required in '${context}'.`);
  28993. }
  28994. }
  28995. function convertUnrestrictedDouble(value) {
  28996. return Number(value);
  28997. }
  28998. function censorNegativeZero(x5) {
  28999. return x5 === 0 ? 0 : x5;
  29000. }
  29001. function integerPart(x5) {
  29002. return censorNegativeZero(MathTrunc(x5));
  29003. }
  29004. function convertUnsignedLongLongWithEnforceRange(value, context) {
  29005. const lowerBound = 0;
  29006. const upperBound = Number.MAX_SAFE_INTEGER;
  29007. let x5 = Number(value);
  29008. x5 = censorNegativeZero(x5);
  29009. if (!NumberIsFinite(x5)) {
  29010. throw new TypeError(`${context} is not a finite number`);
  29011. }
  29012. x5 = integerPart(x5);
  29013. if (x5 < lowerBound || x5 > upperBound) {
  29014. throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
  29015. }
  29016. if (!NumberIsFinite(x5) || x5 === 0) {
  29017. return 0;
  29018. }
  29019. return x5;
  29020. }
  29021. function assertReadableStream(x5, context) {
  29022. if (!IsReadableStream(x5)) {
  29023. throw new TypeError(`${context} is not a ReadableStream.`);
  29024. }
  29025. }
  29026. function AcquireReadableStreamDefaultReader(stream) {
  29027. return new ReadableStreamDefaultReader(stream);
  29028. }
  29029. function ReadableStreamAddReadRequest(stream, readRequest) {
  29030. stream._reader._readRequests.push(readRequest);
  29031. }
  29032. function ReadableStreamFulfillReadRequest(stream, chunk, done) {
  29033. const reader = stream._reader;
  29034. const readRequest = reader._readRequests.shift();
  29035. if (done) {
  29036. readRequest._closeSteps();
  29037. } else {
  29038. readRequest._chunkSteps(chunk);
  29039. }
  29040. }
  29041. function ReadableStreamGetNumReadRequests(stream) {
  29042. return stream._reader._readRequests.length;
  29043. }
  29044. function ReadableStreamHasDefaultReader(stream) {
  29045. const reader = stream._reader;
  29046. if (reader === void 0) {
  29047. return false;
  29048. }
  29049. if (!IsReadableStreamDefaultReader(reader)) {
  29050. return false;
  29051. }
  29052. return true;
  29053. }
  29054. class ReadableStreamDefaultReader {
  29055. constructor(stream) {
  29056. assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader");
  29057. assertReadableStream(stream, "First parameter");
  29058. if (IsReadableStreamLocked(stream)) {
  29059. throw new TypeError("This stream has already been locked for exclusive reading by another reader");
  29060. }
  29061. ReadableStreamReaderGenericInitialize(this, stream);
  29062. this._readRequests = new SimpleQueue();
  29063. }
  29064. /**
  29065. * Returns a promise that will be fulfilled when the stream becomes closed,
  29066. * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
  29067. */
  29068. get closed() {
  29069. if (!IsReadableStreamDefaultReader(this)) {
  29070. return promiseRejectedWith(defaultReaderBrandCheckException("closed"));
  29071. }
  29072. return this._closedPromise;
  29073. }
  29074. /**
  29075. * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
  29076. */
  29077. cancel(reason = void 0) {
  29078. if (!IsReadableStreamDefaultReader(this)) {
  29079. return promiseRejectedWith(defaultReaderBrandCheckException("cancel"));
  29080. }
  29081. if (this._ownerReadableStream === void 0) {
  29082. return promiseRejectedWith(readerLockException("cancel"));
  29083. }
  29084. return ReadableStreamReaderGenericCancel(this, reason);
  29085. }
  29086. /**
  29087. * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
  29088. *
  29089. * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
  29090. */
  29091. read() {
  29092. if (!IsReadableStreamDefaultReader(this)) {
  29093. return promiseRejectedWith(defaultReaderBrandCheckException("read"));
  29094. }
  29095. if (this._ownerReadableStream === void 0) {
  29096. return promiseRejectedWith(readerLockException("read from"));
  29097. }
  29098. let resolvePromise;
  29099. let rejectPromise;
  29100. const promise = newPromise((resolve, reject) => {
  29101. resolvePromise = resolve;
  29102. rejectPromise = reject;
  29103. });
  29104. const readRequest = {
  29105. _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
  29106. _closeSteps: () => resolvePromise({ value: void 0, done: true }),
  29107. _errorSteps: (e6) => rejectPromise(e6)
  29108. };
  29109. ReadableStreamDefaultReaderRead(this, readRequest);
  29110. return promise;
  29111. }
  29112. /**
  29113. * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
  29114. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
  29115. * from now on; otherwise, the reader will appear closed.
  29116. *
  29117. * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
  29118. * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
  29119. * do so will throw a `TypeError` and leave the reader locked to the stream.
  29120. */
  29121. releaseLock() {
  29122. if (!IsReadableStreamDefaultReader(this)) {
  29123. throw defaultReaderBrandCheckException("releaseLock");
  29124. }
  29125. if (this._ownerReadableStream === void 0) {
  29126. return;
  29127. }
  29128. ReadableStreamDefaultReaderRelease(this);
  29129. }
  29130. }
  29131. Object.defineProperties(ReadableStreamDefaultReader.prototype, {
  29132. cancel: { enumerable: true },
  29133. read: { enumerable: true },
  29134. releaseLock: { enumerable: true },
  29135. closed: { enumerable: true }
  29136. });
  29137. setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel");
  29138. setFunctionName(ReadableStreamDefaultReader.prototype.read, "read");
  29139. setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock");
  29140. if (typeof Symbol.toStringTag === "symbol") {
  29141. Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {
  29142. value: "ReadableStreamDefaultReader",
  29143. configurable: true
  29144. });
  29145. }
  29146. function IsReadableStreamDefaultReader(x5) {
  29147. if (!typeIsObject(x5)) {
  29148. return false;
  29149. }
  29150. if (!Object.prototype.hasOwnProperty.call(x5, "_readRequests")) {
  29151. return false;
  29152. }
  29153. return x5 instanceof ReadableStreamDefaultReader;
  29154. }
  29155. function ReadableStreamDefaultReaderRead(reader, readRequest) {
  29156. const stream = reader._ownerReadableStream;
  29157. stream._disturbed = true;
  29158. if (stream._state === "closed") {
  29159. readRequest._closeSteps();
  29160. } else if (stream._state === "errored") {
  29161. readRequest._errorSteps(stream._storedError);
  29162. } else {
  29163. stream._readableStreamController[PullSteps](readRequest);
  29164. }
  29165. }
  29166. function ReadableStreamDefaultReaderRelease(reader) {
  29167. ReadableStreamReaderGenericRelease(reader);
  29168. const e6 = new TypeError("Reader was released");
  29169. ReadableStreamDefaultReaderErrorReadRequests(reader, e6);
  29170. }
  29171. function ReadableStreamDefaultReaderErrorReadRequests(reader, e6) {
  29172. const readRequests = reader._readRequests;
  29173. reader._readRequests = new SimpleQueue();
  29174. readRequests.forEach((readRequest) => {
  29175. readRequest._errorSteps(e6);
  29176. });
  29177. }
  29178. function defaultReaderBrandCheckException(name) {
  29179. return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
  29180. }
  29181. const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {
  29182. }).prototype);
  29183. class ReadableStreamAsyncIteratorImpl {
  29184. constructor(reader, preventCancel) {
  29185. this._ongoingPromise = void 0;
  29186. this._isFinished = false;
  29187. this._reader = reader;
  29188. this._preventCancel = preventCancel;
  29189. }
  29190. next() {
  29191. const nextSteps = () => this._nextSteps();
  29192. this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps();
  29193. return this._ongoingPromise;
  29194. }
  29195. return(value) {
  29196. const returnSteps = () => this._returnSteps(value);
  29197. return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps();
  29198. }
  29199. _nextSteps() {
  29200. if (this._isFinished) {
  29201. return Promise.resolve({ value: void 0, done: true });
  29202. }
  29203. const reader = this._reader;
  29204. let resolvePromise;
  29205. let rejectPromise;
  29206. const promise = newPromise((resolve, reject) => {
  29207. resolvePromise = resolve;
  29208. rejectPromise = reject;
  29209. });
  29210. const readRequest = {
  29211. _chunkSteps: (chunk) => {
  29212. this._ongoingPromise = void 0;
  29213. _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
  29214. },
  29215. _closeSteps: () => {
  29216. this._ongoingPromise = void 0;
  29217. this._isFinished = true;
  29218. ReadableStreamReaderGenericRelease(reader);
  29219. resolvePromise({ value: void 0, done: true });
  29220. },
  29221. _errorSteps: (reason) => {
  29222. this._ongoingPromise = void 0;
  29223. this._isFinished = true;
  29224. ReadableStreamReaderGenericRelease(reader);
  29225. rejectPromise(reason);
  29226. }
  29227. };
  29228. ReadableStreamDefaultReaderRead(reader, readRequest);
  29229. return promise;
  29230. }
  29231. _returnSteps(value) {
  29232. if (this._isFinished) {
  29233. return Promise.resolve({ value, done: true });
  29234. }
  29235. this._isFinished = true;
  29236. const reader = this._reader;
  29237. if (!this._preventCancel) {
  29238. const result = ReadableStreamReaderGenericCancel(reader, value);
  29239. ReadableStreamReaderGenericRelease(reader);
  29240. return transformPromiseWith(result, () => ({ value, done: true }));
  29241. }
  29242. ReadableStreamReaderGenericRelease(reader);
  29243. return promiseResolvedWith({ value, done: true });
  29244. }
  29245. }
  29246. const ReadableStreamAsyncIteratorPrototype = {
  29247. next() {
  29248. if (!IsReadableStreamAsyncIterator(this)) {
  29249. return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next"));
  29250. }
  29251. return this._asyncIteratorImpl.next();
  29252. },
  29253. return(value) {
  29254. if (!IsReadableStreamAsyncIterator(this)) {
  29255. return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return"));
  29256. }
  29257. return this._asyncIteratorImpl.return(value);
  29258. }
  29259. };
  29260. Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
  29261. function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
  29262. const reader = AcquireReadableStreamDefaultReader(stream);
  29263. const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
  29264. const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
  29265. iterator._asyncIteratorImpl = impl;
  29266. return iterator;
  29267. }
  29268. function IsReadableStreamAsyncIterator(x5) {
  29269. if (!typeIsObject(x5)) {
  29270. return false;
  29271. }
  29272. if (!Object.prototype.hasOwnProperty.call(x5, "_asyncIteratorImpl")) {
  29273. return false;
  29274. }
  29275. try {
  29276. return x5._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl;
  29277. } catch (_a16) {
  29278. return false;
  29279. }
  29280. }
  29281. function streamAsyncIteratorBrandCheckException(name) {
  29282. return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
  29283. }
  29284. const NumberIsNaN = Number.isNaN || function(x5) {
  29285. return x5 !== x5;
  29286. };
  29287. var _a15, _b, _c;
  29288. function CreateArrayFromList(elements) {
  29289. return elements.slice();
  29290. }
  29291. function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n5) {
  29292. new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n5), destOffset);
  29293. }
  29294. let TransferArrayBuffer = (O) => {
  29295. if (typeof O.transfer === "function") {
  29296. TransferArrayBuffer = (buffer) => buffer.transfer();
  29297. } else if (typeof structuredClone === "function") {
  29298. TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] });
  29299. } else {
  29300. TransferArrayBuffer = (buffer) => buffer;
  29301. }
  29302. return TransferArrayBuffer(O);
  29303. };
  29304. let IsDetachedBuffer = (O) => {
  29305. if (typeof O.detached === "boolean") {
  29306. IsDetachedBuffer = (buffer) => buffer.detached;
  29307. } else {
  29308. IsDetachedBuffer = (buffer) => buffer.byteLength === 0;
  29309. }
  29310. return IsDetachedBuffer(O);
  29311. };
  29312. function ArrayBufferSlice(buffer, begin, end) {
  29313. if (buffer.slice) {
  29314. return buffer.slice(begin, end);
  29315. }
  29316. const length = end - begin;
  29317. const slice = new ArrayBuffer(length);
  29318. CopyDataBlockBytes(slice, 0, buffer, begin, length);
  29319. return slice;
  29320. }
  29321. function GetMethod(receiver, prop) {
  29322. const func = receiver[prop];
  29323. if (func === void 0 || func === null) {
  29324. return void 0;
  29325. }
  29326. if (typeof func !== "function") {
  29327. throw new TypeError(`${String(prop)} is not a function`);
  29328. }
  29329. return func;
  29330. }
  29331. function CreateAsyncFromSyncIterator(syncIteratorRecord) {
  29332. const syncIterable = {
  29333. [Symbol.iterator]: () => syncIteratorRecord.iterator
  29334. };
  29335. const asyncIterator = async function* () {
  29336. return yield* syncIterable;
  29337. }();
  29338. const nextMethod = asyncIterator.next;
  29339. return { iterator: asyncIterator, nextMethod, done: false };
  29340. }
  29341. const SymbolAsyncIterator = (_c = (_a15 = Symbol.asyncIterator) !== null && _a15 !== void 0 ? _a15 : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== void 0 ? _c : "@@asyncIterator";
  29342. function GetIterator(obj, hint = "sync", method) {
  29343. if (method === void 0) {
  29344. if (hint === "async") {
  29345. method = GetMethod(obj, SymbolAsyncIterator);
  29346. if (method === void 0) {
  29347. const syncMethod = GetMethod(obj, Symbol.iterator);
  29348. const syncIteratorRecord = GetIterator(obj, "sync", syncMethod);
  29349. return CreateAsyncFromSyncIterator(syncIteratorRecord);
  29350. }
  29351. } else {
  29352. method = GetMethod(obj, Symbol.iterator);
  29353. }
  29354. }
  29355. if (method === void 0) {
  29356. throw new TypeError("The object is not iterable");
  29357. }
  29358. const iterator = reflectCall(method, obj, []);
  29359. if (!typeIsObject(iterator)) {
  29360. throw new TypeError("The iterator method must return an object");
  29361. }
  29362. const nextMethod = iterator.next;
  29363. return { iterator, nextMethod, done: false };
  29364. }
  29365. function IteratorNext(iteratorRecord) {
  29366. const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
  29367. if (!typeIsObject(result)) {
  29368. throw new TypeError("The iterator.next() method must return an object");
  29369. }
  29370. return result;
  29371. }
  29372. function IteratorComplete(iterResult) {
  29373. return Boolean(iterResult.done);
  29374. }
  29375. function IteratorValue(iterResult) {
  29376. return iterResult.value;
  29377. }
  29378. function IsNonNegativeNumber(v6) {
  29379. if (typeof v6 !== "number") {
  29380. return false;
  29381. }
  29382. if (NumberIsNaN(v6)) {
  29383. return false;
  29384. }
  29385. if (v6 < 0) {
  29386. return false;
  29387. }
  29388. return true;
  29389. }
  29390. function CloneAsUint8Array(O) {
  29391. const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
  29392. return new Uint8Array(buffer);
  29393. }
  29394. function DequeueValue(container) {
  29395. const pair = container._queue.shift();
  29396. container._queueTotalSize -= pair.size;
  29397. if (container._queueTotalSize < 0) {
  29398. container._queueTotalSize = 0;
  29399. }
  29400. return pair.value;
  29401. }
  29402. function EnqueueValueWithSize(container, value, size) {
  29403. if (!IsNonNegativeNumber(size) || size === Infinity) {
  29404. throw new RangeError("Size must be a finite, non-NaN, non-negative number.");
  29405. }
  29406. container._queue.push({ value, size });
  29407. container._queueTotalSize += size;
  29408. }
  29409. function PeekQueueValue(container) {
  29410. const pair = container._queue.peek();
  29411. return pair.value;
  29412. }
  29413. function ResetQueue(container) {
  29414. container._queue = new SimpleQueue();
  29415. container._queueTotalSize = 0;
  29416. }
  29417. function isDataViewConstructor(ctor) {
  29418. return ctor === DataView;
  29419. }
  29420. function isDataView(view5) {
  29421. return isDataViewConstructor(view5.constructor);
  29422. }
  29423. function arrayBufferViewElementSize(ctor) {
  29424. if (isDataViewConstructor(ctor)) {
  29425. return 1;
  29426. }
  29427. return ctor.BYTES_PER_ELEMENT;
  29428. }
  29429. class ReadableStreamBYOBRequest {
  29430. constructor() {
  29431. throw new TypeError("Illegal constructor");
  29432. }
  29433. /**
  29434. * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
  29435. */
  29436. get view() {
  29437. if (!IsReadableStreamBYOBRequest(this)) {
  29438. throw byobRequestBrandCheckException("view");
  29439. }
  29440. return this._view;
  29441. }
  29442. respond(bytesWritten) {
  29443. if (!IsReadableStreamBYOBRequest(this)) {
  29444. throw byobRequestBrandCheckException("respond");
  29445. }
  29446. assertRequiredArgument(bytesWritten, 1, "respond");
  29447. bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter");
  29448. if (this._associatedReadableByteStreamController === void 0) {
  29449. throw new TypeError("This BYOB request has been invalidated");
  29450. }
  29451. if (IsDetachedBuffer(this._view.buffer)) {
  29452. throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
  29453. }
  29454. ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
  29455. }
  29456. respondWithNewView(view5) {
  29457. if (!IsReadableStreamBYOBRequest(this)) {
  29458. throw byobRequestBrandCheckException("respondWithNewView");
  29459. }
  29460. assertRequiredArgument(view5, 1, "respondWithNewView");
  29461. if (!ArrayBuffer.isView(view5)) {
  29462. throw new TypeError("You can only respond with array buffer views");
  29463. }
  29464. if (this._associatedReadableByteStreamController === void 0) {
  29465. throw new TypeError("This BYOB request has been invalidated");
  29466. }
  29467. if (IsDetachedBuffer(view5.buffer)) {
  29468. throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");
  29469. }
  29470. ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view5);
  29471. }
  29472. }
  29473. Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
  29474. respond: { enumerable: true },
  29475. respondWithNewView: { enumerable: true },
  29476. view: { enumerable: true }
  29477. });
  29478. setFunctionName(ReadableStreamBYOBRequest.prototype.respond, "respond");
  29479. setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView");
  29480. if (typeof Symbol.toStringTag === "symbol") {
  29481. Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {
  29482. value: "ReadableStreamBYOBRequest",
  29483. configurable: true
  29484. });
  29485. }
  29486. class ReadableByteStreamController {
  29487. constructor() {
  29488. throw new TypeError("Illegal constructor");
  29489. }
  29490. /**
  29491. * Returns the current BYOB pull request, or `null` if there isn't one.
  29492. */
  29493. get byobRequest() {
  29494. if (!IsReadableByteStreamController(this)) {
  29495. throw byteStreamControllerBrandCheckException("byobRequest");
  29496. }
  29497. return ReadableByteStreamControllerGetBYOBRequest(this);
  29498. }
  29499. /**
  29500. * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
  29501. * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
  29502. */
  29503. get desiredSize() {
  29504. if (!IsReadableByteStreamController(this)) {
  29505. throw byteStreamControllerBrandCheckException("desiredSize");
  29506. }
  29507. return ReadableByteStreamControllerGetDesiredSize(this);
  29508. }
  29509. /**
  29510. * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
  29511. * the stream, but once those are read, the stream will become closed.
  29512. */
  29513. close() {
  29514. if (!IsReadableByteStreamController(this)) {
  29515. throw byteStreamControllerBrandCheckException("close");
  29516. }
  29517. if (this._closeRequested) {
  29518. throw new TypeError("The stream has already been closed; do not close it again!");
  29519. }
  29520. const state2 = this._controlledReadableByteStream._state;
  29521. if (state2 !== "readable") {
  29522. throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be closed`);
  29523. }
  29524. ReadableByteStreamControllerClose(this);
  29525. }
  29526. enqueue(chunk) {
  29527. if (!IsReadableByteStreamController(this)) {
  29528. throw byteStreamControllerBrandCheckException("enqueue");
  29529. }
  29530. assertRequiredArgument(chunk, 1, "enqueue");
  29531. if (!ArrayBuffer.isView(chunk)) {
  29532. throw new TypeError("chunk must be an array buffer view");
  29533. }
  29534. if (chunk.byteLength === 0) {
  29535. throw new TypeError("chunk must have non-zero byteLength");
  29536. }
  29537. if (chunk.buffer.byteLength === 0) {
  29538. throw new TypeError(`chunk's buffer must have non-zero byteLength`);
  29539. }
  29540. if (this._closeRequested) {
  29541. throw new TypeError("stream is closed or draining");
  29542. }
  29543. const state2 = this._controlledReadableByteStream._state;
  29544. if (state2 !== "readable") {
  29545. throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be enqueued to`);
  29546. }
  29547. ReadableByteStreamControllerEnqueue(this, chunk);
  29548. }
  29549. /**
  29550. * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
  29551. */
  29552. error(e6 = void 0) {
  29553. if (!IsReadableByteStreamController(this)) {
  29554. throw byteStreamControllerBrandCheckException("error");
  29555. }
  29556. ReadableByteStreamControllerError(this, e6);
  29557. }
  29558. /** @internal */
  29559. [CancelSteps](reason) {
  29560. ReadableByteStreamControllerClearPendingPullIntos(this);
  29561. ResetQueue(this);
  29562. const result = this._cancelAlgorithm(reason);
  29563. ReadableByteStreamControllerClearAlgorithms(this);
  29564. return result;
  29565. }
  29566. /** @internal */
  29567. [PullSteps](readRequest) {
  29568. const stream = this._controlledReadableByteStream;
  29569. if (this._queueTotalSize > 0) {
  29570. ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
  29571. return;
  29572. }
  29573. const autoAllocateChunkSize = this._autoAllocateChunkSize;
  29574. if (autoAllocateChunkSize !== void 0) {
  29575. let buffer;
  29576. try {
  29577. buffer = new ArrayBuffer(autoAllocateChunkSize);
  29578. } catch (bufferE) {
  29579. readRequest._errorSteps(bufferE);
  29580. return;
  29581. }
  29582. const pullIntoDescriptor = {
  29583. buffer,
  29584. bufferByteLength: autoAllocateChunkSize,
  29585. byteOffset: 0,
  29586. byteLength: autoAllocateChunkSize,
  29587. bytesFilled: 0,
  29588. minimumFill: 1,
  29589. elementSize: 1,
  29590. viewConstructor: Uint8Array,
  29591. readerType: "default"
  29592. };
  29593. this._pendingPullIntos.push(pullIntoDescriptor);
  29594. }
  29595. ReadableStreamAddReadRequest(stream, readRequest);
  29596. ReadableByteStreamControllerCallPullIfNeeded(this);
  29597. }
  29598. /** @internal */
  29599. [ReleaseSteps]() {
  29600. if (this._pendingPullIntos.length > 0) {
  29601. const firstPullInto = this._pendingPullIntos.peek();
  29602. firstPullInto.readerType = "none";
  29603. this._pendingPullIntos = new SimpleQueue();
  29604. this._pendingPullIntos.push(firstPullInto);
  29605. }
  29606. }
  29607. }
  29608. Object.defineProperties(ReadableByteStreamController.prototype, {
  29609. close: { enumerable: true },
  29610. enqueue: { enumerable: true },
  29611. error: { enumerable: true },
  29612. byobRequest: { enumerable: true },
  29613. desiredSize: { enumerable: true }
  29614. });
  29615. setFunctionName(ReadableByteStreamController.prototype.close, "close");
  29616. setFunctionName(ReadableByteStreamController.prototype.enqueue, "enqueue");
  29617. setFunctionName(ReadableByteStreamController.prototype.error, "error");
  29618. if (typeof Symbol.toStringTag === "symbol") {
  29619. Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {
  29620. value: "ReadableByteStreamController",
  29621. configurable: true
  29622. });
  29623. }
  29624. function IsReadableByteStreamController(x5) {
  29625. if (!typeIsObject(x5)) {
  29626. return false;
  29627. }
  29628. if (!Object.prototype.hasOwnProperty.call(x5, "_controlledReadableByteStream")) {
  29629. return false;
  29630. }
  29631. return x5 instanceof ReadableByteStreamController;
  29632. }
  29633. function IsReadableStreamBYOBRequest(x5) {
  29634. if (!typeIsObject(x5)) {
  29635. return false;
  29636. }
  29637. if (!Object.prototype.hasOwnProperty.call(x5, "_associatedReadableByteStreamController")) {
  29638. return false;
  29639. }
  29640. return x5 instanceof ReadableStreamBYOBRequest;
  29641. }
  29642. function ReadableByteStreamControllerCallPullIfNeeded(controller) {
  29643. const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
  29644. if (!shouldPull) {
  29645. return;
  29646. }
  29647. if (controller._pulling) {
  29648. controller._pullAgain = true;
  29649. return;
  29650. }
  29651. controller._pulling = true;
  29652. const pullPromise = controller._pullAlgorithm();
  29653. uponPromise(pullPromise, () => {
  29654. controller._pulling = false;
  29655. if (controller._pullAgain) {
  29656. controller._pullAgain = false;
  29657. ReadableByteStreamControllerCallPullIfNeeded(controller);
  29658. }
  29659. return null;
  29660. }, (e6) => {
  29661. ReadableByteStreamControllerError(controller, e6);
  29662. return null;
  29663. });
  29664. }
  29665. function ReadableByteStreamControllerClearPendingPullIntos(controller) {
  29666. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  29667. controller._pendingPullIntos = new SimpleQueue();
  29668. }
  29669. function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
  29670. let done = false;
  29671. if (stream._state === "closed") {
  29672. done = true;
  29673. }
  29674. const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
  29675. if (pullIntoDescriptor.readerType === "default") {
  29676. ReadableStreamFulfillReadRequest(stream, filledView, done);
  29677. } else {
  29678. ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
  29679. }
  29680. }
  29681. function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
  29682. const bytesFilled = pullIntoDescriptor.bytesFilled;
  29683. const elementSize = pullIntoDescriptor.elementSize;
  29684. return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
  29685. }
  29686. function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
  29687. controller._queue.push({ buffer, byteOffset, byteLength });
  29688. controller._queueTotalSize += byteLength;
  29689. }
  29690. function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
  29691. let clonedChunk;
  29692. try {
  29693. clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
  29694. } catch (cloneE) {
  29695. ReadableByteStreamControllerError(controller, cloneE);
  29696. throw cloneE;
  29697. }
  29698. ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
  29699. }
  29700. function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
  29701. if (firstDescriptor.bytesFilled > 0) {
  29702. ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
  29703. }
  29704. ReadableByteStreamControllerShiftPendingPullInto(controller);
  29705. }
  29706. function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
  29707. const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
  29708. const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
  29709. let totalBytesToCopyRemaining = maxBytesToCopy;
  29710. let ready = false;
  29711. const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
  29712. const maxAlignedBytes = maxBytesFilled - remainderBytes;
  29713. if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
  29714. totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
  29715. ready = true;
  29716. }
  29717. const queue = controller._queue;
  29718. while (totalBytesToCopyRemaining > 0) {
  29719. const headOfQueue = queue.peek();
  29720. const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
  29721. const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
  29722. CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
  29723. if (headOfQueue.byteLength === bytesToCopy) {
  29724. queue.shift();
  29725. } else {
  29726. headOfQueue.byteOffset += bytesToCopy;
  29727. headOfQueue.byteLength -= bytesToCopy;
  29728. }
  29729. controller._queueTotalSize -= bytesToCopy;
  29730. ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
  29731. totalBytesToCopyRemaining -= bytesToCopy;
  29732. }
  29733. return ready;
  29734. }
  29735. function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
  29736. pullIntoDescriptor.bytesFilled += size;
  29737. }
  29738. function ReadableByteStreamControllerHandleQueueDrain(controller) {
  29739. if (controller._queueTotalSize === 0 && controller._closeRequested) {
  29740. ReadableByteStreamControllerClearAlgorithms(controller);
  29741. ReadableStreamClose(controller._controlledReadableByteStream);
  29742. } else {
  29743. ReadableByteStreamControllerCallPullIfNeeded(controller);
  29744. }
  29745. }
  29746. function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
  29747. if (controller._byobRequest === null) {
  29748. return;
  29749. }
  29750. controller._byobRequest._associatedReadableByteStreamController = void 0;
  29751. controller._byobRequest._view = null;
  29752. controller._byobRequest = null;
  29753. }
  29754. function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
  29755. while (controller._pendingPullIntos.length > 0) {
  29756. if (controller._queueTotalSize === 0) {
  29757. return;
  29758. }
  29759. const pullIntoDescriptor = controller._pendingPullIntos.peek();
  29760. if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
  29761. ReadableByteStreamControllerShiftPendingPullInto(controller);
  29762. ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
  29763. }
  29764. }
  29765. }
  29766. function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
  29767. const reader = controller._controlledReadableByteStream._reader;
  29768. while (reader._readRequests.length > 0) {
  29769. if (controller._queueTotalSize === 0) {
  29770. return;
  29771. }
  29772. const readRequest = reader._readRequests.shift();
  29773. ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
  29774. }
  29775. }
  29776. function ReadableByteStreamControllerPullInto(controller, view5, min, readIntoRequest) {
  29777. const stream = controller._controlledReadableByteStream;
  29778. const ctor = view5.constructor;
  29779. const elementSize = arrayBufferViewElementSize(ctor);
  29780. const { byteOffset, byteLength } = view5;
  29781. const minimumFill = min * elementSize;
  29782. let buffer;
  29783. try {
  29784. buffer = TransferArrayBuffer(view5.buffer);
  29785. } catch (e6) {
  29786. readIntoRequest._errorSteps(e6);
  29787. return;
  29788. }
  29789. const pullIntoDescriptor = {
  29790. buffer,
  29791. bufferByteLength: buffer.byteLength,
  29792. byteOffset,
  29793. byteLength,
  29794. bytesFilled: 0,
  29795. minimumFill,
  29796. elementSize,
  29797. viewConstructor: ctor,
  29798. readerType: "byob"
  29799. };
  29800. if (controller._pendingPullIntos.length > 0) {
  29801. controller._pendingPullIntos.push(pullIntoDescriptor);
  29802. ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
  29803. return;
  29804. }
  29805. if (stream._state === "closed") {
  29806. const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
  29807. readIntoRequest._closeSteps(emptyView);
  29808. return;
  29809. }
  29810. if (controller._queueTotalSize > 0) {
  29811. if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
  29812. const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
  29813. ReadableByteStreamControllerHandleQueueDrain(controller);
  29814. readIntoRequest._chunkSteps(filledView);
  29815. return;
  29816. }
  29817. if (controller._closeRequested) {
  29818. const e6 = new TypeError("Insufficient bytes to fill elements in the given buffer");
  29819. ReadableByteStreamControllerError(controller, e6);
  29820. readIntoRequest._errorSteps(e6);
  29821. return;
  29822. }
  29823. }
  29824. controller._pendingPullIntos.push(pullIntoDescriptor);
  29825. ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
  29826. ReadableByteStreamControllerCallPullIfNeeded(controller);
  29827. }
  29828. function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
  29829. if (firstDescriptor.readerType === "none") {
  29830. ReadableByteStreamControllerShiftPendingPullInto(controller);
  29831. }
  29832. const stream = controller._controlledReadableByteStream;
  29833. if (ReadableStreamHasBYOBReader(stream)) {
  29834. while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
  29835. const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
  29836. ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
  29837. }
  29838. }
  29839. }
  29840. function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
  29841. ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
  29842. if (pullIntoDescriptor.readerType === "none") {
  29843. ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
  29844. ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
  29845. return;
  29846. }
  29847. if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
  29848. return;
  29849. }
  29850. ReadableByteStreamControllerShiftPendingPullInto(controller);
  29851. const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
  29852. if (remainderSize > 0) {
  29853. const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
  29854. ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
  29855. }
  29856. pullIntoDescriptor.bytesFilled -= remainderSize;
  29857. ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
  29858. ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
  29859. }
  29860. function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
  29861. const firstDescriptor = controller._pendingPullIntos.peek();
  29862. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  29863. const state2 = controller._controlledReadableByteStream._state;
  29864. if (state2 === "closed") {
  29865. ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
  29866. } else {
  29867. ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
  29868. }
  29869. ReadableByteStreamControllerCallPullIfNeeded(controller);
  29870. }
  29871. function ReadableByteStreamControllerShiftPendingPullInto(controller) {
  29872. const descriptor = controller._pendingPullIntos.shift();
  29873. return descriptor;
  29874. }
  29875. function ReadableByteStreamControllerShouldCallPull(controller) {
  29876. const stream = controller._controlledReadableByteStream;
  29877. if (stream._state !== "readable") {
  29878. return false;
  29879. }
  29880. if (controller._closeRequested) {
  29881. return false;
  29882. }
  29883. if (!controller._started) {
  29884. return false;
  29885. }
  29886. if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  29887. return true;
  29888. }
  29889. if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
  29890. return true;
  29891. }
  29892. const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
  29893. if (desiredSize > 0) {
  29894. return true;
  29895. }
  29896. return false;
  29897. }
  29898. function ReadableByteStreamControllerClearAlgorithms(controller) {
  29899. controller._pullAlgorithm = void 0;
  29900. controller._cancelAlgorithm = void 0;
  29901. }
  29902. function ReadableByteStreamControllerClose(controller) {
  29903. const stream = controller._controlledReadableByteStream;
  29904. if (controller._closeRequested || stream._state !== "readable") {
  29905. return;
  29906. }
  29907. if (controller._queueTotalSize > 0) {
  29908. controller._closeRequested = true;
  29909. return;
  29910. }
  29911. if (controller._pendingPullIntos.length > 0) {
  29912. const firstPendingPullInto = controller._pendingPullIntos.peek();
  29913. if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
  29914. const e6 = new TypeError("Insufficient bytes to fill elements in the given buffer");
  29915. ReadableByteStreamControllerError(controller, e6);
  29916. throw e6;
  29917. }
  29918. }
  29919. ReadableByteStreamControllerClearAlgorithms(controller);
  29920. ReadableStreamClose(stream);
  29921. }
  29922. function ReadableByteStreamControllerEnqueue(controller, chunk) {
  29923. const stream = controller._controlledReadableByteStream;
  29924. if (controller._closeRequested || stream._state !== "readable") {
  29925. return;
  29926. }
  29927. const { buffer, byteOffset, byteLength } = chunk;
  29928. if (IsDetachedBuffer(buffer)) {
  29929. throw new TypeError("chunk's buffer is detached and so cannot be enqueued");
  29930. }
  29931. const transferredBuffer = TransferArrayBuffer(buffer);
  29932. if (controller._pendingPullIntos.length > 0) {
  29933. const firstPendingPullInto = controller._pendingPullIntos.peek();
  29934. if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
  29935. throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");
  29936. }
  29937. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  29938. firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
  29939. if (firstPendingPullInto.readerType === "none") {
  29940. ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
  29941. }
  29942. }
  29943. if (ReadableStreamHasDefaultReader(stream)) {
  29944. ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
  29945. if (ReadableStreamGetNumReadRequests(stream) === 0) {
  29946. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  29947. } else {
  29948. if (controller._pendingPullIntos.length > 0) {
  29949. ReadableByteStreamControllerShiftPendingPullInto(controller);
  29950. }
  29951. const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
  29952. ReadableStreamFulfillReadRequest(stream, transferredView, false);
  29953. }
  29954. } else if (ReadableStreamHasBYOBReader(stream)) {
  29955. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  29956. ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
  29957. } else {
  29958. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  29959. }
  29960. ReadableByteStreamControllerCallPullIfNeeded(controller);
  29961. }
  29962. function ReadableByteStreamControllerError(controller, e6) {
  29963. const stream = controller._controlledReadableByteStream;
  29964. if (stream._state !== "readable") {
  29965. return;
  29966. }
  29967. ReadableByteStreamControllerClearPendingPullIntos(controller);
  29968. ResetQueue(controller);
  29969. ReadableByteStreamControllerClearAlgorithms(controller);
  29970. ReadableStreamError(stream, e6);
  29971. }
  29972. function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
  29973. const entry = controller._queue.shift();
  29974. controller._queueTotalSize -= entry.byteLength;
  29975. ReadableByteStreamControllerHandleQueueDrain(controller);
  29976. const view5 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
  29977. readRequest._chunkSteps(view5);
  29978. }
  29979. function ReadableByteStreamControllerGetBYOBRequest(controller) {
  29980. if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
  29981. const firstDescriptor = controller._pendingPullIntos.peek();
  29982. const view5 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
  29983. const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
  29984. SetUpReadableStreamBYOBRequest(byobRequest, controller, view5);
  29985. controller._byobRequest = byobRequest;
  29986. }
  29987. return controller._byobRequest;
  29988. }
  29989. function ReadableByteStreamControllerGetDesiredSize(controller) {
  29990. const state2 = controller._controlledReadableByteStream._state;
  29991. if (state2 === "errored") {
  29992. return null;
  29993. }
  29994. if (state2 === "closed") {
  29995. return 0;
  29996. }
  29997. return controller._strategyHWM - controller._queueTotalSize;
  29998. }
  29999. function ReadableByteStreamControllerRespond(controller, bytesWritten) {
  30000. const firstDescriptor = controller._pendingPullIntos.peek();
  30001. const state2 = controller._controlledReadableByteStream._state;
  30002. if (state2 === "closed") {
  30003. if (bytesWritten !== 0) {
  30004. throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");
  30005. }
  30006. } else {
  30007. if (bytesWritten === 0) {
  30008. throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");
  30009. }
  30010. if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
  30011. throw new RangeError("bytesWritten out of range");
  30012. }
  30013. }
  30014. firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
  30015. ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
  30016. }
  30017. function ReadableByteStreamControllerRespondWithNewView(controller, view5) {
  30018. const firstDescriptor = controller._pendingPullIntos.peek();
  30019. const state2 = controller._controlledReadableByteStream._state;
  30020. if (state2 === "closed") {
  30021. if (view5.byteLength !== 0) {
  30022. throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
  30023. }
  30024. } else {
  30025. if (view5.byteLength === 0) {
  30026. throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");
  30027. }
  30028. }
  30029. if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view5.byteOffset) {
  30030. throw new RangeError("The region specified by view does not match byobRequest");
  30031. }
  30032. if (firstDescriptor.bufferByteLength !== view5.buffer.byteLength) {
  30033. throw new RangeError("The buffer of view has different capacity than byobRequest");
  30034. }
  30035. if (firstDescriptor.bytesFilled + view5.byteLength > firstDescriptor.byteLength) {
  30036. throw new RangeError("The region specified by view is larger than byobRequest");
  30037. }
  30038. const viewByteLength = view5.byteLength;
  30039. firstDescriptor.buffer = TransferArrayBuffer(view5.buffer);
  30040. ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
  30041. }
  30042. function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
  30043. controller._controlledReadableByteStream = stream;
  30044. controller._pullAgain = false;
  30045. controller._pulling = false;
  30046. controller._byobRequest = null;
  30047. controller._queue = controller._queueTotalSize = void 0;
  30048. ResetQueue(controller);
  30049. controller._closeRequested = false;
  30050. controller._started = false;
  30051. controller._strategyHWM = highWaterMark;
  30052. controller._pullAlgorithm = pullAlgorithm;
  30053. controller._cancelAlgorithm = cancelAlgorithm;
  30054. controller._autoAllocateChunkSize = autoAllocateChunkSize;
  30055. controller._pendingPullIntos = new SimpleQueue();
  30056. stream._readableStreamController = controller;
  30057. const startResult = startAlgorithm();
  30058. uponPromise(promiseResolvedWith(startResult), () => {
  30059. controller._started = true;
  30060. ReadableByteStreamControllerCallPullIfNeeded(controller);
  30061. return null;
  30062. }, (r6) => {
  30063. ReadableByteStreamControllerError(controller, r6);
  30064. return null;
  30065. });
  30066. }
  30067. function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
  30068. const controller = Object.create(ReadableByteStreamController.prototype);
  30069. let startAlgorithm;
  30070. let pullAlgorithm;
  30071. let cancelAlgorithm;
  30072. if (underlyingByteSource.start !== void 0) {
  30073. startAlgorithm = () => underlyingByteSource.start(controller);
  30074. } else {
  30075. startAlgorithm = () => void 0;
  30076. }
  30077. if (underlyingByteSource.pull !== void 0) {
  30078. pullAlgorithm = () => underlyingByteSource.pull(controller);
  30079. } else {
  30080. pullAlgorithm = () => promiseResolvedWith(void 0);
  30081. }
  30082. if (underlyingByteSource.cancel !== void 0) {
  30083. cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason);
  30084. } else {
  30085. cancelAlgorithm = () => promiseResolvedWith(void 0);
  30086. }
  30087. const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
  30088. if (autoAllocateChunkSize === 0) {
  30089. throw new TypeError("autoAllocateChunkSize must be greater than 0");
  30090. }
  30091. SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
  30092. }
  30093. function SetUpReadableStreamBYOBRequest(request2, controller, view5) {
  30094. request2._associatedReadableByteStreamController = controller;
  30095. request2._view = view5;
  30096. }
  30097. function byobRequestBrandCheckException(name) {
  30098. return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
  30099. }
  30100. function byteStreamControllerBrandCheckException(name) {
  30101. return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
  30102. }
  30103. function convertReaderOptions(options, context) {
  30104. assertDictionary(options, context);
  30105. const mode = options === null || options === void 0 ? void 0 : options.mode;
  30106. return {
  30107. mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
  30108. };
  30109. }
  30110. function convertReadableStreamReaderMode(mode, context) {
  30111. mode = `${mode}`;
  30112. if (mode !== "byob") {
  30113. throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
  30114. }
  30115. return mode;
  30116. }
  30117. function convertByobReadOptions(options, context) {
  30118. var _a16;
  30119. assertDictionary(options, context);
  30120. const min = (_a16 = options === null || options === void 0 ? void 0 : options.min) !== null && _a16 !== void 0 ? _a16 : 1;
  30121. return {
  30122. min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
  30123. };
  30124. }
  30125. function AcquireReadableStreamBYOBReader(stream) {
  30126. return new ReadableStreamBYOBReader(stream);
  30127. }
  30128. function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
  30129. stream._reader._readIntoRequests.push(readIntoRequest);
  30130. }
  30131. function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
  30132. const reader = stream._reader;
  30133. const readIntoRequest = reader._readIntoRequests.shift();
  30134. if (done) {
  30135. readIntoRequest._closeSteps(chunk);
  30136. } else {
  30137. readIntoRequest._chunkSteps(chunk);
  30138. }
  30139. }
  30140. function ReadableStreamGetNumReadIntoRequests(stream) {
  30141. return stream._reader._readIntoRequests.length;
  30142. }
  30143. function ReadableStreamHasBYOBReader(stream) {
  30144. const reader = stream._reader;
  30145. if (reader === void 0) {
  30146. return false;
  30147. }
  30148. if (!IsReadableStreamBYOBReader(reader)) {
  30149. return false;
  30150. }
  30151. return true;
  30152. }
  30153. class ReadableStreamBYOBReader {
  30154. constructor(stream) {
  30155. assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader");
  30156. assertReadableStream(stream, "First parameter");
  30157. if (IsReadableStreamLocked(stream)) {
  30158. throw new TypeError("This stream has already been locked for exclusive reading by another reader");
  30159. }
  30160. if (!IsReadableByteStreamController(stream._readableStreamController)) {
  30161. throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");
  30162. }
  30163. ReadableStreamReaderGenericInitialize(this, stream);
  30164. this._readIntoRequests = new SimpleQueue();
  30165. }
  30166. /**
  30167. * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
  30168. * the reader's lock is released before the stream finishes closing.
  30169. */
  30170. get closed() {
  30171. if (!IsReadableStreamBYOBReader(this)) {
  30172. return promiseRejectedWith(byobReaderBrandCheckException("closed"));
  30173. }
  30174. return this._closedPromise;
  30175. }
  30176. /**
  30177. * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
  30178. */
  30179. cancel(reason = void 0) {
  30180. if (!IsReadableStreamBYOBReader(this)) {
  30181. return promiseRejectedWith(byobReaderBrandCheckException("cancel"));
  30182. }
  30183. if (this._ownerReadableStream === void 0) {
  30184. return promiseRejectedWith(readerLockException("cancel"));
  30185. }
  30186. return ReadableStreamReaderGenericCancel(this, reason);
  30187. }
  30188. read(view5, rawOptions = {}) {
  30189. if (!IsReadableStreamBYOBReader(this)) {
  30190. return promiseRejectedWith(byobReaderBrandCheckException("read"));
  30191. }
  30192. if (!ArrayBuffer.isView(view5)) {
  30193. return promiseRejectedWith(new TypeError("view must be an array buffer view"));
  30194. }
  30195. if (view5.byteLength === 0) {
  30196. return promiseRejectedWith(new TypeError("view must have non-zero byteLength"));
  30197. }
  30198. if (view5.buffer.byteLength === 0) {
  30199. return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
  30200. }
  30201. if (IsDetachedBuffer(view5.buffer)) {
  30202. return promiseRejectedWith(new TypeError("view's buffer has been detached"));
  30203. }
  30204. let options;
  30205. try {
  30206. options = convertByobReadOptions(rawOptions, "options");
  30207. } catch (e6) {
  30208. return promiseRejectedWith(e6);
  30209. }
  30210. const min = options.min;
  30211. if (min === 0) {
  30212. return promiseRejectedWith(new TypeError("options.min must be greater than 0"));
  30213. }
  30214. if (!isDataView(view5)) {
  30215. if (min > view5.length) {
  30216. return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length"));
  30217. }
  30218. } else if (min > view5.byteLength) {
  30219. return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength"));
  30220. }
  30221. if (this._ownerReadableStream === void 0) {
  30222. return promiseRejectedWith(readerLockException("read from"));
  30223. }
  30224. let resolvePromise;
  30225. let rejectPromise;
  30226. const promise = newPromise((resolve, reject) => {
  30227. resolvePromise = resolve;
  30228. rejectPromise = reject;
  30229. });
  30230. const readIntoRequest = {
  30231. _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
  30232. _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }),
  30233. _errorSteps: (e6) => rejectPromise(e6)
  30234. };
  30235. ReadableStreamBYOBReaderRead(this, view5, min, readIntoRequest);
  30236. return promise;
  30237. }
  30238. /**
  30239. * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
  30240. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
  30241. * from now on; otherwise, the reader will appear closed.
  30242. *
  30243. * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
  30244. * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
  30245. * do so will throw a `TypeError` and leave the reader locked to the stream.
  30246. */
  30247. releaseLock() {
  30248. if (!IsReadableStreamBYOBReader(this)) {
  30249. throw byobReaderBrandCheckException("releaseLock");
  30250. }
  30251. if (this._ownerReadableStream === void 0) {
  30252. return;
  30253. }
  30254. ReadableStreamBYOBReaderRelease(this);
  30255. }
  30256. }
  30257. Object.defineProperties(ReadableStreamBYOBReader.prototype, {
  30258. cancel: { enumerable: true },
  30259. read: { enumerable: true },
  30260. releaseLock: { enumerable: true },
  30261. closed: { enumerable: true }
  30262. });
  30263. setFunctionName(ReadableStreamBYOBReader.prototype.cancel, "cancel");
  30264. setFunctionName(ReadableStreamBYOBReader.prototype.read, "read");
  30265. setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock");
  30266. if (typeof Symbol.toStringTag === "symbol") {
  30267. Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {
  30268. value: "ReadableStreamBYOBReader",
  30269. configurable: true
  30270. });
  30271. }
  30272. function IsReadableStreamBYOBReader(x5) {
  30273. if (!typeIsObject(x5)) {
  30274. return false;
  30275. }
  30276. if (!Object.prototype.hasOwnProperty.call(x5, "_readIntoRequests")) {
  30277. return false;
  30278. }
  30279. return x5 instanceof ReadableStreamBYOBReader;
  30280. }
  30281. function ReadableStreamBYOBReaderRead(reader, view5, min, readIntoRequest) {
  30282. const stream = reader._ownerReadableStream;
  30283. stream._disturbed = true;
  30284. if (stream._state === "errored") {
  30285. readIntoRequest._errorSteps(stream._storedError);
  30286. } else {
  30287. ReadableByteStreamControllerPullInto(stream._readableStreamController, view5, min, readIntoRequest);
  30288. }
  30289. }
  30290. function ReadableStreamBYOBReaderRelease(reader) {
  30291. ReadableStreamReaderGenericRelease(reader);
  30292. const e6 = new TypeError("Reader was released");
  30293. ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6);
  30294. }
  30295. function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6) {
  30296. const readIntoRequests = reader._readIntoRequests;
  30297. reader._readIntoRequests = new SimpleQueue();
  30298. readIntoRequests.forEach((readIntoRequest) => {
  30299. readIntoRequest._errorSteps(e6);
  30300. });
  30301. }
  30302. function byobReaderBrandCheckException(name) {
  30303. return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
  30304. }
  30305. function ExtractHighWaterMark(strategy, defaultHWM) {
  30306. const { highWaterMark } = strategy;
  30307. if (highWaterMark === void 0) {
  30308. return defaultHWM;
  30309. }
  30310. if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
  30311. throw new RangeError("Invalid highWaterMark");
  30312. }
  30313. return highWaterMark;
  30314. }
  30315. function ExtractSizeAlgorithm(strategy) {
  30316. const { size } = strategy;
  30317. if (!size) {
  30318. return () => 1;
  30319. }
  30320. return size;
  30321. }
  30322. function convertQueuingStrategy(init2, context) {
  30323. assertDictionary(init2, context);
  30324. const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark;
  30325. const size = init2 === null || init2 === void 0 ? void 0 : init2.size;
  30326. return {
  30327. highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark),
  30328. size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`)
  30329. };
  30330. }
  30331. function convertQueuingStrategySize(fn, context) {
  30332. assertFunction(fn, context);
  30333. return (chunk) => convertUnrestrictedDouble(fn(chunk));
  30334. }
  30335. function convertUnderlyingSink(original, context) {
  30336. assertDictionary(original, context);
  30337. const abort = original === null || original === void 0 ? void 0 : original.abort;
  30338. const close = original === null || original === void 0 ? void 0 : original.close;
  30339. const start = original === null || original === void 0 ? void 0 : original.start;
  30340. const type = original === null || original === void 0 ? void 0 : original.type;
  30341. const write = original === null || original === void 0 ? void 0 : original.write;
  30342. return {
  30343. abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
  30344. close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
  30345. start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
  30346. write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
  30347. type
  30348. };
  30349. }
  30350. function convertUnderlyingSinkAbortCallback(fn, original, context) {
  30351. assertFunction(fn, context);
  30352. return (reason) => promiseCall(fn, original, [reason]);
  30353. }
  30354. function convertUnderlyingSinkCloseCallback(fn, original, context) {
  30355. assertFunction(fn, context);
  30356. return () => promiseCall(fn, original, []);
  30357. }
  30358. function convertUnderlyingSinkStartCallback(fn, original, context) {
  30359. assertFunction(fn, context);
  30360. return (controller) => reflectCall(fn, original, [controller]);
  30361. }
  30362. function convertUnderlyingSinkWriteCallback(fn, original, context) {
  30363. assertFunction(fn, context);
  30364. return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
  30365. }
  30366. function assertWritableStream(x5, context) {
  30367. if (!IsWritableStream(x5)) {
  30368. throw new TypeError(`${context} is not a WritableStream.`);
  30369. }
  30370. }
  30371. function isAbortSignal2(value) {
  30372. if (typeof value !== "object" || value === null) {
  30373. return false;
  30374. }
  30375. try {
  30376. return typeof value.aborted === "boolean";
  30377. } catch (_a16) {
  30378. return false;
  30379. }
  30380. }
  30381. const supportsAbortController = typeof AbortController === "function";
  30382. function createAbortController() {
  30383. if (supportsAbortController) {
  30384. return new AbortController();
  30385. }
  30386. return void 0;
  30387. }
  30388. class WritableStream {
  30389. constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
  30390. if (rawUnderlyingSink === void 0) {
  30391. rawUnderlyingSink = null;
  30392. } else {
  30393. assertObject(rawUnderlyingSink, "First parameter");
  30394. }
  30395. const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
  30396. const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter");
  30397. InitializeWritableStream(this);
  30398. const type = underlyingSink.type;
  30399. if (type !== void 0) {
  30400. throw new RangeError("Invalid type is specified");
  30401. }
  30402. const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
  30403. const highWaterMark = ExtractHighWaterMark(strategy, 1);
  30404. SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
  30405. }
  30406. /**
  30407. * Returns whether or not the writable stream is locked to a writer.
  30408. */
  30409. get locked() {
  30410. if (!IsWritableStream(this)) {
  30411. throw streamBrandCheckException$2("locked");
  30412. }
  30413. return IsWritableStreamLocked(this);
  30414. }
  30415. /**
  30416. * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
  30417. * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
  30418. * mechanism of the underlying sink.
  30419. *
  30420. * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
  30421. * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
  30422. * the stream) if the stream is currently locked.
  30423. */
  30424. abort(reason = void 0) {
  30425. if (!IsWritableStream(this)) {
  30426. return promiseRejectedWith(streamBrandCheckException$2("abort"));
  30427. }
  30428. if (IsWritableStreamLocked(this)) {
  30429. return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer"));
  30430. }
  30431. return WritableStreamAbort(this, reason);
  30432. }
  30433. /**
  30434. * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
  30435. * close behavior. During this time any further attempts to write will fail (without erroring the stream).
  30436. *
  30437. * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
  30438. * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
  30439. * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
  30440. */
  30441. close() {
  30442. if (!IsWritableStream(this)) {
  30443. return promiseRejectedWith(streamBrandCheckException$2("close"));
  30444. }
  30445. if (IsWritableStreamLocked(this)) {
  30446. return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer"));
  30447. }
  30448. if (WritableStreamCloseQueuedOrInFlight(this)) {
  30449. return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
  30450. }
  30451. return WritableStreamClose(this);
  30452. }
  30453. /**
  30454. * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
  30455. * is locked, no other writer can be acquired until this one is released.
  30456. *
  30457. * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
  30458. * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
  30459. * the same time, which would cause the resulting written data to be unpredictable and probably useless.
  30460. */
  30461. getWriter() {
  30462. if (!IsWritableStream(this)) {
  30463. throw streamBrandCheckException$2("getWriter");
  30464. }
  30465. return AcquireWritableStreamDefaultWriter(this);
  30466. }
  30467. }
  30468. Object.defineProperties(WritableStream.prototype, {
  30469. abort: { enumerable: true },
  30470. close: { enumerable: true },
  30471. getWriter: { enumerable: true },
  30472. locked: { enumerable: true }
  30473. });
  30474. setFunctionName(WritableStream.prototype.abort, "abort");
  30475. setFunctionName(WritableStream.prototype.close, "close");
  30476. setFunctionName(WritableStream.prototype.getWriter, "getWriter");
  30477. if (typeof Symbol.toStringTag === "symbol") {
  30478. Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {
  30479. value: "WritableStream",
  30480. configurable: true
  30481. });
  30482. }
  30483. function AcquireWritableStreamDefaultWriter(stream) {
  30484. return new WritableStreamDefaultWriter(stream);
  30485. }
  30486. function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
  30487. const stream = Object.create(WritableStream.prototype);
  30488. InitializeWritableStream(stream);
  30489. const controller = Object.create(WritableStreamDefaultController.prototype);
  30490. SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
  30491. return stream;
  30492. }
  30493. function InitializeWritableStream(stream) {
  30494. stream._state = "writable";
  30495. stream._storedError = void 0;
  30496. stream._writer = void 0;
  30497. stream._writableStreamController = void 0;
  30498. stream._writeRequests = new SimpleQueue();
  30499. stream._inFlightWriteRequest = void 0;
  30500. stream._closeRequest = void 0;
  30501. stream._inFlightCloseRequest = void 0;
  30502. stream._pendingAbortRequest = void 0;
  30503. stream._backpressure = false;
  30504. }
  30505. function IsWritableStream(x5) {
  30506. if (!typeIsObject(x5)) {
  30507. return false;
  30508. }
  30509. if (!Object.prototype.hasOwnProperty.call(x5, "_writableStreamController")) {
  30510. return false;
  30511. }
  30512. return x5 instanceof WritableStream;
  30513. }
  30514. function IsWritableStreamLocked(stream) {
  30515. if (stream._writer === void 0) {
  30516. return false;
  30517. }
  30518. return true;
  30519. }
  30520. function WritableStreamAbort(stream, reason) {
  30521. var _a16;
  30522. if (stream._state === "closed" || stream._state === "errored") {
  30523. return promiseResolvedWith(void 0);
  30524. }
  30525. stream._writableStreamController._abortReason = reason;
  30526. (_a16 = stream._writableStreamController._abortController) === null || _a16 === void 0 ? void 0 : _a16.abort(reason);
  30527. const state2 = stream._state;
  30528. if (state2 === "closed" || state2 === "errored") {
  30529. return promiseResolvedWith(void 0);
  30530. }
  30531. if (stream._pendingAbortRequest !== void 0) {
  30532. return stream._pendingAbortRequest._promise;
  30533. }
  30534. let wasAlreadyErroring = false;
  30535. if (state2 === "erroring") {
  30536. wasAlreadyErroring = true;
  30537. reason = void 0;
  30538. }
  30539. const promise = newPromise((resolve, reject) => {
  30540. stream._pendingAbortRequest = {
  30541. _promise: void 0,
  30542. _resolve: resolve,
  30543. _reject: reject,
  30544. _reason: reason,
  30545. _wasAlreadyErroring: wasAlreadyErroring
  30546. };
  30547. });
  30548. stream._pendingAbortRequest._promise = promise;
  30549. if (!wasAlreadyErroring) {
  30550. WritableStreamStartErroring(stream, reason);
  30551. }
  30552. return promise;
  30553. }
  30554. function WritableStreamClose(stream) {
  30555. const state2 = stream._state;
  30556. if (state2 === "closed" || state2 === "errored") {
  30557. return promiseRejectedWith(new TypeError(`The stream (in ${state2} state) is not in the writable state and cannot be closed`));
  30558. }
  30559. const promise = newPromise((resolve, reject) => {
  30560. const closeRequest = {
  30561. _resolve: resolve,
  30562. _reject: reject
  30563. };
  30564. stream._closeRequest = closeRequest;
  30565. });
  30566. const writer = stream._writer;
  30567. if (writer !== void 0 && stream._backpressure && state2 === "writable") {
  30568. defaultWriterReadyPromiseResolve(writer);
  30569. }
  30570. WritableStreamDefaultControllerClose(stream._writableStreamController);
  30571. return promise;
  30572. }
  30573. function WritableStreamAddWriteRequest(stream) {
  30574. const promise = newPromise((resolve, reject) => {
  30575. const writeRequest = {
  30576. _resolve: resolve,
  30577. _reject: reject
  30578. };
  30579. stream._writeRequests.push(writeRequest);
  30580. });
  30581. return promise;
  30582. }
  30583. function WritableStreamDealWithRejection(stream, error2) {
  30584. const state2 = stream._state;
  30585. if (state2 === "writable") {
  30586. WritableStreamStartErroring(stream, error2);
  30587. return;
  30588. }
  30589. WritableStreamFinishErroring(stream);
  30590. }
  30591. function WritableStreamStartErroring(stream, reason) {
  30592. const controller = stream._writableStreamController;
  30593. stream._state = "erroring";
  30594. stream._storedError = reason;
  30595. const writer = stream._writer;
  30596. if (writer !== void 0) {
  30597. WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
  30598. }
  30599. if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
  30600. WritableStreamFinishErroring(stream);
  30601. }
  30602. }
  30603. function WritableStreamFinishErroring(stream) {
  30604. stream._state = "errored";
  30605. stream._writableStreamController[ErrorSteps]();
  30606. const storedError = stream._storedError;
  30607. stream._writeRequests.forEach((writeRequest) => {
  30608. writeRequest._reject(storedError);
  30609. });
  30610. stream._writeRequests = new SimpleQueue();
  30611. if (stream._pendingAbortRequest === void 0) {
  30612. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  30613. return;
  30614. }
  30615. const abortRequest = stream._pendingAbortRequest;
  30616. stream._pendingAbortRequest = void 0;
  30617. if (abortRequest._wasAlreadyErroring) {
  30618. abortRequest._reject(storedError);
  30619. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  30620. return;
  30621. }
  30622. const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
  30623. uponPromise(promise, () => {
  30624. abortRequest._resolve();
  30625. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  30626. return null;
  30627. }, (reason) => {
  30628. abortRequest._reject(reason);
  30629. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  30630. return null;
  30631. });
  30632. }
  30633. function WritableStreamFinishInFlightWrite(stream) {
  30634. stream._inFlightWriteRequest._resolve(void 0);
  30635. stream._inFlightWriteRequest = void 0;
  30636. }
  30637. function WritableStreamFinishInFlightWriteWithError(stream, error2) {
  30638. stream._inFlightWriteRequest._reject(error2);
  30639. stream._inFlightWriteRequest = void 0;
  30640. WritableStreamDealWithRejection(stream, error2);
  30641. }
  30642. function WritableStreamFinishInFlightClose(stream) {
  30643. stream._inFlightCloseRequest._resolve(void 0);
  30644. stream._inFlightCloseRequest = void 0;
  30645. const state2 = stream._state;
  30646. if (state2 === "erroring") {
  30647. stream._storedError = void 0;
  30648. if (stream._pendingAbortRequest !== void 0) {
  30649. stream._pendingAbortRequest._resolve();
  30650. stream._pendingAbortRequest = void 0;
  30651. }
  30652. }
  30653. stream._state = "closed";
  30654. const writer = stream._writer;
  30655. if (writer !== void 0) {
  30656. defaultWriterClosedPromiseResolve(writer);
  30657. }
  30658. }
  30659. function WritableStreamFinishInFlightCloseWithError(stream, error2) {
  30660. stream._inFlightCloseRequest._reject(error2);
  30661. stream._inFlightCloseRequest = void 0;
  30662. if (stream._pendingAbortRequest !== void 0) {
  30663. stream._pendingAbortRequest._reject(error2);
  30664. stream._pendingAbortRequest = void 0;
  30665. }
  30666. WritableStreamDealWithRejection(stream, error2);
  30667. }
  30668. function WritableStreamCloseQueuedOrInFlight(stream) {
  30669. if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) {
  30670. return false;
  30671. }
  30672. return true;
  30673. }
  30674. function WritableStreamHasOperationMarkedInFlight(stream) {
  30675. if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) {
  30676. return false;
  30677. }
  30678. return true;
  30679. }
  30680. function WritableStreamMarkCloseRequestInFlight(stream) {
  30681. stream._inFlightCloseRequest = stream._closeRequest;
  30682. stream._closeRequest = void 0;
  30683. }
  30684. function WritableStreamMarkFirstWriteRequestInFlight(stream) {
  30685. stream._inFlightWriteRequest = stream._writeRequests.shift();
  30686. }
  30687. function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
  30688. if (stream._closeRequest !== void 0) {
  30689. stream._closeRequest._reject(stream._storedError);
  30690. stream._closeRequest = void 0;
  30691. }
  30692. const writer = stream._writer;
  30693. if (writer !== void 0) {
  30694. defaultWriterClosedPromiseReject(writer, stream._storedError);
  30695. }
  30696. }
  30697. function WritableStreamUpdateBackpressure(stream, backpressure) {
  30698. const writer = stream._writer;
  30699. if (writer !== void 0 && backpressure !== stream._backpressure) {
  30700. if (backpressure) {
  30701. defaultWriterReadyPromiseReset(writer);
  30702. } else {
  30703. defaultWriterReadyPromiseResolve(writer);
  30704. }
  30705. }
  30706. stream._backpressure = backpressure;
  30707. }
  30708. class WritableStreamDefaultWriter {
  30709. constructor(stream) {
  30710. assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter");
  30711. assertWritableStream(stream, "First parameter");
  30712. if (IsWritableStreamLocked(stream)) {
  30713. throw new TypeError("This stream has already been locked for exclusive writing by another writer");
  30714. }
  30715. this._ownerWritableStream = stream;
  30716. stream._writer = this;
  30717. const state2 = stream._state;
  30718. if (state2 === "writable") {
  30719. if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
  30720. defaultWriterReadyPromiseInitialize(this);
  30721. } else {
  30722. defaultWriterReadyPromiseInitializeAsResolved(this);
  30723. }
  30724. defaultWriterClosedPromiseInitialize(this);
  30725. } else if (state2 === "erroring") {
  30726. defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
  30727. defaultWriterClosedPromiseInitialize(this);
  30728. } else if (state2 === "closed") {
  30729. defaultWriterReadyPromiseInitializeAsResolved(this);
  30730. defaultWriterClosedPromiseInitializeAsResolved(this);
  30731. } else {
  30732. const storedError = stream._storedError;
  30733. defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
  30734. defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
  30735. }
  30736. }
  30737. /**
  30738. * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
  30739. * the writer’s lock is released before the stream finishes closing.
  30740. */
  30741. get closed() {
  30742. if (!IsWritableStreamDefaultWriter(this)) {
  30743. return promiseRejectedWith(defaultWriterBrandCheckException("closed"));
  30744. }
  30745. return this._closedPromise;
  30746. }
  30747. /**
  30748. * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
  30749. * A producer can use this information to determine the right amount of data to write.
  30750. *
  30751. * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
  30752. * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
  30753. * the writer’s lock is released.
  30754. */
  30755. get desiredSize() {
  30756. if (!IsWritableStreamDefaultWriter(this)) {
  30757. throw defaultWriterBrandCheckException("desiredSize");
  30758. }
  30759. if (this._ownerWritableStream === void 0) {
  30760. throw defaultWriterLockException("desiredSize");
  30761. }
  30762. return WritableStreamDefaultWriterGetDesiredSize(this);
  30763. }
  30764. /**
  30765. * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
  30766. * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
  30767. * back to zero or below, the getter will return a new promise that stays pending until the next transition.
  30768. *
  30769. * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
  30770. * rejected.
  30771. */
  30772. get ready() {
  30773. if (!IsWritableStreamDefaultWriter(this)) {
  30774. return promiseRejectedWith(defaultWriterBrandCheckException("ready"));
  30775. }
  30776. return this._readyPromise;
  30777. }
  30778. /**
  30779. * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
  30780. */
  30781. abort(reason = void 0) {
  30782. if (!IsWritableStreamDefaultWriter(this)) {
  30783. return promiseRejectedWith(defaultWriterBrandCheckException("abort"));
  30784. }
  30785. if (this._ownerWritableStream === void 0) {
  30786. return promiseRejectedWith(defaultWriterLockException("abort"));
  30787. }
  30788. return WritableStreamDefaultWriterAbort(this, reason);
  30789. }
  30790. /**
  30791. * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
  30792. */
  30793. close() {
  30794. if (!IsWritableStreamDefaultWriter(this)) {
  30795. return promiseRejectedWith(defaultWriterBrandCheckException("close"));
  30796. }
  30797. const stream = this._ownerWritableStream;
  30798. if (stream === void 0) {
  30799. return promiseRejectedWith(defaultWriterLockException("close"));
  30800. }
  30801. if (WritableStreamCloseQueuedOrInFlight(stream)) {
  30802. return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
  30803. }
  30804. return WritableStreamDefaultWriterClose(this);
  30805. }
  30806. /**
  30807. * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
  30808. * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
  30809. * now on; otherwise, the writer will appear closed.
  30810. *
  30811. * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
  30812. * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
  30813. * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
  30814. * other producers from writing in an interleaved manner.
  30815. */
  30816. releaseLock() {
  30817. if (!IsWritableStreamDefaultWriter(this)) {
  30818. throw defaultWriterBrandCheckException("releaseLock");
  30819. }
  30820. const stream = this._ownerWritableStream;
  30821. if (stream === void 0) {
  30822. return;
  30823. }
  30824. WritableStreamDefaultWriterRelease(this);
  30825. }
  30826. write(chunk = void 0) {
  30827. if (!IsWritableStreamDefaultWriter(this)) {
  30828. return promiseRejectedWith(defaultWriterBrandCheckException("write"));
  30829. }
  30830. if (this._ownerWritableStream === void 0) {
  30831. return promiseRejectedWith(defaultWriterLockException("write to"));
  30832. }
  30833. return WritableStreamDefaultWriterWrite(this, chunk);
  30834. }
  30835. }
  30836. Object.defineProperties(WritableStreamDefaultWriter.prototype, {
  30837. abort: { enumerable: true },
  30838. close: { enumerable: true },
  30839. releaseLock: { enumerable: true },
  30840. write: { enumerable: true },
  30841. closed: { enumerable: true },
  30842. desiredSize: { enumerable: true },
  30843. ready: { enumerable: true }
  30844. });
  30845. setFunctionName(WritableStreamDefaultWriter.prototype.abort, "abort");
  30846. setFunctionName(WritableStreamDefaultWriter.prototype.close, "close");
  30847. setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock");
  30848. setFunctionName(WritableStreamDefaultWriter.prototype.write, "write");
  30849. if (typeof Symbol.toStringTag === "symbol") {
  30850. Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {
  30851. value: "WritableStreamDefaultWriter",
  30852. configurable: true
  30853. });
  30854. }
  30855. function IsWritableStreamDefaultWriter(x5) {
  30856. if (!typeIsObject(x5)) {
  30857. return false;
  30858. }
  30859. if (!Object.prototype.hasOwnProperty.call(x5, "_ownerWritableStream")) {
  30860. return false;
  30861. }
  30862. return x5 instanceof WritableStreamDefaultWriter;
  30863. }
  30864. function WritableStreamDefaultWriterAbort(writer, reason) {
  30865. const stream = writer._ownerWritableStream;
  30866. return WritableStreamAbort(stream, reason);
  30867. }
  30868. function WritableStreamDefaultWriterClose(writer) {
  30869. const stream = writer._ownerWritableStream;
  30870. return WritableStreamClose(stream);
  30871. }
  30872. function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
  30873. const stream = writer._ownerWritableStream;
  30874. const state2 = stream._state;
  30875. if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") {
  30876. return promiseResolvedWith(void 0);
  30877. }
  30878. if (state2 === "errored") {
  30879. return promiseRejectedWith(stream._storedError);
  30880. }
  30881. return WritableStreamDefaultWriterClose(writer);
  30882. }
  30883. function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error2) {
  30884. if (writer._closedPromiseState === "pending") {
  30885. defaultWriterClosedPromiseReject(writer, error2);
  30886. } else {
  30887. defaultWriterClosedPromiseResetToRejected(writer, error2);
  30888. }
  30889. }
  30890. function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error2) {
  30891. if (writer._readyPromiseState === "pending") {
  30892. defaultWriterReadyPromiseReject(writer, error2);
  30893. } else {
  30894. defaultWriterReadyPromiseResetToRejected(writer, error2);
  30895. }
  30896. }
  30897. function WritableStreamDefaultWriterGetDesiredSize(writer) {
  30898. const stream = writer._ownerWritableStream;
  30899. const state2 = stream._state;
  30900. if (state2 === "errored" || state2 === "erroring") {
  30901. return null;
  30902. }
  30903. if (state2 === "closed") {
  30904. return 0;
  30905. }
  30906. return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
  30907. }
  30908. function WritableStreamDefaultWriterRelease(writer) {
  30909. const stream = writer._ownerWritableStream;
  30910. const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
  30911. WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
  30912. WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
  30913. stream._writer = void 0;
  30914. writer._ownerWritableStream = void 0;
  30915. }
  30916. function WritableStreamDefaultWriterWrite(writer, chunk) {
  30917. const stream = writer._ownerWritableStream;
  30918. const controller = stream._writableStreamController;
  30919. const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
  30920. if (stream !== writer._ownerWritableStream) {
  30921. return promiseRejectedWith(defaultWriterLockException("write to"));
  30922. }
  30923. const state2 = stream._state;
  30924. if (state2 === "errored") {
  30925. return promiseRejectedWith(stream._storedError);
  30926. }
  30927. if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") {
  30928. return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to"));
  30929. }
  30930. if (state2 === "erroring") {
  30931. return promiseRejectedWith(stream._storedError);
  30932. }
  30933. const promise = WritableStreamAddWriteRequest(stream);
  30934. WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
  30935. return promise;
  30936. }
  30937. const closeSentinel = {};
  30938. class WritableStreamDefaultController {
  30939. constructor() {
  30940. throw new TypeError("Illegal constructor");
  30941. }
  30942. /**
  30943. * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
  30944. *
  30945. * @deprecated
  30946. * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
  30947. * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
  30948. */
  30949. get abortReason() {
  30950. if (!IsWritableStreamDefaultController(this)) {
  30951. throw defaultControllerBrandCheckException$2("abortReason");
  30952. }
  30953. return this._abortReason;
  30954. }
  30955. /**
  30956. * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
  30957. */
  30958. get signal() {
  30959. if (!IsWritableStreamDefaultController(this)) {
  30960. throw defaultControllerBrandCheckException$2("signal");
  30961. }
  30962. if (this._abortController === void 0) {
  30963. throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");
  30964. }
  30965. return this._abortController.signal;
  30966. }
  30967. /**
  30968. * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
  30969. *
  30970. * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
  30971. * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
  30972. * normal lifecycle of interactions with the underlying sink.
  30973. */
  30974. error(e6 = void 0) {
  30975. if (!IsWritableStreamDefaultController(this)) {
  30976. throw defaultControllerBrandCheckException$2("error");
  30977. }
  30978. const state2 = this._controlledWritableStream._state;
  30979. if (state2 !== "writable") {
  30980. return;
  30981. }
  30982. WritableStreamDefaultControllerError(this, e6);
  30983. }
  30984. /** @internal */
  30985. [AbortSteps](reason) {
  30986. const result = this._abortAlgorithm(reason);
  30987. WritableStreamDefaultControllerClearAlgorithms(this);
  30988. return result;
  30989. }
  30990. /** @internal */
  30991. [ErrorSteps]() {
  30992. ResetQueue(this);
  30993. }
  30994. }
  30995. Object.defineProperties(WritableStreamDefaultController.prototype, {
  30996. abortReason: { enumerable: true },
  30997. signal: { enumerable: true },
  30998. error: { enumerable: true }
  30999. });
  31000. if (typeof Symbol.toStringTag === "symbol") {
  31001. Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {
  31002. value: "WritableStreamDefaultController",
  31003. configurable: true
  31004. });
  31005. }
  31006. function IsWritableStreamDefaultController(x5) {
  31007. if (!typeIsObject(x5)) {
  31008. return false;
  31009. }
  31010. if (!Object.prototype.hasOwnProperty.call(x5, "_controlledWritableStream")) {
  31011. return false;
  31012. }
  31013. return x5 instanceof WritableStreamDefaultController;
  31014. }
  31015. function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
  31016. controller._controlledWritableStream = stream;
  31017. stream._writableStreamController = controller;
  31018. controller._queue = void 0;
  31019. controller._queueTotalSize = void 0;
  31020. ResetQueue(controller);
  31021. controller._abortReason = void 0;
  31022. controller._abortController = createAbortController();
  31023. controller._started = false;
  31024. controller._strategySizeAlgorithm = sizeAlgorithm;
  31025. controller._strategyHWM = highWaterMark;
  31026. controller._writeAlgorithm = writeAlgorithm;
  31027. controller._closeAlgorithm = closeAlgorithm;
  31028. controller._abortAlgorithm = abortAlgorithm;
  31029. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  31030. WritableStreamUpdateBackpressure(stream, backpressure);
  31031. const startResult = startAlgorithm();
  31032. const startPromise = promiseResolvedWith(startResult);
  31033. uponPromise(startPromise, () => {
  31034. controller._started = true;
  31035. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  31036. return null;
  31037. }, (r6) => {
  31038. controller._started = true;
  31039. WritableStreamDealWithRejection(stream, r6);
  31040. return null;
  31041. });
  31042. }
  31043. function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
  31044. const controller = Object.create(WritableStreamDefaultController.prototype);
  31045. let startAlgorithm;
  31046. let writeAlgorithm;
  31047. let closeAlgorithm;
  31048. let abortAlgorithm;
  31049. if (underlyingSink.start !== void 0) {
  31050. startAlgorithm = () => underlyingSink.start(controller);
  31051. } else {
  31052. startAlgorithm = () => void 0;
  31053. }
  31054. if (underlyingSink.write !== void 0) {
  31055. writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller);
  31056. } else {
  31057. writeAlgorithm = () => promiseResolvedWith(void 0);
  31058. }
  31059. if (underlyingSink.close !== void 0) {
  31060. closeAlgorithm = () => underlyingSink.close();
  31061. } else {
  31062. closeAlgorithm = () => promiseResolvedWith(void 0);
  31063. }
  31064. if (underlyingSink.abort !== void 0) {
  31065. abortAlgorithm = (reason) => underlyingSink.abort(reason);
  31066. } else {
  31067. abortAlgorithm = () => promiseResolvedWith(void 0);
  31068. }
  31069. SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
  31070. }
  31071. function WritableStreamDefaultControllerClearAlgorithms(controller) {
  31072. controller._writeAlgorithm = void 0;
  31073. controller._closeAlgorithm = void 0;
  31074. controller._abortAlgorithm = void 0;
  31075. controller._strategySizeAlgorithm = void 0;
  31076. }
  31077. function WritableStreamDefaultControllerClose(controller) {
  31078. EnqueueValueWithSize(controller, closeSentinel, 0);
  31079. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  31080. }
  31081. function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
  31082. try {
  31083. return controller._strategySizeAlgorithm(chunk);
  31084. } catch (chunkSizeE) {
  31085. WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
  31086. return 1;
  31087. }
  31088. }
  31089. function WritableStreamDefaultControllerGetDesiredSize(controller) {
  31090. return controller._strategyHWM - controller._queueTotalSize;
  31091. }
  31092. function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
  31093. try {
  31094. EnqueueValueWithSize(controller, chunk, chunkSize);
  31095. } catch (enqueueE) {
  31096. WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
  31097. return;
  31098. }
  31099. const stream = controller._controlledWritableStream;
  31100. if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") {
  31101. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  31102. WritableStreamUpdateBackpressure(stream, backpressure);
  31103. }
  31104. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  31105. }
  31106. function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
  31107. const stream = controller._controlledWritableStream;
  31108. if (!controller._started) {
  31109. return;
  31110. }
  31111. if (stream._inFlightWriteRequest !== void 0) {
  31112. return;
  31113. }
  31114. const state2 = stream._state;
  31115. if (state2 === "erroring") {
  31116. WritableStreamFinishErroring(stream);
  31117. return;
  31118. }
  31119. if (controller._queue.length === 0) {
  31120. return;
  31121. }
  31122. const value = PeekQueueValue(controller);
  31123. if (value === closeSentinel) {
  31124. WritableStreamDefaultControllerProcessClose(controller);
  31125. } else {
  31126. WritableStreamDefaultControllerProcessWrite(controller, value);
  31127. }
  31128. }
  31129. function WritableStreamDefaultControllerErrorIfNeeded(controller, error2) {
  31130. if (controller._controlledWritableStream._state === "writable") {
  31131. WritableStreamDefaultControllerError(controller, error2);
  31132. }
  31133. }
  31134. function WritableStreamDefaultControllerProcessClose(controller) {
  31135. const stream = controller._controlledWritableStream;
  31136. WritableStreamMarkCloseRequestInFlight(stream);
  31137. DequeueValue(controller);
  31138. const sinkClosePromise = controller._closeAlgorithm();
  31139. WritableStreamDefaultControllerClearAlgorithms(controller);
  31140. uponPromise(sinkClosePromise, () => {
  31141. WritableStreamFinishInFlightClose(stream);
  31142. return null;
  31143. }, (reason) => {
  31144. WritableStreamFinishInFlightCloseWithError(stream, reason);
  31145. return null;
  31146. });
  31147. }
  31148. function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
  31149. const stream = controller._controlledWritableStream;
  31150. WritableStreamMarkFirstWriteRequestInFlight(stream);
  31151. const sinkWritePromise = controller._writeAlgorithm(chunk);
  31152. uponPromise(sinkWritePromise, () => {
  31153. WritableStreamFinishInFlightWrite(stream);
  31154. const state2 = stream._state;
  31155. DequeueValue(controller);
  31156. if (!WritableStreamCloseQueuedOrInFlight(stream) && state2 === "writable") {
  31157. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  31158. WritableStreamUpdateBackpressure(stream, backpressure);
  31159. }
  31160. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  31161. return null;
  31162. }, (reason) => {
  31163. if (stream._state === "writable") {
  31164. WritableStreamDefaultControllerClearAlgorithms(controller);
  31165. }
  31166. WritableStreamFinishInFlightWriteWithError(stream, reason);
  31167. return null;
  31168. });
  31169. }
  31170. function WritableStreamDefaultControllerGetBackpressure(controller) {
  31171. const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
  31172. return desiredSize <= 0;
  31173. }
  31174. function WritableStreamDefaultControllerError(controller, error2) {
  31175. const stream = controller._controlledWritableStream;
  31176. WritableStreamDefaultControllerClearAlgorithms(controller);
  31177. WritableStreamStartErroring(stream, error2);
  31178. }
  31179. function streamBrandCheckException$2(name) {
  31180. return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
  31181. }
  31182. function defaultControllerBrandCheckException$2(name) {
  31183. return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
  31184. }
  31185. function defaultWriterBrandCheckException(name) {
  31186. return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
  31187. }
  31188. function defaultWriterLockException(name) {
  31189. return new TypeError("Cannot " + name + " a stream using a released writer");
  31190. }
  31191. function defaultWriterClosedPromiseInitialize(writer) {
  31192. writer._closedPromise = newPromise((resolve, reject) => {
  31193. writer._closedPromise_resolve = resolve;
  31194. writer._closedPromise_reject = reject;
  31195. writer._closedPromiseState = "pending";
  31196. });
  31197. }
  31198. function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
  31199. defaultWriterClosedPromiseInitialize(writer);
  31200. defaultWriterClosedPromiseReject(writer, reason);
  31201. }
  31202. function defaultWriterClosedPromiseInitializeAsResolved(writer) {
  31203. defaultWriterClosedPromiseInitialize(writer);
  31204. defaultWriterClosedPromiseResolve(writer);
  31205. }
  31206. function defaultWriterClosedPromiseReject(writer, reason) {
  31207. if (writer._closedPromise_reject === void 0) {
  31208. return;
  31209. }
  31210. setPromiseIsHandledToTrue(writer._closedPromise);
  31211. writer._closedPromise_reject(reason);
  31212. writer._closedPromise_resolve = void 0;
  31213. writer._closedPromise_reject = void 0;
  31214. writer._closedPromiseState = "rejected";
  31215. }
  31216. function defaultWriterClosedPromiseResetToRejected(writer, reason) {
  31217. defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
  31218. }
  31219. function defaultWriterClosedPromiseResolve(writer) {
  31220. if (writer._closedPromise_resolve === void 0) {
  31221. return;
  31222. }
  31223. writer._closedPromise_resolve(void 0);
  31224. writer._closedPromise_resolve = void 0;
  31225. writer._closedPromise_reject = void 0;
  31226. writer._closedPromiseState = "resolved";
  31227. }
  31228. function defaultWriterReadyPromiseInitialize(writer) {
  31229. writer._readyPromise = newPromise((resolve, reject) => {
  31230. writer._readyPromise_resolve = resolve;
  31231. writer._readyPromise_reject = reject;
  31232. });
  31233. writer._readyPromiseState = "pending";
  31234. }
  31235. function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
  31236. defaultWriterReadyPromiseInitialize(writer);
  31237. defaultWriterReadyPromiseReject(writer, reason);
  31238. }
  31239. function defaultWriterReadyPromiseInitializeAsResolved(writer) {
  31240. defaultWriterReadyPromiseInitialize(writer);
  31241. defaultWriterReadyPromiseResolve(writer);
  31242. }
  31243. function defaultWriterReadyPromiseReject(writer, reason) {
  31244. if (writer._readyPromise_reject === void 0) {
  31245. return;
  31246. }
  31247. setPromiseIsHandledToTrue(writer._readyPromise);
  31248. writer._readyPromise_reject(reason);
  31249. writer._readyPromise_resolve = void 0;
  31250. writer._readyPromise_reject = void 0;
  31251. writer._readyPromiseState = "rejected";
  31252. }
  31253. function defaultWriterReadyPromiseReset(writer) {
  31254. defaultWriterReadyPromiseInitialize(writer);
  31255. }
  31256. function defaultWriterReadyPromiseResetToRejected(writer, reason) {
  31257. defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
  31258. }
  31259. function defaultWriterReadyPromiseResolve(writer) {
  31260. if (writer._readyPromise_resolve === void 0) {
  31261. return;
  31262. }
  31263. writer._readyPromise_resolve(void 0);
  31264. writer._readyPromise_resolve = void 0;
  31265. writer._readyPromise_reject = void 0;
  31266. writer._readyPromiseState = "fulfilled";
  31267. }
  31268. function getGlobals() {
  31269. if (typeof globalThis !== "undefined") {
  31270. return globalThis;
  31271. } else if (typeof self !== "undefined") {
  31272. return self;
  31273. } else if (typeof global !== "undefined") {
  31274. return global;
  31275. }
  31276. return void 0;
  31277. }
  31278. const globals = getGlobals();
  31279. function isDOMExceptionConstructor(ctor) {
  31280. if (!(typeof ctor === "function" || typeof ctor === "object")) {
  31281. return false;
  31282. }
  31283. if (ctor.name !== "DOMException") {
  31284. return false;
  31285. }
  31286. try {
  31287. new ctor();
  31288. return true;
  31289. } catch (_a16) {
  31290. return false;
  31291. }
  31292. }
  31293. function getFromGlobal() {
  31294. const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
  31295. return isDOMExceptionConstructor(ctor) ? ctor : void 0;
  31296. }
  31297. function createPolyfill() {
  31298. const ctor = function DOMException3(message, name) {
  31299. this.message = message || "";
  31300. this.name = name || "Error";
  31301. if (Error.captureStackTrace) {
  31302. Error.captureStackTrace(this, this.constructor);
  31303. }
  31304. };
  31305. setFunctionName(ctor, "DOMException");
  31306. ctor.prototype = Object.create(Error.prototype);
  31307. Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true });
  31308. return ctor;
  31309. }
  31310. const DOMException2 = getFromGlobal() || createPolyfill();
  31311. function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
  31312. const reader = AcquireReadableStreamDefaultReader(source);
  31313. const writer = AcquireWritableStreamDefaultWriter(dest);
  31314. source._disturbed = true;
  31315. let shuttingDown = false;
  31316. let currentWrite = promiseResolvedWith(void 0);
  31317. return newPromise((resolve, reject) => {
  31318. let abortAlgorithm;
  31319. if (signal !== void 0) {
  31320. abortAlgorithm = () => {
  31321. const error2 = signal.reason !== void 0 ? signal.reason : new DOMException2("Aborted", "AbortError");
  31322. const actions = [];
  31323. if (!preventAbort) {
  31324. actions.push(() => {
  31325. if (dest._state === "writable") {
  31326. return WritableStreamAbort(dest, error2);
  31327. }
  31328. return promiseResolvedWith(void 0);
  31329. });
  31330. }
  31331. if (!preventCancel) {
  31332. actions.push(() => {
  31333. if (source._state === "readable") {
  31334. return ReadableStreamCancel(source, error2);
  31335. }
  31336. return promiseResolvedWith(void 0);
  31337. });
  31338. }
  31339. shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error2);
  31340. };
  31341. if (signal.aborted) {
  31342. abortAlgorithm();
  31343. return;
  31344. }
  31345. signal.addEventListener("abort", abortAlgorithm);
  31346. }
  31347. function pipeLoop() {
  31348. return newPromise((resolveLoop, rejectLoop) => {
  31349. function next(done) {
  31350. if (done) {
  31351. resolveLoop();
  31352. } else {
  31353. PerformPromiseThen(pipeStep(), next, rejectLoop);
  31354. }
  31355. }
  31356. next(false);
  31357. });
  31358. }
  31359. function pipeStep() {
  31360. if (shuttingDown) {
  31361. return promiseResolvedWith(true);
  31362. }
  31363. return PerformPromiseThen(writer._readyPromise, () => {
  31364. return newPromise((resolveRead, rejectRead) => {
  31365. ReadableStreamDefaultReaderRead(reader, {
  31366. _chunkSteps: (chunk) => {
  31367. currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2);
  31368. resolveRead(false);
  31369. },
  31370. _closeSteps: () => resolveRead(true),
  31371. _errorSteps: rejectRead
  31372. });
  31373. });
  31374. });
  31375. }
  31376. isOrBecomesErrored(source, reader._closedPromise, (storedError) => {
  31377. if (!preventAbort) {
  31378. shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
  31379. } else {
  31380. shutdown(true, storedError);
  31381. }
  31382. return null;
  31383. });
  31384. isOrBecomesErrored(dest, writer._closedPromise, (storedError) => {
  31385. if (!preventCancel) {
  31386. shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
  31387. } else {
  31388. shutdown(true, storedError);
  31389. }
  31390. return null;
  31391. });
  31392. isOrBecomesClosed(source, reader._closedPromise, () => {
  31393. if (!preventClose) {
  31394. shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
  31395. } else {
  31396. shutdown();
  31397. }
  31398. return null;
  31399. });
  31400. if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") {
  31401. const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it");
  31402. if (!preventCancel) {
  31403. shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
  31404. } else {
  31405. shutdown(true, destClosed);
  31406. }
  31407. }
  31408. setPromiseIsHandledToTrue(pipeLoop());
  31409. function waitForWritesToFinish() {
  31410. const oldCurrentWrite = currentWrite;
  31411. return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0);
  31412. }
  31413. function isOrBecomesErrored(stream, promise, action) {
  31414. if (stream._state === "errored") {
  31415. action(stream._storedError);
  31416. } else {
  31417. uponRejection(promise, action);
  31418. }
  31419. }
  31420. function isOrBecomesClosed(stream, promise, action) {
  31421. if (stream._state === "closed") {
  31422. action();
  31423. } else {
  31424. uponFulfillment(promise, action);
  31425. }
  31426. }
  31427. function shutdownWithAction(action, originalIsError, originalError) {
  31428. if (shuttingDown) {
  31429. return;
  31430. }
  31431. shuttingDown = true;
  31432. if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
  31433. uponFulfillment(waitForWritesToFinish(), doTheRest);
  31434. } else {
  31435. doTheRest();
  31436. }
  31437. function doTheRest() {
  31438. uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError));
  31439. return null;
  31440. }
  31441. }
  31442. function shutdown(isError, error2) {
  31443. if (shuttingDown) {
  31444. return;
  31445. }
  31446. shuttingDown = true;
  31447. if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
  31448. uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error2));
  31449. } else {
  31450. finalize(isError, error2);
  31451. }
  31452. }
  31453. function finalize(isError, error2) {
  31454. WritableStreamDefaultWriterRelease(writer);
  31455. ReadableStreamReaderGenericRelease(reader);
  31456. if (signal !== void 0) {
  31457. signal.removeEventListener("abort", abortAlgorithm);
  31458. }
  31459. if (isError) {
  31460. reject(error2);
  31461. } else {
  31462. resolve(void 0);
  31463. }
  31464. return null;
  31465. }
  31466. });
  31467. }
  31468. class ReadableStreamDefaultController {
  31469. constructor() {
  31470. throw new TypeError("Illegal constructor");
  31471. }
  31472. /**
  31473. * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
  31474. * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
  31475. */
  31476. get desiredSize() {
  31477. if (!IsReadableStreamDefaultController(this)) {
  31478. throw defaultControllerBrandCheckException$1("desiredSize");
  31479. }
  31480. return ReadableStreamDefaultControllerGetDesiredSize(this);
  31481. }
  31482. /**
  31483. * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
  31484. * the stream, but once those are read, the stream will become closed.
  31485. */
  31486. close() {
  31487. if (!IsReadableStreamDefaultController(this)) {
  31488. throw defaultControllerBrandCheckException$1("close");
  31489. }
  31490. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
  31491. throw new TypeError("The stream is not in a state that permits close");
  31492. }
  31493. ReadableStreamDefaultControllerClose(this);
  31494. }
  31495. enqueue(chunk = void 0) {
  31496. if (!IsReadableStreamDefaultController(this)) {
  31497. throw defaultControllerBrandCheckException$1("enqueue");
  31498. }
  31499. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
  31500. throw new TypeError("The stream is not in a state that permits enqueue");
  31501. }
  31502. return ReadableStreamDefaultControllerEnqueue(this, chunk);
  31503. }
  31504. /**
  31505. * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
  31506. */
  31507. error(e6 = void 0) {
  31508. if (!IsReadableStreamDefaultController(this)) {
  31509. throw defaultControllerBrandCheckException$1("error");
  31510. }
  31511. ReadableStreamDefaultControllerError(this, e6);
  31512. }
  31513. /** @internal */
  31514. [CancelSteps](reason) {
  31515. ResetQueue(this);
  31516. const result = this._cancelAlgorithm(reason);
  31517. ReadableStreamDefaultControllerClearAlgorithms(this);
  31518. return result;
  31519. }
  31520. /** @internal */
  31521. [PullSteps](readRequest) {
  31522. const stream = this._controlledReadableStream;
  31523. if (this._queue.length > 0) {
  31524. const chunk = DequeueValue(this);
  31525. if (this._closeRequested && this._queue.length === 0) {
  31526. ReadableStreamDefaultControllerClearAlgorithms(this);
  31527. ReadableStreamClose(stream);
  31528. } else {
  31529. ReadableStreamDefaultControllerCallPullIfNeeded(this);
  31530. }
  31531. readRequest._chunkSteps(chunk);
  31532. } else {
  31533. ReadableStreamAddReadRequest(stream, readRequest);
  31534. ReadableStreamDefaultControllerCallPullIfNeeded(this);
  31535. }
  31536. }
  31537. /** @internal */
  31538. [ReleaseSteps]() {
  31539. }
  31540. }
  31541. Object.defineProperties(ReadableStreamDefaultController.prototype, {
  31542. close: { enumerable: true },
  31543. enqueue: { enumerable: true },
  31544. error: { enumerable: true },
  31545. desiredSize: { enumerable: true }
  31546. });
  31547. setFunctionName(ReadableStreamDefaultController.prototype.close, "close");
  31548. setFunctionName(ReadableStreamDefaultController.prototype.enqueue, "enqueue");
  31549. setFunctionName(ReadableStreamDefaultController.prototype.error, "error");
  31550. if (typeof Symbol.toStringTag === "symbol") {
  31551. Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {
  31552. value: "ReadableStreamDefaultController",
  31553. configurable: true
  31554. });
  31555. }
  31556. function IsReadableStreamDefaultController(x5) {
  31557. if (!typeIsObject(x5)) {
  31558. return false;
  31559. }
  31560. if (!Object.prototype.hasOwnProperty.call(x5, "_controlledReadableStream")) {
  31561. return false;
  31562. }
  31563. return x5 instanceof ReadableStreamDefaultController;
  31564. }
  31565. function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
  31566. const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
  31567. if (!shouldPull) {
  31568. return;
  31569. }
  31570. if (controller._pulling) {
  31571. controller._pullAgain = true;
  31572. return;
  31573. }
  31574. controller._pulling = true;
  31575. const pullPromise = controller._pullAlgorithm();
  31576. uponPromise(pullPromise, () => {
  31577. controller._pulling = false;
  31578. if (controller._pullAgain) {
  31579. controller._pullAgain = false;
  31580. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  31581. }
  31582. return null;
  31583. }, (e6) => {
  31584. ReadableStreamDefaultControllerError(controller, e6);
  31585. return null;
  31586. });
  31587. }
  31588. function ReadableStreamDefaultControllerShouldCallPull(controller) {
  31589. const stream = controller._controlledReadableStream;
  31590. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  31591. return false;
  31592. }
  31593. if (!controller._started) {
  31594. return false;
  31595. }
  31596. if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  31597. return true;
  31598. }
  31599. const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
  31600. if (desiredSize > 0) {
  31601. return true;
  31602. }
  31603. return false;
  31604. }
  31605. function ReadableStreamDefaultControllerClearAlgorithms(controller) {
  31606. controller._pullAlgorithm = void 0;
  31607. controller._cancelAlgorithm = void 0;
  31608. controller._strategySizeAlgorithm = void 0;
  31609. }
  31610. function ReadableStreamDefaultControllerClose(controller) {
  31611. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  31612. return;
  31613. }
  31614. const stream = controller._controlledReadableStream;
  31615. controller._closeRequested = true;
  31616. if (controller._queue.length === 0) {
  31617. ReadableStreamDefaultControllerClearAlgorithms(controller);
  31618. ReadableStreamClose(stream);
  31619. }
  31620. }
  31621. function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
  31622. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  31623. return;
  31624. }
  31625. const stream = controller._controlledReadableStream;
  31626. if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  31627. ReadableStreamFulfillReadRequest(stream, chunk, false);
  31628. } else {
  31629. let chunkSize;
  31630. try {
  31631. chunkSize = controller._strategySizeAlgorithm(chunk);
  31632. } catch (chunkSizeE) {
  31633. ReadableStreamDefaultControllerError(controller, chunkSizeE);
  31634. throw chunkSizeE;
  31635. }
  31636. try {
  31637. EnqueueValueWithSize(controller, chunk, chunkSize);
  31638. } catch (enqueueE) {
  31639. ReadableStreamDefaultControllerError(controller, enqueueE);
  31640. throw enqueueE;
  31641. }
  31642. }
  31643. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  31644. }
  31645. function ReadableStreamDefaultControllerError(controller, e6) {
  31646. const stream = controller._controlledReadableStream;
  31647. if (stream._state !== "readable") {
  31648. return;
  31649. }
  31650. ResetQueue(controller);
  31651. ReadableStreamDefaultControllerClearAlgorithms(controller);
  31652. ReadableStreamError(stream, e6);
  31653. }
  31654. function ReadableStreamDefaultControllerGetDesiredSize(controller) {
  31655. const state2 = controller._controlledReadableStream._state;
  31656. if (state2 === "errored") {
  31657. return null;
  31658. }
  31659. if (state2 === "closed") {
  31660. return 0;
  31661. }
  31662. return controller._strategyHWM - controller._queueTotalSize;
  31663. }
  31664. function ReadableStreamDefaultControllerHasBackpressure(controller) {
  31665. if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
  31666. return false;
  31667. }
  31668. return true;
  31669. }
  31670. function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
  31671. const state2 = controller._controlledReadableStream._state;
  31672. if (!controller._closeRequested && state2 === "readable") {
  31673. return true;
  31674. }
  31675. return false;
  31676. }
  31677. function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
  31678. controller._controlledReadableStream = stream;
  31679. controller._queue = void 0;
  31680. controller._queueTotalSize = void 0;
  31681. ResetQueue(controller);
  31682. controller._started = false;
  31683. controller._closeRequested = false;
  31684. controller._pullAgain = false;
  31685. controller._pulling = false;
  31686. controller._strategySizeAlgorithm = sizeAlgorithm;
  31687. controller._strategyHWM = highWaterMark;
  31688. controller._pullAlgorithm = pullAlgorithm;
  31689. controller._cancelAlgorithm = cancelAlgorithm;
  31690. stream._readableStreamController = controller;
  31691. const startResult = startAlgorithm();
  31692. uponPromise(promiseResolvedWith(startResult), () => {
  31693. controller._started = true;
  31694. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  31695. return null;
  31696. }, (r6) => {
  31697. ReadableStreamDefaultControllerError(controller, r6);
  31698. return null;
  31699. });
  31700. }
  31701. function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
  31702. const controller = Object.create(ReadableStreamDefaultController.prototype);
  31703. let startAlgorithm;
  31704. let pullAlgorithm;
  31705. let cancelAlgorithm;
  31706. if (underlyingSource.start !== void 0) {
  31707. startAlgorithm = () => underlyingSource.start(controller);
  31708. } else {
  31709. startAlgorithm = () => void 0;
  31710. }
  31711. if (underlyingSource.pull !== void 0) {
  31712. pullAlgorithm = () => underlyingSource.pull(controller);
  31713. } else {
  31714. pullAlgorithm = () => promiseResolvedWith(void 0);
  31715. }
  31716. if (underlyingSource.cancel !== void 0) {
  31717. cancelAlgorithm = (reason) => underlyingSource.cancel(reason);
  31718. } else {
  31719. cancelAlgorithm = () => promiseResolvedWith(void 0);
  31720. }
  31721. SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
  31722. }
  31723. function defaultControllerBrandCheckException$1(name) {
  31724. return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
  31725. }
  31726. function ReadableStreamTee(stream, cloneForBranch2) {
  31727. if (IsReadableByteStreamController(stream._readableStreamController)) {
  31728. return ReadableByteStreamTee(stream);
  31729. }
  31730. return ReadableStreamDefaultTee(stream);
  31731. }
  31732. function ReadableStreamDefaultTee(stream, cloneForBranch2) {
  31733. const reader = AcquireReadableStreamDefaultReader(stream);
  31734. let reading = false;
  31735. let readAgain = false;
  31736. let canceled1 = false;
  31737. let canceled2 = false;
  31738. let reason1;
  31739. let reason2;
  31740. let branch1;
  31741. let branch2;
  31742. let resolveCancelPromise;
  31743. const cancelPromise = newPromise((resolve) => {
  31744. resolveCancelPromise = resolve;
  31745. });
  31746. function pullAlgorithm() {
  31747. if (reading) {
  31748. readAgain = true;
  31749. return promiseResolvedWith(void 0);
  31750. }
  31751. reading = true;
  31752. const readRequest = {
  31753. _chunkSteps: (chunk) => {
  31754. _queueMicrotask(() => {
  31755. readAgain = false;
  31756. const chunk1 = chunk;
  31757. const chunk2 = chunk;
  31758. if (!canceled1) {
  31759. ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
  31760. }
  31761. if (!canceled2) {
  31762. ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
  31763. }
  31764. reading = false;
  31765. if (readAgain) {
  31766. pullAlgorithm();
  31767. }
  31768. });
  31769. },
  31770. _closeSteps: () => {
  31771. reading = false;
  31772. if (!canceled1) {
  31773. ReadableStreamDefaultControllerClose(branch1._readableStreamController);
  31774. }
  31775. if (!canceled2) {
  31776. ReadableStreamDefaultControllerClose(branch2._readableStreamController);
  31777. }
  31778. if (!canceled1 || !canceled2) {
  31779. resolveCancelPromise(void 0);
  31780. }
  31781. },
  31782. _errorSteps: () => {
  31783. reading = false;
  31784. }
  31785. };
  31786. ReadableStreamDefaultReaderRead(reader, readRequest);
  31787. return promiseResolvedWith(void 0);
  31788. }
  31789. function cancel1Algorithm(reason) {
  31790. canceled1 = true;
  31791. reason1 = reason;
  31792. if (canceled2) {
  31793. const compositeReason = CreateArrayFromList([reason1, reason2]);
  31794. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  31795. resolveCancelPromise(cancelResult);
  31796. }
  31797. return cancelPromise;
  31798. }
  31799. function cancel2Algorithm(reason) {
  31800. canceled2 = true;
  31801. reason2 = reason;
  31802. if (canceled1) {
  31803. const compositeReason = CreateArrayFromList([reason1, reason2]);
  31804. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  31805. resolveCancelPromise(cancelResult);
  31806. }
  31807. return cancelPromise;
  31808. }
  31809. function startAlgorithm() {
  31810. }
  31811. branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
  31812. branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
  31813. uponRejection(reader._closedPromise, (r6) => {
  31814. ReadableStreamDefaultControllerError(branch1._readableStreamController, r6);
  31815. ReadableStreamDefaultControllerError(branch2._readableStreamController, r6);
  31816. if (!canceled1 || !canceled2) {
  31817. resolveCancelPromise(void 0);
  31818. }
  31819. return null;
  31820. });
  31821. return [branch1, branch2];
  31822. }
  31823. function ReadableByteStreamTee(stream) {
  31824. let reader = AcquireReadableStreamDefaultReader(stream);
  31825. let reading = false;
  31826. let readAgainForBranch1 = false;
  31827. let readAgainForBranch2 = false;
  31828. let canceled1 = false;
  31829. let canceled2 = false;
  31830. let reason1;
  31831. let reason2;
  31832. let branch1;
  31833. let branch2;
  31834. let resolveCancelPromise;
  31835. const cancelPromise = newPromise((resolve) => {
  31836. resolveCancelPromise = resolve;
  31837. });
  31838. function forwardReaderError(thisReader) {
  31839. uponRejection(thisReader._closedPromise, (r6) => {
  31840. if (thisReader !== reader) {
  31841. return null;
  31842. }
  31843. ReadableByteStreamControllerError(branch1._readableStreamController, r6);
  31844. ReadableByteStreamControllerError(branch2._readableStreamController, r6);
  31845. if (!canceled1 || !canceled2) {
  31846. resolveCancelPromise(void 0);
  31847. }
  31848. return null;
  31849. });
  31850. }
  31851. function pullWithDefaultReader() {
  31852. if (IsReadableStreamBYOBReader(reader)) {
  31853. ReadableStreamReaderGenericRelease(reader);
  31854. reader = AcquireReadableStreamDefaultReader(stream);
  31855. forwardReaderError(reader);
  31856. }
  31857. const readRequest = {
  31858. _chunkSteps: (chunk) => {
  31859. _queueMicrotask(() => {
  31860. readAgainForBranch1 = false;
  31861. readAgainForBranch2 = false;
  31862. const chunk1 = chunk;
  31863. let chunk2 = chunk;
  31864. if (!canceled1 && !canceled2) {
  31865. try {
  31866. chunk2 = CloneAsUint8Array(chunk);
  31867. } catch (cloneE) {
  31868. ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
  31869. ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
  31870. resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
  31871. return;
  31872. }
  31873. }
  31874. if (!canceled1) {
  31875. ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
  31876. }
  31877. if (!canceled2) {
  31878. ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
  31879. }
  31880. reading = false;
  31881. if (readAgainForBranch1) {
  31882. pull1Algorithm();
  31883. } else if (readAgainForBranch2) {
  31884. pull2Algorithm();
  31885. }
  31886. });
  31887. },
  31888. _closeSteps: () => {
  31889. reading = false;
  31890. if (!canceled1) {
  31891. ReadableByteStreamControllerClose(branch1._readableStreamController);
  31892. }
  31893. if (!canceled2) {
  31894. ReadableByteStreamControllerClose(branch2._readableStreamController);
  31895. }
  31896. if (branch1._readableStreamController._pendingPullIntos.length > 0) {
  31897. ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
  31898. }
  31899. if (branch2._readableStreamController._pendingPullIntos.length > 0) {
  31900. ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
  31901. }
  31902. if (!canceled1 || !canceled2) {
  31903. resolveCancelPromise(void 0);
  31904. }
  31905. },
  31906. _errorSteps: () => {
  31907. reading = false;
  31908. }
  31909. };
  31910. ReadableStreamDefaultReaderRead(reader, readRequest);
  31911. }
  31912. function pullWithBYOBReader(view5, forBranch2) {
  31913. if (IsReadableStreamDefaultReader(reader)) {
  31914. ReadableStreamReaderGenericRelease(reader);
  31915. reader = AcquireReadableStreamBYOBReader(stream);
  31916. forwardReaderError(reader);
  31917. }
  31918. const byobBranch = forBranch2 ? branch2 : branch1;
  31919. const otherBranch = forBranch2 ? branch1 : branch2;
  31920. const readIntoRequest = {
  31921. _chunkSteps: (chunk) => {
  31922. _queueMicrotask(() => {
  31923. readAgainForBranch1 = false;
  31924. readAgainForBranch2 = false;
  31925. const byobCanceled = forBranch2 ? canceled2 : canceled1;
  31926. const otherCanceled = forBranch2 ? canceled1 : canceled2;
  31927. if (!otherCanceled) {
  31928. let clonedChunk;
  31929. try {
  31930. clonedChunk = CloneAsUint8Array(chunk);
  31931. } catch (cloneE) {
  31932. ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
  31933. ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
  31934. resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
  31935. return;
  31936. }
  31937. if (!byobCanceled) {
  31938. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  31939. }
  31940. ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
  31941. } else if (!byobCanceled) {
  31942. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  31943. }
  31944. reading = false;
  31945. if (readAgainForBranch1) {
  31946. pull1Algorithm();
  31947. } else if (readAgainForBranch2) {
  31948. pull2Algorithm();
  31949. }
  31950. });
  31951. },
  31952. _closeSteps: (chunk) => {
  31953. reading = false;
  31954. const byobCanceled = forBranch2 ? canceled2 : canceled1;
  31955. const otherCanceled = forBranch2 ? canceled1 : canceled2;
  31956. if (!byobCanceled) {
  31957. ReadableByteStreamControllerClose(byobBranch._readableStreamController);
  31958. }
  31959. if (!otherCanceled) {
  31960. ReadableByteStreamControllerClose(otherBranch._readableStreamController);
  31961. }
  31962. if (chunk !== void 0) {
  31963. if (!byobCanceled) {
  31964. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  31965. }
  31966. if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
  31967. ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
  31968. }
  31969. }
  31970. if (!byobCanceled || !otherCanceled) {
  31971. resolveCancelPromise(void 0);
  31972. }
  31973. },
  31974. _errorSteps: () => {
  31975. reading = false;
  31976. }
  31977. };
  31978. ReadableStreamBYOBReaderRead(reader, view5, 1, readIntoRequest);
  31979. }
  31980. function pull1Algorithm() {
  31981. if (reading) {
  31982. readAgainForBranch1 = true;
  31983. return promiseResolvedWith(void 0);
  31984. }
  31985. reading = true;
  31986. const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
  31987. if (byobRequest === null) {
  31988. pullWithDefaultReader();
  31989. } else {
  31990. pullWithBYOBReader(byobRequest._view, false);
  31991. }
  31992. return promiseResolvedWith(void 0);
  31993. }
  31994. function pull2Algorithm() {
  31995. if (reading) {
  31996. readAgainForBranch2 = true;
  31997. return promiseResolvedWith(void 0);
  31998. }
  31999. reading = true;
  32000. const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
  32001. if (byobRequest === null) {
  32002. pullWithDefaultReader();
  32003. } else {
  32004. pullWithBYOBReader(byobRequest._view, true);
  32005. }
  32006. return promiseResolvedWith(void 0);
  32007. }
  32008. function cancel1Algorithm(reason) {
  32009. canceled1 = true;
  32010. reason1 = reason;
  32011. if (canceled2) {
  32012. const compositeReason = CreateArrayFromList([reason1, reason2]);
  32013. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  32014. resolveCancelPromise(cancelResult);
  32015. }
  32016. return cancelPromise;
  32017. }
  32018. function cancel2Algorithm(reason) {
  32019. canceled2 = true;
  32020. reason2 = reason;
  32021. if (canceled1) {
  32022. const compositeReason = CreateArrayFromList([reason1, reason2]);
  32023. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  32024. resolveCancelPromise(cancelResult);
  32025. }
  32026. return cancelPromise;
  32027. }
  32028. function startAlgorithm() {
  32029. return;
  32030. }
  32031. branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
  32032. branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
  32033. forwardReaderError(reader);
  32034. return [branch1, branch2];
  32035. }
  32036. function isReadableStreamLike(stream) {
  32037. return typeIsObject(stream) && typeof stream.getReader !== "undefined";
  32038. }
  32039. function ReadableStreamFrom(source) {
  32040. if (isReadableStreamLike(source)) {
  32041. return ReadableStreamFromDefaultReader(source.getReader());
  32042. }
  32043. return ReadableStreamFromIterable(source);
  32044. }
  32045. function ReadableStreamFromIterable(asyncIterable) {
  32046. let stream;
  32047. const iteratorRecord = GetIterator(asyncIterable, "async");
  32048. const startAlgorithm = noop2;
  32049. function pullAlgorithm() {
  32050. let nextResult;
  32051. try {
  32052. nextResult = IteratorNext(iteratorRecord);
  32053. } catch (e6) {
  32054. return promiseRejectedWith(e6);
  32055. }
  32056. const nextPromise = promiseResolvedWith(nextResult);
  32057. return transformPromiseWith(nextPromise, (iterResult) => {
  32058. if (!typeIsObject(iterResult)) {
  32059. throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");
  32060. }
  32061. const done = IteratorComplete(iterResult);
  32062. if (done) {
  32063. ReadableStreamDefaultControllerClose(stream._readableStreamController);
  32064. } else {
  32065. const value = IteratorValue(iterResult);
  32066. ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
  32067. }
  32068. });
  32069. }
  32070. function cancelAlgorithm(reason) {
  32071. const iterator = iteratorRecord.iterator;
  32072. let returnMethod;
  32073. try {
  32074. returnMethod = GetMethod(iterator, "return");
  32075. } catch (e6) {
  32076. return promiseRejectedWith(e6);
  32077. }
  32078. if (returnMethod === void 0) {
  32079. return promiseResolvedWith(void 0);
  32080. }
  32081. let returnResult;
  32082. try {
  32083. returnResult = reflectCall(returnMethod, iterator, [reason]);
  32084. } catch (e6) {
  32085. return promiseRejectedWith(e6);
  32086. }
  32087. const returnPromise = promiseResolvedWith(returnResult);
  32088. return transformPromiseWith(returnPromise, (iterResult) => {
  32089. if (!typeIsObject(iterResult)) {
  32090. throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object");
  32091. }
  32092. return void 0;
  32093. });
  32094. }
  32095. stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
  32096. return stream;
  32097. }
  32098. function ReadableStreamFromDefaultReader(reader) {
  32099. let stream;
  32100. const startAlgorithm = noop2;
  32101. function pullAlgorithm() {
  32102. let readPromise;
  32103. try {
  32104. readPromise = reader.read();
  32105. } catch (e6) {
  32106. return promiseRejectedWith(e6);
  32107. }
  32108. return transformPromiseWith(readPromise, (readResult) => {
  32109. if (!typeIsObject(readResult)) {
  32110. throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");
  32111. }
  32112. if (readResult.done) {
  32113. ReadableStreamDefaultControllerClose(stream._readableStreamController);
  32114. } else {
  32115. const value = readResult.value;
  32116. ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
  32117. }
  32118. });
  32119. }
  32120. function cancelAlgorithm(reason) {
  32121. try {
  32122. return promiseResolvedWith(reader.cancel(reason));
  32123. } catch (e6) {
  32124. return promiseRejectedWith(e6);
  32125. }
  32126. }
  32127. stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
  32128. return stream;
  32129. }
  32130. function convertUnderlyingDefaultOrByteSource(source, context) {
  32131. assertDictionary(source, context);
  32132. const original = source;
  32133. const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
  32134. const cancel = original === null || original === void 0 ? void 0 : original.cancel;
  32135. const pull = original === null || original === void 0 ? void 0 : original.pull;
  32136. const start = original === null || original === void 0 ? void 0 : original.start;
  32137. const type = original === null || original === void 0 ? void 0 : original.type;
  32138. return {
  32139. autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
  32140. cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
  32141. pull: pull === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
  32142. start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
  32143. type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`)
  32144. };
  32145. }
  32146. function convertUnderlyingSourceCancelCallback(fn, original, context) {
  32147. assertFunction(fn, context);
  32148. return (reason) => promiseCall(fn, original, [reason]);
  32149. }
  32150. function convertUnderlyingSourcePullCallback(fn, original, context) {
  32151. assertFunction(fn, context);
  32152. return (controller) => promiseCall(fn, original, [controller]);
  32153. }
  32154. function convertUnderlyingSourceStartCallback(fn, original, context) {
  32155. assertFunction(fn, context);
  32156. return (controller) => reflectCall(fn, original, [controller]);
  32157. }
  32158. function convertReadableStreamType(type, context) {
  32159. type = `${type}`;
  32160. if (type !== "bytes") {
  32161. throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
  32162. }
  32163. return type;
  32164. }
  32165. function convertIteratorOptions(options, context) {
  32166. assertDictionary(options, context);
  32167. const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
  32168. return { preventCancel: Boolean(preventCancel) };
  32169. }
  32170. function convertPipeOptions(options, context) {
  32171. assertDictionary(options, context);
  32172. const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
  32173. const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
  32174. const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
  32175. const signal = options === null || options === void 0 ? void 0 : options.signal;
  32176. if (signal !== void 0) {
  32177. assertAbortSignal(signal, `${context} has member 'signal' that`);
  32178. }
  32179. return {
  32180. preventAbort: Boolean(preventAbort),
  32181. preventCancel: Boolean(preventCancel),
  32182. preventClose: Boolean(preventClose),
  32183. signal
  32184. };
  32185. }
  32186. function assertAbortSignal(signal, context) {
  32187. if (!isAbortSignal2(signal)) {
  32188. throw new TypeError(`${context} is not an AbortSignal.`);
  32189. }
  32190. }
  32191. function convertReadableWritablePair(pair, context) {
  32192. assertDictionary(pair, context);
  32193. const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
  32194. assertRequiredField(readable, "readable", "ReadableWritablePair");
  32195. assertReadableStream(readable, `${context} has member 'readable' that`);
  32196. const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
  32197. assertRequiredField(writable, "writable", "ReadableWritablePair");
  32198. assertWritableStream(writable, `${context} has member 'writable' that`);
  32199. return { readable, writable };
  32200. }
  32201. class ReadableStream2 {
  32202. constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
  32203. if (rawUnderlyingSource === void 0) {
  32204. rawUnderlyingSource = null;
  32205. } else {
  32206. assertObject(rawUnderlyingSource, "First parameter");
  32207. }
  32208. const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
  32209. const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter");
  32210. InitializeReadableStream(this);
  32211. if (underlyingSource.type === "bytes") {
  32212. if (strategy.size !== void 0) {
  32213. throw new RangeError("The strategy for a byte stream cannot have a size function");
  32214. }
  32215. const highWaterMark = ExtractHighWaterMark(strategy, 0);
  32216. SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
  32217. } else {
  32218. const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
  32219. const highWaterMark = ExtractHighWaterMark(strategy, 1);
  32220. SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
  32221. }
  32222. }
  32223. /**
  32224. * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
  32225. */
  32226. get locked() {
  32227. if (!IsReadableStream(this)) {
  32228. throw streamBrandCheckException$1("locked");
  32229. }
  32230. return IsReadableStreamLocked(this);
  32231. }
  32232. /**
  32233. * Cancels the stream, signaling a loss of interest in the stream by a consumer.
  32234. *
  32235. * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
  32236. * method, which might or might not use it.
  32237. */
  32238. cancel(reason = void 0) {
  32239. if (!IsReadableStream(this)) {
  32240. return promiseRejectedWith(streamBrandCheckException$1("cancel"));
  32241. }
  32242. if (IsReadableStreamLocked(this)) {
  32243. return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader"));
  32244. }
  32245. return ReadableStreamCancel(this, reason);
  32246. }
  32247. getReader(rawOptions = void 0) {
  32248. if (!IsReadableStream(this)) {
  32249. throw streamBrandCheckException$1("getReader");
  32250. }
  32251. const options = convertReaderOptions(rawOptions, "First parameter");
  32252. if (options.mode === void 0) {
  32253. return AcquireReadableStreamDefaultReader(this);
  32254. }
  32255. return AcquireReadableStreamBYOBReader(this);
  32256. }
  32257. pipeThrough(rawTransform, rawOptions = {}) {
  32258. if (!IsReadableStream(this)) {
  32259. throw streamBrandCheckException$1("pipeThrough");
  32260. }
  32261. assertRequiredArgument(rawTransform, 1, "pipeThrough");
  32262. const transform = convertReadableWritablePair(rawTransform, "First parameter");
  32263. const options = convertPipeOptions(rawOptions, "Second parameter");
  32264. if (IsReadableStreamLocked(this)) {
  32265. throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");
  32266. }
  32267. if (IsWritableStreamLocked(transform.writable)) {
  32268. throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");
  32269. }
  32270. const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
  32271. setPromiseIsHandledToTrue(promise);
  32272. return transform.readable;
  32273. }
  32274. pipeTo(destination, rawOptions = {}) {
  32275. if (!IsReadableStream(this)) {
  32276. return promiseRejectedWith(streamBrandCheckException$1("pipeTo"));
  32277. }
  32278. if (destination === void 0) {
  32279. return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
  32280. }
  32281. if (!IsWritableStream(destination)) {
  32282. return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
  32283. }
  32284. let options;
  32285. try {
  32286. options = convertPipeOptions(rawOptions, "Second parameter");
  32287. } catch (e6) {
  32288. return promiseRejectedWith(e6);
  32289. }
  32290. if (IsReadableStreamLocked(this)) {
  32291. return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));
  32292. }
  32293. if (IsWritableStreamLocked(destination)) {
  32294. return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));
  32295. }
  32296. return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
  32297. }
  32298. /**
  32299. * Tees this readable stream, returning a two-element array containing the two resulting branches as
  32300. * new {@link ReadableStream} instances.
  32301. *
  32302. * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
  32303. * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
  32304. * propagated to the stream's underlying source.
  32305. *
  32306. * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
  32307. * this could allow interference between the two branches.
  32308. */
  32309. tee() {
  32310. if (!IsReadableStream(this)) {
  32311. throw streamBrandCheckException$1("tee");
  32312. }
  32313. const branches = ReadableStreamTee(this);
  32314. return CreateArrayFromList(branches);
  32315. }
  32316. values(rawOptions = void 0) {
  32317. if (!IsReadableStream(this)) {
  32318. throw streamBrandCheckException$1("values");
  32319. }
  32320. const options = convertIteratorOptions(rawOptions, "First parameter");
  32321. return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
  32322. }
  32323. [SymbolAsyncIterator](options) {
  32324. return this.values(options);
  32325. }
  32326. /**
  32327. * Creates a new ReadableStream wrapping the provided iterable or async iterable.
  32328. *
  32329. * This can be used to adapt various kinds of objects into a readable stream,
  32330. * such as an array, an async generator, or a Node.js readable stream.
  32331. */
  32332. static from(asyncIterable) {
  32333. return ReadableStreamFrom(asyncIterable);
  32334. }
  32335. }
  32336. Object.defineProperties(ReadableStream2, {
  32337. from: { enumerable: true }
  32338. });
  32339. Object.defineProperties(ReadableStream2.prototype, {
  32340. cancel: { enumerable: true },
  32341. getReader: { enumerable: true },
  32342. pipeThrough: { enumerable: true },
  32343. pipeTo: { enumerable: true },
  32344. tee: { enumerable: true },
  32345. values: { enumerable: true },
  32346. locked: { enumerable: true }
  32347. });
  32348. setFunctionName(ReadableStream2.from, "from");
  32349. setFunctionName(ReadableStream2.prototype.cancel, "cancel");
  32350. setFunctionName(ReadableStream2.prototype.getReader, "getReader");
  32351. setFunctionName(ReadableStream2.prototype.pipeThrough, "pipeThrough");
  32352. setFunctionName(ReadableStream2.prototype.pipeTo, "pipeTo");
  32353. setFunctionName(ReadableStream2.prototype.tee, "tee");
  32354. setFunctionName(ReadableStream2.prototype.values, "values");
  32355. if (typeof Symbol.toStringTag === "symbol") {
  32356. Object.defineProperty(ReadableStream2.prototype, Symbol.toStringTag, {
  32357. value: "ReadableStream",
  32358. configurable: true
  32359. });
  32360. }
  32361. Object.defineProperty(ReadableStream2.prototype, SymbolAsyncIterator, {
  32362. value: ReadableStream2.prototype.values,
  32363. writable: true,
  32364. configurable: true
  32365. });
  32366. function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
  32367. const stream = Object.create(ReadableStream2.prototype);
  32368. InitializeReadableStream(stream);
  32369. const controller = Object.create(ReadableStreamDefaultController.prototype);
  32370. SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
  32371. return stream;
  32372. }
  32373. function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
  32374. const stream = Object.create(ReadableStream2.prototype);
  32375. InitializeReadableStream(stream);
  32376. const controller = Object.create(ReadableByteStreamController.prototype);
  32377. SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0);
  32378. return stream;
  32379. }
  32380. function InitializeReadableStream(stream) {
  32381. stream._state = "readable";
  32382. stream._reader = void 0;
  32383. stream._storedError = void 0;
  32384. stream._disturbed = false;
  32385. }
  32386. function IsReadableStream(x5) {
  32387. if (!typeIsObject(x5)) {
  32388. return false;
  32389. }
  32390. if (!Object.prototype.hasOwnProperty.call(x5, "_readableStreamController")) {
  32391. return false;
  32392. }
  32393. return x5 instanceof ReadableStream2;
  32394. }
  32395. function IsReadableStreamLocked(stream) {
  32396. if (stream._reader === void 0) {
  32397. return false;
  32398. }
  32399. return true;
  32400. }
  32401. function ReadableStreamCancel(stream, reason) {
  32402. stream._disturbed = true;
  32403. if (stream._state === "closed") {
  32404. return promiseResolvedWith(void 0);
  32405. }
  32406. if (stream._state === "errored") {
  32407. return promiseRejectedWith(stream._storedError);
  32408. }
  32409. ReadableStreamClose(stream);
  32410. const reader = stream._reader;
  32411. if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) {
  32412. const readIntoRequests = reader._readIntoRequests;
  32413. reader._readIntoRequests = new SimpleQueue();
  32414. readIntoRequests.forEach((readIntoRequest) => {
  32415. readIntoRequest._closeSteps(void 0);
  32416. });
  32417. }
  32418. const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
  32419. return transformPromiseWith(sourceCancelPromise, noop2);
  32420. }
  32421. function ReadableStreamClose(stream) {
  32422. stream._state = "closed";
  32423. const reader = stream._reader;
  32424. if (reader === void 0) {
  32425. return;
  32426. }
  32427. defaultReaderClosedPromiseResolve(reader);
  32428. if (IsReadableStreamDefaultReader(reader)) {
  32429. const readRequests = reader._readRequests;
  32430. reader._readRequests = new SimpleQueue();
  32431. readRequests.forEach((readRequest) => {
  32432. readRequest._closeSteps();
  32433. });
  32434. }
  32435. }
  32436. function ReadableStreamError(stream, e6) {
  32437. stream._state = "errored";
  32438. stream._storedError = e6;
  32439. const reader = stream._reader;
  32440. if (reader === void 0) {
  32441. return;
  32442. }
  32443. defaultReaderClosedPromiseReject(reader, e6);
  32444. if (IsReadableStreamDefaultReader(reader)) {
  32445. ReadableStreamDefaultReaderErrorReadRequests(reader, e6);
  32446. } else {
  32447. ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e6);
  32448. }
  32449. }
  32450. function streamBrandCheckException$1(name) {
  32451. return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
  32452. }
  32453. function convertQueuingStrategyInit(init2, context) {
  32454. assertDictionary(init2, context);
  32455. const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark;
  32456. assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit");
  32457. return {
  32458. highWaterMark: convertUnrestrictedDouble(highWaterMark)
  32459. };
  32460. }
  32461. const byteLengthSizeFunction = (chunk) => {
  32462. return chunk.byteLength;
  32463. };
  32464. setFunctionName(byteLengthSizeFunction, "size");
  32465. class ByteLengthQueuingStrategy {
  32466. constructor(options) {
  32467. assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy");
  32468. options = convertQueuingStrategyInit(options, "First parameter");
  32469. this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
  32470. }
  32471. /**
  32472. * Returns the high water mark provided to the constructor.
  32473. */
  32474. get highWaterMark() {
  32475. if (!IsByteLengthQueuingStrategy(this)) {
  32476. throw byteLengthBrandCheckException("highWaterMark");
  32477. }
  32478. return this._byteLengthQueuingStrategyHighWaterMark;
  32479. }
  32480. /**
  32481. * Measures the size of `chunk` by returning the value of its `byteLength` property.
  32482. */
  32483. get size() {
  32484. if (!IsByteLengthQueuingStrategy(this)) {
  32485. throw byteLengthBrandCheckException("size");
  32486. }
  32487. return byteLengthSizeFunction;
  32488. }
  32489. }
  32490. Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
  32491. highWaterMark: { enumerable: true },
  32492. size: { enumerable: true }
  32493. });
  32494. if (typeof Symbol.toStringTag === "symbol") {
  32495. Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {
  32496. value: "ByteLengthQueuingStrategy",
  32497. configurable: true
  32498. });
  32499. }
  32500. function byteLengthBrandCheckException(name) {
  32501. return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
  32502. }
  32503. function IsByteLengthQueuingStrategy(x5) {
  32504. if (!typeIsObject(x5)) {
  32505. return false;
  32506. }
  32507. if (!Object.prototype.hasOwnProperty.call(x5, "_byteLengthQueuingStrategyHighWaterMark")) {
  32508. return false;
  32509. }
  32510. return x5 instanceof ByteLengthQueuingStrategy;
  32511. }
  32512. const countSizeFunction = () => {
  32513. return 1;
  32514. };
  32515. setFunctionName(countSizeFunction, "size");
  32516. class CountQueuingStrategy {
  32517. constructor(options) {
  32518. assertRequiredArgument(options, 1, "CountQueuingStrategy");
  32519. options = convertQueuingStrategyInit(options, "First parameter");
  32520. this._countQueuingStrategyHighWaterMark = options.highWaterMark;
  32521. }
  32522. /**
  32523. * Returns the high water mark provided to the constructor.
  32524. */
  32525. get highWaterMark() {
  32526. if (!IsCountQueuingStrategy(this)) {
  32527. throw countBrandCheckException("highWaterMark");
  32528. }
  32529. return this._countQueuingStrategyHighWaterMark;
  32530. }
  32531. /**
  32532. * Measures the size of `chunk` by always returning 1.
  32533. * This ensures that the total queue size is a count of the number of chunks in the queue.
  32534. */
  32535. get size() {
  32536. if (!IsCountQueuingStrategy(this)) {
  32537. throw countBrandCheckException("size");
  32538. }
  32539. return countSizeFunction;
  32540. }
  32541. }
  32542. Object.defineProperties(CountQueuingStrategy.prototype, {
  32543. highWaterMark: { enumerable: true },
  32544. size: { enumerable: true }
  32545. });
  32546. if (typeof Symbol.toStringTag === "symbol") {
  32547. Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {
  32548. value: "CountQueuingStrategy",
  32549. configurable: true
  32550. });
  32551. }
  32552. function countBrandCheckException(name) {
  32553. return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
  32554. }
  32555. function IsCountQueuingStrategy(x5) {
  32556. if (!typeIsObject(x5)) {
  32557. return false;
  32558. }
  32559. if (!Object.prototype.hasOwnProperty.call(x5, "_countQueuingStrategyHighWaterMark")) {
  32560. return false;
  32561. }
  32562. return x5 instanceof CountQueuingStrategy;
  32563. }
  32564. function convertTransformer(original, context) {
  32565. assertDictionary(original, context);
  32566. const cancel = original === null || original === void 0 ? void 0 : original.cancel;
  32567. const flush2 = original === null || original === void 0 ? void 0 : original.flush;
  32568. const readableType = original === null || original === void 0 ? void 0 : original.readableType;
  32569. const start = original === null || original === void 0 ? void 0 : original.start;
  32570. const transform = original === null || original === void 0 ? void 0 : original.transform;
  32571. const writableType = original === null || original === void 0 ? void 0 : original.writableType;
  32572. return {
  32573. cancel: cancel === void 0 ? void 0 : convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
  32574. flush: flush2 === void 0 ? void 0 : convertTransformerFlushCallback(flush2, original, `${context} has member 'flush' that`),
  32575. readableType,
  32576. start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
  32577. transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
  32578. writableType
  32579. };
  32580. }
  32581. function convertTransformerFlushCallback(fn, original, context) {
  32582. assertFunction(fn, context);
  32583. return (controller) => promiseCall(fn, original, [controller]);
  32584. }
  32585. function convertTransformerStartCallback(fn, original, context) {
  32586. assertFunction(fn, context);
  32587. return (controller) => reflectCall(fn, original, [controller]);
  32588. }
  32589. function convertTransformerTransformCallback(fn, original, context) {
  32590. assertFunction(fn, context);
  32591. return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
  32592. }
  32593. function convertTransformerCancelCallback(fn, original, context) {
  32594. assertFunction(fn, context);
  32595. return (reason) => promiseCall(fn, original, [reason]);
  32596. }
  32597. class TransformStream2 {
  32598. constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
  32599. if (rawTransformer === void 0) {
  32600. rawTransformer = null;
  32601. }
  32602. const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter");
  32603. const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter");
  32604. const transformer = convertTransformer(rawTransformer, "First parameter");
  32605. if (transformer.readableType !== void 0) {
  32606. throw new RangeError("Invalid readableType specified");
  32607. }
  32608. if (transformer.writableType !== void 0) {
  32609. throw new RangeError("Invalid writableType specified");
  32610. }
  32611. const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
  32612. const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
  32613. const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
  32614. const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
  32615. let startPromise_resolve;
  32616. const startPromise = newPromise((resolve) => {
  32617. startPromise_resolve = resolve;
  32618. });
  32619. InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
  32620. SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
  32621. if (transformer.start !== void 0) {
  32622. startPromise_resolve(transformer.start(this._transformStreamController));
  32623. } else {
  32624. startPromise_resolve(void 0);
  32625. }
  32626. }
  32627. /**
  32628. * The readable side of the transform stream.
  32629. */
  32630. get readable() {
  32631. if (!IsTransformStream(this)) {
  32632. throw streamBrandCheckException("readable");
  32633. }
  32634. return this._readable;
  32635. }
  32636. /**
  32637. * The writable side of the transform stream.
  32638. */
  32639. get writable() {
  32640. if (!IsTransformStream(this)) {
  32641. throw streamBrandCheckException("writable");
  32642. }
  32643. return this._writable;
  32644. }
  32645. }
  32646. Object.defineProperties(TransformStream2.prototype, {
  32647. readable: { enumerable: true },
  32648. writable: { enumerable: true }
  32649. });
  32650. if (typeof Symbol.toStringTag === "symbol") {
  32651. Object.defineProperty(TransformStream2.prototype, Symbol.toStringTag, {
  32652. value: "TransformStream",
  32653. configurable: true
  32654. });
  32655. }
  32656. function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
  32657. function startAlgorithm() {
  32658. return startPromise;
  32659. }
  32660. function writeAlgorithm(chunk) {
  32661. return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
  32662. }
  32663. function abortAlgorithm(reason) {
  32664. return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
  32665. }
  32666. function closeAlgorithm() {
  32667. return TransformStreamDefaultSinkCloseAlgorithm(stream);
  32668. }
  32669. stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
  32670. function pullAlgorithm() {
  32671. return TransformStreamDefaultSourcePullAlgorithm(stream);
  32672. }
  32673. function cancelAlgorithm(reason) {
  32674. return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
  32675. }
  32676. stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
  32677. stream._backpressure = void 0;
  32678. stream._backpressureChangePromise = void 0;
  32679. stream._backpressureChangePromise_resolve = void 0;
  32680. TransformStreamSetBackpressure(stream, true);
  32681. stream._transformStreamController = void 0;
  32682. }
  32683. function IsTransformStream(x5) {
  32684. if (!typeIsObject(x5)) {
  32685. return false;
  32686. }
  32687. if (!Object.prototype.hasOwnProperty.call(x5, "_transformStreamController")) {
  32688. return false;
  32689. }
  32690. return x5 instanceof TransformStream2;
  32691. }
  32692. function TransformStreamError(stream, e6) {
  32693. ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e6);
  32694. TransformStreamErrorWritableAndUnblockWrite(stream, e6);
  32695. }
  32696. function TransformStreamErrorWritableAndUnblockWrite(stream, e6) {
  32697. TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
  32698. WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e6);
  32699. TransformStreamUnblockWrite(stream);
  32700. }
  32701. function TransformStreamUnblockWrite(stream) {
  32702. if (stream._backpressure) {
  32703. TransformStreamSetBackpressure(stream, false);
  32704. }
  32705. }
  32706. function TransformStreamSetBackpressure(stream, backpressure) {
  32707. if (stream._backpressureChangePromise !== void 0) {
  32708. stream._backpressureChangePromise_resolve();
  32709. }
  32710. stream._backpressureChangePromise = newPromise((resolve) => {
  32711. stream._backpressureChangePromise_resolve = resolve;
  32712. });
  32713. stream._backpressure = backpressure;
  32714. }
  32715. class TransformStreamDefaultController {
  32716. constructor() {
  32717. throw new TypeError("Illegal constructor");
  32718. }
  32719. /**
  32720. * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
  32721. */
  32722. get desiredSize() {
  32723. if (!IsTransformStreamDefaultController(this)) {
  32724. throw defaultControllerBrandCheckException("desiredSize");
  32725. }
  32726. const readableController = this._controlledTransformStream._readable._readableStreamController;
  32727. return ReadableStreamDefaultControllerGetDesiredSize(readableController);
  32728. }
  32729. enqueue(chunk = void 0) {
  32730. if (!IsTransformStreamDefaultController(this)) {
  32731. throw defaultControllerBrandCheckException("enqueue");
  32732. }
  32733. TransformStreamDefaultControllerEnqueue(this, chunk);
  32734. }
  32735. /**
  32736. * Errors both the readable side and the writable side of the controlled transform stream, making all future
  32737. * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
  32738. */
  32739. error(reason = void 0) {
  32740. if (!IsTransformStreamDefaultController(this)) {
  32741. throw defaultControllerBrandCheckException("error");
  32742. }
  32743. TransformStreamDefaultControllerError(this, reason);
  32744. }
  32745. /**
  32746. * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
  32747. * transformer only needs to consume a portion of the chunks written to the writable side.
  32748. */
  32749. terminate() {
  32750. if (!IsTransformStreamDefaultController(this)) {
  32751. throw defaultControllerBrandCheckException("terminate");
  32752. }
  32753. TransformStreamDefaultControllerTerminate(this);
  32754. }
  32755. }
  32756. Object.defineProperties(TransformStreamDefaultController.prototype, {
  32757. enqueue: { enumerable: true },
  32758. error: { enumerable: true },
  32759. terminate: { enumerable: true },
  32760. desiredSize: { enumerable: true }
  32761. });
  32762. setFunctionName(TransformStreamDefaultController.prototype.enqueue, "enqueue");
  32763. setFunctionName(TransformStreamDefaultController.prototype.error, "error");
  32764. setFunctionName(TransformStreamDefaultController.prototype.terminate, "terminate");
  32765. if (typeof Symbol.toStringTag === "symbol") {
  32766. Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {
  32767. value: "TransformStreamDefaultController",
  32768. configurable: true
  32769. });
  32770. }
  32771. function IsTransformStreamDefaultController(x5) {
  32772. if (!typeIsObject(x5)) {
  32773. return false;
  32774. }
  32775. if (!Object.prototype.hasOwnProperty.call(x5, "_controlledTransformStream")) {
  32776. return false;
  32777. }
  32778. return x5 instanceof TransformStreamDefaultController;
  32779. }
  32780. function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
  32781. controller._controlledTransformStream = stream;
  32782. stream._transformStreamController = controller;
  32783. controller._transformAlgorithm = transformAlgorithm;
  32784. controller._flushAlgorithm = flushAlgorithm;
  32785. controller._cancelAlgorithm = cancelAlgorithm;
  32786. controller._finishPromise = void 0;
  32787. controller._finishPromise_resolve = void 0;
  32788. controller._finishPromise_reject = void 0;
  32789. }
  32790. function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
  32791. const controller = Object.create(TransformStreamDefaultController.prototype);
  32792. let transformAlgorithm;
  32793. let flushAlgorithm;
  32794. let cancelAlgorithm;
  32795. if (transformer.transform !== void 0) {
  32796. transformAlgorithm = (chunk) => transformer.transform(chunk, controller);
  32797. } else {
  32798. transformAlgorithm = (chunk) => {
  32799. try {
  32800. TransformStreamDefaultControllerEnqueue(controller, chunk);
  32801. return promiseResolvedWith(void 0);
  32802. } catch (transformResultE) {
  32803. return promiseRejectedWith(transformResultE);
  32804. }
  32805. };
  32806. }
  32807. if (transformer.flush !== void 0) {
  32808. flushAlgorithm = () => transformer.flush(controller);
  32809. } else {
  32810. flushAlgorithm = () => promiseResolvedWith(void 0);
  32811. }
  32812. if (transformer.cancel !== void 0) {
  32813. cancelAlgorithm = (reason) => transformer.cancel(reason);
  32814. } else {
  32815. cancelAlgorithm = () => promiseResolvedWith(void 0);
  32816. }
  32817. SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
  32818. }
  32819. function TransformStreamDefaultControllerClearAlgorithms(controller) {
  32820. controller._transformAlgorithm = void 0;
  32821. controller._flushAlgorithm = void 0;
  32822. controller._cancelAlgorithm = void 0;
  32823. }
  32824. function TransformStreamDefaultControllerEnqueue(controller, chunk) {
  32825. const stream = controller._controlledTransformStream;
  32826. const readableController = stream._readable._readableStreamController;
  32827. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
  32828. throw new TypeError("Readable side is not in a state that permits enqueue");
  32829. }
  32830. try {
  32831. ReadableStreamDefaultControllerEnqueue(readableController, chunk);
  32832. } catch (e6) {
  32833. TransformStreamErrorWritableAndUnblockWrite(stream, e6);
  32834. throw stream._readable._storedError;
  32835. }
  32836. const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
  32837. if (backpressure !== stream._backpressure) {
  32838. TransformStreamSetBackpressure(stream, true);
  32839. }
  32840. }
  32841. function TransformStreamDefaultControllerError(controller, e6) {
  32842. TransformStreamError(controller._controlledTransformStream, e6);
  32843. }
  32844. function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
  32845. const transformPromise = controller._transformAlgorithm(chunk);
  32846. return transformPromiseWith(transformPromise, void 0, (r6) => {
  32847. TransformStreamError(controller._controlledTransformStream, r6);
  32848. throw r6;
  32849. });
  32850. }
  32851. function TransformStreamDefaultControllerTerminate(controller) {
  32852. const stream = controller._controlledTransformStream;
  32853. const readableController = stream._readable._readableStreamController;
  32854. ReadableStreamDefaultControllerClose(readableController);
  32855. const error2 = new TypeError("TransformStream terminated");
  32856. TransformStreamErrorWritableAndUnblockWrite(stream, error2);
  32857. }
  32858. function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
  32859. const controller = stream._transformStreamController;
  32860. if (stream._backpressure) {
  32861. const backpressureChangePromise = stream._backpressureChangePromise;
  32862. return transformPromiseWith(backpressureChangePromise, () => {
  32863. const writable = stream._writable;
  32864. const state2 = writable._state;
  32865. if (state2 === "erroring") {
  32866. throw writable._storedError;
  32867. }
  32868. return TransformStreamDefaultControllerPerformTransform(controller, chunk);
  32869. });
  32870. }
  32871. return TransformStreamDefaultControllerPerformTransform(controller, chunk);
  32872. }
  32873. function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
  32874. const controller = stream._transformStreamController;
  32875. if (controller._finishPromise !== void 0) {
  32876. return controller._finishPromise;
  32877. }
  32878. const readable = stream._readable;
  32879. controller._finishPromise = newPromise((resolve, reject) => {
  32880. controller._finishPromise_resolve = resolve;
  32881. controller._finishPromise_reject = reject;
  32882. });
  32883. const cancelPromise = controller._cancelAlgorithm(reason);
  32884. TransformStreamDefaultControllerClearAlgorithms(controller);
  32885. uponPromise(cancelPromise, () => {
  32886. if (readable._state === "errored") {
  32887. defaultControllerFinishPromiseReject(controller, readable._storedError);
  32888. } else {
  32889. ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
  32890. defaultControllerFinishPromiseResolve(controller);
  32891. }
  32892. return null;
  32893. }, (r6) => {
  32894. ReadableStreamDefaultControllerError(readable._readableStreamController, r6);
  32895. defaultControllerFinishPromiseReject(controller, r6);
  32896. return null;
  32897. });
  32898. return controller._finishPromise;
  32899. }
  32900. function TransformStreamDefaultSinkCloseAlgorithm(stream) {
  32901. const controller = stream._transformStreamController;
  32902. if (controller._finishPromise !== void 0) {
  32903. return controller._finishPromise;
  32904. }
  32905. const readable = stream._readable;
  32906. controller._finishPromise = newPromise((resolve, reject) => {
  32907. controller._finishPromise_resolve = resolve;
  32908. controller._finishPromise_reject = reject;
  32909. });
  32910. const flushPromise = controller._flushAlgorithm();
  32911. TransformStreamDefaultControllerClearAlgorithms(controller);
  32912. uponPromise(flushPromise, () => {
  32913. if (readable._state === "errored") {
  32914. defaultControllerFinishPromiseReject(controller, readable._storedError);
  32915. } else {
  32916. ReadableStreamDefaultControllerClose(readable._readableStreamController);
  32917. defaultControllerFinishPromiseResolve(controller);
  32918. }
  32919. return null;
  32920. }, (r6) => {
  32921. ReadableStreamDefaultControllerError(readable._readableStreamController, r6);
  32922. defaultControllerFinishPromiseReject(controller, r6);
  32923. return null;
  32924. });
  32925. return controller._finishPromise;
  32926. }
  32927. function TransformStreamDefaultSourcePullAlgorithm(stream) {
  32928. TransformStreamSetBackpressure(stream, false);
  32929. return stream._backpressureChangePromise;
  32930. }
  32931. function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
  32932. const controller = stream._transformStreamController;
  32933. if (controller._finishPromise !== void 0) {
  32934. return controller._finishPromise;
  32935. }
  32936. const writable = stream._writable;
  32937. controller._finishPromise = newPromise((resolve, reject) => {
  32938. controller._finishPromise_resolve = resolve;
  32939. controller._finishPromise_reject = reject;
  32940. });
  32941. const cancelPromise = controller._cancelAlgorithm(reason);
  32942. TransformStreamDefaultControllerClearAlgorithms(controller);
  32943. uponPromise(cancelPromise, () => {
  32944. if (writable._state === "errored") {
  32945. defaultControllerFinishPromiseReject(controller, writable._storedError);
  32946. } else {
  32947. WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
  32948. TransformStreamUnblockWrite(stream);
  32949. defaultControllerFinishPromiseResolve(controller);
  32950. }
  32951. return null;
  32952. }, (r6) => {
  32953. WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r6);
  32954. TransformStreamUnblockWrite(stream);
  32955. defaultControllerFinishPromiseReject(controller, r6);
  32956. return null;
  32957. });
  32958. return controller._finishPromise;
  32959. }
  32960. function defaultControllerBrandCheckException(name) {
  32961. return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
  32962. }
  32963. function defaultControllerFinishPromiseResolve(controller) {
  32964. if (controller._finishPromise_resolve === void 0) {
  32965. return;
  32966. }
  32967. controller._finishPromise_resolve();
  32968. controller._finishPromise_resolve = void 0;
  32969. controller._finishPromise_reject = void 0;
  32970. }
  32971. function defaultControllerFinishPromiseReject(controller, reason) {
  32972. if (controller._finishPromise_reject === void 0) {
  32973. return;
  32974. }
  32975. setPromiseIsHandledToTrue(controller._finishPromise);
  32976. controller._finishPromise_reject(reason);
  32977. controller._finishPromise_resolve = void 0;
  32978. controller._finishPromise_reject = void 0;
  32979. }
  32980. function streamBrandCheckException(name) {
  32981. return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
  32982. }
  32983. exports2.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
  32984. exports2.CountQueuingStrategy = CountQueuingStrategy;
  32985. exports2.ReadableByteStreamController = ReadableByteStreamController;
  32986. exports2.ReadableStream = ReadableStream2;
  32987. exports2.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
  32988. exports2.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
  32989. exports2.ReadableStreamDefaultController = ReadableStreamDefaultController;
  32990. exports2.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
  32991. exports2.TransformStream = TransformStream2;
  32992. exports2.TransformStreamDefaultController = TransformStreamDefaultController;
  32993. exports2.WritableStream = WritableStream;
  32994. exports2.WritableStreamDefaultController = WritableStreamDefaultController;
  32995. exports2.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
  32996. });
  32997. }
  32998. });
  32999. // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs
  33000. var require_streams = __commonJS({
  33001. "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs"() {
  33002. "use strict";
  33003. var POOL_SIZE2 = 65536;
  33004. if (!globalThis.ReadableStream) {
  33005. try {
  33006. const process4 = __require("process");
  33007. const { emitWarning } = process4;
  33008. try {
  33009. process4.emitWarning = () => {
  33010. };
  33011. Object.assign(globalThis, __require("stream/web"));
  33012. process4.emitWarning = emitWarning;
  33013. } catch (error2) {
  33014. process4.emitWarning = emitWarning;
  33015. throw error2;
  33016. }
  33017. } catch (error2) {
  33018. Object.assign(globalThis, require_ponyfill_es2018());
  33019. }
  33020. }
  33021. try {
  33022. const { Blob: Blob3 } = __require("buffer");
  33023. if (Blob3 && !Blob3.prototype.stream) {
  33024. Blob3.prototype.stream = function name(params) {
  33025. let position = 0;
  33026. const blob = this;
  33027. return new ReadableStream({
  33028. type: "bytes",
  33029. async pull(ctrl) {
  33030. const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2));
  33031. const buffer = await chunk.arrayBuffer();
  33032. position += buffer.byteLength;
  33033. ctrl.enqueue(new Uint8Array(buffer));
  33034. if (position === blob.size) {
  33035. ctrl.close();
  33036. }
  33037. }
  33038. });
  33039. };
  33040. }
  33041. } catch (error2) {
  33042. }
  33043. }
  33044. });
  33045. // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js
  33046. async function* toIterator(parts, clone2 = true) {
  33047. for (const part of parts) {
  33048. if ("stream" in part) {
  33049. yield* (
  33050. /** @type {AsyncIterableIterator<Uint8Array>} */
  33051. part.stream()
  33052. );
  33053. } else if (ArrayBuffer.isView(part)) {
  33054. if (clone2) {
  33055. let position = part.byteOffset;
  33056. const end = part.byteOffset + part.byteLength;
  33057. while (position !== end) {
  33058. const size = Math.min(end - position, POOL_SIZE);
  33059. const chunk = part.buffer.slice(position, position + size);
  33060. position += chunk.byteLength;
  33061. yield new Uint8Array(chunk);
  33062. }
  33063. } else {
  33064. yield part;
  33065. }
  33066. } else {
  33067. let position = 0, b5 = (
  33068. /** @type {Blob} */
  33069. part
  33070. );
  33071. while (position !== b5.size) {
  33072. const chunk = b5.slice(position, Math.min(b5.size, position + POOL_SIZE));
  33073. const buffer = await chunk.arrayBuffer();
  33074. position += buffer.byteLength;
  33075. yield new Uint8Array(buffer);
  33076. }
  33077. }
  33078. }
  33079. }
  33080. var import_streams, POOL_SIZE, _parts, _type, _size, _endings, _a11, _Blob, Blob2, fetch_blob_default;
  33081. var init_fetch_blob = __esm({
  33082. "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js"() {
  33083. "use strict";
  33084. import_streams = __toESM(require_streams(), 1);
  33085. POOL_SIZE = 65536;
  33086. _Blob = (_a11 = class {
  33087. /**
  33088. * The Blob() constructor returns a new Blob object. The content
  33089. * of the blob consists of the concatenation of the values given
  33090. * in the parameter array.
  33091. *
  33092. * @param {*} blobParts
  33093. * @param {{ type?: string, endings?: string }} [options]
  33094. */
  33095. constructor(blobParts = [], options = {}) {
  33096. /** @type {Array.<(Blob|Uint8Array)>} */
  33097. __privateAdd(this, _parts, []);
  33098. __privateAdd(this, _type, "");
  33099. __privateAdd(this, _size, 0);
  33100. __privateAdd(this, _endings, "transparent");
  33101. if (typeof blobParts !== "object" || blobParts === null) {
  33102. throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");
  33103. }
  33104. if (typeof blobParts[Symbol.iterator] !== "function") {
  33105. throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");
  33106. }
  33107. if (typeof options !== "object" && typeof options !== "function") {
  33108. throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
  33109. }
  33110. if (options === null) options = {};
  33111. const encoder = new TextEncoder();
  33112. for (const element of blobParts) {
  33113. let part;
  33114. if (ArrayBuffer.isView(element)) {
  33115. part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength));
  33116. } else if (element instanceof ArrayBuffer) {
  33117. part = new Uint8Array(element.slice(0));
  33118. } else if (element instanceof _a11) {
  33119. part = element;
  33120. } else {
  33121. part = encoder.encode(`${element}`);
  33122. }
  33123. __privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size));
  33124. __privateGet(this, _parts).push(part);
  33125. }
  33126. __privateSet(this, _endings, `${options.endings === void 0 ? "transparent" : options.endings}`);
  33127. const type = options.type === void 0 ? "" : String(options.type);
  33128. __privateSet(this, _type, /^[\x20-\x7E]*$/.test(type) ? type : "");
  33129. }
  33130. /**
  33131. * The Blob interface's size property returns the
  33132. * size of the Blob in bytes.
  33133. */
  33134. get size() {
  33135. return __privateGet(this, _size);
  33136. }
  33137. /**
  33138. * The type property of a Blob object returns the MIME type of the file.
  33139. */
  33140. get type() {
  33141. return __privateGet(this, _type);
  33142. }
  33143. /**
  33144. * The text() method in the Blob interface returns a Promise
  33145. * that resolves with a string containing the contents of
  33146. * the blob, interpreted as UTF-8.
  33147. *
  33148. * @return {Promise<string>}
  33149. */
  33150. async text() {
  33151. const decoder = new TextDecoder();
  33152. let str = "";
  33153. for await (const part of toIterator(__privateGet(this, _parts), false)) {
  33154. str += decoder.decode(part, { stream: true });
  33155. }
  33156. str += decoder.decode();
  33157. return str;
  33158. }
  33159. /**
  33160. * The arrayBuffer() method in the Blob interface returns a
  33161. * Promise that resolves with the contents of the blob as
  33162. * binary data contained in an ArrayBuffer.
  33163. *
  33164. * @return {Promise<ArrayBuffer>}
  33165. */
  33166. async arrayBuffer() {
  33167. const data = new Uint8Array(this.size);
  33168. let offset = 0;
  33169. for await (const chunk of toIterator(__privateGet(this, _parts), false)) {
  33170. data.set(chunk, offset);
  33171. offset += chunk.length;
  33172. }
  33173. return data.buffer;
  33174. }
  33175. stream() {
  33176. const it = toIterator(__privateGet(this, _parts), true);
  33177. return new globalThis.ReadableStream({
  33178. // @ts-ignore
  33179. type: "bytes",
  33180. async pull(ctrl) {
  33181. const chunk = await it.next();
  33182. chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
  33183. },
  33184. async cancel() {
  33185. await it.return();
  33186. }
  33187. });
  33188. }
  33189. /**
  33190. * The Blob interface's slice() method creates and returns a
  33191. * new Blob object which contains data from a subset of the
  33192. * blob on which it's called.
  33193. *
  33194. * @param {number} [start]
  33195. * @param {number} [end]
  33196. * @param {string} [type]
  33197. */
  33198. slice(start = 0, end = this.size, type = "") {
  33199. const { size } = this;
  33200. let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size);
  33201. let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size);
  33202. const span = Math.max(relativeEnd - relativeStart, 0);
  33203. const parts = __privateGet(this, _parts);
  33204. const blobParts = [];
  33205. let added = 0;
  33206. for (const part of parts) {
  33207. if (added >= span) {
  33208. break;
  33209. }
  33210. const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size;
  33211. if (relativeStart && size2 <= relativeStart) {
  33212. relativeStart -= size2;
  33213. relativeEnd -= size2;
  33214. } else {
  33215. let chunk;
  33216. if (ArrayBuffer.isView(part)) {
  33217. chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd));
  33218. added += chunk.byteLength;
  33219. } else {
  33220. chunk = part.slice(relativeStart, Math.min(size2, relativeEnd));
  33221. added += chunk.size;
  33222. }
  33223. relativeEnd -= size2;
  33224. blobParts.push(chunk);
  33225. relativeStart = 0;
  33226. }
  33227. }
  33228. const blob = new _a11([], { type: String(type).toLowerCase() });
  33229. __privateSet(blob, _size, span);
  33230. __privateSet(blob, _parts, blobParts);
  33231. return blob;
  33232. }
  33233. get [Symbol.toStringTag]() {
  33234. return "Blob";
  33235. }
  33236. static [Symbol.hasInstance](object) {
  33237. return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]);
  33238. }
  33239. }, _parts = new WeakMap(), _type = new WeakMap(), _size = new WeakMap(), _endings = new WeakMap(), _a11);
  33240. Object.defineProperties(_Blob.prototype, {
  33241. size: { enumerable: true },
  33242. type: { enumerable: true },
  33243. slice: { enumerable: true }
  33244. });
  33245. Blob2 = _Blob;
  33246. fetch_blob_default = Blob2;
  33247. }
  33248. });
  33249. // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js
  33250. var _lastModified, _name, _a12, _File, File2, file_default;
  33251. var init_file = __esm({
  33252. "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js"() {
  33253. "use strict";
  33254. init_fetch_blob();
  33255. _File = (_a12 = class extends fetch_blob_default {
  33256. /**
  33257. * @param {*[]} fileBits
  33258. * @param {string} fileName
  33259. * @param {{lastModified?: number, type?: string}} options
  33260. */
  33261. // @ts-ignore
  33262. constructor(fileBits, fileName, options = {}) {
  33263. if (arguments.length < 2) {
  33264. throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);
  33265. }
  33266. super(fileBits, options);
  33267. __privateAdd(this, _lastModified, 0);
  33268. __privateAdd(this, _name, "");
  33269. if (options === null) options = {};
  33270. const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified);
  33271. if (!Number.isNaN(lastModified)) {
  33272. __privateSet(this, _lastModified, lastModified);
  33273. }
  33274. __privateSet(this, _name, String(fileName));
  33275. }
  33276. get name() {
  33277. return __privateGet(this, _name);
  33278. }
  33279. get lastModified() {
  33280. return __privateGet(this, _lastModified);
  33281. }
  33282. get [Symbol.toStringTag]() {
  33283. return "File";
  33284. }
  33285. static [Symbol.hasInstance](object) {
  33286. return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]);
  33287. }
  33288. }, _lastModified = new WeakMap(), _name = new WeakMap(), _a12);
  33289. File2 = _File;
  33290. file_default = File2;
  33291. }
  33292. });
  33293. // ../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js
  33294. function formDataToBlob(F3, B2 = fetch_blob_default) {
  33295. var b5 = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c5 = [], p5 = `--${b5}\r
  33296. Content-Disposition: form-data; name="`;
  33297. F3.forEach((v6, n5) => typeof v6 == "string" ? c5.push(p5 + e(n5) + `"\r
  33298. \r
  33299. ${v6.replace(/\r(?!\n)|(?<!\r)\n/g, "\r\n")}\r
  33300. `) : c5.push(p5 + e(n5) + `"; filename="${e(v6.name, 1)}"\r
  33301. Content-Type: ${v6.type || "application/octet-stream"}\r
  33302. \r
  33303. `, v6, "\r\n"));
  33304. c5.push(`--${b5}--`);
  33305. return new B2(c5, { type: "multipart/form-data; boundary=" + b5 });
  33306. }
  33307. var t, i, h, r, m, f, e, x, _d, _a13, FormData;
  33308. var init_esm_min = __esm({
  33309. "../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js"() {
  33310. "use strict";
  33311. init_fetch_blob();
  33312. init_file();
  33313. ({ toStringTag: t, iterator: i, hasInstance: h } = Symbol);
  33314. r = Math.random;
  33315. m = "append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(",");
  33316. f = (a5, b5, c5) => (a5 += "", /^(Blob|File)$/.test(b5 && b5[t]) ? [(c5 = c5 !== void 0 ? c5 + "" : b5[t] == "File" ? b5.name : "blob", a5), b5.name !== c5 || b5[t] == "blob" ? new file_default([b5], c5, b5) : b5] : [a5, b5 + ""]);
  33317. e = (c5, f7) => (f7 ? c5 : c5.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
  33318. x = (n5, a5, e6) => {
  33319. if (a5.length < e6) {
  33320. throw new TypeError(`Failed to execute '${n5}' on 'FormData': ${e6} arguments required, but only ${a5.length} present.`);
  33321. }
  33322. };
  33323. FormData = (_a13 = class {
  33324. constructor(...a5) {
  33325. __privateAdd(this, _d, []);
  33326. if (a5.length) throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`);
  33327. }
  33328. get [t]() {
  33329. return "FormData";
  33330. }
  33331. [i]() {
  33332. return this.entries();
  33333. }
  33334. static [h](o5) {
  33335. return o5 && typeof o5 === "object" && o5[t] === "FormData" && !m.some((m6) => typeof o5[m6] != "function");
  33336. }
  33337. append(...a5) {
  33338. x("append", arguments, 2);
  33339. __privateGet(this, _d).push(f(...a5));
  33340. }
  33341. delete(a5) {
  33342. x("delete", arguments, 1);
  33343. a5 += "";
  33344. __privateSet(this, _d, __privateGet(this, _d).filter(([b5]) => b5 !== a5));
  33345. }
  33346. get(a5) {
  33347. x("get", arguments, 1);
  33348. a5 += "";
  33349. for (var b5 = __privateGet(this, _d), l5 = b5.length, c5 = 0; c5 < l5; c5++) if (b5[c5][0] === a5) return b5[c5][1];
  33350. return null;
  33351. }
  33352. getAll(a5, b5) {
  33353. x("getAll", arguments, 1);
  33354. b5 = [];
  33355. a5 += "";
  33356. __privateGet(this, _d).forEach((c5) => c5[0] === a5 && b5.push(c5[1]));
  33357. return b5;
  33358. }
  33359. has(a5) {
  33360. x("has", arguments, 1);
  33361. a5 += "";
  33362. return __privateGet(this, _d).some((b5) => b5[0] === a5);
  33363. }
  33364. forEach(a5, b5) {
  33365. x("forEach", arguments, 1);
  33366. for (var [c5, d5] of this) a5.call(b5, d5, c5, this);
  33367. }
  33368. set(...a5) {
  33369. x("set", arguments, 2);
  33370. var b5 = [], c5 = true;
  33371. a5 = f(...a5);
  33372. __privateGet(this, _d).forEach((d5) => {
  33373. d5[0] === a5[0] ? c5 && (c5 = !b5.push(a5)) : b5.push(d5);
  33374. });
  33375. c5 && b5.push(a5);
  33376. __privateSet(this, _d, b5);
  33377. }
  33378. *entries() {
  33379. yield* __privateGet(this, _d);
  33380. }
  33381. *keys() {
  33382. for (var [a5] of this) yield a5;
  33383. }
  33384. *values() {
  33385. for (var [, a5] of this) yield a5;
  33386. }
  33387. }, _d = new WeakMap(), _a13);
  33388. }
  33389. });
  33390. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js
  33391. var FetchBaseError;
  33392. var init_base = __esm({
  33393. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js"() {
  33394. "use strict";
  33395. FetchBaseError = class extends Error {
  33396. constructor(message, type) {
  33397. super(message);
  33398. Error.captureStackTrace(this, this.constructor);
  33399. this.type = type;
  33400. }
  33401. get name() {
  33402. return this.constructor.name;
  33403. }
  33404. get [Symbol.toStringTag]() {
  33405. return this.constructor.name;
  33406. }
  33407. };
  33408. }
  33409. });
  33410. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js
  33411. var FetchError;
  33412. var init_fetch_error = __esm({
  33413. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js"() {
  33414. "use strict";
  33415. init_base();
  33416. FetchError = class extends FetchBaseError {
  33417. /**
  33418. * @param {string} message - Error message for human
  33419. * @param {string} [type] - Error type for machine
  33420. * @param {SystemError} [systemError] - For Node.js system error
  33421. */
  33422. constructor(message, type, systemError) {
  33423. super(message, type);
  33424. if (systemError) {
  33425. this.code = this.errno = systemError.code;
  33426. this.erroredSysCall = systemError.syscall;
  33427. }
  33428. }
  33429. };
  33430. }
  33431. });
  33432. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js
  33433. var NAME, isURLSearchParameters, isBlob, isAbortSignal, isDomainOrSubdomain, isSameProtocol;
  33434. var init_is = __esm({
  33435. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js"() {
  33436. "use strict";
  33437. NAME = Symbol.toStringTag;
  33438. isURLSearchParameters = (object) => {
  33439. return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
  33440. };
  33441. isBlob = (object) => {
  33442. return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
  33443. };
  33444. isAbortSignal = (object) => {
  33445. return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget");
  33446. };
  33447. isDomainOrSubdomain = (destination, original) => {
  33448. const orig = new URL(original).hostname;
  33449. const dest = new URL(destination).hostname;
  33450. return orig === dest || orig.endsWith(`.${dest}`);
  33451. };
  33452. isSameProtocol = (destination, original) => {
  33453. const orig = new URL(original).protocol;
  33454. const dest = new URL(destination).protocol;
  33455. return orig === dest;
  33456. };
  33457. }
  33458. });
  33459. // ../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js
  33460. var require_node_domexception = __commonJS({
  33461. "../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js"(exports, module) {
  33462. "use strict";
  33463. if (!globalThis.DOMException) {
  33464. try {
  33465. const { MessageChannel } = __require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer();
  33466. port.postMessage(ab, [ab, ab]);
  33467. } catch (err2) {
  33468. err2.constructor.name === "DOMException" && (globalThis.DOMException = err2.constructor);
  33469. }
  33470. }
  33471. module.exports = globalThis.DOMException;
  33472. }
  33473. });
  33474. // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js
  33475. import { statSync, createReadStream, promises as fs2 } from "fs";
  33476. import { basename } from "path";
  33477. var import_node_domexception, stat;
  33478. var init_from = __esm({
  33479. "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js"() {
  33480. "use strict";
  33481. import_node_domexception = __toESM(require_node_domexception(), 1);
  33482. init_file();
  33483. init_fetch_blob();
  33484. ({ stat } = fs2);
  33485. }
  33486. });
  33487. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js
  33488. var multipart_parser_exports = {};
  33489. __export(multipart_parser_exports, {
  33490. toFormData: () => toFormData
  33491. });
  33492. function _fileName(headerValue) {
  33493. const m6 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
  33494. if (!m6) {
  33495. return;
  33496. }
  33497. const match2 = m6[2] || m6[3] || "";
  33498. let filename = match2.slice(match2.lastIndexOf("\\") + 1);
  33499. filename = filename.replace(/%22/g, '"');
  33500. filename = filename.replace(/&#(\d{4});/g, (m7, code) => {
  33501. return String.fromCharCode(code);
  33502. });
  33503. return filename;
  33504. }
  33505. async function toFormData(Body2, ct) {
  33506. if (!/multipart/i.test(ct)) {
  33507. throw new TypeError("Failed to fetch");
  33508. }
  33509. const m6 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
  33510. if (!m6) {
  33511. throw new TypeError("no or bad content-type header, no multipart boundary");
  33512. }
  33513. const parser = new MultipartParser(m6[1] || m6[2]);
  33514. let headerField;
  33515. let headerValue;
  33516. let entryValue;
  33517. let entryName;
  33518. let contentType;
  33519. let filename;
  33520. const entryChunks = [];
  33521. const formData = new FormData();
  33522. const onPartData = (ui8a) => {
  33523. entryValue += decoder.decode(ui8a, { stream: true });
  33524. };
  33525. const appendToFile = (ui8a) => {
  33526. entryChunks.push(ui8a);
  33527. };
  33528. const appendFileToFormData = () => {
  33529. const file = new file_default(entryChunks, filename, { type: contentType });
  33530. formData.append(entryName, file);
  33531. };
  33532. const appendEntryToFormData = () => {
  33533. formData.append(entryName, entryValue);
  33534. };
  33535. const decoder = new TextDecoder("utf-8");
  33536. decoder.decode();
  33537. parser.onPartBegin = function() {
  33538. parser.onPartData = onPartData;
  33539. parser.onPartEnd = appendEntryToFormData;
  33540. headerField = "";
  33541. headerValue = "";
  33542. entryValue = "";
  33543. entryName = "";
  33544. contentType = "";
  33545. filename = null;
  33546. entryChunks.length = 0;
  33547. };
  33548. parser.onHeaderField = function(ui8a) {
  33549. headerField += decoder.decode(ui8a, { stream: true });
  33550. };
  33551. parser.onHeaderValue = function(ui8a) {
  33552. headerValue += decoder.decode(ui8a, { stream: true });
  33553. };
  33554. parser.onHeaderEnd = function() {
  33555. headerValue += decoder.decode();
  33556. headerField = headerField.toLowerCase();
  33557. if (headerField === "content-disposition") {
  33558. const m7 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
  33559. if (m7) {
  33560. entryName = m7[2] || m7[3] || "";
  33561. }
  33562. filename = _fileName(headerValue);
  33563. if (filename) {
  33564. parser.onPartData = appendToFile;
  33565. parser.onPartEnd = appendFileToFormData;
  33566. }
  33567. } else if (headerField === "content-type") {
  33568. contentType = headerValue;
  33569. }
  33570. headerValue = "";
  33571. headerField = "";
  33572. };
  33573. for await (const chunk of Body2) {
  33574. parser.write(chunk);
  33575. }
  33576. parser.end();
  33577. return formData;
  33578. }
  33579. var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser;
  33580. var init_multipart_parser = __esm({
  33581. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js"() {
  33582. "use strict";
  33583. init_from();
  33584. init_esm_min();
  33585. s = 0;
  33586. S = {
  33587. START_BOUNDARY: s++,
  33588. HEADER_FIELD_START: s++,
  33589. HEADER_FIELD: s++,
  33590. HEADER_VALUE_START: s++,
  33591. HEADER_VALUE: s++,
  33592. HEADER_VALUE_ALMOST_DONE: s++,
  33593. HEADERS_ALMOST_DONE: s++,
  33594. PART_DATA_START: s++,
  33595. PART_DATA: s++,
  33596. END: s++
  33597. };
  33598. f2 = 1;
  33599. F = {
  33600. PART_BOUNDARY: f2,
  33601. LAST_BOUNDARY: f2 *= 2
  33602. };
  33603. LF = 10;
  33604. CR = 13;
  33605. SPACE = 32;
  33606. HYPHEN = 45;
  33607. COLON = 58;
  33608. A = 97;
  33609. Z = 122;
  33610. lower = (c5) => c5 | 32;
  33611. noop = () => {
  33612. };
  33613. MultipartParser = class {
  33614. /**
  33615. * @param {string} boundary
  33616. */
  33617. constructor(boundary) {
  33618. this.index = 0;
  33619. this.flags = 0;
  33620. this.onHeaderEnd = noop;
  33621. this.onHeaderField = noop;
  33622. this.onHeadersEnd = noop;
  33623. this.onHeaderValue = noop;
  33624. this.onPartBegin = noop;
  33625. this.onPartData = noop;
  33626. this.onPartEnd = noop;
  33627. this.boundaryChars = {};
  33628. boundary = "\r\n--" + boundary;
  33629. const ui8a = new Uint8Array(boundary.length);
  33630. for (let i6 = 0; i6 < boundary.length; i6++) {
  33631. ui8a[i6] = boundary.charCodeAt(i6);
  33632. this.boundaryChars[ui8a[i6]] = true;
  33633. }
  33634. this.boundary = ui8a;
  33635. this.lookbehind = new Uint8Array(this.boundary.length + 8);
  33636. this.state = S.START_BOUNDARY;
  33637. }
  33638. /**
  33639. * @param {Uint8Array} data
  33640. */
  33641. write(data) {
  33642. let i6 = 0;
  33643. const length_ = data.length;
  33644. let previousIndex = this.index;
  33645. let { lookbehind, boundary, boundaryChars, index: index6, state: state2, flags } = this;
  33646. const boundaryLength = this.boundary.length;
  33647. const boundaryEnd = boundaryLength - 1;
  33648. const bufferLength = data.length;
  33649. let c5;
  33650. let cl;
  33651. const mark = (name) => {
  33652. this[name + "Mark"] = i6;
  33653. };
  33654. const clear = (name) => {
  33655. delete this[name + "Mark"];
  33656. };
  33657. const callback = (callbackSymbol, start, end, ui8a) => {
  33658. if (start === void 0 || start !== end) {
  33659. this[callbackSymbol](ui8a && ui8a.subarray(start, end));
  33660. }
  33661. };
  33662. const dataCallback = (name, clear2) => {
  33663. const markSymbol = name + "Mark";
  33664. if (!(markSymbol in this)) {
  33665. return;
  33666. }
  33667. if (clear2) {
  33668. callback(name, this[markSymbol], i6, data);
  33669. delete this[markSymbol];
  33670. } else {
  33671. callback(name, this[markSymbol], data.length, data);
  33672. this[markSymbol] = 0;
  33673. }
  33674. };
  33675. for (i6 = 0; i6 < length_; i6++) {
  33676. c5 = data[i6];
  33677. switch (state2) {
  33678. case S.START_BOUNDARY:
  33679. if (index6 === boundary.length - 2) {
  33680. if (c5 === HYPHEN) {
  33681. flags |= F.LAST_BOUNDARY;
  33682. } else if (c5 !== CR) {
  33683. return;
  33684. }
  33685. index6++;
  33686. break;
  33687. } else if (index6 - 1 === boundary.length - 2) {
  33688. if (flags & F.LAST_BOUNDARY && c5 === HYPHEN) {
  33689. state2 = S.END;
  33690. flags = 0;
  33691. } else if (!(flags & F.LAST_BOUNDARY) && c5 === LF) {
  33692. index6 = 0;
  33693. callback("onPartBegin");
  33694. state2 = S.HEADER_FIELD_START;
  33695. } else {
  33696. return;
  33697. }
  33698. break;
  33699. }
  33700. if (c5 !== boundary[index6 + 2]) {
  33701. index6 = -2;
  33702. }
  33703. if (c5 === boundary[index6 + 2]) {
  33704. index6++;
  33705. }
  33706. break;
  33707. case S.HEADER_FIELD_START:
  33708. state2 = S.HEADER_FIELD;
  33709. mark("onHeaderField");
  33710. index6 = 0;
  33711. // falls through
  33712. case S.HEADER_FIELD:
  33713. if (c5 === CR) {
  33714. clear("onHeaderField");
  33715. state2 = S.HEADERS_ALMOST_DONE;
  33716. break;
  33717. }
  33718. index6++;
  33719. if (c5 === HYPHEN) {
  33720. break;
  33721. }
  33722. if (c5 === COLON) {
  33723. if (index6 === 1) {
  33724. return;
  33725. }
  33726. dataCallback("onHeaderField", true);
  33727. state2 = S.HEADER_VALUE_START;
  33728. break;
  33729. }
  33730. cl = lower(c5);
  33731. if (cl < A || cl > Z) {
  33732. return;
  33733. }
  33734. break;
  33735. case S.HEADER_VALUE_START:
  33736. if (c5 === SPACE) {
  33737. break;
  33738. }
  33739. mark("onHeaderValue");
  33740. state2 = S.HEADER_VALUE;
  33741. // falls through
  33742. case S.HEADER_VALUE:
  33743. if (c5 === CR) {
  33744. dataCallback("onHeaderValue", true);
  33745. callback("onHeaderEnd");
  33746. state2 = S.HEADER_VALUE_ALMOST_DONE;
  33747. }
  33748. break;
  33749. case S.HEADER_VALUE_ALMOST_DONE:
  33750. if (c5 !== LF) {
  33751. return;
  33752. }
  33753. state2 = S.HEADER_FIELD_START;
  33754. break;
  33755. case S.HEADERS_ALMOST_DONE:
  33756. if (c5 !== LF) {
  33757. return;
  33758. }
  33759. callback("onHeadersEnd");
  33760. state2 = S.PART_DATA_START;
  33761. break;
  33762. case S.PART_DATA_START:
  33763. state2 = S.PART_DATA;
  33764. mark("onPartData");
  33765. // falls through
  33766. case S.PART_DATA:
  33767. previousIndex = index6;
  33768. if (index6 === 0) {
  33769. i6 += boundaryEnd;
  33770. while (i6 < bufferLength && !(data[i6] in boundaryChars)) {
  33771. i6 += boundaryLength;
  33772. }
  33773. i6 -= boundaryEnd;
  33774. c5 = data[i6];
  33775. }
  33776. if (index6 < boundary.length) {
  33777. if (boundary[index6] === c5) {
  33778. if (index6 === 0) {
  33779. dataCallback("onPartData", true);
  33780. }
  33781. index6++;
  33782. } else {
  33783. index6 = 0;
  33784. }
  33785. } else if (index6 === boundary.length) {
  33786. index6++;
  33787. if (c5 === CR) {
  33788. flags |= F.PART_BOUNDARY;
  33789. } else if (c5 === HYPHEN) {
  33790. flags |= F.LAST_BOUNDARY;
  33791. } else {
  33792. index6 = 0;
  33793. }
  33794. } else if (index6 - 1 === boundary.length) {
  33795. if (flags & F.PART_BOUNDARY) {
  33796. index6 = 0;
  33797. if (c5 === LF) {
  33798. flags &= ~F.PART_BOUNDARY;
  33799. callback("onPartEnd");
  33800. callback("onPartBegin");
  33801. state2 = S.HEADER_FIELD_START;
  33802. break;
  33803. }
  33804. } else if (flags & F.LAST_BOUNDARY) {
  33805. if (c5 === HYPHEN) {
  33806. callback("onPartEnd");
  33807. state2 = S.END;
  33808. flags = 0;
  33809. } else {
  33810. index6 = 0;
  33811. }
  33812. } else {
  33813. index6 = 0;
  33814. }
  33815. }
  33816. if (index6 > 0) {
  33817. lookbehind[index6 - 1] = c5;
  33818. } else if (previousIndex > 0) {
  33819. const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
  33820. callback("onPartData", 0, previousIndex, _lookbehind);
  33821. previousIndex = 0;
  33822. mark("onPartData");
  33823. i6--;
  33824. }
  33825. break;
  33826. case S.END:
  33827. break;
  33828. default:
  33829. throw new Error(`Unexpected state entered: ${state2}`);
  33830. }
  33831. }
  33832. dataCallback("onHeaderField");
  33833. dataCallback("onHeaderValue");
  33834. dataCallback("onPartData");
  33835. this.index = index6;
  33836. this.state = state2;
  33837. this.flags = flags;
  33838. }
  33839. end() {
  33840. if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) {
  33841. this.onPartEnd();
  33842. } else if (this.state !== S.END) {
  33843. throw new Error("MultipartParser.end(): stream ended unexpectedly");
  33844. }
  33845. }
  33846. };
  33847. }
  33848. });
  33849. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js
  33850. import Stream, { PassThrough } from "stream";
  33851. import { types, deprecate, promisify } from "util";
  33852. import { Buffer as Buffer2 } from "buffer";
  33853. async function consumeBody(data) {
  33854. if (data[INTERNALS].disturbed) {
  33855. throw new TypeError(`body used already for: ${data.url}`);
  33856. }
  33857. data[INTERNALS].disturbed = true;
  33858. if (data[INTERNALS].error) {
  33859. throw data[INTERNALS].error;
  33860. }
  33861. const { body } = data;
  33862. if (body === null) {
  33863. return Buffer2.alloc(0);
  33864. }
  33865. if (!(body instanceof Stream)) {
  33866. return Buffer2.alloc(0);
  33867. }
  33868. const accum = [];
  33869. let accumBytes = 0;
  33870. try {
  33871. for await (const chunk of body) {
  33872. if (data.size > 0 && accumBytes + chunk.length > data.size) {
  33873. const error2 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
  33874. body.destroy(error2);
  33875. throw error2;
  33876. }
  33877. accumBytes += chunk.length;
  33878. accum.push(chunk);
  33879. }
  33880. } catch (error2) {
  33881. const error_ = error2 instanceof FetchBaseError ? error2 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2);
  33882. throw error_;
  33883. }
  33884. if (body.readableEnded === true || body._readableState.ended === true) {
  33885. try {
  33886. if (accum.every((c5) => typeof c5 === "string")) {
  33887. return Buffer2.from(accum.join(""));
  33888. }
  33889. return Buffer2.concat(accum, accumBytes);
  33890. } catch (error2) {
  33891. throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2);
  33892. }
  33893. } else {
  33894. throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
  33895. }
  33896. }
  33897. var pipeline, INTERNALS, Body, clone, getNonSpecFormDataBoundary, extractContentType, getTotalBytes, writeToStream;
  33898. var init_body2 = __esm({
  33899. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js"() {
  33900. "use strict";
  33901. init_fetch_blob();
  33902. init_esm_min();
  33903. init_fetch_error();
  33904. init_base();
  33905. init_is();
  33906. pipeline = promisify(Stream.pipeline);
  33907. INTERNALS = Symbol("Body internals");
  33908. Body = class {
  33909. constructor(body, {
  33910. size = 0
  33911. } = {}) {
  33912. let boundary = null;
  33913. if (body === null) {
  33914. body = null;
  33915. } else if (isURLSearchParameters(body)) {
  33916. body = Buffer2.from(body.toString());
  33917. } else if (isBlob(body)) {
  33918. } else if (Buffer2.isBuffer(body)) {
  33919. } else if (types.isAnyArrayBuffer(body)) {
  33920. body = Buffer2.from(body);
  33921. } else if (ArrayBuffer.isView(body)) {
  33922. body = Buffer2.from(body.buffer, body.byteOffset, body.byteLength);
  33923. } else if (body instanceof Stream) {
  33924. } else if (body instanceof FormData) {
  33925. body = formDataToBlob(body);
  33926. boundary = body.type.split("=")[1];
  33927. } else {
  33928. body = Buffer2.from(String(body));
  33929. }
  33930. let stream = body;
  33931. if (Buffer2.isBuffer(body)) {
  33932. stream = Stream.Readable.from(body);
  33933. } else if (isBlob(body)) {
  33934. stream = Stream.Readable.from(body.stream());
  33935. }
  33936. this[INTERNALS] = {
  33937. body,
  33938. stream,
  33939. boundary,
  33940. disturbed: false,
  33941. error: null
  33942. };
  33943. this.size = size;
  33944. if (body instanceof Stream) {
  33945. body.on("error", (error_) => {
  33946. const error2 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
  33947. this[INTERNALS].error = error2;
  33948. });
  33949. }
  33950. }
  33951. get body() {
  33952. return this[INTERNALS].stream;
  33953. }
  33954. get bodyUsed() {
  33955. return this[INTERNALS].disturbed;
  33956. }
  33957. /**
  33958. * Decode response as ArrayBuffer
  33959. *
  33960. * @return Promise
  33961. */
  33962. async arrayBuffer() {
  33963. const { buffer, byteOffset, byteLength } = await consumeBody(this);
  33964. return buffer.slice(byteOffset, byteOffset + byteLength);
  33965. }
  33966. async formData() {
  33967. const ct = this.headers.get("content-type");
  33968. if (ct.startsWith("application/x-www-form-urlencoded")) {
  33969. const formData = new FormData();
  33970. const parameters = new URLSearchParams(await this.text());
  33971. for (const [name, value] of parameters) {
  33972. formData.append(name, value);
  33973. }
  33974. return formData;
  33975. }
  33976. const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports));
  33977. return toFormData2(this.body, ct);
  33978. }
  33979. /**
  33980. * Return raw response as Blob
  33981. *
  33982. * @return Promise
  33983. */
  33984. async blob() {
  33985. const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || "";
  33986. const buf = await this.arrayBuffer();
  33987. return new fetch_blob_default([buf], {
  33988. type: ct
  33989. });
  33990. }
  33991. /**
  33992. * Decode response as json
  33993. *
  33994. * @return Promise
  33995. */
  33996. async json() {
  33997. const text = await this.text();
  33998. return JSON.parse(text);
  33999. }
  34000. /**
  34001. * Decode response as text
  34002. *
  34003. * @return Promise
  34004. */
  34005. async text() {
  34006. const buffer = await consumeBody(this);
  34007. return new TextDecoder().decode(buffer);
  34008. }
  34009. /**
  34010. * Decode response as buffer (non-spec api)
  34011. *
  34012. * @return Promise
  34013. */
  34014. buffer() {
  34015. return consumeBody(this);
  34016. }
  34017. };
  34018. Body.prototype.buffer = deprecate(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer");
  34019. Object.defineProperties(Body.prototype, {
  34020. body: { enumerable: true },
  34021. bodyUsed: { enumerable: true },
  34022. arrayBuffer: { enumerable: true },
  34023. blob: { enumerable: true },
  34024. json: { enumerable: true },
  34025. text: { enumerable: true },
  34026. data: { get: deprecate(
  34027. () => {
  34028. },
  34029. "data doesn't exist, use json(), text(), arrayBuffer(), or body instead",
  34030. "https://github.com/node-fetch/node-fetch/issues/1000 (response)"
  34031. ) }
  34032. });
  34033. clone = (instance, highWaterMark) => {
  34034. let p1;
  34035. let p22;
  34036. let { body } = instance[INTERNALS];
  34037. if (instance.bodyUsed) {
  34038. throw new Error("cannot clone body after it is used");
  34039. }
  34040. if (body instanceof Stream && typeof body.getBoundary !== "function") {
  34041. p1 = new PassThrough({ highWaterMark });
  34042. p22 = new PassThrough({ highWaterMark });
  34043. body.pipe(p1);
  34044. body.pipe(p22);
  34045. instance[INTERNALS].stream = p1;
  34046. body = p22;
  34047. }
  34048. return body;
  34049. };
  34050. getNonSpecFormDataBoundary = deprecate(
  34051. (body) => body.getBoundary(),
  34052. "form-data doesn't follow the spec and requires special treatment. Use alternative package",
  34053. "https://github.com/node-fetch/node-fetch/issues/1167"
  34054. );
  34055. extractContentType = (body, request2) => {
  34056. if (body === null) {
  34057. return null;
  34058. }
  34059. if (typeof body === "string") {
  34060. return "text/plain;charset=UTF-8";
  34061. }
  34062. if (isURLSearchParameters(body)) {
  34063. return "application/x-www-form-urlencoded;charset=UTF-8";
  34064. }
  34065. if (isBlob(body)) {
  34066. return body.type || null;
  34067. }
  34068. if (Buffer2.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
  34069. return null;
  34070. }
  34071. if (body instanceof FormData) {
  34072. return `multipart/form-data; boundary=${request2[INTERNALS].boundary}`;
  34073. }
  34074. if (body && typeof body.getBoundary === "function") {
  34075. return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
  34076. }
  34077. if (body instanceof Stream) {
  34078. return null;
  34079. }
  34080. return "text/plain;charset=UTF-8";
  34081. };
  34082. getTotalBytes = (request2) => {
  34083. const { body } = request2[INTERNALS];
  34084. if (body === null) {
  34085. return 0;
  34086. }
  34087. if (isBlob(body)) {
  34088. return body.size;
  34089. }
  34090. if (Buffer2.isBuffer(body)) {
  34091. return body.length;
  34092. }
  34093. if (body && typeof body.getLengthSync === "function") {
  34094. return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
  34095. }
  34096. return null;
  34097. };
  34098. writeToStream = async (dest, { body }) => {
  34099. if (body === null) {
  34100. dest.end();
  34101. } else {
  34102. await pipeline(body, dest);
  34103. }
  34104. };
  34105. }
  34106. });
  34107. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
  34108. import { types as types2 } from "util";
  34109. import http from "http";
  34110. function fromRawHeaders(headers = []) {
  34111. return new Headers2(
  34112. headers.reduce((result, value, index6, array2) => {
  34113. if (index6 % 2 === 0) {
  34114. result.push(array2.slice(index6, index6 + 2));
  34115. }
  34116. return result;
  34117. }, []).filter(([name, value]) => {
  34118. try {
  34119. validateHeaderName(name);
  34120. validateHeaderValue(name, String(value));
  34121. return true;
  34122. } catch {
  34123. return false;
  34124. }
  34125. })
  34126. );
  34127. }
  34128. var validateHeaderName, validateHeaderValue, Headers2;
  34129. var init_headers = __esm({
  34130. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js"() {
  34131. "use strict";
  34132. validateHeaderName = typeof http.validateHeaderName === "function" ? http.validateHeaderName : (name) => {
  34133. if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
  34134. const error2 = new TypeError(`Header name must be a valid HTTP token [${name}]`);
  34135. Object.defineProperty(error2, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
  34136. throw error2;
  34137. }
  34138. };
  34139. validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name, value) => {
  34140. if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
  34141. const error2 = new TypeError(`Invalid character in header content ["${name}"]`);
  34142. Object.defineProperty(error2, "code", { value: "ERR_INVALID_CHAR" });
  34143. throw error2;
  34144. }
  34145. };
  34146. Headers2 = class _Headers extends URLSearchParams {
  34147. /**
  34148. * Headers class
  34149. *
  34150. * @constructor
  34151. * @param {HeadersInit} [init] - Response headers
  34152. */
  34153. constructor(init2) {
  34154. let result = [];
  34155. if (init2 instanceof _Headers) {
  34156. const raw2 = init2.raw();
  34157. for (const [name, values] of Object.entries(raw2)) {
  34158. result.push(...values.map((value) => [name, value]));
  34159. }
  34160. } else if (init2 == null) {
  34161. } else if (typeof init2 === "object" && !types2.isBoxedPrimitive(init2)) {
  34162. const method = init2[Symbol.iterator];
  34163. if (method == null) {
  34164. result.push(...Object.entries(init2));
  34165. } else {
  34166. if (typeof method !== "function") {
  34167. throw new TypeError("Header pairs must be iterable");
  34168. }
  34169. result = [...init2].map((pair) => {
  34170. if (typeof pair !== "object" || types2.isBoxedPrimitive(pair)) {
  34171. throw new TypeError("Each header pair must be an iterable object");
  34172. }
  34173. return [...pair];
  34174. }).map((pair) => {
  34175. if (pair.length !== 2) {
  34176. throw new TypeError("Each header pair must be a name/value tuple");
  34177. }
  34178. return [...pair];
  34179. });
  34180. }
  34181. } else {
  34182. throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
  34183. }
  34184. result = result.length > 0 ? result.map(([name, value]) => {
  34185. validateHeaderName(name);
  34186. validateHeaderValue(name, String(value));
  34187. return [String(name).toLowerCase(), String(value)];
  34188. }) : void 0;
  34189. super(result);
  34190. return new Proxy(this, {
  34191. get(target, p5, receiver) {
  34192. switch (p5) {
  34193. case "append":
  34194. case "set":
  34195. return (name, value) => {
  34196. validateHeaderName(name);
  34197. validateHeaderValue(name, String(value));
  34198. return URLSearchParams.prototype[p5].call(
  34199. target,
  34200. String(name).toLowerCase(),
  34201. String(value)
  34202. );
  34203. };
  34204. case "delete":
  34205. case "has":
  34206. case "getAll":
  34207. return (name) => {
  34208. validateHeaderName(name);
  34209. return URLSearchParams.prototype[p5].call(
  34210. target,
  34211. String(name).toLowerCase()
  34212. );
  34213. };
  34214. case "keys":
  34215. return () => {
  34216. target.sort();
  34217. return new Set(URLSearchParams.prototype.keys.call(target)).keys();
  34218. };
  34219. default:
  34220. return Reflect.get(target, p5, receiver);
  34221. }
  34222. }
  34223. });
  34224. }
  34225. get [Symbol.toStringTag]() {
  34226. return this.constructor.name;
  34227. }
  34228. toString() {
  34229. return Object.prototype.toString.call(this);
  34230. }
  34231. get(name) {
  34232. const values = this.getAll(name);
  34233. if (values.length === 0) {
  34234. return null;
  34235. }
  34236. let value = values.join(", ");
  34237. if (/^content-encoding$/i.test(name)) {
  34238. value = value.toLowerCase();
  34239. }
  34240. return value;
  34241. }
  34242. forEach(callback, thisArg = void 0) {
  34243. for (const name of this.keys()) {
  34244. Reflect.apply(callback, thisArg, [this.get(name), name, this]);
  34245. }
  34246. }
  34247. *values() {
  34248. for (const name of this.keys()) {
  34249. yield this.get(name);
  34250. }
  34251. }
  34252. /**
  34253. * @type {() => IterableIterator<[string, string]>}
  34254. */
  34255. *entries() {
  34256. for (const name of this.keys()) {
  34257. yield [name, this.get(name)];
  34258. }
  34259. }
  34260. [Symbol.iterator]() {
  34261. return this.entries();
  34262. }
  34263. /**
  34264. * Node-fetch non-spec method
  34265. * returning all headers and their values as array
  34266. * @returns {Record<string, string[]>}
  34267. */
  34268. raw() {
  34269. return [...this.keys()].reduce((result, key) => {
  34270. result[key] = this.getAll(key);
  34271. return result;
  34272. }, {});
  34273. }
  34274. /**
  34275. * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
  34276. */
  34277. [Symbol.for("nodejs.util.inspect.custom")]() {
  34278. return [...this.keys()].reduce((result, key) => {
  34279. const values = this.getAll(key);
  34280. if (key === "host") {
  34281. result[key] = values[0];
  34282. } else {
  34283. result[key] = values.length > 1 ? values : values[0];
  34284. }
  34285. return result;
  34286. }, {});
  34287. }
  34288. };
  34289. Object.defineProperties(
  34290. Headers2.prototype,
  34291. ["get", "entries", "forEach", "values"].reduce((result, property) => {
  34292. result[property] = { enumerable: true };
  34293. return result;
  34294. }, {})
  34295. );
  34296. }
  34297. });
  34298. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js
  34299. var redirectStatus, isRedirect;
  34300. var init_is_redirect = __esm({
  34301. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js"() {
  34302. "use strict";
  34303. redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  34304. isRedirect = (code) => {
  34305. return redirectStatus.has(code);
  34306. };
  34307. }
  34308. });
  34309. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js
  34310. var INTERNALS2, Response3;
  34311. var init_response = __esm({
  34312. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js"() {
  34313. "use strict";
  34314. init_headers();
  34315. init_body2();
  34316. init_is_redirect();
  34317. INTERNALS2 = Symbol("Response internals");
  34318. Response3 = class _Response extends Body {
  34319. constructor(body = null, options = {}) {
  34320. super(body, options);
  34321. const status = options.status != null ? options.status : 200;
  34322. const headers = new Headers2(options.headers);
  34323. if (body !== null && !headers.has("Content-Type")) {
  34324. const contentType = extractContentType(body, this);
  34325. if (contentType) {
  34326. headers.append("Content-Type", contentType);
  34327. }
  34328. }
  34329. this[INTERNALS2] = {
  34330. type: "default",
  34331. url: options.url,
  34332. status,
  34333. statusText: options.statusText || "",
  34334. headers,
  34335. counter: options.counter,
  34336. highWaterMark: options.highWaterMark
  34337. };
  34338. }
  34339. get type() {
  34340. return this[INTERNALS2].type;
  34341. }
  34342. get url() {
  34343. return this[INTERNALS2].url || "";
  34344. }
  34345. get status() {
  34346. return this[INTERNALS2].status;
  34347. }
  34348. /**
  34349. * Convenience property representing if the request ended normally
  34350. */
  34351. get ok() {
  34352. return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300;
  34353. }
  34354. get redirected() {
  34355. return this[INTERNALS2].counter > 0;
  34356. }
  34357. get statusText() {
  34358. return this[INTERNALS2].statusText;
  34359. }
  34360. get headers() {
  34361. return this[INTERNALS2].headers;
  34362. }
  34363. get highWaterMark() {
  34364. return this[INTERNALS2].highWaterMark;
  34365. }
  34366. /**
  34367. * Clone this response
  34368. *
  34369. * @return Response
  34370. */
  34371. clone() {
  34372. return new _Response(clone(this, this.highWaterMark), {
  34373. type: this.type,
  34374. url: this.url,
  34375. status: this.status,
  34376. statusText: this.statusText,
  34377. headers: this.headers,
  34378. ok: this.ok,
  34379. redirected: this.redirected,
  34380. size: this.size,
  34381. highWaterMark: this.highWaterMark
  34382. });
  34383. }
  34384. /**
  34385. * @param {string} url The URL that the new response is to originate from.
  34386. * @param {number} status An optional status code for the response (e.g., 302.)
  34387. * @returns {Response} A Response object.
  34388. */
  34389. static redirect(url, status = 302) {
  34390. if (!isRedirect(status)) {
  34391. throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
  34392. }
  34393. return new _Response(null, {
  34394. headers: {
  34395. location: new URL(url).toString()
  34396. },
  34397. status
  34398. });
  34399. }
  34400. static error() {
  34401. const response = new _Response(null, { status: 0, statusText: "" });
  34402. response[INTERNALS2].type = "error";
  34403. return response;
  34404. }
  34405. static json(data = void 0, init2 = {}) {
  34406. const body = JSON.stringify(data);
  34407. if (body === void 0) {
  34408. throw new TypeError("data is not JSON serializable");
  34409. }
  34410. const headers = new Headers2(init2 && init2.headers);
  34411. if (!headers.has("content-type")) {
  34412. headers.set("content-type", "application/json");
  34413. }
  34414. return new _Response(body, {
  34415. ...init2,
  34416. headers
  34417. });
  34418. }
  34419. get [Symbol.toStringTag]() {
  34420. return "Response";
  34421. }
  34422. };
  34423. Object.defineProperties(Response3.prototype, {
  34424. type: { enumerable: true },
  34425. url: { enumerable: true },
  34426. status: { enumerable: true },
  34427. ok: { enumerable: true },
  34428. redirected: { enumerable: true },
  34429. statusText: { enumerable: true },
  34430. headers: { enumerable: true },
  34431. clone: { enumerable: true }
  34432. });
  34433. }
  34434. });
  34435. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js
  34436. var getSearch;
  34437. var init_get_search = __esm({
  34438. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js"() {
  34439. "use strict";
  34440. getSearch = (parsedURL) => {
  34441. if (parsedURL.search) {
  34442. return parsedURL.search;
  34443. }
  34444. const lastOffset = parsedURL.href.length - 1;
  34445. const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
  34446. return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
  34447. };
  34448. }
  34449. });
  34450. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js
  34451. import { isIP } from "net";
  34452. function stripURLForUseAsAReferrer(url, originOnly = false) {
  34453. if (url == null) {
  34454. return "no-referrer";
  34455. }
  34456. url = new URL(url);
  34457. if (/^(about|blob|data):$/.test(url.protocol)) {
  34458. return "no-referrer";
  34459. }
  34460. url.username = "";
  34461. url.password = "";
  34462. url.hash = "";
  34463. if (originOnly) {
  34464. url.pathname = "";
  34465. url.search = "";
  34466. }
  34467. return url;
  34468. }
  34469. function validateReferrerPolicy(referrerPolicy) {
  34470. if (!ReferrerPolicy.has(referrerPolicy)) {
  34471. throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
  34472. }
  34473. return referrerPolicy;
  34474. }
  34475. function isOriginPotentiallyTrustworthy(url) {
  34476. if (/^(http|ws)s:$/.test(url.protocol)) {
  34477. return true;
  34478. }
  34479. const hostIp = url.host.replace(/(^\[)|(]$)/g, "");
  34480. const hostIPVersion = isIP(hostIp);
  34481. if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
  34482. return true;
  34483. }
  34484. if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
  34485. return true;
  34486. }
  34487. if (url.host === "localhost" || url.host.endsWith(".localhost")) {
  34488. return false;
  34489. }
  34490. if (url.protocol === "file:") {
  34491. return true;
  34492. }
  34493. return false;
  34494. }
  34495. function isUrlPotentiallyTrustworthy(url) {
  34496. if (/^about:(blank|srcdoc)$/.test(url)) {
  34497. return true;
  34498. }
  34499. if (url.protocol === "data:") {
  34500. return true;
  34501. }
  34502. if (/^(blob|filesystem):$/.test(url.protocol)) {
  34503. return true;
  34504. }
  34505. return isOriginPotentiallyTrustworthy(url);
  34506. }
  34507. function determineRequestsReferrer(request2, { referrerURLCallback, referrerOriginCallback } = {}) {
  34508. if (request2.referrer === "no-referrer" || request2.referrerPolicy === "") {
  34509. return null;
  34510. }
  34511. const policy5 = request2.referrerPolicy;
  34512. if (request2.referrer === "about:client") {
  34513. return "no-referrer";
  34514. }
  34515. const referrerSource = request2.referrer;
  34516. let referrerURL = stripURLForUseAsAReferrer(referrerSource);
  34517. let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
  34518. if (referrerURL.toString().length > 4096) {
  34519. referrerURL = referrerOrigin;
  34520. }
  34521. if (referrerURLCallback) {
  34522. referrerURL = referrerURLCallback(referrerURL);
  34523. }
  34524. if (referrerOriginCallback) {
  34525. referrerOrigin = referrerOriginCallback(referrerOrigin);
  34526. }
  34527. const currentURL = new URL(request2.url);
  34528. switch (policy5) {
  34529. case "no-referrer":
  34530. return "no-referrer";
  34531. case "origin":
  34532. return referrerOrigin;
  34533. case "unsafe-url":
  34534. return referrerURL;
  34535. case "strict-origin":
  34536. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
  34537. return "no-referrer";
  34538. }
  34539. return referrerOrigin.toString();
  34540. case "strict-origin-when-cross-origin":
  34541. if (referrerURL.origin === currentURL.origin) {
  34542. return referrerURL;
  34543. }
  34544. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
  34545. return "no-referrer";
  34546. }
  34547. return referrerOrigin;
  34548. case "same-origin":
  34549. if (referrerURL.origin === currentURL.origin) {
  34550. return referrerURL;
  34551. }
  34552. return "no-referrer";
  34553. case "origin-when-cross-origin":
  34554. if (referrerURL.origin === currentURL.origin) {
  34555. return referrerURL;
  34556. }
  34557. return referrerOrigin;
  34558. case "no-referrer-when-downgrade":
  34559. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
  34560. return "no-referrer";
  34561. }
  34562. return referrerURL;
  34563. default:
  34564. throw new TypeError(`Invalid referrerPolicy: ${policy5}`);
  34565. }
  34566. }
  34567. function parseReferrerPolicyFromHeader(headers) {
  34568. const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
  34569. let policy5 = "";
  34570. for (const token of policyTokens) {
  34571. if (token && ReferrerPolicy.has(token)) {
  34572. policy5 = token;
  34573. }
  34574. }
  34575. return policy5;
  34576. }
  34577. var ReferrerPolicy, DEFAULT_REFERRER_POLICY;
  34578. var init_referrer = __esm({
  34579. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js"() {
  34580. "use strict";
  34581. ReferrerPolicy = /* @__PURE__ */ new Set([
  34582. "",
  34583. "no-referrer",
  34584. "no-referrer-when-downgrade",
  34585. "same-origin",
  34586. "origin",
  34587. "strict-origin",
  34588. "origin-when-cross-origin",
  34589. "strict-origin-when-cross-origin",
  34590. "unsafe-url"
  34591. ]);
  34592. DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
  34593. }
  34594. });
  34595. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js
  34596. import { format as formatUrl } from "url";
  34597. import { deprecate as deprecate2 } from "util";
  34598. var INTERNALS3, isRequest, doBadDataWarn, Request3, getNodeRequestOptions;
  34599. var init_request2 = __esm({
  34600. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js"() {
  34601. "use strict";
  34602. init_headers();
  34603. init_body2();
  34604. init_is();
  34605. init_get_search();
  34606. init_referrer();
  34607. INTERNALS3 = Symbol("Request internals");
  34608. isRequest = (object) => {
  34609. return typeof object === "object" && typeof object[INTERNALS3] === "object";
  34610. };
  34611. doBadDataWarn = deprecate2(
  34612. () => {
  34613. },
  34614. ".data is not a valid RequestInit property, use .body instead",
  34615. "https://github.com/node-fetch/node-fetch/issues/1000 (request)"
  34616. );
  34617. Request3 = class _Request extends Body {
  34618. constructor(input, init2 = {}) {
  34619. let parsedURL;
  34620. if (isRequest(input)) {
  34621. parsedURL = new URL(input.url);
  34622. } else {
  34623. parsedURL = new URL(input);
  34624. input = {};
  34625. }
  34626. if (parsedURL.username !== "" || parsedURL.password !== "") {
  34627. throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
  34628. }
  34629. let method = init2.method || input.method || "GET";
  34630. if (/^(delete|get|head|options|post|put)$/i.test(method)) {
  34631. method = method.toUpperCase();
  34632. }
  34633. if (!isRequest(init2) && "data" in init2) {
  34634. doBadDataWarn();
  34635. }
  34636. if ((init2.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
  34637. throw new TypeError("Request with GET/HEAD method cannot have body");
  34638. }
  34639. const inputBody = init2.body ? init2.body : isRequest(input) && input.body !== null ? clone(input) : null;
  34640. super(inputBody, {
  34641. size: init2.size || input.size || 0
  34642. });
  34643. const headers = new Headers2(init2.headers || input.headers || {});
  34644. if (inputBody !== null && !headers.has("Content-Type")) {
  34645. const contentType = extractContentType(inputBody, this);
  34646. if (contentType) {
  34647. headers.set("Content-Type", contentType);
  34648. }
  34649. }
  34650. let signal = isRequest(input) ? input.signal : null;
  34651. if ("signal" in init2) {
  34652. signal = init2.signal;
  34653. }
  34654. if (signal != null && !isAbortSignal(signal)) {
  34655. throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
  34656. }
  34657. let referrer = init2.referrer == null ? input.referrer : init2.referrer;
  34658. if (referrer === "") {
  34659. referrer = "no-referrer";
  34660. } else if (referrer) {
  34661. const parsedReferrer = new URL(referrer);
  34662. referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
  34663. } else {
  34664. referrer = void 0;
  34665. }
  34666. this[INTERNALS3] = {
  34667. method,
  34668. redirect: init2.redirect || input.redirect || "follow",
  34669. headers,
  34670. parsedURL,
  34671. signal,
  34672. referrer
  34673. };
  34674. this.follow = init2.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init2.follow;
  34675. this.compress = init2.compress === void 0 ? input.compress === void 0 ? true : input.compress : init2.compress;
  34676. this.counter = init2.counter || input.counter || 0;
  34677. this.agent = init2.agent || input.agent;
  34678. this.highWaterMark = init2.highWaterMark || input.highWaterMark || 16384;
  34679. this.insecureHTTPParser = init2.insecureHTTPParser || input.insecureHTTPParser || false;
  34680. this.referrerPolicy = init2.referrerPolicy || input.referrerPolicy || "";
  34681. }
  34682. /** @returns {string} */
  34683. get method() {
  34684. return this[INTERNALS3].method;
  34685. }
  34686. /** @returns {string} */
  34687. get url() {
  34688. return formatUrl(this[INTERNALS3].parsedURL);
  34689. }
  34690. /** @returns {Headers} */
  34691. get headers() {
  34692. return this[INTERNALS3].headers;
  34693. }
  34694. get redirect() {
  34695. return this[INTERNALS3].redirect;
  34696. }
  34697. /** @returns {AbortSignal} */
  34698. get signal() {
  34699. return this[INTERNALS3].signal;
  34700. }
  34701. // https://fetch.spec.whatwg.org/#dom-request-referrer
  34702. get referrer() {
  34703. if (this[INTERNALS3].referrer === "no-referrer") {
  34704. return "";
  34705. }
  34706. if (this[INTERNALS3].referrer === "client") {
  34707. return "about:client";
  34708. }
  34709. if (this[INTERNALS3].referrer) {
  34710. return this[INTERNALS3].referrer.toString();
  34711. }
  34712. return void 0;
  34713. }
  34714. get referrerPolicy() {
  34715. return this[INTERNALS3].referrerPolicy;
  34716. }
  34717. set referrerPolicy(referrerPolicy) {
  34718. this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy);
  34719. }
  34720. /**
  34721. * Clone this request
  34722. *
  34723. * @return Request
  34724. */
  34725. clone() {
  34726. return new _Request(this);
  34727. }
  34728. get [Symbol.toStringTag]() {
  34729. return "Request";
  34730. }
  34731. };
  34732. Object.defineProperties(Request3.prototype, {
  34733. method: { enumerable: true },
  34734. url: { enumerable: true },
  34735. headers: { enumerable: true },
  34736. redirect: { enumerable: true },
  34737. clone: { enumerable: true },
  34738. signal: { enumerable: true },
  34739. referrer: { enumerable: true },
  34740. referrerPolicy: { enumerable: true }
  34741. });
  34742. getNodeRequestOptions = (request2) => {
  34743. const { parsedURL } = request2[INTERNALS3];
  34744. const headers = new Headers2(request2[INTERNALS3].headers);
  34745. if (!headers.has("Accept")) {
  34746. headers.set("Accept", "*/*");
  34747. }
  34748. let contentLengthValue = null;
  34749. if (request2.body === null && /^(post|put)$/i.test(request2.method)) {
  34750. contentLengthValue = "0";
  34751. }
  34752. if (request2.body !== null) {
  34753. const totalBytes = getTotalBytes(request2);
  34754. if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
  34755. contentLengthValue = String(totalBytes);
  34756. }
  34757. }
  34758. if (contentLengthValue) {
  34759. headers.set("Content-Length", contentLengthValue);
  34760. }
  34761. if (request2.referrerPolicy === "") {
  34762. request2.referrerPolicy = DEFAULT_REFERRER_POLICY;
  34763. }
  34764. if (request2.referrer && request2.referrer !== "no-referrer") {
  34765. request2[INTERNALS3].referrer = determineRequestsReferrer(request2);
  34766. } else {
  34767. request2[INTERNALS3].referrer = "no-referrer";
  34768. }
  34769. if (request2[INTERNALS3].referrer instanceof URL) {
  34770. headers.set("Referer", request2.referrer);
  34771. }
  34772. if (!headers.has("User-Agent")) {
  34773. headers.set("User-Agent", "node-fetch");
  34774. }
  34775. if (request2.compress && !headers.has("Accept-Encoding")) {
  34776. headers.set("Accept-Encoding", "gzip, deflate, br");
  34777. }
  34778. let { agent } = request2;
  34779. if (typeof agent === "function") {
  34780. agent = agent(parsedURL);
  34781. }
  34782. const search = getSearch(parsedURL);
  34783. const options = {
  34784. // Overwrite search to retain trailing ? (issue #776)
  34785. path: parsedURL.pathname + search,
  34786. // The following options are not expressed in the URL
  34787. method: request2.method,
  34788. headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
  34789. insecureHTTPParser: request2.insecureHTTPParser,
  34790. agent
  34791. };
  34792. return {
  34793. /** @type {URL} */
  34794. parsedURL,
  34795. options
  34796. };
  34797. };
  34798. }
  34799. });
  34800. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js
  34801. var AbortError;
  34802. var init_abort_error = __esm({
  34803. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js"() {
  34804. "use strict";
  34805. init_base();
  34806. AbortError = class extends FetchBaseError {
  34807. constructor(message, type = "aborted") {
  34808. super(message, type);
  34809. }
  34810. };
  34811. }
  34812. });
  34813. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js
  34814. import http2 from "http";
  34815. import https from "https";
  34816. import zlib from "zlib";
  34817. import Stream2, { PassThrough as PassThrough2, pipeline as pump } from "stream";
  34818. import { Buffer as Buffer3 } from "buffer";
  34819. async function fetch2(url, options_) {
  34820. return new Promise((resolve, reject) => {
  34821. const request2 = new Request3(url, options_);
  34822. const { parsedURL, options } = getNodeRequestOptions(request2);
  34823. if (!supportedSchemas.has(parsedURL.protocol)) {
  34824. throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`);
  34825. }
  34826. if (parsedURL.protocol === "data:") {
  34827. const data = dist_default(request2.url);
  34828. const response2 = new Response3(data, { headers: { "Content-Type": data.typeFull } });
  34829. resolve(response2);
  34830. return;
  34831. }
  34832. const send = (parsedURL.protocol === "https:" ? https : http2).request;
  34833. const { signal } = request2;
  34834. let response = null;
  34835. const abort = () => {
  34836. const error2 = new AbortError("The operation was aborted.");
  34837. reject(error2);
  34838. if (request2.body && request2.body instanceof Stream2.Readable) {
  34839. request2.body.destroy(error2);
  34840. }
  34841. if (!response || !response.body) {
  34842. return;
  34843. }
  34844. response.body.emit("error", error2);
  34845. };
  34846. if (signal && signal.aborted) {
  34847. abort();
  34848. return;
  34849. }
  34850. const abortAndFinalize = () => {
  34851. abort();
  34852. finalize();
  34853. };
  34854. const request_ = send(parsedURL.toString(), options);
  34855. if (signal) {
  34856. signal.addEventListener("abort", abortAndFinalize);
  34857. }
  34858. const finalize = () => {
  34859. request_.abort();
  34860. if (signal) {
  34861. signal.removeEventListener("abort", abortAndFinalize);
  34862. }
  34863. };
  34864. request_.on("error", (error2) => {
  34865. reject(new FetchError(`request to ${request2.url} failed, reason: ${error2.message}`, "system", error2));
  34866. finalize();
  34867. });
  34868. fixResponseChunkedTransferBadEnding(request_, (error2) => {
  34869. if (response && response.body) {
  34870. response.body.destroy(error2);
  34871. }
  34872. });
  34873. if (process.version < "v14") {
  34874. request_.on("socket", (s6) => {
  34875. let endedWithEventsCount;
  34876. s6.prependListener("end", () => {
  34877. endedWithEventsCount = s6._eventsCount;
  34878. });
  34879. s6.prependListener("close", (hadError) => {
  34880. if (response && endedWithEventsCount < s6._eventsCount && !hadError) {
  34881. const error2 = new Error("Premature close");
  34882. error2.code = "ERR_STREAM_PREMATURE_CLOSE";
  34883. response.body.emit("error", error2);
  34884. }
  34885. });
  34886. });
  34887. }
  34888. request_.on("response", (response_) => {
  34889. request_.setTimeout(0);
  34890. const headers = fromRawHeaders(response_.rawHeaders);
  34891. if (isRedirect(response_.statusCode)) {
  34892. const location = headers.get("Location");
  34893. let locationURL = null;
  34894. try {
  34895. locationURL = location === null ? null : new URL(location, request2.url);
  34896. } catch {
  34897. if (request2.redirect !== "manual") {
  34898. reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
  34899. finalize();
  34900. return;
  34901. }
  34902. }
  34903. switch (request2.redirect) {
  34904. case "error":
  34905. reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request2.url}`, "no-redirect"));
  34906. finalize();
  34907. return;
  34908. case "manual":
  34909. break;
  34910. case "follow": {
  34911. if (locationURL === null) {
  34912. break;
  34913. }
  34914. if (request2.counter >= request2.follow) {
  34915. reject(new FetchError(`maximum redirect reached at: ${request2.url}`, "max-redirect"));
  34916. finalize();
  34917. return;
  34918. }
  34919. const requestOptions = {
  34920. headers: new Headers2(request2.headers),
  34921. follow: request2.follow,
  34922. counter: request2.counter + 1,
  34923. agent: request2.agent,
  34924. compress: request2.compress,
  34925. method: request2.method,
  34926. body: clone(request2),
  34927. signal: request2.signal,
  34928. size: request2.size,
  34929. referrer: request2.referrer,
  34930. referrerPolicy: request2.referrerPolicy
  34931. };
  34932. if (!isDomainOrSubdomain(request2.url, locationURL) || !isSameProtocol(request2.url, locationURL)) {
  34933. for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
  34934. requestOptions.headers.delete(name);
  34935. }
  34936. }
  34937. if (response_.statusCode !== 303 && request2.body && options_.body instanceof Stream2.Readable) {
  34938. reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
  34939. finalize();
  34940. return;
  34941. }
  34942. if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request2.method === "POST") {
  34943. requestOptions.method = "GET";
  34944. requestOptions.body = void 0;
  34945. requestOptions.headers.delete("content-length");
  34946. }
  34947. const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
  34948. if (responseReferrerPolicy) {
  34949. requestOptions.referrerPolicy = responseReferrerPolicy;
  34950. }
  34951. resolve(fetch2(new Request3(locationURL, requestOptions)));
  34952. finalize();
  34953. return;
  34954. }
  34955. default:
  34956. return reject(new TypeError(`Redirect option '${request2.redirect}' is not a valid value of RequestRedirect`));
  34957. }
  34958. }
  34959. if (signal) {
  34960. response_.once("end", () => {
  34961. signal.removeEventListener("abort", abortAndFinalize);
  34962. });
  34963. }
  34964. let body = pump(response_, new PassThrough2(), (error2) => {
  34965. if (error2) {
  34966. reject(error2);
  34967. }
  34968. });
  34969. if (process.version < "v12.10") {
  34970. response_.on("aborted", abortAndFinalize);
  34971. }
  34972. const responseOptions = {
  34973. url: request2.url,
  34974. status: response_.statusCode,
  34975. statusText: response_.statusMessage,
  34976. headers,
  34977. size: request2.size,
  34978. counter: request2.counter,
  34979. highWaterMark: request2.highWaterMark
  34980. };
  34981. const codings = headers.get("Content-Encoding");
  34982. if (!request2.compress || request2.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
  34983. response = new Response3(body, responseOptions);
  34984. resolve(response);
  34985. return;
  34986. }
  34987. const zlibOptions = {
  34988. flush: zlib.Z_SYNC_FLUSH,
  34989. finishFlush: zlib.Z_SYNC_FLUSH
  34990. };
  34991. if (codings === "gzip" || codings === "x-gzip") {
  34992. body = pump(body, zlib.createGunzip(zlibOptions), (error2) => {
  34993. if (error2) {
  34994. reject(error2);
  34995. }
  34996. });
  34997. response = new Response3(body, responseOptions);
  34998. resolve(response);
  34999. return;
  35000. }
  35001. if (codings === "deflate" || codings === "x-deflate") {
  35002. const raw2 = pump(response_, new PassThrough2(), (error2) => {
  35003. if (error2) {
  35004. reject(error2);
  35005. }
  35006. });
  35007. raw2.once("data", (chunk) => {
  35008. if ((chunk[0] & 15) === 8) {
  35009. body = pump(body, zlib.createInflate(), (error2) => {
  35010. if (error2) {
  35011. reject(error2);
  35012. }
  35013. });
  35014. } else {
  35015. body = pump(body, zlib.createInflateRaw(), (error2) => {
  35016. if (error2) {
  35017. reject(error2);
  35018. }
  35019. });
  35020. }
  35021. response = new Response3(body, responseOptions);
  35022. resolve(response);
  35023. });
  35024. raw2.once("end", () => {
  35025. if (!response) {
  35026. response = new Response3(body, responseOptions);
  35027. resolve(response);
  35028. }
  35029. });
  35030. return;
  35031. }
  35032. if (codings === "br") {
  35033. body = pump(body, zlib.createBrotliDecompress(), (error2) => {
  35034. if (error2) {
  35035. reject(error2);
  35036. }
  35037. });
  35038. response = new Response3(body, responseOptions);
  35039. resolve(response);
  35040. return;
  35041. }
  35042. response = new Response3(body, responseOptions);
  35043. resolve(response);
  35044. });
  35045. writeToStream(request_, request2).catch(reject);
  35046. });
  35047. }
  35048. function fixResponseChunkedTransferBadEnding(request2, errorCallback) {
  35049. const LAST_CHUNK = Buffer3.from("0\r\n\r\n");
  35050. let isChunkedTransfer = false;
  35051. let properLastChunkReceived = false;
  35052. let previousChunk;
  35053. request2.on("response", (response) => {
  35054. const { headers } = response;
  35055. isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
  35056. });
  35057. request2.on("socket", (socket) => {
  35058. const onSocketClose = () => {
  35059. if (isChunkedTransfer && !properLastChunkReceived) {
  35060. const error2 = new Error("Premature close");
  35061. error2.code = "ERR_STREAM_PREMATURE_CLOSE";
  35062. errorCallback(error2);
  35063. }
  35064. };
  35065. const onData = (buf) => {
  35066. properLastChunkReceived = Buffer3.compare(buf.slice(-5), LAST_CHUNK) === 0;
  35067. if (!properLastChunkReceived && previousChunk) {
  35068. properLastChunkReceived = Buffer3.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && Buffer3.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0;
  35069. }
  35070. previousChunk = buf;
  35071. };
  35072. socket.prependListener("close", onSocketClose);
  35073. socket.on("data", onData);
  35074. request2.on("close", () => {
  35075. socket.removeListener("close", onSocketClose);
  35076. socket.removeListener("data", onData);
  35077. });
  35078. });
  35079. }
  35080. var supportedSchemas;
  35081. var init_src = __esm({
  35082. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js"() {
  35083. "use strict";
  35084. init_dist3();
  35085. init_body2();
  35086. init_response();
  35087. init_headers();
  35088. init_request2();
  35089. init_fetch_error();
  35090. init_abort_error();
  35091. init_is_redirect();
  35092. init_esm_min();
  35093. init_is();
  35094. init_referrer();
  35095. init_from();
  35096. supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]);
  35097. }
  35098. });
  35099. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/constants.js
  35100. var require_constants = __commonJS({
  35101. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/constants.js"(exports, module) {
  35102. "use strict";
  35103. var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
  35104. var hasBlob = typeof Blob !== "undefined";
  35105. if (hasBlob) BINARY_TYPES.push("blob");
  35106. module.exports = {
  35107. BINARY_TYPES,
  35108. EMPTY_BUFFER: Buffer.alloc(0),
  35109. GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
  35110. hasBlob,
  35111. kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
  35112. kListener: Symbol("kListener"),
  35113. kStatusCode: Symbol("status-code"),
  35114. kWebSocket: Symbol("websocket"),
  35115. NOOP: () => {
  35116. }
  35117. };
  35118. }
  35119. });
  35120. // ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js
  35121. var require_node_gyp_build = __commonJS({
  35122. "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(exports, module) {
  35123. "use strict";
  35124. var fs5 = __require("fs");
  35125. var path3 = __require("path");
  35126. var os3 = __require("os");
  35127. var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
  35128. var vars = process.config && process.config.variables || {};
  35129. var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
  35130. var abi = process.versions.modules;
  35131. var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
  35132. var arch = process.env.npm_config_arch || os3.arch();
  35133. var platform2 = process.env.npm_config_platform || os3.platform();
  35134. var libc = process.env.LIBC || (isAlpine(platform2) ? "musl" : "glibc");
  35135. var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
  35136. var uv = (process.versions.uv || "").split(".")[0];
  35137. module.exports = load;
  35138. function load(dir) {
  35139. return runtimeRequire(load.resolve(dir));
  35140. }
  35141. load.resolve = load.path = function(dir) {
  35142. dir = path3.resolve(dir || ".");
  35143. try {
  35144. var name = runtimeRequire(path3.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
  35145. if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
  35146. } catch (err2) {
  35147. }
  35148. if (!prebuildsOnly) {
  35149. var release2 = getFirst(path3.join(dir, "build/Release"), matchBuild);
  35150. if (release2) return release2;
  35151. var debug = getFirst(path3.join(dir, "build/Debug"), matchBuild);
  35152. if (debug) return debug;
  35153. }
  35154. var prebuild = resolve(dir);
  35155. if (prebuild) return prebuild;
  35156. var nearby = resolve(path3.dirname(process.execPath));
  35157. if (nearby) return nearby;
  35158. var target = [
  35159. "platform=" + platform2,
  35160. "arch=" + arch,
  35161. "runtime=" + runtime,
  35162. "abi=" + abi,
  35163. "uv=" + uv,
  35164. armv ? "armv=" + armv : "",
  35165. "libc=" + libc,
  35166. "node=" + process.versions.node,
  35167. process.versions.electron ? "electron=" + process.versions.electron : "",
  35168. typeof __webpack_require__ === "function" ? "webpack=true" : ""
  35169. // eslint-disable-line
  35170. ].filter(Boolean).join(" ");
  35171. throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n");
  35172. function resolve(dir2) {
  35173. var tuples = readdirSync(path3.join(dir2, "prebuilds")).map(parseTuple);
  35174. var tuple = tuples.filter(matchTuple(platform2, arch)).sort(compareTuples)[0];
  35175. if (!tuple) return;
  35176. var prebuilds = path3.join(dir2, "prebuilds", tuple.name);
  35177. var parsed = readdirSync(prebuilds).map(parseTags);
  35178. var candidates = parsed.filter(matchTags(runtime, abi));
  35179. var winner = candidates.sort(compareTags(runtime))[0];
  35180. if (winner) return path3.join(prebuilds, winner.file);
  35181. }
  35182. };
  35183. function readdirSync(dir) {
  35184. try {
  35185. return fs5.readdirSync(dir);
  35186. } catch (err2) {
  35187. return [];
  35188. }
  35189. }
  35190. function getFirst(dir, filter2) {
  35191. var files = readdirSync(dir).filter(filter2);
  35192. return files[0] && path3.join(dir, files[0]);
  35193. }
  35194. function matchBuild(name) {
  35195. return /\.node$/.test(name);
  35196. }
  35197. function parseTuple(name) {
  35198. var arr = name.split("-");
  35199. if (arr.length !== 2) return;
  35200. var platform3 = arr[0];
  35201. var architectures = arr[1].split("+");
  35202. if (!platform3) return;
  35203. if (!architectures.length) return;
  35204. if (!architectures.every(Boolean)) return;
  35205. return { name, platform: platform3, architectures };
  35206. }
  35207. function matchTuple(platform3, arch2) {
  35208. return function(tuple) {
  35209. if (tuple == null) return false;
  35210. if (tuple.platform !== platform3) return false;
  35211. return tuple.architectures.includes(arch2);
  35212. };
  35213. }
  35214. function compareTuples(a5, b5) {
  35215. return a5.architectures.length - b5.architectures.length;
  35216. }
  35217. function parseTags(file) {
  35218. var arr = file.split(".");
  35219. var extension = arr.pop();
  35220. var tags = { file, specificity: 0 };
  35221. if (extension !== "node") return;
  35222. for (var i6 = 0; i6 < arr.length; i6++) {
  35223. var tag = arr[i6];
  35224. if (tag === "node" || tag === "electron" || tag === "node-webkit") {
  35225. tags.runtime = tag;
  35226. } else if (tag === "napi") {
  35227. tags.napi = true;
  35228. } else if (tag.slice(0, 3) === "abi") {
  35229. tags.abi = tag.slice(3);
  35230. } else if (tag.slice(0, 2) === "uv") {
  35231. tags.uv = tag.slice(2);
  35232. } else if (tag.slice(0, 4) === "armv") {
  35233. tags.armv = tag.slice(4);
  35234. } else if (tag === "glibc" || tag === "musl") {
  35235. tags.libc = tag;
  35236. } else {
  35237. continue;
  35238. }
  35239. tags.specificity++;
  35240. }
  35241. return tags;
  35242. }
  35243. function matchTags(runtime2, abi2) {
  35244. return function(tags) {
  35245. if (tags == null) return false;
  35246. if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
  35247. if (tags.abi && tags.abi !== abi2 && !tags.napi) return false;
  35248. if (tags.uv && tags.uv !== uv) return false;
  35249. if (tags.armv && tags.armv !== armv) return false;
  35250. if (tags.libc && tags.libc !== libc) return false;
  35251. return true;
  35252. };
  35253. }
  35254. function runtimeAgnostic(tags) {
  35255. return tags.runtime === "node" && tags.napi;
  35256. }
  35257. function compareTags(runtime2) {
  35258. return function(a5, b5) {
  35259. if (a5.runtime !== b5.runtime) {
  35260. return a5.runtime === runtime2 ? -1 : 1;
  35261. } else if (a5.abi !== b5.abi) {
  35262. return a5.abi ? -1 : 1;
  35263. } else if (a5.specificity !== b5.specificity) {
  35264. return a5.specificity > b5.specificity ? -1 : 1;
  35265. } else {
  35266. return 0;
  35267. }
  35268. };
  35269. }
  35270. function isNwjs() {
  35271. return !!(process.versions && process.versions.nw);
  35272. }
  35273. function isElectron() {
  35274. if (process.versions && process.versions.electron) return true;
  35275. if (process.env.ELECTRON_RUN_AS_NODE) return true;
  35276. return typeof window !== "undefined" && window.process && window.process.type === "renderer";
  35277. }
  35278. function isAlpine(platform3) {
  35279. return platform3 === "linux" && fs5.existsSync("/etc/alpine-release");
  35280. }
  35281. load.parseTags = parseTags;
  35282. load.matchTags = matchTags;
  35283. load.compareTags = compareTags;
  35284. load.parseTuple = parseTuple;
  35285. load.matchTuple = matchTuple;
  35286. load.compareTuples = compareTuples;
  35287. }
  35288. });
  35289. // ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js
  35290. var require_node_gyp_build2 = __commonJS({
  35291. "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(exports, module) {
  35292. "use strict";
  35293. var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
  35294. if (typeof runtimeRequire.addon === "function") {
  35295. module.exports = runtimeRequire.addon.bind(runtimeRequire);
  35296. } else {
  35297. module.exports = require_node_gyp_build();
  35298. }
  35299. }
  35300. });
  35301. // ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js
  35302. var require_fallback = __commonJS({
  35303. "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js"(exports, module) {
  35304. "use strict";
  35305. var mask = (source, mask2, output, offset, length) => {
  35306. for (var i6 = 0; i6 < length; i6++) {
  35307. output[offset + i6] = source[i6] ^ mask2[i6 & 3];
  35308. }
  35309. };
  35310. var unmask = (buffer, mask2) => {
  35311. const length = buffer.length;
  35312. for (var i6 = 0; i6 < length; i6++) {
  35313. buffer[i6] ^= mask2[i6 & 3];
  35314. }
  35315. };
  35316. module.exports = { mask, unmask };
  35317. }
  35318. });
  35319. // ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js
  35320. var require_bufferutil = __commonJS({
  35321. "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js"(exports, module) {
  35322. "use strict";
  35323. try {
  35324. module.exports = require_node_gyp_build2()(__dirname);
  35325. } catch (e6) {
  35326. module.exports = require_fallback();
  35327. }
  35328. }
  35329. });
  35330. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/buffer-util.js
  35331. var require_buffer_util = __commonJS({
  35332. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/buffer-util.js"(exports, module) {
  35333. "use strict";
  35334. var { EMPTY_BUFFER } = require_constants();
  35335. var FastBuffer = Buffer[Symbol.species];
  35336. function concat(list, totalLength) {
  35337. if (list.length === 0) return EMPTY_BUFFER;
  35338. if (list.length === 1) return list[0];
  35339. const target = Buffer.allocUnsafe(totalLength);
  35340. let offset = 0;
  35341. for (let i6 = 0; i6 < list.length; i6++) {
  35342. const buf = list[i6];
  35343. target.set(buf, offset);
  35344. offset += buf.length;
  35345. }
  35346. if (offset < totalLength) {
  35347. return new FastBuffer(target.buffer, target.byteOffset, offset);
  35348. }
  35349. return target;
  35350. }
  35351. function _mask(source, mask, output, offset, length) {
  35352. for (let i6 = 0; i6 < length; i6++) {
  35353. output[offset + i6] = source[i6] ^ mask[i6 & 3];
  35354. }
  35355. }
  35356. function _unmask(buffer, mask) {
  35357. for (let i6 = 0; i6 < buffer.length; i6++) {
  35358. buffer[i6] ^= mask[i6 & 3];
  35359. }
  35360. }
  35361. function toArrayBuffer(buf) {
  35362. if (buf.length === buf.buffer.byteLength) {
  35363. return buf.buffer;
  35364. }
  35365. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
  35366. }
  35367. function toBuffer(data) {
  35368. toBuffer.readOnly = true;
  35369. if (Buffer.isBuffer(data)) return data;
  35370. let buf;
  35371. if (data instanceof ArrayBuffer) {
  35372. buf = new FastBuffer(data);
  35373. } else if (ArrayBuffer.isView(data)) {
  35374. buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
  35375. } else {
  35376. buf = Buffer.from(data);
  35377. toBuffer.readOnly = false;
  35378. }
  35379. return buf;
  35380. }
  35381. module.exports = {
  35382. concat,
  35383. mask: _mask,
  35384. toArrayBuffer,
  35385. toBuffer,
  35386. unmask: _unmask
  35387. };
  35388. if (!process.env.WS_NO_BUFFER_UTIL) {
  35389. try {
  35390. const bufferUtil = require_bufferutil();
  35391. module.exports.mask = function(source, mask, output, offset, length) {
  35392. if (length < 48) _mask(source, mask, output, offset, length);
  35393. else bufferUtil.mask(source, mask, output, offset, length);
  35394. };
  35395. module.exports.unmask = function(buffer, mask) {
  35396. if (buffer.length < 32) _unmask(buffer, mask);
  35397. else bufferUtil.unmask(buffer, mask);
  35398. };
  35399. } catch (e6) {
  35400. }
  35401. }
  35402. }
  35403. });
  35404. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/limiter.js
  35405. var require_limiter = __commonJS({
  35406. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/limiter.js"(exports, module) {
  35407. "use strict";
  35408. var kDone = Symbol("kDone");
  35409. var kRun = Symbol("kRun");
  35410. var Limiter = class {
  35411. /**
  35412. * Creates a new `Limiter`.
  35413. *
  35414. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  35415. * to run concurrently
  35416. */
  35417. constructor(concurrency) {
  35418. this[kDone] = () => {
  35419. this.pending--;
  35420. this[kRun]();
  35421. };
  35422. this.concurrency = concurrency || Infinity;
  35423. this.jobs = [];
  35424. this.pending = 0;
  35425. }
  35426. /**
  35427. * Adds a job to the queue.
  35428. *
  35429. * @param {Function} job The job to run
  35430. * @public
  35431. */
  35432. add(job) {
  35433. this.jobs.push(job);
  35434. this[kRun]();
  35435. }
  35436. /**
  35437. * Removes a job from the queue and runs it if possible.
  35438. *
  35439. * @private
  35440. */
  35441. [kRun]() {
  35442. if (this.pending === this.concurrency) return;
  35443. if (this.jobs.length) {
  35444. const job = this.jobs.shift();
  35445. this.pending++;
  35446. job(this[kDone]);
  35447. }
  35448. }
  35449. };
  35450. module.exports = Limiter;
  35451. }
  35452. });
  35453. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/permessage-deflate.js
  35454. var require_permessage_deflate = __commonJS({
  35455. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
  35456. "use strict";
  35457. var zlib2 = __require("zlib");
  35458. var bufferUtil = require_buffer_util();
  35459. var Limiter = require_limiter();
  35460. var { kStatusCode } = require_constants();
  35461. var FastBuffer = Buffer[Symbol.species];
  35462. var TRAILER = Buffer.from([0, 0, 255, 255]);
  35463. var kPerMessageDeflate = Symbol("permessage-deflate");
  35464. var kTotalLength = Symbol("total-length");
  35465. var kCallback = Symbol("callback");
  35466. var kBuffers = Symbol("buffers");
  35467. var kError = Symbol("error");
  35468. var zlibLimiter;
  35469. var PerMessageDeflate = class {
  35470. /**
  35471. * Creates a PerMessageDeflate instance.
  35472. *
  35473. * @param {Object} [options] Configuration options
  35474. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  35475. * for, or request, a custom client window size
  35476. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  35477. * acknowledge disabling of client context takeover
  35478. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  35479. * calls to zlib
  35480. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  35481. * use of a custom server window size
  35482. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  35483. * disabling of server context takeover
  35484. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  35485. * messages should not be compressed if context takeover is disabled
  35486. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  35487. * deflate
  35488. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  35489. * inflate
  35490. * @param {Boolean} [isServer=false] Create the instance in either server or
  35491. * client mode
  35492. * @param {Number} [maxPayload=0] The maximum allowed message length
  35493. */
  35494. constructor(options, isServer, maxPayload) {
  35495. this._maxPayload = maxPayload | 0;
  35496. this._options = options || {};
  35497. this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
  35498. this._isServer = !!isServer;
  35499. this._deflate = null;
  35500. this._inflate = null;
  35501. this.params = null;
  35502. if (!zlibLimiter) {
  35503. const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
  35504. zlibLimiter = new Limiter(concurrency);
  35505. }
  35506. }
  35507. /**
  35508. * @type {String}
  35509. */
  35510. static get extensionName() {
  35511. return "permessage-deflate";
  35512. }
  35513. /**
  35514. * Create an extension negotiation offer.
  35515. *
  35516. * @return {Object} Extension parameters
  35517. * @public
  35518. */
  35519. offer() {
  35520. const params = {};
  35521. if (this._options.serverNoContextTakeover) {
  35522. params.server_no_context_takeover = true;
  35523. }
  35524. if (this._options.clientNoContextTakeover) {
  35525. params.client_no_context_takeover = true;
  35526. }
  35527. if (this._options.serverMaxWindowBits) {
  35528. params.server_max_window_bits = this._options.serverMaxWindowBits;
  35529. }
  35530. if (this._options.clientMaxWindowBits) {
  35531. params.client_max_window_bits = this._options.clientMaxWindowBits;
  35532. } else if (this._options.clientMaxWindowBits == null) {
  35533. params.client_max_window_bits = true;
  35534. }
  35535. return params;
  35536. }
  35537. /**
  35538. * Accept an extension negotiation offer/response.
  35539. *
  35540. * @param {Array} configurations The extension negotiation offers/reponse
  35541. * @return {Object} Accepted configuration
  35542. * @public
  35543. */
  35544. accept(configurations) {
  35545. configurations = this.normalizeParams(configurations);
  35546. this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
  35547. return this.params;
  35548. }
  35549. /**
  35550. * Releases all resources used by the extension.
  35551. *
  35552. * @public
  35553. */
  35554. cleanup() {
  35555. if (this._inflate) {
  35556. this._inflate.close();
  35557. this._inflate = null;
  35558. }
  35559. if (this._deflate) {
  35560. const callback = this._deflate[kCallback];
  35561. this._deflate.close();
  35562. this._deflate = null;
  35563. if (callback) {
  35564. callback(
  35565. new Error(
  35566. "The deflate stream was closed while data was being processed"
  35567. )
  35568. );
  35569. }
  35570. }
  35571. }
  35572. /**
  35573. * Accept an extension negotiation offer.
  35574. *
  35575. * @param {Array} offers The extension negotiation offers
  35576. * @return {Object} Accepted configuration
  35577. * @private
  35578. */
  35579. acceptAsServer(offers) {
  35580. const opts = this._options;
  35581. const accepted = offers.find((params) => {
  35582. if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
  35583. return false;
  35584. }
  35585. return true;
  35586. });
  35587. if (!accepted) {
  35588. throw new Error("None of the extension offers can be accepted");
  35589. }
  35590. if (opts.serverNoContextTakeover) {
  35591. accepted.server_no_context_takeover = true;
  35592. }
  35593. if (opts.clientNoContextTakeover) {
  35594. accepted.client_no_context_takeover = true;
  35595. }
  35596. if (typeof opts.serverMaxWindowBits === "number") {
  35597. accepted.server_max_window_bits = opts.serverMaxWindowBits;
  35598. }
  35599. if (typeof opts.clientMaxWindowBits === "number") {
  35600. accepted.client_max_window_bits = opts.clientMaxWindowBits;
  35601. } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
  35602. delete accepted.client_max_window_bits;
  35603. }
  35604. return accepted;
  35605. }
  35606. /**
  35607. * Accept the extension negotiation response.
  35608. *
  35609. * @param {Array} response The extension negotiation response
  35610. * @return {Object} Accepted configuration
  35611. * @private
  35612. */
  35613. acceptAsClient(response) {
  35614. const params = response[0];
  35615. if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
  35616. throw new Error('Unexpected parameter "client_no_context_takeover"');
  35617. }
  35618. if (!params.client_max_window_bits) {
  35619. if (typeof this._options.clientMaxWindowBits === "number") {
  35620. params.client_max_window_bits = this._options.clientMaxWindowBits;
  35621. }
  35622. } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
  35623. throw new Error(
  35624. 'Unexpected or invalid parameter "client_max_window_bits"'
  35625. );
  35626. }
  35627. return params;
  35628. }
  35629. /**
  35630. * Normalize parameters.
  35631. *
  35632. * @param {Array} configurations The extension negotiation offers/reponse
  35633. * @return {Array} The offers/response with normalized parameters
  35634. * @private
  35635. */
  35636. normalizeParams(configurations) {
  35637. configurations.forEach((params) => {
  35638. Object.keys(params).forEach((key) => {
  35639. let value = params[key];
  35640. if (value.length > 1) {
  35641. throw new Error(`Parameter "${key}" must have only a single value`);
  35642. }
  35643. value = value[0];
  35644. if (key === "client_max_window_bits") {
  35645. if (value !== true) {
  35646. const num = +value;
  35647. if (!Number.isInteger(num) || num < 8 || num > 15) {
  35648. throw new TypeError(
  35649. `Invalid value for parameter "${key}": ${value}`
  35650. );
  35651. }
  35652. value = num;
  35653. } else if (!this._isServer) {
  35654. throw new TypeError(
  35655. `Invalid value for parameter "${key}": ${value}`
  35656. );
  35657. }
  35658. } else if (key === "server_max_window_bits") {
  35659. const num = +value;
  35660. if (!Number.isInteger(num) || num < 8 || num > 15) {
  35661. throw new TypeError(
  35662. `Invalid value for parameter "${key}": ${value}`
  35663. );
  35664. }
  35665. value = num;
  35666. } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
  35667. if (value !== true) {
  35668. throw new TypeError(
  35669. `Invalid value for parameter "${key}": ${value}`
  35670. );
  35671. }
  35672. } else {
  35673. throw new Error(`Unknown parameter "${key}"`);
  35674. }
  35675. params[key] = value;
  35676. });
  35677. });
  35678. return configurations;
  35679. }
  35680. /**
  35681. * Decompress data. Concurrency limited.
  35682. *
  35683. * @param {Buffer} data Compressed data
  35684. * @param {Boolean} fin Specifies whether or not this is the last fragment
  35685. * @param {Function} callback Callback
  35686. * @public
  35687. */
  35688. decompress(data, fin, callback) {
  35689. zlibLimiter.add((done) => {
  35690. this._decompress(data, fin, (err2, result) => {
  35691. done();
  35692. callback(err2, result);
  35693. });
  35694. });
  35695. }
  35696. /**
  35697. * Compress data. Concurrency limited.
  35698. *
  35699. * @param {(Buffer|String)} data Data to compress
  35700. * @param {Boolean} fin Specifies whether or not this is the last fragment
  35701. * @param {Function} callback Callback
  35702. * @public
  35703. */
  35704. compress(data, fin, callback) {
  35705. zlibLimiter.add((done) => {
  35706. this._compress(data, fin, (err2, result) => {
  35707. done();
  35708. callback(err2, result);
  35709. });
  35710. });
  35711. }
  35712. /**
  35713. * Decompress data.
  35714. *
  35715. * @param {Buffer} data Compressed data
  35716. * @param {Boolean} fin Specifies whether or not this is the last fragment
  35717. * @param {Function} callback Callback
  35718. * @private
  35719. */
  35720. _decompress(data, fin, callback) {
  35721. const endpoint = this._isServer ? "client" : "server";
  35722. if (!this._inflate) {
  35723. const key = `${endpoint}_max_window_bits`;
  35724. const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
  35725. this._inflate = zlib2.createInflateRaw({
  35726. ...this._options.zlibInflateOptions,
  35727. windowBits
  35728. });
  35729. this._inflate[kPerMessageDeflate] = this;
  35730. this._inflate[kTotalLength] = 0;
  35731. this._inflate[kBuffers] = [];
  35732. this._inflate.on("error", inflateOnError);
  35733. this._inflate.on("data", inflateOnData);
  35734. }
  35735. this._inflate[kCallback] = callback;
  35736. this._inflate.write(data);
  35737. if (fin) this._inflate.write(TRAILER);
  35738. this._inflate.flush(() => {
  35739. const err2 = this._inflate[kError];
  35740. if (err2) {
  35741. this._inflate.close();
  35742. this._inflate = null;
  35743. callback(err2);
  35744. return;
  35745. }
  35746. const data2 = bufferUtil.concat(
  35747. this._inflate[kBuffers],
  35748. this._inflate[kTotalLength]
  35749. );
  35750. if (this._inflate._readableState.endEmitted) {
  35751. this._inflate.close();
  35752. this._inflate = null;
  35753. } else {
  35754. this._inflate[kTotalLength] = 0;
  35755. this._inflate[kBuffers] = [];
  35756. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  35757. this._inflate.reset();
  35758. }
  35759. }
  35760. callback(null, data2);
  35761. });
  35762. }
  35763. /**
  35764. * Compress data.
  35765. *
  35766. * @param {(Buffer|String)} data Data to compress
  35767. * @param {Boolean} fin Specifies whether or not this is the last fragment
  35768. * @param {Function} callback Callback
  35769. * @private
  35770. */
  35771. _compress(data, fin, callback) {
  35772. const endpoint = this._isServer ? "server" : "client";
  35773. if (!this._deflate) {
  35774. const key = `${endpoint}_max_window_bits`;
  35775. const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
  35776. this._deflate = zlib2.createDeflateRaw({
  35777. ...this._options.zlibDeflateOptions,
  35778. windowBits
  35779. });
  35780. this._deflate[kTotalLength] = 0;
  35781. this._deflate[kBuffers] = [];
  35782. this._deflate.on("data", deflateOnData);
  35783. }
  35784. this._deflate[kCallback] = callback;
  35785. this._deflate.write(data);
  35786. this._deflate.flush(zlib2.Z_SYNC_FLUSH, () => {
  35787. if (!this._deflate) {
  35788. return;
  35789. }
  35790. let data2 = bufferUtil.concat(
  35791. this._deflate[kBuffers],
  35792. this._deflate[kTotalLength]
  35793. );
  35794. if (fin) {
  35795. data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
  35796. }
  35797. this._deflate[kCallback] = null;
  35798. this._deflate[kTotalLength] = 0;
  35799. this._deflate[kBuffers] = [];
  35800. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  35801. this._deflate.reset();
  35802. }
  35803. callback(null, data2);
  35804. });
  35805. }
  35806. };
  35807. module.exports = PerMessageDeflate;
  35808. function deflateOnData(chunk) {
  35809. this[kBuffers].push(chunk);
  35810. this[kTotalLength] += chunk.length;
  35811. }
  35812. function inflateOnData(chunk) {
  35813. this[kTotalLength] += chunk.length;
  35814. if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
  35815. this[kBuffers].push(chunk);
  35816. return;
  35817. }
  35818. this[kError] = new RangeError("Max payload size exceeded");
  35819. this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
  35820. this[kError][kStatusCode] = 1009;
  35821. this.removeListener("data", inflateOnData);
  35822. this.reset();
  35823. }
  35824. function inflateOnError(err2) {
  35825. this[kPerMessageDeflate]._inflate = null;
  35826. if (this[kError]) {
  35827. this[kCallback](this[kError]);
  35828. return;
  35829. }
  35830. err2[kStatusCode] = 1007;
  35831. this[kCallback](err2);
  35832. }
  35833. }
  35834. });
  35835. // ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js
  35836. var require_fallback2 = __commonJS({
  35837. "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js"(exports, module) {
  35838. "use strict";
  35839. function isValidUTF8(buf) {
  35840. const len = buf.length;
  35841. let i6 = 0;
  35842. while (i6 < len) {
  35843. if ((buf[i6] & 128) === 0) {
  35844. i6++;
  35845. } else if ((buf[i6] & 224) === 192) {
  35846. if (i6 + 1 === len || (buf[i6 + 1] & 192) !== 128 || (buf[i6] & 254) === 192) {
  35847. return false;
  35848. }
  35849. i6 += 2;
  35850. } else if ((buf[i6] & 240) === 224) {
  35851. if (i6 + 2 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || buf[i6] === 224 && (buf[i6 + 1] & 224) === 128 || // overlong
  35852. buf[i6] === 237 && (buf[i6 + 1] & 224) === 160) {
  35853. return false;
  35854. }
  35855. i6 += 3;
  35856. } else if ((buf[i6] & 248) === 240) {
  35857. if (i6 + 3 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || (buf[i6 + 3] & 192) !== 128 || buf[i6] === 240 && (buf[i6 + 1] & 240) === 128 || // overlong
  35858. buf[i6] === 244 && buf[i6 + 1] > 143 || buf[i6] > 244) {
  35859. return false;
  35860. }
  35861. i6 += 4;
  35862. } else {
  35863. return false;
  35864. }
  35865. }
  35866. return true;
  35867. }
  35868. module.exports = isValidUTF8;
  35869. }
  35870. });
  35871. // ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js
  35872. var require_utf_8_validate = __commonJS({
  35873. "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js"(exports, module) {
  35874. "use strict";
  35875. try {
  35876. module.exports = require_node_gyp_build2()(__dirname);
  35877. } catch (e6) {
  35878. module.exports = require_fallback2();
  35879. }
  35880. }
  35881. });
  35882. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/validation.js
  35883. var require_validation = __commonJS({
  35884. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/validation.js"(exports, module) {
  35885. "use strict";
  35886. var { isUtf8 } = __require("buffer");
  35887. var { hasBlob } = require_constants();
  35888. var tokenChars = [
  35889. 0,
  35890. 0,
  35891. 0,
  35892. 0,
  35893. 0,
  35894. 0,
  35895. 0,
  35896. 0,
  35897. 0,
  35898. 0,
  35899. 0,
  35900. 0,
  35901. 0,
  35902. 0,
  35903. 0,
  35904. 0,
  35905. // 0 - 15
  35906. 0,
  35907. 0,
  35908. 0,
  35909. 0,
  35910. 0,
  35911. 0,
  35912. 0,
  35913. 0,
  35914. 0,
  35915. 0,
  35916. 0,
  35917. 0,
  35918. 0,
  35919. 0,
  35920. 0,
  35921. 0,
  35922. // 16 - 31
  35923. 0,
  35924. 1,
  35925. 0,
  35926. 1,
  35927. 1,
  35928. 1,
  35929. 1,
  35930. 1,
  35931. 0,
  35932. 0,
  35933. 1,
  35934. 1,
  35935. 0,
  35936. 1,
  35937. 1,
  35938. 0,
  35939. // 32 - 47
  35940. 1,
  35941. 1,
  35942. 1,
  35943. 1,
  35944. 1,
  35945. 1,
  35946. 1,
  35947. 1,
  35948. 1,
  35949. 1,
  35950. 0,
  35951. 0,
  35952. 0,
  35953. 0,
  35954. 0,
  35955. 0,
  35956. // 48 - 63
  35957. 0,
  35958. 1,
  35959. 1,
  35960. 1,
  35961. 1,
  35962. 1,
  35963. 1,
  35964. 1,
  35965. 1,
  35966. 1,
  35967. 1,
  35968. 1,
  35969. 1,
  35970. 1,
  35971. 1,
  35972. 1,
  35973. // 64 - 79
  35974. 1,
  35975. 1,
  35976. 1,
  35977. 1,
  35978. 1,
  35979. 1,
  35980. 1,
  35981. 1,
  35982. 1,
  35983. 1,
  35984. 1,
  35985. 0,
  35986. 0,
  35987. 0,
  35988. 1,
  35989. 1,
  35990. // 80 - 95
  35991. 1,
  35992. 1,
  35993. 1,
  35994. 1,
  35995. 1,
  35996. 1,
  35997. 1,
  35998. 1,
  35999. 1,
  36000. 1,
  36001. 1,
  36002. 1,
  36003. 1,
  36004. 1,
  36005. 1,
  36006. 1,
  36007. // 96 - 111
  36008. 1,
  36009. 1,
  36010. 1,
  36011. 1,
  36012. 1,
  36013. 1,
  36014. 1,
  36015. 1,
  36016. 1,
  36017. 1,
  36018. 1,
  36019. 0,
  36020. 1,
  36021. 0,
  36022. 1,
  36023. 0
  36024. // 112 - 127
  36025. ];
  36026. function isValidStatusCode(code) {
  36027. return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
  36028. }
  36029. function _isValidUTF8(buf) {
  36030. const len = buf.length;
  36031. let i6 = 0;
  36032. while (i6 < len) {
  36033. if ((buf[i6] & 128) === 0) {
  36034. i6++;
  36035. } else if ((buf[i6] & 224) === 192) {
  36036. if (i6 + 1 === len || (buf[i6 + 1] & 192) !== 128 || (buf[i6] & 254) === 192) {
  36037. return false;
  36038. }
  36039. i6 += 2;
  36040. } else if ((buf[i6] & 240) === 224) {
  36041. if (i6 + 2 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || buf[i6] === 224 && (buf[i6 + 1] & 224) === 128 || // Overlong
  36042. buf[i6] === 237 && (buf[i6 + 1] & 224) === 160) {
  36043. return false;
  36044. }
  36045. i6 += 3;
  36046. } else if ((buf[i6] & 248) === 240) {
  36047. if (i6 + 3 >= len || (buf[i6 + 1] & 192) !== 128 || (buf[i6 + 2] & 192) !== 128 || (buf[i6 + 3] & 192) !== 128 || buf[i6] === 240 && (buf[i6 + 1] & 240) === 128 || // Overlong
  36048. buf[i6] === 244 && buf[i6 + 1] > 143 || buf[i6] > 244) {
  36049. return false;
  36050. }
  36051. i6 += 4;
  36052. } else {
  36053. return false;
  36054. }
  36055. }
  36056. return true;
  36057. }
  36058. function isBlob3(value) {
  36059. return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
  36060. }
  36061. module.exports = {
  36062. isBlob: isBlob3,
  36063. isValidStatusCode,
  36064. isValidUTF8: _isValidUTF8,
  36065. tokenChars
  36066. };
  36067. if (isUtf8) {
  36068. module.exports.isValidUTF8 = function(buf) {
  36069. return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
  36070. };
  36071. } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
  36072. try {
  36073. const isValidUTF8 = require_utf_8_validate();
  36074. module.exports.isValidUTF8 = function(buf) {
  36075. return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
  36076. };
  36077. } catch (e6) {
  36078. }
  36079. }
  36080. }
  36081. });
  36082. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/receiver.js
  36083. var require_receiver = __commonJS({
  36084. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/receiver.js"(exports, module) {
  36085. "use strict";
  36086. var { Writable: Writable2 } = __require("stream");
  36087. var PerMessageDeflate = require_permessage_deflate();
  36088. var {
  36089. BINARY_TYPES,
  36090. EMPTY_BUFFER,
  36091. kStatusCode,
  36092. kWebSocket
  36093. } = require_constants();
  36094. var { concat, toArrayBuffer, unmask } = require_buffer_util();
  36095. var { isValidStatusCode, isValidUTF8 } = require_validation();
  36096. var FastBuffer = Buffer[Symbol.species];
  36097. var GET_INFO = 0;
  36098. var GET_PAYLOAD_LENGTH_16 = 1;
  36099. var GET_PAYLOAD_LENGTH_64 = 2;
  36100. var GET_MASK = 3;
  36101. var GET_DATA = 4;
  36102. var INFLATING = 5;
  36103. var DEFER_EVENT = 6;
  36104. var Receiver2 = class extends Writable2 {
  36105. /**
  36106. * Creates a Receiver instance.
  36107. *
  36108. * @param {Object} [options] Options object
  36109. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  36110. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  36111. * multiple times in the same tick
  36112. * @param {String} [options.binaryType=nodebuffer] The type for binary data
  36113. * @param {Object} [options.extensions] An object containing the negotiated
  36114. * extensions
  36115. * @param {Boolean} [options.isServer=false] Specifies whether to operate in
  36116. * client or server mode
  36117. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  36118. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  36119. * not to skip UTF-8 validation for text and close messages
  36120. */
  36121. constructor(options = {}) {
  36122. super();
  36123. this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
  36124. this._binaryType = options.binaryType || BINARY_TYPES[0];
  36125. this._extensions = options.extensions || {};
  36126. this._isServer = !!options.isServer;
  36127. this._maxPayload = options.maxPayload | 0;
  36128. this._skipUTF8Validation = !!options.skipUTF8Validation;
  36129. this[kWebSocket] = void 0;
  36130. this._bufferedBytes = 0;
  36131. this._buffers = [];
  36132. this._compressed = false;
  36133. this._payloadLength = 0;
  36134. this._mask = void 0;
  36135. this._fragmented = 0;
  36136. this._masked = false;
  36137. this._fin = false;
  36138. this._opcode = 0;
  36139. this._totalPayloadLength = 0;
  36140. this._messageLength = 0;
  36141. this._fragments = [];
  36142. this._errored = false;
  36143. this._loop = false;
  36144. this._state = GET_INFO;
  36145. }
  36146. /**
  36147. * Implements `Writable.prototype._write()`.
  36148. *
  36149. * @param {Buffer} chunk The chunk of data to write
  36150. * @param {String} encoding The character encoding of `chunk`
  36151. * @param {Function} cb Callback
  36152. * @private
  36153. */
  36154. _write(chunk, encoding, cb) {
  36155. if (this._opcode === 8 && this._state == GET_INFO) return cb();
  36156. this._bufferedBytes += chunk.length;
  36157. this._buffers.push(chunk);
  36158. this.startLoop(cb);
  36159. }
  36160. /**
  36161. * Consumes `n` bytes from the buffered data.
  36162. *
  36163. * @param {Number} n The number of bytes to consume
  36164. * @return {Buffer} The consumed bytes
  36165. * @private
  36166. */
  36167. consume(n5) {
  36168. this._bufferedBytes -= n5;
  36169. if (n5 === this._buffers[0].length) return this._buffers.shift();
  36170. if (n5 < this._buffers[0].length) {
  36171. const buf = this._buffers[0];
  36172. this._buffers[0] = new FastBuffer(
  36173. buf.buffer,
  36174. buf.byteOffset + n5,
  36175. buf.length - n5
  36176. );
  36177. return new FastBuffer(buf.buffer, buf.byteOffset, n5);
  36178. }
  36179. const dst = Buffer.allocUnsafe(n5);
  36180. do {
  36181. const buf = this._buffers[0];
  36182. const offset = dst.length - n5;
  36183. if (n5 >= buf.length) {
  36184. dst.set(this._buffers.shift(), offset);
  36185. } else {
  36186. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n5), offset);
  36187. this._buffers[0] = new FastBuffer(
  36188. buf.buffer,
  36189. buf.byteOffset + n5,
  36190. buf.length - n5
  36191. );
  36192. }
  36193. n5 -= buf.length;
  36194. } while (n5 > 0);
  36195. return dst;
  36196. }
  36197. /**
  36198. * Starts the parsing loop.
  36199. *
  36200. * @param {Function} cb Callback
  36201. * @private
  36202. */
  36203. startLoop(cb) {
  36204. this._loop = true;
  36205. do {
  36206. switch (this._state) {
  36207. case GET_INFO:
  36208. this.getInfo(cb);
  36209. break;
  36210. case GET_PAYLOAD_LENGTH_16:
  36211. this.getPayloadLength16(cb);
  36212. break;
  36213. case GET_PAYLOAD_LENGTH_64:
  36214. this.getPayloadLength64(cb);
  36215. break;
  36216. case GET_MASK:
  36217. this.getMask();
  36218. break;
  36219. case GET_DATA:
  36220. this.getData(cb);
  36221. break;
  36222. case INFLATING:
  36223. case DEFER_EVENT:
  36224. this._loop = false;
  36225. return;
  36226. }
  36227. } while (this._loop);
  36228. if (!this._errored) cb();
  36229. }
  36230. /**
  36231. * Reads the first two bytes of a frame.
  36232. *
  36233. * @param {Function} cb Callback
  36234. * @private
  36235. */
  36236. getInfo(cb) {
  36237. if (this._bufferedBytes < 2) {
  36238. this._loop = false;
  36239. return;
  36240. }
  36241. const buf = this.consume(2);
  36242. if ((buf[0] & 48) !== 0) {
  36243. const error2 = this.createError(
  36244. RangeError,
  36245. "RSV2 and RSV3 must be clear",
  36246. true,
  36247. 1002,
  36248. "WS_ERR_UNEXPECTED_RSV_2_3"
  36249. );
  36250. cb(error2);
  36251. return;
  36252. }
  36253. const compressed = (buf[0] & 64) === 64;
  36254. if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
  36255. const error2 = this.createError(
  36256. RangeError,
  36257. "RSV1 must be clear",
  36258. true,
  36259. 1002,
  36260. "WS_ERR_UNEXPECTED_RSV_1"
  36261. );
  36262. cb(error2);
  36263. return;
  36264. }
  36265. this._fin = (buf[0] & 128) === 128;
  36266. this._opcode = buf[0] & 15;
  36267. this._payloadLength = buf[1] & 127;
  36268. if (this._opcode === 0) {
  36269. if (compressed) {
  36270. const error2 = this.createError(
  36271. RangeError,
  36272. "RSV1 must be clear",
  36273. true,
  36274. 1002,
  36275. "WS_ERR_UNEXPECTED_RSV_1"
  36276. );
  36277. cb(error2);
  36278. return;
  36279. }
  36280. if (!this._fragmented) {
  36281. const error2 = this.createError(
  36282. RangeError,
  36283. "invalid opcode 0",
  36284. true,
  36285. 1002,
  36286. "WS_ERR_INVALID_OPCODE"
  36287. );
  36288. cb(error2);
  36289. return;
  36290. }
  36291. this._opcode = this._fragmented;
  36292. } else if (this._opcode === 1 || this._opcode === 2) {
  36293. if (this._fragmented) {
  36294. const error2 = this.createError(
  36295. RangeError,
  36296. `invalid opcode ${this._opcode}`,
  36297. true,
  36298. 1002,
  36299. "WS_ERR_INVALID_OPCODE"
  36300. );
  36301. cb(error2);
  36302. return;
  36303. }
  36304. this._compressed = compressed;
  36305. } else if (this._opcode > 7 && this._opcode < 11) {
  36306. if (!this._fin) {
  36307. const error2 = this.createError(
  36308. RangeError,
  36309. "FIN must be set",
  36310. true,
  36311. 1002,
  36312. "WS_ERR_EXPECTED_FIN"
  36313. );
  36314. cb(error2);
  36315. return;
  36316. }
  36317. if (compressed) {
  36318. const error2 = this.createError(
  36319. RangeError,
  36320. "RSV1 must be clear",
  36321. true,
  36322. 1002,
  36323. "WS_ERR_UNEXPECTED_RSV_1"
  36324. );
  36325. cb(error2);
  36326. return;
  36327. }
  36328. if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
  36329. const error2 = this.createError(
  36330. RangeError,
  36331. `invalid payload length ${this._payloadLength}`,
  36332. true,
  36333. 1002,
  36334. "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
  36335. );
  36336. cb(error2);
  36337. return;
  36338. }
  36339. } else {
  36340. const error2 = this.createError(
  36341. RangeError,
  36342. `invalid opcode ${this._opcode}`,
  36343. true,
  36344. 1002,
  36345. "WS_ERR_INVALID_OPCODE"
  36346. );
  36347. cb(error2);
  36348. return;
  36349. }
  36350. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  36351. this._masked = (buf[1] & 128) === 128;
  36352. if (this._isServer) {
  36353. if (!this._masked) {
  36354. const error2 = this.createError(
  36355. RangeError,
  36356. "MASK must be set",
  36357. true,
  36358. 1002,
  36359. "WS_ERR_EXPECTED_MASK"
  36360. );
  36361. cb(error2);
  36362. return;
  36363. }
  36364. } else if (this._masked) {
  36365. const error2 = this.createError(
  36366. RangeError,
  36367. "MASK must be clear",
  36368. true,
  36369. 1002,
  36370. "WS_ERR_UNEXPECTED_MASK"
  36371. );
  36372. cb(error2);
  36373. return;
  36374. }
  36375. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  36376. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  36377. else this.haveLength(cb);
  36378. }
  36379. /**
  36380. * Gets extended payload length (7+16).
  36381. *
  36382. * @param {Function} cb Callback
  36383. * @private
  36384. */
  36385. getPayloadLength16(cb) {
  36386. if (this._bufferedBytes < 2) {
  36387. this._loop = false;
  36388. return;
  36389. }
  36390. this._payloadLength = this.consume(2).readUInt16BE(0);
  36391. this.haveLength(cb);
  36392. }
  36393. /**
  36394. * Gets extended payload length (7+64).
  36395. *
  36396. * @param {Function} cb Callback
  36397. * @private
  36398. */
  36399. getPayloadLength64(cb) {
  36400. if (this._bufferedBytes < 8) {
  36401. this._loop = false;
  36402. return;
  36403. }
  36404. const buf = this.consume(8);
  36405. const num = buf.readUInt32BE(0);
  36406. if (num > Math.pow(2, 53 - 32) - 1) {
  36407. const error2 = this.createError(
  36408. RangeError,
  36409. "Unsupported WebSocket frame: payload length > 2^53 - 1",
  36410. false,
  36411. 1009,
  36412. "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
  36413. );
  36414. cb(error2);
  36415. return;
  36416. }
  36417. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  36418. this.haveLength(cb);
  36419. }
  36420. /**
  36421. * Payload length has been read.
  36422. *
  36423. * @param {Function} cb Callback
  36424. * @private
  36425. */
  36426. haveLength(cb) {
  36427. if (this._payloadLength && this._opcode < 8) {
  36428. this._totalPayloadLength += this._payloadLength;
  36429. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  36430. const error2 = this.createError(
  36431. RangeError,
  36432. "Max payload size exceeded",
  36433. false,
  36434. 1009,
  36435. "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
  36436. );
  36437. cb(error2);
  36438. return;
  36439. }
  36440. }
  36441. if (this._masked) this._state = GET_MASK;
  36442. else this._state = GET_DATA;
  36443. }
  36444. /**
  36445. * Reads mask bytes.
  36446. *
  36447. * @private
  36448. */
  36449. getMask() {
  36450. if (this._bufferedBytes < 4) {
  36451. this._loop = false;
  36452. return;
  36453. }
  36454. this._mask = this.consume(4);
  36455. this._state = GET_DATA;
  36456. }
  36457. /**
  36458. * Reads data bytes.
  36459. *
  36460. * @param {Function} cb Callback
  36461. * @private
  36462. */
  36463. getData(cb) {
  36464. let data = EMPTY_BUFFER;
  36465. if (this._payloadLength) {
  36466. if (this._bufferedBytes < this._payloadLength) {
  36467. this._loop = false;
  36468. return;
  36469. }
  36470. data = this.consume(this._payloadLength);
  36471. if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
  36472. unmask(data, this._mask);
  36473. }
  36474. }
  36475. if (this._opcode > 7) {
  36476. this.controlMessage(data, cb);
  36477. return;
  36478. }
  36479. if (this._compressed) {
  36480. this._state = INFLATING;
  36481. this.decompress(data, cb);
  36482. return;
  36483. }
  36484. if (data.length) {
  36485. this._messageLength = this._totalPayloadLength;
  36486. this._fragments.push(data);
  36487. }
  36488. this.dataMessage(cb);
  36489. }
  36490. /**
  36491. * Decompresses data.
  36492. *
  36493. * @param {Buffer} data Compressed data
  36494. * @param {Function} cb Callback
  36495. * @private
  36496. */
  36497. decompress(data, cb) {
  36498. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  36499. perMessageDeflate.decompress(data, this._fin, (err2, buf) => {
  36500. if (err2) return cb(err2);
  36501. if (buf.length) {
  36502. this._messageLength += buf.length;
  36503. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  36504. const error2 = this.createError(
  36505. RangeError,
  36506. "Max payload size exceeded",
  36507. false,
  36508. 1009,
  36509. "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
  36510. );
  36511. cb(error2);
  36512. return;
  36513. }
  36514. this._fragments.push(buf);
  36515. }
  36516. this.dataMessage(cb);
  36517. if (this._state === GET_INFO) this.startLoop(cb);
  36518. });
  36519. }
  36520. /**
  36521. * Handles a data message.
  36522. *
  36523. * @param {Function} cb Callback
  36524. * @private
  36525. */
  36526. dataMessage(cb) {
  36527. if (!this._fin) {
  36528. this._state = GET_INFO;
  36529. return;
  36530. }
  36531. const messageLength = this._messageLength;
  36532. const fragments = this._fragments;
  36533. this._totalPayloadLength = 0;
  36534. this._messageLength = 0;
  36535. this._fragmented = 0;
  36536. this._fragments = [];
  36537. if (this._opcode === 2) {
  36538. let data;
  36539. if (this._binaryType === "nodebuffer") {
  36540. data = concat(fragments, messageLength);
  36541. } else if (this._binaryType === "arraybuffer") {
  36542. data = toArrayBuffer(concat(fragments, messageLength));
  36543. } else if (this._binaryType === "blob") {
  36544. data = new Blob(fragments);
  36545. } else {
  36546. data = fragments;
  36547. }
  36548. if (this._allowSynchronousEvents) {
  36549. this.emit("message", data, true);
  36550. this._state = GET_INFO;
  36551. } else {
  36552. this._state = DEFER_EVENT;
  36553. setImmediate(() => {
  36554. this.emit("message", data, true);
  36555. this._state = GET_INFO;
  36556. this.startLoop(cb);
  36557. });
  36558. }
  36559. } else {
  36560. const buf = concat(fragments, messageLength);
  36561. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  36562. const error2 = this.createError(
  36563. Error,
  36564. "invalid UTF-8 sequence",
  36565. true,
  36566. 1007,
  36567. "WS_ERR_INVALID_UTF8"
  36568. );
  36569. cb(error2);
  36570. return;
  36571. }
  36572. if (this._state === INFLATING || this._allowSynchronousEvents) {
  36573. this.emit("message", buf, false);
  36574. this._state = GET_INFO;
  36575. } else {
  36576. this._state = DEFER_EVENT;
  36577. setImmediate(() => {
  36578. this.emit("message", buf, false);
  36579. this._state = GET_INFO;
  36580. this.startLoop(cb);
  36581. });
  36582. }
  36583. }
  36584. }
  36585. /**
  36586. * Handles a control message.
  36587. *
  36588. * @param {Buffer} data Data to handle
  36589. * @return {(Error|RangeError|undefined)} A possible error
  36590. * @private
  36591. */
  36592. controlMessage(data, cb) {
  36593. if (this._opcode === 8) {
  36594. if (data.length === 0) {
  36595. this._loop = false;
  36596. this.emit("conclude", 1005, EMPTY_BUFFER);
  36597. this.end();
  36598. } else {
  36599. const code = data.readUInt16BE(0);
  36600. if (!isValidStatusCode(code)) {
  36601. const error2 = this.createError(
  36602. RangeError,
  36603. `invalid status code ${code}`,
  36604. true,
  36605. 1002,
  36606. "WS_ERR_INVALID_CLOSE_CODE"
  36607. );
  36608. cb(error2);
  36609. return;
  36610. }
  36611. const buf = new FastBuffer(
  36612. data.buffer,
  36613. data.byteOffset + 2,
  36614. data.length - 2
  36615. );
  36616. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  36617. const error2 = this.createError(
  36618. Error,
  36619. "invalid UTF-8 sequence",
  36620. true,
  36621. 1007,
  36622. "WS_ERR_INVALID_UTF8"
  36623. );
  36624. cb(error2);
  36625. return;
  36626. }
  36627. this._loop = false;
  36628. this.emit("conclude", code, buf);
  36629. this.end();
  36630. }
  36631. this._state = GET_INFO;
  36632. return;
  36633. }
  36634. if (this._allowSynchronousEvents) {
  36635. this.emit(this._opcode === 9 ? "ping" : "pong", data);
  36636. this._state = GET_INFO;
  36637. } else {
  36638. this._state = DEFER_EVENT;
  36639. setImmediate(() => {
  36640. this.emit(this._opcode === 9 ? "ping" : "pong", data);
  36641. this._state = GET_INFO;
  36642. this.startLoop(cb);
  36643. });
  36644. }
  36645. }
  36646. /**
  36647. * Builds an error object.
  36648. *
  36649. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  36650. * @param {String} message The error message
  36651. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  36652. * `message`
  36653. * @param {Number} statusCode The status code
  36654. * @param {String} errorCode The exposed error code
  36655. * @return {(Error|RangeError)} The error
  36656. * @private
  36657. */
  36658. createError(ErrorCtor, message, prefix2, statusCode, errorCode) {
  36659. this._loop = false;
  36660. this._errored = true;
  36661. const err2 = new ErrorCtor(
  36662. prefix2 ? `Invalid WebSocket frame: ${message}` : message
  36663. );
  36664. Error.captureStackTrace(err2, this.createError);
  36665. err2.code = errorCode;
  36666. err2[kStatusCode] = statusCode;
  36667. return err2;
  36668. }
  36669. };
  36670. module.exports = Receiver2;
  36671. }
  36672. });
  36673. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/sender.js
  36674. var require_sender = __commonJS({
  36675. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/sender.js"(exports, module) {
  36676. "use strict";
  36677. var { Duplex } = __require("stream");
  36678. var { randomFillSync } = __require("crypto");
  36679. var PerMessageDeflate = require_permessage_deflate();
  36680. var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
  36681. var { isBlob: isBlob3, isValidStatusCode } = require_validation();
  36682. var { mask: applyMask, toBuffer } = require_buffer_util();
  36683. var kByteLength = Symbol("kByteLength");
  36684. var maskBuffer = Buffer.alloc(4);
  36685. var RANDOM_POOL_SIZE = 8 * 1024;
  36686. var randomPool;
  36687. var randomPoolPointer = RANDOM_POOL_SIZE;
  36688. var DEFAULT = 0;
  36689. var DEFLATING = 1;
  36690. var GET_BLOB_DATA = 2;
  36691. var Sender2 = class _Sender {
  36692. /**
  36693. * Creates a Sender instance.
  36694. *
  36695. * @param {Duplex} socket The connection socket
  36696. * @param {Object} [extensions] An object containing the negotiated extensions
  36697. * @param {Function} [generateMask] The function used to generate the masking
  36698. * key
  36699. */
  36700. constructor(socket, extensions, generateMask) {
  36701. this._extensions = extensions || {};
  36702. if (generateMask) {
  36703. this._generateMask = generateMask;
  36704. this._maskBuffer = Buffer.alloc(4);
  36705. }
  36706. this._socket = socket;
  36707. this._firstFragment = true;
  36708. this._compress = false;
  36709. this._bufferedBytes = 0;
  36710. this._queue = [];
  36711. this._state = DEFAULT;
  36712. this.onerror = NOOP;
  36713. this[kWebSocket] = void 0;
  36714. }
  36715. /**
  36716. * Frames a piece of data according to the HyBi WebSocket protocol.
  36717. *
  36718. * @param {(Buffer|String)} data The data to frame
  36719. * @param {Object} options Options object
  36720. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  36721. * FIN bit
  36722. * @param {Function} [options.generateMask] The function used to generate the
  36723. * masking key
  36724. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  36725. * `data`
  36726. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  36727. * key
  36728. * @param {Number} options.opcode The opcode
  36729. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  36730. * modified
  36731. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  36732. * RSV1 bit
  36733. * @return {(Buffer|String)[]} The framed data
  36734. * @public
  36735. */
  36736. static frame(data, options) {
  36737. let mask;
  36738. let merge2 = false;
  36739. let offset = 2;
  36740. let skipMasking = false;
  36741. if (options.mask) {
  36742. mask = options.maskBuffer || maskBuffer;
  36743. if (options.generateMask) {
  36744. options.generateMask(mask);
  36745. } else {
  36746. if (randomPoolPointer === RANDOM_POOL_SIZE) {
  36747. if (randomPool === void 0) {
  36748. randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
  36749. }
  36750. randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
  36751. randomPoolPointer = 0;
  36752. }
  36753. mask[0] = randomPool[randomPoolPointer++];
  36754. mask[1] = randomPool[randomPoolPointer++];
  36755. mask[2] = randomPool[randomPoolPointer++];
  36756. mask[3] = randomPool[randomPoolPointer++];
  36757. }
  36758. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  36759. offset = 6;
  36760. }
  36761. let dataLength;
  36762. if (typeof data === "string") {
  36763. if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
  36764. dataLength = options[kByteLength];
  36765. } else {
  36766. data = Buffer.from(data);
  36767. dataLength = data.length;
  36768. }
  36769. } else {
  36770. dataLength = data.length;
  36771. merge2 = options.mask && options.readOnly && !skipMasking;
  36772. }
  36773. let payloadLength = dataLength;
  36774. if (dataLength >= 65536) {
  36775. offset += 8;
  36776. payloadLength = 127;
  36777. } else if (dataLength > 125) {
  36778. offset += 2;
  36779. payloadLength = 126;
  36780. }
  36781. const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset);
  36782. target[0] = options.fin ? options.opcode | 128 : options.opcode;
  36783. if (options.rsv1) target[0] |= 64;
  36784. target[1] = payloadLength;
  36785. if (payloadLength === 126) {
  36786. target.writeUInt16BE(dataLength, 2);
  36787. } else if (payloadLength === 127) {
  36788. target[2] = target[3] = 0;
  36789. target.writeUIntBE(dataLength, 4, 6);
  36790. }
  36791. if (!options.mask) return [target, data];
  36792. target[1] |= 128;
  36793. target[offset - 4] = mask[0];
  36794. target[offset - 3] = mask[1];
  36795. target[offset - 2] = mask[2];
  36796. target[offset - 1] = mask[3];
  36797. if (skipMasking) return [target, data];
  36798. if (merge2) {
  36799. applyMask(data, mask, target, offset, dataLength);
  36800. return [target];
  36801. }
  36802. applyMask(data, mask, data, 0, dataLength);
  36803. return [target, data];
  36804. }
  36805. /**
  36806. * Sends a close message to the other peer.
  36807. *
  36808. * @param {Number} [code] The status code component of the body
  36809. * @param {(String|Buffer)} [data] The message component of the body
  36810. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  36811. * @param {Function} [cb] Callback
  36812. * @public
  36813. */
  36814. close(code, data, mask, cb) {
  36815. let buf;
  36816. if (code === void 0) {
  36817. buf = EMPTY_BUFFER;
  36818. } else if (typeof code !== "number" || !isValidStatusCode(code)) {
  36819. throw new TypeError("First argument must be a valid error code number");
  36820. } else if (data === void 0 || !data.length) {
  36821. buf = Buffer.allocUnsafe(2);
  36822. buf.writeUInt16BE(code, 0);
  36823. } else {
  36824. const length = Buffer.byteLength(data);
  36825. if (length > 123) {
  36826. throw new RangeError("The message must not be greater than 123 bytes");
  36827. }
  36828. buf = Buffer.allocUnsafe(2 + length);
  36829. buf.writeUInt16BE(code, 0);
  36830. if (typeof data === "string") {
  36831. buf.write(data, 2);
  36832. } else {
  36833. buf.set(data, 2);
  36834. }
  36835. }
  36836. const options = {
  36837. [kByteLength]: buf.length,
  36838. fin: true,
  36839. generateMask: this._generateMask,
  36840. mask,
  36841. maskBuffer: this._maskBuffer,
  36842. opcode: 8,
  36843. readOnly: false,
  36844. rsv1: false
  36845. };
  36846. if (this._state !== DEFAULT) {
  36847. this.enqueue([this.dispatch, buf, false, options, cb]);
  36848. } else {
  36849. this.sendFrame(_Sender.frame(buf, options), cb);
  36850. }
  36851. }
  36852. /**
  36853. * Sends a ping message to the other peer.
  36854. *
  36855. * @param {*} data The message to send
  36856. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  36857. * @param {Function} [cb] Callback
  36858. * @public
  36859. */
  36860. ping(data, mask, cb) {
  36861. let byteLength;
  36862. let readOnly;
  36863. if (typeof data === "string") {
  36864. byteLength = Buffer.byteLength(data);
  36865. readOnly = false;
  36866. } else if (isBlob3(data)) {
  36867. byteLength = data.size;
  36868. readOnly = false;
  36869. } else {
  36870. data = toBuffer(data);
  36871. byteLength = data.length;
  36872. readOnly = toBuffer.readOnly;
  36873. }
  36874. if (byteLength > 125) {
  36875. throw new RangeError("The data size must not be greater than 125 bytes");
  36876. }
  36877. const options = {
  36878. [kByteLength]: byteLength,
  36879. fin: true,
  36880. generateMask: this._generateMask,
  36881. mask,
  36882. maskBuffer: this._maskBuffer,
  36883. opcode: 9,
  36884. readOnly,
  36885. rsv1: false
  36886. };
  36887. if (isBlob3(data)) {
  36888. if (this._state !== DEFAULT) {
  36889. this.enqueue([this.getBlobData, data, false, options, cb]);
  36890. } else {
  36891. this.getBlobData(data, false, options, cb);
  36892. }
  36893. } else if (this._state !== DEFAULT) {
  36894. this.enqueue([this.dispatch, data, false, options, cb]);
  36895. } else {
  36896. this.sendFrame(_Sender.frame(data, options), cb);
  36897. }
  36898. }
  36899. /**
  36900. * Sends a pong message to the other peer.
  36901. *
  36902. * @param {*} data The message to send
  36903. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  36904. * @param {Function} [cb] Callback
  36905. * @public
  36906. */
  36907. pong(data, mask, cb) {
  36908. let byteLength;
  36909. let readOnly;
  36910. if (typeof data === "string") {
  36911. byteLength = Buffer.byteLength(data);
  36912. readOnly = false;
  36913. } else if (isBlob3(data)) {
  36914. byteLength = data.size;
  36915. readOnly = false;
  36916. } else {
  36917. data = toBuffer(data);
  36918. byteLength = data.length;
  36919. readOnly = toBuffer.readOnly;
  36920. }
  36921. if (byteLength > 125) {
  36922. throw new RangeError("The data size must not be greater than 125 bytes");
  36923. }
  36924. const options = {
  36925. [kByteLength]: byteLength,
  36926. fin: true,
  36927. generateMask: this._generateMask,
  36928. mask,
  36929. maskBuffer: this._maskBuffer,
  36930. opcode: 10,
  36931. readOnly,
  36932. rsv1: false
  36933. };
  36934. if (isBlob3(data)) {
  36935. if (this._state !== DEFAULT) {
  36936. this.enqueue([this.getBlobData, data, false, options, cb]);
  36937. } else {
  36938. this.getBlobData(data, false, options, cb);
  36939. }
  36940. } else if (this._state !== DEFAULT) {
  36941. this.enqueue([this.dispatch, data, false, options, cb]);
  36942. } else {
  36943. this.sendFrame(_Sender.frame(data, options), cb);
  36944. }
  36945. }
  36946. /**
  36947. * Sends a data message to the other peer.
  36948. *
  36949. * @param {*} data The message to send
  36950. * @param {Object} options Options object
  36951. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  36952. * or text
  36953. * @param {Boolean} [options.compress=false] Specifies whether or not to
  36954. * compress `data`
  36955. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  36956. * last one
  36957. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  36958. * `data`
  36959. * @param {Function} [cb] Callback
  36960. * @public
  36961. */
  36962. send(data, options, cb) {
  36963. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  36964. let opcode = options.binary ? 2 : 1;
  36965. let rsv1 = options.compress;
  36966. let byteLength;
  36967. let readOnly;
  36968. if (typeof data === "string") {
  36969. byteLength = Buffer.byteLength(data);
  36970. readOnly = false;
  36971. } else if (isBlob3(data)) {
  36972. byteLength = data.size;
  36973. readOnly = false;
  36974. } else {
  36975. data = toBuffer(data);
  36976. byteLength = data.length;
  36977. readOnly = toBuffer.readOnly;
  36978. }
  36979. if (this._firstFragment) {
  36980. this._firstFragment = false;
  36981. if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
  36982. rsv1 = byteLength >= perMessageDeflate._threshold;
  36983. }
  36984. this._compress = rsv1;
  36985. } else {
  36986. rsv1 = false;
  36987. opcode = 0;
  36988. }
  36989. if (options.fin) this._firstFragment = true;
  36990. const opts = {
  36991. [kByteLength]: byteLength,
  36992. fin: options.fin,
  36993. generateMask: this._generateMask,
  36994. mask: options.mask,
  36995. maskBuffer: this._maskBuffer,
  36996. opcode,
  36997. readOnly,
  36998. rsv1
  36999. };
  37000. if (isBlob3(data)) {
  37001. if (this._state !== DEFAULT) {
  37002. this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
  37003. } else {
  37004. this.getBlobData(data, this._compress, opts, cb);
  37005. }
  37006. } else if (this._state !== DEFAULT) {
  37007. this.enqueue([this.dispatch, data, this._compress, opts, cb]);
  37008. } else {
  37009. this.dispatch(data, this._compress, opts, cb);
  37010. }
  37011. }
  37012. /**
  37013. * Gets the contents of a blob as binary data.
  37014. *
  37015. * @param {Blob} blob The blob
  37016. * @param {Boolean} [compress=false] Specifies whether or not to compress
  37017. * the data
  37018. * @param {Object} options Options object
  37019. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  37020. * FIN bit
  37021. * @param {Function} [options.generateMask] The function used to generate the
  37022. * masking key
  37023. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  37024. * `data`
  37025. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  37026. * key
  37027. * @param {Number} options.opcode The opcode
  37028. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  37029. * modified
  37030. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  37031. * RSV1 bit
  37032. * @param {Function} [cb] Callback
  37033. * @private
  37034. */
  37035. getBlobData(blob, compress2, options, cb) {
  37036. this._bufferedBytes += options[kByteLength];
  37037. this._state = GET_BLOB_DATA;
  37038. blob.arrayBuffer().then((arrayBuffer) => {
  37039. if (this._socket.destroyed) {
  37040. const err2 = new Error(
  37041. "The socket was closed while the blob was being read"
  37042. );
  37043. process.nextTick(callCallbacks, this, err2, cb);
  37044. return;
  37045. }
  37046. this._bufferedBytes -= options[kByteLength];
  37047. const data = toBuffer(arrayBuffer);
  37048. if (!compress2) {
  37049. this._state = DEFAULT;
  37050. this.sendFrame(_Sender.frame(data, options), cb);
  37051. this.dequeue();
  37052. } else {
  37053. this.dispatch(data, compress2, options, cb);
  37054. }
  37055. }).catch((err2) => {
  37056. process.nextTick(onError, this, err2, cb);
  37057. });
  37058. }
  37059. /**
  37060. * Dispatches a message.
  37061. *
  37062. * @param {(Buffer|String)} data The message to send
  37063. * @param {Boolean} [compress=false] Specifies whether or not to compress
  37064. * `data`
  37065. * @param {Object} options Options object
  37066. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  37067. * FIN bit
  37068. * @param {Function} [options.generateMask] The function used to generate the
  37069. * masking key
  37070. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  37071. * `data`
  37072. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  37073. * key
  37074. * @param {Number} options.opcode The opcode
  37075. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  37076. * modified
  37077. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  37078. * RSV1 bit
  37079. * @param {Function} [cb] Callback
  37080. * @private
  37081. */
  37082. dispatch(data, compress2, options, cb) {
  37083. if (!compress2) {
  37084. this.sendFrame(_Sender.frame(data, options), cb);
  37085. return;
  37086. }
  37087. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  37088. this._bufferedBytes += options[kByteLength];
  37089. this._state = DEFLATING;
  37090. perMessageDeflate.compress(data, options.fin, (_3, buf) => {
  37091. if (this._socket.destroyed) {
  37092. const err2 = new Error(
  37093. "The socket was closed while data was being compressed"
  37094. );
  37095. callCallbacks(this, err2, cb);
  37096. return;
  37097. }
  37098. this._bufferedBytes -= options[kByteLength];
  37099. this._state = DEFAULT;
  37100. options.readOnly = false;
  37101. this.sendFrame(_Sender.frame(buf, options), cb);
  37102. this.dequeue();
  37103. });
  37104. }
  37105. /**
  37106. * Executes queued send operations.
  37107. *
  37108. * @private
  37109. */
  37110. dequeue() {
  37111. while (this._state === DEFAULT && this._queue.length) {
  37112. const params = this._queue.shift();
  37113. this._bufferedBytes -= params[3][kByteLength];
  37114. Reflect.apply(params[0], this, params.slice(1));
  37115. }
  37116. }
  37117. /**
  37118. * Enqueues a send operation.
  37119. *
  37120. * @param {Array} params Send operation parameters.
  37121. * @private
  37122. */
  37123. enqueue(params) {
  37124. this._bufferedBytes += params[3][kByteLength];
  37125. this._queue.push(params);
  37126. }
  37127. /**
  37128. * Sends a frame.
  37129. *
  37130. * @param {(Buffer | String)[]} list The frame to send
  37131. * @param {Function} [cb] Callback
  37132. * @private
  37133. */
  37134. sendFrame(list, cb) {
  37135. if (list.length === 2) {
  37136. this._socket.cork();
  37137. this._socket.write(list[0]);
  37138. this._socket.write(list[1], cb);
  37139. this._socket.uncork();
  37140. } else {
  37141. this._socket.write(list[0], cb);
  37142. }
  37143. }
  37144. };
  37145. module.exports = Sender2;
  37146. function callCallbacks(sender, err2, cb) {
  37147. if (typeof cb === "function") cb(err2);
  37148. for (let i6 = 0; i6 < sender._queue.length; i6++) {
  37149. const params = sender._queue[i6];
  37150. const callback = params[params.length - 1];
  37151. if (typeof callback === "function") callback(err2);
  37152. }
  37153. }
  37154. function onError(sender, err2, cb) {
  37155. callCallbacks(sender, err2, cb);
  37156. sender.onerror(err2);
  37157. }
  37158. }
  37159. });
  37160. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/event-target.js
  37161. var require_event_target = __commonJS({
  37162. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/event-target.js"(exports, module) {
  37163. "use strict";
  37164. var { kForOnEventAttribute, kListener } = require_constants();
  37165. var kCode = Symbol("kCode");
  37166. var kData = Symbol("kData");
  37167. var kError = Symbol("kError");
  37168. var kMessage = Symbol("kMessage");
  37169. var kReason = Symbol("kReason");
  37170. var kTarget = Symbol("kTarget");
  37171. var kType = Symbol("kType");
  37172. var kWasClean = Symbol("kWasClean");
  37173. var Event = class {
  37174. /**
  37175. * Create a new `Event`.
  37176. *
  37177. * @param {String} type The name of the event
  37178. * @throws {TypeError} If the `type` argument is not specified
  37179. */
  37180. constructor(type) {
  37181. this[kTarget] = null;
  37182. this[kType] = type;
  37183. }
  37184. /**
  37185. * @type {*}
  37186. */
  37187. get target() {
  37188. return this[kTarget];
  37189. }
  37190. /**
  37191. * @type {String}
  37192. */
  37193. get type() {
  37194. return this[kType];
  37195. }
  37196. };
  37197. Object.defineProperty(Event.prototype, "target", { enumerable: true });
  37198. Object.defineProperty(Event.prototype, "type", { enumerable: true });
  37199. var CloseEvent = class extends Event {
  37200. /**
  37201. * Create a new `CloseEvent`.
  37202. *
  37203. * @param {String} type The name of the event
  37204. * @param {Object} [options] A dictionary object that allows for setting
  37205. * attributes via object members of the same name
  37206. * @param {Number} [options.code=0] The status code explaining why the
  37207. * connection was closed
  37208. * @param {String} [options.reason=''] A human-readable string explaining why
  37209. * the connection was closed
  37210. * @param {Boolean} [options.wasClean=false] Indicates whether or not the
  37211. * connection was cleanly closed
  37212. */
  37213. constructor(type, options = {}) {
  37214. super(type);
  37215. this[kCode] = options.code === void 0 ? 0 : options.code;
  37216. this[kReason] = options.reason === void 0 ? "" : options.reason;
  37217. this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
  37218. }
  37219. /**
  37220. * @type {Number}
  37221. */
  37222. get code() {
  37223. return this[kCode];
  37224. }
  37225. /**
  37226. * @type {String}
  37227. */
  37228. get reason() {
  37229. return this[kReason];
  37230. }
  37231. /**
  37232. * @type {Boolean}
  37233. */
  37234. get wasClean() {
  37235. return this[kWasClean];
  37236. }
  37237. };
  37238. Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
  37239. Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
  37240. Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
  37241. var ErrorEvent = class extends Event {
  37242. /**
  37243. * Create a new `ErrorEvent`.
  37244. *
  37245. * @param {String} type The name of the event
  37246. * @param {Object} [options] A dictionary object that allows for setting
  37247. * attributes via object members of the same name
  37248. * @param {*} [options.error=null] The error that generated this event
  37249. * @param {String} [options.message=''] The error message
  37250. */
  37251. constructor(type, options = {}) {
  37252. super(type);
  37253. this[kError] = options.error === void 0 ? null : options.error;
  37254. this[kMessage] = options.message === void 0 ? "" : options.message;
  37255. }
  37256. /**
  37257. * @type {*}
  37258. */
  37259. get error() {
  37260. return this[kError];
  37261. }
  37262. /**
  37263. * @type {String}
  37264. */
  37265. get message() {
  37266. return this[kMessage];
  37267. }
  37268. };
  37269. Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
  37270. Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
  37271. var MessageEvent = class extends Event {
  37272. /**
  37273. * Create a new `MessageEvent`.
  37274. *
  37275. * @param {String} type The name of the event
  37276. * @param {Object} [options] A dictionary object that allows for setting
  37277. * attributes via object members of the same name
  37278. * @param {*} [options.data=null] The message content
  37279. */
  37280. constructor(type, options = {}) {
  37281. super(type);
  37282. this[kData] = options.data === void 0 ? null : options.data;
  37283. }
  37284. /**
  37285. * @type {*}
  37286. */
  37287. get data() {
  37288. return this[kData];
  37289. }
  37290. };
  37291. Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
  37292. var EventTarget = {
  37293. /**
  37294. * Register an event listener.
  37295. *
  37296. * @param {String} type A string representing the event type to listen for
  37297. * @param {(Function|Object)} handler The listener to add
  37298. * @param {Object} [options] An options object specifies characteristics about
  37299. * the event listener
  37300. * @param {Boolean} [options.once=false] A `Boolean` indicating that the
  37301. * listener should be invoked at most once after being added. If `true`,
  37302. * the listener would be automatically removed when invoked.
  37303. * @public
  37304. */
  37305. addEventListener(type, handler, options = {}) {
  37306. for (const listener of this.listeners(type)) {
  37307. if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
  37308. return;
  37309. }
  37310. }
  37311. let wrapper;
  37312. if (type === "message") {
  37313. wrapper = function onMessage(data, isBinary) {
  37314. const event = new MessageEvent("message", {
  37315. data: isBinary ? data : data.toString()
  37316. });
  37317. event[kTarget] = this;
  37318. callListener(handler, this, event);
  37319. };
  37320. } else if (type === "close") {
  37321. wrapper = function onClose(code, message) {
  37322. const event = new CloseEvent("close", {
  37323. code,
  37324. reason: message.toString(),
  37325. wasClean: this._closeFrameReceived && this._closeFrameSent
  37326. });
  37327. event[kTarget] = this;
  37328. callListener(handler, this, event);
  37329. };
  37330. } else if (type === "error") {
  37331. wrapper = function onError(error2) {
  37332. const event = new ErrorEvent("error", {
  37333. error: error2,
  37334. message: error2.message
  37335. });
  37336. event[kTarget] = this;
  37337. callListener(handler, this, event);
  37338. };
  37339. } else if (type === "open") {
  37340. wrapper = function onOpen() {
  37341. const event = new Event("open");
  37342. event[kTarget] = this;
  37343. callListener(handler, this, event);
  37344. };
  37345. } else {
  37346. return;
  37347. }
  37348. wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
  37349. wrapper[kListener] = handler;
  37350. if (options.once) {
  37351. this.once(type, wrapper);
  37352. } else {
  37353. this.on(type, wrapper);
  37354. }
  37355. },
  37356. /**
  37357. * Remove an event listener.
  37358. *
  37359. * @param {String} type A string representing the event type to remove
  37360. * @param {(Function|Object)} handler The listener to remove
  37361. * @public
  37362. */
  37363. removeEventListener(type, handler) {
  37364. for (const listener of this.listeners(type)) {
  37365. if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
  37366. this.removeListener(type, listener);
  37367. break;
  37368. }
  37369. }
  37370. }
  37371. };
  37372. module.exports = {
  37373. CloseEvent,
  37374. ErrorEvent,
  37375. Event,
  37376. EventTarget,
  37377. MessageEvent
  37378. };
  37379. function callListener(listener, thisArg, event) {
  37380. if (typeof listener === "object" && listener.handleEvent) {
  37381. listener.handleEvent.call(listener, event);
  37382. } else {
  37383. listener.call(thisArg, event);
  37384. }
  37385. }
  37386. }
  37387. });
  37388. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/extension.js
  37389. var require_extension = __commonJS({
  37390. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/extension.js"(exports, module) {
  37391. "use strict";
  37392. var { tokenChars } = require_validation();
  37393. function push(dest, name, elem) {
  37394. if (dest[name] === void 0) dest[name] = [elem];
  37395. else dest[name].push(elem);
  37396. }
  37397. function parse4(header) {
  37398. const offers = /* @__PURE__ */ Object.create(null);
  37399. let params = /* @__PURE__ */ Object.create(null);
  37400. let mustUnescape = false;
  37401. let isEscaping = false;
  37402. let inQuotes = false;
  37403. let extensionName;
  37404. let paramName;
  37405. let start = -1;
  37406. let code = -1;
  37407. let end = -1;
  37408. let i6 = 0;
  37409. for (; i6 < header.length; i6++) {
  37410. code = header.charCodeAt(i6);
  37411. if (extensionName === void 0) {
  37412. if (end === -1 && tokenChars[code] === 1) {
  37413. if (start === -1) start = i6;
  37414. } else if (i6 !== 0 && (code === 32 || code === 9)) {
  37415. if (end === -1 && start !== -1) end = i6;
  37416. } else if (code === 59 || code === 44) {
  37417. if (start === -1) {
  37418. throw new SyntaxError(`Unexpected character at index ${i6}`);
  37419. }
  37420. if (end === -1) end = i6;
  37421. const name = header.slice(start, end);
  37422. if (code === 44) {
  37423. push(offers, name, params);
  37424. params = /* @__PURE__ */ Object.create(null);
  37425. } else {
  37426. extensionName = name;
  37427. }
  37428. start = end = -1;
  37429. } else {
  37430. throw new SyntaxError(`Unexpected character at index ${i6}`);
  37431. }
  37432. } else if (paramName === void 0) {
  37433. if (end === -1 && tokenChars[code] === 1) {
  37434. if (start === -1) start = i6;
  37435. } else if (code === 32 || code === 9) {
  37436. if (end === -1 && start !== -1) end = i6;
  37437. } else if (code === 59 || code === 44) {
  37438. if (start === -1) {
  37439. throw new SyntaxError(`Unexpected character at index ${i6}`);
  37440. }
  37441. if (end === -1) end = i6;
  37442. push(params, header.slice(start, end), true);
  37443. if (code === 44) {
  37444. push(offers, extensionName, params);
  37445. params = /* @__PURE__ */ Object.create(null);
  37446. extensionName = void 0;
  37447. }
  37448. start = end = -1;
  37449. } else if (code === 61 && start !== -1 && end === -1) {
  37450. paramName = header.slice(start, i6);
  37451. start = end = -1;
  37452. } else {
  37453. throw new SyntaxError(`Unexpected character at index ${i6}`);
  37454. }
  37455. } else {
  37456. if (isEscaping) {
  37457. if (tokenChars[code] !== 1) {
  37458. throw new SyntaxError(`Unexpected character at index ${i6}`);
  37459. }
  37460. if (start === -1) start = i6;
  37461. else if (!mustUnescape) mustUnescape = true;
  37462. isEscaping = false;
  37463. } else if (inQuotes) {
  37464. if (tokenChars[code] === 1) {
  37465. if (start === -1) start = i6;
  37466. } else if (code === 34 && start !== -1) {
  37467. inQuotes = false;
  37468. end = i6;
  37469. } else if (code === 92) {
  37470. isEscaping = true;
  37471. } else {
  37472. throw new SyntaxError(`Unexpected character at index ${i6}`);
  37473. }
  37474. } else if (code === 34 && header.charCodeAt(i6 - 1) === 61) {
  37475. inQuotes = true;
  37476. } else if (end === -1 && tokenChars[code] === 1) {
  37477. if (start === -1) start = i6;
  37478. } else if (start !== -1 && (code === 32 || code === 9)) {
  37479. if (end === -1) end = i6;
  37480. } else if (code === 59 || code === 44) {
  37481. if (start === -1) {
  37482. throw new SyntaxError(`Unexpected character at index ${i6}`);
  37483. }
  37484. if (end === -1) end = i6;
  37485. let value = header.slice(start, end);
  37486. if (mustUnescape) {
  37487. value = value.replace(/\\/g, "");
  37488. mustUnescape = false;
  37489. }
  37490. push(params, paramName, value);
  37491. if (code === 44) {
  37492. push(offers, extensionName, params);
  37493. params = /* @__PURE__ */ Object.create(null);
  37494. extensionName = void 0;
  37495. }
  37496. paramName = void 0;
  37497. start = end = -1;
  37498. } else {
  37499. throw new SyntaxError(`Unexpected character at index ${i6}`);
  37500. }
  37501. }
  37502. }
  37503. if (start === -1 || inQuotes || code === 32 || code === 9) {
  37504. throw new SyntaxError("Unexpected end of input");
  37505. }
  37506. if (end === -1) end = i6;
  37507. const token = header.slice(start, end);
  37508. if (extensionName === void 0) {
  37509. push(offers, token, params);
  37510. } else {
  37511. if (paramName === void 0) {
  37512. push(params, token, true);
  37513. } else if (mustUnescape) {
  37514. push(params, paramName, token.replace(/\\/g, ""));
  37515. } else {
  37516. push(params, paramName, token);
  37517. }
  37518. push(offers, extensionName, params);
  37519. }
  37520. return offers;
  37521. }
  37522. function format(extensions) {
  37523. return Object.keys(extensions).map((extension) => {
  37524. let configurations = extensions[extension];
  37525. if (!Array.isArray(configurations)) configurations = [configurations];
  37526. return configurations.map((params) => {
  37527. return [extension].concat(
  37528. Object.keys(params).map((k5) => {
  37529. let values = params[k5];
  37530. if (!Array.isArray(values)) values = [values];
  37531. return values.map((v6) => v6 === true ? k5 : `${k5}=${v6}`).join("; ");
  37532. })
  37533. ).join("; ");
  37534. }).join(", ");
  37535. }).join(", ");
  37536. }
  37537. module.exports = { format, parse: parse4 };
  37538. }
  37539. });
  37540. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket.js
  37541. var require_websocket = __commonJS({
  37542. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket.js"(exports, module) {
  37543. "use strict";
  37544. var EventEmitter = __require("events");
  37545. var https2 = __require("https");
  37546. var http3 = __require("http");
  37547. var net = __require("net");
  37548. var tls = __require("tls");
  37549. var { randomBytes, createHash: createHash4 } = __require("crypto");
  37550. var { Duplex, Readable: Readable6 } = __require("stream");
  37551. var { URL: URL2 } = __require("url");
  37552. var PerMessageDeflate = require_permessage_deflate();
  37553. var Receiver2 = require_receiver();
  37554. var Sender2 = require_sender();
  37555. var { isBlob: isBlob3 } = require_validation();
  37556. var {
  37557. BINARY_TYPES,
  37558. EMPTY_BUFFER,
  37559. GUID,
  37560. kForOnEventAttribute,
  37561. kListener,
  37562. kStatusCode,
  37563. kWebSocket,
  37564. NOOP
  37565. } = require_constants();
  37566. var {
  37567. EventTarget: { addEventListener: addEventListener2, removeEventListener }
  37568. } = require_event_target();
  37569. var { format, parse: parse4 } = require_extension();
  37570. var { toBuffer } = require_buffer_util();
  37571. var closeTimeout = 30 * 1e3;
  37572. var kAborted = Symbol("kAborted");
  37573. var protocolVersions = [8, 13];
  37574. var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
  37575. var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
  37576. var WebSocket2 = class _WebSocket extends EventEmitter {
  37577. /**
  37578. * Create a new `WebSocket`.
  37579. *
  37580. * @param {(String|URL)} address The URL to which to connect
  37581. * @param {(String|String[])} [protocols] The subprotocols
  37582. * @param {Object} [options] Connection options
  37583. */
  37584. constructor(address, protocols, options) {
  37585. super();
  37586. this._binaryType = BINARY_TYPES[0];
  37587. this._closeCode = 1006;
  37588. this._closeFrameReceived = false;
  37589. this._closeFrameSent = false;
  37590. this._closeMessage = EMPTY_BUFFER;
  37591. this._closeTimer = null;
  37592. this._errorEmitted = false;
  37593. this._extensions = {};
  37594. this._paused = false;
  37595. this._protocol = "";
  37596. this._readyState = _WebSocket.CONNECTING;
  37597. this._receiver = null;
  37598. this._sender = null;
  37599. this._socket = null;
  37600. if (address !== null) {
  37601. this._bufferedAmount = 0;
  37602. this._isServer = false;
  37603. this._redirects = 0;
  37604. if (protocols === void 0) {
  37605. protocols = [];
  37606. } else if (!Array.isArray(protocols)) {
  37607. if (typeof protocols === "object" && protocols !== null) {
  37608. options = protocols;
  37609. protocols = [];
  37610. } else {
  37611. protocols = [protocols];
  37612. }
  37613. }
  37614. initAsClient(this, address, protocols, options);
  37615. } else {
  37616. this._autoPong = options.autoPong;
  37617. this._isServer = true;
  37618. }
  37619. }
  37620. /**
  37621. * For historical reasons, the custom "nodebuffer" type is used by the default
  37622. * instead of "blob".
  37623. *
  37624. * @type {String}
  37625. */
  37626. get binaryType() {
  37627. return this._binaryType;
  37628. }
  37629. set binaryType(type) {
  37630. if (!BINARY_TYPES.includes(type)) return;
  37631. this._binaryType = type;
  37632. if (this._receiver) this._receiver._binaryType = type;
  37633. }
  37634. /**
  37635. * @type {Number}
  37636. */
  37637. get bufferedAmount() {
  37638. if (!this._socket) return this._bufferedAmount;
  37639. return this._socket._writableState.length + this._sender._bufferedBytes;
  37640. }
  37641. /**
  37642. * @type {String}
  37643. */
  37644. get extensions() {
  37645. return Object.keys(this._extensions).join();
  37646. }
  37647. /**
  37648. * @type {Boolean}
  37649. */
  37650. get isPaused() {
  37651. return this._paused;
  37652. }
  37653. /**
  37654. * @type {Function}
  37655. */
  37656. /* istanbul ignore next */
  37657. get onclose() {
  37658. return null;
  37659. }
  37660. /**
  37661. * @type {Function}
  37662. */
  37663. /* istanbul ignore next */
  37664. get onerror() {
  37665. return null;
  37666. }
  37667. /**
  37668. * @type {Function}
  37669. */
  37670. /* istanbul ignore next */
  37671. get onopen() {
  37672. return null;
  37673. }
  37674. /**
  37675. * @type {Function}
  37676. */
  37677. /* istanbul ignore next */
  37678. get onmessage() {
  37679. return null;
  37680. }
  37681. /**
  37682. * @type {String}
  37683. */
  37684. get protocol() {
  37685. return this._protocol;
  37686. }
  37687. /**
  37688. * @type {Number}
  37689. */
  37690. get readyState() {
  37691. return this._readyState;
  37692. }
  37693. /**
  37694. * @type {String}
  37695. */
  37696. get url() {
  37697. return this._url;
  37698. }
  37699. /**
  37700. * Set up the socket and the internal resources.
  37701. *
  37702. * @param {Duplex} socket The network socket between the server and client
  37703. * @param {Buffer} head The first packet of the upgraded stream
  37704. * @param {Object} options Options object
  37705. * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
  37706. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  37707. * multiple times in the same tick
  37708. * @param {Function} [options.generateMask] The function used to generate the
  37709. * masking key
  37710. * @param {Number} [options.maxPayload=0] The maximum allowed message size
  37711. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  37712. * not to skip UTF-8 validation for text and close messages
  37713. * @private
  37714. */
  37715. setSocket(socket, head, options) {
  37716. const receiver = new Receiver2({
  37717. allowSynchronousEvents: options.allowSynchronousEvents,
  37718. binaryType: this.binaryType,
  37719. extensions: this._extensions,
  37720. isServer: this._isServer,
  37721. maxPayload: options.maxPayload,
  37722. skipUTF8Validation: options.skipUTF8Validation
  37723. });
  37724. const sender = new Sender2(socket, this._extensions, options.generateMask);
  37725. this._receiver = receiver;
  37726. this._sender = sender;
  37727. this._socket = socket;
  37728. receiver[kWebSocket] = this;
  37729. sender[kWebSocket] = this;
  37730. socket[kWebSocket] = this;
  37731. receiver.on("conclude", receiverOnConclude);
  37732. receiver.on("drain", receiverOnDrain);
  37733. receiver.on("error", receiverOnError);
  37734. receiver.on("message", receiverOnMessage);
  37735. receiver.on("ping", receiverOnPing);
  37736. receiver.on("pong", receiverOnPong);
  37737. sender.onerror = senderOnError;
  37738. if (socket.setTimeout) socket.setTimeout(0);
  37739. if (socket.setNoDelay) socket.setNoDelay();
  37740. if (head.length > 0) socket.unshift(head);
  37741. socket.on("close", socketOnClose);
  37742. socket.on("data", socketOnData);
  37743. socket.on("end", socketOnEnd);
  37744. socket.on("error", socketOnError);
  37745. this._readyState = _WebSocket.OPEN;
  37746. this.emit("open");
  37747. }
  37748. /**
  37749. * Emit the `'close'` event.
  37750. *
  37751. * @private
  37752. */
  37753. emitClose() {
  37754. if (!this._socket) {
  37755. this._readyState = _WebSocket.CLOSED;
  37756. this.emit("close", this._closeCode, this._closeMessage);
  37757. return;
  37758. }
  37759. if (this._extensions[PerMessageDeflate.extensionName]) {
  37760. this._extensions[PerMessageDeflate.extensionName].cleanup();
  37761. }
  37762. this._receiver.removeAllListeners();
  37763. this._readyState = _WebSocket.CLOSED;
  37764. this.emit("close", this._closeCode, this._closeMessage);
  37765. }
  37766. /**
  37767. * Start a closing handshake.
  37768. *
  37769. * +----------+ +-----------+ +----------+
  37770. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  37771. * | +----------+ +-----------+ +----------+ |
  37772. * +----------+ +-----------+ |
  37773. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  37774. * +----------+ +-----------+ |
  37775. * | | | +---+ |
  37776. * +------------------------+-->|fin| - - - -
  37777. * | +---+ | +---+
  37778. * - - - - -|fin|<---------------------+
  37779. * +---+
  37780. *
  37781. * @param {Number} [code] Status code explaining why the connection is closing
  37782. * @param {(String|Buffer)} [data] The reason why the connection is
  37783. * closing
  37784. * @public
  37785. */
  37786. close(code, data) {
  37787. if (this.readyState === _WebSocket.CLOSED) return;
  37788. if (this.readyState === _WebSocket.CONNECTING) {
  37789. const msg = "WebSocket was closed before the connection was established";
  37790. abortHandshake(this, this._req, msg);
  37791. return;
  37792. }
  37793. if (this.readyState === _WebSocket.CLOSING) {
  37794. if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
  37795. this._socket.end();
  37796. }
  37797. return;
  37798. }
  37799. this._readyState = _WebSocket.CLOSING;
  37800. this._sender.close(code, data, !this._isServer, (err2) => {
  37801. if (err2) return;
  37802. this._closeFrameSent = true;
  37803. if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
  37804. this._socket.end();
  37805. }
  37806. });
  37807. setCloseTimer(this);
  37808. }
  37809. /**
  37810. * Pause the socket.
  37811. *
  37812. * @public
  37813. */
  37814. pause() {
  37815. if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
  37816. return;
  37817. }
  37818. this._paused = true;
  37819. this._socket.pause();
  37820. }
  37821. /**
  37822. * Send a ping.
  37823. *
  37824. * @param {*} [data] The data to send
  37825. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  37826. * @param {Function} [cb] Callback which is executed when the ping is sent
  37827. * @public
  37828. */
  37829. ping(data, mask, cb) {
  37830. if (this.readyState === _WebSocket.CONNECTING) {
  37831. throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  37832. }
  37833. if (typeof data === "function") {
  37834. cb = data;
  37835. data = mask = void 0;
  37836. } else if (typeof mask === "function") {
  37837. cb = mask;
  37838. mask = void 0;
  37839. }
  37840. if (typeof data === "number") data = data.toString();
  37841. if (this.readyState !== _WebSocket.OPEN) {
  37842. sendAfterClose(this, data, cb);
  37843. return;
  37844. }
  37845. if (mask === void 0) mask = !this._isServer;
  37846. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  37847. }
  37848. /**
  37849. * Send a pong.
  37850. *
  37851. * @param {*} [data] The data to send
  37852. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  37853. * @param {Function} [cb] Callback which is executed when the pong is sent
  37854. * @public
  37855. */
  37856. pong(data, mask, cb) {
  37857. if (this.readyState === _WebSocket.CONNECTING) {
  37858. throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  37859. }
  37860. if (typeof data === "function") {
  37861. cb = data;
  37862. data = mask = void 0;
  37863. } else if (typeof mask === "function") {
  37864. cb = mask;
  37865. mask = void 0;
  37866. }
  37867. if (typeof data === "number") data = data.toString();
  37868. if (this.readyState !== _WebSocket.OPEN) {
  37869. sendAfterClose(this, data, cb);
  37870. return;
  37871. }
  37872. if (mask === void 0) mask = !this._isServer;
  37873. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  37874. }
  37875. /**
  37876. * Resume the socket.
  37877. *
  37878. * @public
  37879. */
  37880. resume() {
  37881. if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
  37882. return;
  37883. }
  37884. this._paused = false;
  37885. if (!this._receiver._writableState.needDrain) this._socket.resume();
  37886. }
  37887. /**
  37888. * Send a data message.
  37889. *
  37890. * @param {*} data The message to send
  37891. * @param {Object} [options] Options object
  37892. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  37893. * text
  37894. * @param {Boolean} [options.compress] Specifies whether or not to compress
  37895. * `data`
  37896. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  37897. * last one
  37898. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  37899. * @param {Function} [cb] Callback which is executed when data is written out
  37900. * @public
  37901. */
  37902. send(data, options, cb) {
  37903. if (this.readyState === _WebSocket.CONNECTING) {
  37904. throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  37905. }
  37906. if (typeof options === "function") {
  37907. cb = options;
  37908. options = {};
  37909. }
  37910. if (typeof data === "number") data = data.toString();
  37911. if (this.readyState !== _WebSocket.OPEN) {
  37912. sendAfterClose(this, data, cb);
  37913. return;
  37914. }
  37915. const opts = {
  37916. binary: typeof data !== "string",
  37917. mask: !this._isServer,
  37918. compress: true,
  37919. fin: true,
  37920. ...options
  37921. };
  37922. if (!this._extensions[PerMessageDeflate.extensionName]) {
  37923. opts.compress = false;
  37924. }
  37925. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  37926. }
  37927. /**
  37928. * Forcibly close the connection.
  37929. *
  37930. * @public
  37931. */
  37932. terminate() {
  37933. if (this.readyState === _WebSocket.CLOSED) return;
  37934. if (this.readyState === _WebSocket.CONNECTING) {
  37935. const msg = "WebSocket was closed before the connection was established";
  37936. abortHandshake(this, this._req, msg);
  37937. return;
  37938. }
  37939. if (this._socket) {
  37940. this._readyState = _WebSocket.CLOSING;
  37941. this._socket.destroy();
  37942. }
  37943. }
  37944. };
  37945. Object.defineProperty(WebSocket2, "CONNECTING", {
  37946. enumerable: true,
  37947. value: readyStates.indexOf("CONNECTING")
  37948. });
  37949. Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
  37950. enumerable: true,
  37951. value: readyStates.indexOf("CONNECTING")
  37952. });
  37953. Object.defineProperty(WebSocket2, "OPEN", {
  37954. enumerable: true,
  37955. value: readyStates.indexOf("OPEN")
  37956. });
  37957. Object.defineProperty(WebSocket2.prototype, "OPEN", {
  37958. enumerable: true,
  37959. value: readyStates.indexOf("OPEN")
  37960. });
  37961. Object.defineProperty(WebSocket2, "CLOSING", {
  37962. enumerable: true,
  37963. value: readyStates.indexOf("CLOSING")
  37964. });
  37965. Object.defineProperty(WebSocket2.prototype, "CLOSING", {
  37966. enumerable: true,
  37967. value: readyStates.indexOf("CLOSING")
  37968. });
  37969. Object.defineProperty(WebSocket2, "CLOSED", {
  37970. enumerable: true,
  37971. value: readyStates.indexOf("CLOSED")
  37972. });
  37973. Object.defineProperty(WebSocket2.prototype, "CLOSED", {
  37974. enumerable: true,
  37975. value: readyStates.indexOf("CLOSED")
  37976. });
  37977. [
  37978. "binaryType",
  37979. "bufferedAmount",
  37980. "extensions",
  37981. "isPaused",
  37982. "protocol",
  37983. "readyState",
  37984. "url"
  37985. ].forEach((property) => {
  37986. Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
  37987. });
  37988. ["open", "error", "close", "message"].forEach((method) => {
  37989. Object.defineProperty(WebSocket2.prototype, `on${method}`, {
  37990. enumerable: true,
  37991. get() {
  37992. for (const listener of this.listeners(method)) {
  37993. if (listener[kForOnEventAttribute]) return listener[kListener];
  37994. }
  37995. return null;
  37996. },
  37997. set(handler) {
  37998. for (const listener of this.listeners(method)) {
  37999. if (listener[kForOnEventAttribute]) {
  38000. this.removeListener(method, listener);
  38001. break;
  38002. }
  38003. }
  38004. if (typeof handler !== "function") return;
  38005. this.addEventListener(method, handler, {
  38006. [kForOnEventAttribute]: true
  38007. });
  38008. }
  38009. });
  38010. });
  38011. WebSocket2.prototype.addEventListener = addEventListener2;
  38012. WebSocket2.prototype.removeEventListener = removeEventListener;
  38013. module.exports = WebSocket2;
  38014. function initAsClient(websocket, address, protocols, options) {
  38015. const opts = {
  38016. allowSynchronousEvents: true,
  38017. autoPong: true,
  38018. protocolVersion: protocolVersions[1],
  38019. maxPayload: 100 * 1024 * 1024,
  38020. skipUTF8Validation: false,
  38021. perMessageDeflate: true,
  38022. followRedirects: false,
  38023. maxRedirects: 10,
  38024. ...options,
  38025. socketPath: void 0,
  38026. hostname: void 0,
  38027. protocol: void 0,
  38028. timeout: void 0,
  38029. method: "GET",
  38030. host: void 0,
  38031. path: void 0,
  38032. port: void 0
  38033. };
  38034. websocket._autoPong = opts.autoPong;
  38035. if (!protocolVersions.includes(opts.protocolVersion)) {
  38036. throw new RangeError(
  38037. `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
  38038. );
  38039. }
  38040. let parsedUrl;
  38041. if (address instanceof URL2) {
  38042. parsedUrl = address;
  38043. } else {
  38044. try {
  38045. parsedUrl = new URL2(address);
  38046. } catch (e6) {
  38047. throw new SyntaxError(`Invalid URL: ${address}`);
  38048. }
  38049. }
  38050. if (parsedUrl.protocol === "http:") {
  38051. parsedUrl.protocol = "ws:";
  38052. } else if (parsedUrl.protocol === "https:") {
  38053. parsedUrl.protocol = "wss:";
  38054. }
  38055. websocket._url = parsedUrl.href;
  38056. const isSecure = parsedUrl.protocol === "wss:";
  38057. const isIpcUrl = parsedUrl.protocol === "ws+unix:";
  38058. let invalidUrlMessage;
  38059. if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
  38060. invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
  38061. } else if (isIpcUrl && !parsedUrl.pathname) {
  38062. invalidUrlMessage = "The URL's pathname is empty";
  38063. } else if (parsedUrl.hash) {
  38064. invalidUrlMessage = "The URL contains a fragment identifier";
  38065. }
  38066. if (invalidUrlMessage) {
  38067. const err2 = new SyntaxError(invalidUrlMessage);
  38068. if (websocket._redirects === 0) {
  38069. throw err2;
  38070. } else {
  38071. emitErrorAndClose(websocket, err2);
  38072. return;
  38073. }
  38074. }
  38075. const defaultPort = isSecure ? 443 : 80;
  38076. const key = randomBytes(16).toString("base64");
  38077. const request2 = isSecure ? https2.request : http3.request;
  38078. const protocolSet = /* @__PURE__ */ new Set();
  38079. let perMessageDeflate;
  38080. opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
  38081. opts.defaultPort = opts.defaultPort || defaultPort;
  38082. opts.port = parsedUrl.port || defaultPort;
  38083. opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
  38084. opts.headers = {
  38085. ...opts.headers,
  38086. "Sec-WebSocket-Version": opts.protocolVersion,
  38087. "Sec-WebSocket-Key": key,
  38088. Connection: "Upgrade",
  38089. Upgrade: "websocket"
  38090. };
  38091. opts.path = parsedUrl.pathname + parsedUrl.search;
  38092. opts.timeout = opts.handshakeTimeout;
  38093. if (opts.perMessageDeflate) {
  38094. perMessageDeflate = new PerMessageDeflate(
  38095. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  38096. false,
  38097. opts.maxPayload
  38098. );
  38099. opts.headers["Sec-WebSocket-Extensions"] = format({
  38100. [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
  38101. });
  38102. }
  38103. if (protocols.length) {
  38104. for (const protocol of protocols) {
  38105. if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
  38106. throw new SyntaxError(
  38107. "An invalid or duplicated subprotocol was specified"
  38108. );
  38109. }
  38110. protocolSet.add(protocol);
  38111. }
  38112. opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
  38113. }
  38114. if (opts.origin) {
  38115. if (opts.protocolVersion < 13) {
  38116. opts.headers["Sec-WebSocket-Origin"] = opts.origin;
  38117. } else {
  38118. opts.headers.Origin = opts.origin;
  38119. }
  38120. }
  38121. if (parsedUrl.username || parsedUrl.password) {
  38122. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  38123. }
  38124. if (isIpcUrl) {
  38125. const parts = opts.path.split(":");
  38126. opts.socketPath = parts[0];
  38127. opts.path = parts[1];
  38128. }
  38129. let req;
  38130. if (opts.followRedirects) {
  38131. if (websocket._redirects === 0) {
  38132. websocket._originalIpc = isIpcUrl;
  38133. websocket._originalSecure = isSecure;
  38134. websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
  38135. const headers = options && options.headers;
  38136. options = { ...options, headers: {} };
  38137. if (headers) {
  38138. for (const [key2, value] of Object.entries(headers)) {
  38139. options.headers[key2.toLowerCase()] = value;
  38140. }
  38141. }
  38142. } else if (websocket.listenerCount("redirect") === 0) {
  38143. const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
  38144. if (!isSameHost || websocket._originalSecure && !isSecure) {
  38145. delete opts.headers.authorization;
  38146. delete opts.headers.cookie;
  38147. if (!isSameHost) delete opts.headers.host;
  38148. opts.auth = void 0;
  38149. }
  38150. }
  38151. if (opts.auth && !options.headers.authorization) {
  38152. options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
  38153. }
  38154. req = websocket._req = request2(opts);
  38155. if (websocket._redirects) {
  38156. websocket.emit("redirect", websocket.url, req);
  38157. }
  38158. } else {
  38159. req = websocket._req = request2(opts);
  38160. }
  38161. if (opts.timeout) {
  38162. req.on("timeout", () => {
  38163. abortHandshake(websocket, req, "Opening handshake has timed out");
  38164. });
  38165. }
  38166. req.on("error", (err2) => {
  38167. if (req === null || req[kAborted]) return;
  38168. req = websocket._req = null;
  38169. emitErrorAndClose(websocket, err2);
  38170. });
  38171. req.on("response", (res) => {
  38172. const location = res.headers.location;
  38173. const statusCode = res.statusCode;
  38174. if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
  38175. if (++websocket._redirects > opts.maxRedirects) {
  38176. abortHandshake(websocket, req, "Maximum redirects exceeded");
  38177. return;
  38178. }
  38179. req.abort();
  38180. let addr;
  38181. try {
  38182. addr = new URL2(location, address);
  38183. } catch (e6) {
  38184. const err2 = new SyntaxError(`Invalid URL: ${location}`);
  38185. emitErrorAndClose(websocket, err2);
  38186. return;
  38187. }
  38188. initAsClient(websocket, addr, protocols, options);
  38189. } else if (!websocket.emit("unexpected-response", req, res)) {
  38190. abortHandshake(
  38191. websocket,
  38192. req,
  38193. `Unexpected server response: ${res.statusCode}`
  38194. );
  38195. }
  38196. });
  38197. req.on("upgrade", (res, socket, head) => {
  38198. websocket.emit("upgrade", res);
  38199. if (websocket.readyState !== WebSocket2.CONNECTING) return;
  38200. req = websocket._req = null;
  38201. const upgrade = res.headers.upgrade;
  38202. if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
  38203. abortHandshake(websocket, socket, "Invalid Upgrade header");
  38204. return;
  38205. }
  38206. const digest = createHash4("sha1").update(key + GUID).digest("base64");
  38207. if (res.headers["sec-websocket-accept"] !== digest) {
  38208. abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
  38209. return;
  38210. }
  38211. const serverProt = res.headers["sec-websocket-protocol"];
  38212. let protError;
  38213. if (serverProt !== void 0) {
  38214. if (!protocolSet.size) {
  38215. protError = "Server sent a subprotocol but none was requested";
  38216. } else if (!protocolSet.has(serverProt)) {
  38217. protError = "Server sent an invalid subprotocol";
  38218. }
  38219. } else if (protocolSet.size) {
  38220. protError = "Server sent no subprotocol";
  38221. }
  38222. if (protError) {
  38223. abortHandshake(websocket, socket, protError);
  38224. return;
  38225. }
  38226. if (serverProt) websocket._protocol = serverProt;
  38227. const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
  38228. if (secWebSocketExtensions !== void 0) {
  38229. if (!perMessageDeflate) {
  38230. const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
  38231. abortHandshake(websocket, socket, message);
  38232. return;
  38233. }
  38234. let extensions;
  38235. try {
  38236. extensions = parse4(secWebSocketExtensions);
  38237. } catch (err2) {
  38238. const message = "Invalid Sec-WebSocket-Extensions header";
  38239. abortHandshake(websocket, socket, message);
  38240. return;
  38241. }
  38242. const extensionNames = Object.keys(extensions);
  38243. if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
  38244. const message = "Server indicated an extension that was not requested";
  38245. abortHandshake(websocket, socket, message);
  38246. return;
  38247. }
  38248. try {
  38249. perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
  38250. } catch (err2) {
  38251. const message = "Invalid Sec-WebSocket-Extensions header";
  38252. abortHandshake(websocket, socket, message);
  38253. return;
  38254. }
  38255. websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  38256. }
  38257. websocket.setSocket(socket, head, {
  38258. allowSynchronousEvents: opts.allowSynchronousEvents,
  38259. generateMask: opts.generateMask,
  38260. maxPayload: opts.maxPayload,
  38261. skipUTF8Validation: opts.skipUTF8Validation
  38262. });
  38263. });
  38264. if (opts.finishRequest) {
  38265. opts.finishRequest(req, websocket);
  38266. } else {
  38267. req.end();
  38268. }
  38269. }
  38270. function emitErrorAndClose(websocket, err2) {
  38271. websocket._readyState = WebSocket2.CLOSING;
  38272. websocket._errorEmitted = true;
  38273. websocket.emit("error", err2);
  38274. websocket.emitClose();
  38275. }
  38276. function netConnect(options) {
  38277. options.path = options.socketPath;
  38278. return net.connect(options);
  38279. }
  38280. function tlsConnect(options) {
  38281. options.path = void 0;
  38282. if (!options.servername && options.servername !== "") {
  38283. options.servername = net.isIP(options.host) ? "" : options.host;
  38284. }
  38285. return tls.connect(options);
  38286. }
  38287. function abortHandshake(websocket, stream, message) {
  38288. websocket._readyState = WebSocket2.CLOSING;
  38289. const err2 = new Error(message);
  38290. Error.captureStackTrace(err2, abortHandshake);
  38291. if (stream.setHeader) {
  38292. stream[kAborted] = true;
  38293. stream.abort();
  38294. if (stream.socket && !stream.socket.destroyed) {
  38295. stream.socket.destroy();
  38296. }
  38297. process.nextTick(emitErrorAndClose, websocket, err2);
  38298. } else {
  38299. stream.destroy(err2);
  38300. stream.once("error", websocket.emit.bind(websocket, "error"));
  38301. stream.once("close", websocket.emitClose.bind(websocket));
  38302. }
  38303. }
  38304. function sendAfterClose(websocket, data, cb) {
  38305. if (data) {
  38306. const length = isBlob3(data) ? data.size : toBuffer(data).length;
  38307. if (websocket._socket) websocket._sender._bufferedBytes += length;
  38308. else websocket._bufferedAmount += length;
  38309. }
  38310. if (cb) {
  38311. const err2 = new Error(
  38312. `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
  38313. );
  38314. process.nextTick(cb, err2);
  38315. }
  38316. }
  38317. function receiverOnConclude(code, reason) {
  38318. const websocket = this[kWebSocket];
  38319. websocket._closeFrameReceived = true;
  38320. websocket._closeMessage = reason;
  38321. websocket._closeCode = code;
  38322. if (websocket._socket[kWebSocket] === void 0) return;
  38323. websocket._socket.removeListener("data", socketOnData);
  38324. process.nextTick(resume, websocket._socket);
  38325. if (code === 1005) websocket.close();
  38326. else websocket.close(code, reason);
  38327. }
  38328. function receiverOnDrain() {
  38329. const websocket = this[kWebSocket];
  38330. if (!websocket.isPaused) websocket._socket.resume();
  38331. }
  38332. function receiverOnError(err2) {
  38333. const websocket = this[kWebSocket];
  38334. if (websocket._socket[kWebSocket] !== void 0) {
  38335. websocket._socket.removeListener("data", socketOnData);
  38336. process.nextTick(resume, websocket._socket);
  38337. websocket.close(err2[kStatusCode]);
  38338. }
  38339. if (!websocket._errorEmitted) {
  38340. websocket._errorEmitted = true;
  38341. websocket.emit("error", err2);
  38342. }
  38343. }
  38344. function receiverOnFinish() {
  38345. this[kWebSocket].emitClose();
  38346. }
  38347. function receiverOnMessage(data, isBinary) {
  38348. this[kWebSocket].emit("message", data, isBinary);
  38349. }
  38350. function receiverOnPing(data) {
  38351. const websocket = this[kWebSocket];
  38352. if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
  38353. websocket.emit("ping", data);
  38354. }
  38355. function receiverOnPong(data) {
  38356. this[kWebSocket].emit("pong", data);
  38357. }
  38358. function resume(stream) {
  38359. stream.resume();
  38360. }
  38361. function senderOnError(err2) {
  38362. const websocket = this[kWebSocket];
  38363. if (websocket.readyState === WebSocket2.CLOSED) return;
  38364. if (websocket.readyState === WebSocket2.OPEN) {
  38365. websocket._readyState = WebSocket2.CLOSING;
  38366. setCloseTimer(websocket);
  38367. }
  38368. this._socket.end();
  38369. if (!websocket._errorEmitted) {
  38370. websocket._errorEmitted = true;
  38371. websocket.emit("error", err2);
  38372. }
  38373. }
  38374. function setCloseTimer(websocket) {
  38375. websocket._closeTimer = setTimeout(
  38376. websocket._socket.destroy.bind(websocket._socket),
  38377. closeTimeout
  38378. );
  38379. }
  38380. function socketOnClose() {
  38381. const websocket = this[kWebSocket];
  38382. this.removeListener("close", socketOnClose);
  38383. this.removeListener("data", socketOnData);
  38384. this.removeListener("end", socketOnEnd);
  38385. websocket._readyState = WebSocket2.CLOSING;
  38386. let chunk;
  38387. if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
  38388. websocket._receiver.write(chunk);
  38389. }
  38390. websocket._receiver.end();
  38391. this[kWebSocket] = void 0;
  38392. clearTimeout(websocket._closeTimer);
  38393. if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
  38394. websocket.emitClose();
  38395. } else {
  38396. websocket._receiver.on("error", receiverOnFinish);
  38397. websocket._receiver.on("finish", receiverOnFinish);
  38398. }
  38399. }
  38400. function socketOnData(chunk) {
  38401. if (!this[kWebSocket]._receiver.write(chunk)) {
  38402. this.pause();
  38403. }
  38404. }
  38405. function socketOnEnd() {
  38406. const websocket = this[kWebSocket];
  38407. websocket._readyState = WebSocket2.CLOSING;
  38408. websocket._receiver.end();
  38409. this.end();
  38410. }
  38411. function socketOnError() {
  38412. const websocket = this[kWebSocket];
  38413. this.removeListener("error", socketOnError);
  38414. this.on("error", NOOP);
  38415. if (websocket) {
  38416. websocket._readyState = WebSocket2.CLOSING;
  38417. this.destroy();
  38418. }
  38419. }
  38420. }
  38421. });
  38422. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/stream.js
  38423. var require_stream = __commonJS({
  38424. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/stream.js"(exports, module) {
  38425. "use strict";
  38426. var WebSocket2 = require_websocket();
  38427. var { Duplex } = __require("stream");
  38428. function emitClose(stream) {
  38429. stream.emit("close");
  38430. }
  38431. function duplexOnEnd() {
  38432. if (!this.destroyed && this._writableState.finished) {
  38433. this.destroy();
  38434. }
  38435. }
  38436. function duplexOnError(err2) {
  38437. this.removeListener("error", duplexOnError);
  38438. this.destroy();
  38439. if (this.listenerCount("error") === 0) {
  38440. this.emit("error", err2);
  38441. }
  38442. }
  38443. function createWebSocketStream2(ws, options) {
  38444. let terminateOnDestroy = true;
  38445. const duplex = new Duplex({
  38446. ...options,
  38447. autoDestroy: false,
  38448. emitClose: false,
  38449. objectMode: false,
  38450. writableObjectMode: false
  38451. });
  38452. ws.on("message", function message(msg, isBinary) {
  38453. const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
  38454. if (!duplex.push(data)) ws.pause();
  38455. });
  38456. ws.once("error", function error2(err2) {
  38457. if (duplex.destroyed) return;
  38458. terminateOnDestroy = false;
  38459. duplex.destroy(err2);
  38460. });
  38461. ws.once("close", function close() {
  38462. if (duplex.destroyed) return;
  38463. duplex.push(null);
  38464. });
  38465. duplex._destroy = function(err2, callback) {
  38466. if (ws.readyState === ws.CLOSED) {
  38467. callback(err2);
  38468. process.nextTick(emitClose, duplex);
  38469. return;
  38470. }
  38471. let called = false;
  38472. ws.once("error", function error2(err3) {
  38473. called = true;
  38474. callback(err3);
  38475. });
  38476. ws.once("close", function close() {
  38477. if (!called) callback(err2);
  38478. process.nextTick(emitClose, duplex);
  38479. });
  38480. if (terminateOnDestroy) ws.terminate();
  38481. };
  38482. duplex._final = function(callback) {
  38483. if (ws.readyState === ws.CONNECTING) {
  38484. ws.once("open", function open() {
  38485. duplex._final(callback);
  38486. });
  38487. return;
  38488. }
  38489. if (ws._socket === null) return;
  38490. if (ws._socket._writableState.finished) {
  38491. callback();
  38492. if (duplex._readableState.endEmitted) duplex.destroy();
  38493. } else {
  38494. ws._socket.once("finish", function finish() {
  38495. callback();
  38496. });
  38497. ws.close();
  38498. }
  38499. };
  38500. duplex._read = function() {
  38501. if (ws.isPaused) ws.resume();
  38502. };
  38503. duplex._write = function(chunk, encoding, callback) {
  38504. if (ws.readyState === ws.CONNECTING) {
  38505. ws.once("open", function open() {
  38506. duplex._write(chunk, encoding, callback);
  38507. });
  38508. return;
  38509. }
  38510. ws.send(chunk, callback);
  38511. };
  38512. duplex.on("end", duplexOnEnd);
  38513. duplex.on("error", duplexOnError);
  38514. return duplex;
  38515. }
  38516. module.exports = createWebSocketStream2;
  38517. }
  38518. });
  38519. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/subprotocol.js
  38520. var require_subprotocol = __commonJS({
  38521. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/subprotocol.js"(exports, module) {
  38522. "use strict";
  38523. var { tokenChars } = require_validation();
  38524. function parse4(header) {
  38525. const protocols = /* @__PURE__ */ new Set();
  38526. let start = -1;
  38527. let end = -1;
  38528. let i6 = 0;
  38529. for (i6; i6 < header.length; i6++) {
  38530. const code = header.charCodeAt(i6);
  38531. if (end === -1 && tokenChars[code] === 1) {
  38532. if (start === -1) start = i6;
  38533. } else if (i6 !== 0 && (code === 32 || code === 9)) {
  38534. if (end === -1 && start !== -1) end = i6;
  38535. } else if (code === 44) {
  38536. if (start === -1) {
  38537. throw new SyntaxError(`Unexpected character at index ${i6}`);
  38538. }
  38539. if (end === -1) end = i6;
  38540. const protocol2 = header.slice(start, end);
  38541. if (protocols.has(protocol2)) {
  38542. throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
  38543. }
  38544. protocols.add(protocol2);
  38545. start = end = -1;
  38546. } else {
  38547. throw new SyntaxError(`Unexpected character at index ${i6}`);
  38548. }
  38549. }
  38550. if (start === -1 || end !== -1) {
  38551. throw new SyntaxError("Unexpected end of input");
  38552. }
  38553. const protocol = header.slice(start, i6);
  38554. if (protocols.has(protocol)) {
  38555. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  38556. }
  38557. protocols.add(protocol);
  38558. return protocols;
  38559. }
  38560. module.exports = { parse: parse4 };
  38561. }
  38562. });
  38563. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket-server.js
  38564. var require_websocket_server = __commonJS({
  38565. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket-server.js"(exports, module) {
  38566. "use strict";
  38567. var EventEmitter = __require("events");
  38568. var http3 = __require("http");
  38569. var { Duplex } = __require("stream");
  38570. var { createHash: createHash4 } = __require("crypto");
  38571. var extension = require_extension();
  38572. var PerMessageDeflate = require_permessage_deflate();
  38573. var subprotocol = require_subprotocol();
  38574. var WebSocket2 = require_websocket();
  38575. var { GUID, kWebSocket } = require_constants();
  38576. var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  38577. var RUNNING = 0;
  38578. var CLOSING = 1;
  38579. var CLOSED = 2;
  38580. var WebSocketServer2 = class extends EventEmitter {
  38581. /**
  38582. * Create a `WebSocketServer` instance.
  38583. *
  38584. * @param {Object} options Configuration options
  38585. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  38586. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  38587. * multiple times in the same tick
  38588. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  38589. * automatically send a pong in response to a ping
  38590. * @param {Number} [options.backlog=511] The maximum length of the queue of
  38591. * pending connections
  38592. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  38593. * track clients
  38594. * @param {Function} [options.handleProtocols] A hook to handle protocols
  38595. * @param {String} [options.host] The hostname where to bind the server
  38596. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  38597. * size
  38598. * @param {Boolean} [options.noServer=false] Enable no server mode
  38599. * @param {String} [options.path] Accept only connections matching this path
  38600. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  38601. * permessage-deflate
  38602. * @param {Number} [options.port] The port where to bind the server
  38603. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  38604. * server to use
  38605. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  38606. * not to skip UTF-8 validation for text and close messages
  38607. * @param {Function} [options.verifyClient] A hook to reject connections
  38608. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  38609. * class to use. It must be the `WebSocket` class or class that extends it
  38610. * @param {Function} [callback] A listener for the `listening` event
  38611. */
  38612. constructor(options, callback) {
  38613. super();
  38614. options = {
  38615. allowSynchronousEvents: true,
  38616. autoPong: true,
  38617. maxPayload: 100 * 1024 * 1024,
  38618. skipUTF8Validation: false,
  38619. perMessageDeflate: false,
  38620. handleProtocols: null,
  38621. clientTracking: true,
  38622. verifyClient: null,
  38623. noServer: false,
  38624. backlog: null,
  38625. // use default (511 as implemented in net.js)
  38626. server: null,
  38627. host: null,
  38628. path: null,
  38629. port: null,
  38630. WebSocket: WebSocket2,
  38631. ...options
  38632. };
  38633. if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
  38634. throw new TypeError(
  38635. 'One and only one of the "port", "server", or "noServer" options must be specified'
  38636. );
  38637. }
  38638. if (options.port != null) {
  38639. this._server = http3.createServer((req, res) => {
  38640. const body = http3.STATUS_CODES[426];
  38641. res.writeHead(426, {
  38642. "Content-Length": body.length,
  38643. "Content-Type": "text/plain"
  38644. });
  38645. res.end(body);
  38646. });
  38647. this._server.listen(
  38648. options.port,
  38649. options.host,
  38650. options.backlog,
  38651. callback
  38652. );
  38653. } else if (options.server) {
  38654. this._server = options.server;
  38655. }
  38656. if (this._server) {
  38657. const emitConnection = this.emit.bind(this, "connection");
  38658. this._removeListeners = addListeners(this._server, {
  38659. listening: this.emit.bind(this, "listening"),
  38660. error: this.emit.bind(this, "error"),
  38661. upgrade: (req, socket, head) => {
  38662. this.handleUpgrade(req, socket, head, emitConnection);
  38663. }
  38664. });
  38665. }
  38666. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  38667. if (options.clientTracking) {
  38668. this.clients = /* @__PURE__ */ new Set();
  38669. this._shouldEmitClose = false;
  38670. }
  38671. this.options = options;
  38672. this._state = RUNNING;
  38673. }
  38674. /**
  38675. * Returns the bound address, the address family name, and port of the server
  38676. * as reported by the operating system if listening on an IP socket.
  38677. * If the server is listening on a pipe or UNIX domain socket, the name is
  38678. * returned as a string.
  38679. *
  38680. * @return {(Object|String|null)} The address of the server
  38681. * @public
  38682. */
  38683. address() {
  38684. if (this.options.noServer) {
  38685. throw new Error('The server is operating in "noServer" mode');
  38686. }
  38687. if (!this._server) return null;
  38688. return this._server.address();
  38689. }
  38690. /**
  38691. * Stop the server from accepting new connections and emit the `'close'` event
  38692. * when all existing connections are closed.
  38693. *
  38694. * @param {Function} [cb] A one-time listener for the `'close'` event
  38695. * @public
  38696. */
  38697. close(cb) {
  38698. if (this._state === CLOSED) {
  38699. if (cb) {
  38700. this.once("close", () => {
  38701. cb(new Error("The server is not running"));
  38702. });
  38703. }
  38704. process.nextTick(emitClose, this);
  38705. return;
  38706. }
  38707. if (cb) this.once("close", cb);
  38708. if (this._state === CLOSING) return;
  38709. this._state = CLOSING;
  38710. if (this.options.noServer || this.options.server) {
  38711. if (this._server) {
  38712. this._removeListeners();
  38713. this._removeListeners = this._server = null;
  38714. }
  38715. if (this.clients) {
  38716. if (!this.clients.size) {
  38717. process.nextTick(emitClose, this);
  38718. } else {
  38719. this._shouldEmitClose = true;
  38720. }
  38721. } else {
  38722. process.nextTick(emitClose, this);
  38723. }
  38724. } else {
  38725. const server = this._server;
  38726. this._removeListeners();
  38727. this._removeListeners = this._server = null;
  38728. server.close(() => {
  38729. emitClose(this);
  38730. });
  38731. }
  38732. }
  38733. /**
  38734. * See if a given request should be handled by this server instance.
  38735. *
  38736. * @param {http.IncomingMessage} req Request object to inspect
  38737. * @return {Boolean} `true` if the request is valid, else `false`
  38738. * @public
  38739. */
  38740. shouldHandle(req) {
  38741. if (this.options.path) {
  38742. const index6 = req.url.indexOf("?");
  38743. const pathname = index6 !== -1 ? req.url.slice(0, index6) : req.url;
  38744. if (pathname !== this.options.path) return false;
  38745. }
  38746. return true;
  38747. }
  38748. /**
  38749. * Handle a HTTP Upgrade request.
  38750. *
  38751. * @param {http.IncomingMessage} req The request object
  38752. * @param {Duplex} socket The network socket between the server and client
  38753. * @param {Buffer} head The first packet of the upgraded stream
  38754. * @param {Function} cb Callback
  38755. * @public
  38756. */
  38757. handleUpgrade(req, socket, head, cb) {
  38758. socket.on("error", socketOnError);
  38759. const key = req.headers["sec-websocket-key"];
  38760. const upgrade = req.headers.upgrade;
  38761. const version = +req.headers["sec-websocket-version"];
  38762. if (req.method !== "GET") {
  38763. const message = "Invalid HTTP method";
  38764. abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
  38765. return;
  38766. }
  38767. if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
  38768. const message = "Invalid Upgrade header";
  38769. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  38770. return;
  38771. }
  38772. if (key === void 0 || !keyRegex.test(key)) {
  38773. const message = "Missing or invalid Sec-WebSocket-Key header";
  38774. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  38775. return;
  38776. }
  38777. if (version !== 8 && version !== 13) {
  38778. const message = "Missing or invalid Sec-WebSocket-Version header";
  38779. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  38780. return;
  38781. }
  38782. if (!this.shouldHandle(req)) {
  38783. abortHandshake(socket, 400);
  38784. return;
  38785. }
  38786. const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
  38787. let protocols = /* @__PURE__ */ new Set();
  38788. if (secWebSocketProtocol !== void 0) {
  38789. try {
  38790. protocols = subprotocol.parse(secWebSocketProtocol);
  38791. } catch (err2) {
  38792. const message = "Invalid Sec-WebSocket-Protocol header";
  38793. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  38794. return;
  38795. }
  38796. }
  38797. const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
  38798. const extensions = {};
  38799. if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
  38800. const perMessageDeflate = new PerMessageDeflate(
  38801. this.options.perMessageDeflate,
  38802. true,
  38803. this.options.maxPayload
  38804. );
  38805. try {
  38806. const offers = extension.parse(secWebSocketExtensions);
  38807. if (offers[PerMessageDeflate.extensionName]) {
  38808. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  38809. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  38810. }
  38811. } catch (err2) {
  38812. const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
  38813. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  38814. return;
  38815. }
  38816. }
  38817. if (this.options.verifyClient) {
  38818. const info2 = {
  38819. origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
  38820. secure: !!(req.socket.authorized || req.socket.encrypted),
  38821. req
  38822. };
  38823. if (this.options.verifyClient.length === 2) {
  38824. this.options.verifyClient(info2, (verified, code, message, headers) => {
  38825. if (!verified) {
  38826. return abortHandshake(socket, code || 401, message, headers);
  38827. }
  38828. this.completeUpgrade(
  38829. extensions,
  38830. key,
  38831. protocols,
  38832. req,
  38833. socket,
  38834. head,
  38835. cb
  38836. );
  38837. });
  38838. return;
  38839. }
  38840. if (!this.options.verifyClient(info2)) return abortHandshake(socket, 401);
  38841. }
  38842. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  38843. }
  38844. /**
  38845. * Upgrade the connection to WebSocket.
  38846. *
  38847. * @param {Object} extensions The accepted extensions
  38848. * @param {String} key The value of the `Sec-WebSocket-Key` header
  38849. * @param {Set} protocols The subprotocols
  38850. * @param {http.IncomingMessage} req The request object
  38851. * @param {Duplex} socket The network socket between the server and client
  38852. * @param {Buffer} head The first packet of the upgraded stream
  38853. * @param {Function} cb Callback
  38854. * @throws {Error} If called more than once with the same socket
  38855. * @private
  38856. */
  38857. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  38858. if (!socket.readable || !socket.writable) return socket.destroy();
  38859. if (socket[kWebSocket]) {
  38860. throw new Error(
  38861. "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
  38862. );
  38863. }
  38864. if (this._state > RUNNING) return abortHandshake(socket, 503);
  38865. const digest = createHash4("sha1").update(key + GUID).digest("base64");
  38866. const headers = [
  38867. "HTTP/1.1 101 Switching Protocols",
  38868. "Upgrade: websocket",
  38869. "Connection: Upgrade",
  38870. `Sec-WebSocket-Accept: ${digest}`
  38871. ];
  38872. const ws = new this.options.WebSocket(null, void 0, this.options);
  38873. if (protocols.size) {
  38874. const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
  38875. if (protocol) {
  38876. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  38877. ws._protocol = protocol;
  38878. }
  38879. }
  38880. if (extensions[PerMessageDeflate.extensionName]) {
  38881. const params = extensions[PerMessageDeflate.extensionName].params;
  38882. const value = extension.format({
  38883. [PerMessageDeflate.extensionName]: [params]
  38884. });
  38885. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  38886. ws._extensions = extensions;
  38887. }
  38888. this.emit("headers", headers, req);
  38889. socket.write(headers.concat("\r\n").join("\r\n"));
  38890. socket.removeListener("error", socketOnError);
  38891. ws.setSocket(socket, head, {
  38892. allowSynchronousEvents: this.options.allowSynchronousEvents,
  38893. maxPayload: this.options.maxPayload,
  38894. skipUTF8Validation: this.options.skipUTF8Validation
  38895. });
  38896. if (this.clients) {
  38897. this.clients.add(ws);
  38898. ws.on("close", () => {
  38899. this.clients.delete(ws);
  38900. if (this._shouldEmitClose && !this.clients.size) {
  38901. process.nextTick(emitClose, this);
  38902. }
  38903. });
  38904. }
  38905. cb(ws, req);
  38906. }
  38907. };
  38908. module.exports = WebSocketServer2;
  38909. function addListeners(server, map2) {
  38910. for (const event of Object.keys(map2)) server.on(event, map2[event]);
  38911. return function removeListeners() {
  38912. for (const event of Object.keys(map2)) {
  38913. server.removeListener(event, map2[event]);
  38914. }
  38915. };
  38916. }
  38917. function emitClose(server) {
  38918. server._state = CLOSED;
  38919. server.emit("close");
  38920. }
  38921. function socketOnError() {
  38922. this.destroy();
  38923. }
  38924. function abortHandshake(socket, code, message, headers) {
  38925. message = message || http3.STATUS_CODES[code];
  38926. headers = {
  38927. Connection: "close",
  38928. "Content-Type": "text/html",
  38929. "Content-Length": Buffer.byteLength(message),
  38930. ...headers
  38931. };
  38932. socket.once("finish", socket.destroy);
  38933. socket.end(
  38934. `HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r
  38935. ` + Object.keys(headers).map((h6) => `${h6}: ${headers[h6]}`).join("\r\n") + "\r\n\r\n" + message
  38936. );
  38937. }
  38938. function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
  38939. if (server.listenerCount("wsClientError")) {
  38940. const err2 = new Error(message);
  38941. Error.captureStackTrace(err2, abortHandshakeOrEmitwsClientError);
  38942. server.emit("wsClientError", err2, socket, req);
  38943. } else {
  38944. abortHandshake(socket, code, message);
  38945. }
  38946. }
  38947. }
  38948. });
  38949. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/wrapper.mjs
  38950. var import_stream2, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
  38951. var init_wrapper = __esm({
  38952. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/wrapper.mjs"() {
  38953. "use strict";
  38954. import_stream2 = __toESM(require_stream(), 1);
  38955. import_receiver = __toESM(require_receiver(), 1);
  38956. import_sender = __toESM(require_sender(), 1);
  38957. import_websocket = __toESM(require_websocket(), 1);
  38958. import_websocket_server = __toESM(require_websocket_server(), 1);
  38959. wrapper_default = import_websocket.default;
  38960. }
  38961. });
  38962. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js
  38963. var require_constants2 = __commonJS({
  38964. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js"(exports, module) {
  38965. "use strict";
  38966. var SEMVER_SPEC_VERSION = "2.0.0";
  38967. var MAX_LENGTH = 256;
  38968. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
  38969. 9007199254740991;
  38970. var MAX_SAFE_COMPONENT_LENGTH = 16;
  38971. var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
  38972. var RELEASE_TYPES = [
  38973. "major",
  38974. "premajor",
  38975. "minor",
  38976. "preminor",
  38977. "patch",
  38978. "prepatch",
  38979. "prerelease"
  38980. ];
  38981. module.exports = {
  38982. MAX_LENGTH,
  38983. MAX_SAFE_COMPONENT_LENGTH,
  38984. MAX_SAFE_BUILD_LENGTH,
  38985. MAX_SAFE_INTEGER,
  38986. RELEASE_TYPES,
  38987. SEMVER_SPEC_VERSION,
  38988. FLAG_INCLUDE_PRERELEASE: 1,
  38989. FLAG_LOOSE: 2
  38990. };
  38991. }
  38992. });
  38993. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js
  38994. var require_debug = __commonJS({
  38995. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js"(exports, module) {
  38996. "use strict";
  38997. var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
  38998. };
  38999. module.exports = debug;
  39000. }
  39001. });
  39002. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js
  39003. var require_re = __commonJS({
  39004. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js"(exports, module) {
  39005. "use strict";
  39006. var {
  39007. MAX_SAFE_COMPONENT_LENGTH,
  39008. MAX_SAFE_BUILD_LENGTH,
  39009. MAX_LENGTH
  39010. } = require_constants2();
  39011. var debug = require_debug();
  39012. exports = module.exports = {};
  39013. var re = exports.re = [];
  39014. var safeRe = exports.safeRe = [];
  39015. var src = exports.src = [];
  39016. var safeSrc = exports.safeSrc = [];
  39017. var t6 = exports.t = {};
  39018. var R = 0;
  39019. var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
  39020. var safeRegexReplacements = [
  39021. ["\\s", 1],
  39022. ["\\d", MAX_LENGTH],
  39023. [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
  39024. ];
  39025. var makeSafeRegex = (value) => {
  39026. for (const [token, max] of safeRegexReplacements) {
  39027. value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
  39028. }
  39029. return value;
  39030. };
  39031. var createToken = (name, value, isGlobal) => {
  39032. const safe = makeSafeRegex(value);
  39033. const index6 = R++;
  39034. debug(name, index6, value);
  39035. t6[name] = index6;
  39036. src[index6] = value;
  39037. safeSrc[index6] = safe;
  39038. re[index6] = new RegExp(value, isGlobal ? "g" : void 0);
  39039. safeRe[index6] = new RegExp(safe, isGlobal ? "g" : void 0);
  39040. };
  39041. createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
  39042. createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
  39043. createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
  39044. createToken("MAINVERSION", `(${src[t6.NUMERICIDENTIFIER]})\\.(${src[t6.NUMERICIDENTIFIER]})\\.(${src[t6.NUMERICIDENTIFIER]})`);
  39045. createToken("MAINVERSIONLOOSE", `(${src[t6.NUMERICIDENTIFIERLOOSE]})\\.(${src[t6.NUMERICIDENTIFIERLOOSE]})\\.(${src[t6.NUMERICIDENTIFIERLOOSE]})`);
  39046. createToken("PRERELEASEIDENTIFIER", `(?:${src[t6.NONNUMERICIDENTIFIER]}|${src[t6.NUMERICIDENTIFIER]})`);
  39047. createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t6.NONNUMERICIDENTIFIER]}|${src[t6.NUMERICIDENTIFIERLOOSE]})`);
  39048. createToken("PRERELEASE", `(?:-(${src[t6.PRERELEASEIDENTIFIER]}(?:\\.${src[t6.PRERELEASEIDENTIFIER]})*))`);
  39049. createToken("PRERELEASELOOSE", `(?:-?(${src[t6.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t6.PRERELEASEIDENTIFIERLOOSE]})*))`);
  39050. createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
  39051. createToken("BUILD", `(?:\\+(${src[t6.BUILDIDENTIFIER]}(?:\\.${src[t6.BUILDIDENTIFIER]})*))`);
  39052. createToken("FULLPLAIN", `v?${src[t6.MAINVERSION]}${src[t6.PRERELEASE]}?${src[t6.BUILD]}?`);
  39053. createToken("FULL", `^${src[t6.FULLPLAIN]}$`);
  39054. createToken("LOOSEPLAIN", `[v=\\s]*${src[t6.MAINVERSIONLOOSE]}${src[t6.PRERELEASELOOSE]}?${src[t6.BUILD]}?`);
  39055. createToken("LOOSE", `^${src[t6.LOOSEPLAIN]}$`);
  39056. createToken("GTLT", "((?:<|>)?=?)");
  39057. createToken("XRANGEIDENTIFIERLOOSE", `${src[t6.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
  39058. createToken("XRANGEIDENTIFIER", `${src[t6.NUMERICIDENTIFIER]}|x|X|\\*`);
  39059. createToken("XRANGEPLAIN", `[v=\\s]*(${src[t6.XRANGEIDENTIFIER]})(?:\\.(${src[t6.XRANGEIDENTIFIER]})(?:\\.(${src[t6.XRANGEIDENTIFIER]})(?:${src[t6.PRERELEASE]})?${src[t6.BUILD]}?)?)?`);
  39060. createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t6.XRANGEIDENTIFIERLOOSE]})(?:${src[t6.PRERELEASELOOSE]})?${src[t6.BUILD]}?)?)?`);
  39061. createToken("XRANGE", `^${src[t6.GTLT]}\\s*${src[t6.XRANGEPLAIN]}$`);
  39062. createToken("XRANGELOOSE", `^${src[t6.GTLT]}\\s*${src[t6.XRANGEPLAINLOOSE]}$`);
  39063. createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
  39064. createToken("COERCE", `${src[t6.COERCEPLAIN]}(?:$|[^\\d])`);
  39065. createToken("COERCEFULL", src[t6.COERCEPLAIN] + `(?:${src[t6.PRERELEASE]})?(?:${src[t6.BUILD]})?(?:$|[^\\d])`);
  39066. createToken("COERCERTL", src[t6.COERCE], true);
  39067. createToken("COERCERTLFULL", src[t6.COERCEFULL], true);
  39068. createToken("LONETILDE", "(?:~>?)");
  39069. createToken("TILDETRIM", `(\\s*)${src[t6.LONETILDE]}\\s+`, true);
  39070. exports.tildeTrimReplace = "$1~";
  39071. createToken("TILDE", `^${src[t6.LONETILDE]}${src[t6.XRANGEPLAIN]}$`);
  39072. createToken("TILDELOOSE", `^${src[t6.LONETILDE]}${src[t6.XRANGEPLAINLOOSE]}$`);
  39073. createToken("LONECARET", "(?:\\^)");
  39074. createToken("CARETTRIM", `(\\s*)${src[t6.LONECARET]}\\s+`, true);
  39075. exports.caretTrimReplace = "$1^";
  39076. createToken("CARET", `^${src[t6.LONECARET]}${src[t6.XRANGEPLAIN]}$`);
  39077. createToken("CARETLOOSE", `^${src[t6.LONECARET]}${src[t6.XRANGEPLAINLOOSE]}$`);
  39078. createToken("COMPARATORLOOSE", `^${src[t6.GTLT]}\\s*(${src[t6.LOOSEPLAIN]})$|^$`);
  39079. createToken("COMPARATOR", `^${src[t6.GTLT]}\\s*(${src[t6.FULLPLAIN]})$|^$`);
  39080. createToken("COMPARATORTRIM", `(\\s*)${src[t6.GTLT]}\\s*(${src[t6.LOOSEPLAIN]}|${src[t6.XRANGEPLAIN]})`, true);
  39081. exports.comparatorTrimReplace = "$1$2$3";
  39082. createToken("HYPHENRANGE", `^\\s*(${src[t6.XRANGEPLAIN]})\\s+-\\s+(${src[t6.XRANGEPLAIN]})\\s*$`);
  39083. createToken("HYPHENRANGELOOSE", `^\\s*(${src[t6.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t6.XRANGEPLAINLOOSE]})\\s*$`);
  39084. createToken("STAR", "(<|>)?=?\\s*\\*");
  39085. createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
  39086. createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
  39087. }
  39088. });
  39089. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js
  39090. var require_parse_options = __commonJS({
  39091. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js"(exports, module) {
  39092. "use strict";
  39093. var looseOption = Object.freeze({ loose: true });
  39094. var emptyOpts = Object.freeze({});
  39095. var parseOptions = (options) => {
  39096. if (!options) {
  39097. return emptyOpts;
  39098. }
  39099. if (typeof options !== "object") {
  39100. return looseOption;
  39101. }
  39102. return options;
  39103. };
  39104. module.exports = parseOptions;
  39105. }
  39106. });
  39107. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js
  39108. var require_identifiers = __commonJS({
  39109. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js"(exports, module) {
  39110. "use strict";
  39111. var numeric = /^[0-9]+$/;
  39112. var compareIdentifiers = (a5, b5) => {
  39113. const anum = numeric.test(a5);
  39114. const bnum = numeric.test(b5);
  39115. if (anum && bnum) {
  39116. a5 = +a5;
  39117. b5 = +b5;
  39118. }
  39119. return a5 === b5 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a5 < b5 ? -1 : 1;
  39120. };
  39121. var rcompareIdentifiers = (a5, b5) => compareIdentifiers(b5, a5);
  39122. module.exports = {
  39123. compareIdentifiers,
  39124. rcompareIdentifiers
  39125. };
  39126. }
  39127. });
  39128. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js
  39129. var require_semver = __commonJS({
  39130. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js"(exports, module) {
  39131. "use strict";
  39132. var debug = require_debug();
  39133. var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants2();
  39134. var { safeRe: re, t: t6 } = require_re();
  39135. var parseOptions = require_parse_options();
  39136. var { compareIdentifiers } = require_identifiers();
  39137. var SemVer = class _SemVer {
  39138. constructor(version, options) {
  39139. options = parseOptions(options);
  39140. if (version instanceof _SemVer) {
  39141. if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
  39142. return version;
  39143. } else {
  39144. version = version.version;
  39145. }
  39146. } else if (typeof version !== "string") {
  39147. throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
  39148. }
  39149. if (version.length > MAX_LENGTH) {
  39150. throw new TypeError(
  39151. `version is longer than ${MAX_LENGTH} characters`
  39152. );
  39153. }
  39154. debug("SemVer", version, options);
  39155. this.options = options;
  39156. this.loose = !!options.loose;
  39157. this.includePrerelease = !!options.includePrerelease;
  39158. const m6 = version.trim().match(options.loose ? re[t6.LOOSE] : re[t6.FULL]);
  39159. if (!m6) {
  39160. throw new TypeError(`Invalid Version: ${version}`);
  39161. }
  39162. this.raw = version;
  39163. this.major = +m6[1];
  39164. this.minor = +m6[2];
  39165. this.patch = +m6[3];
  39166. if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
  39167. throw new TypeError("Invalid major version");
  39168. }
  39169. if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
  39170. throw new TypeError("Invalid minor version");
  39171. }
  39172. if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
  39173. throw new TypeError("Invalid patch version");
  39174. }
  39175. if (!m6[4]) {
  39176. this.prerelease = [];
  39177. } else {
  39178. this.prerelease = m6[4].split(".").map((id) => {
  39179. if (/^[0-9]+$/.test(id)) {
  39180. const num = +id;
  39181. if (num >= 0 && num < MAX_SAFE_INTEGER) {
  39182. return num;
  39183. }
  39184. }
  39185. return id;
  39186. });
  39187. }
  39188. this.build = m6[5] ? m6[5].split(".") : [];
  39189. this.format();
  39190. }
  39191. format() {
  39192. this.version = `${this.major}.${this.minor}.${this.patch}`;
  39193. if (this.prerelease.length) {
  39194. this.version += `-${this.prerelease.join(".")}`;
  39195. }
  39196. return this.version;
  39197. }
  39198. toString() {
  39199. return this.version;
  39200. }
  39201. compare(other) {
  39202. debug("SemVer.compare", this.version, this.options, other);
  39203. if (!(other instanceof _SemVer)) {
  39204. if (typeof other === "string" && other === this.version) {
  39205. return 0;
  39206. }
  39207. other = new _SemVer(other, this.options);
  39208. }
  39209. if (other.version === this.version) {
  39210. return 0;
  39211. }
  39212. return this.compareMain(other) || this.comparePre(other);
  39213. }
  39214. compareMain(other) {
  39215. if (!(other instanceof _SemVer)) {
  39216. other = new _SemVer(other, this.options);
  39217. }
  39218. return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
  39219. }
  39220. comparePre(other) {
  39221. if (!(other instanceof _SemVer)) {
  39222. other = new _SemVer(other, this.options);
  39223. }
  39224. if (this.prerelease.length && !other.prerelease.length) {
  39225. return -1;
  39226. } else if (!this.prerelease.length && other.prerelease.length) {
  39227. return 1;
  39228. } else if (!this.prerelease.length && !other.prerelease.length) {
  39229. return 0;
  39230. }
  39231. let i6 = 0;
  39232. do {
  39233. const a5 = this.prerelease[i6];
  39234. const b5 = other.prerelease[i6];
  39235. debug("prerelease compare", i6, a5, b5);
  39236. if (a5 === void 0 && b5 === void 0) {
  39237. return 0;
  39238. } else if (b5 === void 0) {
  39239. return 1;
  39240. } else if (a5 === void 0) {
  39241. return -1;
  39242. } else if (a5 === b5) {
  39243. continue;
  39244. } else {
  39245. return compareIdentifiers(a5, b5);
  39246. }
  39247. } while (++i6);
  39248. }
  39249. compareBuild(other) {
  39250. if (!(other instanceof _SemVer)) {
  39251. other = new _SemVer(other, this.options);
  39252. }
  39253. let i6 = 0;
  39254. do {
  39255. const a5 = this.build[i6];
  39256. const b5 = other.build[i6];
  39257. debug("build compare", i6, a5, b5);
  39258. if (a5 === void 0 && b5 === void 0) {
  39259. return 0;
  39260. } else if (b5 === void 0) {
  39261. return 1;
  39262. } else if (a5 === void 0) {
  39263. return -1;
  39264. } else if (a5 === b5) {
  39265. continue;
  39266. } else {
  39267. return compareIdentifiers(a5, b5);
  39268. }
  39269. } while (++i6);
  39270. }
  39271. // preminor will bump the version up to the next minor release, and immediately
  39272. // down to pre-release. premajor and prepatch work the same way.
  39273. inc(release2, identifier, identifierBase) {
  39274. if (release2.startsWith("pre")) {
  39275. if (!identifier && identifierBase === false) {
  39276. throw new Error("invalid increment argument: identifier is empty");
  39277. }
  39278. if (identifier) {
  39279. const match2 = `-${identifier}`.match(this.options.loose ? re[t6.PRERELEASELOOSE] : re[t6.PRERELEASE]);
  39280. if (!match2 || match2[1] !== identifier) {
  39281. throw new Error(`invalid identifier: ${identifier}`);
  39282. }
  39283. }
  39284. }
  39285. switch (release2) {
  39286. case "premajor":
  39287. this.prerelease.length = 0;
  39288. this.patch = 0;
  39289. this.minor = 0;
  39290. this.major++;
  39291. this.inc("pre", identifier, identifierBase);
  39292. break;
  39293. case "preminor":
  39294. this.prerelease.length = 0;
  39295. this.patch = 0;
  39296. this.minor++;
  39297. this.inc("pre", identifier, identifierBase);
  39298. break;
  39299. case "prepatch":
  39300. this.prerelease.length = 0;
  39301. this.inc("patch", identifier, identifierBase);
  39302. this.inc("pre", identifier, identifierBase);
  39303. break;
  39304. // If the input is a non-prerelease version, this acts the same as
  39305. // prepatch.
  39306. case "prerelease":
  39307. if (this.prerelease.length === 0) {
  39308. this.inc("patch", identifier, identifierBase);
  39309. }
  39310. this.inc("pre", identifier, identifierBase);
  39311. break;
  39312. case "release":
  39313. if (this.prerelease.length === 0) {
  39314. throw new Error(`version ${this.raw} is not a prerelease`);
  39315. }
  39316. this.prerelease.length = 0;
  39317. break;
  39318. case "major":
  39319. if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
  39320. this.major++;
  39321. }
  39322. this.minor = 0;
  39323. this.patch = 0;
  39324. this.prerelease = [];
  39325. break;
  39326. case "minor":
  39327. if (this.patch !== 0 || this.prerelease.length === 0) {
  39328. this.minor++;
  39329. }
  39330. this.patch = 0;
  39331. this.prerelease = [];
  39332. break;
  39333. case "patch":
  39334. if (this.prerelease.length === 0) {
  39335. this.patch++;
  39336. }
  39337. this.prerelease = [];
  39338. break;
  39339. // This probably shouldn't be used publicly.
  39340. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
  39341. case "pre": {
  39342. const base = Number(identifierBase) ? 1 : 0;
  39343. if (this.prerelease.length === 0) {
  39344. this.prerelease = [base];
  39345. } else {
  39346. let i6 = this.prerelease.length;
  39347. while (--i6 >= 0) {
  39348. if (typeof this.prerelease[i6] === "number") {
  39349. this.prerelease[i6]++;
  39350. i6 = -2;
  39351. }
  39352. }
  39353. if (i6 === -1) {
  39354. if (identifier === this.prerelease.join(".") && identifierBase === false) {
  39355. throw new Error("invalid increment argument: identifier already exists");
  39356. }
  39357. this.prerelease.push(base);
  39358. }
  39359. }
  39360. if (identifier) {
  39361. let prerelease = [identifier, base];
  39362. if (identifierBase === false) {
  39363. prerelease = [identifier];
  39364. }
  39365. if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
  39366. if (isNaN(this.prerelease[1])) {
  39367. this.prerelease = prerelease;
  39368. }
  39369. } else {
  39370. this.prerelease = prerelease;
  39371. }
  39372. }
  39373. break;
  39374. }
  39375. default:
  39376. throw new Error(`invalid increment argument: ${release2}`);
  39377. }
  39378. this.raw = this.format();
  39379. if (this.build.length) {
  39380. this.raw += `+${this.build.join(".")}`;
  39381. }
  39382. return this;
  39383. }
  39384. };
  39385. module.exports = SemVer;
  39386. }
  39387. });
  39388. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js
  39389. var require_parse = __commonJS({
  39390. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js"(exports, module) {
  39391. "use strict";
  39392. var SemVer = require_semver();
  39393. var parse4 = (version, options, throwErrors = false) => {
  39394. if (version instanceof SemVer) {
  39395. return version;
  39396. }
  39397. try {
  39398. return new SemVer(version, options);
  39399. } catch (er) {
  39400. if (!throwErrors) {
  39401. return null;
  39402. }
  39403. throw er;
  39404. }
  39405. };
  39406. module.exports = parse4;
  39407. }
  39408. });
  39409. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js
  39410. var require_valid = __commonJS({
  39411. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js"(exports, module) {
  39412. "use strict";
  39413. var parse4 = require_parse();
  39414. var valid = (version, options) => {
  39415. const v6 = parse4(version, options);
  39416. return v6 ? v6.version : null;
  39417. };
  39418. module.exports = valid;
  39419. }
  39420. });
  39421. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js
  39422. var require_clean = __commonJS({
  39423. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js"(exports, module) {
  39424. "use strict";
  39425. var parse4 = require_parse();
  39426. var clean = (version, options) => {
  39427. const s6 = parse4(version.trim().replace(/^[=v]+/, ""), options);
  39428. return s6 ? s6.version : null;
  39429. };
  39430. module.exports = clean;
  39431. }
  39432. });
  39433. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js
  39434. var require_inc = __commonJS({
  39435. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js"(exports, module) {
  39436. "use strict";
  39437. var SemVer = require_semver();
  39438. var inc = (version, release2, options, identifier, identifierBase) => {
  39439. if (typeof options === "string") {
  39440. identifierBase = identifier;
  39441. identifier = options;
  39442. options = void 0;
  39443. }
  39444. try {
  39445. return new SemVer(
  39446. version instanceof SemVer ? version.version : version,
  39447. options
  39448. ).inc(release2, identifier, identifierBase).version;
  39449. } catch (er) {
  39450. return null;
  39451. }
  39452. };
  39453. module.exports = inc;
  39454. }
  39455. });
  39456. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js
  39457. var require_diff = __commonJS({
  39458. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js"(exports, module) {
  39459. "use strict";
  39460. var parse4 = require_parse();
  39461. var diff2 = (version1, version2) => {
  39462. const v1 = parse4(version1, null, true);
  39463. const v22 = parse4(version2, null, true);
  39464. const comparison = v1.compare(v22);
  39465. if (comparison === 0) {
  39466. return null;
  39467. }
  39468. const v1Higher = comparison > 0;
  39469. const highVersion = v1Higher ? v1 : v22;
  39470. const lowVersion = v1Higher ? v22 : v1;
  39471. const highHasPre = !!highVersion.prerelease.length;
  39472. const lowHasPre = !!lowVersion.prerelease.length;
  39473. if (lowHasPre && !highHasPre) {
  39474. if (!lowVersion.patch && !lowVersion.minor) {
  39475. return "major";
  39476. }
  39477. if (lowVersion.compareMain(highVersion) === 0) {
  39478. if (lowVersion.minor && !lowVersion.patch) {
  39479. return "minor";
  39480. }
  39481. return "patch";
  39482. }
  39483. }
  39484. const prefix2 = highHasPre ? "pre" : "";
  39485. if (v1.major !== v22.major) {
  39486. return prefix2 + "major";
  39487. }
  39488. if (v1.minor !== v22.minor) {
  39489. return prefix2 + "minor";
  39490. }
  39491. if (v1.patch !== v22.patch) {
  39492. return prefix2 + "patch";
  39493. }
  39494. return "prerelease";
  39495. };
  39496. module.exports = diff2;
  39497. }
  39498. });
  39499. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js
  39500. var require_major = __commonJS({
  39501. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js"(exports, module) {
  39502. "use strict";
  39503. var SemVer = require_semver();
  39504. var major = (a5, loose) => new SemVer(a5, loose).major;
  39505. module.exports = major;
  39506. }
  39507. });
  39508. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js
  39509. var require_minor = __commonJS({
  39510. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js"(exports, module) {
  39511. "use strict";
  39512. var SemVer = require_semver();
  39513. var minor = (a5, loose) => new SemVer(a5, loose).minor;
  39514. module.exports = minor;
  39515. }
  39516. });
  39517. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js
  39518. var require_patch = __commonJS({
  39519. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js"(exports, module) {
  39520. "use strict";
  39521. var SemVer = require_semver();
  39522. var patch = (a5, loose) => new SemVer(a5, loose).patch;
  39523. module.exports = patch;
  39524. }
  39525. });
  39526. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js
  39527. var require_prerelease = __commonJS({
  39528. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js"(exports, module) {
  39529. "use strict";
  39530. var parse4 = require_parse();
  39531. var prerelease = (version, options) => {
  39532. const parsed = parse4(version, options);
  39533. return parsed && parsed.prerelease.length ? parsed.prerelease : null;
  39534. };
  39535. module.exports = prerelease;
  39536. }
  39537. });
  39538. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js
  39539. var require_compare = __commonJS({
  39540. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js"(exports, module) {
  39541. "use strict";
  39542. var SemVer = require_semver();
  39543. var compare = (a5, b5, loose) => new SemVer(a5, loose).compare(new SemVer(b5, loose));
  39544. module.exports = compare;
  39545. }
  39546. });
  39547. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js
  39548. var require_rcompare = __commonJS({
  39549. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js"(exports, module) {
  39550. "use strict";
  39551. var compare = require_compare();
  39552. var rcompare = (a5, b5, loose) => compare(b5, a5, loose);
  39553. module.exports = rcompare;
  39554. }
  39555. });
  39556. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js
  39557. var require_compare_loose = __commonJS({
  39558. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js"(exports, module) {
  39559. "use strict";
  39560. var compare = require_compare();
  39561. var compareLoose = (a5, b5) => compare(a5, b5, true);
  39562. module.exports = compareLoose;
  39563. }
  39564. });
  39565. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js
  39566. var require_compare_build = __commonJS({
  39567. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js"(exports, module) {
  39568. "use strict";
  39569. var SemVer = require_semver();
  39570. var compareBuild = (a5, b5, loose) => {
  39571. const versionA = new SemVer(a5, loose);
  39572. const versionB = new SemVer(b5, loose);
  39573. return versionA.compare(versionB) || versionA.compareBuild(versionB);
  39574. };
  39575. module.exports = compareBuild;
  39576. }
  39577. });
  39578. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js
  39579. var require_sort = __commonJS({
  39580. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js"(exports, module) {
  39581. "use strict";
  39582. var compareBuild = require_compare_build();
  39583. var sort = (list, loose) => list.sort((a5, b5) => compareBuild(a5, b5, loose));
  39584. module.exports = sort;
  39585. }
  39586. });
  39587. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js
  39588. var require_rsort = __commonJS({
  39589. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js"(exports, module) {
  39590. "use strict";
  39591. var compareBuild = require_compare_build();
  39592. var rsort = (list, loose) => list.sort((a5, b5) => compareBuild(b5, a5, loose));
  39593. module.exports = rsort;
  39594. }
  39595. });
  39596. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js
  39597. var require_gt = __commonJS({
  39598. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js"(exports, module) {
  39599. "use strict";
  39600. var compare = require_compare();
  39601. var gt = (a5, b5, loose) => compare(a5, b5, loose) > 0;
  39602. module.exports = gt;
  39603. }
  39604. });
  39605. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js
  39606. var require_lt = __commonJS({
  39607. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js"(exports, module) {
  39608. "use strict";
  39609. var compare = require_compare();
  39610. var lt = (a5, b5, loose) => compare(a5, b5, loose) < 0;
  39611. module.exports = lt;
  39612. }
  39613. });
  39614. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js
  39615. var require_eq = __commonJS({
  39616. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js"(exports, module) {
  39617. "use strict";
  39618. var compare = require_compare();
  39619. var eq = (a5, b5, loose) => compare(a5, b5, loose) === 0;
  39620. module.exports = eq;
  39621. }
  39622. });
  39623. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js
  39624. var require_neq = __commonJS({
  39625. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js"(exports, module) {
  39626. "use strict";
  39627. var compare = require_compare();
  39628. var neq = (a5, b5, loose) => compare(a5, b5, loose) !== 0;
  39629. module.exports = neq;
  39630. }
  39631. });
  39632. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js
  39633. var require_gte = __commonJS({
  39634. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js"(exports, module) {
  39635. "use strict";
  39636. var compare = require_compare();
  39637. var gte = (a5, b5, loose) => compare(a5, b5, loose) >= 0;
  39638. module.exports = gte;
  39639. }
  39640. });
  39641. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js
  39642. var require_lte = __commonJS({
  39643. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js"(exports, module) {
  39644. "use strict";
  39645. var compare = require_compare();
  39646. var lte = (a5, b5, loose) => compare(a5, b5, loose) <= 0;
  39647. module.exports = lte;
  39648. }
  39649. });
  39650. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js
  39651. var require_cmp = __commonJS({
  39652. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js"(exports, module) {
  39653. "use strict";
  39654. var eq = require_eq();
  39655. var neq = require_neq();
  39656. var gt = require_gt();
  39657. var gte = require_gte();
  39658. var lt = require_lt();
  39659. var lte = require_lte();
  39660. var cmp = (a5, op, b5, loose) => {
  39661. switch (op) {
  39662. case "===":
  39663. if (typeof a5 === "object") {
  39664. a5 = a5.version;
  39665. }
  39666. if (typeof b5 === "object") {
  39667. b5 = b5.version;
  39668. }
  39669. return a5 === b5;
  39670. case "!==":
  39671. if (typeof a5 === "object") {
  39672. a5 = a5.version;
  39673. }
  39674. if (typeof b5 === "object") {
  39675. b5 = b5.version;
  39676. }
  39677. return a5 !== b5;
  39678. case "":
  39679. case "=":
  39680. case "==":
  39681. return eq(a5, b5, loose);
  39682. case "!=":
  39683. return neq(a5, b5, loose);
  39684. case ">":
  39685. return gt(a5, b5, loose);
  39686. case ">=":
  39687. return gte(a5, b5, loose);
  39688. case "<":
  39689. return lt(a5, b5, loose);
  39690. case "<=":
  39691. return lte(a5, b5, loose);
  39692. default:
  39693. throw new TypeError(`Invalid operator: ${op}`);
  39694. }
  39695. };
  39696. module.exports = cmp;
  39697. }
  39698. });
  39699. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js
  39700. var require_coerce = __commonJS({
  39701. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js"(exports, module) {
  39702. "use strict";
  39703. var SemVer = require_semver();
  39704. var parse4 = require_parse();
  39705. var { safeRe: re, t: t6 } = require_re();
  39706. var coerce2 = (version, options) => {
  39707. if (version instanceof SemVer) {
  39708. return version;
  39709. }
  39710. if (typeof version === "number") {
  39711. version = String(version);
  39712. }
  39713. if (typeof version !== "string") {
  39714. return null;
  39715. }
  39716. options = options || {};
  39717. let match2 = null;
  39718. if (!options.rtl) {
  39719. match2 = version.match(options.includePrerelease ? re[t6.COERCEFULL] : re[t6.COERCE]);
  39720. } else {
  39721. const coerceRtlRegex = options.includePrerelease ? re[t6.COERCERTLFULL] : re[t6.COERCERTL];
  39722. let next;
  39723. while ((next = coerceRtlRegex.exec(version)) && (!match2 || match2.index + match2[0].length !== version.length)) {
  39724. if (!match2 || next.index + next[0].length !== match2.index + match2[0].length) {
  39725. match2 = next;
  39726. }
  39727. coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
  39728. }
  39729. coerceRtlRegex.lastIndex = -1;
  39730. }
  39731. if (match2 === null) {
  39732. return null;
  39733. }
  39734. const major = match2[2];
  39735. const minor = match2[3] || "0";
  39736. const patch = match2[4] || "0";
  39737. const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : "";
  39738. const build = options.includePrerelease && match2[6] ? `+${match2[6]}` : "";
  39739. return parse4(`${major}.${minor}.${patch}${prerelease}${build}`, options);
  39740. };
  39741. module.exports = coerce2;
  39742. }
  39743. });
  39744. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js
  39745. var require_lrucache = __commonJS({
  39746. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js"(exports, module) {
  39747. "use strict";
  39748. var LRUCache = class {
  39749. constructor() {
  39750. this.max = 1e3;
  39751. this.map = /* @__PURE__ */ new Map();
  39752. }
  39753. get(key) {
  39754. const value = this.map.get(key);
  39755. if (value === void 0) {
  39756. return void 0;
  39757. } else {
  39758. this.map.delete(key);
  39759. this.map.set(key, value);
  39760. return value;
  39761. }
  39762. }
  39763. delete(key) {
  39764. return this.map.delete(key);
  39765. }
  39766. set(key, value) {
  39767. const deleted = this.delete(key);
  39768. if (!deleted && value !== void 0) {
  39769. if (this.map.size >= this.max) {
  39770. const firstKey = this.map.keys().next().value;
  39771. this.delete(firstKey);
  39772. }
  39773. this.map.set(key, value);
  39774. }
  39775. return this;
  39776. }
  39777. };
  39778. module.exports = LRUCache;
  39779. }
  39780. });
  39781. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js
  39782. var require_range = __commonJS({
  39783. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js"(exports, module) {
  39784. "use strict";
  39785. var SPACE_CHARACTERS = /\s+/g;
  39786. var Range = class _Range {
  39787. constructor(range, options) {
  39788. options = parseOptions(options);
  39789. if (range instanceof _Range) {
  39790. if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
  39791. return range;
  39792. } else {
  39793. return new _Range(range.raw, options);
  39794. }
  39795. }
  39796. if (range instanceof Comparator) {
  39797. this.raw = range.value;
  39798. this.set = [[range]];
  39799. this.formatted = void 0;
  39800. return this;
  39801. }
  39802. this.options = options;
  39803. this.loose = !!options.loose;
  39804. this.includePrerelease = !!options.includePrerelease;
  39805. this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
  39806. this.set = this.raw.split("||").map((r6) => this.parseRange(r6.trim())).filter((c5) => c5.length);
  39807. if (!this.set.length) {
  39808. throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
  39809. }
  39810. if (this.set.length > 1) {
  39811. const first = this.set[0];
  39812. this.set = this.set.filter((c5) => !isNullSet(c5[0]));
  39813. if (this.set.length === 0) {
  39814. this.set = [first];
  39815. } else if (this.set.length > 1) {
  39816. for (const c5 of this.set) {
  39817. if (c5.length === 1 && isAny(c5[0])) {
  39818. this.set = [c5];
  39819. break;
  39820. }
  39821. }
  39822. }
  39823. }
  39824. this.formatted = void 0;
  39825. }
  39826. get range() {
  39827. if (this.formatted === void 0) {
  39828. this.formatted = "";
  39829. for (let i6 = 0; i6 < this.set.length; i6++) {
  39830. if (i6 > 0) {
  39831. this.formatted += "||";
  39832. }
  39833. const comps = this.set[i6];
  39834. for (let k5 = 0; k5 < comps.length; k5++) {
  39835. if (k5 > 0) {
  39836. this.formatted += " ";
  39837. }
  39838. this.formatted += comps[k5].toString().trim();
  39839. }
  39840. }
  39841. }
  39842. return this.formatted;
  39843. }
  39844. format() {
  39845. return this.range;
  39846. }
  39847. toString() {
  39848. return this.range;
  39849. }
  39850. parseRange(range) {
  39851. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
  39852. const memoKey = memoOpts + ":" + range;
  39853. const cached = cache5.get(memoKey);
  39854. if (cached) {
  39855. return cached;
  39856. }
  39857. const loose = this.options.loose;
  39858. const hr = loose ? re[t6.HYPHENRANGELOOSE] : re[t6.HYPHENRANGE];
  39859. range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
  39860. debug("hyphen replace", range);
  39861. range = range.replace(re[t6.COMPARATORTRIM], comparatorTrimReplace);
  39862. debug("comparator trim", range);
  39863. range = range.replace(re[t6.TILDETRIM], tildeTrimReplace);
  39864. debug("tilde trim", range);
  39865. range = range.replace(re[t6.CARETTRIM], caretTrimReplace);
  39866. debug("caret trim", range);
  39867. let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
  39868. if (loose) {
  39869. rangeList = rangeList.filter((comp) => {
  39870. debug("loose invalid filter", comp, this.options);
  39871. return !!comp.match(re[t6.COMPARATORLOOSE]);
  39872. });
  39873. }
  39874. debug("range list", rangeList);
  39875. const rangeMap = /* @__PURE__ */ new Map();
  39876. const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
  39877. for (const comp of comparators) {
  39878. if (isNullSet(comp)) {
  39879. return [comp];
  39880. }
  39881. rangeMap.set(comp.value, comp);
  39882. }
  39883. if (rangeMap.size > 1 && rangeMap.has("")) {
  39884. rangeMap.delete("");
  39885. }
  39886. const result = [...rangeMap.values()];
  39887. cache5.set(memoKey, result);
  39888. return result;
  39889. }
  39890. intersects(range, options) {
  39891. if (!(range instanceof _Range)) {
  39892. throw new TypeError("a Range is required");
  39893. }
  39894. return this.set.some((thisComparators) => {
  39895. return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
  39896. return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
  39897. return rangeComparators.every((rangeComparator) => {
  39898. return thisComparator.intersects(rangeComparator, options);
  39899. });
  39900. });
  39901. });
  39902. });
  39903. }
  39904. // if ANY of the sets match ALL of its comparators, then pass
  39905. test(version) {
  39906. if (!version) {
  39907. return false;
  39908. }
  39909. if (typeof version === "string") {
  39910. try {
  39911. version = new SemVer(version, this.options);
  39912. } catch (er) {
  39913. return false;
  39914. }
  39915. }
  39916. for (let i6 = 0; i6 < this.set.length; i6++) {
  39917. if (testSet(this.set[i6], version, this.options)) {
  39918. return true;
  39919. }
  39920. }
  39921. return false;
  39922. }
  39923. };
  39924. module.exports = Range;
  39925. var LRU = require_lrucache();
  39926. var cache5 = new LRU();
  39927. var parseOptions = require_parse_options();
  39928. var Comparator = require_comparator();
  39929. var debug = require_debug();
  39930. var SemVer = require_semver();
  39931. var {
  39932. safeRe: re,
  39933. t: t6,
  39934. comparatorTrimReplace,
  39935. tildeTrimReplace,
  39936. caretTrimReplace
  39937. } = require_re();
  39938. var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants2();
  39939. var isNullSet = (c5) => c5.value === "<0.0.0-0";
  39940. var isAny = (c5) => c5.value === "";
  39941. var isSatisfiable = (comparators, options) => {
  39942. let result = true;
  39943. const remainingComparators = comparators.slice();
  39944. let testComparator = remainingComparators.pop();
  39945. while (result && remainingComparators.length) {
  39946. result = remainingComparators.every((otherComparator) => {
  39947. return testComparator.intersects(otherComparator, options);
  39948. });
  39949. testComparator = remainingComparators.pop();
  39950. }
  39951. return result;
  39952. };
  39953. var parseComparator = (comp, options) => {
  39954. debug("comp", comp, options);
  39955. comp = replaceCarets(comp, options);
  39956. debug("caret", comp);
  39957. comp = replaceTildes(comp, options);
  39958. debug("tildes", comp);
  39959. comp = replaceXRanges(comp, options);
  39960. debug("xrange", comp);
  39961. comp = replaceStars(comp, options);
  39962. debug("stars", comp);
  39963. return comp;
  39964. };
  39965. var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
  39966. var replaceTildes = (comp, options) => {
  39967. return comp.trim().split(/\s+/).map((c5) => replaceTilde(c5, options)).join(" ");
  39968. };
  39969. var replaceTilde = (comp, options) => {
  39970. const r6 = options.loose ? re[t6.TILDELOOSE] : re[t6.TILDE];
  39971. return comp.replace(r6, (_3, M, m6, p5, pr) => {
  39972. debug("tilde", comp, _3, M, m6, p5, pr);
  39973. let ret;
  39974. if (isX(M)) {
  39975. ret = "";
  39976. } else if (isX(m6)) {
  39977. ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
  39978. } else if (isX(p5)) {
  39979. ret = `>=${M}.${m6}.0 <${M}.${+m6 + 1}.0-0`;
  39980. } else if (pr) {
  39981. debug("replaceTilde pr", pr);
  39982. ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${+m6 + 1}.0-0`;
  39983. } else {
  39984. ret = `>=${M}.${m6}.${p5} <${M}.${+m6 + 1}.0-0`;
  39985. }
  39986. debug("tilde return", ret);
  39987. return ret;
  39988. });
  39989. };
  39990. var replaceCarets = (comp, options) => {
  39991. return comp.trim().split(/\s+/).map((c5) => replaceCaret(c5, options)).join(" ");
  39992. };
  39993. var replaceCaret = (comp, options) => {
  39994. debug("caret", comp, options);
  39995. const r6 = options.loose ? re[t6.CARETLOOSE] : re[t6.CARET];
  39996. const z2 = options.includePrerelease ? "-0" : "";
  39997. return comp.replace(r6, (_3, M, m6, p5, pr) => {
  39998. debug("caret", comp, _3, M, m6, p5, pr);
  39999. let ret;
  40000. if (isX(M)) {
  40001. ret = "";
  40002. } else if (isX(m6)) {
  40003. ret = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`;
  40004. } else if (isX(p5)) {
  40005. if (M === "0") {
  40006. ret = `>=${M}.${m6}.0${z2} <${M}.${+m6 + 1}.0-0`;
  40007. } else {
  40008. ret = `>=${M}.${m6}.0${z2} <${+M + 1}.0.0-0`;
  40009. }
  40010. } else if (pr) {
  40011. debug("replaceCaret pr", pr);
  40012. if (M === "0") {
  40013. if (m6 === "0") {
  40014. ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${m6}.${+p5 + 1}-0`;
  40015. } else {
  40016. ret = `>=${M}.${m6}.${p5}-${pr} <${M}.${+m6 + 1}.0-0`;
  40017. }
  40018. } else {
  40019. ret = `>=${M}.${m6}.${p5}-${pr} <${+M + 1}.0.0-0`;
  40020. }
  40021. } else {
  40022. debug("no pr");
  40023. if (M === "0") {
  40024. if (m6 === "0") {
  40025. ret = `>=${M}.${m6}.${p5}${z2} <${M}.${m6}.${+p5 + 1}-0`;
  40026. } else {
  40027. ret = `>=${M}.${m6}.${p5}${z2} <${M}.${+m6 + 1}.0-0`;
  40028. }
  40029. } else {
  40030. ret = `>=${M}.${m6}.${p5} <${+M + 1}.0.0-0`;
  40031. }
  40032. }
  40033. debug("caret return", ret);
  40034. return ret;
  40035. });
  40036. };
  40037. var replaceXRanges = (comp, options) => {
  40038. debug("replaceXRanges", comp, options);
  40039. return comp.split(/\s+/).map((c5) => replaceXRange(c5, options)).join(" ");
  40040. };
  40041. var replaceXRange = (comp, options) => {
  40042. comp = comp.trim();
  40043. const r6 = options.loose ? re[t6.XRANGELOOSE] : re[t6.XRANGE];
  40044. return comp.replace(r6, (ret, gtlt, M, m6, p5, pr) => {
  40045. debug("xRange", comp, ret, gtlt, M, m6, p5, pr);
  40046. const xM = isX(M);
  40047. const xm = xM || isX(m6);
  40048. const xp = xm || isX(p5);
  40049. const anyX = xp;
  40050. if (gtlt === "=" && anyX) {
  40051. gtlt = "";
  40052. }
  40053. pr = options.includePrerelease ? "-0" : "";
  40054. if (xM) {
  40055. if (gtlt === ">" || gtlt === "<") {
  40056. ret = "<0.0.0-0";
  40057. } else {
  40058. ret = "*";
  40059. }
  40060. } else if (gtlt && anyX) {
  40061. if (xm) {
  40062. m6 = 0;
  40063. }
  40064. p5 = 0;
  40065. if (gtlt === ">") {
  40066. gtlt = ">=";
  40067. if (xm) {
  40068. M = +M + 1;
  40069. m6 = 0;
  40070. p5 = 0;
  40071. } else {
  40072. m6 = +m6 + 1;
  40073. p5 = 0;
  40074. }
  40075. } else if (gtlt === "<=") {
  40076. gtlt = "<";
  40077. if (xm) {
  40078. M = +M + 1;
  40079. } else {
  40080. m6 = +m6 + 1;
  40081. }
  40082. }
  40083. if (gtlt === "<") {
  40084. pr = "-0";
  40085. }
  40086. ret = `${gtlt + M}.${m6}.${p5}${pr}`;
  40087. } else if (xm) {
  40088. ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
  40089. } else if (xp) {
  40090. ret = `>=${M}.${m6}.0${pr} <${M}.${+m6 + 1}.0-0`;
  40091. }
  40092. debug("xRange return", ret);
  40093. return ret;
  40094. });
  40095. };
  40096. var replaceStars = (comp, options) => {
  40097. debug("replaceStars", comp, options);
  40098. return comp.trim().replace(re[t6.STAR], "");
  40099. };
  40100. var replaceGTE0 = (comp, options) => {
  40101. debug("replaceGTE0", comp, options);
  40102. return comp.trim().replace(re[options.includePrerelease ? t6.GTE0PRE : t6.GTE0], "");
  40103. };
  40104. var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
  40105. if (isX(fM)) {
  40106. from = "";
  40107. } else if (isX(fm)) {
  40108. from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
  40109. } else if (isX(fp)) {
  40110. from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
  40111. } else if (fpr) {
  40112. from = `>=${from}`;
  40113. } else {
  40114. from = `>=${from}${incPr ? "-0" : ""}`;
  40115. }
  40116. if (isX(tM)) {
  40117. to = "";
  40118. } else if (isX(tm)) {
  40119. to = `<${+tM + 1}.0.0-0`;
  40120. } else if (isX(tp)) {
  40121. to = `<${tM}.${+tm + 1}.0-0`;
  40122. } else if (tpr) {
  40123. to = `<=${tM}.${tm}.${tp}-${tpr}`;
  40124. } else if (incPr) {
  40125. to = `<${tM}.${tm}.${+tp + 1}-0`;
  40126. } else {
  40127. to = `<=${to}`;
  40128. }
  40129. return `${from} ${to}`.trim();
  40130. };
  40131. var testSet = (set, version, options) => {
  40132. for (let i6 = 0; i6 < set.length; i6++) {
  40133. if (!set[i6].test(version)) {
  40134. return false;
  40135. }
  40136. }
  40137. if (version.prerelease.length && !options.includePrerelease) {
  40138. for (let i6 = 0; i6 < set.length; i6++) {
  40139. debug(set[i6].semver);
  40140. if (set[i6].semver === Comparator.ANY) {
  40141. continue;
  40142. }
  40143. if (set[i6].semver.prerelease.length > 0) {
  40144. const allowed = set[i6].semver;
  40145. if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
  40146. return true;
  40147. }
  40148. }
  40149. }
  40150. return false;
  40151. }
  40152. return true;
  40153. };
  40154. }
  40155. });
  40156. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js
  40157. var require_comparator = __commonJS({
  40158. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js"(exports, module) {
  40159. "use strict";
  40160. var ANY = Symbol("SemVer ANY");
  40161. var Comparator = class _Comparator {
  40162. static get ANY() {
  40163. return ANY;
  40164. }
  40165. constructor(comp, options) {
  40166. options = parseOptions(options);
  40167. if (comp instanceof _Comparator) {
  40168. if (comp.loose === !!options.loose) {
  40169. return comp;
  40170. } else {
  40171. comp = comp.value;
  40172. }
  40173. }
  40174. comp = comp.trim().split(/\s+/).join(" ");
  40175. debug("comparator", comp, options);
  40176. this.options = options;
  40177. this.loose = !!options.loose;
  40178. this.parse(comp);
  40179. if (this.semver === ANY) {
  40180. this.value = "";
  40181. } else {
  40182. this.value = this.operator + this.semver.version;
  40183. }
  40184. debug("comp", this);
  40185. }
  40186. parse(comp) {
  40187. const r6 = this.options.loose ? re[t6.COMPARATORLOOSE] : re[t6.COMPARATOR];
  40188. const m6 = comp.match(r6);
  40189. if (!m6) {
  40190. throw new TypeError(`Invalid comparator: ${comp}`);
  40191. }
  40192. this.operator = m6[1] !== void 0 ? m6[1] : "";
  40193. if (this.operator === "=") {
  40194. this.operator = "";
  40195. }
  40196. if (!m6[2]) {
  40197. this.semver = ANY;
  40198. } else {
  40199. this.semver = new SemVer(m6[2], this.options.loose);
  40200. }
  40201. }
  40202. toString() {
  40203. return this.value;
  40204. }
  40205. test(version) {
  40206. debug("Comparator.test", version, this.options.loose);
  40207. if (this.semver === ANY || version === ANY) {
  40208. return true;
  40209. }
  40210. if (typeof version === "string") {
  40211. try {
  40212. version = new SemVer(version, this.options);
  40213. } catch (er) {
  40214. return false;
  40215. }
  40216. }
  40217. return cmp(version, this.operator, this.semver, this.options);
  40218. }
  40219. intersects(comp, options) {
  40220. if (!(comp instanceof _Comparator)) {
  40221. throw new TypeError("a Comparator is required");
  40222. }
  40223. if (this.operator === "") {
  40224. if (this.value === "") {
  40225. return true;
  40226. }
  40227. return new Range(comp.value, options).test(this.value);
  40228. } else if (comp.operator === "") {
  40229. if (comp.value === "") {
  40230. return true;
  40231. }
  40232. return new Range(this.value, options).test(comp.semver);
  40233. }
  40234. options = parseOptions(options);
  40235. if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
  40236. return false;
  40237. }
  40238. if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
  40239. return false;
  40240. }
  40241. if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
  40242. return true;
  40243. }
  40244. if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
  40245. return true;
  40246. }
  40247. if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
  40248. return true;
  40249. }
  40250. if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
  40251. return true;
  40252. }
  40253. if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
  40254. return true;
  40255. }
  40256. return false;
  40257. }
  40258. };
  40259. module.exports = Comparator;
  40260. var parseOptions = require_parse_options();
  40261. var { safeRe: re, t: t6 } = require_re();
  40262. var cmp = require_cmp();
  40263. var debug = require_debug();
  40264. var SemVer = require_semver();
  40265. var Range = require_range();
  40266. }
  40267. });
  40268. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js
  40269. var require_satisfies = __commonJS({
  40270. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js"(exports, module) {
  40271. "use strict";
  40272. var Range = require_range();
  40273. var satisfies = (version, range, options) => {
  40274. try {
  40275. range = new Range(range, options);
  40276. } catch (er) {
  40277. return false;
  40278. }
  40279. return range.test(version);
  40280. };
  40281. module.exports = satisfies;
  40282. }
  40283. });
  40284. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js
  40285. var require_to_comparators = __commonJS({
  40286. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js"(exports, module) {
  40287. "use strict";
  40288. var Range = require_range();
  40289. var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c5) => c5.value).join(" ").trim().split(" "));
  40290. module.exports = toComparators;
  40291. }
  40292. });
  40293. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js
  40294. var require_max_satisfying = __commonJS({
  40295. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js"(exports, module) {
  40296. "use strict";
  40297. var SemVer = require_semver();
  40298. var Range = require_range();
  40299. var maxSatisfying = (versions2, range, options) => {
  40300. let max = null;
  40301. let maxSV = null;
  40302. let rangeObj = null;
  40303. try {
  40304. rangeObj = new Range(range, options);
  40305. } catch (er) {
  40306. return null;
  40307. }
  40308. versions2.forEach((v6) => {
  40309. if (rangeObj.test(v6)) {
  40310. if (!max || maxSV.compare(v6) === -1) {
  40311. max = v6;
  40312. maxSV = new SemVer(max, options);
  40313. }
  40314. }
  40315. });
  40316. return max;
  40317. };
  40318. module.exports = maxSatisfying;
  40319. }
  40320. });
  40321. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js
  40322. var require_min_satisfying = __commonJS({
  40323. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js"(exports, module) {
  40324. "use strict";
  40325. var SemVer = require_semver();
  40326. var Range = require_range();
  40327. var minSatisfying = (versions2, range, options) => {
  40328. let min = null;
  40329. let minSV = null;
  40330. let rangeObj = null;
  40331. try {
  40332. rangeObj = new Range(range, options);
  40333. } catch (er) {
  40334. return null;
  40335. }
  40336. versions2.forEach((v6) => {
  40337. if (rangeObj.test(v6)) {
  40338. if (!min || minSV.compare(v6) === 1) {
  40339. min = v6;
  40340. minSV = new SemVer(min, options);
  40341. }
  40342. }
  40343. });
  40344. return min;
  40345. };
  40346. module.exports = minSatisfying;
  40347. }
  40348. });
  40349. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js
  40350. var require_min_version = __commonJS({
  40351. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js"(exports, module) {
  40352. "use strict";
  40353. var SemVer = require_semver();
  40354. var Range = require_range();
  40355. var gt = require_gt();
  40356. var minVersion = (range, loose) => {
  40357. range = new Range(range, loose);
  40358. let minver = new SemVer("0.0.0");
  40359. if (range.test(minver)) {
  40360. return minver;
  40361. }
  40362. minver = new SemVer("0.0.0-0");
  40363. if (range.test(minver)) {
  40364. return minver;
  40365. }
  40366. minver = null;
  40367. for (let i6 = 0; i6 < range.set.length; ++i6) {
  40368. const comparators = range.set[i6];
  40369. let setMin = null;
  40370. comparators.forEach((comparator) => {
  40371. const compver = new SemVer(comparator.semver.version);
  40372. switch (comparator.operator) {
  40373. case ">":
  40374. if (compver.prerelease.length === 0) {
  40375. compver.patch++;
  40376. } else {
  40377. compver.prerelease.push(0);
  40378. }
  40379. compver.raw = compver.format();
  40380. /* fallthrough */
  40381. case "":
  40382. case ">=":
  40383. if (!setMin || gt(compver, setMin)) {
  40384. setMin = compver;
  40385. }
  40386. break;
  40387. case "<":
  40388. case "<=":
  40389. break;
  40390. /* istanbul ignore next */
  40391. default:
  40392. throw new Error(`Unexpected operation: ${comparator.operator}`);
  40393. }
  40394. });
  40395. if (setMin && (!minver || gt(minver, setMin))) {
  40396. minver = setMin;
  40397. }
  40398. }
  40399. if (minver && range.test(minver)) {
  40400. return minver;
  40401. }
  40402. return null;
  40403. };
  40404. module.exports = minVersion;
  40405. }
  40406. });
  40407. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js
  40408. var require_valid2 = __commonJS({
  40409. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js"(exports, module) {
  40410. "use strict";
  40411. var Range = require_range();
  40412. var validRange = (range, options) => {
  40413. try {
  40414. return new Range(range, options).range || "*";
  40415. } catch (er) {
  40416. return null;
  40417. }
  40418. };
  40419. module.exports = validRange;
  40420. }
  40421. });
  40422. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js
  40423. var require_outside = __commonJS({
  40424. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js"(exports, module) {
  40425. "use strict";
  40426. var SemVer = require_semver();
  40427. var Comparator = require_comparator();
  40428. var { ANY } = Comparator;
  40429. var Range = require_range();
  40430. var satisfies = require_satisfies();
  40431. var gt = require_gt();
  40432. var lt = require_lt();
  40433. var lte = require_lte();
  40434. var gte = require_gte();
  40435. var outside = (version, range, hilo, options) => {
  40436. version = new SemVer(version, options);
  40437. range = new Range(range, options);
  40438. let gtfn, ltefn, ltfn, comp, ecomp;
  40439. switch (hilo) {
  40440. case ">":
  40441. gtfn = gt;
  40442. ltefn = lte;
  40443. ltfn = lt;
  40444. comp = ">";
  40445. ecomp = ">=";
  40446. break;
  40447. case "<":
  40448. gtfn = lt;
  40449. ltefn = gte;
  40450. ltfn = gt;
  40451. comp = "<";
  40452. ecomp = "<=";
  40453. break;
  40454. default:
  40455. throw new TypeError('Must provide a hilo val of "<" or ">"');
  40456. }
  40457. if (satisfies(version, range, options)) {
  40458. return false;
  40459. }
  40460. for (let i6 = 0; i6 < range.set.length; ++i6) {
  40461. const comparators = range.set[i6];
  40462. let high = null;
  40463. let low = null;
  40464. comparators.forEach((comparator) => {
  40465. if (comparator.semver === ANY) {
  40466. comparator = new Comparator(">=0.0.0");
  40467. }
  40468. high = high || comparator;
  40469. low = low || comparator;
  40470. if (gtfn(comparator.semver, high.semver, options)) {
  40471. high = comparator;
  40472. } else if (ltfn(comparator.semver, low.semver, options)) {
  40473. low = comparator;
  40474. }
  40475. });
  40476. if (high.operator === comp || high.operator === ecomp) {
  40477. return false;
  40478. }
  40479. if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
  40480. return false;
  40481. } else if (low.operator === ecomp && ltfn(version, low.semver)) {
  40482. return false;
  40483. }
  40484. }
  40485. return true;
  40486. };
  40487. module.exports = outside;
  40488. }
  40489. });
  40490. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js
  40491. var require_gtr = __commonJS({
  40492. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js"(exports, module) {
  40493. "use strict";
  40494. var outside = require_outside();
  40495. var gtr = (version, range, options) => outside(version, range, ">", options);
  40496. module.exports = gtr;
  40497. }
  40498. });
  40499. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js
  40500. var require_ltr = __commonJS({
  40501. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js"(exports, module) {
  40502. "use strict";
  40503. var outside = require_outside();
  40504. var ltr = (version, range, options) => outside(version, range, "<", options);
  40505. module.exports = ltr;
  40506. }
  40507. });
  40508. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js
  40509. var require_intersects = __commonJS({
  40510. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js"(exports, module) {
  40511. "use strict";
  40512. var Range = require_range();
  40513. var intersects = (r1, r22, options) => {
  40514. r1 = new Range(r1, options);
  40515. r22 = new Range(r22, options);
  40516. return r1.intersects(r22, options);
  40517. };
  40518. module.exports = intersects;
  40519. }
  40520. });
  40521. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js
  40522. var require_simplify = __commonJS({
  40523. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js"(exports, module) {
  40524. "use strict";
  40525. var satisfies = require_satisfies();
  40526. var compare = require_compare();
  40527. module.exports = (versions2, range, options) => {
  40528. const set = [];
  40529. let first = null;
  40530. let prev = null;
  40531. const v6 = versions2.sort((a5, b5) => compare(a5, b5, options));
  40532. for (const version of v6) {
  40533. const included = satisfies(version, range, options);
  40534. if (included) {
  40535. prev = version;
  40536. if (!first) {
  40537. first = version;
  40538. }
  40539. } else {
  40540. if (prev) {
  40541. set.push([first, prev]);
  40542. }
  40543. prev = null;
  40544. first = null;
  40545. }
  40546. }
  40547. if (first) {
  40548. set.push([first, null]);
  40549. }
  40550. const ranges = [];
  40551. for (const [min, max] of set) {
  40552. if (min === max) {
  40553. ranges.push(min);
  40554. } else if (!max && min === v6[0]) {
  40555. ranges.push("*");
  40556. } else if (!max) {
  40557. ranges.push(`>=${min}`);
  40558. } else if (min === v6[0]) {
  40559. ranges.push(`<=${max}`);
  40560. } else {
  40561. ranges.push(`${min} - ${max}`);
  40562. }
  40563. }
  40564. const simplified = ranges.join(" || ");
  40565. const original = typeof range.raw === "string" ? range.raw : String(range);
  40566. return simplified.length < original.length ? simplified : range;
  40567. };
  40568. }
  40569. });
  40570. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js
  40571. var require_subset = __commonJS({
  40572. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js"(exports, module) {
  40573. "use strict";
  40574. var Range = require_range();
  40575. var Comparator = require_comparator();
  40576. var { ANY } = Comparator;
  40577. var satisfies = require_satisfies();
  40578. var compare = require_compare();
  40579. var subset = (sub, dom, options = {}) => {
  40580. if (sub === dom) {
  40581. return true;
  40582. }
  40583. sub = new Range(sub, options);
  40584. dom = new Range(dom, options);
  40585. let sawNonNull = false;
  40586. OUTER: for (const simpleSub of sub.set) {
  40587. for (const simpleDom of dom.set) {
  40588. const isSub = simpleSubset(simpleSub, simpleDom, options);
  40589. sawNonNull = sawNonNull || isSub !== null;
  40590. if (isSub) {
  40591. continue OUTER;
  40592. }
  40593. }
  40594. if (sawNonNull) {
  40595. return false;
  40596. }
  40597. }
  40598. return true;
  40599. };
  40600. var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
  40601. var minimumVersion = [new Comparator(">=0.0.0")];
  40602. var simpleSubset = (sub, dom, options) => {
  40603. if (sub === dom) {
  40604. return true;
  40605. }
  40606. if (sub.length === 1 && sub[0].semver === ANY) {
  40607. if (dom.length === 1 && dom[0].semver === ANY) {
  40608. return true;
  40609. } else if (options.includePrerelease) {
  40610. sub = minimumVersionWithPreRelease;
  40611. } else {
  40612. sub = minimumVersion;
  40613. }
  40614. }
  40615. if (dom.length === 1 && dom[0].semver === ANY) {
  40616. if (options.includePrerelease) {
  40617. return true;
  40618. } else {
  40619. dom = minimumVersion;
  40620. }
  40621. }
  40622. const eqSet = /* @__PURE__ */ new Set();
  40623. let gt, lt;
  40624. for (const c5 of sub) {
  40625. if (c5.operator === ">" || c5.operator === ">=") {
  40626. gt = higherGT(gt, c5, options);
  40627. } else if (c5.operator === "<" || c5.operator === "<=") {
  40628. lt = lowerLT(lt, c5, options);
  40629. } else {
  40630. eqSet.add(c5.semver);
  40631. }
  40632. }
  40633. if (eqSet.size > 1) {
  40634. return null;
  40635. }
  40636. let gtltComp;
  40637. if (gt && lt) {
  40638. gtltComp = compare(gt.semver, lt.semver, options);
  40639. if (gtltComp > 0) {
  40640. return null;
  40641. } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
  40642. return null;
  40643. }
  40644. }
  40645. for (const eq of eqSet) {
  40646. if (gt && !satisfies(eq, String(gt), options)) {
  40647. return null;
  40648. }
  40649. if (lt && !satisfies(eq, String(lt), options)) {
  40650. return null;
  40651. }
  40652. for (const c5 of dom) {
  40653. if (!satisfies(eq, String(c5), options)) {
  40654. return false;
  40655. }
  40656. }
  40657. return true;
  40658. }
  40659. let higher, lower2;
  40660. let hasDomLT, hasDomGT;
  40661. let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
  40662. let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
  40663. if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
  40664. needDomLTPre = false;
  40665. }
  40666. for (const c5 of dom) {
  40667. hasDomGT = hasDomGT || c5.operator === ">" || c5.operator === ">=";
  40668. hasDomLT = hasDomLT || c5.operator === "<" || c5.operator === "<=";
  40669. if (gt) {
  40670. if (needDomGTPre) {
  40671. if (c5.semver.prerelease && c5.semver.prerelease.length && c5.semver.major === needDomGTPre.major && c5.semver.minor === needDomGTPre.minor && c5.semver.patch === needDomGTPre.patch) {
  40672. needDomGTPre = false;
  40673. }
  40674. }
  40675. if (c5.operator === ">" || c5.operator === ">=") {
  40676. higher = higherGT(gt, c5, options);
  40677. if (higher === c5 && higher !== gt) {
  40678. return false;
  40679. }
  40680. } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c5), options)) {
  40681. return false;
  40682. }
  40683. }
  40684. if (lt) {
  40685. if (needDomLTPre) {
  40686. if (c5.semver.prerelease && c5.semver.prerelease.length && c5.semver.major === needDomLTPre.major && c5.semver.minor === needDomLTPre.minor && c5.semver.patch === needDomLTPre.patch) {
  40687. needDomLTPre = false;
  40688. }
  40689. }
  40690. if (c5.operator === "<" || c5.operator === "<=") {
  40691. lower2 = lowerLT(lt, c5, options);
  40692. if (lower2 === c5 && lower2 !== lt) {
  40693. return false;
  40694. }
  40695. } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c5), options)) {
  40696. return false;
  40697. }
  40698. }
  40699. if (!c5.operator && (lt || gt) && gtltComp !== 0) {
  40700. return false;
  40701. }
  40702. }
  40703. if (gt && hasDomLT && !lt && gtltComp !== 0) {
  40704. return false;
  40705. }
  40706. if (lt && hasDomGT && !gt && gtltComp !== 0) {
  40707. return false;
  40708. }
  40709. if (needDomGTPre || needDomLTPre) {
  40710. return false;
  40711. }
  40712. return true;
  40713. };
  40714. var higherGT = (a5, b5, options) => {
  40715. if (!a5) {
  40716. return b5;
  40717. }
  40718. const comp = compare(a5.semver, b5.semver, options);
  40719. return comp > 0 ? a5 : comp < 0 ? b5 : b5.operator === ">" && a5.operator === ">=" ? b5 : a5;
  40720. };
  40721. var lowerLT = (a5, b5, options) => {
  40722. if (!a5) {
  40723. return b5;
  40724. }
  40725. const comp = compare(a5.semver, b5.semver, options);
  40726. return comp < 0 ? a5 : comp > 0 ? b5 : b5.operator === "<" && a5.operator === "<=" ? b5 : a5;
  40727. };
  40728. module.exports = subset;
  40729. }
  40730. });
  40731. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js
  40732. var require_semver2 = __commonJS({
  40733. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js"(exports, module) {
  40734. "use strict";
  40735. var internalRe = require_re();
  40736. var constants = require_constants2();
  40737. var SemVer = require_semver();
  40738. var identifiers = require_identifiers();
  40739. var parse4 = require_parse();
  40740. var valid = require_valid();
  40741. var clean = require_clean();
  40742. var inc = require_inc();
  40743. var diff2 = require_diff();
  40744. var major = require_major();
  40745. var minor = require_minor();
  40746. var patch = require_patch();
  40747. var prerelease = require_prerelease();
  40748. var compare = require_compare();
  40749. var rcompare = require_rcompare();
  40750. var compareLoose = require_compare_loose();
  40751. var compareBuild = require_compare_build();
  40752. var sort = require_sort();
  40753. var rsort = require_rsort();
  40754. var gt = require_gt();
  40755. var lt = require_lt();
  40756. var eq = require_eq();
  40757. var neq = require_neq();
  40758. var gte = require_gte();
  40759. var lte = require_lte();
  40760. var cmp = require_cmp();
  40761. var coerce2 = require_coerce();
  40762. var Comparator = require_comparator();
  40763. var Range = require_range();
  40764. var satisfies = require_satisfies();
  40765. var toComparators = require_to_comparators();
  40766. var maxSatisfying = require_max_satisfying();
  40767. var minSatisfying = require_min_satisfying();
  40768. var minVersion = require_min_version();
  40769. var validRange = require_valid2();
  40770. var outside = require_outside();
  40771. var gtr = require_gtr();
  40772. var ltr = require_ltr();
  40773. var intersects = require_intersects();
  40774. var simplifyRange = require_simplify();
  40775. var subset = require_subset();
  40776. module.exports = {
  40777. parse: parse4,
  40778. valid,
  40779. clean,
  40780. inc,
  40781. diff: diff2,
  40782. major,
  40783. minor,
  40784. patch,
  40785. prerelease,
  40786. compare,
  40787. rcompare,
  40788. compareLoose,
  40789. compareBuild,
  40790. sort,
  40791. rsort,
  40792. gt,
  40793. lt,
  40794. eq,
  40795. neq,
  40796. gte,
  40797. lte,
  40798. cmp,
  40799. coerce: coerce2,
  40800. Comparator,
  40801. Range,
  40802. satisfies,
  40803. toComparators,
  40804. maxSatisfying,
  40805. minSatisfying,
  40806. minVersion,
  40807. validRange,
  40808. outside,
  40809. gtr,
  40810. ltr,
  40811. intersects,
  40812. simplifyRange,
  40813. subset,
  40814. SemVer,
  40815. re: internalRe.re,
  40816. src: internalRe.src,
  40817. tokens: internalRe.t,
  40818. SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
  40819. RELEASE_TYPES: constants.RELEASE_TYPES,
  40820. compareIdentifiers: identifiers.compareIdentifiers,
  40821. rcompareIdentifiers: identifiers.rcompareIdentifiers
  40822. };
  40823. }
  40824. });
  40825. // src/cli/utils.ts
  40826. var import_semver, checkPackage, assertPackages;
  40827. var init_utils4 = __esm({
  40828. "src/cli/utils.ts"() {
  40829. "use strict";
  40830. import_semver = __toESM(require_semver2());
  40831. init_views();
  40832. checkPackage = async (it) => {
  40833. try {
  40834. await import(it);
  40835. return true;
  40836. } catch (e6) {
  40837. return false;
  40838. }
  40839. };
  40840. assertPackages = async (...pkgs) => {
  40841. try {
  40842. for (let i6 = 0; i6 < pkgs.length; i6++) {
  40843. const it = pkgs[i6];
  40844. await import(it);
  40845. }
  40846. } catch (e6) {
  40847. err(
  40848. `please install required packages: ${pkgs.map((it) => `'${it}'`).join(" ")}`
  40849. );
  40850. process.exit(1);
  40851. }
  40852. };
  40853. }
  40854. });
  40855. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
  40856. var getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig;
  40857. var init_httpExtensionConfiguration = __esm({
  40858. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  40859. "use strict";
  40860. getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
  40861. return {
  40862. setHttpHandler(handler) {
  40863. runtimeConfig.httpHandler = handler;
  40864. },
  40865. httpHandler() {
  40866. return runtimeConfig.httpHandler;
  40867. },
  40868. updateHttpClientConfig(key, value) {
  40869. runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
  40870. },
  40871. httpHandlerConfigs() {
  40872. return runtimeConfig.httpHandler.httpHandlerConfigs();
  40873. }
  40874. };
  40875. };
  40876. resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
  40877. return {
  40878. httpHandler: httpHandlerExtensionConfiguration.httpHandler()
  40879. };
  40880. };
  40881. }
  40882. });
  40883. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
  40884. var init_extensions = __esm({
  40885. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
  40886. "use strict";
  40887. init_httpExtensionConfiguration();
  40888. }
  40889. });
  40890. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/abort.js
  40891. var init_abort = __esm({
  40892. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/abort.js"() {
  40893. "use strict";
  40894. }
  40895. });
  40896. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/auth.js
  40897. var HttpAuthLocation;
  40898. var init_auth = __esm({
  40899. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/auth.js"() {
  40900. "use strict";
  40901. (function(HttpAuthLocation2) {
  40902. HttpAuthLocation2["HEADER"] = "header";
  40903. HttpAuthLocation2["QUERY"] = "query";
  40904. })(HttpAuthLocation || (HttpAuthLocation = {}));
  40905. }
  40906. });
  40907. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
  40908. var HttpApiKeyAuthLocation;
  40909. var init_HttpApiKeyAuth = __esm({
  40910. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js"() {
  40911. "use strict";
  40912. (function(HttpApiKeyAuthLocation2) {
  40913. HttpApiKeyAuthLocation2["HEADER"] = "header";
  40914. HttpApiKeyAuthLocation2["QUERY"] = "query";
  40915. })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
  40916. }
  40917. });
  40918. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
  40919. var init_HttpAuthScheme = __esm({
  40920. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js"() {
  40921. "use strict";
  40922. }
  40923. });
  40924. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
  40925. var init_HttpAuthSchemeProvider = __esm({
  40926. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js"() {
  40927. "use strict";
  40928. }
  40929. });
  40930. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpSigner.js
  40931. var init_HttpSigner = __esm({
  40932. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/HttpSigner.js"() {
  40933. "use strict";
  40934. }
  40935. });
  40936. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
  40937. var init_IdentityProviderConfig = __esm({
  40938. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js"() {
  40939. "use strict";
  40940. }
  40941. });
  40942. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/index.js
  40943. var init_auth2 = __esm({
  40944. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/auth/index.js"() {
  40945. "use strict";
  40946. init_auth();
  40947. init_HttpApiKeyAuth();
  40948. init_HttpAuthScheme();
  40949. init_HttpAuthSchemeProvider();
  40950. init_HttpSigner();
  40951. init_IdentityProviderConfig();
  40952. }
  40953. });
  40954. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
  40955. var init_blob_payload_input_types = __esm({
  40956. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js"() {
  40957. "use strict";
  40958. }
  40959. });
  40960. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/checksum.js
  40961. var init_checksum = __esm({
  40962. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/checksum.js"() {
  40963. "use strict";
  40964. }
  40965. });
  40966. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/client.js
  40967. var init_client = __esm({
  40968. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/client.js"() {
  40969. "use strict";
  40970. }
  40971. });
  40972. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/command.js
  40973. var init_command = __esm({
  40974. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/command.js"() {
  40975. "use strict";
  40976. }
  40977. });
  40978. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/config.js
  40979. var init_config = __esm({
  40980. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/config.js"() {
  40981. "use strict";
  40982. }
  40983. });
  40984. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/manager.js
  40985. var init_manager = __esm({
  40986. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/manager.js"() {
  40987. "use strict";
  40988. }
  40989. });
  40990. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/pool.js
  40991. var init_pool = __esm({
  40992. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/pool.js"() {
  40993. "use strict";
  40994. }
  40995. });
  40996. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/index.js
  40997. var init_connection = __esm({
  40998. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/connection/index.js"() {
  40999. "use strict";
  41000. init_config();
  41001. init_manager();
  41002. init_pool();
  41003. }
  41004. });
  41005. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/crypto.js
  41006. var init_crypto2 = __esm({
  41007. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/crypto.js"() {
  41008. "use strict";
  41009. }
  41010. });
  41011. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/encode.js
  41012. var init_encode = __esm({
  41013. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/encode.js"() {
  41014. "use strict";
  41015. }
  41016. });
  41017. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoint.js
  41018. var EndpointURLScheme;
  41019. var init_endpoint = __esm({
  41020. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoint.js"() {
  41021. "use strict";
  41022. (function(EndpointURLScheme2) {
  41023. EndpointURLScheme2["HTTP"] = "http";
  41024. EndpointURLScheme2["HTTPS"] = "https";
  41025. })(EndpointURLScheme || (EndpointURLScheme = {}));
  41026. }
  41027. });
  41028. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
  41029. var init_EndpointRuleObject = __esm({
  41030. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js"() {
  41031. "use strict";
  41032. }
  41033. });
  41034. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
  41035. var init_ErrorRuleObject = __esm({
  41036. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js"() {
  41037. "use strict";
  41038. }
  41039. });
  41040. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
  41041. var init_RuleSetObject = __esm({
  41042. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js"() {
  41043. "use strict";
  41044. }
  41045. });
  41046. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/shared.js
  41047. var init_shared = __esm({
  41048. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/shared.js"() {
  41049. "use strict";
  41050. }
  41051. });
  41052. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
  41053. var init_TreeRuleObject = __esm({
  41054. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js"() {
  41055. "use strict";
  41056. }
  41057. });
  41058. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/index.js
  41059. var init_endpoints = __esm({
  41060. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/endpoints/index.js"() {
  41061. "use strict";
  41062. init_EndpointRuleObject();
  41063. init_ErrorRuleObject();
  41064. init_RuleSetObject();
  41065. init_shared();
  41066. init_TreeRuleObject();
  41067. }
  41068. });
  41069. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/eventStream.js
  41070. var init_eventStream = __esm({
  41071. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/eventStream.js"() {
  41072. "use strict";
  41073. }
  41074. });
  41075. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/checksum.js
  41076. var AlgorithmId;
  41077. var init_checksum2 = __esm({
  41078. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/checksum.js"() {
  41079. "use strict";
  41080. (function(AlgorithmId2) {
  41081. AlgorithmId2["MD5"] = "md5";
  41082. AlgorithmId2["CRC32"] = "crc32";
  41083. AlgorithmId2["CRC32C"] = "crc32c";
  41084. AlgorithmId2["SHA1"] = "sha1";
  41085. AlgorithmId2["SHA256"] = "sha256";
  41086. })(AlgorithmId || (AlgorithmId = {}));
  41087. }
  41088. });
  41089. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
  41090. var init_defaultClientConfiguration = __esm({
  41091. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js"() {
  41092. "use strict";
  41093. init_checksum2();
  41094. }
  41095. });
  41096. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
  41097. var init_defaultExtensionConfiguration = __esm({
  41098. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js"() {
  41099. "use strict";
  41100. }
  41101. });
  41102. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/index.js
  41103. var init_extensions2 = __esm({
  41104. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/extensions/index.js"() {
  41105. "use strict";
  41106. init_defaultClientConfiguration();
  41107. init_defaultExtensionConfiguration();
  41108. init_checksum2();
  41109. }
  41110. });
  41111. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/feature-ids.js
  41112. var init_feature_ids = __esm({
  41113. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/feature-ids.js"() {
  41114. "use strict";
  41115. }
  41116. });
  41117. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http.js
  41118. var FieldPosition;
  41119. var init_http = __esm({
  41120. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http.js"() {
  41121. "use strict";
  41122. (function(FieldPosition2) {
  41123. FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
  41124. FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
  41125. })(FieldPosition || (FieldPosition = {}));
  41126. }
  41127. });
  41128. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
  41129. var init_httpHandlerInitialization = __esm({
  41130. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js"() {
  41131. "use strict";
  41132. }
  41133. });
  41134. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
  41135. var init_apiKeyIdentity = __esm({
  41136. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js"() {
  41137. "use strict";
  41138. }
  41139. });
  41140. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
  41141. var init_awsCredentialIdentity = __esm({
  41142. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js"() {
  41143. "use strict";
  41144. }
  41145. });
  41146. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/identity.js
  41147. var init_identity = __esm({
  41148. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/identity.js"() {
  41149. "use strict";
  41150. }
  41151. });
  41152. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
  41153. var init_tokenIdentity = __esm({
  41154. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js"() {
  41155. "use strict";
  41156. }
  41157. });
  41158. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/index.js
  41159. var init_identity2 = __esm({
  41160. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/identity/index.js"() {
  41161. "use strict";
  41162. init_apiKeyIdentity();
  41163. init_awsCredentialIdentity();
  41164. init_identity();
  41165. init_tokenIdentity();
  41166. }
  41167. });
  41168. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/logger.js
  41169. var init_logger = __esm({
  41170. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/logger.js"() {
  41171. "use strict";
  41172. }
  41173. });
  41174. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/middleware.js
  41175. var SMITHY_CONTEXT_KEY;
  41176. var init_middleware = __esm({
  41177. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/middleware.js"() {
  41178. "use strict";
  41179. SMITHY_CONTEXT_KEY = "__smithy_context";
  41180. }
  41181. });
  41182. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/pagination.js
  41183. var init_pagination = __esm({
  41184. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/pagination.js"() {
  41185. "use strict";
  41186. }
  41187. });
  41188. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/profile.js
  41189. var IniSectionType;
  41190. var init_profile = __esm({
  41191. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/profile.js"() {
  41192. "use strict";
  41193. (function(IniSectionType2) {
  41194. IniSectionType2["PROFILE"] = "profile";
  41195. IniSectionType2["SSO_SESSION"] = "sso-session";
  41196. IniSectionType2["SERVICES"] = "services";
  41197. })(IniSectionType || (IniSectionType = {}));
  41198. }
  41199. });
  41200. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/response.js
  41201. var init_response2 = __esm({
  41202. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/response.js"() {
  41203. "use strict";
  41204. }
  41205. });
  41206. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/retry.js
  41207. var init_retry = __esm({
  41208. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/retry.js"() {
  41209. "use strict";
  41210. }
  41211. });
  41212. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/schema.js
  41213. var init_schema = __esm({
  41214. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/schema.js"() {
  41215. "use strict";
  41216. }
  41217. });
  41218. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/sentinels.js
  41219. var init_sentinels = __esm({
  41220. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/schema/sentinels.js"() {
  41221. "use strict";
  41222. }
  41223. });
  41224. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/serde.js
  41225. var init_serde = __esm({
  41226. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/serde.js"() {
  41227. "use strict";
  41228. }
  41229. });
  41230. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/shapes.js
  41231. var init_shapes = __esm({
  41232. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/shapes.js"() {
  41233. "use strict";
  41234. }
  41235. });
  41236. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/signature.js
  41237. var init_signature = __esm({
  41238. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/signature.js"() {
  41239. "use strict";
  41240. }
  41241. });
  41242. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/stream.js
  41243. var init_stream = __esm({
  41244. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/stream.js"() {
  41245. "use strict";
  41246. }
  41247. });
  41248. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
  41249. var init_streaming_blob_common_types = __esm({
  41250. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js"() {
  41251. "use strict";
  41252. }
  41253. });
  41254. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
  41255. var init_streaming_blob_payload_input_types = __esm({
  41256. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js"() {
  41257. "use strict";
  41258. }
  41259. });
  41260. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
  41261. var init_streaming_blob_payload_output_types = __esm({
  41262. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js"() {
  41263. "use strict";
  41264. }
  41265. });
  41266. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transfer.js
  41267. var RequestHandlerProtocol;
  41268. var init_transfer = __esm({
  41269. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transfer.js"() {
  41270. "use strict";
  41271. (function(RequestHandlerProtocol2) {
  41272. RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
  41273. RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
  41274. RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
  41275. })(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
  41276. }
  41277. });
  41278. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
  41279. var init_client_payload_blob_type_narrow = __esm({
  41280. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js"() {
  41281. "use strict";
  41282. }
  41283. });
  41284. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/mutable.js
  41285. var init_mutable = __esm({
  41286. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/mutable.js"() {
  41287. "use strict";
  41288. }
  41289. });
  41290. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/no-undefined.js
  41291. var init_no_undefined = __esm({
  41292. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/no-undefined.js"() {
  41293. "use strict";
  41294. }
  41295. });
  41296. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/type-transform.js
  41297. var init_type_transform = __esm({
  41298. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/transform/type-transform.js"() {
  41299. "use strict";
  41300. }
  41301. });
  41302. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/uri.js
  41303. var init_uri = __esm({
  41304. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/uri.js"() {
  41305. "use strict";
  41306. }
  41307. });
  41308. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/util.js
  41309. var init_util2 = __esm({
  41310. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/util.js"() {
  41311. "use strict";
  41312. }
  41313. });
  41314. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/waiter.js
  41315. var init_waiter = __esm({
  41316. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/waiter.js"() {
  41317. "use strict";
  41318. }
  41319. });
  41320. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/index.js
  41321. var init_dist_es = __esm({
  41322. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-es/index.js"() {
  41323. "use strict";
  41324. init_abort();
  41325. init_auth2();
  41326. init_blob_payload_input_types();
  41327. init_checksum();
  41328. init_client();
  41329. init_command();
  41330. init_connection();
  41331. init_crypto2();
  41332. init_encode();
  41333. init_endpoint();
  41334. init_endpoints();
  41335. init_eventStream();
  41336. init_extensions2();
  41337. init_feature_ids();
  41338. init_http();
  41339. init_httpHandlerInitialization();
  41340. init_identity2();
  41341. init_logger();
  41342. init_middleware();
  41343. init_pagination();
  41344. init_profile();
  41345. init_response2();
  41346. init_retry();
  41347. init_schema();
  41348. init_sentinels();
  41349. init_serde();
  41350. init_shapes();
  41351. init_signature();
  41352. init_stream();
  41353. init_streaming_blob_common_types();
  41354. init_streaming_blob_payload_input_types();
  41355. init_streaming_blob_payload_output_types();
  41356. init_transfer();
  41357. init_client_payload_blob_type_narrow();
  41358. init_mutable();
  41359. init_no_undefined();
  41360. init_type_transform();
  41361. init_uri();
  41362. init_util2();
  41363. init_waiter();
  41364. }
  41365. });
  41366. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Field.js
  41367. var init_Field = __esm({
  41368. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
  41369. "use strict";
  41370. init_dist_es();
  41371. }
  41372. });
  41373. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Fields.js
  41374. var init_Fields = __esm({
  41375. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  41376. "use strict";
  41377. }
  41378. });
  41379. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
  41380. var init_httpHandler = __esm({
  41381. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  41382. "use strict";
  41383. }
  41384. });
  41385. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
  41386. function cloneQuery(query) {
  41387. return Object.keys(query).reduce((carry, paramName) => {
  41388. const param = query[paramName];
  41389. return {
  41390. ...carry,
  41391. [paramName]: Array.isArray(param) ? [...param] : param
  41392. };
  41393. }, {});
  41394. }
  41395. var HttpRequest;
  41396. var init_httpRequest = __esm({
  41397. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
  41398. "use strict";
  41399. HttpRequest = class _HttpRequest {
  41400. constructor(options) {
  41401. this.method = options.method || "GET";
  41402. this.hostname = options.hostname || "localhost";
  41403. this.port = options.port;
  41404. this.query = options.query || {};
  41405. this.headers = options.headers || {};
  41406. this.body = options.body;
  41407. this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
  41408. this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
  41409. this.username = options.username;
  41410. this.password = options.password;
  41411. this.fragment = options.fragment;
  41412. }
  41413. static clone(request2) {
  41414. const cloned = new _HttpRequest({
  41415. ...request2,
  41416. headers: { ...request2.headers }
  41417. });
  41418. if (cloned.query) {
  41419. cloned.query = cloneQuery(cloned.query);
  41420. }
  41421. return cloned;
  41422. }
  41423. static isInstance(request2) {
  41424. if (!request2) {
  41425. return false;
  41426. }
  41427. const req = request2;
  41428. return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
  41429. }
  41430. clone() {
  41431. return _HttpRequest.clone(this);
  41432. }
  41433. };
  41434. }
  41435. });
  41436. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
  41437. var HttpResponse;
  41438. var init_httpResponse = __esm({
  41439. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  41440. "use strict";
  41441. HttpResponse = class {
  41442. constructor(options) {
  41443. this.statusCode = options.statusCode;
  41444. this.reason = options.reason;
  41445. this.headers = options.headers || {};
  41446. this.body = options.body;
  41447. }
  41448. static isInstance(response) {
  41449. if (!response)
  41450. return false;
  41451. const resp = response;
  41452. return typeof resp.statusCode === "number" && typeof resp.headers === "object";
  41453. }
  41454. };
  41455. }
  41456. });
  41457. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
  41458. var init_isValidHostname = __esm({
  41459. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  41460. "use strict";
  41461. }
  41462. });
  41463. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/types.js
  41464. var init_types2 = __esm({
  41465. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  41466. "use strict";
  41467. }
  41468. });
  41469. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/index.js
  41470. var init_dist_es2 = __esm({
  41471. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-es/index.js"() {
  41472. "use strict";
  41473. init_extensions();
  41474. init_Field();
  41475. init_Fields();
  41476. init_httpHandler();
  41477. init_httpRequest();
  41478. init_httpResponse();
  41479. init_isValidHostname();
  41480. init_types2();
  41481. }
  41482. });
  41483. // ../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js
  41484. function resolveHostHeaderConfig(input) {
  41485. return input;
  41486. }
  41487. var hostHeaderMiddleware, hostHeaderMiddlewareOptions, getHostHeaderPlugin;
  41488. var init_dist_es3 = __esm({
  41489. "../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js"() {
  41490. "use strict";
  41491. init_dist_es2();
  41492. hostHeaderMiddleware = (options) => (next) => async (args) => {
  41493. if (!HttpRequest.isInstance(args.request))
  41494. return next(args);
  41495. const { request: request2 } = args;
  41496. const { handlerProtocol = "" } = options.requestHandler.metadata || {};
  41497. if (handlerProtocol.indexOf("h2") >= 0 && !request2.headers[":authority"]) {
  41498. delete request2.headers["host"];
  41499. request2.headers[":authority"] = request2.hostname + (request2.port ? ":" + request2.port : "");
  41500. } else if (!request2.headers["host"]) {
  41501. let host = request2.hostname;
  41502. if (request2.port != null)
  41503. host += `:${request2.port}`;
  41504. request2.headers["host"] = host;
  41505. }
  41506. return next(args);
  41507. };
  41508. hostHeaderMiddlewareOptions = {
  41509. name: "hostHeaderMiddleware",
  41510. step: "build",
  41511. priority: "low",
  41512. tags: ["HOST"],
  41513. override: true
  41514. };
  41515. getHostHeaderPlugin = (options) => ({
  41516. applyToStack: (clientStack) => {
  41517. clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
  41518. }
  41519. });
  41520. }
  41521. });
  41522. // ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js
  41523. var loggerMiddleware, loggerMiddlewareOptions, getLoggerPlugin;
  41524. var init_loggerMiddleware = __esm({
  41525. "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js"() {
  41526. "use strict";
  41527. loggerMiddleware = () => (next, context) => async (args) => {
  41528. try {
  41529. const response = await next(args);
  41530. const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context;
  41531. const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
  41532. const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
  41533. const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;
  41534. const { $metadata, ...outputWithoutMetadata } = response.output;
  41535. logger2?.info?.({
  41536. clientName,
  41537. commandName,
  41538. input: inputFilterSensitiveLog(args.input),
  41539. output: outputFilterSensitiveLog(outputWithoutMetadata),
  41540. metadata: $metadata
  41541. });
  41542. return response;
  41543. } catch (error2) {
  41544. const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context;
  41545. const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
  41546. const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
  41547. logger2?.error?.({
  41548. clientName,
  41549. commandName,
  41550. input: inputFilterSensitiveLog(args.input),
  41551. error: error2,
  41552. metadata: error2.$metadata
  41553. });
  41554. throw error2;
  41555. }
  41556. };
  41557. loggerMiddlewareOptions = {
  41558. name: "loggerMiddleware",
  41559. tags: ["LOGGER"],
  41560. step: "initialize",
  41561. override: true
  41562. };
  41563. getLoggerPlugin = (options) => ({
  41564. applyToStack: (clientStack) => {
  41565. clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
  41566. }
  41567. });
  41568. }
  41569. });
  41570. // ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/index.js
  41571. var init_dist_es4 = __esm({
  41572. "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-es/index.js"() {
  41573. "use strict";
  41574. init_loggerMiddleware();
  41575. }
  41576. });
  41577. // ../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js
  41578. var TRACE_ID_HEADER_NAME, ENV_LAMBDA_FUNCTION_NAME, ENV_TRACE_ID, recursionDetectionMiddleware, addRecursionDetectionMiddlewareOptions, getRecursionDetectionPlugin;
  41579. var init_dist_es5 = __esm({
  41580. "../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js"() {
  41581. "use strict";
  41582. init_dist_es2();
  41583. TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
  41584. ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
  41585. ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
  41586. recursionDetectionMiddleware = (options) => (next) => async (args) => {
  41587. const { request: request2 } = args;
  41588. if (!HttpRequest.isInstance(request2) || options.runtime !== "node") {
  41589. return next(args);
  41590. }
  41591. const traceIdHeader = Object.keys(request2.headers ?? {}).find((h6) => h6.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME;
  41592. if (request2.headers.hasOwnProperty(traceIdHeader)) {
  41593. return next(args);
  41594. }
  41595. const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
  41596. const traceId = process.env[ENV_TRACE_ID];
  41597. const nonEmptyString = (str) => typeof str === "string" && str.length > 0;
  41598. if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
  41599. request2.headers[TRACE_ID_HEADER_NAME] = traceId;
  41600. }
  41601. return next({
  41602. ...args,
  41603. request: request2
  41604. });
  41605. };
  41606. addRecursionDetectionMiddlewareOptions = {
  41607. step: "build",
  41608. tags: ["RECURSION_DETECTION"],
  41609. name: "recursionDetectionMiddleware",
  41610. override: true,
  41611. priority: "low"
  41612. };
  41613. getRecursionDetectionPlugin = (options) => ({
  41614. applyToStack: (clientStack) => {
  41615. clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions);
  41616. }
  41617. });
  41618. }
  41619. });
  41620. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js
  41621. var init_getSmithyContext = __esm({
  41622. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js"() {
  41623. "use strict";
  41624. init_dist_es();
  41625. }
  41626. });
  41627. // ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js
  41628. var getSmithyContext;
  41629. var init_getSmithyContext2 = __esm({
  41630. "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js"() {
  41631. "use strict";
  41632. init_dist_es();
  41633. getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {});
  41634. }
  41635. });
  41636. // ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js
  41637. var normalizeProvider;
  41638. var init_normalizeProvider = __esm({
  41639. "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js"() {
  41640. "use strict";
  41641. normalizeProvider = (input) => {
  41642. if (typeof input === "function")
  41643. return input;
  41644. const promisified = Promise.resolve(input);
  41645. return () => promisified;
  41646. };
  41647. }
  41648. });
  41649. // ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/index.js
  41650. var init_dist_es6 = __esm({
  41651. "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-es/index.js"() {
  41652. "use strict";
  41653. init_getSmithyContext2();
  41654. init_normalizeProvider();
  41655. }
  41656. });
  41657. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js
  41658. var resolveAuthOptions;
  41659. var init_resolveAuthOptions = __esm({
  41660. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() {
  41661. "use strict";
  41662. resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => {
  41663. if (!authSchemePreference || authSchemePreference.length === 0) {
  41664. return candidateAuthOptions;
  41665. }
  41666. const preferredAuthOptions = [];
  41667. for (const preferredSchemeName of authSchemePreference) {
  41668. for (const candidateAuthOption of candidateAuthOptions) {
  41669. const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1];
  41670. if (candidateAuthSchemeName === preferredSchemeName) {
  41671. preferredAuthOptions.push(candidateAuthOption);
  41672. }
  41673. }
  41674. }
  41675. for (const candidateAuthOption of candidateAuthOptions) {
  41676. if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) {
  41677. preferredAuthOptions.push(candidateAuthOption);
  41678. }
  41679. }
  41680. return preferredAuthOptions;
  41681. };
  41682. }
  41683. });
  41684. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
  41685. function convertHttpAuthSchemesToMap(httpAuthSchemes) {
  41686. const map2 = /* @__PURE__ */ new Map();
  41687. for (const scheme of httpAuthSchemes) {
  41688. map2.set(scheme.schemeId, scheme);
  41689. }
  41690. return map2;
  41691. }
  41692. var httpAuthSchemeMiddleware;
  41693. var init_httpAuthSchemeMiddleware = __esm({
  41694. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() {
  41695. "use strict";
  41696. init_dist_es();
  41697. init_dist_es6();
  41698. init_resolveAuthOptions();
  41699. httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => {
  41700. const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input));
  41701. const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : [];
  41702. const resolvedOptions = resolveAuthOptions(options, authSchemePreference);
  41703. const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
  41704. const smithyContext = getSmithyContext(context);
  41705. const failureReasons = [];
  41706. for (const option of resolvedOptions) {
  41707. const scheme = authSchemes.get(option.schemeId);
  41708. if (!scheme) {
  41709. failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);
  41710. continue;
  41711. }
  41712. const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));
  41713. if (!identityProvider) {
  41714. failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);
  41715. continue;
  41716. }
  41717. const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {};
  41718. option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);
  41719. option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);
  41720. smithyContext.selectedHttpAuthScheme = {
  41721. httpAuthOption: option,
  41722. identity: await identityProvider(option.identityProperties),
  41723. signer: scheme.signer
  41724. };
  41725. break;
  41726. }
  41727. if (!smithyContext.selectedHttpAuthScheme) {
  41728. throw new Error(failureReasons.join("\n"));
  41729. }
  41730. return next(args);
  41731. };
  41732. }
  41733. });
  41734. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
  41735. var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin;
  41736. var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({
  41737. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() {
  41738. "use strict";
  41739. init_httpAuthSchemeMiddleware();
  41740. httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
  41741. step: "serialize",
  41742. tags: ["HTTP_AUTH_SCHEME"],
  41743. name: "httpAuthSchemeMiddleware",
  41744. override: true,
  41745. relation: "before",
  41746. toMiddleware: "endpointV2Middleware"
  41747. };
  41748. getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
  41749. applyToStack: (clientStack) => {
  41750. clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
  41751. httpAuthSchemeParametersProvider,
  41752. identityProviderConfigProvider
  41753. }), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
  41754. }
  41755. });
  41756. }
  41757. });
  41758. // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js
  41759. var deserializerMiddleware, findHeader;
  41760. var init_deserializerMiddleware = __esm({
  41761. "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js"() {
  41762. "use strict";
  41763. init_dist_es2();
  41764. deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => {
  41765. const { response } = await next(args);
  41766. try {
  41767. const parsed = await deserializer(response, options);
  41768. return {
  41769. response,
  41770. output: parsed
  41771. };
  41772. } catch (error2) {
  41773. Object.defineProperty(error2, "$response", {
  41774. value: response
  41775. });
  41776. if (!("$metadata" in error2)) {
  41777. const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
  41778. try {
  41779. error2.message += "\n " + hint;
  41780. } catch (e6) {
  41781. if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") {
  41782. console.warn(hint);
  41783. } else {
  41784. context.logger?.warn?.(hint);
  41785. }
  41786. }
  41787. if (typeof error2.$responseBodyText !== "undefined") {
  41788. if (error2.$response) {
  41789. error2.$response.body = error2.$responseBodyText;
  41790. }
  41791. }
  41792. try {
  41793. if (HttpResponse.isInstance(response)) {
  41794. const { headers = {} } = response;
  41795. const headerEntries = Object.entries(headers);
  41796. error2.$metadata = {
  41797. httpStatusCode: response.statusCode,
  41798. requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
  41799. extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
  41800. cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
  41801. };
  41802. }
  41803. } catch (e6) {
  41804. }
  41805. }
  41806. throw error2;
  41807. }
  41808. };
  41809. findHeader = (pattern, headers) => {
  41810. return (headers.find(([k5]) => {
  41811. return k5.match(pattern);
  41812. }) || [void 0, void 0])[1];
  41813. };
  41814. }
  41815. });
  41816. // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js
  41817. var serializerMiddleware;
  41818. var init_serializerMiddleware = __esm({
  41819. "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js"() {
  41820. "use strict";
  41821. serializerMiddleware = (options, serializer) => (next, context) => async (args) => {
  41822. const endpointConfig = options;
  41823. const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint;
  41824. if (!endpoint) {
  41825. throw new Error("No valid endpoint provider available.");
  41826. }
  41827. const request2 = await serializer(args.input, { ...options, endpoint });
  41828. return next({
  41829. ...args,
  41830. request: request2
  41831. });
  41832. };
  41833. }
  41834. });
  41835. // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js
  41836. function getSerdePlugin(config, serializer, deserializer) {
  41837. return {
  41838. applyToStack: (commandStack) => {
  41839. commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
  41840. commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption);
  41841. }
  41842. };
  41843. }
  41844. var deserializerMiddlewareOption, serializerMiddlewareOption;
  41845. var init_serdePlugin = __esm({
  41846. "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js"() {
  41847. "use strict";
  41848. init_deserializerMiddleware();
  41849. init_serializerMiddleware();
  41850. deserializerMiddlewareOption = {
  41851. name: "deserializerMiddleware",
  41852. step: "deserialize",
  41853. tags: ["DESERIALIZER"],
  41854. override: true
  41855. };
  41856. serializerMiddlewareOption = {
  41857. name: "serializerMiddleware",
  41858. step: "serialize",
  41859. tags: ["SERIALIZER"],
  41860. override: true
  41861. };
  41862. }
  41863. });
  41864. // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/index.js
  41865. var init_dist_es7 = __esm({
  41866. "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-es/index.js"() {
  41867. "use strict";
  41868. init_deserializerMiddleware();
  41869. init_serdePlugin();
  41870. init_serializerMiddleware();
  41871. }
  41872. });
  41873. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
  41874. var httpAuthSchemeMiddlewareOptions;
  41875. var init_getHttpAuthSchemePlugin = __esm({
  41876. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() {
  41877. "use strict";
  41878. init_dist_es7();
  41879. init_httpAuthSchemeMiddleware();
  41880. httpAuthSchemeMiddlewareOptions = {
  41881. step: "serialize",
  41882. tags: ["HTTP_AUTH_SCHEME"],
  41883. name: "httpAuthSchemeMiddleware",
  41884. override: true,
  41885. relation: "before",
  41886. toMiddleware: serializerMiddlewareOption.name
  41887. };
  41888. }
  41889. });
  41890. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
  41891. var init_middleware_http_auth_scheme = __esm({
  41892. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() {
  41893. "use strict";
  41894. init_httpAuthSchemeMiddleware();
  41895. init_getHttpAuthSchemeEndpointRuleSetPlugin();
  41896. init_getHttpAuthSchemePlugin();
  41897. }
  41898. });
  41899. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
  41900. var defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware;
  41901. var init_httpSigningMiddleware = __esm({
  41902. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() {
  41903. "use strict";
  41904. init_dist_es2();
  41905. init_dist_es();
  41906. init_dist_es6();
  41907. defaultErrorHandler = (signingProperties) => (error2) => {
  41908. throw error2;
  41909. };
  41910. defaultSuccessHandler = (httpResponse, signingProperties) => {
  41911. };
  41912. httpSigningMiddleware = (config) => (next, context) => async (args) => {
  41913. if (!HttpRequest.isInstance(args.request)) {
  41914. return next(args);
  41915. }
  41916. const smithyContext = getSmithyContext(context);
  41917. const scheme = smithyContext.selectedHttpAuthScheme;
  41918. if (!scheme) {
  41919. throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
  41920. }
  41921. const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme;
  41922. const output = await next({
  41923. ...args,
  41924. request: await signer.sign(args.request, identity, signingProperties)
  41925. }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
  41926. (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
  41927. return output;
  41928. };
  41929. }
  41930. });
  41931. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
  41932. var httpSigningMiddlewareOptions, getHttpSigningPlugin;
  41933. var init_getHttpSigningMiddleware = __esm({
  41934. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() {
  41935. "use strict";
  41936. init_httpSigningMiddleware();
  41937. httpSigningMiddlewareOptions = {
  41938. step: "finalizeRequest",
  41939. tags: ["HTTP_SIGNING"],
  41940. name: "httpSigningMiddleware",
  41941. aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
  41942. override: true,
  41943. relation: "after",
  41944. toMiddleware: "retryMiddleware"
  41945. };
  41946. getHttpSigningPlugin = (config) => ({
  41947. applyToStack: (clientStack) => {
  41948. clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
  41949. }
  41950. });
  41951. }
  41952. });
  41953. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
  41954. var init_middleware_http_signing = __esm({
  41955. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() {
  41956. "use strict";
  41957. init_httpSigningMiddleware();
  41958. init_getHttpSigningMiddleware();
  41959. }
  41960. });
  41961. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js
  41962. var normalizeProvider2;
  41963. var init_normalizeProvider2 = __esm({
  41964. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js"() {
  41965. "use strict";
  41966. normalizeProvider2 = (input) => {
  41967. if (typeof input === "function")
  41968. return input;
  41969. const promisified = Promise.resolve(input);
  41970. return () => promisified;
  41971. };
  41972. }
  41973. });
  41974. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js
  41975. function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
  41976. return async function* paginateOperation(config, input, ...additionalArguments) {
  41977. const _input = input;
  41978. let token = config.startingToken ?? _input[inputTokenName];
  41979. let hasNext = true;
  41980. let page;
  41981. while (hasNext) {
  41982. _input[inputTokenName] = token;
  41983. if (pageSizeTokenName) {
  41984. _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize;
  41985. }
  41986. if (config.client instanceof ClientCtor) {
  41987. page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments);
  41988. } else {
  41989. throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);
  41990. }
  41991. yield page;
  41992. const prevToken = token;
  41993. token = get(page, outputTokenName);
  41994. hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken));
  41995. }
  41996. return void 0;
  41997. };
  41998. }
  41999. var makePagedClientRequest, get;
  42000. var init_createPaginator = __esm({
  42001. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() {
  42002. "use strict";
  42003. makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_3) => _3, ...args) => {
  42004. let command = new CommandCtor(input);
  42005. command = withCommand(command) ?? command;
  42006. return await client.send(command, ...args);
  42007. };
  42008. get = (fromObject, path3) => {
  42009. let cursor = fromObject;
  42010. const pathComponents = path3.split(".");
  42011. for (const step of pathComponents) {
  42012. if (!cursor || typeof cursor !== "object") {
  42013. return void 0;
  42014. }
  42015. cursor = cursor[step];
  42016. }
  42017. return cursor;
  42018. };
  42019. }
  42020. });
  42021. // ../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-es/index.js
  42022. var isArrayBuffer;
  42023. var init_dist_es8 = __esm({
  42024. "../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-es/index.js"() {
  42025. "use strict";
  42026. isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
  42027. }
  42028. });
  42029. // ../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-es/index.js
  42030. import { Buffer as Buffer4 } from "buffer";
  42031. var fromArrayBuffer, fromString;
  42032. var init_dist_es9 = __esm({
  42033. "../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-es/index.js"() {
  42034. "use strict";
  42035. init_dist_es8();
  42036. fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
  42037. if (!isArrayBuffer(input)) {
  42038. throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
  42039. }
  42040. return Buffer4.from(input, offset, length);
  42041. };
  42042. fromString = (input, encoding) => {
  42043. if (typeof input !== "string") {
  42044. throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
  42045. }
  42046. return encoding ? Buffer4.from(input, encoding) : Buffer4.from(input);
  42047. };
  42048. }
  42049. });
  42050. // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/fromBase64.js
  42051. var BASE64_REGEX, fromBase64;
  42052. var init_fromBase64 = __esm({
  42053. "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/fromBase64.js"() {
  42054. "use strict";
  42055. init_dist_es9();
  42056. BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
  42057. fromBase64 = (input) => {
  42058. if (input.length * 3 % 4 !== 0) {
  42059. throw new TypeError(`Incorrect padding on base64 string.`);
  42060. }
  42061. if (!BASE64_REGEX.exec(input)) {
  42062. throw new TypeError(`Invalid base64 string.`);
  42063. }
  42064. const buffer = fromString(input, "base64");
  42065. return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  42066. };
  42067. }
  42068. });
  42069. // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js
  42070. var fromUtf8;
  42071. var init_fromUtf8 = __esm({
  42072. "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js"() {
  42073. "use strict";
  42074. init_dist_es9();
  42075. fromUtf8 = (input) => {
  42076. const buf = fromString(input, "utf8");
  42077. return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
  42078. };
  42079. }
  42080. });
  42081. // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
  42082. var toUint8Array;
  42083. var init_toUint8Array = __esm({
  42084. "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
  42085. "use strict";
  42086. init_fromUtf8();
  42087. toUint8Array = (data) => {
  42088. if (typeof data === "string") {
  42089. return fromUtf8(data);
  42090. }
  42091. if (ArrayBuffer.isView(data)) {
  42092. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
  42093. }
  42094. return new Uint8Array(data);
  42095. };
  42096. }
  42097. });
  42098. // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js
  42099. var toUtf8;
  42100. var init_toUtf8 = __esm({
  42101. "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js"() {
  42102. "use strict";
  42103. init_dist_es9();
  42104. toUtf8 = (input) => {
  42105. if (typeof input === "string") {
  42106. return input;
  42107. }
  42108. if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
  42109. throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
  42110. }
  42111. return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
  42112. };
  42113. }
  42114. });
  42115. // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/index.js
  42116. var init_dist_es10 = __esm({
  42117. "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-es/index.js"() {
  42118. "use strict";
  42119. init_fromUtf8();
  42120. init_toUint8Array();
  42121. init_toUtf8();
  42122. }
  42123. });
  42124. // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/toBase64.js
  42125. var toBase64;
  42126. var init_toBase64 = __esm({
  42127. "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/toBase64.js"() {
  42128. "use strict";
  42129. init_dist_es9();
  42130. init_dist_es10();
  42131. toBase64 = (_input) => {
  42132. let input;
  42133. if (typeof _input === "string") {
  42134. input = fromUtf8(_input);
  42135. } else {
  42136. input = _input;
  42137. }
  42138. if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
  42139. throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
  42140. }
  42141. return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64");
  42142. };
  42143. }
  42144. });
  42145. // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/index.js
  42146. var init_dist_es11 = __esm({
  42147. "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-es/index.js"() {
  42148. "use strict";
  42149. init_fromBase64();
  42150. init_toBase64();
  42151. }
  42152. });
  42153. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/transforms.js
  42154. function transformToString(payload, encoding = "utf-8") {
  42155. if (encoding === "base64") {
  42156. return toBase64(payload);
  42157. }
  42158. return toUtf8(payload);
  42159. }
  42160. function transformFromString(str, encoding) {
  42161. if (encoding === "base64") {
  42162. return Uint8ArrayBlobAdapter.mutate(fromBase64(str));
  42163. }
  42164. return Uint8ArrayBlobAdapter.mutate(fromUtf8(str));
  42165. }
  42166. var init_transforms = __esm({
  42167. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/transforms.js"() {
  42168. "use strict";
  42169. init_dist_es11();
  42170. init_dist_es10();
  42171. init_Uint8ArrayBlobAdapter();
  42172. }
  42173. });
  42174. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js
  42175. var Uint8ArrayBlobAdapter;
  42176. var init_Uint8ArrayBlobAdapter = __esm({
  42177. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js"() {
  42178. "use strict";
  42179. init_transforms();
  42180. Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array {
  42181. static fromString(source, encoding = "utf-8") {
  42182. switch (typeof source) {
  42183. case "string":
  42184. return transformFromString(source, encoding);
  42185. default:
  42186. throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);
  42187. }
  42188. }
  42189. static mutate(source) {
  42190. Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype);
  42191. return source;
  42192. }
  42193. transformToString(encoding = "utf-8") {
  42194. return transformToString(this, encoding);
  42195. }
  42196. };
  42197. }
  42198. });
  42199. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js
  42200. var init_ChecksumStream = __esm({
  42201. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js"() {
  42202. "use strict";
  42203. init_dist_es11();
  42204. }
  42205. });
  42206. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/stream-type-check.js
  42207. var isReadableStream;
  42208. var init_stream_type_check = __esm({
  42209. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/stream-type-check.js"() {
  42210. "use strict";
  42211. isReadableStream = (stream) => typeof ReadableStream === "function" && (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream);
  42212. }
  42213. });
  42214. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js
  42215. var init_ChecksumStream_browser = __esm({
  42216. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js"() {
  42217. "use strict";
  42218. }
  42219. });
  42220. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js
  42221. var init_createChecksumStream_browser = __esm({
  42222. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js"() {
  42223. "use strict";
  42224. init_dist_es11();
  42225. init_stream_type_check();
  42226. init_ChecksumStream_browser();
  42227. }
  42228. });
  42229. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js
  42230. var init_createChecksumStream = __esm({
  42231. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js"() {
  42232. "use strict";
  42233. init_stream_type_check();
  42234. init_ChecksumStream();
  42235. init_createChecksumStream_browser();
  42236. }
  42237. });
  42238. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/ByteArrayCollector.js
  42239. var init_ByteArrayCollector = __esm({
  42240. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/ByteArrayCollector.js"() {
  42241. "use strict";
  42242. }
  42243. });
  42244. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js
  42245. var init_createBufferedReadableStream = __esm({
  42246. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js"() {
  42247. "use strict";
  42248. init_ByteArrayCollector();
  42249. }
  42250. });
  42251. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadable.js
  42252. import { Readable as Readable2 } from "stream";
  42253. var init_createBufferedReadable = __esm({
  42254. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/createBufferedReadable.js"() {
  42255. "use strict";
  42256. init_ByteArrayCollector();
  42257. init_createBufferedReadableStream();
  42258. init_stream_type_check();
  42259. }
  42260. });
  42261. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js
  42262. var init_getAwsChunkedEncodingStream = __esm({
  42263. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js"() {
  42264. "use strict";
  42265. }
  42266. });
  42267. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.browser.js
  42268. var init_headStream_browser = __esm({
  42269. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.browser.js"() {
  42270. "use strict";
  42271. }
  42272. });
  42273. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.js
  42274. var init_headStream = __esm({
  42275. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/headStream.js"() {
  42276. "use strict";
  42277. init_headStream_browser();
  42278. init_stream_type_check();
  42279. }
  42280. });
  42281. // ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js
  42282. var escapeUri, hexEncode;
  42283. var init_escape_uri = __esm({
  42284. "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js"() {
  42285. "use strict";
  42286. escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode);
  42287. hexEncode = (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`;
  42288. }
  42289. });
  42290. // ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js
  42291. var init_escape_uri_path = __esm({
  42292. "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js"() {
  42293. "use strict";
  42294. init_escape_uri();
  42295. }
  42296. });
  42297. // ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/index.js
  42298. var init_dist_es12 = __esm({
  42299. "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-es/index.js"() {
  42300. "use strict";
  42301. init_escape_uri();
  42302. init_escape_uri_path();
  42303. }
  42304. });
  42305. // ../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-es/index.js
  42306. function buildQueryString(query) {
  42307. const parts = [];
  42308. for (let key of Object.keys(query).sort()) {
  42309. const value = query[key];
  42310. key = escapeUri(key);
  42311. if (Array.isArray(value)) {
  42312. for (let i6 = 0, iLen = value.length; i6 < iLen; i6++) {
  42313. parts.push(`${key}=${escapeUri(value[i6])}`);
  42314. }
  42315. } else {
  42316. let qsEntry = key;
  42317. if (value || typeof value === "string") {
  42318. qsEntry += `=${escapeUri(value)}`;
  42319. }
  42320. parts.push(qsEntry);
  42321. }
  42322. }
  42323. return parts.join("&");
  42324. }
  42325. var init_dist_es13 = __esm({
  42326. "../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-es/index.js"() {
  42327. "use strict";
  42328. init_dist_es12();
  42329. }
  42330. });
  42331. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/constants.js
  42332. var NODEJS_TIMEOUT_ERROR_CODES;
  42333. var init_constants2 = __esm({
  42334. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/constants.js"() {
  42335. "use strict";
  42336. NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"];
  42337. }
  42338. });
  42339. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js
  42340. var getTransformedHeaders;
  42341. var init_get_transformed_headers = __esm({
  42342. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js"() {
  42343. "use strict";
  42344. getTransformedHeaders = (headers) => {
  42345. const transformedHeaders = {};
  42346. for (const name of Object.keys(headers)) {
  42347. const headerValues = headers[name];
  42348. transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues;
  42349. }
  42350. return transformedHeaders;
  42351. };
  42352. }
  42353. });
  42354. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/timing.js
  42355. var timing;
  42356. var init_timing = __esm({
  42357. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/timing.js"() {
  42358. "use strict";
  42359. timing = {
  42360. setTimeout: (cb, ms) => setTimeout(cb, ms),
  42361. clearTimeout: (timeoutId) => clearTimeout(timeoutId)
  42362. };
  42363. }
  42364. });
  42365. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js
  42366. var DEFER_EVENT_LISTENER_TIME, setConnectionTimeout;
  42367. var init_set_connection_timeout = __esm({
  42368. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js"() {
  42369. "use strict";
  42370. init_timing();
  42371. DEFER_EVENT_LISTENER_TIME = 1e3;
  42372. setConnectionTimeout = (request2, reject, timeoutInMs = 0) => {
  42373. if (!timeoutInMs) {
  42374. return -1;
  42375. }
  42376. const registerTimeout = (offset) => {
  42377. const timeoutId = timing.setTimeout(() => {
  42378. request2.destroy();
  42379. reject(Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
  42380. name: "TimeoutError"
  42381. }));
  42382. }, timeoutInMs - offset);
  42383. const doWithSocket = (socket) => {
  42384. if (socket?.connecting) {
  42385. socket.on("connect", () => {
  42386. timing.clearTimeout(timeoutId);
  42387. });
  42388. } else {
  42389. timing.clearTimeout(timeoutId);
  42390. }
  42391. };
  42392. if (request2.socket) {
  42393. doWithSocket(request2.socket);
  42394. } else {
  42395. request2.on("socket", doWithSocket);
  42396. }
  42397. };
  42398. if (timeoutInMs < 2e3) {
  42399. registerTimeout(0);
  42400. return 0;
  42401. }
  42402. return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);
  42403. };
  42404. }
  42405. });
  42406. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js
  42407. var DEFER_EVENT_LISTENER_TIME2, setSocketKeepAlive;
  42408. var init_set_socket_keep_alive = __esm({
  42409. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js"() {
  42410. "use strict";
  42411. init_timing();
  42412. DEFER_EVENT_LISTENER_TIME2 = 3e3;
  42413. setSocketKeepAlive = (request2, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => {
  42414. if (keepAlive !== true) {
  42415. return -1;
  42416. }
  42417. const registerListener = () => {
  42418. if (request2.socket) {
  42419. request2.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
  42420. } else {
  42421. request2.on("socket", (socket) => {
  42422. socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
  42423. });
  42424. }
  42425. };
  42426. if (deferTimeMs === 0) {
  42427. registerListener();
  42428. return 0;
  42429. }
  42430. return timing.setTimeout(registerListener, deferTimeMs);
  42431. };
  42432. }
  42433. });
  42434. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js
  42435. var DEFER_EVENT_LISTENER_TIME3, setSocketTimeout;
  42436. var init_set_socket_timeout = __esm({
  42437. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js"() {
  42438. "use strict";
  42439. init_node_http_handler();
  42440. init_timing();
  42441. DEFER_EVENT_LISTENER_TIME3 = 3e3;
  42442. setSocketTimeout = (request2, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => {
  42443. const registerTimeout = (offset) => {
  42444. const timeout = timeoutInMs - offset;
  42445. const onTimeout = () => {
  42446. request2.destroy();
  42447. reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" }));
  42448. };
  42449. if (request2.socket) {
  42450. request2.socket.setTimeout(timeout, onTimeout);
  42451. request2.on("close", () => request2.socket?.removeListener("timeout", onTimeout));
  42452. } else {
  42453. request2.setTimeout(timeout, onTimeout);
  42454. }
  42455. };
  42456. if (0 < timeoutInMs && timeoutInMs < 6e3) {
  42457. registerTimeout(0);
  42458. return 0;
  42459. }
  42460. return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), DEFER_EVENT_LISTENER_TIME3);
  42461. };
  42462. }
  42463. });
  42464. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js
  42465. import { Readable as Readable3 } from "stream";
  42466. async function writeRequestBody(httpRequest2, request2, maxContinueTimeoutMs = MIN_WAIT_TIME) {
  42467. const headers = request2.headers ?? {};
  42468. const expect = headers["Expect"] || headers["expect"];
  42469. let timeoutId = -1;
  42470. let sendBody = true;
  42471. if (expect === "100-continue") {
  42472. sendBody = await Promise.race([
  42473. new Promise((resolve) => {
  42474. timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
  42475. }),
  42476. new Promise((resolve) => {
  42477. httpRequest2.on("continue", () => {
  42478. timing.clearTimeout(timeoutId);
  42479. resolve(true);
  42480. });
  42481. httpRequest2.on("response", () => {
  42482. timing.clearTimeout(timeoutId);
  42483. resolve(false);
  42484. });
  42485. httpRequest2.on("error", () => {
  42486. timing.clearTimeout(timeoutId);
  42487. resolve(false);
  42488. });
  42489. })
  42490. ]);
  42491. }
  42492. if (sendBody) {
  42493. writeBody(httpRequest2, request2.body);
  42494. }
  42495. }
  42496. function writeBody(httpRequest2, body) {
  42497. if (body instanceof Readable3) {
  42498. body.pipe(httpRequest2);
  42499. return;
  42500. }
  42501. if (body) {
  42502. if (Buffer.isBuffer(body) || typeof body === "string") {
  42503. httpRequest2.end(body);
  42504. return;
  42505. }
  42506. const uint8 = body;
  42507. if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") {
  42508. httpRequest2.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
  42509. return;
  42510. }
  42511. httpRequest2.end(Buffer.from(body));
  42512. return;
  42513. }
  42514. httpRequest2.end();
  42515. }
  42516. var MIN_WAIT_TIME;
  42517. var init_write_request_body = __esm({
  42518. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js"() {
  42519. "use strict";
  42520. init_timing();
  42521. MIN_WAIT_TIME = 6e3;
  42522. }
  42523. });
  42524. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js
  42525. import { Agent as hAgent, request as hRequest } from "http";
  42526. import { Agent as hsAgent, request as hsRequest } from "https";
  42527. var DEFAULT_REQUEST_TIMEOUT, NodeHttpHandler;
  42528. var init_node_http_handler = __esm({
  42529. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js"() {
  42530. "use strict";
  42531. init_dist_es2();
  42532. init_dist_es13();
  42533. init_constants2();
  42534. init_get_transformed_headers();
  42535. init_set_connection_timeout();
  42536. init_set_socket_keep_alive();
  42537. init_set_socket_timeout();
  42538. init_timing();
  42539. init_write_request_body();
  42540. DEFAULT_REQUEST_TIMEOUT = 0;
  42541. NodeHttpHandler = class _NodeHttpHandler {
  42542. static create(instanceOrOptions) {
  42543. if (typeof instanceOrOptions?.handle === "function") {
  42544. return instanceOrOptions;
  42545. }
  42546. return new _NodeHttpHandler(instanceOrOptions);
  42547. }
  42548. static checkSocketUsage(agent, socketWarningTimestamp, logger2 = console) {
  42549. const { sockets, requests, maxSockets } = agent;
  42550. if (typeof maxSockets !== "number" || maxSockets === Infinity) {
  42551. return socketWarningTimestamp;
  42552. }
  42553. const interval = 15e3;
  42554. if (Date.now() - interval < socketWarningTimestamp) {
  42555. return socketWarningTimestamp;
  42556. }
  42557. if (sockets && requests) {
  42558. for (const origin in sockets) {
  42559. const socketsInUse = sockets[origin]?.length ?? 0;
  42560. const requestsEnqueued = requests[origin]?.length ?? 0;
  42561. if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
  42562. logger2?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.
  42563. See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
  42564. or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);
  42565. return Date.now();
  42566. }
  42567. }
  42568. }
  42569. return socketWarningTimestamp;
  42570. }
  42571. constructor(options) {
  42572. this.socketWarningTimestamp = 0;
  42573. this.metadata = { handlerProtocol: "http/1.1" };
  42574. this.configProvider = new Promise((resolve, reject) => {
  42575. if (typeof options === "function") {
  42576. options().then((_options) => {
  42577. resolve(this.resolveDefaultConfig(_options));
  42578. }).catch(reject);
  42579. } else {
  42580. resolve(this.resolveDefaultConfig(options));
  42581. }
  42582. });
  42583. }
  42584. resolveDefaultConfig(options) {
  42585. const { requestTimeout: requestTimeout2, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {};
  42586. const keepAlive = true;
  42587. const maxSockets = 50;
  42588. return {
  42589. connectionTimeout,
  42590. requestTimeout: requestTimeout2 ?? socketTimeout,
  42591. socketAcquisitionWarningTimeout,
  42592. httpAgent: (() => {
  42593. if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === "function") {
  42594. return httpAgent;
  42595. }
  42596. return new hAgent({ keepAlive, maxSockets, ...httpAgent });
  42597. })(),
  42598. httpsAgent: (() => {
  42599. if (httpsAgent instanceof hsAgent || typeof httpsAgent?.destroy === "function") {
  42600. return httpsAgent;
  42601. }
  42602. return new hsAgent({ keepAlive, maxSockets, ...httpsAgent });
  42603. })(),
  42604. logger: console
  42605. };
  42606. }
  42607. destroy() {
  42608. this.config?.httpAgent?.destroy();
  42609. this.config?.httpsAgent?.destroy();
  42610. }
  42611. async handle(request2, { abortSignal } = {}) {
  42612. if (!this.config) {
  42613. this.config = await this.configProvider;
  42614. }
  42615. return new Promise((_resolve, _reject) => {
  42616. let writeRequestBodyPromise = void 0;
  42617. const timeouts = [];
  42618. const resolve = async (arg) => {
  42619. await writeRequestBodyPromise;
  42620. timeouts.forEach(timing.clearTimeout);
  42621. _resolve(arg);
  42622. };
  42623. const reject = async (arg) => {
  42624. await writeRequestBodyPromise;
  42625. timeouts.forEach(timing.clearTimeout);
  42626. _reject(arg);
  42627. };
  42628. if (!this.config) {
  42629. throw new Error("Node HTTP request handler config is not resolved");
  42630. }
  42631. if (abortSignal?.aborted) {
  42632. const abortError = new Error("Request aborted");
  42633. abortError.name = "AbortError";
  42634. reject(abortError);
  42635. return;
  42636. }
  42637. const isSSL = request2.protocol === "https:";
  42638. const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent;
  42639. timeouts.push(timing.setTimeout(() => {
  42640. this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, this.config.logger);
  42641. }, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)));
  42642. const queryString = buildQueryString(request2.query || {});
  42643. let auth = void 0;
  42644. if (request2.username != null || request2.password != null) {
  42645. const username = request2.username ?? "";
  42646. const password = request2.password ?? "";
  42647. auth = `${username}:${password}`;
  42648. }
  42649. let path3 = request2.path;
  42650. if (queryString) {
  42651. path3 += `?${queryString}`;
  42652. }
  42653. if (request2.fragment) {
  42654. path3 += `#${request2.fragment}`;
  42655. }
  42656. let hostname = request2.hostname ?? "";
  42657. if (hostname[0] === "[" && hostname.endsWith("]")) {
  42658. hostname = request2.hostname.slice(1, -1);
  42659. } else {
  42660. hostname = request2.hostname;
  42661. }
  42662. const nodeHttpsOptions = {
  42663. headers: request2.headers,
  42664. host: hostname,
  42665. method: request2.method,
  42666. path: path3,
  42667. port: request2.port,
  42668. agent,
  42669. auth
  42670. };
  42671. const requestFunc = isSSL ? hsRequest : hRequest;
  42672. const req = requestFunc(nodeHttpsOptions, (res) => {
  42673. const httpResponse = new HttpResponse({
  42674. statusCode: res.statusCode || -1,
  42675. reason: res.statusMessage,
  42676. headers: getTransformedHeaders(res.headers),
  42677. body: res
  42678. });
  42679. resolve({ response: httpResponse });
  42680. });
  42681. req.on("error", (err2) => {
  42682. if (NODEJS_TIMEOUT_ERROR_CODES.includes(err2.code)) {
  42683. reject(Object.assign(err2, { name: "TimeoutError" }));
  42684. } else {
  42685. reject(err2);
  42686. }
  42687. });
  42688. if (abortSignal) {
  42689. const onAbort = () => {
  42690. req.destroy();
  42691. const abortError = new Error("Request aborted");
  42692. abortError.name = "AbortError";
  42693. reject(abortError);
  42694. };
  42695. if (typeof abortSignal.addEventListener === "function") {
  42696. const signal = abortSignal;
  42697. signal.addEventListener("abort", onAbort, { once: true });
  42698. req.once("close", () => signal.removeEventListener("abort", onAbort));
  42699. } else {
  42700. abortSignal.onabort = onAbort;
  42701. }
  42702. }
  42703. timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout));
  42704. timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout));
  42705. const httpAgent = nodeHttpsOptions.agent;
  42706. if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
  42707. timeouts.push(setSocketKeepAlive(req, {
  42708. keepAlive: httpAgent.keepAlive,
  42709. keepAliveMsecs: httpAgent.keepAliveMsecs
  42710. }));
  42711. }
  42712. writeRequestBodyPromise = writeRequestBody(req, request2, this.config.requestTimeout).catch((e6) => {
  42713. timeouts.forEach(timing.clearTimeout);
  42714. return _reject(e6);
  42715. });
  42716. });
  42717. }
  42718. updateHttpClientConfig(key, value) {
  42719. this.config = void 0;
  42720. this.configProvider = this.configProvider.then((config) => {
  42721. return {
  42722. ...config,
  42723. [key]: value
  42724. };
  42725. });
  42726. }
  42727. httpHandlerConfigs() {
  42728. return this.config ?? {};
  42729. }
  42730. };
  42731. }
  42732. });
  42733. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js
  42734. var init_node_http2_connection_pool = __esm({
  42735. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js"() {
  42736. "use strict";
  42737. }
  42738. });
  42739. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js
  42740. var init_node_http2_connection_manager = __esm({
  42741. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js"() {
  42742. "use strict";
  42743. init_node_http2_connection_pool();
  42744. }
  42745. });
  42746. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js
  42747. var init_node_http2_handler = __esm({
  42748. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js"() {
  42749. "use strict";
  42750. init_dist_es2();
  42751. init_dist_es13();
  42752. init_get_transformed_headers();
  42753. init_node_http2_connection_manager();
  42754. init_write_request_body();
  42755. }
  42756. });
  42757. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js
  42758. import { Writable } from "stream";
  42759. var Collector;
  42760. var init_collector = __esm({
  42761. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js"() {
  42762. "use strict";
  42763. Collector = class extends Writable {
  42764. constructor() {
  42765. super(...arguments);
  42766. this.bufferedBytes = [];
  42767. }
  42768. _write(chunk, encoding, callback) {
  42769. this.bufferedBytes.push(chunk);
  42770. callback();
  42771. }
  42772. };
  42773. }
  42774. });
  42775. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js
  42776. async function collectReadableStream(stream) {
  42777. const chunks = [];
  42778. const reader = stream.getReader();
  42779. let isDone = false;
  42780. let length = 0;
  42781. while (!isDone) {
  42782. const { done, value } = await reader.read();
  42783. if (value) {
  42784. chunks.push(value);
  42785. length += value.length;
  42786. }
  42787. isDone = done;
  42788. }
  42789. const collected = new Uint8Array(length);
  42790. let offset = 0;
  42791. for (const chunk of chunks) {
  42792. collected.set(chunk, offset);
  42793. offset += chunk.length;
  42794. }
  42795. return collected;
  42796. }
  42797. var streamCollector, isReadableStreamInstance;
  42798. var init_stream_collector = __esm({
  42799. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js"() {
  42800. "use strict";
  42801. init_collector();
  42802. streamCollector = (stream) => {
  42803. if (isReadableStreamInstance(stream)) {
  42804. return collectReadableStream(stream);
  42805. }
  42806. return new Promise((resolve, reject) => {
  42807. const collector = new Collector();
  42808. stream.pipe(collector);
  42809. stream.on("error", (err2) => {
  42810. collector.end();
  42811. reject(err2);
  42812. });
  42813. collector.on("error", reject);
  42814. collector.on("finish", function() {
  42815. const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));
  42816. resolve(bytes);
  42817. });
  42818. });
  42819. };
  42820. isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream;
  42821. }
  42822. });
  42823. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/index.js
  42824. var init_dist_es14 = __esm({
  42825. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-es/index.js"() {
  42826. "use strict";
  42827. init_node_http_handler();
  42828. init_node_http2_handler();
  42829. init_stream_collector();
  42830. }
  42831. });
  42832. // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js
  42833. var init_create_request = __esm({
  42834. "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js"() {
  42835. "use strict";
  42836. }
  42837. });
  42838. // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js
  42839. var init_request_timeout = __esm({
  42840. "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js"() {
  42841. "use strict";
  42842. }
  42843. });
  42844. // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js
  42845. var init_fetch_http_handler = __esm({
  42846. "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js"() {
  42847. "use strict";
  42848. init_dist_es2();
  42849. init_dist_es13();
  42850. init_create_request();
  42851. init_request_timeout();
  42852. }
  42853. });
  42854. // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js
  42855. async function collectBlob(blob) {
  42856. const base64 = await readToBase64(blob);
  42857. const arrayBuffer = fromBase64(base64);
  42858. return new Uint8Array(arrayBuffer);
  42859. }
  42860. async function collectStream(stream) {
  42861. const chunks = [];
  42862. const reader = stream.getReader();
  42863. let isDone = false;
  42864. let length = 0;
  42865. while (!isDone) {
  42866. const { done, value } = await reader.read();
  42867. if (value) {
  42868. chunks.push(value);
  42869. length += value.length;
  42870. }
  42871. isDone = done;
  42872. }
  42873. const collected = new Uint8Array(length);
  42874. let offset = 0;
  42875. for (const chunk of chunks) {
  42876. collected.set(chunk, offset);
  42877. offset += chunk.length;
  42878. }
  42879. return collected;
  42880. }
  42881. function readToBase64(blob) {
  42882. return new Promise((resolve, reject) => {
  42883. const reader = new FileReader();
  42884. reader.onloadend = () => {
  42885. if (reader.readyState !== 2) {
  42886. return reject(new Error("Reader aborted too early"));
  42887. }
  42888. const result = reader.result ?? "";
  42889. const commaIndex = result.indexOf(",");
  42890. const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
  42891. resolve(result.substring(dataOffset));
  42892. };
  42893. reader.onabort = () => reject(new Error("Read aborted"));
  42894. reader.onerror = () => reject(reader.error);
  42895. reader.readAsDataURL(blob);
  42896. });
  42897. }
  42898. var streamCollector2;
  42899. var init_stream_collector2 = __esm({
  42900. "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js"() {
  42901. "use strict";
  42902. init_dist_es11();
  42903. streamCollector2 = async (stream) => {
  42904. if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") {
  42905. if (Blob.prototype.arrayBuffer !== void 0) {
  42906. return new Uint8Array(await stream.arrayBuffer());
  42907. }
  42908. return collectBlob(stream);
  42909. }
  42910. return collectStream(stream);
  42911. };
  42912. }
  42913. });
  42914. // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/index.js
  42915. var init_dist_es15 = __esm({
  42916. "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-es/index.js"() {
  42917. "use strict";
  42918. init_fetch_http_handler();
  42919. init_stream_collector2();
  42920. }
  42921. });
  42922. // ../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-es/index.js
  42923. function fromHex(encoded) {
  42924. if (encoded.length % 2 !== 0) {
  42925. throw new Error("Hex encoded strings must have an even number length");
  42926. }
  42927. const out = new Uint8Array(encoded.length / 2);
  42928. for (let i6 = 0; i6 < encoded.length; i6 += 2) {
  42929. const encodedByte = encoded.slice(i6, i6 + 2).toLowerCase();
  42930. if (encodedByte in HEX_TO_SHORT) {
  42931. out[i6 / 2] = HEX_TO_SHORT[encodedByte];
  42932. } else {
  42933. throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
  42934. }
  42935. }
  42936. return out;
  42937. }
  42938. function toHex(bytes) {
  42939. let out = "";
  42940. for (let i6 = 0; i6 < bytes.byteLength; i6++) {
  42941. out += SHORT_TO_HEX[bytes[i6]];
  42942. }
  42943. return out;
  42944. }
  42945. var SHORT_TO_HEX, HEX_TO_SHORT;
  42946. var init_dist_es16 = __esm({
  42947. "../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-es/index.js"() {
  42948. "use strict";
  42949. SHORT_TO_HEX = {};
  42950. HEX_TO_SHORT = {};
  42951. for (let i6 = 0; i6 < 256; i6++) {
  42952. let encodedByte = i6.toString(16).toLowerCase();
  42953. if (encodedByte.length === 1) {
  42954. encodedByte = `0${encodedByte}`;
  42955. }
  42956. SHORT_TO_HEX[i6] = encodedByte;
  42957. HEX_TO_SHORT[encodedByte] = i6;
  42958. }
  42959. }
  42960. });
  42961. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js
  42962. var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED, sdkStreamMixin, isBlobInstance;
  42963. var init_sdk_stream_mixin_browser = __esm({
  42964. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js"() {
  42965. "use strict";
  42966. init_dist_es15();
  42967. init_dist_es11();
  42968. init_dist_es16();
  42969. init_dist_es10();
  42970. init_stream_type_check();
  42971. ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
  42972. sdkStreamMixin = (stream) => {
  42973. if (!isBlobInstance(stream) && !isReadableStream(stream)) {
  42974. const name = stream?.__proto__?.constructor?.name || stream;
  42975. throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`);
  42976. }
  42977. let transformed = false;
  42978. const transformToByteArray = async () => {
  42979. if (transformed) {
  42980. throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
  42981. }
  42982. transformed = true;
  42983. return await streamCollector2(stream);
  42984. };
  42985. const blobToWebStream = (blob) => {
  42986. if (typeof blob.stream !== "function") {
  42987. throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");
  42988. }
  42989. return blob.stream();
  42990. };
  42991. return Object.assign(stream, {
  42992. transformToByteArray,
  42993. transformToString: async (encoding) => {
  42994. const buf = await transformToByteArray();
  42995. if (encoding === "base64") {
  42996. return toBase64(buf);
  42997. } else if (encoding === "hex") {
  42998. return toHex(buf);
  42999. } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
  43000. return toUtf8(buf);
  43001. } else if (typeof TextDecoder === "function") {
  43002. return new TextDecoder(encoding).decode(buf);
  43003. } else {
  43004. throw new Error("TextDecoder is not available, please make sure polyfill is provided.");
  43005. }
  43006. },
  43007. transformToWebStream: () => {
  43008. if (transformed) {
  43009. throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
  43010. }
  43011. transformed = true;
  43012. if (isBlobInstance(stream)) {
  43013. return blobToWebStream(stream);
  43014. } else if (isReadableStream(stream)) {
  43015. return stream;
  43016. } else {
  43017. throw new Error(`Cannot transform payload to web stream, got ${stream}`);
  43018. }
  43019. }
  43020. });
  43021. };
  43022. isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob;
  43023. }
  43024. });
  43025. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js
  43026. import { Readable as Readable4 } from "stream";
  43027. var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2, sdkStreamMixin2;
  43028. var init_sdk_stream_mixin = __esm({
  43029. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js"() {
  43030. "use strict";
  43031. init_dist_es14();
  43032. init_dist_es9();
  43033. init_sdk_stream_mixin_browser();
  43034. ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2 = "The stream has already been transformed.";
  43035. sdkStreamMixin2 = (stream) => {
  43036. if (!(stream instanceof Readable4)) {
  43037. try {
  43038. return sdkStreamMixin(stream);
  43039. } catch (e6) {
  43040. const name = stream?.__proto__?.constructor?.name || stream;
  43041. throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`);
  43042. }
  43043. }
  43044. let transformed = false;
  43045. const transformToByteArray = async () => {
  43046. if (transformed) {
  43047. throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2);
  43048. }
  43049. transformed = true;
  43050. return await streamCollector(stream);
  43051. };
  43052. return Object.assign(stream, {
  43053. transformToByteArray,
  43054. transformToString: async (encoding) => {
  43055. const buf = await transformToByteArray();
  43056. if (encoding === void 0 || Buffer.isEncoding(encoding)) {
  43057. return fromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding);
  43058. } else {
  43059. const decoder = new TextDecoder(encoding);
  43060. return decoder.decode(buf);
  43061. }
  43062. },
  43063. transformToWebStream: () => {
  43064. if (transformed) {
  43065. throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2);
  43066. }
  43067. if (stream.readableFlowing !== null) {
  43068. throw new Error("The stream has been consumed by other callbacks.");
  43069. }
  43070. if (typeof Readable4.toWeb !== "function") {
  43071. throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");
  43072. }
  43073. transformed = true;
  43074. return Readable4.toWeb(stream);
  43075. }
  43076. });
  43077. };
  43078. }
  43079. });
  43080. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js
  43081. var init_splitStream_browser = __esm({
  43082. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js"() {
  43083. "use strict";
  43084. }
  43085. });
  43086. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.js
  43087. var init_splitStream = __esm({
  43088. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/splitStream.js"() {
  43089. "use strict";
  43090. init_splitStream_browser();
  43091. init_stream_type_check();
  43092. }
  43093. });
  43094. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/index.js
  43095. var init_dist_es17 = __esm({
  43096. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-es/index.js"() {
  43097. "use strict";
  43098. init_Uint8ArrayBlobAdapter();
  43099. init_ChecksumStream();
  43100. init_createChecksumStream();
  43101. init_createBufferedReadable();
  43102. init_getAwsChunkedEncodingStream();
  43103. init_headStream();
  43104. init_sdk_stream_mixin();
  43105. init_splitStream();
  43106. init_stream_type_check();
  43107. }
  43108. });
  43109. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js
  43110. var collectBody;
  43111. var init_collect_stream_body = __esm({
  43112. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() {
  43113. "use strict";
  43114. init_dist_es17();
  43115. collectBody = async (streamBody = new Uint8Array(), context) => {
  43116. if (streamBody instanceof Uint8Array) {
  43117. return Uint8ArrayBlobAdapter.mutate(streamBody);
  43118. }
  43119. if (!streamBody) {
  43120. return Uint8ArrayBlobAdapter.mutate(new Uint8Array());
  43121. }
  43122. const fromContext = context.streamCollector(streamBody);
  43123. return Uint8ArrayBlobAdapter.mutate(await fromContext);
  43124. };
  43125. }
  43126. });
  43127. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js
  43128. function extendedEncodeURIComponent(str) {
  43129. return encodeURIComponent(str).replace(/[!'()*]/g, function(c5) {
  43130. return "%" + c5.charCodeAt(0).toString(16).toUpperCase();
  43131. });
  43132. }
  43133. var init_extended_encode_uri_component = __esm({
  43134. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() {
  43135. "use strict";
  43136. }
  43137. });
  43138. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js
  43139. var init_deref = __esm({
  43140. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() {
  43141. "use strict";
  43142. }
  43143. });
  43144. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js
  43145. var init_schemaDeserializationMiddleware = __esm({
  43146. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() {
  43147. "use strict";
  43148. init_dist_es2();
  43149. init_dist_es6();
  43150. }
  43151. });
  43152. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js
  43153. var init_schemaSerializationMiddleware = __esm({
  43154. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() {
  43155. "use strict";
  43156. init_dist_es6();
  43157. }
  43158. });
  43159. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
  43160. var init_getSchemaSerdePlugin = __esm({
  43161. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() {
  43162. "use strict";
  43163. init_schemaDeserializationMiddleware();
  43164. init_schemaSerializationMiddleware();
  43165. }
  43166. });
  43167. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js
  43168. var TypeRegistry;
  43169. var init_TypeRegistry = __esm({
  43170. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() {
  43171. "use strict";
  43172. TypeRegistry = class _TypeRegistry {
  43173. constructor(namespace, schemas = /* @__PURE__ */ new Map()) {
  43174. this.namespace = namespace;
  43175. this.schemas = schemas;
  43176. }
  43177. static for(namespace) {
  43178. if (!_TypeRegistry.registries.has(namespace)) {
  43179. _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace));
  43180. }
  43181. return _TypeRegistry.registries.get(namespace);
  43182. }
  43183. register(shapeId, schema6) {
  43184. const qualifiedName = this.normalizeShapeId(shapeId);
  43185. const registry = _TypeRegistry.for(this.getNamespace(shapeId));
  43186. registry.schemas.set(qualifiedName, schema6);
  43187. }
  43188. getSchema(shapeId) {
  43189. const id = this.normalizeShapeId(shapeId);
  43190. if (!this.schemas.has(id)) {
  43191. throw new Error(`@smithy/core/schema - schema not found for ${id}`);
  43192. }
  43193. return this.schemas.get(id);
  43194. }
  43195. getBaseException() {
  43196. for (const [id, schema6] of this.schemas.entries()) {
  43197. if (id.startsWith("smithyts.client.synthetic.") && id.endsWith("ServiceException")) {
  43198. return schema6;
  43199. }
  43200. }
  43201. return void 0;
  43202. }
  43203. find(predicate) {
  43204. return [...this.schemas.values()].find(predicate);
  43205. }
  43206. destroy() {
  43207. _TypeRegistry.registries.delete(this.namespace);
  43208. this.schemas.clear();
  43209. }
  43210. normalizeShapeId(shapeId) {
  43211. if (shapeId.includes("#")) {
  43212. return shapeId;
  43213. }
  43214. return this.namespace + "#" + shapeId;
  43215. }
  43216. getNamespace(shapeId) {
  43217. return this.normalizeShapeId(shapeId).split("#")[0];
  43218. }
  43219. };
  43220. TypeRegistry.registries = /* @__PURE__ */ new Map();
  43221. }
  43222. });
  43223. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js
  43224. var init_Schema = __esm({
  43225. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() {
  43226. "use strict";
  43227. }
  43228. });
  43229. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js
  43230. var init_ListSchema = __esm({
  43231. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() {
  43232. "use strict";
  43233. init_TypeRegistry();
  43234. init_Schema();
  43235. }
  43236. });
  43237. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js
  43238. var init_MapSchema = __esm({
  43239. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() {
  43240. "use strict";
  43241. init_TypeRegistry();
  43242. init_Schema();
  43243. }
  43244. });
  43245. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js
  43246. var init_OperationSchema = __esm({
  43247. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() {
  43248. "use strict";
  43249. init_TypeRegistry();
  43250. init_Schema();
  43251. }
  43252. });
  43253. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js
  43254. var init_StructureSchema = __esm({
  43255. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() {
  43256. "use strict";
  43257. init_TypeRegistry();
  43258. init_Schema();
  43259. }
  43260. });
  43261. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js
  43262. var init_ErrorSchema = __esm({
  43263. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() {
  43264. "use strict";
  43265. init_TypeRegistry();
  43266. init_StructureSchema();
  43267. }
  43268. });
  43269. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js
  43270. var init_sentinels2 = __esm({
  43271. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() {
  43272. "use strict";
  43273. }
  43274. });
  43275. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js
  43276. var init_SimpleSchema = __esm({
  43277. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() {
  43278. "use strict";
  43279. init_TypeRegistry();
  43280. init_Schema();
  43281. }
  43282. });
  43283. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js
  43284. var init_NormalizedSchema = __esm({
  43285. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() {
  43286. "use strict";
  43287. init_deref();
  43288. init_ListSchema();
  43289. init_MapSchema();
  43290. init_sentinels2();
  43291. init_SimpleSchema();
  43292. init_StructureSchema();
  43293. }
  43294. });
  43295. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js
  43296. var init_schema2 = __esm({
  43297. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js"() {
  43298. "use strict";
  43299. init_deref();
  43300. init_getSchemaSerdePlugin();
  43301. init_ListSchema();
  43302. init_MapSchema();
  43303. init_OperationSchema();
  43304. init_ErrorSchema();
  43305. init_NormalizedSchema();
  43306. init_Schema();
  43307. init_SimpleSchema();
  43308. init_StructureSchema();
  43309. init_sentinels2();
  43310. init_TypeRegistry();
  43311. }
  43312. });
  43313. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js
  43314. var init_copyDocumentWithTransform = __esm({
  43315. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() {
  43316. "use strict";
  43317. init_schema2();
  43318. }
  43319. });
  43320. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js
  43321. var expectBoolean, expectNumber, MAX_FLOAT, expectFloat32, expectLong, expectInt32, expectShort, expectByte, expectSizedInt, castInt, expectNonNull, expectObject, expectString, expectUnion, strictParseFloat32, NUMBER_REGEX, parseNumber, limitedParseDouble, limitedParseFloat32, parseFloatString, strictParseInt32, strictParseShort, strictParseByte, stackTraceWarning, logger;
  43322. var init_parse_utils = __esm({
  43323. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() {
  43324. "use strict";
  43325. expectBoolean = (value) => {
  43326. if (value === null || value === void 0) {
  43327. return void 0;
  43328. }
  43329. if (typeof value === "number") {
  43330. if (value === 0 || value === 1) {
  43331. logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
  43332. }
  43333. if (value === 0) {
  43334. return false;
  43335. }
  43336. if (value === 1) {
  43337. return true;
  43338. }
  43339. }
  43340. if (typeof value === "string") {
  43341. const lower2 = value.toLowerCase();
  43342. if (lower2 === "false" || lower2 === "true") {
  43343. logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
  43344. }
  43345. if (lower2 === "false") {
  43346. return false;
  43347. }
  43348. if (lower2 === "true") {
  43349. return true;
  43350. }
  43351. }
  43352. if (typeof value === "boolean") {
  43353. return value;
  43354. }
  43355. throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`);
  43356. };
  43357. expectNumber = (value) => {
  43358. if (value === null || value === void 0) {
  43359. return void 0;
  43360. }
  43361. if (typeof value === "string") {
  43362. const parsed = parseFloat(value);
  43363. if (!Number.isNaN(parsed)) {
  43364. if (String(parsed) !== String(value)) {
  43365. logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`));
  43366. }
  43367. return parsed;
  43368. }
  43369. }
  43370. if (typeof value === "number") {
  43371. return value;
  43372. }
  43373. throw new TypeError(`Expected number, got ${typeof value}: ${value}`);
  43374. };
  43375. MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
  43376. expectFloat32 = (value) => {
  43377. const expected = expectNumber(value);
  43378. if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {
  43379. if (Math.abs(expected) > MAX_FLOAT) {
  43380. throw new TypeError(`Expected 32-bit float, got ${value}`);
  43381. }
  43382. }
  43383. return expected;
  43384. };
  43385. expectLong = (value) => {
  43386. if (value === null || value === void 0) {
  43387. return void 0;
  43388. }
  43389. if (Number.isInteger(value) && !Number.isNaN(value)) {
  43390. return value;
  43391. }
  43392. throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
  43393. };
  43394. expectInt32 = (value) => expectSizedInt(value, 32);
  43395. expectShort = (value) => expectSizedInt(value, 16);
  43396. expectByte = (value) => expectSizedInt(value, 8);
  43397. expectSizedInt = (value, size) => {
  43398. const expected = expectLong(value);
  43399. if (expected !== void 0 && castInt(expected, size) !== expected) {
  43400. throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
  43401. }
  43402. return expected;
  43403. };
  43404. castInt = (value, size) => {
  43405. switch (size) {
  43406. case 32:
  43407. return Int32Array.of(value)[0];
  43408. case 16:
  43409. return Int16Array.of(value)[0];
  43410. case 8:
  43411. return Int8Array.of(value)[0];
  43412. }
  43413. };
  43414. expectNonNull = (value, location) => {
  43415. if (value === null || value === void 0) {
  43416. if (location) {
  43417. throw new TypeError(`Expected a non-null value for ${location}`);
  43418. }
  43419. throw new TypeError("Expected a non-null value");
  43420. }
  43421. return value;
  43422. };
  43423. expectObject = (value) => {
  43424. if (value === null || value === void 0) {
  43425. return void 0;
  43426. }
  43427. if (typeof value === "object" && !Array.isArray(value)) {
  43428. return value;
  43429. }
  43430. const receivedType = Array.isArray(value) ? "array" : typeof value;
  43431. throw new TypeError(`Expected object, got ${receivedType}: ${value}`);
  43432. };
  43433. expectString = (value) => {
  43434. if (value === null || value === void 0) {
  43435. return void 0;
  43436. }
  43437. if (typeof value === "string") {
  43438. return value;
  43439. }
  43440. if (["boolean", "number", "bigint"].includes(typeof value)) {
  43441. logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
  43442. return String(value);
  43443. }
  43444. throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
  43445. };
  43446. expectUnion = (value) => {
  43447. if (value === null || value === void 0) {
  43448. return void 0;
  43449. }
  43450. const asObject = expectObject(value);
  43451. const setKeys = Object.entries(asObject).filter(([, v6]) => v6 != null).map(([k5]) => k5);
  43452. if (setKeys.length === 0) {
  43453. throw new TypeError(`Unions must have exactly one non-null member. None were found.`);
  43454. }
  43455. if (setKeys.length > 1) {
  43456. throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);
  43457. }
  43458. return asObject;
  43459. };
  43460. strictParseFloat32 = (value) => {
  43461. if (typeof value == "string") {
  43462. return expectFloat32(parseNumber(value));
  43463. }
  43464. return expectFloat32(value);
  43465. };
  43466. NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
  43467. parseNumber = (value) => {
  43468. const matches = value.match(NUMBER_REGEX);
  43469. if (matches === null || matches[0].length !== value.length) {
  43470. throw new TypeError(`Expected real number, got implicit NaN`);
  43471. }
  43472. return parseFloat(value);
  43473. };
  43474. limitedParseDouble = (value) => {
  43475. if (typeof value == "string") {
  43476. return parseFloatString(value);
  43477. }
  43478. return expectNumber(value);
  43479. };
  43480. limitedParseFloat32 = (value) => {
  43481. if (typeof value == "string") {
  43482. return parseFloatString(value);
  43483. }
  43484. return expectFloat32(value);
  43485. };
  43486. parseFloatString = (value) => {
  43487. switch (value) {
  43488. case "NaN":
  43489. return NaN;
  43490. case "Infinity":
  43491. return Infinity;
  43492. case "-Infinity":
  43493. return -Infinity;
  43494. default:
  43495. throw new Error(`Unable to parse float value: ${value}`);
  43496. }
  43497. };
  43498. strictParseInt32 = (value) => {
  43499. if (typeof value === "string") {
  43500. return expectInt32(parseNumber(value));
  43501. }
  43502. return expectInt32(value);
  43503. };
  43504. strictParseShort = (value) => {
  43505. if (typeof value === "string") {
  43506. return expectShort(parseNumber(value));
  43507. }
  43508. return expectShort(value);
  43509. };
  43510. strictParseByte = (value) => {
  43511. if (typeof value === "string") {
  43512. return expectByte(parseNumber(value));
  43513. }
  43514. return expectByte(value);
  43515. };
  43516. stackTraceWarning = (message) => {
  43517. return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s6) => !s6.includes("stackTraceWarning")).join("\n");
  43518. };
  43519. logger = {
  43520. warn: console.warn
  43521. };
  43522. }
  43523. });
  43524. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js
  43525. var MONTHS, RFC3339, parseRfc3339DateTime, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, buildDate, FIFTY_YEARS_IN_MILLIS, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes;
  43526. var init_date_utils = __esm({
  43527. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() {
  43528. "use strict";
  43529. init_parse_utils();
  43530. MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  43531. RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
  43532. parseRfc3339DateTime = (value) => {
  43533. if (value === null || value === void 0) {
  43534. return void 0;
  43535. }
  43536. if (typeof value !== "string") {
  43537. throw new TypeError("RFC-3339 date-times must be expressed as strings");
  43538. }
  43539. const match2 = RFC3339.exec(value);
  43540. if (!match2) {
  43541. throw new TypeError("Invalid RFC-3339 date-time value");
  43542. }
  43543. const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
  43544. const year = strictParseShort(stripLeadingZeroes(yearStr));
  43545. const month = parseDateValue(monthStr, "month", 1, 12);
  43546. const day = parseDateValue(dayStr, "day", 1, 31);
  43547. return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
  43548. };
  43549. RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
  43550. parseRfc3339DateTimeWithOffset = (value) => {
  43551. if (value === null || value === void 0) {
  43552. return void 0;
  43553. }
  43554. if (typeof value !== "string") {
  43555. throw new TypeError("RFC-3339 date-times must be expressed as strings");
  43556. }
  43557. const match2 = RFC3339_WITH_OFFSET.exec(value);
  43558. if (!match2) {
  43559. throw new TypeError("Invalid RFC-3339 date-time value");
  43560. }
  43561. const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2;
  43562. const year = strictParseShort(stripLeadingZeroes(yearStr));
  43563. const month = parseDateValue(monthStr, "month", 1, 12);
  43564. const day = parseDateValue(dayStr, "day", 1, 31);
  43565. const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
  43566. if (offsetStr.toUpperCase() != "Z") {
  43567. date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr));
  43568. }
  43569. return date;
  43570. };
  43571. IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
  43572. RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
  43573. ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
  43574. buildDate = (year, month, day, time) => {
  43575. const adjustedMonth = month - 1;
  43576. validateDayOfMonth(year, adjustedMonth, day);
  43577. return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds)));
  43578. };
  43579. FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3;
  43580. DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  43581. validateDayOfMonth = (year, month, day) => {
  43582. let maxDays = DAYS_IN_MONTH[month];
  43583. if (month === 1 && isLeapYear(year)) {
  43584. maxDays = 29;
  43585. }
  43586. if (day > maxDays) {
  43587. throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);
  43588. }
  43589. };
  43590. isLeapYear = (year) => {
  43591. return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  43592. };
  43593. parseDateValue = (value, type, lower2, upper) => {
  43594. const dateVal = strictParseByte(stripLeadingZeroes(value));
  43595. if (dateVal < lower2 || dateVal > upper) {
  43596. throw new TypeError(`${type} must be between ${lower2} and ${upper}, inclusive`);
  43597. }
  43598. return dateVal;
  43599. };
  43600. parseMilliseconds = (value) => {
  43601. if (value === null || value === void 0) {
  43602. return 0;
  43603. }
  43604. return strictParseFloat32("0." + value) * 1e3;
  43605. };
  43606. parseOffsetToMilliseconds = (value) => {
  43607. const directionStr = value[0];
  43608. let direction = 1;
  43609. if (directionStr == "+") {
  43610. direction = 1;
  43611. } else if (directionStr == "-") {
  43612. direction = -1;
  43613. } else {
  43614. throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
  43615. }
  43616. const hour = Number(value.substring(1, 3));
  43617. const minute = Number(value.substring(4, 6));
  43618. return direction * (hour * 60 + minute) * 60 * 1e3;
  43619. };
  43620. stripLeadingZeroes = (value) => {
  43621. let idx = 0;
  43622. while (idx < value.length - 1 && value.charAt(idx) === "0") {
  43623. idx++;
  43624. }
  43625. if (idx === 0) {
  43626. return value;
  43627. }
  43628. return value.slice(idx);
  43629. };
  43630. }
  43631. });
  43632. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js
  43633. var LazyJsonString;
  43634. var init_lazy_json = __esm({
  43635. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() {
  43636. "use strict";
  43637. LazyJsonString = function LazyJsonString2(val2) {
  43638. const str = Object.assign(new String(val2), {
  43639. deserializeJSON() {
  43640. return JSON.parse(String(val2));
  43641. },
  43642. toString() {
  43643. return String(val2);
  43644. },
  43645. toJSON() {
  43646. return String(val2);
  43647. }
  43648. });
  43649. return str;
  43650. };
  43651. LazyJsonString.from = (object) => {
  43652. if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) {
  43653. return object;
  43654. } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) {
  43655. return LazyJsonString(String(object));
  43656. }
  43657. return LazyJsonString(JSON.stringify(object));
  43658. };
  43659. LazyJsonString.fromObject = LazyJsonString.from;
  43660. }
  43661. });
  43662. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js
  43663. var init_quote_header = __esm({
  43664. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() {
  43665. "use strict";
  43666. }
  43667. });
  43668. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js
  43669. var init_split_every = __esm({
  43670. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() {
  43671. "use strict";
  43672. }
  43673. });
  43674. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js
  43675. var init_split_header = __esm({
  43676. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() {
  43677. "use strict";
  43678. }
  43679. });
  43680. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js
  43681. var init_NumericValue = __esm({
  43682. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() {
  43683. "use strict";
  43684. }
  43685. });
  43686. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js
  43687. var init_serde2 = __esm({
  43688. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js"() {
  43689. "use strict";
  43690. init_copyDocumentWithTransform();
  43691. init_date_utils();
  43692. init_lazy_json();
  43693. init_parse_utils();
  43694. init_quote_header();
  43695. init_split_every();
  43696. init_split_header();
  43697. init_NumericValue();
  43698. }
  43699. });
  43700. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js
  43701. var init_HttpProtocol = __esm({
  43702. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() {
  43703. "use strict";
  43704. init_schema2();
  43705. init_serde2();
  43706. init_dist_es2();
  43707. init_dist_es17();
  43708. init_collect_stream_body();
  43709. }
  43710. });
  43711. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js
  43712. var init_HttpBindingProtocol = __esm({
  43713. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() {
  43714. "use strict";
  43715. init_schema2();
  43716. init_dist_es2();
  43717. init_collect_stream_body();
  43718. init_extended_encode_uri_component();
  43719. init_HttpProtocol();
  43720. }
  43721. });
  43722. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js
  43723. var init_RpcProtocol = __esm({
  43724. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() {
  43725. "use strict";
  43726. init_schema2();
  43727. init_dist_es2();
  43728. init_collect_stream_body();
  43729. init_HttpProtocol();
  43730. }
  43731. });
  43732. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js
  43733. var resolvedPath;
  43734. var init_resolve_path = __esm({
  43735. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() {
  43736. "use strict";
  43737. init_extended_encode_uri_component();
  43738. resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
  43739. if (input != null && input[memberName] !== void 0) {
  43740. const labelValue = labelValueProvider();
  43741. if (labelValue.length <= 0) {
  43742. throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
  43743. }
  43744. resolvedPath2 = resolvedPath2.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue));
  43745. } else {
  43746. throw new Error("No value provided for input HTTP label: " + memberName + ".");
  43747. }
  43748. return resolvedPath2;
  43749. };
  43750. }
  43751. });
  43752. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js
  43753. function requestBuilder(input, context) {
  43754. return new RequestBuilder(input, context);
  43755. }
  43756. var RequestBuilder;
  43757. var init_requestBuilder = __esm({
  43758. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() {
  43759. "use strict";
  43760. init_dist_es2();
  43761. init_resolve_path();
  43762. RequestBuilder = class {
  43763. constructor(input, context) {
  43764. this.input = input;
  43765. this.context = context;
  43766. this.query = {};
  43767. this.method = "";
  43768. this.headers = {};
  43769. this.path = "";
  43770. this.body = null;
  43771. this.hostname = "";
  43772. this.resolvePathStack = [];
  43773. }
  43774. async build() {
  43775. const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint();
  43776. this.path = basePath;
  43777. for (const resolvePath of this.resolvePathStack) {
  43778. resolvePath(this.path);
  43779. }
  43780. return new HttpRequest({
  43781. protocol,
  43782. hostname: this.hostname || hostname,
  43783. port,
  43784. method: this.method,
  43785. path: this.path,
  43786. query: this.query,
  43787. body: this.body,
  43788. headers: this.headers
  43789. });
  43790. }
  43791. hn(hostname) {
  43792. this.hostname = hostname;
  43793. return this;
  43794. }
  43795. bp(uriLabel) {
  43796. this.resolvePathStack.push((basePath) => {
  43797. this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
  43798. });
  43799. return this;
  43800. }
  43801. p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
  43802. this.resolvePathStack.push((path3) => {
  43803. this.path = resolvedPath(path3, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
  43804. });
  43805. return this;
  43806. }
  43807. h(headers) {
  43808. this.headers = headers;
  43809. return this;
  43810. }
  43811. q(query) {
  43812. this.query = query;
  43813. return this;
  43814. }
  43815. b(body) {
  43816. this.body = body;
  43817. return this;
  43818. }
  43819. m(method) {
  43820. this.method = method;
  43821. return this;
  43822. }
  43823. };
  43824. }
  43825. });
  43826. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js
  43827. var init_determineTimestampFormat = __esm({
  43828. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() {
  43829. "use strict";
  43830. init_schema2();
  43831. }
  43832. });
  43833. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js
  43834. var init_FromStringShapeDeserializer = __esm({
  43835. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() {
  43836. "use strict";
  43837. init_schema2();
  43838. init_serde2();
  43839. init_dist_es11();
  43840. init_dist_es10();
  43841. init_determineTimestampFormat();
  43842. }
  43843. });
  43844. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js
  43845. var init_HttpInterceptingShapeDeserializer = __esm({
  43846. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() {
  43847. "use strict";
  43848. init_schema2();
  43849. init_dist_es10();
  43850. init_FromStringShapeDeserializer();
  43851. }
  43852. });
  43853. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js
  43854. var init_ToStringShapeSerializer = __esm({
  43855. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() {
  43856. "use strict";
  43857. init_schema2();
  43858. init_serde2();
  43859. init_dist_es11();
  43860. init_determineTimestampFormat();
  43861. }
  43862. });
  43863. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js
  43864. var init_HttpInterceptingShapeSerializer = __esm({
  43865. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() {
  43866. "use strict";
  43867. init_schema2();
  43868. init_ToStringShapeSerializer();
  43869. }
  43870. });
  43871. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js
  43872. var init_protocols = __esm({
  43873. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() {
  43874. "use strict";
  43875. init_collect_stream_body();
  43876. init_extended_encode_uri_component();
  43877. init_HttpBindingProtocol();
  43878. init_RpcProtocol();
  43879. init_requestBuilder();
  43880. init_resolve_path();
  43881. init_FromStringShapeDeserializer();
  43882. init_HttpInterceptingShapeDeserializer();
  43883. init_HttpInterceptingShapeSerializer();
  43884. init_ToStringShapeSerializer();
  43885. init_determineTimestampFormat();
  43886. }
  43887. });
  43888. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js
  43889. var init_requestBuilder2 = __esm({
  43890. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() {
  43891. "use strict";
  43892. init_protocols();
  43893. }
  43894. });
  43895. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js
  43896. function setFeature(context, feature, value) {
  43897. if (!context.__smithy_context) {
  43898. context.__smithy_context = {
  43899. features: {}
  43900. };
  43901. } else if (!context.__smithy_context.features) {
  43902. context.__smithy_context.features = {};
  43903. }
  43904. context.__smithy_context.features[feature] = value;
  43905. }
  43906. var init_setFeature = __esm({
  43907. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js"() {
  43908. "use strict";
  43909. }
  43910. });
  43911. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
  43912. var DefaultIdentityProviderConfig;
  43913. var init_DefaultIdentityProviderConfig = __esm({
  43914. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() {
  43915. "use strict";
  43916. DefaultIdentityProviderConfig = class {
  43917. constructor(config) {
  43918. this.authSchemes = /* @__PURE__ */ new Map();
  43919. for (const [key, value] of Object.entries(config)) {
  43920. if (value !== void 0) {
  43921. this.authSchemes.set(key, value);
  43922. }
  43923. }
  43924. }
  43925. getIdentityProvider(schemeId) {
  43926. return this.authSchemes.get(schemeId);
  43927. }
  43928. };
  43929. }
  43930. });
  43931. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
  43932. var init_httpApiKeyAuth = __esm({
  43933. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() {
  43934. "use strict";
  43935. init_dist_es2();
  43936. init_dist_es();
  43937. }
  43938. });
  43939. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
  43940. var init_httpBearerAuth = __esm({
  43941. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() {
  43942. "use strict";
  43943. init_dist_es2();
  43944. }
  43945. });
  43946. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
  43947. var NoAuthSigner;
  43948. var init_noAuth = __esm({
  43949. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() {
  43950. "use strict";
  43951. NoAuthSigner = class {
  43952. async sign(httpRequest2, identity, signingProperties) {
  43953. return httpRequest2;
  43954. }
  43955. };
  43956. }
  43957. });
  43958. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
  43959. var init_httpAuthSchemes = __esm({
  43960. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() {
  43961. "use strict";
  43962. init_httpApiKeyAuth();
  43963. init_httpBearerAuth();
  43964. init_noAuth();
  43965. }
  43966. });
  43967. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
  43968. var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider;
  43969. var init_memoizeIdentityProvider = __esm({
  43970. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() {
  43971. "use strict";
  43972. createIsIdentityExpiredFunction = (expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs;
  43973. EXPIRATION_MS = 3e5;
  43974. isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
  43975. doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0;
  43976. memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {
  43977. if (provider === void 0) {
  43978. return void 0;
  43979. }
  43980. const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
  43981. let resolved;
  43982. let pending;
  43983. let hasResult;
  43984. let isConstant = false;
  43985. const coalesceProvider = async (options) => {
  43986. if (!pending) {
  43987. pending = normalizedProvider(options);
  43988. }
  43989. try {
  43990. resolved = await pending;
  43991. hasResult = true;
  43992. isConstant = false;
  43993. } finally {
  43994. pending = void 0;
  43995. }
  43996. return resolved;
  43997. };
  43998. if (isExpired === void 0) {
  43999. return async (options) => {
  44000. if (!hasResult || options?.forceRefresh) {
  44001. resolved = await coalesceProvider(options);
  44002. }
  44003. return resolved;
  44004. };
  44005. }
  44006. return async (options) => {
  44007. if (!hasResult || options?.forceRefresh) {
  44008. resolved = await coalesceProvider(options);
  44009. }
  44010. if (isConstant) {
  44011. return resolved;
  44012. }
  44013. if (!requiresRefresh(resolved)) {
  44014. isConstant = true;
  44015. return resolved;
  44016. }
  44017. if (isExpired(resolved)) {
  44018. await coalesceProvider(options);
  44019. return resolved;
  44020. }
  44021. return resolved;
  44022. };
  44023. };
  44024. }
  44025. });
  44026. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
  44027. var init_util_identity_and_auth = __esm({
  44028. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() {
  44029. "use strict";
  44030. init_DefaultIdentityProviderConfig();
  44031. init_httpAuthSchemes();
  44032. init_memoizeIdentityProvider();
  44033. }
  44034. });
  44035. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js
  44036. var init_dist_es18 = __esm({
  44037. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js"() {
  44038. "use strict";
  44039. init_getSmithyContext();
  44040. init_middleware_http_auth_scheme();
  44041. init_middleware_http_signing();
  44042. init_normalizeProvider2();
  44043. init_createPaginator();
  44044. init_requestBuilder2();
  44045. init_setFeature();
  44046. init_util_identity_and_auth();
  44047. }
  44048. });
  44049. // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js
  44050. function isValidUserAgentAppId(appId) {
  44051. if (appId === void 0) {
  44052. return true;
  44053. }
  44054. return typeof appId === "string" && appId.length <= 50;
  44055. }
  44056. function resolveUserAgentConfig(input) {
  44057. const normalizedAppIdProvider = normalizeProvider2(input.userAgentAppId ?? DEFAULT_UA_APP_ID);
  44058. const { customUserAgent } = input;
  44059. return Object.assign(input, {
  44060. customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent,
  44061. userAgentAppId: async () => {
  44062. const appId = await normalizedAppIdProvider();
  44063. if (!isValidUserAgentAppId(appId)) {
  44064. const logger2 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger;
  44065. if (typeof appId !== "string") {
  44066. logger2?.warn("userAgentAppId must be a string or undefined.");
  44067. } else if (appId.length > 50) {
  44068. logger2?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
  44069. }
  44070. }
  44071. return appId;
  44072. }
  44073. });
  44074. }
  44075. var DEFAULT_UA_APP_ID;
  44076. var init_configurations = __esm({
  44077. "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js"() {
  44078. "use strict";
  44079. init_dist_es18();
  44080. DEFAULT_UA_APP_ID = void 0;
  44081. }
  44082. });
  44083. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js
  44084. var EndpointCache;
  44085. var init_EndpointCache = __esm({
  44086. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js"() {
  44087. "use strict";
  44088. EndpointCache = class {
  44089. constructor({ size, params }) {
  44090. this.data = /* @__PURE__ */ new Map();
  44091. this.parameters = [];
  44092. this.capacity = size ?? 50;
  44093. if (params) {
  44094. this.parameters = params;
  44095. }
  44096. }
  44097. get(endpointParams, resolver) {
  44098. const key = this.hash(endpointParams);
  44099. if (key === false) {
  44100. return resolver();
  44101. }
  44102. if (!this.data.has(key)) {
  44103. if (this.data.size > this.capacity + 10) {
  44104. const keys = this.data.keys();
  44105. let i6 = 0;
  44106. while (true) {
  44107. const { value, done } = keys.next();
  44108. this.data.delete(value);
  44109. if (done || ++i6 > 10) {
  44110. break;
  44111. }
  44112. }
  44113. }
  44114. this.data.set(key, resolver());
  44115. }
  44116. return this.data.get(key);
  44117. }
  44118. size() {
  44119. return this.data.size;
  44120. }
  44121. hash(endpointParams) {
  44122. let buffer = "";
  44123. const { parameters } = this;
  44124. if (parameters.length === 0) {
  44125. return false;
  44126. }
  44127. for (const param of parameters) {
  44128. const val2 = String(endpointParams[param] ?? "");
  44129. if (val2.includes("|;")) {
  44130. return false;
  44131. }
  44132. buffer += val2 + "|;";
  44133. }
  44134. return buffer;
  44135. }
  44136. };
  44137. }
  44138. });
  44139. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js
  44140. var IP_V4_REGEX, isIpAddress;
  44141. var init_isIpAddress = __esm({
  44142. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js"() {
  44143. "use strict";
  44144. IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`);
  44145. isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]");
  44146. }
  44147. });
  44148. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js
  44149. var VALID_HOST_LABEL_REGEX, isValidHostLabel;
  44150. var init_isValidHostLabel = __esm({
  44151. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js"() {
  44152. "use strict";
  44153. VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
  44154. isValidHostLabel = (value, allowSubDomains = false) => {
  44155. if (!allowSubDomains) {
  44156. return VALID_HOST_LABEL_REGEX.test(value);
  44157. }
  44158. const labels = value.split(".");
  44159. for (const label of labels) {
  44160. if (!isValidHostLabel(label)) {
  44161. return false;
  44162. }
  44163. }
  44164. return true;
  44165. };
  44166. }
  44167. });
  44168. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js
  44169. var customEndpointFunctions;
  44170. var init_customEndpointFunctions = __esm({
  44171. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js"() {
  44172. "use strict";
  44173. customEndpointFunctions = {};
  44174. }
  44175. });
  44176. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js
  44177. var debugId;
  44178. var init_debugId = __esm({
  44179. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js"() {
  44180. "use strict";
  44181. debugId = "endpoints";
  44182. }
  44183. });
  44184. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js
  44185. function toDebugString(input) {
  44186. if (typeof input !== "object" || input == null) {
  44187. return input;
  44188. }
  44189. if ("ref" in input) {
  44190. return `$${toDebugString(input.ref)}`;
  44191. }
  44192. if ("fn" in input) {
  44193. return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`;
  44194. }
  44195. return JSON.stringify(input, null, 2);
  44196. }
  44197. var init_toDebugString = __esm({
  44198. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js"() {
  44199. "use strict";
  44200. }
  44201. });
  44202. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/index.js
  44203. var init_debug = __esm({
  44204. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/debug/index.js"() {
  44205. "use strict";
  44206. init_debugId();
  44207. init_toDebugString();
  44208. }
  44209. });
  44210. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js
  44211. var EndpointError;
  44212. var init_EndpointError = __esm({
  44213. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js"() {
  44214. "use strict";
  44215. EndpointError = class extends Error {
  44216. constructor(message) {
  44217. super(message);
  44218. this.name = "EndpointError";
  44219. }
  44220. };
  44221. }
  44222. });
  44223. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js
  44224. var init_EndpointFunctions = __esm({
  44225. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js"() {
  44226. "use strict";
  44227. }
  44228. });
  44229. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js
  44230. var init_EndpointRuleObject2 = __esm({
  44231. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js"() {
  44232. "use strict";
  44233. }
  44234. });
  44235. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js
  44236. var init_ErrorRuleObject2 = __esm({
  44237. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js"() {
  44238. "use strict";
  44239. }
  44240. });
  44241. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js
  44242. var init_RuleSetObject2 = __esm({
  44243. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js"() {
  44244. "use strict";
  44245. }
  44246. });
  44247. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js
  44248. var init_TreeRuleObject2 = __esm({
  44249. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js"() {
  44250. "use strict";
  44251. }
  44252. });
  44253. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/shared.js
  44254. var init_shared2 = __esm({
  44255. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/shared.js"() {
  44256. "use strict";
  44257. }
  44258. });
  44259. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/index.js
  44260. var init_types3 = __esm({
  44261. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/types/index.js"() {
  44262. "use strict";
  44263. init_EndpointError();
  44264. init_EndpointFunctions();
  44265. init_EndpointRuleObject2();
  44266. init_ErrorRuleObject2();
  44267. init_RuleSetObject2();
  44268. init_TreeRuleObject2();
  44269. init_shared2();
  44270. }
  44271. });
  44272. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js
  44273. var booleanEquals;
  44274. var init_booleanEquals = __esm({
  44275. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js"() {
  44276. "use strict";
  44277. booleanEquals = (value1, value2) => value1 === value2;
  44278. }
  44279. });
  44280. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js
  44281. var getAttrPathList;
  44282. var init_getAttrPathList = __esm({
  44283. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js"() {
  44284. "use strict";
  44285. init_types3();
  44286. getAttrPathList = (path3) => {
  44287. const parts = path3.split(".");
  44288. const pathList = [];
  44289. for (const part of parts) {
  44290. const squareBracketIndex = part.indexOf("[");
  44291. if (squareBracketIndex !== -1) {
  44292. if (part.indexOf("]") !== part.length - 1) {
  44293. throw new EndpointError(`Path: '${path3}' does not end with ']'`);
  44294. }
  44295. const arrayIndex = part.slice(squareBracketIndex + 1, -1);
  44296. if (Number.isNaN(parseInt(arrayIndex))) {
  44297. throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path3}'`);
  44298. }
  44299. if (squareBracketIndex !== 0) {
  44300. pathList.push(part.slice(0, squareBracketIndex));
  44301. }
  44302. pathList.push(arrayIndex);
  44303. } else {
  44304. pathList.push(part);
  44305. }
  44306. }
  44307. return pathList;
  44308. };
  44309. }
  44310. });
  44311. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js
  44312. var getAttr;
  44313. var init_getAttr = __esm({
  44314. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js"() {
  44315. "use strict";
  44316. init_types3();
  44317. init_getAttrPathList();
  44318. getAttr = (value, path3) => getAttrPathList(path3).reduce((acc, index6) => {
  44319. if (typeof acc !== "object") {
  44320. throw new EndpointError(`Index '${index6}' in '${path3}' not found in '${JSON.stringify(value)}'`);
  44321. } else if (Array.isArray(acc)) {
  44322. return acc[parseInt(index6)];
  44323. }
  44324. return acc[index6];
  44325. }, value);
  44326. }
  44327. });
  44328. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js
  44329. var isSet;
  44330. var init_isSet = __esm({
  44331. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js"() {
  44332. "use strict";
  44333. isSet = (value) => value != null;
  44334. }
  44335. });
  44336. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/not.js
  44337. var not;
  44338. var init_not = __esm({
  44339. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/not.js"() {
  44340. "use strict";
  44341. not = (value) => !value;
  44342. }
  44343. });
  44344. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js
  44345. var DEFAULT_PORTS, parseURL;
  44346. var init_parseURL = __esm({
  44347. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js"() {
  44348. "use strict";
  44349. init_dist_es();
  44350. init_isIpAddress();
  44351. DEFAULT_PORTS = {
  44352. [EndpointURLScheme.HTTP]: 80,
  44353. [EndpointURLScheme.HTTPS]: 443
  44354. };
  44355. parseURL = (value) => {
  44356. const whatwgURL = (() => {
  44357. try {
  44358. if (value instanceof URL) {
  44359. return value;
  44360. }
  44361. if (typeof value === "object" && "hostname" in value) {
  44362. const { hostname: hostname2, port, protocol: protocol2 = "", path: path3 = "", query = {} } = value;
  44363. const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path3}`);
  44364. url.search = Object.entries(query).map(([k5, v6]) => `${k5}=${v6}`).join("&");
  44365. return url;
  44366. }
  44367. return new URL(value);
  44368. } catch (error2) {
  44369. return null;
  44370. }
  44371. })();
  44372. if (!whatwgURL) {
  44373. console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
  44374. return null;
  44375. }
  44376. const urlString = whatwgURL.href;
  44377. const { host, hostname, pathname, protocol, search } = whatwgURL;
  44378. if (search) {
  44379. return null;
  44380. }
  44381. const scheme = protocol.slice(0, -1);
  44382. if (!Object.values(EndpointURLScheme).includes(scheme)) {
  44383. return null;
  44384. }
  44385. const isIp = isIpAddress(hostname);
  44386. const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`);
  44387. const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`;
  44388. return {
  44389. scheme,
  44390. authority,
  44391. path: pathname,
  44392. normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
  44393. isIp
  44394. };
  44395. };
  44396. }
  44397. });
  44398. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js
  44399. var stringEquals;
  44400. var init_stringEquals = __esm({
  44401. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js"() {
  44402. "use strict";
  44403. stringEquals = (value1, value2) => value1 === value2;
  44404. }
  44405. });
  44406. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js
  44407. var substring;
  44408. var init_substring = __esm({
  44409. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js"() {
  44410. "use strict";
  44411. substring = (input, start, stop, reverse) => {
  44412. if (start >= stop || input.length < stop) {
  44413. return null;
  44414. }
  44415. if (!reverse) {
  44416. return input.substring(start, stop);
  44417. }
  44418. return input.substring(input.length - stop, input.length - start);
  44419. };
  44420. }
  44421. });
  44422. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js
  44423. var uriEncode;
  44424. var init_uriEncode = __esm({
  44425. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js"() {
  44426. "use strict";
  44427. uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`);
  44428. }
  44429. });
  44430. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/index.js
  44431. var init_lib = __esm({
  44432. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/lib/index.js"() {
  44433. "use strict";
  44434. init_booleanEquals();
  44435. init_getAttr();
  44436. init_isSet();
  44437. init_isValidHostLabel();
  44438. init_not();
  44439. init_parseURL();
  44440. init_stringEquals();
  44441. init_substring();
  44442. init_uriEncode();
  44443. }
  44444. });
  44445. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js
  44446. var endpointFunctions;
  44447. var init_endpointFunctions = __esm({
  44448. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js"() {
  44449. "use strict";
  44450. init_lib();
  44451. endpointFunctions = {
  44452. booleanEquals,
  44453. getAttr,
  44454. isSet,
  44455. isValidHostLabel,
  44456. not,
  44457. parseURL,
  44458. stringEquals,
  44459. substring,
  44460. uriEncode
  44461. };
  44462. }
  44463. });
  44464. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js
  44465. var evaluateTemplate;
  44466. var init_evaluateTemplate = __esm({
  44467. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js"() {
  44468. "use strict";
  44469. init_lib();
  44470. evaluateTemplate = (template, options) => {
  44471. const evaluatedTemplateArr = [];
  44472. const templateContext = {
  44473. ...options.endpointParams,
  44474. ...options.referenceRecord
  44475. };
  44476. let currentIndex = 0;
  44477. while (currentIndex < template.length) {
  44478. const openingBraceIndex = template.indexOf("{", currentIndex);
  44479. if (openingBraceIndex === -1) {
  44480. evaluatedTemplateArr.push(template.slice(currentIndex));
  44481. break;
  44482. }
  44483. evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
  44484. const closingBraceIndex = template.indexOf("}", openingBraceIndex);
  44485. if (closingBraceIndex === -1) {
  44486. evaluatedTemplateArr.push(template.slice(openingBraceIndex));
  44487. break;
  44488. }
  44489. if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
  44490. evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
  44491. currentIndex = closingBraceIndex + 2;
  44492. }
  44493. const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
  44494. if (parameterName.includes("#")) {
  44495. const [refName, attrName] = parameterName.split("#");
  44496. evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
  44497. } else {
  44498. evaluatedTemplateArr.push(templateContext[parameterName]);
  44499. }
  44500. currentIndex = closingBraceIndex + 1;
  44501. }
  44502. return evaluatedTemplateArr.join("");
  44503. };
  44504. }
  44505. });
  44506. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js
  44507. var getReferenceValue;
  44508. var init_getReferenceValue = __esm({
  44509. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js"() {
  44510. "use strict";
  44511. getReferenceValue = ({ ref }, options) => {
  44512. const referenceRecord = {
  44513. ...options.endpointParams,
  44514. ...options.referenceRecord
  44515. };
  44516. return referenceRecord[ref];
  44517. };
  44518. }
  44519. });
  44520. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js
  44521. var evaluateExpression;
  44522. var init_evaluateExpression = __esm({
  44523. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js"() {
  44524. "use strict";
  44525. init_types3();
  44526. init_callFunction();
  44527. init_evaluateTemplate();
  44528. init_getReferenceValue();
  44529. evaluateExpression = (obj, keyName, options) => {
  44530. if (typeof obj === "string") {
  44531. return evaluateTemplate(obj, options);
  44532. } else if (obj["fn"]) {
  44533. return callFunction(obj, options);
  44534. } else if (obj["ref"]) {
  44535. return getReferenceValue(obj, options);
  44536. }
  44537. throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
  44538. };
  44539. }
  44540. });
  44541. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js
  44542. var callFunction;
  44543. var init_callFunction = __esm({
  44544. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js"() {
  44545. "use strict";
  44546. init_customEndpointFunctions();
  44547. init_endpointFunctions();
  44548. init_evaluateExpression();
  44549. callFunction = ({ fn, argv }, options) => {
  44550. const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options));
  44551. const fnSegments = fn.split(".");
  44552. if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) {
  44553. return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs);
  44554. }
  44555. return endpointFunctions[fn](...evaluatedArgs);
  44556. };
  44557. }
  44558. });
  44559. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js
  44560. var evaluateCondition;
  44561. var init_evaluateCondition = __esm({
  44562. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js"() {
  44563. "use strict";
  44564. init_debug();
  44565. init_types3();
  44566. init_callFunction();
  44567. evaluateCondition = ({ assign, ...fnArgs }, options) => {
  44568. if (assign && assign in options.referenceRecord) {
  44569. throw new EndpointError(`'${assign}' is already defined in Reference Record.`);
  44570. }
  44571. const value = callFunction(fnArgs, options);
  44572. options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);
  44573. return {
  44574. result: value === "" ? true : !!value,
  44575. ...assign != null && { toAssign: { name: assign, value } }
  44576. };
  44577. };
  44578. }
  44579. });
  44580. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js
  44581. var evaluateConditions;
  44582. var init_evaluateConditions = __esm({
  44583. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js"() {
  44584. "use strict";
  44585. init_debug();
  44586. init_evaluateCondition();
  44587. evaluateConditions = (conditions = [], options) => {
  44588. const conditionsReferenceRecord = {};
  44589. for (const condition of conditions) {
  44590. const { result, toAssign } = evaluateCondition(condition, {
  44591. ...options,
  44592. referenceRecord: {
  44593. ...options.referenceRecord,
  44594. ...conditionsReferenceRecord
  44595. }
  44596. });
  44597. if (!result) {
  44598. return { result };
  44599. }
  44600. if (toAssign) {
  44601. conditionsReferenceRecord[toAssign.name] = toAssign.value;
  44602. options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
  44603. }
  44604. }
  44605. return { result: true, referenceRecord: conditionsReferenceRecord };
  44606. };
  44607. }
  44608. });
  44609. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js
  44610. var getEndpointHeaders;
  44611. var init_getEndpointHeaders = __esm({
  44612. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js"() {
  44613. "use strict";
  44614. init_types3();
  44615. init_evaluateExpression();
  44616. getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({
  44617. ...acc,
  44618. [headerKey]: headerVal.map((headerValEntry) => {
  44619. const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options);
  44620. if (typeof processedExpr !== "string") {
  44621. throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);
  44622. }
  44623. return processedExpr;
  44624. })
  44625. }), {});
  44626. }
  44627. });
  44628. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js
  44629. var getEndpointProperty;
  44630. var init_getEndpointProperty = __esm({
  44631. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js"() {
  44632. "use strict";
  44633. init_types3();
  44634. init_evaluateTemplate();
  44635. init_getEndpointProperties();
  44636. getEndpointProperty = (property, options) => {
  44637. if (Array.isArray(property)) {
  44638. return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options));
  44639. }
  44640. switch (typeof property) {
  44641. case "string":
  44642. return evaluateTemplate(property, options);
  44643. case "object":
  44644. if (property === null) {
  44645. throw new EndpointError(`Unexpected endpoint property: ${property}`);
  44646. }
  44647. return getEndpointProperties(property, options);
  44648. case "boolean":
  44649. return property;
  44650. default:
  44651. throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`);
  44652. }
  44653. };
  44654. }
  44655. });
  44656. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js
  44657. var getEndpointProperties;
  44658. var init_getEndpointProperties = __esm({
  44659. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js"() {
  44660. "use strict";
  44661. init_getEndpointProperty();
  44662. getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({
  44663. ...acc,
  44664. [propertyKey]: getEndpointProperty(propertyVal, options)
  44665. }), {});
  44666. }
  44667. });
  44668. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js
  44669. var getEndpointUrl;
  44670. var init_getEndpointUrl = __esm({
  44671. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js"() {
  44672. "use strict";
  44673. init_types3();
  44674. init_evaluateExpression();
  44675. getEndpointUrl = (endpointUrl, options) => {
  44676. const expression = evaluateExpression(endpointUrl, "Endpoint URL", options);
  44677. if (typeof expression === "string") {
  44678. try {
  44679. return new URL(expression);
  44680. } catch (error2) {
  44681. console.error(`Failed to construct URL with ${expression}`, error2);
  44682. throw error2;
  44683. }
  44684. }
  44685. throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`);
  44686. };
  44687. }
  44688. });
  44689. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js
  44690. var evaluateEndpointRule;
  44691. var init_evaluateEndpointRule = __esm({
  44692. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js"() {
  44693. "use strict";
  44694. init_debug();
  44695. init_evaluateConditions();
  44696. init_getEndpointHeaders();
  44697. init_getEndpointProperties();
  44698. init_getEndpointUrl();
  44699. evaluateEndpointRule = (endpointRule, options) => {
  44700. const { conditions, endpoint } = endpointRule;
  44701. const { result, referenceRecord } = evaluateConditions(conditions, options);
  44702. if (!result) {
  44703. return;
  44704. }
  44705. const endpointRuleOptions = {
  44706. ...options,
  44707. referenceRecord: { ...options.referenceRecord, ...referenceRecord }
  44708. };
  44709. const { url, properties, headers } = endpoint;
  44710. options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);
  44711. return {
  44712. ...headers != void 0 && {
  44713. headers: getEndpointHeaders(headers, endpointRuleOptions)
  44714. },
  44715. ...properties != void 0 && {
  44716. properties: getEndpointProperties(properties, endpointRuleOptions)
  44717. },
  44718. url: getEndpointUrl(url, endpointRuleOptions)
  44719. };
  44720. };
  44721. }
  44722. });
  44723. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js
  44724. var evaluateErrorRule;
  44725. var init_evaluateErrorRule = __esm({
  44726. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js"() {
  44727. "use strict";
  44728. init_types3();
  44729. init_evaluateConditions();
  44730. init_evaluateExpression();
  44731. evaluateErrorRule = (errorRule, options) => {
  44732. const { conditions, error: error2 } = errorRule;
  44733. const { result, referenceRecord } = evaluateConditions(conditions, options);
  44734. if (!result) {
  44735. return;
  44736. }
  44737. throw new EndpointError(evaluateExpression(error2, "Error", {
  44738. ...options,
  44739. referenceRecord: { ...options.referenceRecord, ...referenceRecord }
  44740. }));
  44741. };
  44742. }
  44743. });
  44744. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js
  44745. var evaluateTreeRule;
  44746. var init_evaluateTreeRule = __esm({
  44747. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js"() {
  44748. "use strict";
  44749. init_evaluateConditions();
  44750. init_evaluateRules();
  44751. evaluateTreeRule = (treeRule, options) => {
  44752. const { conditions, rules } = treeRule;
  44753. const { result, referenceRecord } = evaluateConditions(conditions, options);
  44754. if (!result) {
  44755. return;
  44756. }
  44757. return evaluateRules(rules, {
  44758. ...options,
  44759. referenceRecord: { ...options.referenceRecord, ...referenceRecord }
  44760. });
  44761. };
  44762. }
  44763. });
  44764. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js
  44765. var evaluateRules;
  44766. var init_evaluateRules = __esm({
  44767. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js"() {
  44768. "use strict";
  44769. init_types3();
  44770. init_evaluateEndpointRule();
  44771. init_evaluateErrorRule();
  44772. init_evaluateTreeRule();
  44773. evaluateRules = (rules, options) => {
  44774. for (const rule of rules) {
  44775. if (rule.type === "endpoint") {
  44776. const endpointOrUndefined = evaluateEndpointRule(rule, options);
  44777. if (endpointOrUndefined) {
  44778. return endpointOrUndefined;
  44779. }
  44780. } else if (rule.type === "error") {
  44781. evaluateErrorRule(rule, options);
  44782. } else if (rule.type === "tree") {
  44783. const endpointOrUndefined = evaluateTreeRule(rule, options);
  44784. if (endpointOrUndefined) {
  44785. return endpointOrUndefined;
  44786. }
  44787. } else {
  44788. throw new EndpointError(`Unknown endpoint rule: ${rule}`);
  44789. }
  44790. }
  44791. throw new EndpointError(`Rules evaluation failed`);
  44792. };
  44793. }
  44794. });
  44795. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/index.js
  44796. var init_utils5 = __esm({
  44797. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/utils/index.js"() {
  44798. "use strict";
  44799. init_customEndpointFunctions();
  44800. init_evaluateRules();
  44801. }
  44802. });
  44803. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js
  44804. var resolveEndpoint;
  44805. var init_resolveEndpoint = __esm({
  44806. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js"() {
  44807. "use strict";
  44808. init_debug();
  44809. init_types3();
  44810. init_utils5();
  44811. resolveEndpoint = (ruleSetObject, options) => {
  44812. const { endpointParams, logger: logger2 } = options;
  44813. const { parameters, rules } = ruleSetObject;
  44814. options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
  44815. const paramsWithDefault = Object.entries(parameters).filter(([, v6]) => v6.default != null).map(([k5, v6]) => [k5, v6.default]);
  44816. if (paramsWithDefault.length > 0) {
  44817. for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
  44818. endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
  44819. }
  44820. }
  44821. const requiredParams = Object.entries(parameters).filter(([, v6]) => v6.required).map(([k5]) => k5);
  44822. for (const requiredParam of requiredParams) {
  44823. if (endpointParams[requiredParam] == null) {
  44824. throw new EndpointError(`Missing required parameter: '${requiredParam}'`);
  44825. }
  44826. }
  44827. const endpoint = evaluateRules(rules, { endpointParams, logger: logger2, referenceRecord: {} });
  44828. options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
  44829. return endpoint;
  44830. };
  44831. }
  44832. });
  44833. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/index.js
  44834. var init_dist_es19 = __esm({
  44835. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-es/index.js"() {
  44836. "use strict";
  44837. init_EndpointCache();
  44838. init_isIpAddress();
  44839. init_isValidHostLabel();
  44840. init_customEndpointFunctions();
  44841. init_resolveEndpoint();
  44842. init_types3();
  44843. }
  44844. });
  44845. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js
  44846. var init_isIpAddress2 = __esm({
  44847. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() {
  44848. "use strict";
  44849. init_dist_es19();
  44850. }
  44851. });
  44852. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js
  44853. var isVirtualHostableS3Bucket;
  44854. var init_isVirtualHostableS3Bucket = __esm({
  44855. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() {
  44856. "use strict";
  44857. init_dist_es19();
  44858. init_isIpAddress2();
  44859. isVirtualHostableS3Bucket = (value, allowSubDomains = false) => {
  44860. if (allowSubDomains) {
  44861. for (const label of value.split(".")) {
  44862. if (!isVirtualHostableS3Bucket(label)) {
  44863. return false;
  44864. }
  44865. }
  44866. return true;
  44867. }
  44868. if (!isValidHostLabel(value)) {
  44869. return false;
  44870. }
  44871. if (value.length < 3 || value.length > 63) {
  44872. return false;
  44873. }
  44874. if (value !== value.toLowerCase()) {
  44875. return false;
  44876. }
  44877. if (isIpAddress(value)) {
  44878. return false;
  44879. }
  44880. return true;
  44881. };
  44882. }
  44883. });
  44884. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js
  44885. var ARN_DELIMITER, RESOURCE_DELIMITER, parseArn;
  44886. var init_parseArn = __esm({
  44887. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() {
  44888. "use strict";
  44889. ARN_DELIMITER = ":";
  44890. RESOURCE_DELIMITER = "/";
  44891. parseArn = (value) => {
  44892. const segments = value.split(ARN_DELIMITER);
  44893. if (segments.length < 6)
  44894. return null;
  44895. const [arn, partition2, service, region, accountId, ...resourcePath] = segments;
  44896. if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "")
  44897. return null;
  44898. const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();
  44899. return {
  44900. partition: partition2,
  44901. service,
  44902. region,
  44903. accountId,
  44904. resourceId
  44905. };
  44906. };
  44907. }
  44908. });
  44909. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json
  44910. var partitions_default;
  44911. var init_partitions = __esm({
  44912. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() {
  44913. partitions_default = {
  44914. partitions: [{
  44915. id: "aws",
  44916. outputs: {
  44917. dnsSuffix: "amazonaws.com",
  44918. dualStackDnsSuffix: "api.aws",
  44919. implicitGlobalRegion: "us-east-1",
  44920. name: "aws",
  44921. supportsDualStack: true,
  44922. supportsFIPS: true
  44923. },
  44924. regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",
  44925. regions: {
  44926. "af-south-1": {
  44927. description: "Africa (Cape Town)"
  44928. },
  44929. "ap-east-1": {
  44930. description: "Asia Pacific (Hong Kong)"
  44931. },
  44932. "ap-northeast-1": {
  44933. description: "Asia Pacific (Tokyo)"
  44934. },
  44935. "ap-northeast-2": {
  44936. description: "Asia Pacific (Seoul)"
  44937. },
  44938. "ap-northeast-3": {
  44939. description: "Asia Pacific (Osaka)"
  44940. },
  44941. "ap-south-1": {
  44942. description: "Asia Pacific (Mumbai)"
  44943. },
  44944. "ap-south-2": {
  44945. description: "Asia Pacific (Hyderabad)"
  44946. },
  44947. "ap-southeast-1": {
  44948. description: "Asia Pacific (Singapore)"
  44949. },
  44950. "ap-southeast-2": {
  44951. description: "Asia Pacific (Sydney)"
  44952. },
  44953. "ap-southeast-3": {
  44954. description: "Asia Pacific (Jakarta)"
  44955. },
  44956. "ap-southeast-4": {
  44957. description: "Asia Pacific (Melbourne)"
  44958. },
  44959. "ap-southeast-5": {
  44960. description: "Asia Pacific (Malaysia)"
  44961. },
  44962. "ap-southeast-7": {
  44963. description: "Asia Pacific (Thailand)"
  44964. },
  44965. "aws-global": {
  44966. description: "AWS Standard global region"
  44967. },
  44968. "ca-central-1": {
  44969. description: "Canada (Central)"
  44970. },
  44971. "ca-west-1": {
  44972. description: "Canada West (Calgary)"
  44973. },
  44974. "eu-central-1": {
  44975. description: "Europe (Frankfurt)"
  44976. },
  44977. "eu-central-2": {
  44978. description: "Europe (Zurich)"
  44979. },
  44980. "eu-north-1": {
  44981. description: "Europe (Stockholm)"
  44982. },
  44983. "eu-south-1": {
  44984. description: "Europe (Milan)"
  44985. },
  44986. "eu-south-2": {
  44987. description: "Europe (Spain)"
  44988. },
  44989. "eu-west-1": {
  44990. description: "Europe (Ireland)"
  44991. },
  44992. "eu-west-2": {
  44993. description: "Europe (London)"
  44994. },
  44995. "eu-west-3": {
  44996. description: "Europe (Paris)"
  44997. },
  44998. "il-central-1": {
  44999. description: "Israel (Tel Aviv)"
  45000. },
  45001. "me-central-1": {
  45002. description: "Middle East (UAE)"
  45003. },
  45004. "me-south-1": {
  45005. description: "Middle East (Bahrain)"
  45006. },
  45007. "mx-central-1": {
  45008. description: "Mexico (Central)"
  45009. },
  45010. "sa-east-1": {
  45011. description: "South America (Sao Paulo)"
  45012. },
  45013. "us-east-1": {
  45014. description: "US East (N. Virginia)"
  45015. },
  45016. "us-east-2": {
  45017. description: "US East (Ohio)"
  45018. },
  45019. "us-west-1": {
  45020. description: "US West (N. California)"
  45021. },
  45022. "us-west-2": {
  45023. description: "US West (Oregon)"
  45024. }
  45025. }
  45026. }, {
  45027. id: "aws-cn",
  45028. outputs: {
  45029. dnsSuffix: "amazonaws.com.cn",
  45030. dualStackDnsSuffix: "api.amazonwebservices.com.cn",
  45031. implicitGlobalRegion: "cn-northwest-1",
  45032. name: "aws-cn",
  45033. supportsDualStack: true,
  45034. supportsFIPS: true
  45035. },
  45036. regionRegex: "^cn\\-\\w+\\-\\d+$",
  45037. regions: {
  45038. "aws-cn-global": {
  45039. description: "AWS China global region"
  45040. },
  45041. "cn-north-1": {
  45042. description: "China (Beijing)"
  45043. },
  45044. "cn-northwest-1": {
  45045. description: "China (Ningxia)"
  45046. }
  45047. }
  45048. }, {
  45049. id: "aws-us-gov",
  45050. outputs: {
  45051. dnsSuffix: "amazonaws.com",
  45052. dualStackDnsSuffix: "api.aws",
  45053. implicitGlobalRegion: "us-gov-west-1",
  45054. name: "aws-us-gov",
  45055. supportsDualStack: true,
  45056. supportsFIPS: true
  45057. },
  45058. regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
  45059. regions: {
  45060. "aws-us-gov-global": {
  45061. description: "AWS GovCloud (US) global region"
  45062. },
  45063. "us-gov-east-1": {
  45064. description: "AWS GovCloud (US-East)"
  45065. },
  45066. "us-gov-west-1": {
  45067. description: "AWS GovCloud (US-West)"
  45068. }
  45069. }
  45070. }, {
  45071. id: "aws-iso",
  45072. outputs: {
  45073. dnsSuffix: "c2s.ic.gov",
  45074. dualStackDnsSuffix: "c2s.ic.gov",
  45075. implicitGlobalRegion: "us-iso-east-1",
  45076. name: "aws-iso",
  45077. supportsDualStack: false,
  45078. supportsFIPS: true
  45079. },
  45080. regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
  45081. regions: {
  45082. "aws-iso-global": {
  45083. description: "AWS ISO (US) global region"
  45084. },
  45085. "us-iso-east-1": {
  45086. description: "US ISO East"
  45087. },
  45088. "us-iso-west-1": {
  45089. description: "US ISO WEST"
  45090. }
  45091. }
  45092. }, {
  45093. id: "aws-iso-b",
  45094. outputs: {
  45095. dnsSuffix: "sc2s.sgov.gov",
  45096. dualStackDnsSuffix: "sc2s.sgov.gov",
  45097. implicitGlobalRegion: "us-isob-east-1",
  45098. name: "aws-iso-b",
  45099. supportsDualStack: false,
  45100. supportsFIPS: true
  45101. },
  45102. regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
  45103. regions: {
  45104. "aws-iso-b-global": {
  45105. description: "AWS ISOB (US) global region"
  45106. },
  45107. "us-isob-east-1": {
  45108. description: "US ISOB East (Ohio)"
  45109. }
  45110. }
  45111. }, {
  45112. id: "aws-iso-e",
  45113. outputs: {
  45114. dnsSuffix: "cloud.adc-e.uk",
  45115. dualStackDnsSuffix: "cloud.adc-e.uk",
  45116. implicitGlobalRegion: "eu-isoe-west-1",
  45117. name: "aws-iso-e",
  45118. supportsDualStack: false,
  45119. supportsFIPS: true
  45120. },
  45121. regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
  45122. regions: {
  45123. "aws-iso-e-global": {
  45124. description: "AWS ISOE (Europe) global region"
  45125. },
  45126. "eu-isoe-west-1": {
  45127. description: "EU ISOE West"
  45128. }
  45129. }
  45130. }, {
  45131. id: "aws-iso-f",
  45132. outputs: {
  45133. dnsSuffix: "csp.hci.ic.gov",
  45134. dualStackDnsSuffix: "csp.hci.ic.gov",
  45135. implicitGlobalRegion: "us-isof-south-1",
  45136. name: "aws-iso-f",
  45137. supportsDualStack: false,
  45138. supportsFIPS: true
  45139. },
  45140. regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
  45141. regions: {
  45142. "aws-iso-f-global": {
  45143. description: "AWS ISOF global region"
  45144. },
  45145. "us-isof-east-1": {
  45146. description: "US ISOF EAST"
  45147. },
  45148. "us-isof-south-1": {
  45149. description: "US ISOF SOUTH"
  45150. }
  45151. }
  45152. }, {
  45153. id: "aws-eusc",
  45154. outputs: {
  45155. dnsSuffix: "amazonaws.eu",
  45156. dualStackDnsSuffix: "amazonaws.eu",
  45157. implicitGlobalRegion: "eusc-de-east-1",
  45158. name: "aws-eusc",
  45159. supportsDualStack: false,
  45160. supportsFIPS: true
  45161. },
  45162. regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$",
  45163. regions: {
  45164. "eusc-de-east-1": {
  45165. description: "EU (Germany)"
  45166. }
  45167. }
  45168. }],
  45169. version: "1.1"
  45170. };
  45171. }
  45172. });
  45173. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js
  45174. var selectedPartitionsInfo, selectedUserAgentPrefix, partition, getUserAgentPrefix;
  45175. var init_partition = __esm({
  45176. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() {
  45177. "use strict";
  45178. init_partitions();
  45179. selectedPartitionsInfo = partitions_default;
  45180. selectedUserAgentPrefix = "";
  45181. partition = (value) => {
  45182. const { partitions } = selectedPartitionsInfo;
  45183. for (const partition2 of partitions) {
  45184. const { regions, outputs: outputs2 } = partition2;
  45185. for (const [region, regionData] of Object.entries(regions)) {
  45186. if (region === value) {
  45187. return {
  45188. ...outputs2,
  45189. ...regionData
  45190. };
  45191. }
  45192. }
  45193. }
  45194. for (const partition2 of partitions) {
  45195. const { regionRegex, outputs: outputs2 } = partition2;
  45196. if (new RegExp(regionRegex).test(value)) {
  45197. return {
  45198. ...outputs2
  45199. };
  45200. }
  45201. }
  45202. const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws");
  45203. if (!DEFAULT_PARTITION) {
  45204. throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");
  45205. }
  45206. return {
  45207. ...DEFAULT_PARTITION.outputs
  45208. };
  45209. };
  45210. getUserAgentPrefix = () => selectedUserAgentPrefix;
  45211. }
  45212. });
  45213. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js
  45214. var awsEndpointFunctions;
  45215. var init_aws = __esm({
  45216. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() {
  45217. "use strict";
  45218. init_dist_es19();
  45219. init_isVirtualHostableS3Bucket();
  45220. init_parseArn();
  45221. init_partition();
  45222. awsEndpointFunctions = {
  45223. isVirtualHostableS3Bucket,
  45224. parseArn,
  45225. partition
  45226. };
  45227. customEndpointFunctions.aws = awsEndpointFunctions;
  45228. }
  45229. });
  45230. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js
  45231. var init_resolveEndpoint2 = __esm({
  45232. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() {
  45233. "use strict";
  45234. init_dist_es19();
  45235. }
  45236. });
  45237. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js
  45238. var init_EndpointError2 = __esm({
  45239. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() {
  45240. "use strict";
  45241. init_dist_es19();
  45242. }
  45243. });
  45244. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js
  45245. var init_EndpointRuleObject3 = __esm({
  45246. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() {
  45247. "use strict";
  45248. }
  45249. });
  45250. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js
  45251. var init_ErrorRuleObject3 = __esm({
  45252. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() {
  45253. "use strict";
  45254. }
  45255. });
  45256. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js
  45257. var init_RuleSetObject3 = __esm({
  45258. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() {
  45259. "use strict";
  45260. }
  45261. });
  45262. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js
  45263. var init_TreeRuleObject3 = __esm({
  45264. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() {
  45265. "use strict";
  45266. }
  45267. });
  45268. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js
  45269. var init_shared3 = __esm({
  45270. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() {
  45271. "use strict";
  45272. }
  45273. });
  45274. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js
  45275. var init_types4 = __esm({
  45276. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() {
  45277. "use strict";
  45278. init_EndpointError2();
  45279. init_EndpointRuleObject3();
  45280. init_ErrorRuleObject3();
  45281. init_RuleSetObject3();
  45282. init_TreeRuleObject3();
  45283. init_shared3();
  45284. }
  45285. });
  45286. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/index.js
  45287. var init_dist_es20 = __esm({
  45288. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() {
  45289. "use strict";
  45290. init_aws();
  45291. init_partition();
  45292. init_isIpAddress2();
  45293. init_resolveEndpoint2();
  45294. init_types4();
  45295. }
  45296. });
  45297. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js
  45298. var state, emitWarningIfUnsupportedVersion;
  45299. var init_emitWarningIfUnsupportedVersion = __esm({
  45300. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() {
  45301. "use strict";
  45302. state = {
  45303. warningEmitted: false
  45304. };
  45305. emitWarningIfUnsupportedVersion = (version) => {
  45306. if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) {
  45307. state.warningEmitted = true;
  45308. process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
  45309. no longer support Node.js 16.x on January 6, 2025.
  45310. To continue receiving updates to AWS services, bug fixes, and security
  45311. updates please upgrade to a supported Node.js LTS version.
  45312. More information can be found at: https://a.co/74kJMmI`);
  45313. }
  45314. };
  45315. }
  45316. });
  45317. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js
  45318. function setCredentialFeature(credentials2, feature, value) {
  45319. if (!credentials2.$source) {
  45320. credentials2.$source = {};
  45321. }
  45322. credentials2.$source[feature] = value;
  45323. return credentials2;
  45324. }
  45325. var init_setCredentialFeature = __esm({
  45326. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() {
  45327. "use strict";
  45328. }
  45329. });
  45330. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js
  45331. function setFeature2(context, feature, value) {
  45332. if (!context.__aws_sdk_context) {
  45333. context.__aws_sdk_context = {
  45334. features: {}
  45335. };
  45336. } else if (!context.__aws_sdk_context.features) {
  45337. context.__aws_sdk_context.features = {};
  45338. }
  45339. context.__aws_sdk_context.features[feature] = value;
  45340. }
  45341. var init_setFeature2 = __esm({
  45342. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() {
  45343. "use strict";
  45344. }
  45345. });
  45346. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js
  45347. var init_client2 = __esm({
  45348. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() {
  45349. "use strict";
  45350. init_emitWarningIfUnsupportedVersion();
  45351. init_setCredentialFeature();
  45352. init_setFeature2();
  45353. }
  45354. });
  45355. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js
  45356. var getDateHeader;
  45357. var init_getDateHeader = __esm({
  45358. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() {
  45359. "use strict";
  45360. init_dist_es2();
  45361. getDateHeader = (response) => HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0;
  45362. }
  45363. });
  45364. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js
  45365. var getSkewCorrectedDate;
  45366. var init_getSkewCorrectedDate = __esm({
  45367. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() {
  45368. "use strict";
  45369. getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);
  45370. }
  45371. });
  45372. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js
  45373. var isClockSkewed;
  45374. var init_isClockSkewed = __esm({
  45375. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() {
  45376. "use strict";
  45377. init_getSkewCorrectedDate();
  45378. isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5;
  45379. }
  45380. });
  45381. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js
  45382. var getUpdatedSystemClockOffset;
  45383. var init_getUpdatedSystemClockOffset = __esm({
  45384. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() {
  45385. "use strict";
  45386. init_isClockSkewed();
  45387. getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
  45388. const clockTimeInMs = Date.parse(clockTime);
  45389. if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
  45390. return clockTimeInMs - Date.now();
  45391. }
  45392. return currentSystemClockOffset;
  45393. };
  45394. }
  45395. });
  45396. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js
  45397. var init_utils6 = __esm({
  45398. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() {
  45399. "use strict";
  45400. init_getDateHeader();
  45401. init_getSkewCorrectedDate();
  45402. init_getUpdatedSystemClockOffset();
  45403. }
  45404. });
  45405. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js
  45406. var throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer;
  45407. var init_AwsSdkSigV4Signer = __esm({
  45408. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() {
  45409. "use strict";
  45410. init_dist_es2();
  45411. init_utils6();
  45412. throwSigningPropertyError = (name, property) => {
  45413. if (!property) {
  45414. throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
  45415. }
  45416. return property;
  45417. };
  45418. validateSigningProperties = async (signingProperties) => {
  45419. const context = throwSigningPropertyError("context", signingProperties.context);
  45420. const config = throwSigningPropertyError("config", signingProperties.config);
  45421. const authScheme = context.endpointV2?.properties?.authSchemes?.[0];
  45422. const signerFunction = throwSigningPropertyError("signer", config.signer);
  45423. const signer = await signerFunction(authScheme);
  45424. const signingRegion = signingProperties?.signingRegion;
  45425. const signingRegionSet = signingProperties?.signingRegionSet;
  45426. const signingName = signingProperties?.signingName;
  45427. return {
  45428. config,
  45429. signer,
  45430. signingRegion,
  45431. signingRegionSet,
  45432. signingName
  45433. };
  45434. };
  45435. AwsSdkSigV4Signer = class {
  45436. async sign(httpRequest2, identity, signingProperties) {
  45437. if (!HttpRequest.isInstance(httpRequest2)) {
  45438. throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
  45439. }
  45440. const validatedProps = await validateSigningProperties(signingProperties);
  45441. const { config, signer } = validatedProps;
  45442. let { signingRegion, signingName } = validatedProps;
  45443. const handlerExecutionContext = signingProperties.context;
  45444. if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) {
  45445. const [first, second] = handlerExecutionContext.authSchemes;
  45446. if (first?.name === "sigv4a" && second?.name === "sigv4") {
  45447. signingRegion = second?.signingRegion ?? signingRegion;
  45448. signingName = second?.signingName ?? signingName;
  45449. }
  45450. }
  45451. const signedRequest = await signer.sign(httpRequest2, {
  45452. signingDate: getSkewCorrectedDate(config.systemClockOffset),
  45453. signingRegion,
  45454. signingService: signingName
  45455. });
  45456. return signedRequest;
  45457. }
  45458. errorHandler(signingProperties) {
  45459. return (error2) => {
  45460. const serverTime = error2.ServerTime ?? getDateHeader(error2.$response);
  45461. if (serverTime) {
  45462. const config = throwSigningPropertyError("config", signingProperties.config);
  45463. const initialSystemClockOffset = config.systemClockOffset;
  45464. config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);
  45465. const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;
  45466. if (clockSkewCorrected && error2.$metadata) {
  45467. error2.$metadata.clockSkewCorrected = true;
  45468. }
  45469. }
  45470. throw error2;
  45471. };
  45472. }
  45473. successHandler(httpResponse, signingProperties) {
  45474. const dateHeader = getDateHeader(httpResponse);
  45475. if (dateHeader) {
  45476. const config = throwSigningPropertyError("config", signingProperties.config);
  45477. config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);
  45478. }
  45479. }
  45480. };
  45481. }
  45482. });
  45483. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js
  45484. var getArrayForCommaSeparatedString;
  45485. var init_getArrayForCommaSeparatedString = __esm({
  45486. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js"() {
  45487. "use strict";
  45488. getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [];
  45489. }
  45490. });
  45491. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js
  45492. var getBearerTokenEnvKey;
  45493. var init_getBearerTokenEnvKey = __esm({
  45494. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js"() {
  45495. "use strict";
  45496. getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`;
  45497. }
  45498. });
  45499. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js
  45500. var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY, NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS;
  45501. var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esm({
  45502. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js"() {
  45503. "use strict";
  45504. init_getArrayForCommaSeparatedString();
  45505. init_getBearerTokenEnvKey();
  45506. NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE";
  45507. NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference";
  45508. NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = {
  45509. environmentVariableSelector: (env4, options) => {
  45510. if (options?.signingName) {
  45511. const bearerTokenKey = getBearerTokenEnvKey(options.signingName);
  45512. if (bearerTokenKey in env4)
  45513. return ["httpBearerAuth"];
  45514. }
  45515. if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env4))
  45516. return void 0;
  45517. return getArrayForCommaSeparatedString(env4[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]);
  45518. },
  45519. configFileSelector: (profile) => {
  45520. if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile))
  45521. return void 0;
  45522. return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]);
  45523. },
  45524. default: []
  45525. };
  45526. }
  45527. });
  45528. // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/ProviderError.js
  45529. var ProviderError;
  45530. var init_ProviderError = __esm({
  45531. "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/ProviderError.js"() {
  45532. "use strict";
  45533. ProviderError = class _ProviderError extends Error {
  45534. constructor(message, options = true) {
  45535. let logger2;
  45536. let tryNextLink = true;
  45537. if (typeof options === "boolean") {
  45538. logger2 = void 0;
  45539. tryNextLink = options;
  45540. } else if (options != null && typeof options === "object") {
  45541. logger2 = options.logger;
  45542. tryNextLink = options.tryNextLink ?? true;
  45543. }
  45544. super(message);
  45545. this.name = "ProviderError";
  45546. this.tryNextLink = tryNextLink;
  45547. Object.setPrototypeOf(this, _ProviderError.prototype);
  45548. logger2?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
  45549. }
  45550. static from(error2, options = true) {
  45551. return Object.assign(new this(error2.message, options), error2);
  45552. }
  45553. };
  45554. }
  45555. });
  45556. // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js
  45557. var CredentialsProviderError;
  45558. var init_CredentialsProviderError = __esm({
  45559. "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js"() {
  45560. "use strict";
  45561. init_ProviderError();
  45562. CredentialsProviderError = class _CredentialsProviderError extends ProviderError {
  45563. constructor(message, options = true) {
  45564. super(message, options);
  45565. this.name = "CredentialsProviderError";
  45566. Object.setPrototypeOf(this, _CredentialsProviderError.prototype);
  45567. }
  45568. };
  45569. }
  45570. });
  45571. // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/TokenProviderError.js
  45572. var TokenProviderError;
  45573. var init_TokenProviderError = __esm({
  45574. "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/TokenProviderError.js"() {
  45575. "use strict";
  45576. init_ProviderError();
  45577. TokenProviderError = class _TokenProviderError extends ProviderError {
  45578. constructor(message, options = true) {
  45579. super(message, options);
  45580. this.name = "TokenProviderError";
  45581. Object.setPrototypeOf(this, _TokenProviderError.prototype);
  45582. }
  45583. };
  45584. }
  45585. });
  45586. // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/chain.js
  45587. var chain;
  45588. var init_chain = __esm({
  45589. "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/chain.js"() {
  45590. "use strict";
  45591. init_ProviderError();
  45592. chain = (...providers) => async () => {
  45593. if (providers.length === 0) {
  45594. throw new ProviderError("No providers in chain");
  45595. }
  45596. let lastProviderError;
  45597. for (const provider of providers) {
  45598. try {
  45599. const credentials2 = await provider();
  45600. return credentials2;
  45601. } catch (err2) {
  45602. lastProviderError = err2;
  45603. if (err2?.tryNextLink) {
  45604. continue;
  45605. }
  45606. throw err2;
  45607. }
  45608. }
  45609. throw lastProviderError;
  45610. };
  45611. }
  45612. });
  45613. // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/fromStatic.js
  45614. var fromStatic;
  45615. var init_fromStatic = __esm({
  45616. "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/fromStatic.js"() {
  45617. "use strict";
  45618. fromStatic = (staticValue) => () => Promise.resolve(staticValue);
  45619. }
  45620. });
  45621. // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/memoize.js
  45622. var memoize;
  45623. var init_memoize = __esm({
  45624. "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/memoize.js"() {
  45625. "use strict";
  45626. memoize = (provider, isExpired, requiresRefresh) => {
  45627. let resolved;
  45628. let pending;
  45629. let hasResult;
  45630. let isConstant = false;
  45631. const coalesceProvider = async () => {
  45632. if (!pending) {
  45633. pending = provider();
  45634. }
  45635. try {
  45636. resolved = await pending;
  45637. hasResult = true;
  45638. isConstant = false;
  45639. } finally {
  45640. pending = void 0;
  45641. }
  45642. return resolved;
  45643. };
  45644. if (isExpired === void 0) {
  45645. return async (options) => {
  45646. if (!hasResult || options?.forceRefresh) {
  45647. resolved = await coalesceProvider();
  45648. }
  45649. return resolved;
  45650. };
  45651. }
  45652. return async (options) => {
  45653. if (!hasResult || options?.forceRefresh) {
  45654. resolved = await coalesceProvider();
  45655. }
  45656. if (isConstant) {
  45657. return resolved;
  45658. }
  45659. if (requiresRefresh && !requiresRefresh(resolved)) {
  45660. isConstant = true;
  45661. return resolved;
  45662. }
  45663. if (isExpired(resolved)) {
  45664. await coalesceProvider();
  45665. return resolved;
  45666. }
  45667. return resolved;
  45668. };
  45669. };
  45670. }
  45671. });
  45672. // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/index.js
  45673. var init_dist_es21 = __esm({
  45674. "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-es/index.js"() {
  45675. "use strict";
  45676. init_CredentialsProviderError();
  45677. init_ProviderError();
  45678. init_TokenProviderError();
  45679. init_chain();
  45680. init_fromStatic();
  45681. init_memoize();
  45682. }
  45683. });
  45684. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js
  45685. var init_resolveAwsSdkSigV4AConfig = __esm({
  45686. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() {
  45687. "use strict";
  45688. init_dist_es18();
  45689. init_dist_es21();
  45690. }
  45691. });
  45692. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/constants.js
  45693. var ALGORITHM_QUERY_PARAM, CREDENTIAL_QUERY_PARAM, AMZ_DATE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, EXPIRES_QUERY_PARAM, SIGNATURE_QUERY_PARAM, TOKEN_QUERY_PARAM, AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER, GENERATED_HEADERS, SIGNATURE_HEADER, SHA256_HEADER, TOKEN_HEADER, ALWAYS_UNSIGNABLE_HEADERS, PROXY_HEADER_PATTERN, SEC_HEADER_PATTERN, ALGORITHM_IDENTIFIER, EVENT_ALGORITHM_IDENTIFIER, UNSIGNED_PAYLOAD, MAX_CACHE_SIZE, KEY_TYPE_IDENTIFIER, MAX_PRESIGNED_TTL;
  45694. var init_constants3 = __esm({
  45695. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/constants.js"() {
  45696. "use strict";
  45697. ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
  45698. CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
  45699. AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
  45700. SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
  45701. EXPIRES_QUERY_PARAM = "X-Amz-Expires";
  45702. SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
  45703. TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
  45704. AUTH_HEADER = "authorization";
  45705. AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
  45706. DATE_HEADER = "date";
  45707. GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
  45708. SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
  45709. SHA256_HEADER = "x-amz-content-sha256";
  45710. TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
  45711. ALWAYS_UNSIGNABLE_HEADERS = {
  45712. authorization: true,
  45713. "cache-control": true,
  45714. connection: true,
  45715. expect: true,
  45716. from: true,
  45717. "keep-alive": true,
  45718. "max-forwards": true,
  45719. pragma: true,
  45720. referer: true,
  45721. te: true,
  45722. trailer: true,
  45723. "transfer-encoding": true,
  45724. upgrade: true,
  45725. "user-agent": true,
  45726. "x-amzn-trace-id": true
  45727. };
  45728. PROXY_HEADER_PATTERN = /^proxy-/;
  45729. SEC_HEADER_PATTERN = /^sec-/;
  45730. ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
  45731. EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
  45732. UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
  45733. MAX_CACHE_SIZE = 50;
  45734. KEY_TYPE_IDENTIFIER = "aws4_request";
  45735. MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
  45736. }
  45737. });
  45738. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js
  45739. var signingKeyCache, cacheQueue, createScope, getSigningKey, hmac;
  45740. var init_credentialDerivation = __esm({
  45741. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js"() {
  45742. "use strict";
  45743. init_dist_es16();
  45744. init_dist_es10();
  45745. init_constants3();
  45746. signingKeyCache = {};
  45747. cacheQueue = [];
  45748. createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;
  45749. getSigningKey = async (sha256Constructor, credentials2, shortDate, region, service) => {
  45750. const credsHash = await hmac(sha256Constructor, credentials2.secretAccessKey, credentials2.accessKeyId);
  45751. const cacheKey2 = `${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials2.sessionToken}`;
  45752. if (cacheKey2 in signingKeyCache) {
  45753. return signingKeyCache[cacheKey2];
  45754. }
  45755. cacheQueue.push(cacheKey2);
  45756. while (cacheQueue.length > MAX_CACHE_SIZE) {
  45757. delete signingKeyCache[cacheQueue.shift()];
  45758. }
  45759. let key = `AWS4${credentials2.secretAccessKey}`;
  45760. for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
  45761. key = await hmac(sha256Constructor, key, signable);
  45762. }
  45763. return signingKeyCache[cacheKey2] = key;
  45764. };
  45765. hmac = (ctor, secret, data) => {
  45766. const hash = new ctor(secret);
  45767. hash.update(toUint8Array(data));
  45768. return hash.digest();
  45769. };
  45770. }
  45771. });
  45772. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js
  45773. var getCanonicalHeaders;
  45774. var init_getCanonicalHeaders = __esm({
  45775. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js"() {
  45776. "use strict";
  45777. init_constants3();
  45778. getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => {
  45779. const canonical = {};
  45780. for (const headerName of Object.keys(headers).sort()) {
  45781. if (headers[headerName] == void 0) {
  45782. continue;
  45783. }
  45784. const canonicalHeaderName = headerName.toLowerCase();
  45785. if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
  45786. if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
  45787. continue;
  45788. }
  45789. }
  45790. canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
  45791. }
  45792. return canonical;
  45793. };
  45794. }
  45795. });
  45796. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js
  45797. var getPayloadHash;
  45798. var init_getPayloadHash = __esm({
  45799. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js"() {
  45800. "use strict";
  45801. init_dist_es8();
  45802. init_dist_es16();
  45803. init_dist_es10();
  45804. init_constants3();
  45805. getPayloadHash = async ({ headers, body }, hashConstructor) => {
  45806. for (const headerName of Object.keys(headers)) {
  45807. if (headerName.toLowerCase() === SHA256_HEADER) {
  45808. return headers[headerName];
  45809. }
  45810. }
  45811. if (body == void 0) {
  45812. return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
  45813. } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) {
  45814. const hashCtor = new hashConstructor();
  45815. hashCtor.update(toUint8Array(body));
  45816. return toHex(await hashCtor.digest());
  45817. }
  45818. return UNSIGNED_PAYLOAD;
  45819. };
  45820. }
  45821. });
  45822. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js
  45823. function negate(bytes) {
  45824. for (let i6 = 0; i6 < 8; i6++) {
  45825. bytes[i6] ^= 255;
  45826. }
  45827. for (let i6 = 7; i6 > -1; i6--) {
  45828. bytes[i6]++;
  45829. if (bytes[i6] !== 0)
  45830. break;
  45831. }
  45832. }
  45833. var HeaderFormatter, HEADER_VALUE_TYPE, UUID_PATTERN, Int64;
  45834. var init_HeaderFormatter = __esm({
  45835. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js"() {
  45836. "use strict";
  45837. init_dist_es16();
  45838. init_dist_es10();
  45839. HeaderFormatter = class {
  45840. format(headers) {
  45841. const chunks = [];
  45842. for (const headerName of Object.keys(headers)) {
  45843. const bytes = fromUtf8(headerName);
  45844. chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
  45845. }
  45846. const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
  45847. let position = 0;
  45848. for (const chunk of chunks) {
  45849. out.set(chunk, position);
  45850. position += chunk.byteLength;
  45851. }
  45852. return out;
  45853. }
  45854. formatHeaderValue(header) {
  45855. switch (header.type) {
  45856. case "boolean":
  45857. return Uint8Array.from([header.value ? 0 : 1]);
  45858. case "byte":
  45859. return Uint8Array.from([2, header.value]);
  45860. case "short":
  45861. const shortView = new DataView(new ArrayBuffer(3));
  45862. shortView.setUint8(0, 3);
  45863. shortView.setInt16(1, header.value, false);
  45864. return new Uint8Array(shortView.buffer);
  45865. case "integer":
  45866. const intView = new DataView(new ArrayBuffer(5));
  45867. intView.setUint8(0, 4);
  45868. intView.setInt32(1, header.value, false);
  45869. return new Uint8Array(intView.buffer);
  45870. case "long":
  45871. const longBytes = new Uint8Array(9);
  45872. longBytes[0] = 5;
  45873. longBytes.set(header.value.bytes, 1);
  45874. return longBytes;
  45875. case "binary":
  45876. const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
  45877. binView.setUint8(0, 6);
  45878. binView.setUint16(1, header.value.byteLength, false);
  45879. const binBytes = new Uint8Array(binView.buffer);
  45880. binBytes.set(header.value, 3);
  45881. return binBytes;
  45882. case "string":
  45883. const utf8Bytes = fromUtf8(header.value);
  45884. const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
  45885. strView.setUint8(0, 7);
  45886. strView.setUint16(1, utf8Bytes.byteLength, false);
  45887. const strBytes = new Uint8Array(strView.buffer);
  45888. strBytes.set(utf8Bytes, 3);
  45889. return strBytes;
  45890. case "timestamp":
  45891. const tsBytes = new Uint8Array(9);
  45892. tsBytes[0] = 8;
  45893. tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
  45894. return tsBytes;
  45895. case "uuid":
  45896. if (!UUID_PATTERN.test(header.value)) {
  45897. throw new Error(`Invalid UUID received: ${header.value}`);
  45898. }
  45899. const uuidBytes = new Uint8Array(17);
  45900. uuidBytes[0] = 9;
  45901. uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1);
  45902. return uuidBytes;
  45903. }
  45904. }
  45905. };
  45906. (function(HEADER_VALUE_TYPE2) {
  45907. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue";
  45908. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse";
  45909. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte";
  45910. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short";
  45911. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer";
  45912. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long";
  45913. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray";
  45914. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string";
  45915. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp";
  45916. HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid";
  45917. })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));
  45918. UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
  45919. Int64 = class _Int64 {
  45920. constructor(bytes) {
  45921. this.bytes = bytes;
  45922. if (bytes.byteLength !== 8) {
  45923. throw new Error("Int64 buffers must be exactly 8 bytes");
  45924. }
  45925. }
  45926. static fromNumber(number) {
  45927. if (number > 9223372036854776e3 || number < -9223372036854776e3) {
  45928. throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);
  45929. }
  45930. const bytes = new Uint8Array(8);
  45931. for (let i6 = 7, remaining = Math.abs(Math.round(number)); i6 > -1 && remaining > 0; i6--, remaining /= 256) {
  45932. bytes[i6] = remaining;
  45933. }
  45934. if (number < 0) {
  45935. negate(bytes);
  45936. }
  45937. return new _Int64(bytes);
  45938. }
  45939. valueOf() {
  45940. const bytes = this.bytes.slice(0);
  45941. const negative = bytes[0] & 128;
  45942. if (negative) {
  45943. negate(bytes);
  45944. }
  45945. return parseInt(toHex(bytes), 16) * (negative ? -1 : 1);
  45946. }
  45947. toString() {
  45948. return String(this.valueOf());
  45949. }
  45950. };
  45951. }
  45952. });
  45953. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/headerUtil.js
  45954. var hasHeader;
  45955. var init_headerUtil = __esm({
  45956. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/headerUtil.js"() {
  45957. "use strict";
  45958. hasHeader = (soughtHeader, headers) => {
  45959. soughtHeader = soughtHeader.toLowerCase();
  45960. for (const headerName of Object.keys(headers)) {
  45961. if (soughtHeader === headerName.toLowerCase()) {
  45962. return true;
  45963. }
  45964. }
  45965. return false;
  45966. };
  45967. }
  45968. });
  45969. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js
  45970. var moveHeadersToQuery;
  45971. var init_moveHeadersToQuery = __esm({
  45972. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js"() {
  45973. "use strict";
  45974. init_dist_es2();
  45975. moveHeadersToQuery = (request2, options = {}) => {
  45976. const { headers, query = {} } = HttpRequest.clone(request2);
  45977. for (const name of Object.keys(headers)) {
  45978. const lname = name.toLowerCase();
  45979. if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) {
  45980. query[name] = headers[name];
  45981. delete headers[name];
  45982. }
  45983. }
  45984. return {
  45985. ...request2,
  45986. headers,
  45987. query
  45988. };
  45989. };
  45990. }
  45991. });
  45992. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js
  45993. var prepareRequest;
  45994. var init_prepareRequest = __esm({
  45995. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js"() {
  45996. "use strict";
  45997. init_dist_es2();
  45998. init_constants3();
  45999. prepareRequest = (request2) => {
  46000. request2 = HttpRequest.clone(request2);
  46001. for (const headerName of Object.keys(request2.headers)) {
  46002. if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
  46003. delete request2.headers[headerName];
  46004. }
  46005. }
  46006. return request2;
  46007. };
  46008. }
  46009. });
  46010. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js
  46011. var getCanonicalQuery;
  46012. var init_getCanonicalQuery = __esm({
  46013. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js"() {
  46014. "use strict";
  46015. init_dist_es12();
  46016. init_constants3();
  46017. getCanonicalQuery = ({ query = {} }) => {
  46018. const keys = [];
  46019. const serialized = {};
  46020. for (const key of Object.keys(query)) {
  46021. if (key.toLowerCase() === SIGNATURE_HEADER) {
  46022. continue;
  46023. }
  46024. const encodedKey = escapeUri(key);
  46025. keys.push(encodedKey);
  46026. const value = query[key];
  46027. if (typeof value === "string") {
  46028. serialized[encodedKey] = `${encodedKey}=${escapeUri(value)}`;
  46029. } else if (Array.isArray(value)) {
  46030. serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${escapeUri(value2)}`]), []).sort().join("&");
  46031. }
  46032. }
  46033. return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
  46034. };
  46035. }
  46036. });
  46037. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/utilDate.js
  46038. var iso8601, toDate;
  46039. var init_utilDate = __esm({
  46040. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/utilDate.js"() {
  46041. "use strict";
  46042. iso8601 = (time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z");
  46043. toDate = (time) => {
  46044. if (typeof time === "number") {
  46045. return new Date(time * 1e3);
  46046. }
  46047. if (typeof time === "string") {
  46048. if (Number(time)) {
  46049. return new Date(Number(time) * 1e3);
  46050. }
  46051. return new Date(time);
  46052. }
  46053. return time;
  46054. };
  46055. }
  46056. });
  46057. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js
  46058. var SignatureV4Base;
  46059. var init_SignatureV4Base = __esm({
  46060. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js"() {
  46061. "use strict";
  46062. init_dist_es16();
  46063. init_dist_es6();
  46064. init_dist_es12();
  46065. init_dist_es10();
  46066. init_getCanonicalQuery();
  46067. init_utilDate();
  46068. SignatureV4Base = class {
  46069. constructor({ applyChecksum, credentials: credentials2, region, service, sha256: sha2562, uriEscapePath = true }) {
  46070. this.service = service;
  46071. this.sha256 = sha2562;
  46072. this.uriEscapePath = uriEscapePath;
  46073. this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
  46074. this.regionProvider = normalizeProvider(region);
  46075. this.credentialProvider = normalizeProvider(credentials2);
  46076. }
  46077. createCanonicalRequest(request2, canonicalHeaders, payloadHash) {
  46078. const sortedHeaders = Object.keys(canonicalHeaders).sort();
  46079. return `${request2.method}
  46080. ${this.getCanonicalPath(request2)}
  46081. ${getCanonicalQuery(request2)}
  46082. ${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")}
  46083. ${sortedHeaders.join(";")}
  46084. ${payloadHash}`;
  46085. }
  46086. async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) {
  46087. const hash = new this.sha256();
  46088. hash.update(toUint8Array(canonicalRequest));
  46089. const hashedRequest = await hash.digest();
  46090. return `${algorithmIdentifier}
  46091. ${longDate}
  46092. ${credentialScope}
  46093. ${toHex(hashedRequest)}`;
  46094. }
  46095. getCanonicalPath({ path: path3 }) {
  46096. if (this.uriEscapePath) {
  46097. const normalizedPathSegments = [];
  46098. for (const pathSegment of path3.split("/")) {
  46099. if (pathSegment?.length === 0)
  46100. continue;
  46101. if (pathSegment === ".")
  46102. continue;
  46103. if (pathSegment === "..") {
  46104. normalizedPathSegments.pop();
  46105. } else {
  46106. normalizedPathSegments.push(pathSegment);
  46107. }
  46108. }
  46109. const normalizedPath = `${path3?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path3?.endsWith("/") ? "/" : ""}`;
  46110. const doubleEncoded = escapeUri(normalizedPath);
  46111. return doubleEncoded.replace(/%2F/g, "/");
  46112. }
  46113. return path3;
  46114. }
  46115. validateResolvedCredentials(credentials2) {
  46116. if (typeof credentials2 !== "object" || typeof credentials2.accessKeyId !== "string" || typeof credentials2.secretAccessKey !== "string") {
  46117. throw new Error("Resolved credential object is not valid");
  46118. }
  46119. }
  46120. formatDate(now) {
  46121. const longDate = iso8601(now).replace(/[\-:]/g, "");
  46122. return {
  46123. longDate,
  46124. shortDate: longDate.slice(0, 8)
  46125. };
  46126. }
  46127. getCanonicalHeaderList(headers) {
  46128. return Object.keys(headers).sort().join(";");
  46129. }
  46130. };
  46131. }
  46132. });
  46133. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js
  46134. var SignatureV4;
  46135. var init_SignatureV4 = __esm({
  46136. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js"() {
  46137. "use strict";
  46138. init_dist_es16();
  46139. init_dist_es10();
  46140. init_constants3();
  46141. init_credentialDerivation();
  46142. init_getCanonicalHeaders();
  46143. init_getPayloadHash();
  46144. init_HeaderFormatter();
  46145. init_headerUtil();
  46146. init_moveHeadersToQuery();
  46147. init_prepareRequest();
  46148. init_SignatureV4Base();
  46149. SignatureV4 = class extends SignatureV4Base {
  46150. constructor({ applyChecksum, credentials: credentials2, region, service, sha256: sha2562, uriEscapePath = true }) {
  46151. super({
  46152. applyChecksum,
  46153. credentials: credentials2,
  46154. region,
  46155. service,
  46156. sha256: sha2562,
  46157. uriEscapePath
  46158. });
  46159. this.headerFormatter = new HeaderFormatter();
  46160. }
  46161. async presign(originalRequest, options = {}) {
  46162. const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options;
  46163. const credentials2 = await this.credentialProvider();
  46164. this.validateResolvedCredentials(credentials2);
  46165. const region = signingRegion ?? await this.regionProvider();
  46166. const { longDate, shortDate } = this.formatDate(signingDate);
  46167. if (expiresIn > MAX_PRESIGNED_TTL) {
  46168. return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");
  46169. }
  46170. const scope = createScope(shortDate, region, signingService ?? this.service);
  46171. const request2 = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders });
  46172. if (credentials2.sessionToken) {
  46173. request2.query[TOKEN_QUERY_PARAM] = credentials2.sessionToken;
  46174. }
  46175. request2.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
  46176. request2.query[CREDENTIAL_QUERY_PARAM] = `${credentials2.accessKeyId}/${scope}`;
  46177. request2.query[AMZ_DATE_QUERY_PARAM] = longDate;
  46178. request2.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
  46179. const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
  46180. request2.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders);
  46181. request2.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials2, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)));
  46182. return request2;
  46183. }
  46184. async sign(toSign, options) {
  46185. if (typeof toSign === "string") {
  46186. return this.signString(toSign, options);
  46187. } else if (toSign.headers && toSign.payload) {
  46188. return this.signEvent(toSign, options);
  46189. } else if (toSign.message) {
  46190. return this.signMessage(toSign, options);
  46191. } else {
  46192. return this.signRequest(toSign, options);
  46193. }
  46194. }
  46195. async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) {
  46196. const region = signingRegion ?? await this.regionProvider();
  46197. const { shortDate, longDate } = this.formatDate(signingDate);
  46198. const scope = createScope(shortDate, region, signingService ?? this.service);
  46199. const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
  46200. const hash = new this.sha256();
  46201. hash.update(headers);
  46202. const hashedHeaders = toHex(await hash.digest());
  46203. const stringToSign = [
  46204. EVENT_ALGORITHM_IDENTIFIER,
  46205. longDate,
  46206. scope,
  46207. priorSignature,
  46208. hashedHeaders,
  46209. hashedPayload
  46210. ].join("\n");
  46211. return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
  46212. }
  46213. async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) {
  46214. const promise = this.signEvent({
  46215. headers: this.headerFormatter.format(signableMessage.message.headers),
  46216. payload: signableMessage.message.body
  46217. }, {
  46218. signingDate,
  46219. signingRegion,
  46220. signingService,
  46221. priorSignature: signableMessage.priorSignature
  46222. });
  46223. return promise.then((signature) => {
  46224. return { message: signableMessage.message, signature };
  46225. });
  46226. }
  46227. async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) {
  46228. const credentials2 = await this.credentialProvider();
  46229. this.validateResolvedCredentials(credentials2);
  46230. const region = signingRegion ?? await this.regionProvider();
  46231. const { shortDate } = this.formatDate(signingDate);
  46232. const hash = new this.sha256(await this.getSigningKey(credentials2, region, shortDate, signingService));
  46233. hash.update(toUint8Array(stringToSign));
  46234. return toHex(await hash.digest());
  46235. }
  46236. async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) {
  46237. const credentials2 = await this.credentialProvider();
  46238. this.validateResolvedCredentials(credentials2);
  46239. const region = signingRegion ?? await this.regionProvider();
  46240. const request2 = prepareRequest(requestToSign);
  46241. const { longDate, shortDate } = this.formatDate(signingDate);
  46242. const scope = createScope(shortDate, region, signingService ?? this.service);
  46243. request2.headers[AMZ_DATE_HEADER] = longDate;
  46244. if (credentials2.sessionToken) {
  46245. request2.headers[TOKEN_HEADER] = credentials2.sessionToken;
  46246. }
  46247. const payloadHash = await getPayloadHash(request2, this.sha256);
  46248. if (!hasHeader(SHA256_HEADER, request2.headers) && this.applyChecksum) {
  46249. request2.headers[SHA256_HEADER] = payloadHash;
  46250. }
  46251. const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
  46252. const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials2, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, payloadHash));
  46253. request2.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials2.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;
  46254. return request2;
  46255. }
  46256. async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
  46257. const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER);
  46258. const hash = new this.sha256(await keyPromise);
  46259. hash.update(toUint8Array(stringToSign));
  46260. return toHex(await hash.digest());
  46261. }
  46262. getSigningKey(credentials2, region, shortDate, service) {
  46263. return getSigningKey(this.sha256, credentials2, shortDate, region, service || this.service);
  46264. }
  46265. };
  46266. }
  46267. });
  46268. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js
  46269. var init_signature_v4a_container = __esm({
  46270. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js"() {
  46271. "use strict";
  46272. }
  46273. });
  46274. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/index.js
  46275. var init_dist_es22 = __esm({
  46276. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-es/index.js"() {
  46277. "use strict";
  46278. init_SignatureV4();
  46279. init_constants3();
  46280. init_getCanonicalHeaders();
  46281. init_getCanonicalQuery();
  46282. init_getPayloadHash();
  46283. init_moveHeadersToQuery();
  46284. init_prepareRequest();
  46285. init_credentialDerivation();
  46286. init_SignatureV4Base();
  46287. init_headerUtil();
  46288. init_signature_v4a_container();
  46289. }
  46290. });
  46291. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js
  46292. function normalizeCredentialProvider(config, { credentials: credentials2, credentialDefaultProvider }) {
  46293. let credentialsProvider;
  46294. if (credentials2) {
  46295. if (!credentials2?.memoized) {
  46296. credentialsProvider = memoizeIdentityProvider(credentials2, isIdentityExpired, doesIdentityRequireRefresh);
  46297. } else {
  46298. credentialsProvider = credentials2;
  46299. }
  46300. } else {
  46301. if (credentialDefaultProvider) {
  46302. credentialsProvider = normalizeProvider2(credentialDefaultProvider(Object.assign({}, config, {
  46303. parentClientConfig: config
  46304. })));
  46305. } else {
  46306. credentialsProvider = async () => {
  46307. throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.");
  46308. };
  46309. }
  46310. }
  46311. credentialsProvider.memoized = true;
  46312. return credentialsProvider;
  46313. }
  46314. function bindCallerConfig(config, credentialsProvider) {
  46315. if (credentialsProvider.configBound) {
  46316. return credentialsProvider;
  46317. }
  46318. const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config });
  46319. fn.memoized = credentialsProvider.memoized;
  46320. fn.configBound = true;
  46321. return fn;
  46322. }
  46323. var resolveAwsSdkSigV4Config;
  46324. var init_resolveAwsSdkSigV4Config = __esm({
  46325. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() {
  46326. "use strict";
  46327. init_client2();
  46328. init_dist_es18();
  46329. init_dist_es22();
  46330. resolveAwsSdkSigV4Config = (config) => {
  46331. let inputCredentials = config.credentials;
  46332. let isUserSupplied = !!config.credentials;
  46333. let resolvedCredentials = void 0;
  46334. Object.defineProperty(config, "credentials", {
  46335. set(credentials2) {
  46336. if (credentials2 && credentials2 !== inputCredentials && credentials2 !== resolvedCredentials) {
  46337. isUserSupplied = true;
  46338. }
  46339. inputCredentials = credentials2;
  46340. const memoizedProvider = normalizeCredentialProvider(config, {
  46341. credentials: inputCredentials,
  46342. credentialDefaultProvider: config.credentialDefaultProvider
  46343. });
  46344. const boundProvider = bindCallerConfig(config, memoizedProvider);
  46345. if (isUserSupplied && !boundProvider.attributed) {
  46346. resolvedCredentials = async (options) => boundProvider(options).then((creds) => setCredentialFeature(creds, "CREDENTIALS_CODE", "e"));
  46347. resolvedCredentials.memoized = boundProvider.memoized;
  46348. resolvedCredentials.configBound = boundProvider.configBound;
  46349. resolvedCredentials.attributed = true;
  46350. } else {
  46351. resolvedCredentials = boundProvider;
  46352. }
  46353. },
  46354. get() {
  46355. return resolvedCredentials;
  46356. },
  46357. enumerable: true,
  46358. configurable: true
  46359. });
  46360. config.credentials = inputCredentials;
  46361. const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256: sha2562 } = config;
  46362. let signer;
  46363. if (config.signer) {
  46364. signer = normalizeProvider2(config.signer);
  46365. } else if (config.regionInfoProvider) {
  46366. signer = () => normalizeProvider2(config.region)().then(async (region) => [
  46367. await config.regionInfoProvider(region, {
  46368. useFipsEndpoint: await config.useFipsEndpoint(),
  46369. useDualstackEndpoint: await config.useDualstackEndpoint()
  46370. }) || {},
  46371. region
  46372. ]).then(([regionInfo, region]) => {
  46373. const { signingRegion, signingService } = regionInfo;
  46374. config.signingRegion = config.signingRegion || signingRegion || region;
  46375. config.signingName = config.signingName || signingService || config.serviceId;
  46376. const params = {
  46377. ...config,
  46378. credentials: config.credentials,
  46379. region: config.signingRegion,
  46380. service: config.signingName,
  46381. sha256: sha2562,
  46382. uriEscapePath: signingEscapePath
  46383. };
  46384. const SignerCtor = config.signerConstructor || SignatureV4;
  46385. return new SignerCtor(params);
  46386. });
  46387. } else {
  46388. signer = async (authScheme) => {
  46389. authScheme = Object.assign({}, {
  46390. name: "sigv4",
  46391. signingName: config.signingName || config.defaultSigningName,
  46392. signingRegion: await normalizeProvider2(config.region)(),
  46393. properties: {}
  46394. }, authScheme);
  46395. const signingRegion = authScheme.signingRegion;
  46396. const signingService = authScheme.signingName;
  46397. config.signingRegion = config.signingRegion || signingRegion;
  46398. config.signingName = config.signingName || signingService || config.serviceId;
  46399. const params = {
  46400. ...config,
  46401. credentials: config.credentials,
  46402. region: config.signingRegion,
  46403. service: config.signingName,
  46404. sha256: sha2562,
  46405. uriEscapePath: signingEscapePath
  46406. };
  46407. const SignerCtor = config.signerConstructor || SignatureV4;
  46408. return new SignerCtor(params);
  46409. };
  46410. }
  46411. const resolvedConfig = Object.assign(config, {
  46412. systemClockOffset,
  46413. signingEscapePath,
  46414. signer
  46415. });
  46416. return resolvedConfig;
  46417. };
  46418. }
  46419. });
  46420. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js
  46421. var init_aws_sdk = __esm({
  46422. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() {
  46423. "use strict";
  46424. init_AwsSdkSigV4Signer();
  46425. init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS();
  46426. init_resolveAwsSdkSigV4AConfig();
  46427. init_resolveAwsSdkSigV4Config();
  46428. }
  46429. });
  46430. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js
  46431. var init_httpAuthSchemes2 = __esm({
  46432. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() {
  46433. "use strict";
  46434. init_aws_sdk();
  46435. init_getBearerTokenEnvKey();
  46436. }
  46437. });
  46438. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js
  46439. var init_coercing_serializers = __esm({
  46440. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() {
  46441. "use strict";
  46442. }
  46443. });
  46444. // ../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js
  46445. var getAllAliases, getMiddlewareNameWithAliases, constructStack, stepWeights, priorityWeights;
  46446. var init_MiddlewareStack = __esm({
  46447. "../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js"() {
  46448. "use strict";
  46449. getAllAliases = (name, aliases) => {
  46450. const _aliases = [];
  46451. if (name) {
  46452. _aliases.push(name);
  46453. }
  46454. if (aliases) {
  46455. for (const alias of aliases) {
  46456. _aliases.push(alias);
  46457. }
  46458. }
  46459. return _aliases;
  46460. };
  46461. getMiddlewareNameWithAliases = (name, aliases) => {
  46462. return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`;
  46463. };
  46464. constructStack = () => {
  46465. let absoluteEntries = [];
  46466. let relativeEntries = [];
  46467. let identifyOnResolve = false;
  46468. const entriesNameSet = /* @__PURE__ */ new Set();
  46469. const sort = (entries) => entries.sort((a5, b5) => stepWeights[b5.step] - stepWeights[a5.step] || priorityWeights[b5.priority || "normal"] - priorityWeights[a5.priority || "normal"]);
  46470. const removeByName = (toRemove) => {
  46471. let isRemoved = false;
  46472. const filterCb = (entry) => {
  46473. const aliases = getAllAliases(entry.name, entry.aliases);
  46474. if (aliases.includes(toRemove)) {
  46475. isRemoved = true;
  46476. for (const alias of aliases) {
  46477. entriesNameSet.delete(alias);
  46478. }
  46479. return false;
  46480. }
  46481. return true;
  46482. };
  46483. absoluteEntries = absoluteEntries.filter(filterCb);
  46484. relativeEntries = relativeEntries.filter(filterCb);
  46485. return isRemoved;
  46486. };
  46487. const removeByReference = (toRemove) => {
  46488. let isRemoved = false;
  46489. const filterCb = (entry) => {
  46490. if (entry.middleware === toRemove) {
  46491. isRemoved = true;
  46492. for (const alias of getAllAliases(entry.name, entry.aliases)) {
  46493. entriesNameSet.delete(alias);
  46494. }
  46495. return false;
  46496. }
  46497. return true;
  46498. };
  46499. absoluteEntries = absoluteEntries.filter(filterCb);
  46500. relativeEntries = relativeEntries.filter(filterCb);
  46501. return isRemoved;
  46502. };
  46503. const cloneTo = (toStack) => {
  46504. absoluteEntries.forEach((entry) => {
  46505. toStack.add(entry.middleware, { ...entry });
  46506. });
  46507. relativeEntries.forEach((entry) => {
  46508. toStack.addRelativeTo(entry.middleware, { ...entry });
  46509. });
  46510. toStack.identifyOnResolve?.(stack.identifyOnResolve());
  46511. return toStack;
  46512. };
  46513. const expandRelativeMiddlewareList = (from) => {
  46514. const expandedMiddlewareList = [];
  46515. from.before.forEach((entry) => {
  46516. if (entry.before.length === 0 && entry.after.length === 0) {
  46517. expandedMiddlewareList.push(entry);
  46518. } else {
  46519. expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
  46520. }
  46521. });
  46522. expandedMiddlewareList.push(from);
  46523. from.after.reverse().forEach((entry) => {
  46524. if (entry.before.length === 0 && entry.after.length === 0) {
  46525. expandedMiddlewareList.push(entry);
  46526. } else {
  46527. expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
  46528. }
  46529. });
  46530. return expandedMiddlewareList;
  46531. };
  46532. const getMiddlewareList = (debug = false) => {
  46533. const normalizedAbsoluteEntries = [];
  46534. const normalizedRelativeEntries = [];
  46535. const normalizedEntriesNameMap = {};
  46536. absoluteEntries.forEach((entry) => {
  46537. const normalizedEntry = {
  46538. ...entry,
  46539. before: [],
  46540. after: []
  46541. };
  46542. for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
  46543. normalizedEntriesNameMap[alias] = normalizedEntry;
  46544. }
  46545. normalizedAbsoluteEntries.push(normalizedEntry);
  46546. });
  46547. relativeEntries.forEach((entry) => {
  46548. const normalizedEntry = {
  46549. ...entry,
  46550. before: [],
  46551. after: []
  46552. };
  46553. for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
  46554. normalizedEntriesNameMap[alias] = normalizedEntry;
  46555. }
  46556. normalizedRelativeEntries.push(normalizedEntry);
  46557. });
  46558. normalizedRelativeEntries.forEach((entry) => {
  46559. if (entry.toMiddleware) {
  46560. const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware];
  46561. if (toMiddleware === void 0) {
  46562. if (debug) {
  46563. return;
  46564. }
  46565. throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`);
  46566. }
  46567. if (entry.relation === "after") {
  46568. toMiddleware.after.push(entry);
  46569. }
  46570. if (entry.relation === "before") {
  46571. toMiddleware.before.push(entry);
  46572. }
  46573. }
  46574. });
  46575. const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => {
  46576. wholeList.push(...expandedMiddlewareList);
  46577. return wholeList;
  46578. }, []);
  46579. return mainChain;
  46580. };
  46581. const stack = {
  46582. add: (middleware, options = {}) => {
  46583. const { name, override, aliases: _aliases } = options;
  46584. const entry = {
  46585. step: "initialize",
  46586. priority: "normal",
  46587. middleware,
  46588. ...options
  46589. };
  46590. const aliases = getAllAliases(name, _aliases);
  46591. if (aliases.length > 0) {
  46592. if (aliases.some((alias) => entriesNameSet.has(alias))) {
  46593. if (!override)
  46594. throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
  46595. for (const alias of aliases) {
  46596. const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias));
  46597. if (toOverrideIndex === -1) {
  46598. continue;
  46599. }
  46600. const toOverride = absoluteEntries[toOverrideIndex];
  46601. if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) {
  46602. throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`);
  46603. }
  46604. absoluteEntries.splice(toOverrideIndex, 1);
  46605. }
  46606. }
  46607. for (const alias of aliases) {
  46608. entriesNameSet.add(alias);
  46609. }
  46610. }
  46611. absoluteEntries.push(entry);
  46612. },
  46613. addRelativeTo: (middleware, options) => {
  46614. const { name, override, aliases: _aliases } = options;
  46615. const entry = {
  46616. middleware,
  46617. ...options
  46618. };
  46619. const aliases = getAllAliases(name, _aliases);
  46620. if (aliases.length > 0) {
  46621. if (aliases.some((alias) => entriesNameSet.has(alias))) {
  46622. if (!override)
  46623. throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
  46624. for (const alias of aliases) {
  46625. const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias));
  46626. if (toOverrideIndex === -1) {
  46627. continue;
  46628. }
  46629. const toOverride = relativeEntries[toOverrideIndex];
  46630. if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) {
  46631. throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`);
  46632. }
  46633. relativeEntries.splice(toOverrideIndex, 1);
  46634. }
  46635. }
  46636. for (const alias of aliases) {
  46637. entriesNameSet.add(alias);
  46638. }
  46639. }
  46640. relativeEntries.push(entry);
  46641. },
  46642. clone: () => cloneTo(constructStack()),
  46643. use: (plugin) => {
  46644. plugin.applyToStack(stack);
  46645. },
  46646. remove: (toRemove) => {
  46647. if (typeof toRemove === "string")
  46648. return removeByName(toRemove);
  46649. else
  46650. return removeByReference(toRemove);
  46651. },
  46652. removeByTag: (toRemove) => {
  46653. let isRemoved = false;
  46654. const filterCb = (entry) => {
  46655. const { tags, name, aliases: _aliases } = entry;
  46656. if (tags && tags.includes(toRemove)) {
  46657. const aliases = getAllAliases(name, _aliases);
  46658. for (const alias of aliases) {
  46659. entriesNameSet.delete(alias);
  46660. }
  46661. isRemoved = true;
  46662. return false;
  46663. }
  46664. return true;
  46665. };
  46666. absoluteEntries = absoluteEntries.filter(filterCb);
  46667. relativeEntries = relativeEntries.filter(filterCb);
  46668. return isRemoved;
  46669. },
  46670. concat: (from) => {
  46671. const cloned = cloneTo(constructStack());
  46672. cloned.use(from);
  46673. cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false));
  46674. return cloned;
  46675. },
  46676. applyToStack: cloneTo,
  46677. identify: () => {
  46678. return getMiddlewareList(true).map((mw) => {
  46679. const step = mw.step ?? mw.relation + " " + mw.toMiddleware;
  46680. return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step;
  46681. });
  46682. },
  46683. identifyOnResolve(toggle) {
  46684. if (typeof toggle === "boolean")
  46685. identifyOnResolve = toggle;
  46686. return identifyOnResolve;
  46687. },
  46688. resolve: (handler, context) => {
  46689. for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) {
  46690. handler = middleware(handler, context);
  46691. }
  46692. if (identifyOnResolve) {
  46693. console.log(stack.identify());
  46694. }
  46695. return handler;
  46696. }
  46697. };
  46698. return stack;
  46699. };
  46700. stepWeights = {
  46701. initialize: 5,
  46702. serialize: 4,
  46703. build: 3,
  46704. finalizeRequest: 2,
  46705. deserialize: 1
  46706. };
  46707. priorityWeights = {
  46708. high: 3,
  46709. normal: 2,
  46710. low: 1
  46711. };
  46712. }
  46713. });
  46714. // ../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/index.js
  46715. var init_dist_es23 = __esm({
  46716. "../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-es/index.js"() {
  46717. "use strict";
  46718. init_MiddlewareStack();
  46719. }
  46720. });
  46721. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/client.js
  46722. var Client;
  46723. var init_client3 = __esm({
  46724. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/client.js"() {
  46725. "use strict";
  46726. init_dist_es23();
  46727. Client = class {
  46728. constructor(config) {
  46729. this.config = config;
  46730. this.middlewareStack = constructStack();
  46731. }
  46732. send(command, optionsOrCb, cb) {
  46733. const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0;
  46734. const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
  46735. const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true;
  46736. let handler;
  46737. if (useHandlerCache) {
  46738. if (!this.handlers) {
  46739. this.handlers = /* @__PURE__ */ new WeakMap();
  46740. }
  46741. const handlers = this.handlers;
  46742. if (handlers.has(command.constructor)) {
  46743. handler = handlers.get(command.constructor);
  46744. } else {
  46745. handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
  46746. handlers.set(command.constructor, handler);
  46747. }
  46748. } else {
  46749. delete this.handlers;
  46750. handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
  46751. }
  46752. if (callback) {
  46753. handler(command).then((result) => callback(null, result.output), (err2) => callback(err2)).catch(() => {
  46754. });
  46755. } else {
  46756. return handler(command).then((result) => result.output);
  46757. }
  46758. }
  46759. destroy() {
  46760. this.config?.requestHandler?.destroy?.();
  46761. delete this.handlers;
  46762. }
  46763. };
  46764. }
  46765. });
  46766. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
  46767. var init_collect_stream_body2 = __esm({
  46768. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js"() {
  46769. "use strict";
  46770. init_protocols();
  46771. }
  46772. });
  46773. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/command.js
  46774. var Command, ClassBuilder;
  46775. var init_command2 = __esm({
  46776. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/command.js"() {
  46777. "use strict";
  46778. init_dist_es23();
  46779. init_dist_es();
  46780. Command = class {
  46781. constructor() {
  46782. this.middlewareStack = constructStack();
  46783. }
  46784. static classBuilder() {
  46785. return new ClassBuilder();
  46786. }
  46787. resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
  46788. for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
  46789. this.middlewareStack.use(mw);
  46790. }
  46791. const stack = clientStack.concat(this.middlewareStack);
  46792. const { logger: logger2 } = configuration;
  46793. const handlerExecutionContext = {
  46794. logger: logger2,
  46795. clientName,
  46796. commandName,
  46797. inputFilterSensitiveLog,
  46798. outputFilterSensitiveLog,
  46799. [SMITHY_CONTEXT_KEY]: {
  46800. commandInstance: this,
  46801. ...smithyContext
  46802. },
  46803. ...additionalContext
  46804. };
  46805. const { requestHandler } = configuration;
  46806. return stack.resolve((request2) => requestHandler.handle(request2.request, options || {}), handlerExecutionContext);
  46807. }
  46808. };
  46809. ClassBuilder = class {
  46810. constructor() {
  46811. this._init = () => {
  46812. };
  46813. this._ep = {};
  46814. this._middlewareFn = () => [];
  46815. this._commandName = "";
  46816. this._clientName = "";
  46817. this._additionalContext = {};
  46818. this._smithyContext = {};
  46819. this._inputFilterSensitiveLog = (_3) => _3;
  46820. this._outputFilterSensitiveLog = (_3) => _3;
  46821. this._serializer = null;
  46822. this._deserializer = null;
  46823. }
  46824. init(cb) {
  46825. this._init = cb;
  46826. }
  46827. ep(endpointParameterInstructions) {
  46828. this._ep = endpointParameterInstructions;
  46829. return this;
  46830. }
  46831. m(middlewareSupplier) {
  46832. this._middlewareFn = middlewareSupplier;
  46833. return this;
  46834. }
  46835. s(service, operation, smithyContext = {}) {
  46836. this._smithyContext = {
  46837. service,
  46838. operation,
  46839. ...smithyContext
  46840. };
  46841. return this;
  46842. }
  46843. c(additionalContext = {}) {
  46844. this._additionalContext = additionalContext;
  46845. return this;
  46846. }
  46847. n(clientName, commandName) {
  46848. this._clientName = clientName;
  46849. this._commandName = commandName;
  46850. return this;
  46851. }
  46852. f(inputFilter = (_3) => _3, outputFilter = (_3) => _3) {
  46853. this._inputFilterSensitiveLog = inputFilter;
  46854. this._outputFilterSensitiveLog = outputFilter;
  46855. return this;
  46856. }
  46857. ser(serializer) {
  46858. this._serializer = serializer;
  46859. return this;
  46860. }
  46861. de(deserializer) {
  46862. this._deserializer = deserializer;
  46863. return this;
  46864. }
  46865. sc(operation) {
  46866. this._operationSchema = operation;
  46867. this._smithyContext.operationSchema = operation;
  46868. return this;
  46869. }
  46870. build() {
  46871. const closure = this;
  46872. let CommandRef;
  46873. return CommandRef = class extends Command {
  46874. static getEndpointParameterInstructions() {
  46875. return closure._ep;
  46876. }
  46877. constructor(...[input]) {
  46878. super();
  46879. this.serialize = closure._serializer;
  46880. this.deserialize = closure._deserializer;
  46881. this.input = input ?? {};
  46882. closure._init(this);
  46883. this.schema = closure._operationSchema;
  46884. }
  46885. resolveMiddleware(stack, configuration, options) {
  46886. return this.resolveMiddlewareWithContext(stack, configuration, options, {
  46887. CommandCtor: CommandRef,
  46888. middlewareFn: closure._middlewareFn,
  46889. clientName: closure._clientName,
  46890. commandName: closure._commandName,
  46891. inputFilterSensitiveLog: closure._inputFilterSensitiveLog,
  46892. outputFilterSensitiveLog: closure._outputFilterSensitiveLog,
  46893. smithyContext: closure._smithyContext,
  46894. additionalContext: closure._additionalContext
  46895. });
  46896. }
  46897. };
  46898. }
  46899. };
  46900. }
  46901. });
  46902. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/constants.js
  46903. var SENSITIVE_STRING;
  46904. var init_constants4 = __esm({
  46905. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/constants.js"() {
  46906. "use strict";
  46907. SENSITIVE_STRING = "***SensitiveInformation***";
  46908. }
  46909. });
  46910. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js
  46911. var createAggregatedClient;
  46912. var init_create_aggregated_client = __esm({
  46913. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js"() {
  46914. "use strict";
  46915. createAggregatedClient = (commands5, Client2) => {
  46916. for (const command of Object.keys(commands5)) {
  46917. const CommandCtor = commands5[command];
  46918. const methodImpl = async function(args, optionsOrCb, cb) {
  46919. const command2 = new CommandCtor(args);
  46920. if (typeof optionsOrCb === "function") {
  46921. this.send(command2, optionsOrCb);
  46922. } else if (typeof cb === "function") {
  46923. if (typeof optionsOrCb !== "object")
  46924. throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
  46925. this.send(command2, optionsOrCb || {}, cb);
  46926. } else {
  46927. return this.send(command2, optionsOrCb);
  46928. }
  46929. };
  46930. const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, "");
  46931. Client2.prototype[methodName] = methodImpl;
  46932. }
  46933. };
  46934. }
  46935. });
  46936. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/exceptions.js
  46937. var ServiceException, decorateServiceException;
  46938. var init_exceptions = __esm({
  46939. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/exceptions.js"() {
  46940. "use strict";
  46941. ServiceException = class _ServiceException extends Error {
  46942. constructor(options) {
  46943. super(options.message);
  46944. Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
  46945. this.name = options.name;
  46946. this.$fault = options.$fault;
  46947. this.$metadata = options.$metadata;
  46948. }
  46949. static isInstance(value) {
  46950. if (!value)
  46951. return false;
  46952. const candidate = value;
  46953. return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
  46954. }
  46955. static [Symbol.hasInstance](instance) {
  46956. if (!instance)
  46957. return false;
  46958. const candidate = instance;
  46959. if (this === _ServiceException) {
  46960. return _ServiceException.isInstance(instance);
  46961. }
  46962. if (_ServiceException.isInstance(instance)) {
  46963. if (candidate.name && this.name) {
  46964. return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
  46965. }
  46966. return this.prototype.isPrototypeOf(instance);
  46967. }
  46968. return false;
  46969. }
  46970. };
  46971. decorateServiceException = (exception, additions = {}) => {
  46972. Object.entries(additions).filter(([, v6]) => v6 !== void 0).forEach(([k5, v6]) => {
  46973. if (exception[k5] == void 0 || exception[k5] === "") {
  46974. exception[k5] = v6;
  46975. }
  46976. });
  46977. const message = exception.message || exception.Message || "UnknownError";
  46978. exception.message = message;
  46979. delete exception.Message;
  46980. return exception;
  46981. };
  46982. }
  46983. });
  46984. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
  46985. var throwDefaultError, withBaseException, deserializeMetadata;
  46986. var init_default_error_handler = __esm({
  46987. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js"() {
  46988. "use strict";
  46989. init_exceptions();
  46990. throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => {
  46991. const $metadata = deserializeMetadata(output);
  46992. const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0;
  46993. const response = new exceptionCtor({
  46994. name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
  46995. $fault: "client",
  46996. $metadata
  46997. });
  46998. throw decorateServiceException(response, parsedBody);
  46999. };
  47000. withBaseException = (ExceptionCtor) => {
  47001. return ({ output, parsedBody, errorCode }) => {
  47002. throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
  47003. };
  47004. };
  47005. deserializeMetadata = (output) => ({
  47006. httpStatusCode: output.statusCode,
  47007. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  47008. extendedRequestId: output.headers["x-amz-id-2"],
  47009. cfId: output.headers["x-amz-cf-id"]
  47010. });
  47011. }
  47012. });
  47013. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
  47014. var loadConfigsForDefaultMode;
  47015. var init_defaults_mode = __esm({
  47016. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js"() {
  47017. "use strict";
  47018. loadConfigsForDefaultMode = (mode) => {
  47019. switch (mode) {
  47020. case "standard":
  47021. return {
  47022. retryMode: "standard",
  47023. connectionTimeout: 3100
  47024. };
  47025. case "in-region":
  47026. return {
  47027. retryMode: "standard",
  47028. connectionTimeout: 1100
  47029. };
  47030. case "cross-region":
  47031. return {
  47032. retryMode: "standard",
  47033. connectionTimeout: 3100
  47034. };
  47035. case "mobile":
  47036. return {
  47037. retryMode: "standard",
  47038. connectionTimeout: 3e4
  47039. };
  47040. default:
  47041. return {};
  47042. }
  47043. };
  47044. }
  47045. });
  47046. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js
  47047. var warningEmitted, emitWarningIfUnsupportedVersion2;
  47048. var init_emitWarningIfUnsupportedVersion2 = __esm({
  47049. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js"() {
  47050. "use strict";
  47051. warningEmitted = false;
  47052. emitWarningIfUnsupportedVersion2 = (version) => {
  47053. if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) {
  47054. warningEmitted = true;
  47055. }
  47056. };
  47057. }
  47058. });
  47059. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js
  47060. var init_extended_encode_uri_component2 = __esm({
  47061. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js"() {
  47062. "use strict";
  47063. init_protocols();
  47064. }
  47065. });
  47066. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
  47067. var getChecksumConfiguration2, resolveChecksumRuntimeConfig2;
  47068. var init_checksum3 = __esm({
  47069. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js"() {
  47070. "use strict";
  47071. init_dist_es();
  47072. getChecksumConfiguration2 = (runtimeConfig) => {
  47073. const checksumAlgorithms = [];
  47074. for (const id in AlgorithmId) {
  47075. const algorithmId = AlgorithmId[id];
  47076. if (runtimeConfig[algorithmId] === void 0) {
  47077. continue;
  47078. }
  47079. checksumAlgorithms.push({
  47080. algorithmId: () => algorithmId,
  47081. checksumConstructor: () => runtimeConfig[algorithmId]
  47082. });
  47083. }
  47084. return {
  47085. addChecksumAlgorithm(algo) {
  47086. checksumAlgorithms.push(algo);
  47087. },
  47088. checksumAlgorithms() {
  47089. return checksumAlgorithms;
  47090. }
  47091. };
  47092. };
  47093. resolveChecksumRuntimeConfig2 = (clientConfig) => {
  47094. const runtimeConfig = {};
  47095. clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
  47096. runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
  47097. });
  47098. return runtimeConfig;
  47099. };
  47100. }
  47101. });
  47102. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
  47103. var getRetryConfiguration, resolveRetryRuntimeConfig;
  47104. var init_retry2 = __esm({
  47105. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js"() {
  47106. "use strict";
  47107. getRetryConfiguration = (runtimeConfig) => {
  47108. return {
  47109. setRetryStrategy(retryStrategy) {
  47110. runtimeConfig.retryStrategy = retryStrategy;
  47111. },
  47112. retryStrategy() {
  47113. return runtimeConfig.retryStrategy;
  47114. }
  47115. };
  47116. };
  47117. resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {
  47118. const runtimeConfig = {};
  47119. runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
  47120. return runtimeConfig;
  47121. };
  47122. }
  47123. });
  47124. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
  47125. var getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig;
  47126. var init_defaultExtensionConfiguration2 = __esm({
  47127. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js"() {
  47128. "use strict";
  47129. init_checksum3();
  47130. init_retry2();
  47131. getDefaultExtensionConfiguration = (runtimeConfig) => {
  47132. return Object.assign(getChecksumConfiguration2(runtimeConfig), getRetryConfiguration(runtimeConfig));
  47133. };
  47134. resolveDefaultRuntimeConfig = (config) => {
  47135. return Object.assign(resolveChecksumRuntimeConfig2(config), resolveRetryRuntimeConfig(config));
  47136. };
  47137. }
  47138. });
  47139. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/index.js
  47140. var init_extensions3 = __esm({
  47141. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/extensions/index.js"() {
  47142. "use strict";
  47143. init_defaultExtensionConfiguration2();
  47144. }
  47145. });
  47146. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js
  47147. var init_get_array_if_single_item = __esm({
  47148. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js"() {
  47149. "use strict";
  47150. }
  47151. });
  47152. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js
  47153. var getValueFromTextNode;
  47154. var init_get_value_from_text_node = __esm({
  47155. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js"() {
  47156. "use strict";
  47157. getValueFromTextNode = (obj) => {
  47158. const textNodeName = "#text";
  47159. for (const key in obj) {
  47160. if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) {
  47161. obj[key] = obj[key][textNodeName];
  47162. } else if (typeof obj[key] === "object" && obj[key] !== null) {
  47163. obj[key] = getValueFromTextNode(obj[key]);
  47164. }
  47165. }
  47166. return obj;
  47167. };
  47168. }
  47169. });
  47170. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js
  47171. var isSerializableHeaderValue;
  47172. var init_is_serializable_header_value = __esm({
  47173. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js"() {
  47174. "use strict";
  47175. isSerializableHeaderValue = (value) => {
  47176. return value != null;
  47177. };
  47178. }
  47179. });
  47180. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
  47181. var NoOpLogger;
  47182. var init_NoOpLogger = __esm({
  47183. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js"() {
  47184. "use strict";
  47185. NoOpLogger = class {
  47186. trace() {
  47187. }
  47188. debug() {
  47189. }
  47190. info() {
  47191. }
  47192. warn() {
  47193. }
  47194. error() {
  47195. }
  47196. };
  47197. }
  47198. });
  47199. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/object-mapping.js
  47200. function map(arg0, arg1, arg2) {
  47201. let target;
  47202. let filter2;
  47203. let instructions;
  47204. if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
  47205. target = {};
  47206. instructions = arg0;
  47207. } else {
  47208. target = arg0;
  47209. if (typeof arg1 === "function") {
  47210. filter2 = arg1;
  47211. instructions = arg2;
  47212. return mapWithFilter(target, filter2, instructions);
  47213. } else {
  47214. instructions = arg1;
  47215. }
  47216. }
  47217. for (const key of Object.keys(instructions)) {
  47218. if (!Array.isArray(instructions[key])) {
  47219. target[key] = instructions[key];
  47220. continue;
  47221. }
  47222. applyInstruction(target, null, instructions, key);
  47223. }
  47224. return target;
  47225. }
  47226. var take, mapWithFilter, applyInstruction, nonNullish, pass;
  47227. var init_object_mapping = __esm({
  47228. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/object-mapping.js"() {
  47229. "use strict";
  47230. take = (source, instructions) => {
  47231. const out = {};
  47232. for (const key in instructions) {
  47233. applyInstruction(out, source, instructions, key);
  47234. }
  47235. return out;
  47236. };
  47237. mapWithFilter = (target, filter2, instructions) => {
  47238. return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
  47239. if (Array.isArray(value)) {
  47240. _instructions[key] = value;
  47241. } else {
  47242. if (typeof value === "function") {
  47243. _instructions[key] = [filter2, value()];
  47244. } else {
  47245. _instructions[key] = [filter2, value];
  47246. }
  47247. }
  47248. return _instructions;
  47249. }, {}));
  47250. };
  47251. applyInstruction = (target, source, instructions, targetKey) => {
  47252. if (source !== null) {
  47253. let instruction = instructions[targetKey];
  47254. if (typeof instruction === "function") {
  47255. instruction = [, instruction];
  47256. }
  47257. const [filter3 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
  47258. if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
  47259. target[targetKey] = valueFn(source[sourceKey]);
  47260. }
  47261. return;
  47262. }
  47263. let [filter2, value] = instructions[targetKey];
  47264. if (typeof value === "function") {
  47265. let _value;
  47266. const defaultFilterPassed = filter2 === void 0 && (_value = value()) != null;
  47267. const customFilterPassed = typeof filter2 === "function" && !!filter2(void 0) || typeof filter2 !== "function" && !!filter2;
  47268. if (defaultFilterPassed) {
  47269. target[targetKey] = _value;
  47270. } else if (customFilterPassed) {
  47271. target[targetKey] = value();
  47272. }
  47273. } else {
  47274. const defaultFilterPassed = filter2 === void 0 && value != null;
  47275. const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
  47276. if (defaultFilterPassed || customFilterPassed) {
  47277. target[targetKey] = value;
  47278. }
  47279. }
  47280. };
  47281. nonNullish = (_3) => _3 != null;
  47282. pass = (_3) => _3;
  47283. }
  47284. });
  47285. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/resolve-path.js
  47286. var init_resolve_path2 = __esm({
  47287. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/resolve-path.js"() {
  47288. "use strict";
  47289. init_protocols();
  47290. }
  47291. });
  47292. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/ser-utils.js
  47293. var serializeFloat;
  47294. var init_ser_utils = __esm({
  47295. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/ser-utils.js"() {
  47296. "use strict";
  47297. serializeFloat = (value) => {
  47298. if (value !== value) {
  47299. return "NaN";
  47300. }
  47301. switch (value) {
  47302. case Infinity:
  47303. return "Infinity";
  47304. case -Infinity:
  47305. return "-Infinity";
  47306. default:
  47307. return value;
  47308. }
  47309. };
  47310. }
  47311. });
  47312. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/serde-json.js
  47313. var _json;
  47314. var init_serde_json = __esm({
  47315. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/serde-json.js"() {
  47316. "use strict";
  47317. _json = (obj) => {
  47318. if (obj == null) {
  47319. return {};
  47320. }
  47321. if (Array.isArray(obj)) {
  47322. return obj.filter((_3) => _3 != null).map(_json);
  47323. }
  47324. if (typeof obj === "object") {
  47325. const target = {};
  47326. for (const key of Object.keys(obj)) {
  47327. if (obj[key] == null) {
  47328. continue;
  47329. }
  47330. target[key] = _json(obj[key]);
  47331. }
  47332. return target;
  47333. }
  47334. return obj;
  47335. };
  47336. }
  47337. });
  47338. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/index.js
  47339. var init_dist_es24 = __esm({
  47340. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-es/index.js"() {
  47341. "use strict";
  47342. init_client3();
  47343. init_collect_stream_body2();
  47344. init_command2();
  47345. init_constants4();
  47346. init_create_aggregated_client();
  47347. init_default_error_handler();
  47348. init_defaults_mode();
  47349. init_emitWarningIfUnsupportedVersion2();
  47350. init_exceptions();
  47351. init_extended_encode_uri_component2();
  47352. init_extensions3();
  47353. init_get_array_if_single_item();
  47354. init_get_value_from_text_node();
  47355. init_is_serializable_header_value();
  47356. init_NoOpLogger();
  47357. init_object_mapping();
  47358. init_resolve_path2();
  47359. init_ser_utils();
  47360. init_serde_json();
  47361. init_serde2();
  47362. }
  47363. });
  47364. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js
  47365. var awsExpectUnion;
  47366. var init_awsExpectUnion = __esm({
  47367. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() {
  47368. "use strict";
  47369. init_dist_es24();
  47370. awsExpectUnion = (value) => {
  47371. if (value == null) {
  47372. return void 0;
  47373. }
  47374. if (typeof value === "object" && "__type" in value) {
  47375. delete value.__type;
  47376. }
  47377. return expectUnion(value);
  47378. };
  47379. }
  47380. });
  47381. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js
  47382. var collectBodyString;
  47383. var init_common2 = __esm({
  47384. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() {
  47385. "use strict";
  47386. init_dist_es24();
  47387. collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => context.utf8Encoder(body));
  47388. }
  47389. });
  47390. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js
  47391. var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode;
  47392. var init_parseJsonBody = __esm({
  47393. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() {
  47394. "use strict";
  47395. init_common2();
  47396. parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
  47397. if (encoded.length) {
  47398. try {
  47399. return JSON.parse(encoded);
  47400. } catch (e6) {
  47401. if (e6?.name === "SyntaxError") {
  47402. Object.defineProperty(e6, "$responseBodyText", {
  47403. value: encoded
  47404. });
  47405. }
  47406. throw e6;
  47407. }
  47408. }
  47409. return {};
  47410. });
  47411. parseJsonErrorBody = async (errorBody, context) => {
  47412. const value = await parseJsonBody(errorBody, context);
  47413. value.message = value.message ?? value.Message;
  47414. return value;
  47415. };
  47416. loadRestJsonErrorCode = (output, data) => {
  47417. const findKey = (object, key) => Object.keys(object).find((k5) => k5.toLowerCase() === key.toLowerCase());
  47418. const sanitizeErrorCode = (rawValue) => {
  47419. let cleanValue = rawValue;
  47420. if (typeof cleanValue === "number") {
  47421. cleanValue = cleanValue.toString();
  47422. }
  47423. if (cleanValue.indexOf(",") >= 0) {
  47424. cleanValue = cleanValue.split(",")[0];
  47425. }
  47426. if (cleanValue.indexOf(":") >= 0) {
  47427. cleanValue = cleanValue.split(":")[0];
  47428. }
  47429. if (cleanValue.indexOf("#") >= 0) {
  47430. cleanValue = cleanValue.split("#")[1];
  47431. }
  47432. return cleanValue;
  47433. };
  47434. const headerKey = findKey(output.headers, "x-amzn-errortype");
  47435. if (headerKey !== void 0) {
  47436. return sanitizeErrorCode(output.headers[headerKey]);
  47437. }
  47438. if (data && typeof data === "object") {
  47439. const codeKey = findKey(data, "code");
  47440. if (codeKey && data[codeKey] !== void 0) {
  47441. return sanitizeErrorCode(data[codeKey]);
  47442. }
  47443. if (data["__type"] !== void 0) {
  47444. return sanitizeErrorCode(data["__type"]);
  47445. }
  47446. }
  47447. };
  47448. }
  47449. });
  47450. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js
  47451. var require_util2 = __commonJS({
  47452. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js"(exports) {
  47453. "use strict";
  47454. var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
  47455. var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
  47456. var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
  47457. var regexName = new RegExp("^" + nameRegexp + "$");
  47458. var getAllMatches = function(string, regex) {
  47459. const matches = [];
  47460. let match2 = regex.exec(string);
  47461. while (match2) {
  47462. const allmatches = [];
  47463. allmatches.startIndex = regex.lastIndex - match2[0].length;
  47464. const len = match2.length;
  47465. for (let index6 = 0; index6 < len; index6++) {
  47466. allmatches.push(match2[index6]);
  47467. }
  47468. matches.push(allmatches);
  47469. match2 = regex.exec(string);
  47470. }
  47471. return matches;
  47472. };
  47473. var isName = function(string) {
  47474. const match2 = regexName.exec(string);
  47475. return !(match2 === null || typeof match2 === "undefined");
  47476. };
  47477. exports.isExist = function(v6) {
  47478. return typeof v6 !== "undefined";
  47479. };
  47480. exports.isEmptyObject = function(obj) {
  47481. return Object.keys(obj).length === 0;
  47482. };
  47483. exports.merge = function(target, a5, arrayMode) {
  47484. if (a5) {
  47485. const keys = Object.keys(a5);
  47486. const len = keys.length;
  47487. for (let i6 = 0; i6 < len; i6++) {
  47488. if (arrayMode === "strict") {
  47489. target[keys[i6]] = [a5[keys[i6]]];
  47490. } else {
  47491. target[keys[i6]] = a5[keys[i6]];
  47492. }
  47493. }
  47494. }
  47495. };
  47496. exports.getValue = function(v6) {
  47497. if (exports.isExist(v6)) {
  47498. return v6;
  47499. } else {
  47500. return "";
  47501. }
  47502. };
  47503. exports.isName = isName;
  47504. exports.getAllMatches = getAllMatches;
  47505. exports.nameRegexp = nameRegexp;
  47506. }
  47507. });
  47508. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js
  47509. var require_validator = __commonJS({
  47510. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js"(exports) {
  47511. "use strict";
  47512. var util2 = require_util2();
  47513. var defaultOptions = {
  47514. allowBooleanAttributes: false,
  47515. //A tag can have attributes without any value
  47516. unpairedTags: []
  47517. };
  47518. exports.validate = function(xmlData, options) {
  47519. options = Object.assign({}, defaultOptions, options);
  47520. const tags = [];
  47521. let tagFound = false;
  47522. let reachedRoot = false;
  47523. if (xmlData[0] === "\uFEFF") {
  47524. xmlData = xmlData.substr(1);
  47525. }
  47526. for (let i6 = 0; i6 < xmlData.length; i6++) {
  47527. if (xmlData[i6] === "<" && xmlData[i6 + 1] === "?") {
  47528. i6 += 2;
  47529. i6 = readPI(xmlData, i6);
  47530. if (i6.err) return i6;
  47531. } else if (xmlData[i6] === "<") {
  47532. let tagStartPos = i6;
  47533. i6++;
  47534. if (xmlData[i6] === "!") {
  47535. i6 = readCommentAndCDATA(xmlData, i6);
  47536. continue;
  47537. } else {
  47538. let closingTag = false;
  47539. if (xmlData[i6] === "/") {
  47540. closingTag = true;
  47541. i6++;
  47542. }
  47543. let tagName = "";
  47544. for (; i6 < xmlData.length && xmlData[i6] !== ">" && xmlData[i6] !== " " && xmlData[i6] !== " " && xmlData[i6] !== "\n" && xmlData[i6] !== "\r"; i6++) {
  47545. tagName += xmlData[i6];
  47546. }
  47547. tagName = tagName.trim();
  47548. if (tagName[tagName.length - 1] === "/") {
  47549. tagName = tagName.substring(0, tagName.length - 1);
  47550. i6--;
  47551. }
  47552. if (!validateTagName(tagName)) {
  47553. let msg;
  47554. if (tagName.trim().length === 0) {
  47555. msg = "Invalid space after '<'.";
  47556. } else {
  47557. msg = "Tag '" + tagName + "' is an invalid name.";
  47558. }
  47559. return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i6));
  47560. }
  47561. const result = readAttributeStr(xmlData, i6);
  47562. if (result === false) {
  47563. return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i6));
  47564. }
  47565. let attrStr = result.value;
  47566. i6 = result.index;
  47567. if (attrStr[attrStr.length - 1] === "/") {
  47568. const attrStrStart = i6 - attrStr.length;
  47569. attrStr = attrStr.substring(0, attrStr.length - 1);
  47570. const isValid2 = validateAttributeString(attrStr, options);
  47571. if (isValid2 === true) {
  47572. tagFound = true;
  47573. } else {
  47574. return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid2.err.line));
  47575. }
  47576. } else if (closingTag) {
  47577. if (!result.tagClosed) {
  47578. return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i6));
  47579. } else if (attrStr.trim().length > 0) {
  47580. return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
  47581. } else if (tags.length === 0) {
  47582. return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
  47583. } else {
  47584. const otg = tags.pop();
  47585. if (tagName !== otg.tagName) {
  47586. let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
  47587. return getErrorObject(
  47588. "InvalidTag",
  47589. "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.",
  47590. getLineNumberForPosition(xmlData, tagStartPos)
  47591. );
  47592. }
  47593. if (tags.length == 0) {
  47594. reachedRoot = true;
  47595. }
  47596. }
  47597. } else {
  47598. const isValid2 = validateAttributeString(attrStr, options);
  47599. if (isValid2 !== true) {
  47600. return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, i6 - attrStr.length + isValid2.err.line));
  47601. }
  47602. if (reachedRoot === true) {
  47603. return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i6));
  47604. } else if (options.unpairedTags.indexOf(tagName) !== -1) {
  47605. } else {
  47606. tags.push({ tagName, tagStartPos });
  47607. }
  47608. tagFound = true;
  47609. }
  47610. for (i6++; i6 < xmlData.length; i6++) {
  47611. if (xmlData[i6] === "<") {
  47612. if (xmlData[i6 + 1] === "!") {
  47613. i6++;
  47614. i6 = readCommentAndCDATA(xmlData, i6);
  47615. continue;
  47616. } else if (xmlData[i6 + 1] === "?") {
  47617. i6 = readPI(xmlData, ++i6);
  47618. if (i6.err) return i6;
  47619. } else {
  47620. break;
  47621. }
  47622. } else if (xmlData[i6] === "&") {
  47623. const afterAmp = validateAmpersand(xmlData, i6);
  47624. if (afterAmp == -1)
  47625. return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i6));
  47626. i6 = afterAmp;
  47627. } else {
  47628. if (reachedRoot === true && !isWhiteSpace(xmlData[i6])) {
  47629. return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i6));
  47630. }
  47631. }
  47632. }
  47633. if (xmlData[i6] === "<") {
  47634. i6--;
  47635. }
  47636. }
  47637. } else {
  47638. if (isWhiteSpace(xmlData[i6])) {
  47639. continue;
  47640. }
  47641. return getErrorObject("InvalidChar", "char '" + xmlData[i6] + "' is not expected.", getLineNumberForPosition(xmlData, i6));
  47642. }
  47643. }
  47644. if (!tagFound) {
  47645. return getErrorObject("InvalidXml", "Start tag expected.", 1);
  47646. } else if (tags.length == 1) {
  47647. return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
  47648. } else if (tags.length > 0) {
  47649. return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t6) => t6.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
  47650. }
  47651. return true;
  47652. };
  47653. function isWhiteSpace(char) {
  47654. return char === " " || char === " " || char === "\n" || char === "\r";
  47655. }
  47656. function readPI(xmlData, i6) {
  47657. const start = i6;
  47658. for (; i6 < xmlData.length; i6++) {
  47659. if (xmlData[i6] == "?" || xmlData[i6] == " ") {
  47660. const tagname = xmlData.substr(start, i6 - start);
  47661. if (i6 > 5 && tagname === "xml") {
  47662. return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i6));
  47663. } else if (xmlData[i6] == "?" && xmlData[i6 + 1] == ">") {
  47664. i6++;
  47665. break;
  47666. } else {
  47667. continue;
  47668. }
  47669. }
  47670. }
  47671. return i6;
  47672. }
  47673. function readCommentAndCDATA(xmlData, i6) {
  47674. if (xmlData.length > i6 + 5 && xmlData[i6 + 1] === "-" && xmlData[i6 + 2] === "-") {
  47675. for (i6 += 3; i6 < xmlData.length; i6++) {
  47676. if (xmlData[i6] === "-" && xmlData[i6 + 1] === "-" && xmlData[i6 + 2] === ">") {
  47677. i6 += 2;
  47678. break;
  47679. }
  47680. }
  47681. } else if (xmlData.length > i6 + 8 && xmlData[i6 + 1] === "D" && xmlData[i6 + 2] === "O" && xmlData[i6 + 3] === "C" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "Y" && xmlData[i6 + 6] === "P" && xmlData[i6 + 7] === "E") {
  47682. let angleBracketsCount = 1;
  47683. for (i6 += 8; i6 < xmlData.length; i6++) {
  47684. if (xmlData[i6] === "<") {
  47685. angleBracketsCount++;
  47686. } else if (xmlData[i6] === ">") {
  47687. angleBracketsCount--;
  47688. if (angleBracketsCount === 0) {
  47689. break;
  47690. }
  47691. }
  47692. }
  47693. } else if (xmlData.length > i6 + 9 && xmlData[i6 + 1] === "[" && xmlData[i6 + 2] === "C" && xmlData[i6 + 3] === "D" && xmlData[i6 + 4] === "A" && xmlData[i6 + 5] === "T" && xmlData[i6 + 6] === "A" && xmlData[i6 + 7] === "[") {
  47694. for (i6 += 8; i6 < xmlData.length; i6++) {
  47695. if (xmlData[i6] === "]" && xmlData[i6 + 1] === "]" && xmlData[i6 + 2] === ">") {
  47696. i6 += 2;
  47697. break;
  47698. }
  47699. }
  47700. }
  47701. return i6;
  47702. }
  47703. var doubleQuote = '"';
  47704. var singleQuote = "'";
  47705. function readAttributeStr(xmlData, i6) {
  47706. let attrStr = "";
  47707. let startChar = "";
  47708. let tagClosed = false;
  47709. for (; i6 < xmlData.length; i6++) {
  47710. if (xmlData[i6] === doubleQuote || xmlData[i6] === singleQuote) {
  47711. if (startChar === "") {
  47712. startChar = xmlData[i6];
  47713. } else if (startChar !== xmlData[i6]) {
  47714. } else {
  47715. startChar = "";
  47716. }
  47717. } else if (xmlData[i6] === ">") {
  47718. if (startChar === "") {
  47719. tagClosed = true;
  47720. break;
  47721. }
  47722. }
  47723. attrStr += xmlData[i6];
  47724. }
  47725. if (startChar !== "") {
  47726. return false;
  47727. }
  47728. return {
  47729. value: attrStr,
  47730. index: i6,
  47731. tagClosed
  47732. };
  47733. }
  47734. var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
  47735. function validateAttributeString(attrStr, options) {
  47736. const matches = util2.getAllMatches(attrStr, validAttrStrRegxp);
  47737. const attrNames = {};
  47738. for (let i6 = 0; i6 < matches.length; i6++) {
  47739. if (matches[i6][1].length === 0) {
  47740. return getErrorObject("InvalidAttr", "Attribute '" + matches[i6][2] + "' has no space in starting.", getPositionFromMatch(matches[i6]));
  47741. } else if (matches[i6][3] !== void 0 && matches[i6][4] === void 0) {
  47742. return getErrorObject("InvalidAttr", "Attribute '" + matches[i6][2] + "' is without value.", getPositionFromMatch(matches[i6]));
  47743. } else if (matches[i6][3] === void 0 && !options.allowBooleanAttributes) {
  47744. return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i6][2] + "' is not allowed.", getPositionFromMatch(matches[i6]));
  47745. }
  47746. const attrName = matches[i6][2];
  47747. if (!validateAttrName(attrName)) {
  47748. return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i6]));
  47749. }
  47750. if (!attrNames.hasOwnProperty(attrName)) {
  47751. attrNames[attrName] = 1;
  47752. } else {
  47753. return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i6]));
  47754. }
  47755. }
  47756. return true;
  47757. }
  47758. function validateNumberAmpersand(xmlData, i6) {
  47759. let re = /\d/;
  47760. if (xmlData[i6] === "x") {
  47761. i6++;
  47762. re = /[\da-fA-F]/;
  47763. }
  47764. for (; i6 < xmlData.length; i6++) {
  47765. if (xmlData[i6] === ";")
  47766. return i6;
  47767. if (!xmlData[i6].match(re))
  47768. break;
  47769. }
  47770. return -1;
  47771. }
  47772. function validateAmpersand(xmlData, i6) {
  47773. i6++;
  47774. if (xmlData[i6] === ";")
  47775. return -1;
  47776. if (xmlData[i6] === "#") {
  47777. i6++;
  47778. return validateNumberAmpersand(xmlData, i6);
  47779. }
  47780. let count = 0;
  47781. for (; i6 < xmlData.length; i6++, count++) {
  47782. if (xmlData[i6].match(/\w/) && count < 20)
  47783. continue;
  47784. if (xmlData[i6] === ";")
  47785. break;
  47786. return -1;
  47787. }
  47788. return i6;
  47789. }
  47790. function getErrorObject(code, message, lineNumber) {
  47791. return {
  47792. err: {
  47793. code,
  47794. msg: message,
  47795. line: lineNumber.line || lineNumber,
  47796. col: lineNumber.col
  47797. }
  47798. };
  47799. }
  47800. function validateAttrName(attrName) {
  47801. return util2.isName(attrName);
  47802. }
  47803. function validateTagName(tagname) {
  47804. return util2.isName(tagname);
  47805. }
  47806. function getLineNumberForPosition(xmlData, index6) {
  47807. const lines = xmlData.substring(0, index6).split(/\r?\n/);
  47808. return {
  47809. line: lines.length,
  47810. // column number is last line's length + 1, because column numbering starts at 1:
  47811. col: lines[lines.length - 1].length + 1
  47812. };
  47813. }
  47814. function getPositionFromMatch(match2) {
  47815. return match2.startIndex + match2[1].length;
  47816. }
  47817. }
  47818. });
  47819. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
  47820. var require_OptionsBuilder = __commonJS({
  47821. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports) {
  47822. "use strict";
  47823. var defaultOptions = {
  47824. preserveOrder: false,
  47825. attributeNamePrefix: "@_",
  47826. attributesGroupName: false,
  47827. textNodeName: "#text",
  47828. ignoreAttributes: true,
  47829. removeNSPrefix: false,
  47830. // remove NS from tag name or attribute name if true
  47831. allowBooleanAttributes: false,
  47832. //a tag can have attributes without any value
  47833. //ignoreRootElement : false,
  47834. parseTagValue: true,
  47835. parseAttributeValue: false,
  47836. trimValues: true,
  47837. //Trim string values of tag and attributes
  47838. cdataPropName: false,
  47839. numberParseOptions: {
  47840. hex: true,
  47841. leadingZeros: true,
  47842. eNotation: true
  47843. },
  47844. tagValueProcessor: function(tagName, val2) {
  47845. return val2;
  47846. },
  47847. attributeValueProcessor: function(attrName, val2) {
  47848. return val2;
  47849. },
  47850. stopNodes: [],
  47851. //nested tags will not be parsed even for errors
  47852. alwaysCreateTextNode: false,
  47853. isArray: () => false,
  47854. commentPropName: false,
  47855. unpairedTags: [],
  47856. processEntities: true,
  47857. htmlEntities: false,
  47858. ignoreDeclaration: false,
  47859. ignorePiTags: false,
  47860. transformTagName: false,
  47861. transformAttributeName: false,
  47862. updateTag: function(tagName, jPath, attrs) {
  47863. return tagName;
  47864. }
  47865. // skipEmptyListItem: false
  47866. };
  47867. var buildOptions = function(options) {
  47868. return Object.assign({}, defaultOptions, options);
  47869. };
  47870. exports.buildOptions = buildOptions;
  47871. exports.defaultOptions = defaultOptions;
  47872. }
  47873. });
  47874. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
  47875. var require_xmlNode = __commonJS({
  47876. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports, module) {
  47877. "use strict";
  47878. var XmlNode = class {
  47879. constructor(tagname) {
  47880. this.tagname = tagname;
  47881. this.child = [];
  47882. this[":@"] = {};
  47883. }
  47884. add(key, val2) {
  47885. if (key === "__proto__") key = "#__proto__";
  47886. this.child.push({ [key]: val2 });
  47887. }
  47888. addChild(node) {
  47889. if (node.tagname === "__proto__") node.tagname = "#__proto__";
  47890. if (node[":@"] && Object.keys(node[":@"]).length > 0) {
  47891. this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] });
  47892. } else {
  47893. this.child.push({ [node.tagname]: node.child });
  47894. }
  47895. }
  47896. };
  47897. module.exports = XmlNode;
  47898. }
  47899. });
  47900. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
  47901. var require_DocTypeReader = __commonJS({
  47902. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports, module) {
  47903. "use strict";
  47904. var util2 = require_util2();
  47905. function readDocType(xmlData, i6) {
  47906. const entities = {};
  47907. if (xmlData[i6 + 3] === "O" && xmlData[i6 + 4] === "C" && xmlData[i6 + 5] === "T" && xmlData[i6 + 6] === "Y" && xmlData[i6 + 7] === "P" && xmlData[i6 + 8] === "E") {
  47908. i6 = i6 + 9;
  47909. let angleBracketsCount = 1;
  47910. let hasBody = false, comment = false;
  47911. let exp = "";
  47912. for (; i6 < xmlData.length; i6++) {
  47913. if (xmlData[i6] === "<" && !comment) {
  47914. if (hasBody && isEntity(xmlData, i6)) {
  47915. i6 += 7;
  47916. [entityName, val, i6] = readEntityExp(xmlData, i6 + 1);
  47917. if (val.indexOf("&") === -1)
  47918. entities[validateEntityName(entityName)] = {
  47919. regx: RegExp(`&${entityName};`, "g"),
  47920. val
  47921. };
  47922. } else if (hasBody && isElement(xmlData, i6)) i6 += 8;
  47923. else if (hasBody && isAttlist(xmlData, i6)) i6 += 8;
  47924. else if (hasBody && isNotation(xmlData, i6)) i6 += 9;
  47925. else if (isComment) comment = true;
  47926. else throw new Error("Invalid DOCTYPE");
  47927. angleBracketsCount++;
  47928. exp = "";
  47929. } else if (xmlData[i6] === ">") {
  47930. if (comment) {
  47931. if (xmlData[i6 - 1] === "-" && xmlData[i6 - 2] === "-") {
  47932. comment = false;
  47933. angleBracketsCount--;
  47934. }
  47935. } else {
  47936. angleBracketsCount--;
  47937. }
  47938. if (angleBracketsCount === 0) {
  47939. break;
  47940. }
  47941. } else if (xmlData[i6] === "[") {
  47942. hasBody = true;
  47943. } else {
  47944. exp += xmlData[i6];
  47945. }
  47946. }
  47947. if (angleBracketsCount !== 0) {
  47948. throw new Error(`Unclosed DOCTYPE`);
  47949. }
  47950. } else {
  47951. throw new Error(`Invalid Tag instead of DOCTYPE`);
  47952. }
  47953. return { entities, i: i6 };
  47954. }
  47955. function readEntityExp(xmlData, i6) {
  47956. let entityName2 = "";
  47957. for (; i6 < xmlData.length && (xmlData[i6] !== "'" && xmlData[i6] !== '"'); i6++) {
  47958. entityName2 += xmlData[i6];
  47959. }
  47960. entityName2 = entityName2.trim();
  47961. if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported");
  47962. const startChar = xmlData[i6++];
  47963. let val2 = "";
  47964. for (; i6 < xmlData.length && xmlData[i6] !== startChar; i6++) {
  47965. val2 += xmlData[i6];
  47966. }
  47967. return [entityName2, val2, i6];
  47968. }
  47969. function isComment(xmlData, i6) {
  47970. if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "-" && xmlData[i6 + 3] === "-") return true;
  47971. return false;
  47972. }
  47973. function isEntity(xmlData, i6) {
  47974. if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "E" && xmlData[i6 + 3] === "N" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "I" && xmlData[i6 + 6] === "T" && xmlData[i6 + 7] === "Y") return true;
  47975. return false;
  47976. }
  47977. function isElement(xmlData, i6) {
  47978. if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "E" && xmlData[i6 + 3] === "L" && xmlData[i6 + 4] === "E" && xmlData[i6 + 5] === "M" && xmlData[i6 + 6] === "E" && xmlData[i6 + 7] === "N" && xmlData[i6 + 8] === "T") return true;
  47979. return false;
  47980. }
  47981. function isAttlist(xmlData, i6) {
  47982. if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "A" && xmlData[i6 + 3] === "T" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "L" && xmlData[i6 + 6] === "I" && xmlData[i6 + 7] === "S" && xmlData[i6 + 8] === "T") return true;
  47983. return false;
  47984. }
  47985. function isNotation(xmlData, i6) {
  47986. if (xmlData[i6 + 1] === "!" && xmlData[i6 + 2] === "N" && xmlData[i6 + 3] === "O" && xmlData[i6 + 4] === "T" && xmlData[i6 + 5] === "A" && xmlData[i6 + 6] === "T" && xmlData[i6 + 7] === "I" && xmlData[i6 + 8] === "O" && xmlData[i6 + 9] === "N") return true;
  47987. return false;
  47988. }
  47989. function validateEntityName(name) {
  47990. if (util2.isName(name))
  47991. return name;
  47992. else
  47993. throw new Error(`Invalid entity name ${name}`);
  47994. }
  47995. module.exports = readDocType;
  47996. }
  47997. });
  47998. // ../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js
  47999. var require_strnum = __commonJS({
  48000. "../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js"(exports, module) {
  48001. "use strict";
  48002. var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
  48003. var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;
  48004. var consider = {
  48005. hex: true,
  48006. // oct: false,
  48007. leadingZeros: true,
  48008. decimalPoint: ".",
  48009. eNotation: true
  48010. //skipLike: /regex/
  48011. };
  48012. function toNumber(str, options = {}) {
  48013. options = Object.assign({}, consider, options);
  48014. if (!str || typeof str !== "string") return str;
  48015. let trimmedStr = str.trim();
  48016. if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str;
  48017. else if (str === "0") return 0;
  48018. else if (options.hex && hexRegex.test(trimmedStr)) {
  48019. return parse_int(trimmedStr, 16);
  48020. } else if (trimmedStr.search(/[eE]/) !== -1) {
  48021. const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);
  48022. if (notation) {
  48023. if (options.leadingZeros) {
  48024. trimmedStr = (notation[1] || "") + notation[3];
  48025. } else {
  48026. if (notation[2] === "0" && notation[3][0] === ".") {
  48027. } else {
  48028. return str;
  48029. }
  48030. }
  48031. return options.eNotation ? Number(trimmedStr) : str;
  48032. } else {
  48033. return str;
  48034. }
  48035. } else {
  48036. const match2 = numRegex.exec(trimmedStr);
  48037. if (match2) {
  48038. const sign = match2[1];
  48039. const leadingZeros = match2[2];
  48040. let numTrimmedByZeros = trimZeros(match2[3]);
  48041. if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str;
  48042. else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str;
  48043. else if (options.leadingZeros && leadingZeros === str) return 0;
  48044. else {
  48045. const num = Number(trimmedStr);
  48046. const numStr = "" + num;
  48047. if (numStr.search(/[eE]/) !== -1) {
  48048. if (options.eNotation) return num;
  48049. else return str;
  48050. } else if (trimmedStr.indexOf(".") !== -1) {
  48051. if (numStr === "0" && numTrimmedByZeros === "") return num;
  48052. else if (numStr === numTrimmedByZeros) return num;
  48053. else if (sign && numStr === "-" + numTrimmedByZeros) return num;
  48054. else return str;
  48055. }
  48056. if (leadingZeros) {
  48057. return numTrimmedByZeros === numStr || sign + numTrimmedByZeros === numStr ? num : str;
  48058. } else {
  48059. return trimmedStr === numStr || trimmedStr === sign + numStr ? num : str;
  48060. }
  48061. }
  48062. } else {
  48063. return str;
  48064. }
  48065. }
  48066. }
  48067. function trimZeros(numStr) {
  48068. if (numStr && numStr.indexOf(".") !== -1) {
  48069. numStr = numStr.replace(/0+$/, "");
  48070. if (numStr === ".") numStr = "0";
  48071. else if (numStr[0] === ".") numStr = "0" + numStr;
  48072. else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1);
  48073. return numStr;
  48074. }
  48075. return numStr;
  48076. }
  48077. function parse_int(numStr, base) {
  48078. if (parseInt) return parseInt(numStr, base);
  48079. else if (Number.parseInt) return Number.parseInt(numStr, base);
  48080. else if (window && window.parseInt) return window.parseInt(numStr, base);
  48081. else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported");
  48082. }
  48083. module.exports = toNumber;
  48084. }
  48085. });
  48086. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
  48087. var require_OrderedObjParser = __commonJS({
  48088. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports, module) {
  48089. "use strict";
  48090. var util2 = require_util2();
  48091. var xmlNode = require_xmlNode();
  48092. var readDocType = require_DocTypeReader();
  48093. var toNumber = require_strnum();
  48094. var OrderedObjParser = class {
  48095. constructor(options) {
  48096. this.options = options;
  48097. this.currentNode = null;
  48098. this.tagsNodeStack = [];
  48099. this.docTypeEntities = {};
  48100. this.lastEntities = {
  48101. "apos": { regex: /&(apos|#39|#x27);/g, val: "'" },
  48102. "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" },
  48103. "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" },
  48104. "quot": { regex: /&(quot|#34|#x22);/g, val: '"' }
  48105. };
  48106. this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
  48107. this.htmlEntities = {
  48108. "space": { regex: /&(nbsp|#160);/g, val: " " },
  48109. // "lt" : { regex: /&(lt|#60);/g, val: "<" },
  48110. // "gt" : { regex: /&(gt|#62);/g, val: ">" },
  48111. // "amp" : { regex: /&(amp|#38);/g, val: "&" },
  48112. // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
  48113. // "apos" : { regex: /&(apos|#39);/g, val: "'" },
  48114. "cent": { regex: /&(cent|#162);/g, val: "\xA2" },
  48115. "pound": { regex: /&(pound|#163);/g, val: "\xA3" },
  48116. "yen": { regex: /&(yen|#165);/g, val: "\xA5" },
  48117. "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" },
  48118. "copyright": { regex: /&(copy|#169);/g, val: "\xA9" },
  48119. "reg": { regex: /&(reg|#174);/g, val: "\xAE" },
  48120. "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" },
  48121. "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 10)) },
  48122. "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 16)) }
  48123. };
  48124. this.addExternalEntities = addExternalEntities;
  48125. this.parseXml = parseXml;
  48126. this.parseTextData = parseTextData;
  48127. this.resolveNameSpace = resolveNameSpace;
  48128. this.buildAttributesMap = buildAttributesMap;
  48129. this.isItStopNode = isItStopNode;
  48130. this.replaceEntitiesValue = replaceEntitiesValue;
  48131. this.readStopNodeData = readStopNodeData;
  48132. this.saveTextToParentTag = saveTextToParentTag;
  48133. this.addChild = addChild;
  48134. }
  48135. };
  48136. function addExternalEntities(externalEntities) {
  48137. const entKeys = Object.keys(externalEntities);
  48138. for (let i6 = 0; i6 < entKeys.length; i6++) {
  48139. const ent = entKeys[i6];
  48140. this.lastEntities[ent] = {
  48141. regex: new RegExp("&" + ent + ";", "g"),
  48142. val: externalEntities[ent]
  48143. };
  48144. }
  48145. }
  48146. function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
  48147. if (val2 !== void 0) {
  48148. if (this.options.trimValues && !dontTrim) {
  48149. val2 = val2.trim();
  48150. }
  48151. if (val2.length > 0) {
  48152. if (!escapeEntities) val2 = this.replaceEntitiesValue(val2);
  48153. const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode);
  48154. if (newval === null || newval === void 0) {
  48155. return val2;
  48156. } else if (typeof newval !== typeof val2 || newval !== val2) {
  48157. return newval;
  48158. } else if (this.options.trimValues) {
  48159. return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
  48160. } else {
  48161. const trimmedVal = val2.trim();
  48162. if (trimmedVal === val2) {
  48163. return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
  48164. } else {
  48165. return val2;
  48166. }
  48167. }
  48168. }
  48169. }
  48170. }
  48171. function resolveNameSpace(tagname) {
  48172. if (this.options.removeNSPrefix) {
  48173. const tags = tagname.split(":");
  48174. const prefix2 = tagname.charAt(0) === "/" ? "/" : "";
  48175. if (tags[0] === "xmlns") {
  48176. return "";
  48177. }
  48178. if (tags.length === 2) {
  48179. tagname = prefix2 + tags[1];
  48180. }
  48181. }
  48182. return tagname;
  48183. }
  48184. var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
  48185. function buildAttributesMap(attrStr, jPath, tagName) {
  48186. if (!this.options.ignoreAttributes && typeof attrStr === "string") {
  48187. const matches = util2.getAllMatches(attrStr, attrsRegx);
  48188. const len = matches.length;
  48189. const attrs = {};
  48190. for (let i6 = 0; i6 < len; i6++) {
  48191. const attrName = this.resolveNameSpace(matches[i6][1]);
  48192. let oldVal = matches[i6][4];
  48193. let aName = this.options.attributeNamePrefix + attrName;
  48194. if (attrName.length) {
  48195. if (this.options.transformAttributeName) {
  48196. aName = this.options.transformAttributeName(aName);
  48197. }
  48198. if (aName === "__proto__") aName = "#__proto__";
  48199. if (oldVal !== void 0) {
  48200. if (this.options.trimValues) {
  48201. oldVal = oldVal.trim();
  48202. }
  48203. oldVal = this.replaceEntitiesValue(oldVal);
  48204. const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
  48205. if (newVal === null || newVal === void 0) {
  48206. attrs[aName] = oldVal;
  48207. } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
  48208. attrs[aName] = newVal;
  48209. } else {
  48210. attrs[aName] = parseValue(
  48211. oldVal,
  48212. this.options.parseAttributeValue,
  48213. this.options.numberParseOptions
  48214. );
  48215. }
  48216. } else if (this.options.allowBooleanAttributes) {
  48217. attrs[aName] = true;
  48218. }
  48219. }
  48220. }
  48221. if (!Object.keys(attrs).length) {
  48222. return;
  48223. }
  48224. if (this.options.attributesGroupName) {
  48225. const attrCollection = {};
  48226. attrCollection[this.options.attributesGroupName] = attrs;
  48227. return attrCollection;
  48228. }
  48229. return attrs;
  48230. }
  48231. }
  48232. var parseXml = function(xmlData) {
  48233. xmlData = xmlData.replace(/\r\n?/g, "\n");
  48234. const xmlObj = new xmlNode("!xml");
  48235. let currentNode = xmlObj;
  48236. let textData = "";
  48237. let jPath = "";
  48238. for (let i6 = 0; i6 < xmlData.length; i6++) {
  48239. const ch = xmlData[i6];
  48240. if (ch === "<") {
  48241. if (xmlData[i6 + 1] === "/") {
  48242. const closeIndex = findClosingIndex(xmlData, ">", i6, "Closing Tag is not closed.");
  48243. let tagName = xmlData.substring(i6 + 2, closeIndex).trim();
  48244. if (this.options.removeNSPrefix) {
  48245. const colonIndex = tagName.indexOf(":");
  48246. if (colonIndex !== -1) {
  48247. tagName = tagName.substr(colonIndex + 1);
  48248. }
  48249. }
  48250. if (this.options.transformTagName) {
  48251. tagName = this.options.transformTagName(tagName);
  48252. }
  48253. if (currentNode) {
  48254. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  48255. }
  48256. const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1);
  48257. if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) {
  48258. throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
  48259. }
  48260. let propIndex = 0;
  48261. if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) {
  48262. propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1);
  48263. this.tagsNodeStack.pop();
  48264. } else {
  48265. propIndex = jPath.lastIndexOf(".");
  48266. }
  48267. jPath = jPath.substring(0, propIndex);
  48268. currentNode = this.tagsNodeStack.pop();
  48269. textData = "";
  48270. i6 = closeIndex;
  48271. } else if (xmlData[i6 + 1] === "?") {
  48272. let tagData = readTagExp(xmlData, i6, false, "?>");
  48273. if (!tagData) throw new Error("Pi Tag is not closed.");
  48274. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  48275. if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) {
  48276. } else {
  48277. const childNode = new xmlNode(tagData.tagName);
  48278. childNode.add(this.options.textNodeName, "");
  48279. if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
  48280. childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
  48281. }
  48282. this.addChild(currentNode, childNode, jPath);
  48283. }
  48284. i6 = tagData.closeIndex + 1;
  48285. } else if (xmlData.substr(i6 + 1, 3) === "!--") {
  48286. const endIndex = findClosingIndex(xmlData, "-->", i6 + 4, "Comment is not closed.");
  48287. if (this.options.commentPropName) {
  48288. const comment = xmlData.substring(i6 + 4, endIndex - 2);
  48289. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  48290. currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
  48291. }
  48292. i6 = endIndex;
  48293. } else if (xmlData.substr(i6 + 1, 2) === "!D") {
  48294. const result = readDocType(xmlData, i6);
  48295. this.docTypeEntities = result.entities;
  48296. i6 = result.i;
  48297. } else if (xmlData.substr(i6 + 1, 2) === "![") {
  48298. const closeIndex = findClosingIndex(xmlData, "]]>", i6, "CDATA is not closed.") - 2;
  48299. const tagExp = xmlData.substring(i6 + 9, closeIndex);
  48300. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  48301. let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
  48302. if (val2 == void 0) val2 = "";
  48303. if (this.options.cdataPropName) {
  48304. currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
  48305. } else {
  48306. currentNode.add(this.options.textNodeName, val2);
  48307. }
  48308. i6 = closeIndex + 2;
  48309. } else {
  48310. let result = readTagExp(xmlData, i6, this.options.removeNSPrefix);
  48311. let tagName = result.tagName;
  48312. const rawTagName = result.rawTagName;
  48313. let tagExp = result.tagExp;
  48314. let attrExpPresent = result.attrExpPresent;
  48315. let closeIndex = result.closeIndex;
  48316. if (this.options.transformTagName) {
  48317. tagName = this.options.transformTagName(tagName);
  48318. }
  48319. if (currentNode && textData) {
  48320. if (currentNode.tagname !== "!xml") {
  48321. textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
  48322. }
  48323. }
  48324. const lastTag = currentNode;
  48325. if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) {
  48326. currentNode = this.tagsNodeStack.pop();
  48327. jPath = jPath.substring(0, jPath.lastIndexOf("."));
  48328. }
  48329. if (tagName !== xmlObj.tagname) {
  48330. jPath += jPath ? "." + tagName : tagName;
  48331. }
  48332. if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
  48333. let tagContent = "";
  48334. if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
  48335. if (tagName[tagName.length - 1] === "/") {
  48336. tagName = tagName.substr(0, tagName.length - 1);
  48337. jPath = jPath.substr(0, jPath.length - 1);
  48338. tagExp = tagName;
  48339. } else {
  48340. tagExp = tagExp.substr(0, tagExp.length - 1);
  48341. }
  48342. i6 = result.closeIndex;
  48343. } else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
  48344. i6 = result.closeIndex;
  48345. } else {
  48346. const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
  48347. if (!result2) throw new Error(`Unexpected end of ${rawTagName}`);
  48348. i6 = result2.i;
  48349. tagContent = result2.tagContent;
  48350. }
  48351. const childNode = new xmlNode(tagName);
  48352. if (tagName !== tagExp && attrExpPresent) {
  48353. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  48354. }
  48355. if (tagContent) {
  48356. tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
  48357. }
  48358. jPath = jPath.substr(0, jPath.lastIndexOf("."));
  48359. childNode.add(this.options.textNodeName, tagContent);
  48360. this.addChild(currentNode, childNode, jPath);
  48361. } else {
  48362. if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
  48363. if (tagName[tagName.length - 1] === "/") {
  48364. tagName = tagName.substr(0, tagName.length - 1);
  48365. jPath = jPath.substr(0, jPath.length - 1);
  48366. tagExp = tagName;
  48367. } else {
  48368. tagExp = tagExp.substr(0, tagExp.length - 1);
  48369. }
  48370. if (this.options.transformTagName) {
  48371. tagName = this.options.transformTagName(tagName);
  48372. }
  48373. const childNode = new xmlNode(tagName);
  48374. if (tagName !== tagExp && attrExpPresent) {
  48375. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  48376. }
  48377. this.addChild(currentNode, childNode, jPath);
  48378. jPath = jPath.substr(0, jPath.lastIndexOf("."));
  48379. } else {
  48380. const childNode = new xmlNode(tagName);
  48381. this.tagsNodeStack.push(currentNode);
  48382. if (tagName !== tagExp && attrExpPresent) {
  48383. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  48384. }
  48385. this.addChild(currentNode, childNode, jPath);
  48386. currentNode = childNode;
  48387. }
  48388. textData = "";
  48389. i6 = closeIndex;
  48390. }
  48391. }
  48392. } else {
  48393. textData += xmlData[i6];
  48394. }
  48395. }
  48396. return xmlObj.child;
  48397. };
  48398. function addChild(currentNode, childNode, jPath) {
  48399. const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]);
  48400. if (result === false) {
  48401. } else if (typeof result === "string") {
  48402. childNode.tagname = result;
  48403. currentNode.addChild(childNode);
  48404. } else {
  48405. currentNode.addChild(childNode);
  48406. }
  48407. }
  48408. var replaceEntitiesValue = function(val2) {
  48409. if (this.options.processEntities) {
  48410. for (let entityName2 in this.docTypeEntities) {
  48411. const entity = this.docTypeEntities[entityName2];
  48412. val2 = val2.replace(entity.regx, entity.val);
  48413. }
  48414. for (let entityName2 in this.lastEntities) {
  48415. const entity = this.lastEntities[entityName2];
  48416. val2 = val2.replace(entity.regex, entity.val);
  48417. }
  48418. if (this.options.htmlEntities) {
  48419. for (let entityName2 in this.htmlEntities) {
  48420. const entity = this.htmlEntities[entityName2];
  48421. val2 = val2.replace(entity.regex, entity.val);
  48422. }
  48423. }
  48424. val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val);
  48425. }
  48426. return val2;
  48427. };
  48428. function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
  48429. if (textData) {
  48430. if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0;
  48431. textData = this.parseTextData(
  48432. textData,
  48433. currentNode.tagname,
  48434. jPath,
  48435. false,
  48436. currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
  48437. isLeafNode
  48438. );
  48439. if (textData !== void 0 && textData !== "")
  48440. currentNode.add(this.options.textNodeName, textData);
  48441. textData = "";
  48442. }
  48443. return textData;
  48444. }
  48445. function isItStopNode(stopNodes, jPath, currentTagName) {
  48446. const allNodesExp = "*." + currentTagName;
  48447. for (const stopNodePath in stopNodes) {
  48448. const stopNodeExp = stopNodes[stopNodePath];
  48449. if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true;
  48450. }
  48451. return false;
  48452. }
  48453. function tagExpWithClosingIndex(xmlData, i6, closingChar = ">") {
  48454. let attrBoundary;
  48455. let tagExp = "";
  48456. for (let index6 = i6; index6 < xmlData.length; index6++) {
  48457. let ch = xmlData[index6];
  48458. if (attrBoundary) {
  48459. if (ch === attrBoundary) attrBoundary = "";
  48460. } else if (ch === '"' || ch === "'") {
  48461. attrBoundary = ch;
  48462. } else if (ch === closingChar[0]) {
  48463. if (closingChar[1]) {
  48464. if (xmlData[index6 + 1] === closingChar[1]) {
  48465. return {
  48466. data: tagExp,
  48467. index: index6
  48468. };
  48469. }
  48470. } else {
  48471. return {
  48472. data: tagExp,
  48473. index: index6
  48474. };
  48475. }
  48476. } else if (ch === " ") {
  48477. ch = " ";
  48478. }
  48479. tagExp += ch;
  48480. }
  48481. }
  48482. function findClosingIndex(xmlData, str, i6, errMsg) {
  48483. const closingIndex = xmlData.indexOf(str, i6);
  48484. if (closingIndex === -1) {
  48485. throw new Error(errMsg);
  48486. } else {
  48487. return closingIndex + str.length - 1;
  48488. }
  48489. }
  48490. function readTagExp(xmlData, i6, removeNSPrefix, closingChar = ">") {
  48491. const result = tagExpWithClosingIndex(xmlData, i6 + 1, closingChar);
  48492. if (!result) return;
  48493. let tagExp = result.data;
  48494. const closeIndex = result.index;
  48495. const separatorIndex = tagExp.search(/\s/);
  48496. let tagName = tagExp;
  48497. let attrExpPresent = true;
  48498. if (separatorIndex !== -1) {
  48499. tagName = tagExp.substring(0, separatorIndex);
  48500. tagExp = tagExp.substring(separatorIndex + 1).trimStart();
  48501. }
  48502. const rawTagName = tagName;
  48503. if (removeNSPrefix) {
  48504. const colonIndex = tagName.indexOf(":");
  48505. if (colonIndex !== -1) {
  48506. tagName = tagName.substr(colonIndex + 1);
  48507. attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
  48508. }
  48509. }
  48510. return {
  48511. tagName,
  48512. tagExp,
  48513. closeIndex,
  48514. attrExpPresent,
  48515. rawTagName
  48516. };
  48517. }
  48518. function readStopNodeData(xmlData, tagName, i6) {
  48519. const startIndex = i6;
  48520. let openTagCount = 1;
  48521. for (; i6 < xmlData.length; i6++) {
  48522. if (xmlData[i6] === "<") {
  48523. if (xmlData[i6 + 1] === "/") {
  48524. const closeIndex = findClosingIndex(xmlData, ">", i6, `${tagName} is not closed`);
  48525. let closeTagName = xmlData.substring(i6 + 2, closeIndex).trim();
  48526. if (closeTagName === tagName) {
  48527. openTagCount--;
  48528. if (openTagCount === 0) {
  48529. return {
  48530. tagContent: xmlData.substring(startIndex, i6),
  48531. i: closeIndex
  48532. };
  48533. }
  48534. }
  48535. i6 = closeIndex;
  48536. } else if (xmlData[i6 + 1] === "?") {
  48537. const closeIndex = findClosingIndex(xmlData, "?>", i6 + 1, "StopNode is not closed.");
  48538. i6 = closeIndex;
  48539. } else if (xmlData.substr(i6 + 1, 3) === "!--") {
  48540. const closeIndex = findClosingIndex(xmlData, "-->", i6 + 3, "StopNode is not closed.");
  48541. i6 = closeIndex;
  48542. } else if (xmlData.substr(i6 + 1, 2) === "![") {
  48543. const closeIndex = findClosingIndex(xmlData, "]]>", i6, "StopNode is not closed.") - 2;
  48544. i6 = closeIndex;
  48545. } else {
  48546. const tagData = readTagExp(xmlData, i6, ">");
  48547. if (tagData) {
  48548. const openTagName = tagData && tagData.tagName;
  48549. if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
  48550. openTagCount++;
  48551. }
  48552. i6 = tagData.closeIndex;
  48553. }
  48554. }
  48555. }
  48556. }
  48557. }
  48558. function parseValue(val2, shouldParse, options) {
  48559. if (shouldParse && typeof val2 === "string") {
  48560. const newval = val2.trim();
  48561. if (newval === "true") return true;
  48562. else if (newval === "false") return false;
  48563. else return toNumber(val2, options);
  48564. } else {
  48565. if (util2.isExist(val2)) {
  48566. return val2;
  48567. } else {
  48568. return "";
  48569. }
  48570. }
  48571. }
  48572. module.exports = OrderedObjParser;
  48573. }
  48574. });
  48575. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js
  48576. var require_node2json = __commonJS({
  48577. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports) {
  48578. "use strict";
  48579. function prettify(node, options) {
  48580. return compress2(node, options);
  48581. }
  48582. function compress2(arr, options, jPath) {
  48583. let text;
  48584. const compressedObj = {};
  48585. for (let i6 = 0; i6 < arr.length; i6++) {
  48586. const tagObj = arr[i6];
  48587. const property = propName(tagObj);
  48588. let newJpath = "";
  48589. if (jPath === void 0) newJpath = property;
  48590. else newJpath = jPath + "." + property;
  48591. if (property === options.textNodeName) {
  48592. if (text === void 0) text = tagObj[property];
  48593. else text += "" + tagObj[property];
  48594. } else if (property === void 0) {
  48595. continue;
  48596. } else if (tagObj[property]) {
  48597. let val2 = compress2(tagObj[property], options, newJpath);
  48598. const isLeaf = isLeafTag(val2, options);
  48599. if (tagObj[":@"]) {
  48600. assignAttributes(val2, tagObj[":@"], newJpath, options);
  48601. } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) {
  48602. val2 = val2[options.textNodeName];
  48603. } else if (Object.keys(val2).length === 0) {
  48604. if (options.alwaysCreateTextNode) val2[options.textNodeName] = "";
  48605. else val2 = "";
  48606. }
  48607. if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) {
  48608. if (!Array.isArray(compressedObj[property])) {
  48609. compressedObj[property] = [compressedObj[property]];
  48610. }
  48611. compressedObj[property].push(val2);
  48612. } else {
  48613. if (options.isArray(property, newJpath, isLeaf)) {
  48614. compressedObj[property] = [val2];
  48615. } else {
  48616. compressedObj[property] = val2;
  48617. }
  48618. }
  48619. }
  48620. }
  48621. if (typeof text === "string") {
  48622. if (text.length > 0) compressedObj[options.textNodeName] = text;
  48623. } else if (text !== void 0) compressedObj[options.textNodeName] = text;
  48624. return compressedObj;
  48625. }
  48626. function propName(obj) {
  48627. const keys = Object.keys(obj);
  48628. for (let i6 = 0; i6 < keys.length; i6++) {
  48629. const key = keys[i6];
  48630. if (key !== ":@") return key;
  48631. }
  48632. }
  48633. function assignAttributes(obj, attrMap, jpath, options) {
  48634. if (attrMap) {
  48635. const keys = Object.keys(attrMap);
  48636. const len = keys.length;
  48637. for (let i6 = 0; i6 < len; i6++) {
  48638. const atrrName = keys[i6];
  48639. if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
  48640. obj[atrrName] = [attrMap[atrrName]];
  48641. } else {
  48642. obj[atrrName] = attrMap[atrrName];
  48643. }
  48644. }
  48645. }
  48646. }
  48647. function isLeafTag(obj, options) {
  48648. const { textNodeName } = options;
  48649. const propCount = Object.keys(obj).length;
  48650. if (propCount === 0) {
  48651. return true;
  48652. }
  48653. if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) {
  48654. return true;
  48655. }
  48656. return false;
  48657. }
  48658. exports.prettify = prettify;
  48659. }
  48660. });
  48661. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
  48662. var require_XMLParser = __commonJS({
  48663. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports, module) {
  48664. "use strict";
  48665. var { buildOptions } = require_OptionsBuilder();
  48666. var OrderedObjParser = require_OrderedObjParser();
  48667. var { prettify } = require_node2json();
  48668. var validator2 = require_validator();
  48669. var XMLParser2 = class {
  48670. constructor(options) {
  48671. this.externalEntities = {};
  48672. this.options = buildOptions(options);
  48673. }
  48674. /**
  48675. * Parse XML dats to JS object
  48676. * @param {string|Buffer} xmlData
  48677. * @param {boolean|Object} validationOption
  48678. */
  48679. parse(xmlData, validationOption) {
  48680. if (typeof xmlData === "string") {
  48681. } else if (xmlData.toString) {
  48682. xmlData = xmlData.toString();
  48683. } else {
  48684. throw new Error("XML data is accepted in String or Bytes[] form.");
  48685. }
  48686. if (validationOption) {
  48687. if (validationOption === true) validationOption = {};
  48688. const result = validator2.validate(xmlData, validationOption);
  48689. if (result !== true) {
  48690. throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
  48691. }
  48692. }
  48693. const orderedObjParser = new OrderedObjParser(this.options);
  48694. orderedObjParser.addExternalEntities(this.externalEntities);
  48695. const orderedResult = orderedObjParser.parseXml(xmlData);
  48696. if (this.options.preserveOrder || orderedResult === void 0) return orderedResult;
  48697. else return prettify(orderedResult, this.options);
  48698. }
  48699. /**
  48700. * Add Entity which is not by default supported by this library
  48701. * @param {string} key
  48702. * @param {string} value
  48703. */
  48704. addEntity(key, value) {
  48705. if (value.indexOf("&") !== -1) {
  48706. throw new Error("Entity value can't have '&'");
  48707. } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
  48708. throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
  48709. } else if (value === "&") {
  48710. throw new Error("An entity with value '&' is not permitted");
  48711. } else {
  48712. this.externalEntities[key] = value;
  48713. }
  48714. }
  48715. };
  48716. module.exports = XMLParser2;
  48717. }
  48718. });
  48719. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
  48720. var require_orderedJs2Xml = __commonJS({
  48721. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports, module) {
  48722. "use strict";
  48723. var EOL = "\n";
  48724. function toXml(jArray, options) {
  48725. let indentation = "";
  48726. if (options.format && options.indentBy.length > 0) {
  48727. indentation = EOL;
  48728. }
  48729. return arrToStr(jArray, options, "", indentation);
  48730. }
  48731. function arrToStr(arr, options, jPath, indentation) {
  48732. let xmlStr = "";
  48733. let isPreviousElementTag = false;
  48734. for (let i6 = 0; i6 < arr.length; i6++) {
  48735. const tagObj = arr[i6];
  48736. const tagName = propName(tagObj);
  48737. if (tagName === void 0) continue;
  48738. let newJPath = "";
  48739. if (jPath.length === 0) newJPath = tagName;
  48740. else newJPath = `${jPath}.${tagName}`;
  48741. if (tagName === options.textNodeName) {
  48742. let tagText = tagObj[tagName];
  48743. if (!isStopNode(newJPath, options)) {
  48744. tagText = options.tagValueProcessor(tagName, tagText);
  48745. tagText = replaceEntitiesValue(tagText, options);
  48746. }
  48747. if (isPreviousElementTag) {
  48748. xmlStr += indentation;
  48749. }
  48750. xmlStr += tagText;
  48751. isPreviousElementTag = false;
  48752. continue;
  48753. } else if (tagName === options.cdataPropName) {
  48754. if (isPreviousElementTag) {
  48755. xmlStr += indentation;
  48756. }
  48757. xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
  48758. isPreviousElementTag = false;
  48759. continue;
  48760. } else if (tagName === options.commentPropName) {
  48761. xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
  48762. isPreviousElementTag = true;
  48763. continue;
  48764. } else if (tagName[0] === "?") {
  48765. const attStr2 = attr_to_str(tagObj[":@"], options);
  48766. const tempInd = tagName === "?xml" ? "" : indentation;
  48767. let piTextNodeName = tagObj[tagName][0][options.textNodeName];
  48768. piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : "";
  48769. xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`;
  48770. isPreviousElementTag = true;
  48771. continue;
  48772. }
  48773. let newIdentation = indentation;
  48774. if (newIdentation !== "") {
  48775. newIdentation += options.indentBy;
  48776. }
  48777. const attStr = attr_to_str(tagObj[":@"], options);
  48778. const tagStart = indentation + `<${tagName}${attStr}`;
  48779. const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
  48780. if (options.unpairedTags.indexOf(tagName) !== -1) {
  48781. if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
  48782. else xmlStr += tagStart + "/>";
  48783. } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
  48784. xmlStr += tagStart + "/>";
  48785. } else if (tagValue && tagValue.endsWith(">")) {
  48786. xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
  48787. } else {
  48788. xmlStr += tagStart + ">";
  48789. if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
  48790. xmlStr += indentation + options.indentBy + tagValue + indentation;
  48791. } else {
  48792. xmlStr += tagValue;
  48793. }
  48794. xmlStr += `</${tagName}>`;
  48795. }
  48796. isPreviousElementTag = true;
  48797. }
  48798. return xmlStr;
  48799. }
  48800. function propName(obj) {
  48801. const keys = Object.keys(obj);
  48802. for (let i6 = 0; i6 < keys.length; i6++) {
  48803. const key = keys[i6];
  48804. if (!obj.hasOwnProperty(key)) continue;
  48805. if (key !== ":@") return key;
  48806. }
  48807. }
  48808. function attr_to_str(attrMap, options) {
  48809. let attrStr = "";
  48810. if (attrMap && !options.ignoreAttributes) {
  48811. for (let attr in attrMap) {
  48812. if (!attrMap.hasOwnProperty(attr)) continue;
  48813. let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
  48814. attrVal = replaceEntitiesValue(attrVal, options);
  48815. if (attrVal === true && options.suppressBooleanAttributes) {
  48816. attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
  48817. } else {
  48818. attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
  48819. }
  48820. }
  48821. }
  48822. return attrStr;
  48823. }
  48824. function isStopNode(jPath, options) {
  48825. jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
  48826. let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
  48827. for (let index6 in options.stopNodes) {
  48828. if (options.stopNodes[index6] === jPath || options.stopNodes[index6] === "*." + tagName) return true;
  48829. }
  48830. return false;
  48831. }
  48832. function replaceEntitiesValue(textValue, options) {
  48833. if (textValue && textValue.length > 0 && options.processEntities) {
  48834. for (let i6 = 0; i6 < options.entities.length; i6++) {
  48835. const entity = options.entities[i6];
  48836. textValue = textValue.replace(entity.regex, entity.val);
  48837. }
  48838. }
  48839. return textValue;
  48840. }
  48841. module.exports = toXml;
  48842. }
  48843. });
  48844. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
  48845. var require_json2xml = __commonJS({
  48846. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports, module) {
  48847. "use strict";
  48848. var buildFromOrderedJs = require_orderedJs2Xml();
  48849. var defaultOptions = {
  48850. attributeNamePrefix: "@_",
  48851. attributesGroupName: false,
  48852. textNodeName: "#text",
  48853. ignoreAttributes: true,
  48854. cdataPropName: false,
  48855. format: false,
  48856. indentBy: " ",
  48857. suppressEmptyNode: false,
  48858. suppressUnpairedNode: true,
  48859. suppressBooleanAttributes: true,
  48860. tagValueProcessor: function(key, a5) {
  48861. return a5;
  48862. },
  48863. attributeValueProcessor: function(attrName, a5) {
  48864. return a5;
  48865. },
  48866. preserveOrder: false,
  48867. commentPropName: false,
  48868. unpairedTags: [],
  48869. entities: [
  48870. { regex: new RegExp("&", "g"), val: "&amp;" },
  48871. //it must be on top
  48872. { regex: new RegExp(">", "g"), val: "&gt;" },
  48873. { regex: new RegExp("<", "g"), val: "&lt;" },
  48874. { regex: new RegExp("'", "g"), val: "&apos;" },
  48875. { regex: new RegExp('"', "g"), val: "&quot;" }
  48876. ],
  48877. processEntities: true,
  48878. stopNodes: [],
  48879. // transformTagName: false,
  48880. // transformAttributeName: false,
  48881. oneListGroup: false
  48882. };
  48883. function Builder(options) {
  48884. this.options = Object.assign({}, defaultOptions, options);
  48885. if (this.options.ignoreAttributes || this.options.attributesGroupName) {
  48886. this.isAttribute = function() {
  48887. return false;
  48888. };
  48889. } else {
  48890. this.attrPrefixLen = this.options.attributeNamePrefix.length;
  48891. this.isAttribute = isAttribute;
  48892. }
  48893. this.processTextOrObjNode = processTextOrObjNode;
  48894. if (this.options.format) {
  48895. this.indentate = indentate;
  48896. this.tagEndChar = ">\n";
  48897. this.newLine = "\n";
  48898. } else {
  48899. this.indentate = function() {
  48900. return "";
  48901. };
  48902. this.tagEndChar = ">";
  48903. this.newLine = "";
  48904. }
  48905. }
  48906. Builder.prototype.build = function(jObj) {
  48907. if (this.options.preserveOrder) {
  48908. return buildFromOrderedJs(jObj, this.options);
  48909. } else {
  48910. if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {
  48911. jObj = {
  48912. [this.options.arrayNodeName]: jObj
  48913. };
  48914. }
  48915. return this.j2x(jObj, 0).val;
  48916. }
  48917. };
  48918. Builder.prototype.j2x = function(jObj, level) {
  48919. let attrStr = "";
  48920. let val2 = "";
  48921. for (let key in jObj) {
  48922. if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
  48923. if (typeof jObj[key] === "undefined") {
  48924. if (this.isAttribute(key)) {
  48925. val2 += "";
  48926. }
  48927. } else if (jObj[key] === null) {
  48928. if (this.isAttribute(key)) {
  48929. val2 += "";
  48930. } else if (key[0] === "?") {
  48931. val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
  48932. } else {
  48933. val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
  48934. }
  48935. } else if (jObj[key] instanceof Date) {
  48936. val2 += this.buildTextValNode(jObj[key], key, "", level);
  48937. } else if (typeof jObj[key] !== "object") {
  48938. const attr = this.isAttribute(key);
  48939. if (attr) {
  48940. attrStr += this.buildAttrPairStr(attr, "" + jObj[key]);
  48941. } else {
  48942. if (key === this.options.textNodeName) {
  48943. let newval = this.options.tagValueProcessor(key, "" + jObj[key]);
  48944. val2 += this.replaceEntitiesValue(newval);
  48945. } else {
  48946. val2 += this.buildTextValNode(jObj[key], key, "", level);
  48947. }
  48948. }
  48949. } else if (Array.isArray(jObj[key])) {
  48950. const arrLen = jObj[key].length;
  48951. let listTagVal = "";
  48952. let listTagAttr = "";
  48953. for (let j5 = 0; j5 < arrLen; j5++) {
  48954. const item = jObj[key][j5];
  48955. if (typeof item === "undefined") {
  48956. } else if (item === null) {
  48957. if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
  48958. else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
  48959. } else if (typeof item === "object") {
  48960. if (this.options.oneListGroup) {
  48961. const result = this.j2x(item, level + 1);
  48962. listTagVal += result.val;
  48963. if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
  48964. listTagAttr += result.attrStr;
  48965. }
  48966. } else {
  48967. listTagVal += this.processTextOrObjNode(item, key, level);
  48968. }
  48969. } else {
  48970. if (this.options.oneListGroup) {
  48971. let textValue = this.options.tagValueProcessor(key, item);
  48972. textValue = this.replaceEntitiesValue(textValue);
  48973. listTagVal += textValue;
  48974. } else {
  48975. listTagVal += this.buildTextValNode(item, key, "", level);
  48976. }
  48977. }
  48978. }
  48979. if (this.options.oneListGroup) {
  48980. listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
  48981. }
  48982. val2 += listTagVal;
  48983. } else {
  48984. if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
  48985. const Ks = Object.keys(jObj[key]);
  48986. const L = Ks.length;
  48987. for (let j5 = 0; j5 < L; j5++) {
  48988. attrStr += this.buildAttrPairStr(Ks[j5], "" + jObj[key][Ks[j5]]);
  48989. }
  48990. } else {
  48991. val2 += this.processTextOrObjNode(jObj[key], key, level);
  48992. }
  48993. }
  48994. }
  48995. return { attrStr, val: val2 };
  48996. };
  48997. Builder.prototype.buildAttrPairStr = function(attrName, val2) {
  48998. val2 = this.options.attributeValueProcessor(attrName, "" + val2);
  48999. val2 = this.replaceEntitiesValue(val2);
  49000. if (this.options.suppressBooleanAttributes && val2 === "true") {
  49001. return " " + attrName;
  49002. } else return " " + attrName + '="' + val2 + '"';
  49003. };
  49004. function processTextOrObjNode(object, key, level) {
  49005. const result = this.j2x(object, level + 1);
  49006. if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) {
  49007. return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
  49008. } else {
  49009. return this.buildObjectNode(result.val, key, result.attrStr, level);
  49010. }
  49011. }
  49012. Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) {
  49013. if (val2 === "") {
  49014. if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
  49015. else {
  49016. return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
  49017. }
  49018. } else {
  49019. let tagEndExp = "</" + key + this.tagEndChar;
  49020. let piClosingChar = "";
  49021. if (key[0] === "?") {
  49022. piClosingChar = "?";
  49023. tagEndExp = "";
  49024. }
  49025. if ((attrStr || attrStr === "") && val2.indexOf("<") === -1) {
  49026. return this.indentate(level) + "<" + key + attrStr + piClosingChar + ">" + val2 + tagEndExp;
  49027. } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
  49028. return this.indentate(level) + `<!--${val2}-->` + this.newLine;
  49029. } else {
  49030. return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp;
  49031. }
  49032. }
  49033. };
  49034. Builder.prototype.closeTag = function(key) {
  49035. let closeTag = "";
  49036. if (this.options.unpairedTags.indexOf(key) !== -1) {
  49037. if (!this.options.suppressUnpairedNode) closeTag = "/";
  49038. } else if (this.options.suppressEmptyNode) {
  49039. closeTag = "/";
  49040. } else {
  49041. closeTag = `></${key}`;
  49042. }
  49043. return closeTag;
  49044. };
  49045. Builder.prototype.buildTextValNode = function(val2, key, attrStr, level) {
  49046. if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
  49047. return this.indentate(level) + `<![CDATA[${val2}]]>` + this.newLine;
  49048. } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
  49049. return this.indentate(level) + `<!--${val2}-->` + this.newLine;
  49050. } else if (key[0] === "?") {
  49051. return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
  49052. } else {
  49053. let textValue = this.options.tagValueProcessor(key, val2);
  49054. textValue = this.replaceEntitiesValue(textValue);
  49055. if (textValue === "") {
  49056. return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
  49057. } else {
  49058. return this.indentate(level) + "<" + key + attrStr + ">" + textValue + "</" + key + this.tagEndChar;
  49059. }
  49060. }
  49061. };
  49062. Builder.prototype.replaceEntitiesValue = function(textValue) {
  49063. if (textValue && textValue.length > 0 && this.options.processEntities) {
  49064. for (let i6 = 0; i6 < this.options.entities.length; i6++) {
  49065. const entity = this.options.entities[i6];
  49066. textValue = textValue.replace(entity.regex, entity.val);
  49067. }
  49068. }
  49069. return textValue;
  49070. };
  49071. function indentate(level) {
  49072. return this.options.indentBy.repeat(level);
  49073. }
  49074. function isAttribute(name) {
  49075. if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
  49076. return name.substr(this.attrPrefixLen);
  49077. } else {
  49078. return false;
  49079. }
  49080. }
  49081. module.exports = Builder;
  49082. }
  49083. });
  49084. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js
  49085. var require_fxp = __commonJS({
  49086. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js"(exports, module) {
  49087. "use strict";
  49088. var validator2 = require_validator();
  49089. var XMLParser2 = require_XMLParser();
  49090. var XMLBuilder = require_json2xml();
  49091. module.exports = {
  49092. XMLParser: XMLParser2,
  49093. XMLValidator: validator2,
  49094. XMLBuilder
  49095. };
  49096. }
  49097. });
  49098. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js
  49099. var import_fast_xml_parser, parseXmlBody, parseXmlErrorBody;
  49100. var init_parseXmlBody = __esm({
  49101. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() {
  49102. "use strict";
  49103. init_dist_es24();
  49104. import_fast_xml_parser = __toESM(require_fxp());
  49105. init_common2();
  49106. parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
  49107. if (encoded.length) {
  49108. const parser = new import_fast_xml_parser.XMLParser({
  49109. attributeNamePrefix: "",
  49110. htmlEntities: true,
  49111. ignoreAttributes: false,
  49112. ignoreDeclaration: true,
  49113. parseTagValue: false,
  49114. trimValues: false,
  49115. tagValueProcessor: (_3, val2) => val2.trim() === "" && val2.includes("\n") ? "" : void 0
  49116. });
  49117. parser.addEntity("#xD", "\r");
  49118. parser.addEntity("#10", "\n");
  49119. let parsedObj;
  49120. try {
  49121. parsedObj = parser.parse(encoded, true);
  49122. } catch (e6) {
  49123. if (e6 && typeof e6 === "object") {
  49124. Object.defineProperty(e6, "$responseBodyText", {
  49125. value: encoded
  49126. });
  49127. }
  49128. throw e6;
  49129. }
  49130. const textNodeName = "#text";
  49131. const key = Object.keys(parsedObj)[0];
  49132. const parsedObjToReturn = parsedObj[key];
  49133. if (parsedObjToReturn[textNodeName]) {
  49134. parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
  49135. delete parsedObjToReturn[textNodeName];
  49136. }
  49137. return getValueFromTextNode(parsedObjToReturn);
  49138. }
  49139. return {};
  49140. });
  49141. parseXmlErrorBody = async (errorBody, context) => {
  49142. const value = await parseXmlBody(errorBody, context);
  49143. if (value.Error) {
  49144. value.Error.message = value.Error.message ?? value.Error.Message;
  49145. }
  49146. return value;
  49147. };
  49148. }
  49149. });
  49150. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js
  49151. var init_protocols2 = __esm({
  49152. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() {
  49153. "use strict";
  49154. init_coercing_serializers();
  49155. init_awsExpectUnion();
  49156. init_parseJsonBody();
  49157. init_parseXmlBody();
  49158. }
  49159. });
  49160. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js
  49161. var init_dist_es25 = __esm({
  49162. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js"() {
  49163. "use strict";
  49164. init_client2();
  49165. init_httpAuthSchemes2();
  49166. init_protocols2();
  49167. }
  49168. });
  49169. // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js
  49170. async function checkFeatures(context, config, args) {
  49171. const request2 = args.request;
  49172. if (request2?.headers?.["smithy-protocol"] === "rpc-v2-cbor") {
  49173. setFeature2(context, "PROTOCOL_RPC_V2_CBOR", "M");
  49174. }
  49175. if (typeof config.retryStrategy === "function") {
  49176. const retryStrategy = await config.retryStrategy();
  49177. if (typeof retryStrategy.acquireInitialRetryToken === "function") {
  49178. if (retryStrategy.constructor?.name?.includes("Adaptive")) {
  49179. setFeature2(context, "RETRY_MODE_ADAPTIVE", "F");
  49180. } else {
  49181. setFeature2(context, "RETRY_MODE_STANDARD", "E");
  49182. }
  49183. } else {
  49184. setFeature2(context, "RETRY_MODE_LEGACY", "D");
  49185. }
  49186. }
  49187. if (typeof config.accountIdEndpointMode === "function") {
  49188. const endpointV2 = context.endpointV2;
  49189. if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) {
  49190. setFeature2(context, "ACCOUNT_ID_ENDPOINT", "O");
  49191. }
  49192. switch (await config.accountIdEndpointMode?.()) {
  49193. case "disabled":
  49194. setFeature2(context, "ACCOUNT_ID_MODE_DISABLED", "Q");
  49195. break;
  49196. case "preferred":
  49197. setFeature2(context, "ACCOUNT_ID_MODE_PREFERRED", "P");
  49198. break;
  49199. case "required":
  49200. setFeature2(context, "ACCOUNT_ID_MODE_REQUIRED", "R");
  49201. break;
  49202. }
  49203. }
  49204. const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity;
  49205. if (identity?.$source) {
  49206. const credentials2 = identity;
  49207. if (credentials2.accountId) {
  49208. setFeature2(context, "RESOLVED_ACCOUNT_ID", "T");
  49209. }
  49210. for (const [key, value] of Object.entries(credentials2.$source ?? {})) {
  49211. setFeature2(context, key, value);
  49212. }
  49213. }
  49214. }
  49215. var ACCOUNT_ID_ENDPOINT_REGEX;
  49216. var init_check_features = __esm({
  49217. "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js"() {
  49218. "use strict";
  49219. init_dist_es25();
  49220. ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/;
  49221. }
  49222. });
  49223. // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js
  49224. var USER_AGENT, X_AMZ_USER_AGENT, SPACE2, UA_NAME_SEPARATOR, UA_NAME_ESCAPE_REGEX, UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR;
  49225. var init_constants5 = __esm({
  49226. "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js"() {
  49227. "use strict";
  49228. USER_AGENT = "user-agent";
  49229. X_AMZ_USER_AGENT = "x-amz-user-agent";
  49230. SPACE2 = " ";
  49231. UA_NAME_SEPARATOR = "/";
  49232. UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
  49233. UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
  49234. UA_ESCAPE_CHAR = "-";
  49235. }
  49236. });
  49237. // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js
  49238. function encodeFeatures(features) {
  49239. let buffer = "";
  49240. for (const key in features) {
  49241. const val2 = features[key];
  49242. if (buffer.length + val2.length + 1 <= BYTE_LIMIT) {
  49243. if (buffer.length) {
  49244. buffer += "," + val2;
  49245. } else {
  49246. buffer += val2;
  49247. }
  49248. continue;
  49249. }
  49250. break;
  49251. }
  49252. return buffer;
  49253. }
  49254. var BYTE_LIMIT;
  49255. var init_encode_features = __esm({
  49256. "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js"() {
  49257. "use strict";
  49258. BYTE_LIMIT = 1024;
  49259. }
  49260. });
  49261. // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js
  49262. var userAgentMiddleware, escapeUserAgent, getUserAgentMiddlewareOptions, getUserAgentPlugin;
  49263. var init_user_agent_middleware = __esm({
  49264. "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js"() {
  49265. "use strict";
  49266. init_dist_es20();
  49267. init_dist_es2();
  49268. init_check_features();
  49269. init_constants5();
  49270. init_encode_features();
  49271. userAgentMiddleware = (options) => (next, context) => async (args) => {
  49272. const { request: request2 } = args;
  49273. if (!HttpRequest.isInstance(request2)) {
  49274. return next(args);
  49275. }
  49276. const { headers } = request2;
  49277. const userAgent = context?.userAgent?.map(escapeUserAgent) || [];
  49278. const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
  49279. await checkFeatures(context, options, args);
  49280. const awsContext = context;
  49281. defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`);
  49282. const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];
  49283. const appId = await options.userAgentAppId();
  49284. if (appId) {
  49285. defaultUserAgent.push(escapeUserAgent([`app/${appId}`]));
  49286. }
  49287. const prefix2 = getUserAgentPrefix();
  49288. const sdkUserAgentValue = (prefix2 ? [prefix2] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE2);
  49289. const normalUAValue = [
  49290. ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")),
  49291. ...customUserAgent
  49292. ].join(SPACE2);
  49293. if (options.runtime !== "browser") {
  49294. if (normalUAValue) {
  49295. headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue;
  49296. }
  49297. headers[USER_AGENT] = sdkUserAgentValue;
  49298. } else {
  49299. headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
  49300. }
  49301. return next({
  49302. ...args,
  49303. request: request2
  49304. });
  49305. };
  49306. escapeUserAgent = (userAgentPair) => {
  49307. const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
  49308. const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
  49309. const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR);
  49310. const prefix2 = name.substring(0, prefixSeparatorIndex);
  49311. let uaName = name.substring(prefixSeparatorIndex + 1);
  49312. if (prefix2 === "api") {
  49313. uaName = uaName.toLowerCase();
  49314. }
  49315. return [prefix2, uaName, version].filter((item) => item && item.length > 0).reduce((acc, item, index6) => {
  49316. switch (index6) {
  49317. case 0:
  49318. return item;
  49319. case 1:
  49320. return `${acc}/${item}`;
  49321. default:
  49322. return `${acc}#${item}`;
  49323. }
  49324. }, "");
  49325. };
  49326. getUserAgentMiddlewareOptions = {
  49327. name: "getUserAgentMiddleware",
  49328. step: "build",
  49329. priority: "low",
  49330. tags: ["SET_USER_AGENT", "USER_AGENT"],
  49331. override: true
  49332. };
  49333. getUserAgentPlugin = (config) => ({
  49334. applyToStack: (clientStack) => {
  49335. clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
  49336. }
  49337. });
  49338. }
  49339. });
  49340. // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js
  49341. var init_dist_es26 = __esm({
  49342. "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js"() {
  49343. "use strict";
  49344. init_configurations();
  49345. init_user_agent_middleware();
  49346. }
  49347. });
  49348. // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js
  49349. var booleanSelector;
  49350. var init_booleanSelector = __esm({
  49351. "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js"() {
  49352. "use strict";
  49353. booleanSelector = (obj, key, type) => {
  49354. if (!(key in obj))
  49355. return void 0;
  49356. if (obj[key] === "true")
  49357. return true;
  49358. if (obj[key] === "false")
  49359. return false;
  49360. throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`);
  49361. };
  49362. }
  49363. });
  49364. // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/numberSelector.js
  49365. var init_numberSelector = __esm({
  49366. "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/numberSelector.js"() {
  49367. "use strict";
  49368. }
  49369. });
  49370. // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/types.js
  49371. var SelectorType;
  49372. var init_types5 = __esm({
  49373. "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/types.js"() {
  49374. "use strict";
  49375. (function(SelectorType2) {
  49376. SelectorType2["ENV"] = "env";
  49377. SelectorType2["CONFIG"] = "shared config entry";
  49378. })(SelectorType || (SelectorType = {}));
  49379. }
  49380. });
  49381. // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/index.js
  49382. var init_dist_es27 = __esm({
  49383. "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-es/index.js"() {
  49384. "use strict";
  49385. init_booleanSelector();
  49386. init_numberSelector();
  49387. init_types5();
  49388. }
  49389. });
  49390. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js
  49391. var ENV_USE_DUALSTACK_ENDPOINT, CONFIG_USE_DUALSTACK_ENDPOINT, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS;
  49392. var init_NodeUseDualstackEndpointConfigOptions = __esm({
  49393. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js"() {
  49394. "use strict";
  49395. init_dist_es27();
  49396. ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
  49397. CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
  49398. NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = {
  49399. environmentVariableSelector: (env4) => booleanSelector(env4, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV),
  49400. configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG),
  49401. default: false
  49402. };
  49403. }
  49404. });
  49405. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js
  49406. var ENV_USE_FIPS_ENDPOINT, CONFIG_USE_FIPS_ENDPOINT, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS;
  49407. var init_NodeUseFipsEndpointConfigOptions = __esm({
  49408. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js"() {
  49409. "use strict";
  49410. init_dist_es27();
  49411. ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
  49412. CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
  49413. NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = {
  49414. environmentVariableSelector: (env4) => booleanSelector(env4, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV),
  49415. configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG),
  49416. default: false
  49417. };
  49418. }
  49419. });
  49420. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js
  49421. var init_resolveCustomEndpointsConfig = __esm({
  49422. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js"() {
  49423. "use strict";
  49424. init_dist_es6();
  49425. }
  49426. });
  49427. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js
  49428. var init_getEndpointFromRegion = __esm({
  49429. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js"() {
  49430. "use strict";
  49431. }
  49432. });
  49433. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js
  49434. var init_resolveEndpointsConfig = __esm({
  49435. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js"() {
  49436. "use strict";
  49437. init_dist_es6();
  49438. init_getEndpointFromRegion();
  49439. }
  49440. });
  49441. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js
  49442. var init_endpointsConfig = __esm({
  49443. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js"() {
  49444. "use strict";
  49445. init_NodeUseDualstackEndpointConfigOptions();
  49446. init_NodeUseFipsEndpointConfigOptions();
  49447. init_resolveCustomEndpointsConfig();
  49448. init_resolveEndpointsConfig();
  49449. }
  49450. });
  49451. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js
  49452. var REGION_ENV_NAME, REGION_INI_NAME, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS;
  49453. var init_config2 = __esm({
  49454. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js"() {
  49455. "use strict";
  49456. REGION_ENV_NAME = "AWS_REGION";
  49457. REGION_INI_NAME = "region";
  49458. NODE_REGION_CONFIG_OPTIONS = {
  49459. environmentVariableSelector: (env4) => env4[REGION_ENV_NAME],
  49460. configFileSelector: (profile) => profile[REGION_INI_NAME],
  49461. default: () => {
  49462. throw new Error("Region is missing");
  49463. }
  49464. };
  49465. NODE_REGION_CONFIG_FILE_OPTIONS = {
  49466. preferredFile: "credentials"
  49467. };
  49468. }
  49469. });
  49470. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js
  49471. var isFipsRegion;
  49472. var init_isFipsRegion = __esm({
  49473. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js"() {
  49474. "use strict";
  49475. isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips"));
  49476. }
  49477. });
  49478. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js
  49479. var getRealRegion;
  49480. var init_getRealRegion = __esm({
  49481. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js"() {
  49482. "use strict";
  49483. init_isFipsRegion();
  49484. getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region;
  49485. }
  49486. });
  49487. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js
  49488. var resolveRegionConfig;
  49489. var init_resolveRegionConfig = __esm({
  49490. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() {
  49491. "use strict";
  49492. init_getRealRegion();
  49493. init_isFipsRegion();
  49494. resolveRegionConfig = (input) => {
  49495. const { region, useFipsEndpoint } = input;
  49496. if (!region) {
  49497. throw new Error("Region is missing");
  49498. }
  49499. return Object.assign(input, {
  49500. region: async () => {
  49501. if (typeof region === "string") {
  49502. return getRealRegion(region);
  49503. }
  49504. const providedRegion = await region();
  49505. return getRealRegion(providedRegion);
  49506. },
  49507. useFipsEndpoint: async () => {
  49508. const providedRegion = typeof region === "string" ? region : await region();
  49509. if (isFipsRegion(providedRegion)) {
  49510. return true;
  49511. }
  49512. return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
  49513. }
  49514. });
  49515. };
  49516. }
  49517. });
  49518. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js
  49519. var init_regionConfig = __esm({
  49520. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js"() {
  49521. "use strict";
  49522. init_config2();
  49523. init_resolveRegionConfig();
  49524. }
  49525. });
  49526. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js
  49527. var init_PartitionHash = __esm({
  49528. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js"() {
  49529. "use strict";
  49530. }
  49531. });
  49532. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js
  49533. var init_RegionHash = __esm({
  49534. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js"() {
  49535. "use strict";
  49536. }
  49537. });
  49538. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js
  49539. var init_getHostnameFromVariants = __esm({
  49540. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js"() {
  49541. "use strict";
  49542. }
  49543. });
  49544. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js
  49545. var init_getResolvedHostname = __esm({
  49546. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js"() {
  49547. "use strict";
  49548. }
  49549. });
  49550. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js
  49551. var init_getResolvedPartition = __esm({
  49552. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js"() {
  49553. "use strict";
  49554. }
  49555. });
  49556. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js
  49557. var init_getResolvedSigningRegion = __esm({
  49558. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js"() {
  49559. "use strict";
  49560. }
  49561. });
  49562. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js
  49563. var init_getRegionInfo = __esm({
  49564. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js"() {
  49565. "use strict";
  49566. init_getHostnameFromVariants();
  49567. init_getResolvedHostname();
  49568. init_getResolvedPartition();
  49569. init_getResolvedSigningRegion();
  49570. }
  49571. });
  49572. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js
  49573. var init_regionInfo = __esm({
  49574. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js"() {
  49575. "use strict";
  49576. init_PartitionHash();
  49577. init_RegionHash();
  49578. init_getRegionInfo();
  49579. }
  49580. });
  49581. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/index.js
  49582. var init_dist_es28 = __esm({
  49583. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-es/index.js"() {
  49584. "use strict";
  49585. init_endpointsConfig();
  49586. init_regionConfig();
  49587. init_regionInfo();
  49588. }
  49589. });
  49590. // ../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-es/index.js
  49591. function contentLengthMiddleware(bodyLengthChecker) {
  49592. return (next) => async (args) => {
  49593. const request2 = args.request;
  49594. if (HttpRequest.isInstance(request2)) {
  49595. const { body, headers } = request2;
  49596. if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) {
  49597. try {
  49598. const length = bodyLengthChecker(body);
  49599. request2.headers = {
  49600. ...request2.headers,
  49601. [CONTENT_LENGTH_HEADER]: String(length)
  49602. };
  49603. } catch (error2) {
  49604. }
  49605. }
  49606. }
  49607. return next({
  49608. ...args,
  49609. request: request2
  49610. });
  49611. };
  49612. }
  49613. var CONTENT_LENGTH_HEADER, contentLengthMiddlewareOptions, getContentLengthPlugin;
  49614. var init_dist_es29 = __esm({
  49615. "../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-es/index.js"() {
  49616. "use strict";
  49617. init_dist_es2();
  49618. CONTENT_LENGTH_HEADER = "content-length";
  49619. contentLengthMiddlewareOptions = {
  49620. step: "build",
  49621. tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
  49622. name: "contentLengthMiddleware",
  49623. override: true
  49624. };
  49625. getContentLengthPlugin = (options) => ({
  49626. applyToStack: (clientStack) => {
  49627. clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
  49628. }
  49629. });
  49630. }
  49631. });
  49632. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js
  49633. var resolveParamsForS3, DOMAIN_PATTERN, IP_ADDRESS_PATTERN, DOTS_PATTERN, isDnsCompatibleBucketName, isArnBucketName;
  49634. var init_s3 = __esm({
  49635. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js"() {
  49636. "use strict";
  49637. resolveParamsForS3 = async (endpointParams) => {
  49638. const bucket = endpointParams?.Bucket || "";
  49639. if (typeof endpointParams.Bucket === "string") {
  49640. endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
  49641. }
  49642. if (isArnBucketName(bucket)) {
  49643. if (endpointParams.ForcePathStyle === true) {
  49644. throw new Error("Path-style addressing cannot be used with ARN buckets");
  49645. }
  49646. } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) {
  49647. endpointParams.ForcePathStyle = true;
  49648. }
  49649. if (endpointParams.DisableMultiRegionAccessPoints) {
  49650. endpointParams.disableMultiRegionAccessPoints = true;
  49651. endpointParams.DisableMRAP = true;
  49652. }
  49653. return endpointParams;
  49654. };
  49655. DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
  49656. IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
  49657. DOTS_PATTERN = /\.\./;
  49658. isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName);
  49659. isArnBucketName = (bucketName) => {
  49660. const [arn, partition2, service, , , bucket] = bucketName.split(":");
  49661. const isArn = arn === "arn" && bucketName.split(":").length >= 6;
  49662. const isValidArn = Boolean(isArn && partition2 && service && bucket);
  49663. if (isArn && !isValidArn) {
  49664. throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
  49665. }
  49666. return isValidArn;
  49667. };
  49668. }
  49669. });
  49670. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js
  49671. var init_service_customizations = __esm({
  49672. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js"() {
  49673. "use strict";
  49674. init_s3();
  49675. }
  49676. });
  49677. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js
  49678. var createConfigValueProvider;
  49679. var init_createConfigValueProvider = __esm({
  49680. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js"() {
  49681. "use strict";
  49682. createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => {
  49683. const configProvider = async () => {
  49684. const configValue = config[configKey] ?? config[canonicalEndpointParamKey];
  49685. if (typeof configValue === "function") {
  49686. return configValue();
  49687. }
  49688. return configValue;
  49689. };
  49690. if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
  49691. return async () => {
  49692. const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
  49693. const configValue = credentials2?.credentialScope ?? credentials2?.CredentialScope;
  49694. return configValue;
  49695. };
  49696. }
  49697. if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") {
  49698. return async () => {
  49699. const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
  49700. const configValue = credentials2?.accountId ?? credentials2?.AccountId;
  49701. return configValue;
  49702. };
  49703. }
  49704. if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") {
  49705. return async () => {
  49706. const endpoint = await configProvider();
  49707. if (endpoint && typeof endpoint === "object") {
  49708. if ("url" in endpoint) {
  49709. return endpoint.url.href;
  49710. }
  49711. if ("hostname" in endpoint) {
  49712. const { protocol, hostname, port, path: path3 } = endpoint;
  49713. return `${protocol}//${hostname}${port ? ":" + port : ""}${path3}`;
  49714. }
  49715. }
  49716. return endpoint;
  49717. };
  49718. }
  49719. return configProvider;
  49720. };
  49721. }
  49722. });
  49723. // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js
  49724. function getSelectorName(functionString) {
  49725. try {
  49726. const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? []));
  49727. constants.delete("CONFIG");
  49728. constants.delete("CONFIG_PREFIX_SEPARATOR");
  49729. constants.delete("ENV");
  49730. return [...constants].join(", ");
  49731. } catch (e6) {
  49732. return functionString;
  49733. }
  49734. }
  49735. var init_getSelectorName = __esm({
  49736. "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js"() {
  49737. "use strict";
  49738. }
  49739. });
  49740. // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromEnv.js
  49741. var fromEnv;
  49742. var init_fromEnv = __esm({
  49743. "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromEnv.js"() {
  49744. "use strict";
  49745. init_dist_es21();
  49746. init_getSelectorName();
  49747. fromEnv = (envVarSelector, options) => async () => {
  49748. try {
  49749. const config = envVarSelector(process.env, options);
  49750. if (config === void 0) {
  49751. throw new Error();
  49752. }
  49753. return config;
  49754. } catch (e6) {
  49755. throw new CredentialsProviderError(e6.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger });
  49756. }
  49757. };
  49758. }
  49759. });
  49760. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js
  49761. import { homedir as homedir2 } from "os";
  49762. import { sep as sep2 } from "path";
  49763. var homeDirCache, getHomeDirCacheKey, getHomeDir;
  49764. var init_getHomeDir = __esm({
  49765. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js"() {
  49766. "use strict";
  49767. homeDirCache = {};
  49768. getHomeDirCacheKey = () => {
  49769. if (process && process.geteuid) {
  49770. return `${process.geteuid()}`;
  49771. }
  49772. return "DEFAULT";
  49773. };
  49774. getHomeDir = () => {
  49775. const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${sep2}` } = process.env;
  49776. if (HOME)
  49777. return HOME;
  49778. if (USERPROFILE)
  49779. return USERPROFILE;
  49780. if (HOMEPATH)
  49781. return `${HOMEDRIVE}${HOMEPATH}`;
  49782. const homeDirCacheKey = getHomeDirCacheKey();
  49783. if (!homeDirCache[homeDirCacheKey])
  49784. homeDirCache[homeDirCacheKey] = homedir2();
  49785. return homeDirCache[homeDirCacheKey];
  49786. };
  49787. }
  49788. });
  49789. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js
  49790. var ENV_PROFILE, DEFAULT_PROFILE, getProfileName;
  49791. var init_getProfileName = __esm({
  49792. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js"() {
  49793. "use strict";
  49794. ENV_PROFILE = "AWS_PROFILE";
  49795. DEFAULT_PROFILE = "default";
  49796. getProfileName = (init2) => init2.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE;
  49797. }
  49798. });
  49799. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js
  49800. import { createHash } from "crypto";
  49801. import { join as join2 } from "path";
  49802. var getSSOTokenFilepath;
  49803. var init_getSSOTokenFilepath = __esm({
  49804. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js"() {
  49805. "use strict";
  49806. init_getHomeDir();
  49807. getSSOTokenFilepath = (id) => {
  49808. const hasher = createHash("sha1");
  49809. const cacheName = hasher.update(id).digest("hex");
  49810. return join2(getHomeDir(), ".aws", "sso", "cache", `${cacheName}.json`);
  49811. };
  49812. }
  49813. });
  49814. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js
  49815. import { promises as fsPromises } from "fs";
  49816. var readFile2, getSSOTokenFromFile;
  49817. var init_getSSOTokenFromFile = __esm({
  49818. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js"() {
  49819. "use strict";
  49820. init_getSSOTokenFilepath();
  49821. ({ readFile: readFile2 } = fsPromises);
  49822. getSSOTokenFromFile = async (id) => {
  49823. const ssoTokenFilepath = getSSOTokenFilepath(id);
  49824. const ssoTokenText = await readFile2(ssoTokenFilepath, "utf8");
  49825. return JSON.parse(ssoTokenText);
  49826. };
  49827. }
  49828. });
  49829. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js
  49830. var getConfigData;
  49831. var init_getConfigData = __esm({
  49832. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js"() {
  49833. "use strict";
  49834. init_dist_es();
  49835. init_loadSharedConfigFiles();
  49836. getConfigData = (data) => Object.entries(data).filter(([key]) => {
  49837. const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
  49838. if (indexOfSeparator === -1) {
  49839. return false;
  49840. }
  49841. return Object.values(IniSectionType).includes(key.substring(0, indexOfSeparator));
  49842. }).reduce((acc, [key, value]) => {
  49843. const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
  49844. const updatedKey = key.substring(0, indexOfSeparator) === IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;
  49845. acc[updatedKey] = value;
  49846. return acc;
  49847. }, {
  49848. ...data.default && { default: data.default }
  49849. });
  49850. }
  49851. });
  49852. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js
  49853. import { join as join3 } from "path";
  49854. var ENV_CONFIG_PATH, getConfigFilepath;
  49855. var init_getConfigFilepath = __esm({
  49856. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js"() {
  49857. "use strict";
  49858. init_getHomeDir();
  49859. ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
  49860. getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || join3(getHomeDir(), ".aws", "config");
  49861. }
  49862. });
  49863. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js
  49864. import { join as join4 } from "path";
  49865. var ENV_CREDENTIALS_PATH, getCredentialsFilepath;
  49866. var init_getCredentialsFilepath = __esm({
  49867. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js"() {
  49868. "use strict";
  49869. init_getHomeDir();
  49870. ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
  49871. getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || join4(getHomeDir(), ".aws", "credentials");
  49872. }
  49873. });
  49874. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js
  49875. var prefixKeyRegex, profileNameBlockList, parseIni;
  49876. var init_parseIni = __esm({
  49877. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js"() {
  49878. "use strict";
  49879. init_dist_es();
  49880. init_loadSharedConfigFiles();
  49881. prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/;
  49882. profileNameBlockList = ["__proto__", "profile __proto__"];
  49883. parseIni = (iniData) => {
  49884. const map2 = {};
  49885. let currentSection;
  49886. let currentSubSection;
  49887. for (const iniLine of iniData.split(/\r?\n/)) {
  49888. const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim();
  49889. const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]";
  49890. if (isSection) {
  49891. currentSection = void 0;
  49892. currentSubSection = void 0;
  49893. const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);
  49894. const matches = prefixKeyRegex.exec(sectionName);
  49895. if (matches) {
  49896. const [, prefix2, , name] = matches;
  49897. if (Object.values(IniSectionType).includes(prefix2)) {
  49898. currentSection = [prefix2, name].join(CONFIG_PREFIX_SEPARATOR);
  49899. }
  49900. } else {
  49901. currentSection = sectionName;
  49902. }
  49903. if (profileNameBlockList.includes(sectionName)) {
  49904. throw new Error(`Found invalid profile name "${sectionName}"`);
  49905. }
  49906. } else if (currentSection) {
  49907. const indexOfEqualsSign = trimmedLine.indexOf("=");
  49908. if (![0, -1].includes(indexOfEqualsSign)) {
  49909. const [name, value] = [
  49910. trimmedLine.substring(0, indexOfEqualsSign).trim(),
  49911. trimmedLine.substring(indexOfEqualsSign + 1).trim()
  49912. ];
  49913. if (value === "") {
  49914. currentSubSection = name;
  49915. } else {
  49916. if (currentSubSection && iniLine.trimStart() === iniLine) {
  49917. currentSubSection = void 0;
  49918. }
  49919. map2[currentSection] = map2[currentSection] || {};
  49920. const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;
  49921. map2[currentSection][key] = value;
  49922. }
  49923. }
  49924. }
  49925. }
  49926. return map2;
  49927. };
  49928. }
  49929. });
  49930. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/slurpFile.js
  49931. import { promises as fsPromises2 } from "fs";
  49932. var readFile3, filePromisesHash, slurpFile;
  49933. var init_slurpFile = __esm({
  49934. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/slurpFile.js"() {
  49935. "use strict";
  49936. ({ readFile: readFile3 } = fsPromises2);
  49937. filePromisesHash = {};
  49938. slurpFile = (path3, options) => {
  49939. if (!filePromisesHash[path3] || options?.ignoreCache) {
  49940. filePromisesHash[path3] = readFile3(path3, "utf8");
  49941. }
  49942. return filePromisesHash[path3];
  49943. };
  49944. }
  49945. });
  49946. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js
  49947. import { join as join5 } from "path";
  49948. var swallowError, CONFIG_PREFIX_SEPARATOR, loadSharedConfigFiles;
  49949. var init_loadSharedConfigFiles = __esm({
  49950. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js"() {
  49951. "use strict";
  49952. init_getConfigData();
  49953. init_getConfigFilepath();
  49954. init_getCredentialsFilepath();
  49955. init_getHomeDir();
  49956. init_parseIni();
  49957. init_slurpFile();
  49958. swallowError = () => ({});
  49959. CONFIG_PREFIX_SEPARATOR = ".";
  49960. loadSharedConfigFiles = async (init2 = {}) => {
  49961. const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init2;
  49962. const homeDir = getHomeDir();
  49963. const relativeHomeDirPrefix = "~/";
  49964. let resolvedFilepath = filepath;
  49965. if (filepath.startsWith(relativeHomeDirPrefix)) {
  49966. resolvedFilepath = join5(homeDir, filepath.slice(2));
  49967. }
  49968. let resolvedConfigFilepath = configFilepath;
  49969. if (configFilepath.startsWith(relativeHomeDirPrefix)) {
  49970. resolvedConfigFilepath = join5(homeDir, configFilepath.slice(2));
  49971. }
  49972. const parsedFiles = await Promise.all([
  49973. slurpFile(resolvedConfigFilepath, {
  49974. ignoreCache: init2.ignoreCache
  49975. }).then(parseIni).then(getConfigData).catch(swallowError),
  49976. slurpFile(resolvedFilepath, {
  49977. ignoreCache: init2.ignoreCache
  49978. }).then(parseIni).catch(swallowError)
  49979. ]);
  49980. return {
  49981. configFile: parsedFiles[0],
  49982. credentialsFile: parsedFiles[1]
  49983. };
  49984. };
  49985. }
  49986. });
  49987. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js
  49988. var getSsoSessionData;
  49989. var init_getSsoSessionData = __esm({
  49990. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js"() {
  49991. "use strict";
  49992. init_dist_es();
  49993. init_loadSharedConfigFiles();
  49994. getSsoSessionData = (data) => Object.entries(data).filter(([key]) => key.startsWith(IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {});
  49995. }
  49996. });
  49997. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js
  49998. var swallowError2, loadSsoSessionData;
  49999. var init_loadSsoSessionData = __esm({
  50000. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js"() {
  50001. "use strict";
  50002. init_getConfigFilepath();
  50003. init_getSsoSessionData();
  50004. init_parseIni();
  50005. init_slurpFile();
  50006. swallowError2 = () => ({});
  50007. loadSsoSessionData = async (init2 = {}) => slurpFile(init2.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2);
  50008. }
  50009. });
  50010. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js
  50011. var mergeConfigFiles;
  50012. var init_mergeConfigFiles = __esm({
  50013. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js"() {
  50014. "use strict";
  50015. mergeConfigFiles = (...files) => {
  50016. const merged = {};
  50017. for (const file of files) {
  50018. for (const [key, values] of Object.entries(file)) {
  50019. if (merged[key] !== void 0) {
  50020. Object.assign(merged[key], values);
  50021. } else {
  50022. merged[key] = values;
  50023. }
  50024. }
  50025. }
  50026. return merged;
  50027. };
  50028. }
  50029. });
  50030. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js
  50031. var parseKnownFiles;
  50032. var init_parseKnownFiles = __esm({
  50033. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js"() {
  50034. "use strict";
  50035. init_loadSharedConfigFiles();
  50036. init_mergeConfigFiles();
  50037. parseKnownFiles = async (init2) => {
  50038. const parsedFiles = await loadSharedConfigFiles(init2);
  50039. return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);
  50040. };
  50041. }
  50042. });
  50043. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/types.js
  50044. var init_types6 = __esm({
  50045. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/types.js"() {
  50046. "use strict";
  50047. }
  50048. });
  50049. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/index.js
  50050. var init_dist_es30 = __esm({
  50051. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-es/index.js"() {
  50052. "use strict";
  50053. init_getHomeDir();
  50054. init_getProfileName();
  50055. init_getSSOTokenFilepath();
  50056. init_getSSOTokenFromFile();
  50057. init_loadSharedConfigFiles();
  50058. init_loadSsoSessionData();
  50059. init_parseKnownFiles();
  50060. init_types6();
  50061. }
  50062. });
  50063. // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js
  50064. var fromSharedConfigFiles;
  50065. var init_fromSharedConfigFiles = __esm({
  50066. "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js"() {
  50067. "use strict";
  50068. init_dist_es21();
  50069. init_dist_es30();
  50070. init_getSelectorName();
  50071. fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init2 } = {}) => async () => {
  50072. const profile = getProfileName(init2);
  50073. const { configFile, credentialsFile } = await loadSharedConfigFiles(init2);
  50074. const profileFromCredentials = credentialsFile[profile] || {};
  50075. const profileFromConfig = configFile[profile] || {};
  50076. const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials };
  50077. try {
  50078. const cfgFile = preferredFile === "config" ? configFile : credentialsFile;
  50079. const configValue = configSelector(mergedProfile, cfgFile);
  50080. if (configValue === void 0) {
  50081. throw new Error();
  50082. }
  50083. return configValue;
  50084. } catch (e6) {
  50085. throw new CredentialsProviderError(e6.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init2.logger });
  50086. }
  50087. };
  50088. }
  50089. });
  50090. // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromStatic.js
  50091. var isFunction, fromStatic2;
  50092. var init_fromStatic2 = __esm({
  50093. "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/fromStatic.js"() {
  50094. "use strict";
  50095. init_dist_es21();
  50096. isFunction = (func) => typeof func === "function";
  50097. fromStatic2 = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : fromStatic(defaultValue);
  50098. }
  50099. });
  50100. // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/configLoader.js
  50101. var loadConfig;
  50102. var init_configLoader = __esm({
  50103. "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/configLoader.js"() {
  50104. "use strict";
  50105. init_dist_es21();
  50106. init_fromEnv();
  50107. init_fromSharedConfigFiles();
  50108. init_fromStatic2();
  50109. loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => {
  50110. const { signingName, logger: logger2 } = configuration;
  50111. const envOptions = { signingName, logger: logger2 };
  50112. return memoize(chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic2(defaultValue)));
  50113. };
  50114. }
  50115. });
  50116. // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/index.js
  50117. var init_dist_es31 = __esm({
  50118. "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-es/index.js"() {
  50119. "use strict";
  50120. init_configLoader();
  50121. }
  50122. });
  50123. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js
  50124. var ENV_ENDPOINT_URL, CONFIG_ENDPOINT_URL, getEndpointUrlConfig;
  50125. var init_getEndpointUrlConfig = __esm({
  50126. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js"() {
  50127. "use strict";
  50128. init_dist_es30();
  50129. ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL";
  50130. CONFIG_ENDPOINT_URL = "endpoint_url";
  50131. getEndpointUrlConfig = (serviceId) => ({
  50132. environmentVariableSelector: (env4) => {
  50133. const serviceSuffixParts = serviceId.split(" ").map((w4) => w4.toUpperCase());
  50134. const serviceEndpointUrl = env4[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")];
  50135. if (serviceEndpointUrl)
  50136. return serviceEndpointUrl;
  50137. const endpointUrl = env4[ENV_ENDPOINT_URL];
  50138. if (endpointUrl)
  50139. return endpointUrl;
  50140. return void 0;
  50141. },
  50142. configFileSelector: (profile, config) => {
  50143. if (config && profile.services) {
  50144. const servicesSection = config[["services", profile.services].join(CONFIG_PREFIX_SEPARATOR)];
  50145. if (servicesSection) {
  50146. const servicePrefixParts = serviceId.split(" ").map((w4) => w4.toLowerCase());
  50147. const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(CONFIG_PREFIX_SEPARATOR)];
  50148. if (endpointUrl2)
  50149. return endpointUrl2;
  50150. }
  50151. }
  50152. const endpointUrl = profile[CONFIG_ENDPOINT_URL];
  50153. if (endpointUrl)
  50154. return endpointUrl;
  50155. return void 0;
  50156. },
  50157. default: void 0
  50158. });
  50159. }
  50160. });
  50161. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js
  50162. var getEndpointFromConfig;
  50163. var init_getEndpointFromConfig = __esm({
  50164. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js"() {
  50165. "use strict";
  50166. init_dist_es31();
  50167. init_getEndpointUrlConfig();
  50168. getEndpointFromConfig = async (serviceId) => loadConfig(getEndpointUrlConfig(serviceId ?? ""))();
  50169. }
  50170. });
  50171. // ../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-es/index.js
  50172. function parseQueryString(querystring) {
  50173. const query = {};
  50174. querystring = querystring.replace(/^\?/, "");
  50175. if (querystring) {
  50176. for (const pair of querystring.split("&")) {
  50177. let [key, value = null] = pair.split("=");
  50178. key = decodeURIComponent(key);
  50179. if (value) {
  50180. value = decodeURIComponent(value);
  50181. }
  50182. if (!(key in query)) {
  50183. query[key] = value;
  50184. } else if (Array.isArray(query[key])) {
  50185. query[key].push(value);
  50186. } else {
  50187. query[key] = [query[key], value];
  50188. }
  50189. }
  50190. }
  50191. return query;
  50192. }
  50193. var init_dist_es32 = __esm({
  50194. "../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-es/index.js"() {
  50195. "use strict";
  50196. }
  50197. });
  50198. // ../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-es/index.js
  50199. var parseUrl;
  50200. var init_dist_es33 = __esm({
  50201. "../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-es/index.js"() {
  50202. "use strict";
  50203. init_dist_es32();
  50204. parseUrl = (url) => {
  50205. if (typeof url === "string") {
  50206. return parseUrl(new URL(url));
  50207. }
  50208. const { hostname, pathname, port, protocol, search } = url;
  50209. let query;
  50210. if (search) {
  50211. query = parseQueryString(search);
  50212. }
  50213. return {
  50214. hostname,
  50215. port: port ? parseInt(port) : void 0,
  50216. protocol,
  50217. path: pathname,
  50218. query
  50219. };
  50220. };
  50221. }
  50222. });
  50223. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js
  50224. var toEndpointV1;
  50225. var init_toEndpointV1 = __esm({
  50226. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js"() {
  50227. "use strict";
  50228. init_dist_es33();
  50229. toEndpointV1 = (endpoint) => {
  50230. if (typeof endpoint === "object") {
  50231. if ("url" in endpoint) {
  50232. return parseUrl(endpoint.url);
  50233. }
  50234. return endpoint;
  50235. }
  50236. return parseUrl(endpoint);
  50237. };
  50238. }
  50239. });
  50240. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js
  50241. var getEndpointFromInstructions, resolveParams;
  50242. var init_getEndpointFromInstructions = __esm({
  50243. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js"() {
  50244. "use strict";
  50245. init_service_customizations();
  50246. init_createConfigValueProvider();
  50247. init_getEndpointFromConfig();
  50248. init_toEndpointV1();
  50249. getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => {
  50250. if (!clientConfig.endpoint) {
  50251. let endpointFromConfig;
  50252. if (clientConfig.serviceConfiguredEndpoint) {
  50253. endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();
  50254. } else {
  50255. endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId);
  50256. }
  50257. if (endpointFromConfig) {
  50258. clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
  50259. }
  50260. }
  50261. const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);
  50262. if (typeof clientConfig.endpointProvider !== "function") {
  50263. throw new Error("config.endpointProvider is not set.");
  50264. }
  50265. const endpoint = clientConfig.endpointProvider(endpointParams, context);
  50266. return endpoint;
  50267. };
  50268. resolveParams = async (commandInput, instructionsSupplier, clientConfig) => {
  50269. const endpointParams = {};
  50270. const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {};
  50271. for (const [name, instruction] of Object.entries(instructions)) {
  50272. switch (instruction.type) {
  50273. case "staticContextParams":
  50274. endpointParams[name] = instruction.value;
  50275. break;
  50276. case "contextParams":
  50277. endpointParams[name] = commandInput[instruction.name];
  50278. break;
  50279. case "clientContextParams":
  50280. case "builtInParams":
  50281. endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)();
  50282. break;
  50283. case "operationContextParams":
  50284. endpointParams[name] = instruction.get(commandInput);
  50285. break;
  50286. default:
  50287. throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction));
  50288. }
  50289. }
  50290. if (Object.keys(instructions).length === 0) {
  50291. Object.assign(endpointParams, clientConfig);
  50292. }
  50293. if (String(clientConfig.serviceId).toLowerCase() === "s3") {
  50294. await resolveParamsForS3(endpointParams);
  50295. }
  50296. return endpointParams;
  50297. };
  50298. }
  50299. });
  50300. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js
  50301. var init_adaptors = __esm({
  50302. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js"() {
  50303. "use strict";
  50304. init_getEndpointFromInstructions();
  50305. init_toEndpointV1();
  50306. }
  50307. });
  50308. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js
  50309. var endpointMiddleware;
  50310. var init_endpointMiddleware = __esm({
  50311. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js"() {
  50312. "use strict";
  50313. init_dist_es18();
  50314. init_dist_es6();
  50315. init_getEndpointFromInstructions();
  50316. endpointMiddleware = ({ config, instructions }) => {
  50317. return (next, context) => async (args) => {
  50318. if (config.endpoint) {
  50319. setFeature(context, "ENDPOINT_OVERRIDE", "N");
  50320. }
  50321. const endpoint = await getEndpointFromInstructions(args.input, {
  50322. getEndpointParameterInstructions() {
  50323. return instructions;
  50324. }
  50325. }, { ...config }, context);
  50326. context.endpointV2 = endpoint;
  50327. context.authSchemes = endpoint.properties?.authSchemes;
  50328. const authScheme = context.authSchemes?.[0];
  50329. if (authScheme) {
  50330. context["signing_region"] = authScheme.signingRegion;
  50331. context["signing_service"] = authScheme.signingName;
  50332. const smithyContext = getSmithyContext(context);
  50333. const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption;
  50334. if (httpAuthOption) {
  50335. httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, {
  50336. signing_region: authScheme.signingRegion,
  50337. signingRegion: authScheme.signingRegion,
  50338. signing_service: authScheme.signingName,
  50339. signingName: authScheme.signingName,
  50340. signingRegionSet: authScheme.signingRegionSet
  50341. }, authScheme.properties);
  50342. }
  50343. }
  50344. return next({
  50345. ...args
  50346. });
  50347. };
  50348. };
  50349. }
  50350. });
  50351. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js
  50352. var endpointMiddlewareOptions, getEndpointPlugin;
  50353. var init_getEndpointPlugin = __esm({
  50354. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js"() {
  50355. "use strict";
  50356. init_dist_es7();
  50357. init_endpointMiddleware();
  50358. endpointMiddlewareOptions = {
  50359. step: "serialize",
  50360. tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
  50361. name: "endpointV2Middleware",
  50362. override: true,
  50363. relation: "before",
  50364. toMiddleware: serializerMiddlewareOption.name
  50365. };
  50366. getEndpointPlugin = (config, instructions) => ({
  50367. applyToStack: (clientStack) => {
  50368. clientStack.addRelativeTo(endpointMiddleware({
  50369. config,
  50370. instructions
  50371. }), endpointMiddlewareOptions);
  50372. }
  50373. });
  50374. }
  50375. });
  50376. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js
  50377. var resolveEndpointConfig;
  50378. var init_resolveEndpointConfig = __esm({
  50379. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js"() {
  50380. "use strict";
  50381. init_dist_es6();
  50382. init_getEndpointFromConfig();
  50383. init_toEndpointV1();
  50384. resolveEndpointConfig = (input) => {
  50385. const tls = input.tls ?? true;
  50386. const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input;
  50387. const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : void 0;
  50388. const isCustomEndpoint = !!endpoint;
  50389. const resolvedConfig = Object.assign(input, {
  50390. endpoint: customEndpointProvider,
  50391. tls,
  50392. isCustomEndpoint,
  50393. useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false),
  50394. useFipsEndpoint: normalizeProvider(useFipsEndpoint ?? false)
  50395. });
  50396. let configuredEndpointPromise = void 0;
  50397. resolvedConfig.serviceConfiguredEndpoint = async () => {
  50398. if (input.serviceId && !configuredEndpointPromise) {
  50399. configuredEndpointPromise = getEndpointFromConfig(input.serviceId);
  50400. }
  50401. return configuredEndpointPromise;
  50402. };
  50403. return resolvedConfig;
  50404. };
  50405. }
  50406. });
  50407. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/types.js
  50408. var init_types7 = __esm({
  50409. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/types.js"() {
  50410. "use strict";
  50411. }
  50412. });
  50413. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/index.js
  50414. var init_dist_es34 = __esm({
  50415. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-es/index.js"() {
  50416. "use strict";
  50417. init_adaptors();
  50418. init_endpointMiddleware();
  50419. init_getEndpointPlugin();
  50420. init_resolveEndpointConfig();
  50421. init_types7();
  50422. }
  50423. });
  50424. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/config.js
  50425. var RETRY_MODES, DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_MODE;
  50426. var init_config3 = __esm({
  50427. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/config.js"() {
  50428. "use strict";
  50429. (function(RETRY_MODES2) {
  50430. RETRY_MODES2["STANDARD"] = "standard";
  50431. RETRY_MODES2["ADAPTIVE"] = "adaptive";
  50432. })(RETRY_MODES || (RETRY_MODES = {}));
  50433. DEFAULT_MAX_ATTEMPTS = 3;
  50434. DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD;
  50435. }
  50436. });
  50437. // ../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/constants.js
  50438. var THROTTLING_ERROR_CODES, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_STATUS_CODES, NODEJS_TIMEOUT_ERROR_CODES2;
  50439. var init_constants6 = __esm({
  50440. "../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/constants.js"() {
  50441. "use strict";
  50442. THROTTLING_ERROR_CODES = [
  50443. "BandwidthLimitExceeded",
  50444. "EC2ThrottledException",
  50445. "LimitExceededException",
  50446. "PriorRequestNotComplete",
  50447. "ProvisionedThroughputExceededException",
  50448. "RequestLimitExceeded",
  50449. "RequestThrottled",
  50450. "RequestThrottledException",
  50451. "SlowDown",
  50452. "ThrottledException",
  50453. "Throttling",
  50454. "ThrottlingException",
  50455. "TooManyRequestsException",
  50456. "TransactionInProgressException"
  50457. ];
  50458. TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
  50459. TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
  50460. NODEJS_TIMEOUT_ERROR_CODES2 = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
  50461. }
  50462. });
  50463. // ../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/index.js
  50464. var isClockSkewCorrectedError, isBrowserNetworkError, isThrottlingError, isTransientError, isServerError;
  50465. var init_dist_es35 = __esm({
  50466. "../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-es/index.js"() {
  50467. "use strict";
  50468. init_constants6();
  50469. isClockSkewCorrectedError = (error2) => error2.$metadata?.clockSkewCorrected;
  50470. isBrowserNetworkError = (error2) => {
  50471. const errorMessages = /* @__PURE__ */ new Set([
  50472. "Failed to fetch",
  50473. "NetworkError when attempting to fetch resource",
  50474. "The Internet connection appears to be offline",
  50475. "Load failed",
  50476. "Network request failed"
  50477. ]);
  50478. const isValid2 = error2 && error2 instanceof TypeError;
  50479. if (!isValid2) {
  50480. return false;
  50481. }
  50482. return errorMessages.has(error2.message);
  50483. };
  50484. isThrottlingError = (error2) => error2.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error2.name) || error2.$retryable?.throttling == true;
  50485. isTransientError = (error2, depth = 0) => isClockSkewCorrectedError(error2) || TRANSIENT_ERROR_CODES.includes(error2.name) || NODEJS_TIMEOUT_ERROR_CODES2.includes(error2?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error2.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error2) || error2.cause !== void 0 && depth <= 10 && isTransientError(error2.cause, depth + 1);
  50486. isServerError = (error2) => {
  50487. if (error2.$metadata?.httpStatusCode !== void 0) {
  50488. const statusCode = error2.$metadata.httpStatusCode;
  50489. if (500 <= statusCode && statusCode <= 599 && !isTransientError(error2)) {
  50490. return true;
  50491. }
  50492. return false;
  50493. }
  50494. return false;
  50495. };
  50496. }
  50497. });
  50498. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js
  50499. var DefaultRateLimiter;
  50500. var init_DefaultRateLimiter = __esm({
  50501. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js"() {
  50502. "use strict";
  50503. init_dist_es35();
  50504. DefaultRateLimiter = class _DefaultRateLimiter {
  50505. constructor(options) {
  50506. this.currentCapacity = 0;
  50507. this.enabled = false;
  50508. this.lastMaxRate = 0;
  50509. this.measuredTxRate = 0;
  50510. this.requestCount = 0;
  50511. this.lastTimestamp = 0;
  50512. this.timeWindow = 0;
  50513. this.beta = options?.beta ?? 0.7;
  50514. this.minCapacity = options?.minCapacity ?? 1;
  50515. this.minFillRate = options?.minFillRate ?? 0.5;
  50516. this.scaleConstant = options?.scaleConstant ?? 0.4;
  50517. this.smooth = options?.smooth ?? 0.8;
  50518. const currentTimeInSeconds = this.getCurrentTimeInSeconds();
  50519. this.lastThrottleTime = currentTimeInSeconds;
  50520. this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
  50521. this.fillRate = this.minFillRate;
  50522. this.maxCapacity = this.minCapacity;
  50523. }
  50524. getCurrentTimeInSeconds() {
  50525. return Date.now() / 1e3;
  50526. }
  50527. async getSendToken() {
  50528. return this.acquireTokenBucket(1);
  50529. }
  50530. async acquireTokenBucket(amount) {
  50531. if (!this.enabled) {
  50532. return;
  50533. }
  50534. this.refillTokenBucket();
  50535. if (amount > this.currentCapacity) {
  50536. const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
  50537. await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(resolve, delay));
  50538. }
  50539. this.currentCapacity = this.currentCapacity - amount;
  50540. }
  50541. refillTokenBucket() {
  50542. const timestamp = this.getCurrentTimeInSeconds();
  50543. if (!this.lastTimestamp) {
  50544. this.lastTimestamp = timestamp;
  50545. return;
  50546. }
  50547. const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;
  50548. this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);
  50549. this.lastTimestamp = timestamp;
  50550. }
  50551. updateClientSendingRate(response) {
  50552. let calculatedRate;
  50553. this.updateMeasuredRate();
  50554. if (isThrottlingError(response)) {
  50555. const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
  50556. this.lastMaxRate = rateToUse;
  50557. this.calculateTimeWindow();
  50558. this.lastThrottleTime = this.getCurrentTimeInSeconds();
  50559. calculatedRate = this.cubicThrottle(rateToUse);
  50560. this.enableTokenBucket();
  50561. } else {
  50562. this.calculateTimeWindow();
  50563. calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());
  50564. }
  50565. const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);
  50566. this.updateTokenBucketRate(newRate);
  50567. }
  50568. calculateTimeWindow() {
  50569. this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
  50570. }
  50571. cubicThrottle(rateToUse) {
  50572. return this.getPrecise(rateToUse * this.beta);
  50573. }
  50574. cubicSuccess(timestamp) {
  50575. return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate);
  50576. }
  50577. enableTokenBucket() {
  50578. this.enabled = true;
  50579. }
  50580. updateTokenBucketRate(newRate) {
  50581. this.refillTokenBucket();
  50582. this.fillRate = Math.max(newRate, this.minFillRate);
  50583. this.maxCapacity = Math.max(newRate, this.minCapacity);
  50584. this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
  50585. }
  50586. updateMeasuredRate() {
  50587. const t6 = this.getCurrentTimeInSeconds();
  50588. const timeBucket = Math.floor(t6 * 2) / 2;
  50589. this.requestCount++;
  50590. if (timeBucket > this.lastTxRateBucket) {
  50591. const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);
  50592. this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));
  50593. this.requestCount = 0;
  50594. this.lastTxRateBucket = timeBucket;
  50595. }
  50596. }
  50597. getPrecise(num) {
  50598. return parseFloat(num.toFixed(8));
  50599. }
  50600. };
  50601. DefaultRateLimiter.setTimeoutFn = setTimeout;
  50602. }
  50603. });
  50604. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/constants.js
  50605. var DEFAULT_RETRY_DELAY_BASE, MAXIMUM_RETRY_DELAY, THROTTLING_RETRY_DELAY_BASE, INITIAL_RETRY_TOKENS, RETRY_COST, TIMEOUT_RETRY_COST, NO_RETRY_INCREMENT, INVOCATION_ID_HEADER, REQUEST_HEADER;
  50606. var init_constants7 = __esm({
  50607. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/constants.js"() {
  50608. "use strict";
  50609. DEFAULT_RETRY_DELAY_BASE = 100;
  50610. MAXIMUM_RETRY_DELAY = 20 * 1e3;
  50611. THROTTLING_RETRY_DELAY_BASE = 500;
  50612. INITIAL_RETRY_TOKENS = 500;
  50613. RETRY_COST = 5;
  50614. TIMEOUT_RETRY_COST = 10;
  50615. NO_RETRY_INCREMENT = 1;
  50616. INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
  50617. REQUEST_HEADER = "amz-sdk-request";
  50618. }
  50619. });
  50620. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js
  50621. var getDefaultRetryBackoffStrategy;
  50622. var init_defaultRetryBackoffStrategy = __esm({
  50623. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js"() {
  50624. "use strict";
  50625. init_constants7();
  50626. getDefaultRetryBackoffStrategy = () => {
  50627. let delayBase = DEFAULT_RETRY_DELAY_BASE;
  50628. const computeNextBackoffDelay = (attempts) => {
  50629. return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
  50630. };
  50631. const setDelayBase = (delay) => {
  50632. delayBase = delay;
  50633. };
  50634. return {
  50635. computeNextBackoffDelay,
  50636. setDelayBase
  50637. };
  50638. };
  50639. }
  50640. });
  50641. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js
  50642. var createDefaultRetryToken;
  50643. var init_defaultRetryToken = __esm({
  50644. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js"() {
  50645. "use strict";
  50646. init_constants7();
  50647. createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => {
  50648. const getRetryCount = () => retryCount;
  50649. const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay);
  50650. const getRetryCost = () => retryCost;
  50651. return {
  50652. getRetryCount,
  50653. getRetryDelay,
  50654. getRetryCost
  50655. };
  50656. };
  50657. }
  50658. });
  50659. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js
  50660. var StandardRetryStrategy;
  50661. var init_StandardRetryStrategy = __esm({
  50662. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js"() {
  50663. "use strict";
  50664. init_config3();
  50665. init_constants7();
  50666. init_defaultRetryBackoffStrategy();
  50667. init_defaultRetryToken();
  50668. StandardRetryStrategy = class {
  50669. constructor(maxAttempts) {
  50670. this.maxAttempts = maxAttempts;
  50671. this.mode = RETRY_MODES.STANDARD;
  50672. this.capacity = INITIAL_RETRY_TOKENS;
  50673. this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
  50674. this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
  50675. }
  50676. async acquireInitialRetryToken(retryTokenScope) {
  50677. return createDefaultRetryToken({
  50678. retryDelay: DEFAULT_RETRY_DELAY_BASE,
  50679. retryCount: 0
  50680. });
  50681. }
  50682. async refreshRetryTokenForRetry(token, errorInfo) {
  50683. const maxAttempts = await this.getMaxAttempts();
  50684. if (this.shouldRetry(token, errorInfo, maxAttempts)) {
  50685. const errorType = errorInfo.errorType;
  50686. this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE);
  50687. const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());
  50688. const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType;
  50689. const capacityCost = this.getCapacityCost(errorType);
  50690. this.capacity -= capacityCost;
  50691. return createDefaultRetryToken({
  50692. retryDelay,
  50693. retryCount: token.getRetryCount() + 1,
  50694. retryCost: capacityCost
  50695. });
  50696. }
  50697. throw new Error("No retry token available");
  50698. }
  50699. recordSuccess(token) {
  50700. this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));
  50701. }
  50702. getCapacity() {
  50703. return this.capacity;
  50704. }
  50705. async getMaxAttempts() {
  50706. try {
  50707. return await this.maxAttemptsProvider();
  50708. } catch (error2) {
  50709. console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
  50710. return DEFAULT_MAX_ATTEMPTS;
  50711. }
  50712. }
  50713. shouldRetry(tokenToRenew, errorInfo, maxAttempts) {
  50714. const attempts = tokenToRenew.getRetryCount() + 1;
  50715. return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType);
  50716. }
  50717. getCapacityCost(errorType) {
  50718. return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST;
  50719. }
  50720. isRetryableError(errorType) {
  50721. return errorType === "THROTTLING" || errorType === "TRANSIENT";
  50722. }
  50723. };
  50724. }
  50725. });
  50726. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js
  50727. var AdaptiveRetryStrategy;
  50728. var init_AdaptiveRetryStrategy = __esm({
  50729. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js"() {
  50730. "use strict";
  50731. init_config3();
  50732. init_DefaultRateLimiter();
  50733. init_StandardRetryStrategy();
  50734. AdaptiveRetryStrategy = class {
  50735. constructor(maxAttemptsProvider, options) {
  50736. this.maxAttemptsProvider = maxAttemptsProvider;
  50737. this.mode = RETRY_MODES.ADAPTIVE;
  50738. const { rateLimiter } = options ?? {};
  50739. this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
  50740. this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
  50741. }
  50742. async acquireInitialRetryToken(retryTokenScope) {
  50743. await this.rateLimiter.getSendToken();
  50744. return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
  50745. }
  50746. async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
  50747. this.rateLimiter.updateClientSendingRate(errorInfo);
  50748. return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
  50749. }
  50750. recordSuccess(token) {
  50751. this.rateLimiter.updateClientSendingRate({});
  50752. this.standardRetryStrategy.recordSuccess(token);
  50753. }
  50754. };
  50755. }
  50756. });
  50757. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js
  50758. var init_ConfiguredRetryStrategy = __esm({
  50759. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js"() {
  50760. "use strict";
  50761. init_constants7();
  50762. init_StandardRetryStrategy();
  50763. }
  50764. });
  50765. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/types.js
  50766. var init_types8 = __esm({
  50767. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/types.js"() {
  50768. "use strict";
  50769. }
  50770. });
  50771. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/index.js
  50772. var init_dist_es36 = __esm({
  50773. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-es/index.js"() {
  50774. "use strict";
  50775. init_AdaptiveRetryStrategy();
  50776. init_ConfiguredRetryStrategy();
  50777. init_DefaultRateLimiter();
  50778. init_StandardRetryStrategy();
  50779. init_config3();
  50780. init_constants7();
  50781. init_types8();
  50782. }
  50783. });
  50784. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js
  50785. import crypto3 from "crypto";
  50786. function rng() {
  50787. if (poolPtr > rnds8Pool.length - 16) {
  50788. crypto3.randomFillSync(rnds8Pool);
  50789. poolPtr = 0;
  50790. }
  50791. return rnds8Pool.slice(poolPtr, poolPtr += 16);
  50792. }
  50793. var rnds8Pool, poolPtr;
  50794. var init_rng = __esm({
  50795. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js"() {
  50796. "use strict";
  50797. rnds8Pool = new Uint8Array(256);
  50798. poolPtr = rnds8Pool.length;
  50799. }
  50800. });
  50801. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js
  50802. function unsafeStringify(arr, offset = 0) {
  50803. return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
  50804. }
  50805. var byteToHex;
  50806. var init_stringify = __esm({
  50807. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js"() {
  50808. "use strict";
  50809. byteToHex = [];
  50810. for (let i6 = 0; i6 < 256; ++i6) {
  50811. byteToHex.push((i6 + 256).toString(16).slice(1));
  50812. }
  50813. }
  50814. });
  50815. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js
  50816. import crypto4 from "crypto";
  50817. var native_default;
  50818. var init_native = __esm({
  50819. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js"() {
  50820. "use strict";
  50821. native_default = {
  50822. randomUUID: crypto4.randomUUID
  50823. };
  50824. }
  50825. });
  50826. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js
  50827. function v4(options, buf, offset) {
  50828. if (native_default.randomUUID && !buf && !options) {
  50829. return native_default.randomUUID();
  50830. }
  50831. options = options || {};
  50832. const rnds = options.random || (options.rng || rng)();
  50833. rnds[6] = rnds[6] & 15 | 64;
  50834. rnds[8] = rnds[8] & 63 | 128;
  50835. if (buf) {
  50836. offset = offset || 0;
  50837. for (let i6 = 0; i6 < 16; ++i6) {
  50838. buf[offset + i6] = rnds[i6];
  50839. }
  50840. return buf;
  50841. }
  50842. return unsafeStringify(rnds);
  50843. }
  50844. var v4_default;
  50845. var init_v4 = __esm({
  50846. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js"() {
  50847. "use strict";
  50848. init_native();
  50849. init_rng();
  50850. init_stringify();
  50851. v4_default = v4;
  50852. }
  50853. });
  50854. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js
  50855. var init_esm_node = __esm({
  50856. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js"() {
  50857. "use strict";
  50858. init_v4();
  50859. }
  50860. });
  50861. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js
  50862. var init_defaultRetryQuota = __esm({
  50863. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js"() {
  50864. "use strict";
  50865. init_dist_es36();
  50866. }
  50867. });
  50868. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/delayDecider.js
  50869. var init_delayDecider = __esm({
  50870. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/delayDecider.js"() {
  50871. "use strict";
  50872. init_dist_es36();
  50873. }
  50874. });
  50875. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryDecider.js
  50876. var init_retryDecider = __esm({
  50877. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryDecider.js"() {
  50878. "use strict";
  50879. init_dist_es35();
  50880. }
  50881. });
  50882. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/util.js
  50883. var asSdkError;
  50884. var init_util3 = __esm({
  50885. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/util.js"() {
  50886. "use strict";
  50887. asSdkError = (error2) => {
  50888. if (error2 instanceof Error)
  50889. return error2;
  50890. if (error2 instanceof Object)
  50891. return Object.assign(new Error(), error2);
  50892. if (typeof error2 === "string")
  50893. return new Error(error2);
  50894. return new Error(`AWS SDK error wrapper for ${error2}`);
  50895. };
  50896. }
  50897. });
  50898. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js
  50899. var init_StandardRetryStrategy2 = __esm({
  50900. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js"() {
  50901. "use strict";
  50902. init_dist_es2();
  50903. init_dist_es35();
  50904. init_dist_es36();
  50905. init_defaultRetryQuota();
  50906. init_delayDecider();
  50907. init_retryDecider();
  50908. init_util3();
  50909. }
  50910. });
  50911. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js
  50912. var init_AdaptiveRetryStrategy2 = __esm({
  50913. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js"() {
  50914. "use strict";
  50915. init_dist_es36();
  50916. init_StandardRetryStrategy2();
  50917. }
  50918. });
  50919. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/configurations.js
  50920. var ENV_MAX_ATTEMPTS, CONFIG_MAX_ATTEMPTS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, ENV_RETRY_MODE, CONFIG_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS;
  50921. var init_configurations2 = __esm({
  50922. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/configurations.js"() {
  50923. "use strict";
  50924. init_dist_es6();
  50925. init_dist_es36();
  50926. ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
  50927. CONFIG_MAX_ATTEMPTS = "max_attempts";
  50928. NODE_MAX_ATTEMPT_CONFIG_OPTIONS = {
  50929. environmentVariableSelector: (env4) => {
  50930. const value = env4[ENV_MAX_ATTEMPTS];
  50931. if (!value)
  50932. return void 0;
  50933. const maxAttempt = parseInt(value);
  50934. if (Number.isNaN(maxAttempt)) {
  50935. throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`);
  50936. }
  50937. return maxAttempt;
  50938. },
  50939. configFileSelector: (profile) => {
  50940. const value = profile[CONFIG_MAX_ATTEMPTS];
  50941. if (!value)
  50942. return void 0;
  50943. const maxAttempt = parseInt(value);
  50944. if (Number.isNaN(maxAttempt)) {
  50945. throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`);
  50946. }
  50947. return maxAttempt;
  50948. },
  50949. default: DEFAULT_MAX_ATTEMPTS
  50950. };
  50951. resolveRetryConfig = (input) => {
  50952. const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input;
  50953. const maxAttempts = normalizeProvider(_maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
  50954. return Object.assign(input, {
  50955. maxAttempts,
  50956. retryStrategy: async () => {
  50957. if (retryStrategy) {
  50958. return retryStrategy;
  50959. }
  50960. const retryMode = await normalizeProvider(_retryMode)();
  50961. if (retryMode === RETRY_MODES.ADAPTIVE) {
  50962. return new AdaptiveRetryStrategy(maxAttempts);
  50963. }
  50964. return new StandardRetryStrategy(maxAttempts);
  50965. }
  50966. });
  50967. };
  50968. ENV_RETRY_MODE = "AWS_RETRY_MODE";
  50969. CONFIG_RETRY_MODE = "retry_mode";
  50970. NODE_RETRY_MODE_CONFIG_OPTIONS = {
  50971. environmentVariableSelector: (env4) => env4[ENV_RETRY_MODE],
  50972. configFileSelector: (profile) => profile[CONFIG_RETRY_MODE],
  50973. default: DEFAULT_RETRY_MODE
  50974. };
  50975. }
  50976. });
  50977. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js
  50978. var init_omitRetryHeadersMiddleware = __esm({
  50979. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js"() {
  50980. "use strict";
  50981. init_dist_es2();
  50982. init_dist_es36();
  50983. }
  50984. });
  50985. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js
  50986. import { Readable as Readable5 } from "stream";
  50987. var isStreamingPayload;
  50988. var init_isStreamingPayload = __esm({
  50989. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js"() {
  50990. "use strict";
  50991. isStreamingPayload = (request2) => request2?.body instanceof Readable5 || typeof ReadableStream !== "undefined" && request2?.body instanceof ReadableStream;
  50992. }
  50993. });
  50994. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js
  50995. var retryMiddleware, isRetryStrategyV2, getRetryErrorInfo, getRetryErrorType, retryMiddlewareOptions, getRetryPlugin, getRetryAfterHint;
  50996. var init_retryMiddleware = __esm({
  50997. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js"() {
  50998. "use strict";
  50999. init_dist_es2();
  51000. init_dist_es35();
  51001. init_dist_es24();
  51002. init_dist_es36();
  51003. init_esm_node();
  51004. init_isStreamingPayload();
  51005. init_util3();
  51006. retryMiddleware = (options) => (next, context) => async (args) => {
  51007. let retryStrategy = await options.retryStrategy();
  51008. const maxAttempts = await options.maxAttempts();
  51009. if (isRetryStrategyV2(retryStrategy)) {
  51010. retryStrategy = retryStrategy;
  51011. let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]);
  51012. let lastError = new Error();
  51013. let attempts = 0;
  51014. let totalRetryDelay = 0;
  51015. const { request: request2 } = args;
  51016. const isRequest2 = HttpRequest.isInstance(request2);
  51017. if (isRequest2) {
  51018. request2.headers[INVOCATION_ID_HEADER] = v4_default();
  51019. }
  51020. while (true) {
  51021. try {
  51022. if (isRequest2) {
  51023. request2.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
  51024. }
  51025. const { response, output } = await next(args);
  51026. retryStrategy.recordSuccess(retryToken);
  51027. output.$metadata.attempts = attempts + 1;
  51028. output.$metadata.totalRetryDelay = totalRetryDelay;
  51029. return { response, output };
  51030. } catch (e6) {
  51031. const retryErrorInfo = getRetryErrorInfo(e6);
  51032. lastError = asSdkError(e6);
  51033. if (isRequest2 && isStreamingPayload(request2)) {
  51034. (context.logger instanceof NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request.");
  51035. throw lastError;
  51036. }
  51037. try {
  51038. retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);
  51039. } catch (refreshError) {
  51040. if (!lastError.$metadata) {
  51041. lastError.$metadata = {};
  51042. }
  51043. lastError.$metadata.attempts = attempts + 1;
  51044. lastError.$metadata.totalRetryDelay = totalRetryDelay;
  51045. throw lastError;
  51046. }
  51047. attempts = retryToken.getRetryCount();
  51048. const delay = retryToken.getRetryDelay();
  51049. totalRetryDelay += delay;
  51050. await new Promise((resolve) => setTimeout(resolve, delay));
  51051. }
  51052. }
  51053. } else {
  51054. retryStrategy = retryStrategy;
  51055. if (retryStrategy?.mode)
  51056. context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
  51057. return retryStrategy.retry(next, args);
  51058. }
  51059. };
  51060. isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined";
  51061. getRetryErrorInfo = (error2) => {
  51062. const errorInfo = {
  51063. error: error2,
  51064. errorType: getRetryErrorType(error2)
  51065. };
  51066. const retryAfterHint = getRetryAfterHint(error2.$response);
  51067. if (retryAfterHint) {
  51068. errorInfo.retryAfterHint = retryAfterHint;
  51069. }
  51070. return errorInfo;
  51071. };
  51072. getRetryErrorType = (error2) => {
  51073. if (isThrottlingError(error2))
  51074. return "THROTTLING";
  51075. if (isTransientError(error2))
  51076. return "TRANSIENT";
  51077. if (isServerError(error2))
  51078. return "SERVER_ERROR";
  51079. return "CLIENT_ERROR";
  51080. };
  51081. retryMiddlewareOptions = {
  51082. name: "retryMiddleware",
  51083. tags: ["RETRY"],
  51084. step: "finalizeRequest",
  51085. priority: "high",
  51086. override: true
  51087. };
  51088. getRetryPlugin = (options) => ({
  51089. applyToStack: (clientStack) => {
  51090. clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
  51091. }
  51092. });
  51093. getRetryAfterHint = (response) => {
  51094. if (!HttpResponse.isInstance(response))
  51095. return;
  51096. const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after");
  51097. if (!retryAfterHeaderName)
  51098. return;
  51099. const retryAfter = response.headers[retryAfterHeaderName];
  51100. const retryAfterSeconds = Number(retryAfter);
  51101. if (!Number.isNaN(retryAfterSeconds))
  51102. return new Date(retryAfterSeconds * 1e3);
  51103. const retryAfterDate = new Date(retryAfter);
  51104. return retryAfterDate;
  51105. };
  51106. }
  51107. });
  51108. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/index.js
  51109. var init_dist_es37 = __esm({
  51110. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-es/index.js"() {
  51111. "use strict";
  51112. init_AdaptiveRetryStrategy2();
  51113. init_StandardRetryStrategy2();
  51114. init_configurations2();
  51115. init_delayDecider();
  51116. init_omitRetryHeadersMiddleware();
  51117. init_retryDecider();
  51118. init_retryMiddleware();
  51119. }
  51120. });
  51121. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthSchemeProvider.js
  51122. function createAwsAuthSigv4HttpAuthOption(authParameters) {
  51123. return {
  51124. schemeId: "aws.auth#sigv4",
  51125. signingProperties: {
  51126. name: "rds-data",
  51127. region: authParameters.region
  51128. },
  51129. propertiesExtractor: (config, context) => ({
  51130. signingProperties: {
  51131. config,
  51132. context
  51133. }
  51134. })
  51135. };
  51136. }
  51137. var defaultRDSDataHttpAuthSchemeParametersProvider, defaultRDSDataHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig;
  51138. var init_httpAuthSchemeProvider = __esm({
  51139. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthSchemeProvider.js"() {
  51140. "use strict";
  51141. init_dist_es25();
  51142. init_dist_es6();
  51143. defaultRDSDataHttpAuthSchemeParametersProvider = async (config, context, input) => {
  51144. return {
  51145. operation: getSmithyContext(context).operation,
  51146. region: await normalizeProvider(config.region)() || (() => {
  51147. throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
  51148. })()
  51149. };
  51150. };
  51151. defaultRDSDataHttpAuthSchemeProvider = (authParameters) => {
  51152. const options = [];
  51153. switch (authParameters.operation) {
  51154. default: {
  51155. options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
  51156. }
  51157. }
  51158. return options;
  51159. };
  51160. resolveHttpAuthSchemeConfig = (config) => {
  51161. const config_0 = resolveAwsSdkSigV4Config(config);
  51162. return Object.assign(config_0, {
  51163. authSchemePreference: normalizeProvider(config.authSchemePreference ?? [])
  51164. });
  51165. };
  51166. }
  51167. });
  51168. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/EndpointParameters.js
  51169. var resolveClientEndpointParameters, commonParams;
  51170. var init_EndpointParameters = __esm({
  51171. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/EndpointParameters.js"() {
  51172. "use strict";
  51173. resolveClientEndpointParameters = (options) => {
  51174. return Object.assign(options, {
  51175. useDualstackEndpoint: options.useDualstackEndpoint ?? false,
  51176. useFipsEndpoint: options.useFipsEndpoint ?? false,
  51177. defaultSigningName: "rds-data"
  51178. });
  51179. };
  51180. commonParams = {
  51181. UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
  51182. Endpoint: { type: "builtInParams", name: "endpoint" },
  51183. Region: { type: "builtInParams", name: "region" },
  51184. UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  51185. };
  51186. }
  51187. });
  51188. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json
  51189. var package_default;
  51190. var init_package = __esm({
  51191. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json"() {
  51192. package_default = {
  51193. name: "@aws-sdk/client-rds-data",
  51194. description: "AWS SDK for JavaScript Rds Data Client for Node.js, Browser and React Native",
  51195. version: "3.817.0",
  51196. scripts: {
  51197. build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
  51198. "build:cjs": "node ../../scripts/compilation/inline client-rds-data",
  51199. "build:es": "tsc -p tsconfig.es.json",
  51200. "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
  51201. "build:types": "tsc -p tsconfig.types.json",
  51202. "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
  51203. clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
  51204. "extract:docs": "api-extractor run --local",
  51205. "generate:client": "node ../../scripts/generate-clients/single-service --solo rds-data"
  51206. },
  51207. main: "./dist-cjs/index.js",
  51208. types: "./dist-types/index.d.ts",
  51209. module: "./dist-es/index.js",
  51210. sideEffects: false,
  51211. dependencies: {
  51212. "@aws-crypto/sha256-browser": "5.2.0",
  51213. "@aws-crypto/sha256-js": "5.2.0",
  51214. "@aws-sdk/core": "3.816.0",
  51215. "@aws-sdk/credential-provider-node": "3.817.0",
  51216. "@aws-sdk/middleware-host-header": "3.804.0",
  51217. "@aws-sdk/middleware-logger": "3.804.0",
  51218. "@aws-sdk/middleware-recursion-detection": "3.804.0",
  51219. "@aws-sdk/middleware-user-agent": "3.816.0",
  51220. "@aws-sdk/region-config-resolver": "3.808.0",
  51221. "@aws-sdk/types": "3.804.0",
  51222. "@aws-sdk/util-endpoints": "3.808.0",
  51223. "@aws-sdk/util-user-agent-browser": "3.804.0",
  51224. "@aws-sdk/util-user-agent-node": "3.816.0",
  51225. "@smithy/config-resolver": "^4.1.2",
  51226. "@smithy/core": "^3.3.3",
  51227. "@smithy/fetch-http-handler": "^5.0.2",
  51228. "@smithy/hash-node": "^4.0.2",
  51229. "@smithy/invalid-dependency": "^4.0.2",
  51230. "@smithy/middleware-content-length": "^4.0.2",
  51231. "@smithy/middleware-endpoint": "^4.1.6",
  51232. "@smithy/middleware-retry": "^4.1.7",
  51233. "@smithy/middleware-serde": "^4.0.5",
  51234. "@smithy/middleware-stack": "^4.0.2",
  51235. "@smithy/node-config-provider": "^4.1.1",
  51236. "@smithy/node-http-handler": "^4.0.4",
  51237. "@smithy/protocol-http": "^5.1.0",
  51238. "@smithy/smithy-client": "^4.2.6",
  51239. "@smithy/types": "^4.2.0",
  51240. "@smithy/url-parser": "^4.0.2",
  51241. "@smithy/util-base64": "^4.0.0",
  51242. "@smithy/util-body-length-browser": "^4.0.0",
  51243. "@smithy/util-body-length-node": "^4.0.0",
  51244. "@smithy/util-defaults-mode-browser": "^4.0.14",
  51245. "@smithy/util-defaults-mode-node": "^4.0.14",
  51246. "@smithy/util-endpoints": "^3.0.4",
  51247. "@smithy/util-middleware": "^4.0.2",
  51248. "@smithy/util-retry": "^4.0.3",
  51249. "@smithy/util-utf8": "^4.0.0",
  51250. tslib: "^2.6.2"
  51251. },
  51252. devDependencies: {
  51253. "@tsconfig/node18": "18.2.4",
  51254. "@types/node": "^18.19.69",
  51255. concurrently: "7.0.0",
  51256. "downlevel-dts": "0.10.1",
  51257. rimraf: "3.0.2",
  51258. typescript: "~5.8.3"
  51259. },
  51260. engines: {
  51261. node: ">=18.0.0"
  51262. },
  51263. typesVersions: {
  51264. "<4.0": {
  51265. "dist-types/*": [
  51266. "dist-types/ts3.4/*"
  51267. ]
  51268. }
  51269. },
  51270. files: [
  51271. "dist-*/**"
  51272. ],
  51273. author: {
  51274. name: "AWS SDK for JavaScript Team",
  51275. url: "https://aws.amazon.com/javascript/"
  51276. },
  51277. license: "Apache-2.0",
  51278. browser: {
  51279. "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
  51280. },
  51281. "react-native": {
  51282. "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
  51283. },
  51284. homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-rds-data",
  51285. repository: {
  51286. type: "git",
  51287. url: "https://github.com/aws/aws-sdk-js-v3.git",
  51288. directory: "clients/client-rds-data"
  51289. }
  51290. };
  51291. }
  51292. });
  51293. // ../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js
  51294. var ENV_KEY, ENV_SECRET, ENV_SESSION, ENV_EXPIRATION, ENV_CREDENTIAL_SCOPE, ENV_ACCOUNT_ID, fromEnv2;
  51295. var init_fromEnv2 = __esm({
  51296. "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js"() {
  51297. "use strict";
  51298. init_client2();
  51299. init_dist_es21();
  51300. ENV_KEY = "AWS_ACCESS_KEY_ID";
  51301. ENV_SECRET = "AWS_SECRET_ACCESS_KEY";
  51302. ENV_SESSION = "AWS_SESSION_TOKEN";
  51303. ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION";
  51304. ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE";
  51305. ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID";
  51306. fromEnv2 = (init2) => async () => {
  51307. init2?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");
  51308. const accessKeyId = process.env[ENV_KEY];
  51309. const secretAccessKey = process.env[ENV_SECRET];
  51310. const sessionToken = process.env[ENV_SESSION];
  51311. const expiry = process.env[ENV_EXPIRATION];
  51312. const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];
  51313. const accountId = process.env[ENV_ACCOUNT_ID];
  51314. if (accessKeyId && secretAccessKey) {
  51315. const credentials2 = {
  51316. accessKeyId,
  51317. secretAccessKey,
  51318. ...sessionToken && { sessionToken },
  51319. ...expiry && { expiration: new Date(expiry) },
  51320. ...credentialScope && { credentialScope },
  51321. ...accountId && { accountId }
  51322. };
  51323. setCredentialFeature(credentials2, "CREDENTIALS_ENV_VARS", "g");
  51324. return credentials2;
  51325. }
  51326. throw new CredentialsProviderError("Unable to find environment variable credentials.", { logger: init2?.logger });
  51327. };
  51328. }
  51329. });
  51330. // ../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/index.js
  51331. var dist_es_exports = {};
  51332. __export(dist_es_exports, {
  51333. ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID,
  51334. ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE,
  51335. ENV_EXPIRATION: () => ENV_EXPIRATION,
  51336. ENV_KEY: () => ENV_KEY,
  51337. ENV_SECRET: () => ENV_SECRET,
  51338. ENV_SESSION: () => ENV_SESSION,
  51339. fromEnv: () => fromEnv2
  51340. });
  51341. var init_dist_es38 = __esm({
  51342. "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-es/index.js"() {
  51343. "use strict";
  51344. init_fromEnv2();
  51345. }
  51346. });
  51347. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js
  51348. import { Buffer as Buffer5 } from "buffer";
  51349. import { request } from "http";
  51350. function httpRequest(options) {
  51351. return new Promise((resolve, reject) => {
  51352. const req = request({
  51353. method: "GET",
  51354. ...options,
  51355. hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1")
  51356. });
  51357. req.on("error", (err2) => {
  51358. reject(Object.assign(new ProviderError("Unable to connect to instance metadata service"), err2));
  51359. req.destroy();
  51360. });
  51361. req.on("timeout", () => {
  51362. reject(new ProviderError("TimeoutError from instance metadata service"));
  51363. req.destroy();
  51364. });
  51365. req.on("response", (res) => {
  51366. const { statusCode = 400 } = res;
  51367. if (statusCode < 200 || 300 <= statusCode) {
  51368. reject(Object.assign(new ProviderError("Error response received from instance metadata service"), { statusCode }));
  51369. req.destroy();
  51370. }
  51371. const chunks = [];
  51372. res.on("data", (chunk) => {
  51373. chunks.push(chunk);
  51374. });
  51375. res.on("end", () => {
  51376. resolve(Buffer5.concat(chunks));
  51377. req.destroy();
  51378. });
  51379. });
  51380. req.end();
  51381. });
  51382. }
  51383. var init_httpRequest2 = __esm({
  51384. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js"() {
  51385. "use strict";
  51386. init_dist_es21();
  51387. }
  51388. });
  51389. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js
  51390. var isImdsCredentials, fromImdsCredentials;
  51391. var init_ImdsCredentials = __esm({
  51392. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js"() {
  51393. "use strict";
  51394. isImdsCredentials = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string";
  51395. fromImdsCredentials = (creds) => ({
  51396. accessKeyId: creds.AccessKeyId,
  51397. secretAccessKey: creds.SecretAccessKey,
  51398. sessionToken: creds.Token,
  51399. expiration: new Date(creds.Expiration),
  51400. ...creds.AccountId && { accountId: creds.AccountId }
  51401. });
  51402. }
  51403. });
  51404. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js
  51405. var DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, providerConfigFromInit;
  51406. var init_RemoteProviderInit = __esm({
  51407. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js"() {
  51408. "use strict";
  51409. DEFAULT_TIMEOUT = 1e3;
  51410. DEFAULT_MAX_RETRIES = 0;
  51411. providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT }) => ({ maxRetries, timeout });
  51412. }
  51413. });
  51414. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js
  51415. var retry;
  51416. var init_retry3 = __esm({
  51417. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js"() {
  51418. "use strict";
  51419. retry = (toRetry, maxRetries) => {
  51420. let promise = toRetry();
  51421. for (let i6 = 0; i6 < maxRetries; i6++) {
  51422. promise = promise.catch(toRetry);
  51423. }
  51424. return promise;
  51425. };
  51426. }
  51427. });
  51428. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js
  51429. import { parse as parse3 } from "url";
  51430. var ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, ENV_CMDS_AUTH_TOKEN, fromContainerMetadata, requestFromEcsImds, CMDS_IP, GREENGRASS_HOSTS, GREENGRASS_PROTOCOLS, getCmdsUri;
  51431. var init_fromContainerMetadata = __esm({
  51432. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js"() {
  51433. "use strict";
  51434. init_dist_es21();
  51435. init_httpRequest2();
  51436. init_ImdsCredentials();
  51437. init_RemoteProviderInit();
  51438. init_retry3();
  51439. ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
  51440. ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
  51441. ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
  51442. fromContainerMetadata = (init2 = {}) => {
  51443. const { timeout, maxRetries } = providerConfigFromInit(init2);
  51444. return () => retry(async () => {
  51445. const requestOptions = await getCmdsUri({ logger: init2.logger });
  51446. const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));
  51447. if (!isImdsCredentials(credsResponse)) {
  51448. throw new CredentialsProviderError("Invalid response received from instance metadata service.", {
  51449. logger: init2.logger
  51450. });
  51451. }
  51452. return fromImdsCredentials(credsResponse);
  51453. }, maxRetries);
  51454. };
  51455. requestFromEcsImds = async (timeout, options) => {
  51456. if (process.env[ENV_CMDS_AUTH_TOKEN]) {
  51457. options.headers = {
  51458. ...options.headers,
  51459. Authorization: process.env[ENV_CMDS_AUTH_TOKEN]
  51460. };
  51461. }
  51462. const buffer = await httpRequest({
  51463. ...options,
  51464. timeout
  51465. });
  51466. return buffer.toString();
  51467. };
  51468. CMDS_IP = "169.254.170.2";
  51469. GREENGRASS_HOSTS = {
  51470. localhost: true,
  51471. "127.0.0.1": true
  51472. };
  51473. GREENGRASS_PROTOCOLS = {
  51474. "http:": true,
  51475. "https:": true
  51476. };
  51477. getCmdsUri = async ({ logger: logger2 }) => {
  51478. if (process.env[ENV_CMDS_RELATIVE_URI]) {
  51479. return {
  51480. hostname: CMDS_IP,
  51481. path: process.env[ENV_CMDS_RELATIVE_URI]
  51482. };
  51483. }
  51484. if (process.env[ENV_CMDS_FULL_URI]) {
  51485. const parsed = parse3(process.env[ENV_CMDS_FULL_URI]);
  51486. if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) {
  51487. throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {
  51488. tryNextLink: false,
  51489. logger: logger2
  51490. });
  51491. }
  51492. if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) {
  51493. throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {
  51494. tryNextLink: false,
  51495. logger: logger2
  51496. });
  51497. }
  51498. return {
  51499. ...parsed,
  51500. port: parsed.port ? parseInt(parsed.port, 10) : void 0
  51501. };
  51502. }
  51503. throw new CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, {
  51504. tryNextLink: false,
  51505. logger: logger2
  51506. });
  51507. };
  51508. }
  51509. });
  51510. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js
  51511. var InstanceMetadataV1FallbackError;
  51512. var init_InstanceMetadataV1FallbackError = __esm({
  51513. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js"() {
  51514. "use strict";
  51515. init_dist_es21();
  51516. InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends CredentialsProviderError {
  51517. constructor(message, tryNextLink = true) {
  51518. super(message, tryNextLink);
  51519. this.tryNextLink = tryNextLink;
  51520. this.name = "InstanceMetadataV1FallbackError";
  51521. Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype);
  51522. }
  51523. };
  51524. }
  51525. });
  51526. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js
  51527. var Endpoint;
  51528. var init_Endpoint = __esm({
  51529. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js"() {
  51530. "use strict";
  51531. (function(Endpoint2) {
  51532. Endpoint2["IPv4"] = "http://169.254.169.254";
  51533. Endpoint2["IPv6"] = "http://[fd00:ec2::254]";
  51534. })(Endpoint || (Endpoint = {}));
  51535. }
  51536. });
  51537. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js
  51538. var ENV_ENDPOINT_NAME, CONFIG_ENDPOINT_NAME, ENDPOINT_CONFIG_OPTIONS;
  51539. var init_EndpointConfigOptions = __esm({
  51540. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js"() {
  51541. "use strict";
  51542. ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT";
  51543. CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint";
  51544. ENDPOINT_CONFIG_OPTIONS = {
  51545. environmentVariableSelector: (env4) => env4[ENV_ENDPOINT_NAME],
  51546. configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],
  51547. default: void 0
  51548. };
  51549. }
  51550. });
  51551. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js
  51552. var EndpointMode;
  51553. var init_EndpointMode = __esm({
  51554. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js"() {
  51555. "use strict";
  51556. (function(EndpointMode2) {
  51557. EndpointMode2["IPv4"] = "IPv4";
  51558. EndpointMode2["IPv6"] = "IPv6";
  51559. })(EndpointMode || (EndpointMode = {}));
  51560. }
  51561. });
  51562. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js
  51563. var ENV_ENDPOINT_MODE_NAME, CONFIG_ENDPOINT_MODE_NAME, ENDPOINT_MODE_CONFIG_OPTIONS;
  51564. var init_EndpointModeConfigOptions = __esm({
  51565. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js"() {
  51566. "use strict";
  51567. init_EndpointMode();
  51568. ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE";
  51569. CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode";
  51570. ENDPOINT_MODE_CONFIG_OPTIONS = {
  51571. environmentVariableSelector: (env4) => env4[ENV_ENDPOINT_MODE_NAME],
  51572. configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],
  51573. default: EndpointMode.IPv4
  51574. };
  51575. }
  51576. });
  51577. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js
  51578. var getInstanceMetadataEndpoint, getFromEndpointConfig, getFromEndpointModeConfig;
  51579. var init_getInstanceMetadataEndpoint = __esm({
  51580. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js"() {
  51581. "use strict";
  51582. init_dist_es31();
  51583. init_dist_es33();
  51584. init_Endpoint();
  51585. init_EndpointConfigOptions();
  51586. init_EndpointMode();
  51587. init_EndpointModeConfigOptions();
  51588. getInstanceMetadataEndpoint = async () => parseUrl(await getFromEndpointConfig() || await getFromEndpointModeConfig());
  51589. getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)();
  51590. getFromEndpointModeConfig = async () => {
  51591. const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();
  51592. switch (endpointMode) {
  51593. case EndpointMode.IPv4:
  51594. return Endpoint.IPv4;
  51595. case EndpointMode.IPv6:
  51596. return Endpoint.IPv6;
  51597. default:
  51598. throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`);
  51599. }
  51600. };
  51601. }
  51602. });
  51603. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js
  51604. var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS, STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS, STATIC_STABILITY_DOC_URL, getExtendedInstanceMetadataCredentials;
  51605. var init_getExtendedInstanceMetadataCredentials = __esm({
  51606. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js"() {
  51607. "use strict";
  51608. STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;
  51609. STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;
  51610. STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html";
  51611. getExtendedInstanceMetadataCredentials = (credentials2, logger2) => {
  51612. const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);
  51613. const newExpiration = new Date(Date.now() + refreshInterval * 1e3);
  51614. logger2.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}.
  51615. For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
  51616. const originalExpiration = credentials2.originalExpiration ?? credentials2.expiration;
  51617. return {
  51618. ...credentials2,
  51619. ...originalExpiration ? { originalExpiration } : {},
  51620. expiration: newExpiration
  51621. };
  51622. };
  51623. }
  51624. });
  51625. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js
  51626. var staticStabilityProvider;
  51627. var init_staticStabilityProvider = __esm({
  51628. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js"() {
  51629. "use strict";
  51630. init_getExtendedInstanceMetadataCredentials();
  51631. staticStabilityProvider = (provider, options = {}) => {
  51632. const logger2 = options?.logger || console;
  51633. let pastCredentials;
  51634. return async () => {
  51635. let credentials2;
  51636. try {
  51637. credentials2 = await provider();
  51638. if (credentials2.expiration && credentials2.expiration.getTime() < Date.now()) {
  51639. credentials2 = getExtendedInstanceMetadataCredentials(credentials2, logger2);
  51640. }
  51641. } catch (e6) {
  51642. if (pastCredentials) {
  51643. logger2.warn("Credential renew failed: ", e6);
  51644. credentials2 = getExtendedInstanceMetadataCredentials(pastCredentials, logger2);
  51645. } else {
  51646. throw e6;
  51647. }
  51648. }
  51649. pastCredentials = credentials2;
  51650. return credentials2;
  51651. };
  51652. };
  51653. }
  51654. });
  51655. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js
  51656. var IMDS_PATH, IMDS_TOKEN_PATH, AWS_EC2_METADATA_V1_DISABLED, PROFILE_AWS_EC2_METADATA_V1_DISABLED, X_AWS_EC2_METADATA_TOKEN, fromInstanceMetadata, getInstanceMetadataProvider, getMetadataToken, getProfile, getCredentialsFromProfile;
  51657. var init_fromInstanceMetadata = __esm({
  51658. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js"() {
  51659. "use strict";
  51660. init_dist_es31();
  51661. init_dist_es21();
  51662. init_InstanceMetadataV1FallbackError();
  51663. init_httpRequest2();
  51664. init_ImdsCredentials();
  51665. init_RemoteProviderInit();
  51666. init_retry3();
  51667. init_getInstanceMetadataEndpoint();
  51668. init_staticStabilityProvider();
  51669. IMDS_PATH = "/latest/meta-data/iam/security-credentials/";
  51670. IMDS_TOKEN_PATH = "/latest/api/token";
  51671. AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED";
  51672. PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled";
  51673. X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token";
  51674. fromInstanceMetadata = (init2 = {}) => staticStabilityProvider(getInstanceMetadataProvider(init2), { logger: init2.logger });
  51675. getInstanceMetadataProvider = (init2 = {}) => {
  51676. let disableFetchToken = false;
  51677. const { logger: logger2, profile } = init2;
  51678. const { timeout, maxRetries } = providerConfigFromInit(init2);
  51679. const getCredentials2 = async (maxRetries2, options) => {
  51680. const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;
  51681. if (isImdsV1Fallback) {
  51682. let fallbackBlockedFromProfile = false;
  51683. let fallbackBlockedFromProcessEnv = false;
  51684. const configValue = await loadConfig({
  51685. environmentVariableSelector: (env4) => {
  51686. const envValue = env4[AWS_EC2_METADATA_V1_DISABLED];
  51687. fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false";
  51688. if (envValue === void 0) {
  51689. throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init2.logger });
  51690. }
  51691. return fallbackBlockedFromProcessEnv;
  51692. },
  51693. configFileSelector: (profile2) => {
  51694. const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED];
  51695. fallbackBlockedFromProfile = !!profileValue && profileValue !== "false";
  51696. return fallbackBlockedFromProfile;
  51697. },
  51698. default: false
  51699. }, {
  51700. profile
  51701. })();
  51702. if (init2.ec2MetadataV1Disabled || configValue) {
  51703. const causes = [];
  51704. if (init2.ec2MetadataV1Disabled)
  51705. causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");
  51706. if (fallbackBlockedFromProfile)
  51707. causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);
  51708. if (fallbackBlockedFromProcessEnv)
  51709. causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);
  51710. throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`);
  51711. }
  51712. }
  51713. const imdsProfile = (await retry(async () => {
  51714. let profile2;
  51715. try {
  51716. profile2 = await getProfile(options);
  51717. } catch (err2) {
  51718. if (err2.statusCode === 401) {
  51719. disableFetchToken = false;
  51720. }
  51721. throw err2;
  51722. }
  51723. return profile2;
  51724. }, maxRetries2)).trim();
  51725. return retry(async () => {
  51726. let creds;
  51727. try {
  51728. creds = await getCredentialsFromProfile(imdsProfile, options, init2);
  51729. } catch (err2) {
  51730. if (err2.statusCode === 401) {
  51731. disableFetchToken = false;
  51732. }
  51733. throw err2;
  51734. }
  51735. return creds;
  51736. }, maxRetries2);
  51737. };
  51738. return async () => {
  51739. const endpoint = await getInstanceMetadataEndpoint();
  51740. if (disableFetchToken) {
  51741. logger2?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
  51742. return getCredentials2(maxRetries, { ...endpoint, timeout });
  51743. } else {
  51744. let token;
  51745. try {
  51746. token = (await getMetadataToken({ ...endpoint, timeout })).toString();
  51747. } catch (error2) {
  51748. if (error2?.statusCode === 400) {
  51749. throw Object.assign(error2, {
  51750. message: "EC2 Metadata token request returned error"
  51751. });
  51752. } else if (error2.message === "TimeoutError" || [403, 404, 405].includes(error2.statusCode)) {
  51753. disableFetchToken = true;
  51754. }
  51755. logger2?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
  51756. return getCredentials2(maxRetries, { ...endpoint, timeout });
  51757. }
  51758. return getCredentials2(maxRetries, {
  51759. ...endpoint,
  51760. headers: {
  51761. [X_AWS_EC2_METADATA_TOKEN]: token
  51762. },
  51763. timeout
  51764. });
  51765. }
  51766. };
  51767. };
  51768. getMetadataToken = async (options) => httpRequest({
  51769. ...options,
  51770. path: IMDS_TOKEN_PATH,
  51771. method: "PUT",
  51772. headers: {
  51773. "x-aws-ec2-metadata-token-ttl-seconds": "21600"
  51774. }
  51775. });
  51776. getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString();
  51777. getCredentialsFromProfile = async (profile, options, init2) => {
  51778. const credentialsResponse = JSON.parse((await httpRequest({
  51779. ...options,
  51780. path: IMDS_PATH + profile
  51781. })).toString());
  51782. if (!isImdsCredentials(credentialsResponse)) {
  51783. throw new CredentialsProviderError("Invalid response received from instance metadata service.", {
  51784. logger: init2.logger
  51785. });
  51786. }
  51787. return fromImdsCredentials(credentialsResponse);
  51788. };
  51789. }
  51790. });
  51791. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/types.js
  51792. var init_types9 = __esm({
  51793. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/types.js"() {
  51794. "use strict";
  51795. }
  51796. });
  51797. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/index.js
  51798. var dist_es_exports2 = {};
  51799. __export(dist_es_exports2, {
  51800. DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
  51801. DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
  51802. ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN,
  51803. ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI,
  51804. ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI,
  51805. Endpoint: () => Endpoint,
  51806. fromContainerMetadata: () => fromContainerMetadata,
  51807. fromInstanceMetadata: () => fromInstanceMetadata,
  51808. getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint,
  51809. httpRequest: () => httpRequest,
  51810. providerConfigFromInit: () => providerConfigFromInit
  51811. });
  51812. var init_dist_es39 = __esm({
  51813. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-es/index.js"() {
  51814. "use strict";
  51815. init_fromContainerMetadata();
  51816. init_fromInstanceMetadata();
  51817. init_RemoteProviderInit();
  51818. init_types9();
  51819. init_httpRequest2();
  51820. init_getInstanceMetadataEndpoint();
  51821. init_Endpoint();
  51822. }
  51823. });
  51824. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js
  51825. var ECS_CONTAINER_HOST, EKS_CONTAINER_HOST_IPv4, EKS_CONTAINER_HOST_IPv6, checkUrl;
  51826. var init_checkUrl = __esm({
  51827. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js"() {
  51828. "use strict";
  51829. init_dist_es21();
  51830. ECS_CONTAINER_HOST = "169.254.170.2";
  51831. EKS_CONTAINER_HOST_IPv4 = "169.254.170.23";
  51832. EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]";
  51833. checkUrl = (url, logger2) => {
  51834. if (url.protocol === "https:") {
  51835. return;
  51836. }
  51837. if (url.hostname === ECS_CONTAINER_HOST || url.hostname === EKS_CONTAINER_HOST_IPv4 || url.hostname === EKS_CONTAINER_HOST_IPv6) {
  51838. return;
  51839. }
  51840. if (url.hostname.includes("[")) {
  51841. if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") {
  51842. return;
  51843. }
  51844. } else {
  51845. if (url.hostname === "localhost") {
  51846. return;
  51847. }
  51848. const ipComponents = url.hostname.split(".");
  51849. const inRange = (component) => {
  51850. const num = parseInt(component, 10);
  51851. return 0 <= num && num <= 255;
  51852. };
  51853. if (ipComponents[0] === "127" && inRange(ipComponents[1]) && inRange(ipComponents[2]) && inRange(ipComponents[3]) && ipComponents.length === 4) {
  51854. return;
  51855. }
  51856. }
  51857. throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:
  51858. - loopback CIDR 127.0.0.0/8 or [::1/128]
  51859. - ECS container host 169.254.170.2
  51860. - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger2 });
  51861. };
  51862. }
  51863. });
  51864. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js
  51865. function createGetRequest(url) {
  51866. return new HttpRequest({
  51867. protocol: url.protocol,
  51868. hostname: url.hostname,
  51869. port: Number(url.port),
  51870. path: url.pathname,
  51871. query: Array.from(url.searchParams.entries()).reduce((acc, [k5, v6]) => {
  51872. acc[k5] = v6;
  51873. return acc;
  51874. }, {}),
  51875. fragment: url.hash
  51876. });
  51877. }
  51878. async function getCredentials(response, logger2) {
  51879. const stream = sdkStreamMixin2(response.body);
  51880. const str = await stream.transformToString();
  51881. if (response.statusCode === 200) {
  51882. const parsed = JSON.parse(str);
  51883. if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") {
  51884. throw new CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger2 });
  51885. }
  51886. return {
  51887. accessKeyId: parsed.AccessKeyId,
  51888. secretAccessKey: parsed.SecretAccessKey,
  51889. sessionToken: parsed.Token,
  51890. expiration: parseRfc3339DateTime(parsed.Expiration)
  51891. };
  51892. }
  51893. if (response.statusCode >= 400 && response.statusCode < 500) {
  51894. let parsedBody = {};
  51895. try {
  51896. parsedBody = JSON.parse(str);
  51897. } catch (e6) {
  51898. }
  51899. throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger2 }), {
  51900. Code: parsedBody.Code,
  51901. Message: parsedBody.Message
  51902. });
  51903. }
  51904. throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger2 });
  51905. }
  51906. var init_requestHelpers = __esm({
  51907. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js"() {
  51908. "use strict";
  51909. init_dist_es21();
  51910. init_dist_es2();
  51911. init_dist_es24();
  51912. init_dist_es17();
  51913. }
  51914. });
  51915. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js
  51916. var retryWrapper;
  51917. var init_retry_wrapper = __esm({
  51918. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js"() {
  51919. "use strict";
  51920. retryWrapper = (toRetry, maxRetries, delayMs) => {
  51921. return async () => {
  51922. for (let i6 = 0; i6 < maxRetries; ++i6) {
  51923. try {
  51924. return await toRetry();
  51925. } catch (e6) {
  51926. await new Promise((resolve) => setTimeout(resolve, delayMs));
  51927. }
  51928. }
  51929. return await toRetry();
  51930. };
  51931. };
  51932. }
  51933. });
  51934. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js
  51935. import fs3 from "fs/promises";
  51936. var AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, DEFAULT_LINK_LOCAL_HOST, AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE, AWS_CONTAINER_AUTHORIZATION_TOKEN, fromHttp;
  51937. var init_fromHttp = __esm({
  51938. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js"() {
  51939. "use strict";
  51940. init_client2();
  51941. init_dist_es14();
  51942. init_dist_es21();
  51943. init_checkUrl();
  51944. init_requestHelpers();
  51945. init_retry_wrapper();
  51946. AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
  51947. DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2";
  51948. AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
  51949. AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE";
  51950. AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
  51951. fromHttp = (options = {}) => {
  51952. options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");
  51953. let host;
  51954. const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];
  51955. const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];
  51956. const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];
  51957. const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];
  51958. const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger ? console.warn : options.logger.warn;
  51959. if (relative && full) {
  51960. warn("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.");
  51961. warn("awsContainerCredentialsFullUri will take precedence.");
  51962. }
  51963. if (token && tokenFile) {
  51964. warn("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.");
  51965. warn("awsContainerAuthorizationToken will take precedence.");
  51966. }
  51967. if (full) {
  51968. host = full;
  51969. } else if (relative) {
  51970. host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;
  51971. } else {
  51972. throw new CredentialsProviderError(`No HTTP credential provider host provided.
  51973. Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });
  51974. }
  51975. const url = new URL(host);
  51976. checkUrl(url, options.logger);
  51977. const requestHandler = new NodeHttpHandler({
  51978. requestTimeout: options.timeout ?? 1e3,
  51979. connectionTimeout: options.timeout ?? 1e3
  51980. });
  51981. return retryWrapper(async () => {
  51982. const request2 = createGetRequest(url);
  51983. if (token) {
  51984. request2.headers.Authorization = token;
  51985. } else if (tokenFile) {
  51986. request2.headers.Authorization = (await fs3.readFile(tokenFile)).toString();
  51987. }
  51988. try {
  51989. const result = await requestHandler.handle(request2);
  51990. return getCredentials(result.response).then((creds) => setCredentialFeature(creds, "CREDENTIALS_HTTP", "z"));
  51991. } catch (e6) {
  51992. throw new CredentialsProviderError(String(e6), { logger: options.logger });
  51993. }
  51994. }, options.maxRetries ?? 3, options.timeout ?? 1e3);
  51995. };
  51996. }
  51997. });
  51998. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/index.js
  51999. var dist_es_exports3 = {};
  52000. __export(dist_es_exports3, {
  52001. fromHttp: () => fromHttp
  52002. });
  52003. var init_dist_es40 = __esm({
  52004. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-es/index.js"() {
  52005. "use strict";
  52006. init_fromHttp();
  52007. }
  52008. });
  52009. // ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js
  52010. var ENV_IMDS_DISABLED, remoteProvider;
  52011. var init_remoteProvider = __esm({
  52012. "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js"() {
  52013. "use strict";
  52014. init_dist_es21();
  52015. ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
  52016. remoteProvider = async (init2) => {
  52017. const { ENV_CMDS_FULL_URI: ENV_CMDS_FULL_URI2, ENV_CMDS_RELATIVE_URI: ENV_CMDS_RELATIVE_URI2, fromContainerMetadata: fromContainerMetadata2, fromInstanceMetadata: fromInstanceMetadata2 } = await Promise.resolve().then(() => (init_dist_es39(), dist_es_exports2));
  52018. if (process.env[ENV_CMDS_RELATIVE_URI2] || process.env[ENV_CMDS_FULL_URI2]) {
  52019. init2.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");
  52020. const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es40(), dist_es_exports3));
  52021. return chain(fromHttp2(init2), fromContainerMetadata2(init2));
  52022. }
  52023. if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") {
  52024. return async () => {
  52025. throw new CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init2.logger });
  52026. };
  52027. }
  52028. init2.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata");
  52029. return fromInstanceMetadata2(init2);
  52030. };
  52031. }
  52032. });
  52033. // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js
  52034. var isSsoProfile;
  52035. var init_isSsoProfile = __esm({
  52036. "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js"() {
  52037. "use strict";
  52038. isSsoProfile = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string");
  52039. }
  52040. });
  52041. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromEnvSigningName.js
  52042. var init_fromEnvSigningName = __esm({
  52043. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromEnvSigningName.js"() {
  52044. "use strict";
  52045. init_dist_es21();
  52046. }
  52047. });
  52048. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/constants.js
  52049. var EXPIRE_WINDOW_MS, REFRESH_MESSAGE;
  52050. var init_constants8 = __esm({
  52051. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/constants.js"() {
  52052. "use strict";
  52053. EXPIRE_WINDOW_MS = 5 * 60 * 1e3;
  52054. REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
  52055. }
  52056. });
  52057. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js
  52058. function createAwsAuthSigv4HttpAuthOption2(authParameters) {
  52059. return {
  52060. schemeId: "aws.auth#sigv4",
  52061. signingProperties: {
  52062. name: "sso-oauth",
  52063. region: authParameters.region
  52064. },
  52065. propertiesExtractor: (config, context) => ({
  52066. signingProperties: {
  52067. config,
  52068. context
  52069. }
  52070. })
  52071. };
  52072. }
  52073. function createSmithyApiNoAuthHttpAuthOption(authParameters) {
  52074. return {
  52075. schemeId: "smithy.api#noAuth"
  52076. };
  52077. }
  52078. var defaultSSOOIDCHttpAuthSchemeParametersProvider, defaultSSOOIDCHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig2;
  52079. var init_httpAuthSchemeProvider2 = __esm({
  52080. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js"() {
  52081. "use strict";
  52082. init_dist_es25();
  52083. init_dist_es6();
  52084. defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {
  52085. return {
  52086. operation: getSmithyContext(context).operation,
  52087. region: await normalizeProvider(config.region)() || (() => {
  52088. throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
  52089. })()
  52090. };
  52091. };
  52092. defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {
  52093. const options = [];
  52094. switch (authParameters.operation) {
  52095. case "CreateToken": {
  52096. options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
  52097. break;
  52098. }
  52099. default: {
  52100. options.push(createAwsAuthSigv4HttpAuthOption2(authParameters));
  52101. }
  52102. }
  52103. return options;
  52104. };
  52105. resolveHttpAuthSchemeConfig2 = (config) => {
  52106. const config_0 = resolveAwsSdkSigV4Config(config);
  52107. return Object.assign(config_0, {
  52108. authSchemePreference: normalizeProvider(config.authSchemePreference ?? [])
  52109. });
  52110. };
  52111. }
  52112. });
  52113. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js
  52114. var resolveClientEndpointParameters2, commonParams2;
  52115. var init_EndpointParameters2 = __esm({
  52116. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js"() {
  52117. "use strict";
  52118. resolveClientEndpointParameters2 = (options) => {
  52119. return Object.assign(options, {
  52120. useDualstackEndpoint: options.useDualstackEndpoint ?? false,
  52121. useFipsEndpoint: options.useFipsEndpoint ?? false,
  52122. defaultSigningName: "sso-oauth"
  52123. });
  52124. };
  52125. commonParams2 = {
  52126. UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
  52127. Endpoint: { type: "builtInParams", name: "endpoint" },
  52128. Region: { type: "builtInParams", name: "region" },
  52129. UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  52130. };
  52131. }
  52132. });
  52133. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/package.json
  52134. var package_default2;
  52135. var init_package2 = __esm({
  52136. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/package.json"() {
  52137. package_default2 = {
  52138. name: "@aws-sdk/nested-clients",
  52139. version: "3.817.0",
  52140. description: "Nested clients for AWS SDK packages.",
  52141. main: "./dist-cjs/index.js",
  52142. module: "./dist-es/index.js",
  52143. types: "./dist-types/index.d.ts",
  52144. scripts: {
  52145. build: "yarn lint && concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
  52146. "build:cjs": "node ../../scripts/compilation/inline nested-clients",
  52147. "build:es": "tsc -p tsconfig.es.json",
  52148. "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
  52149. "build:types": "tsc -p tsconfig.types.json",
  52150. "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
  52151. clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
  52152. lint: "node ../../scripts/validation/submodules-linter.js --pkg nested-clients",
  52153. test: "yarn g:vitest run",
  52154. "test:watch": "yarn g:vitest watch"
  52155. },
  52156. engines: {
  52157. node: ">=18.0.0"
  52158. },
  52159. author: {
  52160. name: "AWS SDK for JavaScript Team",
  52161. url: "https://aws.amazon.com/javascript/"
  52162. },
  52163. license: "Apache-2.0",
  52164. dependencies: {
  52165. "@aws-crypto/sha256-browser": "5.2.0",
  52166. "@aws-crypto/sha256-js": "5.2.0",
  52167. "@aws-sdk/core": "3.816.0",
  52168. "@aws-sdk/middleware-host-header": "3.804.0",
  52169. "@aws-sdk/middleware-logger": "3.804.0",
  52170. "@aws-sdk/middleware-recursion-detection": "3.804.0",
  52171. "@aws-sdk/middleware-user-agent": "3.816.0",
  52172. "@aws-sdk/region-config-resolver": "3.808.0",
  52173. "@aws-sdk/types": "3.804.0",
  52174. "@aws-sdk/util-endpoints": "3.808.0",
  52175. "@aws-sdk/util-user-agent-browser": "3.804.0",
  52176. "@aws-sdk/util-user-agent-node": "3.816.0",
  52177. "@smithy/config-resolver": "^4.1.2",
  52178. "@smithy/core": "^3.3.3",
  52179. "@smithy/fetch-http-handler": "^5.0.2",
  52180. "@smithy/hash-node": "^4.0.2",
  52181. "@smithy/invalid-dependency": "^4.0.2",
  52182. "@smithy/middleware-content-length": "^4.0.2",
  52183. "@smithy/middleware-endpoint": "^4.1.6",
  52184. "@smithy/middleware-retry": "^4.1.7",
  52185. "@smithy/middleware-serde": "^4.0.5",
  52186. "@smithy/middleware-stack": "^4.0.2",
  52187. "@smithy/node-config-provider": "^4.1.1",
  52188. "@smithy/node-http-handler": "^4.0.4",
  52189. "@smithy/protocol-http": "^5.1.0",
  52190. "@smithy/smithy-client": "^4.2.6",
  52191. "@smithy/types": "^4.2.0",
  52192. "@smithy/url-parser": "^4.0.2",
  52193. "@smithy/util-base64": "^4.0.0",
  52194. "@smithy/util-body-length-browser": "^4.0.0",
  52195. "@smithy/util-body-length-node": "^4.0.0",
  52196. "@smithy/util-defaults-mode-browser": "^4.0.14",
  52197. "@smithy/util-defaults-mode-node": "^4.0.14",
  52198. "@smithy/util-endpoints": "^3.0.4",
  52199. "@smithy/util-middleware": "^4.0.2",
  52200. "@smithy/util-retry": "^4.0.3",
  52201. "@smithy/util-utf8": "^4.0.0",
  52202. tslib: "^2.6.2"
  52203. },
  52204. devDependencies: {
  52205. concurrently: "7.0.0",
  52206. "downlevel-dts": "0.10.1",
  52207. rimraf: "3.0.2",
  52208. typescript: "~5.8.3"
  52209. },
  52210. typesVersions: {
  52211. "<4.0": {
  52212. "dist-types/*": [
  52213. "dist-types/ts3.4/*"
  52214. ]
  52215. }
  52216. },
  52217. files: [
  52218. "./sso-oidc.d.ts",
  52219. "./sso-oidc.js",
  52220. "./sts.d.ts",
  52221. "./sts.js",
  52222. "dist-*/**"
  52223. ],
  52224. browser: {
  52225. "./dist-es/submodules/sso-oidc/runtimeConfig": "./dist-es/submodules/sso-oidc/runtimeConfig.browser",
  52226. "./dist-es/submodules/sts/runtimeConfig": "./dist-es/submodules/sts/runtimeConfig.browser"
  52227. },
  52228. "react-native": {},
  52229. homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients",
  52230. repository: {
  52231. type: "git",
  52232. url: "https://github.com/aws/aws-sdk-js-v3.git",
  52233. directory: "packages/nested-clients"
  52234. },
  52235. exports: {
  52236. "./sso-oidc": {
  52237. types: "./dist-types/submodules/sso-oidc/index.d.ts",
  52238. module: "./dist-es/submodules/sso-oidc/index.js",
  52239. node: "./dist-cjs/submodules/sso-oidc/index.js",
  52240. import: "./dist-es/submodules/sso-oidc/index.js",
  52241. require: "./dist-cjs/submodules/sso-oidc/index.js"
  52242. },
  52243. "./sts": {
  52244. types: "./dist-types/submodules/sts/index.d.ts",
  52245. module: "./dist-es/submodules/sts/index.js",
  52246. node: "./dist-cjs/submodules/sts/index.js",
  52247. import: "./dist-es/submodules/sts/index.js",
  52248. require: "./dist-cjs/submodules/sts/index.js"
  52249. }
  52250. }
  52251. };
  52252. }
  52253. });
  52254. // ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/crt-availability.js
  52255. var crtAvailability;
  52256. var init_crt_availability = __esm({
  52257. "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/crt-availability.js"() {
  52258. "use strict";
  52259. crtAvailability = {
  52260. isCrtAvailable: false
  52261. };
  52262. }
  52263. });
  52264. // ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/is-crt-available.js
  52265. var isCrtAvailable;
  52266. var init_is_crt_available = __esm({
  52267. "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/is-crt-available.js"() {
  52268. "use strict";
  52269. init_crt_availability();
  52270. isCrtAvailable = () => {
  52271. if (crtAvailability.isCrtAvailable) {
  52272. return ["md/crt-avail"];
  52273. }
  52274. return null;
  52275. };
  52276. }
  52277. });
  52278. // ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/defaultUserAgent.js
  52279. import { platform, release } from "os";
  52280. import { env as env3, versions } from "process";
  52281. var createDefaultUserAgentProvider;
  52282. var init_defaultUserAgent = __esm({
  52283. "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/defaultUserAgent.js"() {
  52284. "use strict";
  52285. init_is_crt_available();
  52286. init_crt_availability();
  52287. createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => {
  52288. return async (config) => {
  52289. const sections = [
  52290. ["aws-sdk-js", clientVersion],
  52291. ["ua", "2.1"],
  52292. [`os/${platform()}`, release()],
  52293. ["lang/js"],
  52294. ["md/nodejs", `${versions.node}`]
  52295. ];
  52296. const crtAvailable = isCrtAvailable();
  52297. if (crtAvailable) {
  52298. sections.push(crtAvailable);
  52299. }
  52300. if (serviceId) {
  52301. sections.push([`api/${serviceId}`, clientVersion]);
  52302. }
  52303. if (env3.AWS_EXECUTION_ENV) {
  52304. sections.push([`exec-env/${env3.AWS_EXECUTION_ENV}`]);
  52305. }
  52306. const appId = await config?.userAgentAppId?.();
  52307. const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections];
  52308. return resolvedUserAgent;
  52309. };
  52310. };
  52311. }
  52312. });
  52313. // ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/nodeAppIdConfigOptions.js
  52314. var UA_APP_ID_ENV_NAME, UA_APP_ID_INI_NAME, UA_APP_ID_INI_NAME_DEPRECATED, NODE_APP_ID_CONFIG_OPTIONS;
  52315. var init_nodeAppIdConfigOptions = __esm({
  52316. "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/nodeAppIdConfigOptions.js"() {
  52317. "use strict";
  52318. init_dist_es26();
  52319. UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID";
  52320. UA_APP_ID_INI_NAME = "sdk_ua_app_id";
  52321. UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id";
  52322. NODE_APP_ID_CONFIG_OPTIONS = {
  52323. environmentVariableSelector: (env4) => env4[UA_APP_ID_ENV_NAME],
  52324. configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED],
  52325. default: DEFAULT_UA_APP_ID
  52326. };
  52327. }
  52328. });
  52329. // ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/index.js
  52330. var init_dist_es41 = __esm({
  52331. "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/index.js"() {
  52332. "use strict";
  52333. init_defaultUserAgent();
  52334. init_nodeAppIdConfigOptions();
  52335. }
  52336. });
  52337. // ../node_modules/.pnpm/@smithy+hash-node@4.0.4/node_modules/@smithy/hash-node/dist-es/index.js
  52338. import { Buffer as Buffer6 } from "buffer";
  52339. import { createHash as createHash2, createHmac } from "crypto";
  52340. function castSourceData(toCast, encoding) {
  52341. if (Buffer6.isBuffer(toCast)) {
  52342. return toCast;
  52343. }
  52344. if (typeof toCast === "string") {
  52345. return fromString(toCast, encoding);
  52346. }
  52347. if (ArrayBuffer.isView(toCast)) {
  52348. return fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength);
  52349. }
  52350. return fromArrayBuffer(toCast);
  52351. }
  52352. var Hash;
  52353. var init_dist_es42 = __esm({
  52354. "../node_modules/.pnpm/@smithy+hash-node@4.0.4/node_modules/@smithy/hash-node/dist-es/index.js"() {
  52355. "use strict";
  52356. init_dist_es9();
  52357. init_dist_es10();
  52358. Hash = class {
  52359. constructor(algorithmIdentifier, secret) {
  52360. this.algorithmIdentifier = algorithmIdentifier;
  52361. this.secret = secret;
  52362. this.reset();
  52363. }
  52364. update(toHash, encoding) {
  52365. this.hash.update(toUint8Array(castSourceData(toHash, encoding)));
  52366. }
  52367. digest() {
  52368. return Promise.resolve(this.hash.digest());
  52369. }
  52370. reset() {
  52371. this.hash = this.secret ? createHmac(this.algorithmIdentifier, castSourceData(this.secret)) : createHash2(this.algorithmIdentifier);
  52372. }
  52373. };
  52374. }
  52375. });
  52376. // ../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js
  52377. import { fstatSync, lstatSync } from "fs";
  52378. var calculateBodyLength;
  52379. var init_calculateBodyLength = __esm({
  52380. "../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js"() {
  52381. "use strict";
  52382. calculateBodyLength = (body) => {
  52383. if (!body) {
  52384. return 0;
  52385. }
  52386. if (typeof body === "string") {
  52387. return Buffer.byteLength(body);
  52388. } else if (typeof body.byteLength === "number") {
  52389. return body.byteLength;
  52390. } else if (typeof body.size === "number") {
  52391. return body.size;
  52392. } else if (typeof body.start === "number" && typeof body.end === "number") {
  52393. return body.end + 1 - body.start;
  52394. } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) {
  52395. return lstatSync(body.path).size;
  52396. } else if (typeof body.fd === "number") {
  52397. return fstatSync(body.fd).size;
  52398. }
  52399. throw new Error(`Body Length computation failed for ${body}`);
  52400. };
  52401. }
  52402. });
  52403. // ../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-es/index.js
  52404. var init_dist_es43 = __esm({
  52405. "../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-es/index.js"() {
  52406. "use strict";
  52407. init_calculateBodyLength();
  52408. }
  52409. });
  52410. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js
  52411. var u, v, w, x2, a, b, c, d, e2, f3, g, h2, i2, j, k, l, m2, n, o, p, q, r2, s2, t2, _data, ruleSet;
  52412. var init_ruleset = __esm({
  52413. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js"() {
  52414. "use strict";
  52415. u = "required";
  52416. v = "fn";
  52417. w = "argv";
  52418. x2 = "ref";
  52419. a = true;
  52420. b = "isSet";
  52421. c = "booleanEquals";
  52422. d = "error";
  52423. e2 = "endpoint";
  52424. f3 = "tree";
  52425. g = "PartitionResult";
  52426. h2 = "getAttr";
  52427. i2 = { [u]: false, "type": "String" };
  52428. j = { [u]: true, "default": false, "type": "Boolean" };
  52429. k = { [x2]: "Endpoint" };
  52430. l = { [v]: c, [w]: [{ [x2]: "UseFIPS" }, true] };
  52431. m2 = { [v]: c, [w]: [{ [x2]: "UseDualStack" }, true] };
  52432. n = {};
  52433. o = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
  52434. p = { [x2]: g };
  52435. q = { [v]: c, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
  52436. r2 = [l];
  52437. s2 = [m2];
  52438. t2 = [{ [x2]: "Region" }];
  52439. _data = { version: "1.0", parameters: { Region: i2, UseDualStack: j, UseFIPS: j, Endpoint: i2 }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e2 }], type: f3 }, { conditions: [{ [v]: b, [w]: t2 }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t2, assign: g }], rules: [{ conditions: [l, m2], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f3 }, { conditions: r2, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h2, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e2 }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f3 }, { conditions: s2, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f3 }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }], type: f3 }, { error: "Invalid Configuration: Missing Region", type: d }] };
  52440. ruleSet = _data;
  52441. }
  52442. });
  52443. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js
  52444. var cache, defaultEndpointResolver;
  52445. var init_endpointResolver = __esm({
  52446. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js"() {
  52447. "use strict";
  52448. init_dist_es20();
  52449. init_dist_es19();
  52450. init_ruleset();
  52451. cache = new EndpointCache({
  52452. size: 50,
  52453. params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
  52454. });
  52455. defaultEndpointResolver = (endpointParams, context = {}) => {
  52456. return cache.get(endpointParams, () => resolveEndpoint(ruleSet, {
  52457. endpointParams,
  52458. logger: context.logger
  52459. }));
  52460. };
  52461. customEndpointFunctions.aws = awsEndpointFunctions;
  52462. }
  52463. });
  52464. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js
  52465. var getRuntimeConfig;
  52466. var init_runtimeConfig_shared = __esm({
  52467. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js"() {
  52468. "use strict";
  52469. init_dist_es25();
  52470. init_dist_es18();
  52471. init_dist_es24();
  52472. init_dist_es33();
  52473. init_dist_es11();
  52474. init_dist_es10();
  52475. init_httpAuthSchemeProvider2();
  52476. init_endpointResolver();
  52477. getRuntimeConfig = (config) => {
  52478. return {
  52479. apiVersion: "2019-06-10",
  52480. base64Decoder: config?.base64Decoder ?? fromBase64,
  52481. base64Encoder: config?.base64Encoder ?? toBase64,
  52482. disableHostPrefix: config?.disableHostPrefix ?? false,
  52483. endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,
  52484. extensions: config?.extensions ?? [],
  52485. httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider,
  52486. httpAuthSchemes: config?.httpAuthSchemes ?? [
  52487. {
  52488. schemeId: "aws.auth#sigv4",
  52489. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
  52490. signer: new AwsSdkSigV4Signer()
  52491. },
  52492. {
  52493. schemeId: "smithy.api#noAuth",
  52494. identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
  52495. signer: new NoAuthSigner()
  52496. }
  52497. ],
  52498. logger: config?.logger ?? new NoOpLogger(),
  52499. serviceId: config?.serviceId ?? "SSO OIDC",
  52500. urlParser: config?.urlParser ?? parseUrl,
  52501. utf8Decoder: config?.utf8Decoder ?? fromUtf8,
  52502. utf8Encoder: config?.utf8Encoder ?? toUtf8
  52503. };
  52504. };
  52505. }
  52506. });
  52507. // ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/constants.js
  52508. var AWS_EXECUTION_ENV, AWS_REGION_ENV, AWS_DEFAULT_REGION_ENV, ENV_IMDS_DISABLED2, DEFAULTS_MODE_OPTIONS, IMDS_REGION_PATH;
  52509. var init_constants9 = __esm({
  52510. "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/constants.js"() {
  52511. "use strict";
  52512. AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV";
  52513. AWS_REGION_ENV = "AWS_REGION";
  52514. AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION";
  52515. ENV_IMDS_DISABLED2 = "AWS_EC2_METADATA_DISABLED";
  52516. DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];
  52517. IMDS_REGION_PATH = "/latest/meta-data/placement/region";
  52518. }
  52519. });
  52520. // ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/defaultsModeConfig.js
  52521. var AWS_DEFAULTS_MODE_ENV, AWS_DEFAULTS_MODE_CONFIG, NODE_DEFAULTS_MODE_CONFIG_OPTIONS;
  52522. var init_defaultsModeConfig = __esm({
  52523. "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/defaultsModeConfig.js"() {
  52524. "use strict";
  52525. AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE";
  52526. AWS_DEFAULTS_MODE_CONFIG = "defaults_mode";
  52527. NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {
  52528. environmentVariableSelector: (env4) => {
  52529. return env4[AWS_DEFAULTS_MODE_ENV];
  52530. },
  52531. configFileSelector: (profile) => {
  52532. return profile[AWS_DEFAULTS_MODE_CONFIG];
  52533. },
  52534. default: "legacy"
  52535. };
  52536. }
  52537. });
  52538. // ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js
  52539. var resolveDefaultsModeConfig, resolveNodeDefaultsModeAuto, inferPhysicalRegion;
  52540. var init_resolveDefaultsModeConfig = __esm({
  52541. "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js"() {
  52542. "use strict";
  52543. init_dist_es28();
  52544. init_dist_es31();
  52545. init_dist_es21();
  52546. init_constants9();
  52547. init_defaultsModeConfig();
  52548. resolveDefaultsModeConfig = ({ region = loadConfig(NODE_REGION_CONFIG_OPTIONS), defaultsMode = loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) } = {}) => memoize(async () => {
  52549. const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
  52550. switch (mode?.toLowerCase()) {
  52551. case "auto":
  52552. return resolveNodeDefaultsModeAuto(region);
  52553. case "in-region":
  52554. case "cross-region":
  52555. case "mobile":
  52556. case "standard":
  52557. case "legacy":
  52558. return Promise.resolve(mode?.toLocaleLowerCase());
  52559. case void 0:
  52560. return Promise.resolve("legacy");
  52561. default:
  52562. throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`);
  52563. }
  52564. });
  52565. resolveNodeDefaultsModeAuto = async (clientRegion) => {
  52566. if (clientRegion) {
  52567. const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion;
  52568. const inferredRegion = await inferPhysicalRegion();
  52569. if (!inferredRegion) {
  52570. return "standard";
  52571. }
  52572. if (resolvedRegion === inferredRegion) {
  52573. return "in-region";
  52574. } else {
  52575. return "cross-region";
  52576. }
  52577. }
  52578. return "standard";
  52579. };
  52580. inferPhysicalRegion = async () => {
  52581. if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) {
  52582. return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV];
  52583. }
  52584. if (!process.env[ENV_IMDS_DISABLED2]) {
  52585. try {
  52586. const { getInstanceMetadataEndpoint: getInstanceMetadataEndpoint2, httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_dist_es39(), dist_es_exports2));
  52587. const endpoint = await getInstanceMetadataEndpoint2();
  52588. return (await httpRequest2({ ...endpoint, path: IMDS_REGION_PATH })).toString();
  52589. } catch (e6) {
  52590. }
  52591. }
  52592. };
  52593. }
  52594. });
  52595. // ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/index.js
  52596. var init_dist_es44 = __esm({
  52597. "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-es/index.js"() {
  52598. "use strict";
  52599. init_resolveDefaultsModeConfig();
  52600. }
  52601. });
  52602. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js
  52603. var getRuntimeConfig2;
  52604. var init_runtimeConfig = __esm({
  52605. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js"() {
  52606. "use strict";
  52607. init_package2();
  52608. init_dist_es25();
  52609. init_dist_es41();
  52610. init_dist_es28();
  52611. init_dist_es42();
  52612. init_dist_es37();
  52613. init_dist_es31();
  52614. init_dist_es14();
  52615. init_dist_es43();
  52616. init_dist_es36();
  52617. init_runtimeConfig_shared();
  52618. init_dist_es24();
  52619. init_dist_es44();
  52620. init_dist_es24();
  52621. getRuntimeConfig2 = (config) => {
  52622. emitWarningIfUnsupportedVersion2(process.version);
  52623. const defaultsMode = resolveDefaultsModeConfig(config);
  52624. const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
  52625. const clientSharedValues = getRuntimeConfig(config);
  52626. emitWarningIfUnsupportedVersion(process.version);
  52627. const loaderConfig = {
  52628. profile: config?.profile,
  52629. logger: clientSharedValues.logger
  52630. };
  52631. return {
  52632. ...clientSharedValues,
  52633. ...config,
  52634. runtime: "node",
  52635. defaultsMode,
  52636. authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
  52637. bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
  52638. defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }),
  52639. maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
  52640. region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
  52641. requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
  52642. retryMode: config?.retryMode ?? loadConfig({
  52643. ...NODE_RETRY_MODE_CONFIG_OPTIONS,
  52644. default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE
  52645. }, config),
  52646. sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
  52647. streamCollector: config?.streamCollector ?? streamCollector,
  52648. useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  52649. useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  52650. userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
  52651. };
  52652. };
  52653. }
  52654. });
  52655. // ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js
  52656. var getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration;
  52657. var init_extensions4 = __esm({
  52658. "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js"() {
  52659. "use strict";
  52660. getAwsRegionExtensionConfiguration = (runtimeConfig) => {
  52661. return {
  52662. setRegion(region) {
  52663. runtimeConfig.region = region;
  52664. },
  52665. region() {
  52666. return runtimeConfig.region;
  52667. }
  52668. };
  52669. };
  52670. resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => {
  52671. return {
  52672. region: awsRegionExtensionConfiguration.region()
  52673. };
  52674. };
  52675. }
  52676. });
  52677. // ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js
  52678. var init_config4 = __esm({
  52679. "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js"() {
  52680. "use strict";
  52681. }
  52682. });
  52683. // ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/isFipsRegion.js
  52684. var init_isFipsRegion2 = __esm({
  52685. "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/isFipsRegion.js"() {
  52686. "use strict";
  52687. }
  52688. });
  52689. // ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/getRealRegion.js
  52690. var init_getRealRegion2 = __esm({
  52691. "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/getRealRegion.js"() {
  52692. "use strict";
  52693. init_isFipsRegion2();
  52694. }
  52695. });
  52696. // ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js
  52697. var init_resolveRegionConfig2 = __esm({
  52698. "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() {
  52699. "use strict";
  52700. init_getRealRegion2();
  52701. init_isFipsRegion2();
  52702. }
  52703. });
  52704. // ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js
  52705. var init_regionConfig2 = __esm({
  52706. "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js"() {
  52707. "use strict";
  52708. init_config4();
  52709. init_resolveRegionConfig2();
  52710. }
  52711. });
  52712. // ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/index.js
  52713. var init_dist_es45 = __esm({
  52714. "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-es/index.js"() {
  52715. "use strict";
  52716. init_extensions4();
  52717. init_regionConfig2();
  52718. }
  52719. });
  52720. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js
  52721. var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig;
  52722. var init_httpAuthExtensionConfiguration = __esm({
  52723. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js"() {
  52724. "use strict";
  52725. getHttpAuthExtensionConfiguration = (runtimeConfig) => {
  52726. const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
  52727. let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
  52728. let _credentials = runtimeConfig.credentials;
  52729. return {
  52730. setHttpAuthScheme(httpAuthScheme) {
  52731. const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
  52732. if (index6 === -1) {
  52733. _httpAuthSchemes.push(httpAuthScheme);
  52734. } else {
  52735. _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
  52736. }
  52737. },
  52738. httpAuthSchemes() {
  52739. return _httpAuthSchemes;
  52740. },
  52741. setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
  52742. _httpAuthSchemeProvider = httpAuthSchemeProvider;
  52743. },
  52744. httpAuthSchemeProvider() {
  52745. return _httpAuthSchemeProvider;
  52746. },
  52747. setCredentials(credentials2) {
  52748. _credentials = credentials2;
  52749. },
  52750. credentials() {
  52751. return _credentials;
  52752. }
  52753. };
  52754. };
  52755. resolveHttpAuthRuntimeConfig = (config) => {
  52756. return {
  52757. httpAuthSchemes: config.httpAuthSchemes(),
  52758. httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
  52759. credentials: config.credentials()
  52760. };
  52761. };
  52762. }
  52763. });
  52764. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js
  52765. var resolveRuntimeExtensions;
  52766. var init_runtimeExtensions = __esm({
  52767. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js"() {
  52768. "use strict";
  52769. init_dist_es45();
  52770. init_dist_es2();
  52771. init_dist_es24();
  52772. init_httpAuthExtensionConfiguration();
  52773. resolveRuntimeExtensions = (runtimeConfig, extensions) => {
  52774. const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));
  52775. extensions.forEach((extension) => extension.configure(extensionConfiguration));
  52776. return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
  52777. };
  52778. }
  52779. });
  52780. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js
  52781. var SSOOIDCClient;
  52782. var init_SSOOIDCClient = __esm({
  52783. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js"() {
  52784. "use strict";
  52785. init_dist_es3();
  52786. init_dist_es4();
  52787. init_dist_es5();
  52788. init_dist_es26();
  52789. init_dist_es28();
  52790. init_dist_es18();
  52791. init_dist_es29();
  52792. init_dist_es34();
  52793. init_dist_es37();
  52794. init_dist_es24();
  52795. init_httpAuthSchemeProvider2();
  52796. init_EndpointParameters2();
  52797. init_runtimeConfig();
  52798. init_runtimeExtensions();
  52799. SSOOIDCClient = class extends Client {
  52800. constructor(...[configuration]) {
  52801. const _config_0 = getRuntimeConfig2(configuration || {});
  52802. super(_config_0);
  52803. __publicField(this, "config");
  52804. this.initConfig = _config_0;
  52805. const _config_1 = resolveClientEndpointParameters2(_config_0);
  52806. const _config_2 = resolveUserAgentConfig(_config_1);
  52807. const _config_3 = resolveRetryConfig(_config_2);
  52808. const _config_4 = resolveRegionConfig(_config_3);
  52809. const _config_5 = resolveHostHeaderConfig(_config_4);
  52810. const _config_6 = resolveEndpointConfig(_config_5);
  52811. const _config_7 = resolveHttpAuthSchemeConfig2(_config_6);
  52812. const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);
  52813. this.config = _config_8;
  52814. this.middlewareStack.use(getUserAgentPlugin(this.config));
  52815. this.middlewareStack.use(getRetryPlugin(this.config));
  52816. this.middlewareStack.use(getContentLengthPlugin(this.config));
  52817. this.middlewareStack.use(getHostHeaderPlugin(this.config));
  52818. this.middlewareStack.use(getLoggerPlugin(this.config));
  52819. this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
  52820. this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
  52821. httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,
  52822. identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
  52823. "aws.auth#sigv4": config.credentials
  52824. })
  52825. }));
  52826. this.middlewareStack.use(getHttpSigningPlugin(this.config));
  52827. }
  52828. destroy() {
  52829. super.destroy();
  52830. }
  52831. };
  52832. }
  52833. });
  52834. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js
  52835. var SSOOIDCServiceException;
  52836. var init_SSOOIDCServiceException = __esm({
  52837. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js"() {
  52838. "use strict";
  52839. init_dist_es24();
  52840. SSOOIDCServiceException = class _SSOOIDCServiceException extends ServiceException {
  52841. constructor(options) {
  52842. super(options);
  52843. Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype);
  52844. }
  52845. };
  52846. }
  52847. });
  52848. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js
  52849. var AccessDeniedException, AuthorizationPendingException, CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog, ExpiredTokenException, InternalServerException, InvalidClientException, InvalidGrantException, InvalidRequestException, InvalidScopeException, SlowDownException, UnauthorizedClientException, UnsupportedGrantTypeException;
  52850. var init_models_0 = __esm({
  52851. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js"() {
  52852. "use strict";
  52853. init_dist_es24();
  52854. init_SSOOIDCServiceException();
  52855. AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException {
  52856. constructor(opts) {
  52857. super({
  52858. name: "AccessDeniedException",
  52859. $fault: "client",
  52860. ...opts
  52861. });
  52862. __publicField(this, "name", "AccessDeniedException");
  52863. __publicField(this, "$fault", "client");
  52864. __publicField(this, "error");
  52865. __publicField(this, "error_description");
  52866. Object.setPrototypeOf(this, _AccessDeniedException.prototype);
  52867. this.error = opts.error;
  52868. this.error_description = opts.error_description;
  52869. }
  52870. };
  52871. AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException {
  52872. constructor(opts) {
  52873. super({
  52874. name: "AuthorizationPendingException",
  52875. $fault: "client",
  52876. ...opts
  52877. });
  52878. __publicField(this, "name", "AuthorizationPendingException");
  52879. __publicField(this, "$fault", "client");
  52880. __publicField(this, "error");
  52881. __publicField(this, "error_description");
  52882. Object.setPrototypeOf(this, _AuthorizationPendingException.prototype);
  52883. this.error = opts.error;
  52884. this.error_description = opts.error_description;
  52885. }
  52886. };
  52887. CreateTokenRequestFilterSensitiveLog = (obj) => ({
  52888. ...obj,
  52889. ...obj.clientSecret && { clientSecret: SENSITIVE_STRING },
  52890. ...obj.refreshToken && { refreshToken: SENSITIVE_STRING },
  52891. ...obj.codeVerifier && { codeVerifier: SENSITIVE_STRING }
  52892. });
  52893. CreateTokenResponseFilterSensitiveLog = (obj) => ({
  52894. ...obj,
  52895. ...obj.accessToken && { accessToken: SENSITIVE_STRING },
  52896. ...obj.refreshToken && { refreshToken: SENSITIVE_STRING },
  52897. ...obj.idToken && { idToken: SENSITIVE_STRING }
  52898. });
  52899. ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException {
  52900. constructor(opts) {
  52901. super({
  52902. name: "ExpiredTokenException",
  52903. $fault: "client",
  52904. ...opts
  52905. });
  52906. __publicField(this, "name", "ExpiredTokenException");
  52907. __publicField(this, "$fault", "client");
  52908. __publicField(this, "error");
  52909. __publicField(this, "error_description");
  52910. Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
  52911. this.error = opts.error;
  52912. this.error_description = opts.error_description;
  52913. }
  52914. };
  52915. InternalServerException = class _InternalServerException extends SSOOIDCServiceException {
  52916. constructor(opts) {
  52917. super({
  52918. name: "InternalServerException",
  52919. $fault: "server",
  52920. ...opts
  52921. });
  52922. __publicField(this, "name", "InternalServerException");
  52923. __publicField(this, "$fault", "server");
  52924. __publicField(this, "error");
  52925. __publicField(this, "error_description");
  52926. Object.setPrototypeOf(this, _InternalServerException.prototype);
  52927. this.error = opts.error;
  52928. this.error_description = opts.error_description;
  52929. }
  52930. };
  52931. InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException {
  52932. constructor(opts) {
  52933. super({
  52934. name: "InvalidClientException",
  52935. $fault: "client",
  52936. ...opts
  52937. });
  52938. __publicField(this, "name", "InvalidClientException");
  52939. __publicField(this, "$fault", "client");
  52940. __publicField(this, "error");
  52941. __publicField(this, "error_description");
  52942. Object.setPrototypeOf(this, _InvalidClientException.prototype);
  52943. this.error = opts.error;
  52944. this.error_description = opts.error_description;
  52945. }
  52946. };
  52947. InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException {
  52948. constructor(opts) {
  52949. super({
  52950. name: "InvalidGrantException",
  52951. $fault: "client",
  52952. ...opts
  52953. });
  52954. __publicField(this, "name", "InvalidGrantException");
  52955. __publicField(this, "$fault", "client");
  52956. __publicField(this, "error");
  52957. __publicField(this, "error_description");
  52958. Object.setPrototypeOf(this, _InvalidGrantException.prototype);
  52959. this.error = opts.error;
  52960. this.error_description = opts.error_description;
  52961. }
  52962. };
  52963. InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException {
  52964. constructor(opts) {
  52965. super({
  52966. name: "InvalidRequestException",
  52967. $fault: "client",
  52968. ...opts
  52969. });
  52970. __publicField(this, "name", "InvalidRequestException");
  52971. __publicField(this, "$fault", "client");
  52972. __publicField(this, "error");
  52973. __publicField(this, "error_description");
  52974. Object.setPrototypeOf(this, _InvalidRequestException.prototype);
  52975. this.error = opts.error;
  52976. this.error_description = opts.error_description;
  52977. }
  52978. };
  52979. InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException {
  52980. constructor(opts) {
  52981. super({
  52982. name: "InvalidScopeException",
  52983. $fault: "client",
  52984. ...opts
  52985. });
  52986. __publicField(this, "name", "InvalidScopeException");
  52987. __publicField(this, "$fault", "client");
  52988. __publicField(this, "error");
  52989. __publicField(this, "error_description");
  52990. Object.setPrototypeOf(this, _InvalidScopeException.prototype);
  52991. this.error = opts.error;
  52992. this.error_description = opts.error_description;
  52993. }
  52994. };
  52995. SlowDownException = class _SlowDownException extends SSOOIDCServiceException {
  52996. constructor(opts) {
  52997. super({
  52998. name: "SlowDownException",
  52999. $fault: "client",
  53000. ...opts
  53001. });
  53002. __publicField(this, "name", "SlowDownException");
  53003. __publicField(this, "$fault", "client");
  53004. __publicField(this, "error");
  53005. __publicField(this, "error_description");
  53006. Object.setPrototypeOf(this, _SlowDownException.prototype);
  53007. this.error = opts.error;
  53008. this.error_description = opts.error_description;
  53009. }
  53010. };
  53011. UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException {
  53012. constructor(opts) {
  53013. super({
  53014. name: "UnauthorizedClientException",
  53015. $fault: "client",
  53016. ...opts
  53017. });
  53018. __publicField(this, "name", "UnauthorizedClientException");
  53019. __publicField(this, "$fault", "client");
  53020. __publicField(this, "error");
  53021. __publicField(this, "error_description");
  53022. Object.setPrototypeOf(this, _UnauthorizedClientException.prototype);
  53023. this.error = opts.error;
  53024. this.error_description = opts.error_description;
  53025. }
  53026. };
  53027. UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException {
  53028. constructor(opts) {
  53029. super({
  53030. name: "UnsupportedGrantTypeException",
  53031. $fault: "client",
  53032. ...opts
  53033. });
  53034. __publicField(this, "name", "UnsupportedGrantTypeException");
  53035. __publicField(this, "$fault", "client");
  53036. __publicField(this, "error");
  53037. __publicField(this, "error_description");
  53038. Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype);
  53039. this.error = opts.error;
  53040. this.error_description = opts.error_description;
  53041. }
  53042. };
  53043. }
  53044. });
  53045. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/protocols/Aws_restJson1.js
  53046. var se_CreateTokenCommand, de_CreateTokenCommand, de_CommandError, throwDefaultError2, de_AccessDeniedExceptionRes, de_AuthorizationPendingExceptionRes, de_ExpiredTokenExceptionRes, de_InternalServerExceptionRes, de_InvalidClientExceptionRes, de_InvalidGrantExceptionRes, de_InvalidRequestExceptionRes, de_InvalidScopeExceptionRes, de_SlowDownExceptionRes, de_UnauthorizedClientExceptionRes, de_UnsupportedGrantTypeExceptionRes, deserializeMetadata2;
  53047. var init_Aws_restJson1 = __esm({
  53048. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/protocols/Aws_restJson1.js"() {
  53049. "use strict";
  53050. init_dist_es25();
  53051. init_dist_es18();
  53052. init_dist_es24();
  53053. init_models_0();
  53054. init_SSOOIDCServiceException();
  53055. se_CreateTokenCommand = async (input, context) => {
  53056. const b5 = requestBuilder(input, context);
  53057. const headers = {
  53058. "content-type": "application/json"
  53059. };
  53060. b5.bp("/token");
  53061. let body;
  53062. body = JSON.stringify(take(input, {
  53063. clientId: [],
  53064. clientSecret: [],
  53065. code: [],
  53066. codeVerifier: [],
  53067. deviceCode: [],
  53068. grantType: [],
  53069. redirectUri: [],
  53070. refreshToken: [],
  53071. scope: (_3) => _json(_3)
  53072. }));
  53073. b5.m("POST").h(headers).b(body);
  53074. return b5.build();
  53075. };
  53076. de_CreateTokenCommand = async (output, context) => {
  53077. if (output.statusCode !== 200 && output.statusCode >= 300) {
  53078. return de_CommandError(output, context);
  53079. }
  53080. const contents = map({
  53081. $metadata: deserializeMetadata2(output)
  53082. });
  53083. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  53084. const doc = take(data, {
  53085. accessToken: expectString,
  53086. expiresIn: expectInt32,
  53087. idToken: expectString,
  53088. refreshToken: expectString,
  53089. tokenType: expectString
  53090. });
  53091. Object.assign(contents, doc);
  53092. return contents;
  53093. };
  53094. de_CommandError = async (output, context) => {
  53095. const parsedOutput = {
  53096. ...output,
  53097. body: await parseJsonErrorBody(output.body, context)
  53098. };
  53099. const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
  53100. switch (errorCode) {
  53101. case "AccessDeniedException":
  53102. case "com.amazonaws.ssooidc#AccessDeniedException":
  53103. throw await de_AccessDeniedExceptionRes(parsedOutput, context);
  53104. case "AuthorizationPendingException":
  53105. case "com.amazonaws.ssooidc#AuthorizationPendingException":
  53106. throw await de_AuthorizationPendingExceptionRes(parsedOutput, context);
  53107. case "ExpiredTokenException":
  53108. case "com.amazonaws.ssooidc#ExpiredTokenException":
  53109. throw await de_ExpiredTokenExceptionRes(parsedOutput, context);
  53110. case "InternalServerException":
  53111. case "com.amazonaws.ssooidc#InternalServerException":
  53112. throw await de_InternalServerExceptionRes(parsedOutput, context);
  53113. case "InvalidClientException":
  53114. case "com.amazonaws.ssooidc#InvalidClientException":
  53115. throw await de_InvalidClientExceptionRes(parsedOutput, context);
  53116. case "InvalidGrantException":
  53117. case "com.amazonaws.ssooidc#InvalidGrantException":
  53118. throw await de_InvalidGrantExceptionRes(parsedOutput, context);
  53119. case "InvalidRequestException":
  53120. case "com.amazonaws.ssooidc#InvalidRequestException":
  53121. throw await de_InvalidRequestExceptionRes(parsedOutput, context);
  53122. case "InvalidScopeException":
  53123. case "com.amazonaws.ssooidc#InvalidScopeException":
  53124. throw await de_InvalidScopeExceptionRes(parsedOutput, context);
  53125. case "SlowDownException":
  53126. case "com.amazonaws.ssooidc#SlowDownException":
  53127. throw await de_SlowDownExceptionRes(parsedOutput, context);
  53128. case "UnauthorizedClientException":
  53129. case "com.amazonaws.ssooidc#UnauthorizedClientException":
  53130. throw await de_UnauthorizedClientExceptionRes(parsedOutput, context);
  53131. case "UnsupportedGrantTypeException":
  53132. case "com.amazonaws.ssooidc#UnsupportedGrantTypeException":
  53133. throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context);
  53134. default:
  53135. const parsedBody = parsedOutput.body;
  53136. return throwDefaultError2({
  53137. output,
  53138. parsedBody,
  53139. errorCode
  53140. });
  53141. }
  53142. };
  53143. throwDefaultError2 = withBaseException(SSOOIDCServiceException);
  53144. de_AccessDeniedExceptionRes = async (parsedOutput, context) => {
  53145. const contents = map({});
  53146. const data = parsedOutput.body;
  53147. const doc = take(data, {
  53148. error: expectString,
  53149. error_description: expectString
  53150. });
  53151. Object.assign(contents, doc);
  53152. const exception = new AccessDeniedException({
  53153. $metadata: deserializeMetadata2(parsedOutput),
  53154. ...contents
  53155. });
  53156. return decorateServiceException(exception, parsedOutput.body);
  53157. };
  53158. de_AuthorizationPendingExceptionRes = async (parsedOutput, context) => {
  53159. const contents = map({});
  53160. const data = parsedOutput.body;
  53161. const doc = take(data, {
  53162. error: expectString,
  53163. error_description: expectString
  53164. });
  53165. Object.assign(contents, doc);
  53166. const exception = new AuthorizationPendingException({
  53167. $metadata: deserializeMetadata2(parsedOutput),
  53168. ...contents
  53169. });
  53170. return decorateServiceException(exception, parsedOutput.body);
  53171. };
  53172. de_ExpiredTokenExceptionRes = async (parsedOutput, context) => {
  53173. const contents = map({});
  53174. const data = parsedOutput.body;
  53175. const doc = take(data, {
  53176. error: expectString,
  53177. error_description: expectString
  53178. });
  53179. Object.assign(contents, doc);
  53180. const exception = new ExpiredTokenException({
  53181. $metadata: deserializeMetadata2(parsedOutput),
  53182. ...contents
  53183. });
  53184. return decorateServiceException(exception, parsedOutput.body);
  53185. };
  53186. de_InternalServerExceptionRes = async (parsedOutput, context) => {
  53187. const contents = map({});
  53188. const data = parsedOutput.body;
  53189. const doc = take(data, {
  53190. error: expectString,
  53191. error_description: expectString
  53192. });
  53193. Object.assign(contents, doc);
  53194. const exception = new InternalServerException({
  53195. $metadata: deserializeMetadata2(parsedOutput),
  53196. ...contents
  53197. });
  53198. return decorateServiceException(exception, parsedOutput.body);
  53199. };
  53200. de_InvalidClientExceptionRes = async (parsedOutput, context) => {
  53201. const contents = map({});
  53202. const data = parsedOutput.body;
  53203. const doc = take(data, {
  53204. error: expectString,
  53205. error_description: expectString
  53206. });
  53207. Object.assign(contents, doc);
  53208. const exception = new InvalidClientException({
  53209. $metadata: deserializeMetadata2(parsedOutput),
  53210. ...contents
  53211. });
  53212. return decorateServiceException(exception, parsedOutput.body);
  53213. };
  53214. de_InvalidGrantExceptionRes = async (parsedOutput, context) => {
  53215. const contents = map({});
  53216. const data = parsedOutput.body;
  53217. const doc = take(data, {
  53218. error: expectString,
  53219. error_description: expectString
  53220. });
  53221. Object.assign(contents, doc);
  53222. const exception = new InvalidGrantException({
  53223. $metadata: deserializeMetadata2(parsedOutput),
  53224. ...contents
  53225. });
  53226. return decorateServiceException(exception, parsedOutput.body);
  53227. };
  53228. de_InvalidRequestExceptionRes = async (parsedOutput, context) => {
  53229. const contents = map({});
  53230. const data = parsedOutput.body;
  53231. const doc = take(data, {
  53232. error: expectString,
  53233. error_description: expectString
  53234. });
  53235. Object.assign(contents, doc);
  53236. const exception = new InvalidRequestException({
  53237. $metadata: deserializeMetadata2(parsedOutput),
  53238. ...contents
  53239. });
  53240. return decorateServiceException(exception, parsedOutput.body);
  53241. };
  53242. de_InvalidScopeExceptionRes = async (parsedOutput, context) => {
  53243. const contents = map({});
  53244. const data = parsedOutput.body;
  53245. const doc = take(data, {
  53246. error: expectString,
  53247. error_description: expectString
  53248. });
  53249. Object.assign(contents, doc);
  53250. const exception = new InvalidScopeException({
  53251. $metadata: deserializeMetadata2(parsedOutput),
  53252. ...contents
  53253. });
  53254. return decorateServiceException(exception, parsedOutput.body);
  53255. };
  53256. de_SlowDownExceptionRes = async (parsedOutput, context) => {
  53257. const contents = map({});
  53258. const data = parsedOutput.body;
  53259. const doc = take(data, {
  53260. error: expectString,
  53261. error_description: expectString
  53262. });
  53263. Object.assign(contents, doc);
  53264. const exception = new SlowDownException({
  53265. $metadata: deserializeMetadata2(parsedOutput),
  53266. ...contents
  53267. });
  53268. return decorateServiceException(exception, parsedOutput.body);
  53269. };
  53270. de_UnauthorizedClientExceptionRes = async (parsedOutput, context) => {
  53271. const contents = map({});
  53272. const data = parsedOutput.body;
  53273. const doc = take(data, {
  53274. error: expectString,
  53275. error_description: expectString
  53276. });
  53277. Object.assign(contents, doc);
  53278. const exception = new UnauthorizedClientException({
  53279. $metadata: deserializeMetadata2(parsedOutput),
  53280. ...contents
  53281. });
  53282. return decorateServiceException(exception, parsedOutput.body);
  53283. };
  53284. de_UnsupportedGrantTypeExceptionRes = async (parsedOutput, context) => {
  53285. const contents = map({});
  53286. const data = parsedOutput.body;
  53287. const doc = take(data, {
  53288. error: expectString,
  53289. error_description: expectString
  53290. });
  53291. Object.assign(contents, doc);
  53292. const exception = new UnsupportedGrantTypeException({
  53293. $metadata: deserializeMetadata2(parsedOutput),
  53294. ...contents
  53295. });
  53296. return decorateServiceException(exception, parsedOutput.body);
  53297. };
  53298. deserializeMetadata2 = (output) => ({
  53299. httpStatusCode: output.statusCode,
  53300. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  53301. extendedRequestId: output.headers["x-amz-id-2"],
  53302. cfId: output.headers["x-amz-cf-id"]
  53303. });
  53304. }
  53305. });
  53306. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js
  53307. var CreateTokenCommand;
  53308. var init_CreateTokenCommand = __esm({
  53309. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js"() {
  53310. "use strict";
  53311. init_dist_es34();
  53312. init_dist_es7();
  53313. init_dist_es24();
  53314. init_EndpointParameters2();
  53315. init_models_0();
  53316. init_Aws_restJson1();
  53317. CreateTokenCommand = class extends Command.classBuilder().ep(commonParams2).m(function(Command2, cs, config, o5) {
  53318. return [
  53319. getSerdePlugin(config, this.serialize, this.deserialize),
  53320. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  53321. ];
  53322. }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() {
  53323. };
  53324. }
  53325. });
  53326. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js
  53327. var commands, SSOOIDC;
  53328. var init_SSOOIDC = __esm({
  53329. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js"() {
  53330. "use strict";
  53331. init_dist_es24();
  53332. init_CreateTokenCommand();
  53333. init_SSOOIDCClient();
  53334. commands = {
  53335. CreateTokenCommand
  53336. };
  53337. SSOOIDC = class extends SSOOIDCClient {
  53338. };
  53339. createAggregatedClient(commands, SSOOIDC);
  53340. }
  53341. });
  53342. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js
  53343. var init_commands = __esm({
  53344. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js"() {
  53345. "use strict";
  53346. init_CreateTokenCommand();
  53347. }
  53348. });
  53349. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/index.js
  53350. var init_models = __esm({
  53351. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/index.js"() {
  53352. "use strict";
  53353. init_models_0();
  53354. }
  53355. });
  53356. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js
  53357. var sso_oidc_exports = {};
  53358. __export(sso_oidc_exports, {
  53359. $Command: () => Command,
  53360. AccessDeniedException: () => AccessDeniedException,
  53361. AuthorizationPendingException: () => AuthorizationPendingException,
  53362. CreateTokenCommand: () => CreateTokenCommand,
  53363. CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog,
  53364. CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog,
  53365. ExpiredTokenException: () => ExpiredTokenException,
  53366. InternalServerException: () => InternalServerException,
  53367. InvalidClientException: () => InvalidClientException,
  53368. InvalidGrantException: () => InvalidGrantException,
  53369. InvalidRequestException: () => InvalidRequestException,
  53370. InvalidScopeException: () => InvalidScopeException,
  53371. SSOOIDC: () => SSOOIDC,
  53372. SSOOIDCClient: () => SSOOIDCClient,
  53373. SSOOIDCServiceException: () => SSOOIDCServiceException,
  53374. SlowDownException: () => SlowDownException,
  53375. UnauthorizedClientException: () => UnauthorizedClientException,
  53376. UnsupportedGrantTypeException: () => UnsupportedGrantTypeException,
  53377. __Client: () => Client
  53378. });
  53379. var init_sso_oidc = __esm({
  53380. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js"() {
  53381. "use strict";
  53382. init_SSOOIDCClient();
  53383. init_SSOOIDC();
  53384. init_commands();
  53385. init_models();
  53386. init_SSOOIDCServiceException();
  53387. }
  53388. });
  53389. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js
  53390. var getSsoOidcClient;
  53391. var init_getSsoOidcClient = __esm({
  53392. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js"() {
  53393. "use strict";
  53394. getSsoOidcClient = async (ssoRegion, init2 = {}) => {
  53395. const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports));
  53396. const ssoOidcClient = new SSOOIDCClient2(Object.assign({}, init2.clientConfig ?? {}, {
  53397. region: ssoRegion ?? init2.clientConfig?.region,
  53398. logger: init2.clientConfig?.logger ?? init2.parentClientConfig?.logger
  53399. }));
  53400. return ssoOidcClient;
  53401. };
  53402. }
  53403. });
  53404. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js
  53405. var getNewSsoOidcToken;
  53406. var init_getNewSsoOidcToken = __esm({
  53407. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js"() {
  53408. "use strict";
  53409. init_getSsoOidcClient();
  53410. getNewSsoOidcToken = async (ssoToken, ssoRegion, init2 = {}) => {
  53411. const { CreateTokenCommand: CreateTokenCommand2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports));
  53412. const ssoOidcClient = await getSsoOidcClient(ssoRegion, init2);
  53413. return ssoOidcClient.send(new CreateTokenCommand2({
  53414. clientId: ssoToken.clientId,
  53415. clientSecret: ssoToken.clientSecret,
  53416. refreshToken: ssoToken.refreshToken,
  53417. grantType: "refresh_token"
  53418. }));
  53419. };
  53420. }
  53421. });
  53422. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js
  53423. var validateTokenExpiry;
  53424. var init_validateTokenExpiry = __esm({
  53425. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js"() {
  53426. "use strict";
  53427. init_dist_es21();
  53428. init_constants8();
  53429. validateTokenExpiry = (token) => {
  53430. if (token.expiration && token.expiration.getTime() < Date.now()) {
  53431. throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
  53432. }
  53433. };
  53434. }
  53435. });
  53436. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js
  53437. var validateTokenKey;
  53438. var init_validateTokenKey = __esm({
  53439. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js"() {
  53440. "use strict";
  53441. init_dist_es21();
  53442. init_constants8();
  53443. validateTokenKey = (key, value, forRefresh = false) => {
  53444. if (typeof value === "undefined") {
  53445. throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false);
  53446. }
  53447. };
  53448. }
  53449. });
  53450. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js
  53451. import { promises as fsPromises3 } from "fs";
  53452. var writeFile, writeSSOTokenToFile;
  53453. var init_writeSSOTokenToFile = __esm({
  53454. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js"() {
  53455. "use strict";
  53456. init_dist_es30();
  53457. ({ writeFile } = fsPromises3);
  53458. writeSSOTokenToFile = (id, ssoToken) => {
  53459. const tokenFilepath = getSSOTokenFilepath(id);
  53460. const tokenString = JSON.stringify(ssoToken, null, 2);
  53461. return writeFile(tokenFilepath, tokenString);
  53462. };
  53463. }
  53464. });
  53465. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js
  53466. var lastRefreshAttemptTime, fromSso;
  53467. var init_fromSso = __esm({
  53468. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js"() {
  53469. "use strict";
  53470. init_dist_es21();
  53471. init_dist_es30();
  53472. init_constants8();
  53473. init_getNewSsoOidcToken();
  53474. init_validateTokenExpiry();
  53475. init_validateTokenKey();
  53476. init_writeSSOTokenToFile();
  53477. lastRefreshAttemptTime = /* @__PURE__ */ new Date(0);
  53478. fromSso = (_init2 = {}) => async ({ callerClientConfig } = {}) => {
  53479. const init2 = {
  53480. ..._init2,
  53481. parentClientConfig: {
  53482. ...callerClientConfig,
  53483. ..._init2.parentClientConfig
  53484. }
  53485. };
  53486. init2.logger?.debug("@aws-sdk/token-providers - fromSso");
  53487. const profiles = await parseKnownFiles(init2);
  53488. const profileName = getProfileName({
  53489. profile: init2.profile ?? callerClientConfig?.profile
  53490. });
  53491. const profile = profiles[profileName];
  53492. if (!profile) {
  53493. throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
  53494. } else if (!profile["sso_session"]) {
  53495. throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
  53496. }
  53497. const ssoSessionName = profile["sso_session"];
  53498. const ssoSessions = await loadSsoSessionData(init2);
  53499. const ssoSession = ssoSessions[ssoSessionName];
  53500. if (!ssoSession) {
  53501. throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);
  53502. }
  53503. for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) {
  53504. if (!ssoSession[ssoSessionRequiredKey]) {
  53505. throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);
  53506. }
  53507. }
  53508. const ssoStartUrl = ssoSession["sso_start_url"];
  53509. const ssoRegion = ssoSession["sso_region"];
  53510. let ssoToken;
  53511. try {
  53512. ssoToken = await getSSOTokenFromFile(ssoSessionName);
  53513. } catch (e6) {
  53514. throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);
  53515. }
  53516. validateTokenKey("accessToken", ssoToken.accessToken);
  53517. validateTokenKey("expiresAt", ssoToken.expiresAt);
  53518. const { accessToken, expiresAt } = ssoToken;
  53519. const existingToken = { token: accessToken, expiration: new Date(expiresAt) };
  53520. if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {
  53521. return existingToken;
  53522. }
  53523. if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) {
  53524. validateTokenExpiry(existingToken);
  53525. return existingToken;
  53526. }
  53527. validateTokenKey("clientId", ssoToken.clientId, true);
  53528. validateTokenKey("clientSecret", ssoToken.clientSecret, true);
  53529. validateTokenKey("refreshToken", ssoToken.refreshToken, true);
  53530. try {
  53531. lastRefreshAttemptTime.setTime(Date.now());
  53532. const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init2);
  53533. validateTokenKey("accessToken", newSsoOidcToken.accessToken);
  53534. validateTokenKey("expiresIn", newSsoOidcToken.expiresIn);
  53535. const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3);
  53536. try {
  53537. await writeSSOTokenToFile(ssoSessionName, {
  53538. ...ssoToken,
  53539. accessToken: newSsoOidcToken.accessToken,
  53540. expiresAt: newTokenExpiration.toISOString(),
  53541. refreshToken: newSsoOidcToken.refreshToken
  53542. });
  53543. } catch (error2) {
  53544. }
  53545. return {
  53546. token: newSsoOidcToken.accessToken,
  53547. expiration: newTokenExpiration
  53548. };
  53549. } catch (error2) {
  53550. validateTokenExpiry(existingToken);
  53551. return existingToken;
  53552. }
  53553. };
  53554. }
  53555. });
  53556. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js
  53557. var init_fromStatic3 = __esm({
  53558. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js"() {
  53559. "use strict";
  53560. init_dist_es21();
  53561. }
  53562. });
  53563. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js
  53564. var init_nodeProvider = __esm({
  53565. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js"() {
  53566. "use strict";
  53567. init_dist_es21();
  53568. }
  53569. });
  53570. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/index.js
  53571. var init_dist_es46 = __esm({
  53572. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-es/index.js"() {
  53573. "use strict";
  53574. init_fromEnvSigningName();
  53575. init_fromSso();
  53576. init_fromStatic3();
  53577. init_nodeProvider();
  53578. }
  53579. });
  53580. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthSchemeProvider.js
  53581. function createAwsAuthSigv4HttpAuthOption3(authParameters) {
  53582. return {
  53583. schemeId: "aws.auth#sigv4",
  53584. signingProperties: {
  53585. name: "awsssoportal",
  53586. region: authParameters.region
  53587. },
  53588. propertiesExtractor: (config, context) => ({
  53589. signingProperties: {
  53590. config,
  53591. context
  53592. }
  53593. })
  53594. };
  53595. }
  53596. function createSmithyApiNoAuthHttpAuthOption2(authParameters) {
  53597. return {
  53598. schemeId: "smithy.api#noAuth"
  53599. };
  53600. }
  53601. var defaultSSOHttpAuthSchemeParametersProvider, defaultSSOHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig3;
  53602. var init_httpAuthSchemeProvider3 = __esm({
  53603. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthSchemeProvider.js"() {
  53604. "use strict";
  53605. init_dist_es25();
  53606. init_dist_es6();
  53607. defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {
  53608. return {
  53609. operation: getSmithyContext(context).operation,
  53610. region: await normalizeProvider(config.region)() || (() => {
  53611. throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
  53612. })()
  53613. };
  53614. };
  53615. defaultSSOHttpAuthSchemeProvider = (authParameters) => {
  53616. const options = [];
  53617. switch (authParameters.operation) {
  53618. case "GetRoleCredentials": {
  53619. options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
  53620. break;
  53621. }
  53622. case "ListAccountRoles": {
  53623. options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
  53624. break;
  53625. }
  53626. case "ListAccounts": {
  53627. options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
  53628. break;
  53629. }
  53630. case "Logout": {
  53631. options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
  53632. break;
  53633. }
  53634. default: {
  53635. options.push(createAwsAuthSigv4HttpAuthOption3(authParameters));
  53636. }
  53637. }
  53638. return options;
  53639. };
  53640. resolveHttpAuthSchemeConfig3 = (config) => {
  53641. const config_0 = resolveAwsSdkSigV4Config(config);
  53642. return Object.assign(config_0, {
  53643. authSchemePreference: normalizeProvider(config.authSchemePreference ?? [])
  53644. });
  53645. };
  53646. }
  53647. });
  53648. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/EndpointParameters.js
  53649. var resolveClientEndpointParameters3, commonParams3;
  53650. var init_EndpointParameters3 = __esm({
  53651. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/EndpointParameters.js"() {
  53652. "use strict";
  53653. resolveClientEndpointParameters3 = (options) => {
  53654. return Object.assign(options, {
  53655. useDualstackEndpoint: options.useDualstackEndpoint ?? false,
  53656. useFipsEndpoint: options.useFipsEndpoint ?? false,
  53657. defaultSigningName: "awsssoportal"
  53658. });
  53659. };
  53660. commonParams3 = {
  53661. UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
  53662. Endpoint: { type: "builtInParams", name: "endpoint" },
  53663. Region: { type: "builtInParams", name: "region" },
  53664. UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  53665. };
  53666. }
  53667. });
  53668. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/package.json
  53669. var package_default3;
  53670. var init_package3 = __esm({
  53671. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/package.json"() {
  53672. package_default3 = {
  53673. name: "@aws-sdk/client-sso",
  53674. description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native",
  53675. version: "3.817.0",
  53676. scripts: {
  53677. build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
  53678. "build:cjs": "node ../../scripts/compilation/inline client-sso",
  53679. "build:es": "tsc -p tsconfig.es.json",
  53680. "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
  53681. "build:types": "tsc -p tsconfig.types.json",
  53682. "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
  53683. clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
  53684. "extract:docs": "api-extractor run --local",
  53685. "generate:client": "node ../../scripts/generate-clients/single-service --solo sso"
  53686. },
  53687. main: "./dist-cjs/index.js",
  53688. types: "./dist-types/index.d.ts",
  53689. module: "./dist-es/index.js",
  53690. sideEffects: false,
  53691. dependencies: {
  53692. "@aws-crypto/sha256-browser": "5.2.0",
  53693. "@aws-crypto/sha256-js": "5.2.0",
  53694. "@aws-sdk/core": "3.816.0",
  53695. "@aws-sdk/middleware-host-header": "3.804.0",
  53696. "@aws-sdk/middleware-logger": "3.804.0",
  53697. "@aws-sdk/middleware-recursion-detection": "3.804.0",
  53698. "@aws-sdk/middleware-user-agent": "3.816.0",
  53699. "@aws-sdk/region-config-resolver": "3.808.0",
  53700. "@aws-sdk/types": "3.804.0",
  53701. "@aws-sdk/util-endpoints": "3.808.0",
  53702. "@aws-sdk/util-user-agent-browser": "3.804.0",
  53703. "@aws-sdk/util-user-agent-node": "3.816.0",
  53704. "@smithy/config-resolver": "^4.1.2",
  53705. "@smithy/core": "^3.3.3",
  53706. "@smithy/fetch-http-handler": "^5.0.2",
  53707. "@smithy/hash-node": "^4.0.2",
  53708. "@smithy/invalid-dependency": "^4.0.2",
  53709. "@smithy/middleware-content-length": "^4.0.2",
  53710. "@smithy/middleware-endpoint": "^4.1.6",
  53711. "@smithy/middleware-retry": "^4.1.7",
  53712. "@smithy/middleware-serde": "^4.0.5",
  53713. "@smithy/middleware-stack": "^4.0.2",
  53714. "@smithy/node-config-provider": "^4.1.1",
  53715. "@smithy/node-http-handler": "^4.0.4",
  53716. "@smithy/protocol-http": "^5.1.0",
  53717. "@smithy/smithy-client": "^4.2.6",
  53718. "@smithy/types": "^4.2.0",
  53719. "@smithy/url-parser": "^4.0.2",
  53720. "@smithy/util-base64": "^4.0.0",
  53721. "@smithy/util-body-length-browser": "^4.0.0",
  53722. "@smithy/util-body-length-node": "^4.0.0",
  53723. "@smithy/util-defaults-mode-browser": "^4.0.14",
  53724. "@smithy/util-defaults-mode-node": "^4.0.14",
  53725. "@smithy/util-endpoints": "^3.0.4",
  53726. "@smithy/util-middleware": "^4.0.2",
  53727. "@smithy/util-retry": "^4.0.3",
  53728. "@smithy/util-utf8": "^4.0.0",
  53729. tslib: "^2.6.2"
  53730. },
  53731. devDependencies: {
  53732. "@tsconfig/node18": "18.2.4",
  53733. "@types/node": "^18.19.69",
  53734. concurrently: "7.0.0",
  53735. "downlevel-dts": "0.10.1",
  53736. rimraf: "3.0.2",
  53737. typescript: "~5.8.3"
  53738. },
  53739. engines: {
  53740. node: ">=18.0.0"
  53741. },
  53742. typesVersions: {
  53743. "<4.0": {
  53744. "dist-types/*": [
  53745. "dist-types/ts3.4/*"
  53746. ]
  53747. }
  53748. },
  53749. files: [
  53750. "dist-*/**"
  53751. ],
  53752. author: {
  53753. name: "AWS SDK for JavaScript Team",
  53754. url: "https://aws.amazon.com/javascript/"
  53755. },
  53756. license: "Apache-2.0",
  53757. browser: {
  53758. "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
  53759. },
  53760. "react-native": {
  53761. "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
  53762. },
  53763. homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso",
  53764. repository: {
  53765. type: "git",
  53766. url: "https://github.com/aws/aws-sdk-js-v3.git",
  53767. directory: "clients/client-sso"
  53768. }
  53769. };
  53770. }
  53771. });
  53772. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/ruleset.js
  53773. var u2, v2, w2, x3, a2, b2, c2, d2, e3, f4, g2, h3, i3, j2, k2, l2, m3, n2, o2, p2, q2, r3, s3, t3, _data2, ruleSet2;
  53774. var init_ruleset2 = __esm({
  53775. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/ruleset.js"() {
  53776. "use strict";
  53777. u2 = "required";
  53778. v2 = "fn";
  53779. w2 = "argv";
  53780. x3 = "ref";
  53781. a2 = true;
  53782. b2 = "isSet";
  53783. c2 = "booleanEquals";
  53784. d2 = "error";
  53785. e3 = "endpoint";
  53786. f4 = "tree";
  53787. g2 = "PartitionResult";
  53788. h3 = "getAttr";
  53789. i3 = { [u2]: false, "type": "String" };
  53790. j2 = { [u2]: true, "default": false, "type": "Boolean" };
  53791. k2 = { [x3]: "Endpoint" };
  53792. l2 = { [v2]: c2, [w2]: [{ [x3]: "UseFIPS" }, true] };
  53793. m3 = { [v2]: c2, [w2]: [{ [x3]: "UseDualStack" }, true] };
  53794. n2 = {};
  53795. o2 = { [v2]: h3, [w2]: [{ [x3]: g2 }, "supportsFIPS"] };
  53796. p2 = { [x3]: g2 };
  53797. q2 = { [v2]: c2, [w2]: [true, { [v2]: h3, [w2]: [p2, "supportsDualStack"] }] };
  53798. r3 = [l2];
  53799. s3 = [m3];
  53800. t3 = [{ [x3]: "Region" }];
  53801. _data2 = { version: "1.0", parameters: { Region: i3, UseDualStack: j2, UseFIPS: j2, Endpoint: i3 }, rules: [{ conditions: [{ [v2]: b2, [w2]: [k2] }], rules: [{ conditions: r3, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d2 }, { conditions: s3, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d2 }, { endpoint: { url: k2, properties: n2, headers: n2 }, type: e3 }], type: f4 }, { conditions: [{ [v2]: b2, [w2]: t3 }], rules: [{ conditions: [{ [v2]: "aws.partition", [w2]: t3, assign: g2 }], rules: [{ conditions: [l2, m3], rules: [{ conditions: [{ [v2]: c2, [w2]: [a2, o2] }, q2], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f4 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d2 }], type: f4 }, { conditions: r3, rules: [{ conditions: [{ [v2]: c2, [w2]: [o2, a2] }], rules: [{ conditions: [{ [v2]: "stringEquals", [w2]: [{ [v2]: h3, [w2]: [p2, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n2, headers: n2 }, type: e3 }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f4 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d2 }], type: f4 }, { conditions: s3, rules: [{ conditions: [q2], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f4 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d2 }], type: f4 }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f4 }], type: f4 }, { error: "Invalid Configuration: Missing Region", type: d2 }] };
  53802. ruleSet2 = _data2;
  53803. }
  53804. });
  53805. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/endpointResolver.js
  53806. var cache2, defaultEndpointResolver2;
  53807. var init_endpointResolver2 = __esm({
  53808. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/endpointResolver.js"() {
  53809. "use strict";
  53810. init_dist_es20();
  53811. init_dist_es19();
  53812. init_ruleset2();
  53813. cache2 = new EndpointCache({
  53814. size: 50,
  53815. params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
  53816. });
  53817. defaultEndpointResolver2 = (endpointParams, context = {}) => {
  53818. return cache2.get(endpointParams, () => resolveEndpoint(ruleSet2, {
  53819. endpointParams,
  53820. logger: context.logger
  53821. }));
  53822. };
  53823. customEndpointFunctions.aws = awsEndpointFunctions;
  53824. }
  53825. });
  53826. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js
  53827. var getRuntimeConfig3;
  53828. var init_runtimeConfig_shared2 = __esm({
  53829. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js"() {
  53830. "use strict";
  53831. init_dist_es25();
  53832. init_dist_es18();
  53833. init_dist_es24();
  53834. init_dist_es33();
  53835. init_dist_es11();
  53836. init_dist_es10();
  53837. init_httpAuthSchemeProvider3();
  53838. init_endpointResolver2();
  53839. getRuntimeConfig3 = (config) => {
  53840. return {
  53841. apiVersion: "2019-06-10",
  53842. base64Decoder: config?.base64Decoder ?? fromBase64,
  53843. base64Encoder: config?.base64Encoder ?? toBase64,
  53844. disableHostPrefix: config?.disableHostPrefix ?? false,
  53845. endpointProvider: config?.endpointProvider ?? defaultEndpointResolver2,
  53846. extensions: config?.extensions ?? [],
  53847. httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider,
  53848. httpAuthSchemes: config?.httpAuthSchemes ?? [
  53849. {
  53850. schemeId: "aws.auth#sigv4",
  53851. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
  53852. signer: new AwsSdkSigV4Signer()
  53853. },
  53854. {
  53855. schemeId: "smithy.api#noAuth",
  53856. identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
  53857. signer: new NoAuthSigner()
  53858. }
  53859. ],
  53860. logger: config?.logger ?? new NoOpLogger(),
  53861. serviceId: config?.serviceId ?? "SSO",
  53862. urlParser: config?.urlParser ?? parseUrl,
  53863. utf8Decoder: config?.utf8Decoder ?? fromUtf8,
  53864. utf8Encoder: config?.utf8Encoder ?? toUtf8
  53865. };
  53866. };
  53867. }
  53868. });
  53869. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js
  53870. var getRuntimeConfig4;
  53871. var init_runtimeConfig2 = __esm({
  53872. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js"() {
  53873. "use strict";
  53874. init_package3();
  53875. init_dist_es25();
  53876. init_dist_es41();
  53877. init_dist_es28();
  53878. init_dist_es42();
  53879. init_dist_es37();
  53880. init_dist_es31();
  53881. init_dist_es14();
  53882. init_dist_es43();
  53883. init_dist_es36();
  53884. init_runtimeConfig_shared2();
  53885. init_dist_es24();
  53886. init_dist_es44();
  53887. init_dist_es24();
  53888. getRuntimeConfig4 = (config) => {
  53889. emitWarningIfUnsupportedVersion2(process.version);
  53890. const defaultsMode = resolveDefaultsModeConfig(config);
  53891. const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
  53892. const clientSharedValues = getRuntimeConfig3(config);
  53893. emitWarningIfUnsupportedVersion(process.version);
  53894. const loaderConfig = {
  53895. profile: config?.profile,
  53896. logger: clientSharedValues.logger
  53897. };
  53898. return {
  53899. ...clientSharedValues,
  53900. ...config,
  53901. runtime: "node",
  53902. defaultsMode,
  53903. authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
  53904. bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
  53905. defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default3.version }),
  53906. maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
  53907. region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
  53908. requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
  53909. retryMode: config?.retryMode ?? loadConfig({
  53910. ...NODE_RETRY_MODE_CONFIG_OPTIONS,
  53911. default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE
  53912. }, config),
  53913. sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
  53914. streamCollector: config?.streamCollector ?? streamCollector,
  53915. useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  53916. useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  53917. userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
  53918. };
  53919. };
  53920. }
  53921. });
  53922. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js
  53923. var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2;
  53924. var init_httpAuthExtensionConfiguration2 = __esm({
  53925. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js"() {
  53926. "use strict";
  53927. getHttpAuthExtensionConfiguration2 = (runtimeConfig) => {
  53928. const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
  53929. let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
  53930. let _credentials = runtimeConfig.credentials;
  53931. return {
  53932. setHttpAuthScheme(httpAuthScheme) {
  53933. const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
  53934. if (index6 === -1) {
  53935. _httpAuthSchemes.push(httpAuthScheme);
  53936. } else {
  53937. _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
  53938. }
  53939. },
  53940. httpAuthSchemes() {
  53941. return _httpAuthSchemes;
  53942. },
  53943. setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
  53944. _httpAuthSchemeProvider = httpAuthSchemeProvider;
  53945. },
  53946. httpAuthSchemeProvider() {
  53947. return _httpAuthSchemeProvider;
  53948. },
  53949. setCredentials(credentials2) {
  53950. _credentials = credentials2;
  53951. },
  53952. credentials() {
  53953. return _credentials;
  53954. }
  53955. };
  53956. };
  53957. resolveHttpAuthRuntimeConfig2 = (config) => {
  53958. return {
  53959. httpAuthSchemes: config.httpAuthSchemes(),
  53960. httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
  53961. credentials: config.credentials()
  53962. };
  53963. };
  53964. }
  53965. });
  53966. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js
  53967. var resolveRuntimeExtensions2;
  53968. var init_runtimeExtensions2 = __esm({
  53969. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js"() {
  53970. "use strict";
  53971. init_dist_es45();
  53972. init_dist_es2();
  53973. init_dist_es24();
  53974. init_httpAuthExtensionConfiguration2();
  53975. resolveRuntimeExtensions2 = (runtimeConfig, extensions) => {
  53976. const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig));
  53977. extensions.forEach((extension) => extension.configure(extensionConfiguration));
  53978. return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration));
  53979. };
  53980. }
  53981. });
  53982. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js
  53983. var SSOClient;
  53984. var init_SSOClient = __esm({
  53985. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js"() {
  53986. "use strict";
  53987. init_dist_es3();
  53988. init_dist_es4();
  53989. init_dist_es5();
  53990. init_dist_es26();
  53991. init_dist_es28();
  53992. init_dist_es18();
  53993. init_dist_es29();
  53994. init_dist_es34();
  53995. init_dist_es37();
  53996. init_dist_es24();
  53997. init_httpAuthSchemeProvider3();
  53998. init_EndpointParameters3();
  53999. init_runtimeConfig2();
  54000. init_runtimeExtensions2();
  54001. SSOClient = class extends Client {
  54002. constructor(...[configuration]) {
  54003. const _config_0 = getRuntimeConfig4(configuration || {});
  54004. super(_config_0);
  54005. __publicField(this, "config");
  54006. this.initConfig = _config_0;
  54007. const _config_1 = resolveClientEndpointParameters3(_config_0);
  54008. const _config_2 = resolveUserAgentConfig(_config_1);
  54009. const _config_3 = resolveRetryConfig(_config_2);
  54010. const _config_4 = resolveRegionConfig(_config_3);
  54011. const _config_5 = resolveHostHeaderConfig(_config_4);
  54012. const _config_6 = resolveEndpointConfig(_config_5);
  54013. const _config_7 = resolveHttpAuthSchemeConfig3(_config_6);
  54014. const _config_8 = resolveRuntimeExtensions2(_config_7, configuration?.extensions || []);
  54015. this.config = _config_8;
  54016. this.middlewareStack.use(getUserAgentPlugin(this.config));
  54017. this.middlewareStack.use(getRetryPlugin(this.config));
  54018. this.middlewareStack.use(getContentLengthPlugin(this.config));
  54019. this.middlewareStack.use(getHostHeaderPlugin(this.config));
  54020. this.middlewareStack.use(getLoggerPlugin(this.config));
  54021. this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
  54022. this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
  54023. httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider,
  54024. identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
  54025. "aws.auth#sigv4": config.credentials
  54026. })
  54027. }));
  54028. this.middlewareStack.use(getHttpSigningPlugin(this.config));
  54029. }
  54030. destroy() {
  54031. super.destroy();
  54032. }
  54033. };
  54034. }
  54035. });
  54036. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/SSOServiceException.js
  54037. var SSOServiceException;
  54038. var init_SSOServiceException = __esm({
  54039. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/SSOServiceException.js"() {
  54040. "use strict";
  54041. init_dist_es24();
  54042. SSOServiceException = class _SSOServiceException extends ServiceException {
  54043. constructor(options) {
  54044. super(options);
  54045. Object.setPrototypeOf(this, _SSOServiceException.prototype);
  54046. }
  54047. };
  54048. }
  54049. });
  54050. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/models_0.js
  54051. var InvalidRequestException2, ResourceNotFoundException, TooManyRequestsException, UnauthorizedException, GetRoleCredentialsRequestFilterSensitiveLog, RoleCredentialsFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog, ListAccountRolesRequestFilterSensitiveLog, ListAccountsRequestFilterSensitiveLog, LogoutRequestFilterSensitiveLog;
  54052. var init_models_02 = __esm({
  54053. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/models_0.js"() {
  54054. "use strict";
  54055. init_dist_es24();
  54056. init_SSOServiceException();
  54057. InvalidRequestException2 = class _InvalidRequestException extends SSOServiceException {
  54058. constructor(opts) {
  54059. super({
  54060. name: "InvalidRequestException",
  54061. $fault: "client",
  54062. ...opts
  54063. });
  54064. __publicField(this, "name", "InvalidRequestException");
  54065. __publicField(this, "$fault", "client");
  54066. Object.setPrototypeOf(this, _InvalidRequestException.prototype);
  54067. }
  54068. };
  54069. ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException {
  54070. constructor(opts) {
  54071. super({
  54072. name: "ResourceNotFoundException",
  54073. $fault: "client",
  54074. ...opts
  54075. });
  54076. __publicField(this, "name", "ResourceNotFoundException");
  54077. __publicField(this, "$fault", "client");
  54078. Object.setPrototypeOf(this, _ResourceNotFoundException.prototype);
  54079. }
  54080. };
  54081. TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException {
  54082. constructor(opts) {
  54083. super({
  54084. name: "TooManyRequestsException",
  54085. $fault: "client",
  54086. ...opts
  54087. });
  54088. __publicField(this, "name", "TooManyRequestsException");
  54089. __publicField(this, "$fault", "client");
  54090. Object.setPrototypeOf(this, _TooManyRequestsException.prototype);
  54091. }
  54092. };
  54093. UnauthorizedException = class _UnauthorizedException extends SSOServiceException {
  54094. constructor(opts) {
  54095. super({
  54096. name: "UnauthorizedException",
  54097. $fault: "client",
  54098. ...opts
  54099. });
  54100. __publicField(this, "name", "UnauthorizedException");
  54101. __publicField(this, "$fault", "client");
  54102. Object.setPrototypeOf(this, _UnauthorizedException.prototype);
  54103. }
  54104. };
  54105. GetRoleCredentialsRequestFilterSensitiveLog = (obj) => ({
  54106. ...obj,
  54107. ...obj.accessToken && { accessToken: SENSITIVE_STRING }
  54108. });
  54109. RoleCredentialsFilterSensitiveLog = (obj) => ({
  54110. ...obj,
  54111. ...obj.secretAccessKey && { secretAccessKey: SENSITIVE_STRING },
  54112. ...obj.sessionToken && { sessionToken: SENSITIVE_STRING }
  54113. });
  54114. GetRoleCredentialsResponseFilterSensitiveLog = (obj) => ({
  54115. ...obj,
  54116. ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) }
  54117. });
  54118. ListAccountRolesRequestFilterSensitiveLog = (obj) => ({
  54119. ...obj,
  54120. ...obj.accessToken && { accessToken: SENSITIVE_STRING }
  54121. });
  54122. ListAccountsRequestFilterSensitiveLog = (obj) => ({
  54123. ...obj,
  54124. ...obj.accessToken && { accessToken: SENSITIVE_STRING }
  54125. });
  54126. LogoutRequestFilterSensitiveLog = (obj) => ({
  54127. ...obj,
  54128. ...obj.accessToken && { accessToken: SENSITIVE_STRING }
  54129. });
  54130. }
  54131. });
  54132. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/protocols/Aws_restJson1.js
  54133. var se_GetRoleCredentialsCommand, se_ListAccountRolesCommand, se_ListAccountsCommand, se_LogoutCommand, de_GetRoleCredentialsCommand, de_ListAccountRolesCommand, de_ListAccountsCommand, de_LogoutCommand, de_CommandError2, throwDefaultError3, de_InvalidRequestExceptionRes2, de_ResourceNotFoundExceptionRes, de_TooManyRequestsExceptionRes, de_UnauthorizedExceptionRes, deserializeMetadata3, _aI, _aT, _ai, _mR, _mr, _nT, _nt, _rN, _rn, _xasbt;
  54134. var init_Aws_restJson12 = __esm({
  54135. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/protocols/Aws_restJson1.js"() {
  54136. "use strict";
  54137. init_dist_es25();
  54138. init_dist_es18();
  54139. init_dist_es24();
  54140. init_models_02();
  54141. init_SSOServiceException();
  54142. se_GetRoleCredentialsCommand = async (input, context) => {
  54143. const b5 = requestBuilder(input, context);
  54144. const headers = map({}, isSerializableHeaderValue, {
  54145. [_xasbt]: input[_aT]
  54146. });
  54147. b5.bp("/federation/credentials");
  54148. const query = map({
  54149. [_rn]: [, expectNonNull(input[_rN], `roleName`)],
  54150. [_ai]: [, expectNonNull(input[_aI], `accountId`)]
  54151. });
  54152. let body;
  54153. b5.m("GET").h(headers).q(query).b(body);
  54154. return b5.build();
  54155. };
  54156. se_ListAccountRolesCommand = async (input, context) => {
  54157. const b5 = requestBuilder(input, context);
  54158. const headers = map({}, isSerializableHeaderValue, {
  54159. [_xasbt]: input[_aT]
  54160. });
  54161. b5.bp("/assignment/roles");
  54162. const query = map({
  54163. [_nt]: [, input[_nT]],
  54164. [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()],
  54165. [_ai]: [, expectNonNull(input[_aI], `accountId`)]
  54166. });
  54167. let body;
  54168. b5.m("GET").h(headers).q(query).b(body);
  54169. return b5.build();
  54170. };
  54171. se_ListAccountsCommand = async (input, context) => {
  54172. const b5 = requestBuilder(input, context);
  54173. const headers = map({}, isSerializableHeaderValue, {
  54174. [_xasbt]: input[_aT]
  54175. });
  54176. b5.bp("/assignment/accounts");
  54177. const query = map({
  54178. [_nt]: [, input[_nT]],
  54179. [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()]
  54180. });
  54181. let body;
  54182. b5.m("GET").h(headers).q(query).b(body);
  54183. return b5.build();
  54184. };
  54185. se_LogoutCommand = async (input, context) => {
  54186. const b5 = requestBuilder(input, context);
  54187. const headers = map({}, isSerializableHeaderValue, {
  54188. [_xasbt]: input[_aT]
  54189. });
  54190. b5.bp("/logout");
  54191. let body;
  54192. b5.m("POST").h(headers).b(body);
  54193. return b5.build();
  54194. };
  54195. de_GetRoleCredentialsCommand = async (output, context) => {
  54196. if (output.statusCode !== 200 && output.statusCode >= 300) {
  54197. return de_CommandError2(output, context);
  54198. }
  54199. const contents = map({
  54200. $metadata: deserializeMetadata3(output)
  54201. });
  54202. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  54203. const doc = take(data, {
  54204. roleCredentials: _json
  54205. });
  54206. Object.assign(contents, doc);
  54207. return contents;
  54208. };
  54209. de_ListAccountRolesCommand = async (output, context) => {
  54210. if (output.statusCode !== 200 && output.statusCode >= 300) {
  54211. return de_CommandError2(output, context);
  54212. }
  54213. const contents = map({
  54214. $metadata: deserializeMetadata3(output)
  54215. });
  54216. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  54217. const doc = take(data, {
  54218. nextToken: expectString,
  54219. roleList: _json
  54220. });
  54221. Object.assign(contents, doc);
  54222. return contents;
  54223. };
  54224. de_ListAccountsCommand = async (output, context) => {
  54225. if (output.statusCode !== 200 && output.statusCode >= 300) {
  54226. return de_CommandError2(output, context);
  54227. }
  54228. const contents = map({
  54229. $metadata: deserializeMetadata3(output)
  54230. });
  54231. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  54232. const doc = take(data, {
  54233. accountList: _json,
  54234. nextToken: expectString
  54235. });
  54236. Object.assign(contents, doc);
  54237. return contents;
  54238. };
  54239. de_LogoutCommand = async (output, context) => {
  54240. if (output.statusCode !== 200 && output.statusCode >= 300) {
  54241. return de_CommandError2(output, context);
  54242. }
  54243. const contents = map({
  54244. $metadata: deserializeMetadata3(output)
  54245. });
  54246. await collectBody(output.body, context);
  54247. return contents;
  54248. };
  54249. de_CommandError2 = async (output, context) => {
  54250. const parsedOutput = {
  54251. ...output,
  54252. body: await parseJsonErrorBody(output.body, context)
  54253. };
  54254. const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
  54255. switch (errorCode) {
  54256. case "InvalidRequestException":
  54257. case "com.amazonaws.sso#InvalidRequestException":
  54258. throw await de_InvalidRequestExceptionRes2(parsedOutput, context);
  54259. case "ResourceNotFoundException":
  54260. case "com.amazonaws.sso#ResourceNotFoundException":
  54261. throw await de_ResourceNotFoundExceptionRes(parsedOutput, context);
  54262. case "TooManyRequestsException":
  54263. case "com.amazonaws.sso#TooManyRequestsException":
  54264. throw await de_TooManyRequestsExceptionRes(parsedOutput, context);
  54265. case "UnauthorizedException":
  54266. case "com.amazonaws.sso#UnauthorizedException":
  54267. throw await de_UnauthorizedExceptionRes(parsedOutput, context);
  54268. default:
  54269. const parsedBody = parsedOutput.body;
  54270. return throwDefaultError3({
  54271. output,
  54272. parsedBody,
  54273. errorCode
  54274. });
  54275. }
  54276. };
  54277. throwDefaultError3 = withBaseException(SSOServiceException);
  54278. de_InvalidRequestExceptionRes2 = async (parsedOutput, context) => {
  54279. const contents = map({});
  54280. const data = parsedOutput.body;
  54281. const doc = take(data, {
  54282. message: expectString
  54283. });
  54284. Object.assign(contents, doc);
  54285. const exception = new InvalidRequestException2({
  54286. $metadata: deserializeMetadata3(parsedOutput),
  54287. ...contents
  54288. });
  54289. return decorateServiceException(exception, parsedOutput.body);
  54290. };
  54291. de_ResourceNotFoundExceptionRes = async (parsedOutput, context) => {
  54292. const contents = map({});
  54293. const data = parsedOutput.body;
  54294. const doc = take(data, {
  54295. message: expectString
  54296. });
  54297. Object.assign(contents, doc);
  54298. const exception = new ResourceNotFoundException({
  54299. $metadata: deserializeMetadata3(parsedOutput),
  54300. ...contents
  54301. });
  54302. return decorateServiceException(exception, parsedOutput.body);
  54303. };
  54304. de_TooManyRequestsExceptionRes = async (parsedOutput, context) => {
  54305. const contents = map({});
  54306. const data = parsedOutput.body;
  54307. const doc = take(data, {
  54308. message: expectString
  54309. });
  54310. Object.assign(contents, doc);
  54311. const exception = new TooManyRequestsException({
  54312. $metadata: deserializeMetadata3(parsedOutput),
  54313. ...contents
  54314. });
  54315. return decorateServiceException(exception, parsedOutput.body);
  54316. };
  54317. de_UnauthorizedExceptionRes = async (parsedOutput, context) => {
  54318. const contents = map({});
  54319. const data = parsedOutput.body;
  54320. const doc = take(data, {
  54321. message: expectString
  54322. });
  54323. Object.assign(contents, doc);
  54324. const exception = new UnauthorizedException({
  54325. $metadata: deserializeMetadata3(parsedOutput),
  54326. ...contents
  54327. });
  54328. return decorateServiceException(exception, parsedOutput.body);
  54329. };
  54330. deserializeMetadata3 = (output) => ({
  54331. httpStatusCode: output.statusCode,
  54332. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  54333. extendedRequestId: output.headers["x-amz-id-2"],
  54334. cfId: output.headers["x-amz-cf-id"]
  54335. });
  54336. _aI = "accountId";
  54337. _aT = "accessToken";
  54338. _ai = "account_id";
  54339. _mR = "maxResults";
  54340. _mr = "max_result";
  54341. _nT = "nextToken";
  54342. _nt = "next_token";
  54343. _rN = "roleName";
  54344. _rn = "role_name";
  54345. _xasbt = "x-amz-sso_bearer_token";
  54346. }
  54347. });
  54348. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/GetRoleCredentialsCommand.js
  54349. var GetRoleCredentialsCommand;
  54350. var init_GetRoleCredentialsCommand = __esm({
  54351. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/GetRoleCredentialsCommand.js"() {
  54352. "use strict";
  54353. init_dist_es34();
  54354. init_dist_es7();
  54355. init_dist_es24();
  54356. init_EndpointParameters3();
  54357. init_models_02();
  54358. init_Aws_restJson12();
  54359. GetRoleCredentialsCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config, o5) {
  54360. return [
  54361. getSerdePlugin(config, this.serialize, this.deserialize),
  54362. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  54363. ];
  54364. }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() {
  54365. };
  54366. }
  54367. });
  54368. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountRolesCommand.js
  54369. var ListAccountRolesCommand;
  54370. var init_ListAccountRolesCommand = __esm({
  54371. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountRolesCommand.js"() {
  54372. "use strict";
  54373. init_dist_es34();
  54374. init_dist_es7();
  54375. init_dist_es24();
  54376. init_EndpointParameters3();
  54377. init_models_02();
  54378. init_Aws_restJson12();
  54379. ListAccountRolesCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config, o5) {
  54380. return [
  54381. getSerdePlugin(config, this.serialize, this.deserialize),
  54382. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  54383. ];
  54384. }).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() {
  54385. };
  54386. }
  54387. });
  54388. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountsCommand.js
  54389. var ListAccountsCommand;
  54390. var init_ListAccountsCommand = __esm({
  54391. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountsCommand.js"() {
  54392. "use strict";
  54393. init_dist_es34();
  54394. init_dist_es7();
  54395. init_dist_es24();
  54396. init_EndpointParameters3();
  54397. init_models_02();
  54398. init_Aws_restJson12();
  54399. ListAccountsCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config, o5) {
  54400. return [
  54401. getSerdePlugin(config, this.serialize, this.deserialize),
  54402. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  54403. ];
  54404. }).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() {
  54405. };
  54406. }
  54407. });
  54408. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/LogoutCommand.js
  54409. var LogoutCommand;
  54410. var init_LogoutCommand = __esm({
  54411. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/LogoutCommand.js"() {
  54412. "use strict";
  54413. init_dist_es34();
  54414. init_dist_es7();
  54415. init_dist_es24();
  54416. init_EndpointParameters3();
  54417. init_models_02();
  54418. init_Aws_restJson12();
  54419. LogoutCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config, o5) {
  54420. return [
  54421. getSerdePlugin(config, this.serialize, this.deserialize),
  54422. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  54423. ];
  54424. }).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() {
  54425. };
  54426. }
  54427. });
  54428. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/SSO.js
  54429. var commands2, SSO;
  54430. var init_SSO = __esm({
  54431. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/SSO.js"() {
  54432. "use strict";
  54433. init_dist_es24();
  54434. init_GetRoleCredentialsCommand();
  54435. init_ListAccountRolesCommand();
  54436. init_ListAccountsCommand();
  54437. init_LogoutCommand();
  54438. init_SSOClient();
  54439. commands2 = {
  54440. GetRoleCredentialsCommand,
  54441. ListAccountRolesCommand,
  54442. ListAccountsCommand,
  54443. LogoutCommand
  54444. };
  54445. SSO = class extends SSOClient {
  54446. };
  54447. createAggregatedClient(commands2, SSO);
  54448. }
  54449. });
  54450. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/index.js
  54451. var init_commands2 = __esm({
  54452. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/commands/index.js"() {
  54453. "use strict";
  54454. init_GetRoleCredentialsCommand();
  54455. init_ListAccountRolesCommand();
  54456. init_ListAccountsCommand();
  54457. init_LogoutCommand();
  54458. }
  54459. });
  54460. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/Interfaces.js
  54461. var init_Interfaces = __esm({
  54462. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/Interfaces.js"() {
  54463. "use strict";
  54464. }
  54465. });
  54466. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js
  54467. var paginateListAccountRoles;
  54468. var init_ListAccountRolesPaginator = __esm({
  54469. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js"() {
  54470. "use strict";
  54471. init_dist_es18();
  54472. init_ListAccountRolesCommand();
  54473. init_SSOClient();
  54474. paginateListAccountRoles = createPaginator(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults");
  54475. }
  54476. });
  54477. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js
  54478. var paginateListAccounts;
  54479. var init_ListAccountsPaginator = __esm({
  54480. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js"() {
  54481. "use strict";
  54482. init_dist_es18();
  54483. init_ListAccountsCommand();
  54484. init_SSOClient();
  54485. paginateListAccounts = createPaginator(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults");
  54486. }
  54487. });
  54488. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/index.js
  54489. var init_pagination2 = __esm({
  54490. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/index.js"() {
  54491. "use strict";
  54492. init_Interfaces();
  54493. init_ListAccountRolesPaginator();
  54494. init_ListAccountsPaginator();
  54495. }
  54496. });
  54497. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/index.js
  54498. var init_models2 = __esm({
  54499. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/models/index.js"() {
  54500. "use strict";
  54501. init_models_02();
  54502. }
  54503. });
  54504. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/index.js
  54505. var init_dist_es47 = __esm({
  54506. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-es/index.js"() {
  54507. "use strict";
  54508. init_SSOClient();
  54509. init_SSO();
  54510. init_commands2();
  54511. init_pagination2();
  54512. init_models2();
  54513. }
  54514. });
  54515. // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js
  54516. var loadSso_exports = {};
  54517. __export(loadSso_exports, {
  54518. GetRoleCredentialsCommand: () => GetRoleCredentialsCommand,
  54519. SSOClient: () => SSOClient
  54520. });
  54521. var init_loadSso = __esm({
  54522. "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js"() {
  54523. "use strict";
  54524. init_dist_es47();
  54525. }
  54526. });
  54527. // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js
  54528. var SHOULD_FAIL_CREDENTIAL_CHAIN, resolveSSOCredentials;
  54529. var init_resolveSSOCredentials = __esm({
  54530. "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js"() {
  54531. "use strict";
  54532. init_client2();
  54533. init_dist_es46();
  54534. init_dist_es21();
  54535. init_dist_es30();
  54536. SHOULD_FAIL_CREDENTIAL_CHAIN = false;
  54537. resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, profile, logger: logger2 }) => {
  54538. let token;
  54539. const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
  54540. if (ssoSession) {
  54541. try {
  54542. const _token = await fromSso({ profile })();
  54543. token = {
  54544. accessToken: _token.token,
  54545. expiresAt: new Date(_token.expiration).toISOString()
  54546. };
  54547. } catch (e6) {
  54548. throw new CredentialsProviderError(e6.message, {
  54549. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  54550. logger: logger2
  54551. });
  54552. }
  54553. } else {
  54554. try {
  54555. token = await getSSOTokenFromFile(ssoStartUrl);
  54556. } catch (e6) {
  54557. throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {
  54558. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  54559. logger: logger2
  54560. });
  54561. }
  54562. }
  54563. if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
  54564. throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {
  54565. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  54566. logger: logger2
  54567. });
  54568. }
  54569. const { accessToken } = token;
  54570. const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports));
  54571. const sso = ssoClient || new SSOClient2(Object.assign({}, clientConfig ?? {}, {
  54572. logger: clientConfig?.logger ?? parentClientConfig?.logger,
  54573. region: clientConfig?.region ?? ssoRegion
  54574. }));
  54575. let ssoResp;
  54576. try {
  54577. ssoResp = await sso.send(new GetRoleCredentialsCommand2({
  54578. accountId: ssoAccountId,
  54579. roleName: ssoRoleName,
  54580. accessToken
  54581. }));
  54582. } catch (e6) {
  54583. throw new CredentialsProviderError(e6, {
  54584. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  54585. logger: logger2
  54586. });
  54587. }
  54588. const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} } = ssoResp;
  54589. if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
  54590. throw new CredentialsProviderError("SSO returns an invalid temporary credential.", {
  54591. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  54592. logger: logger2
  54593. });
  54594. }
  54595. const credentials2 = {
  54596. accessKeyId,
  54597. secretAccessKey,
  54598. sessionToken,
  54599. expiration: new Date(expiration),
  54600. ...credentialScope && { credentialScope },
  54601. ...accountId && { accountId }
  54602. };
  54603. if (ssoSession) {
  54604. setCredentialFeature(credentials2, "CREDENTIALS_SSO", "s");
  54605. } else {
  54606. setCredentialFeature(credentials2, "CREDENTIALS_SSO_LEGACY", "u");
  54607. }
  54608. return credentials2;
  54609. };
  54610. }
  54611. });
  54612. // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js
  54613. var validateSsoProfile;
  54614. var init_validateSsoProfile = __esm({
  54615. "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js"() {
  54616. "use strict";
  54617. init_dist_es21();
  54618. validateSsoProfile = (profile, logger2) => {
  54619. const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;
  54620. if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {
  54621. throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}
  54622. Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger: logger2 });
  54623. }
  54624. return profile;
  54625. };
  54626. }
  54627. });
  54628. // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js
  54629. var fromSSO;
  54630. var init_fromSSO = __esm({
  54631. "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js"() {
  54632. "use strict";
  54633. init_dist_es21();
  54634. init_dist_es30();
  54635. init_isSsoProfile();
  54636. init_resolveSSOCredentials();
  54637. init_validateSsoProfile();
  54638. fromSSO = (init2 = {}) => async ({ callerClientConfig } = {}) => {
  54639. init2.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");
  54640. const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
  54641. const { ssoClient } = init2;
  54642. const profileName = getProfileName({
  54643. profile: init2.profile ?? callerClientConfig?.profile
  54644. });
  54645. if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
  54646. const profiles = await parseKnownFiles(init2);
  54647. const profile = profiles[profileName];
  54648. if (!profile) {
  54649. throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init2.logger });
  54650. }
  54651. if (!isSsoProfile(profile)) {
  54652. throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {
  54653. logger: init2.logger
  54654. });
  54655. }
  54656. if (profile?.sso_session) {
  54657. const ssoSessions = await loadSsoSessionData(init2);
  54658. const session = ssoSessions[profile.sso_session];
  54659. const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;
  54660. if (ssoRegion && ssoRegion !== session.sso_region) {
  54661. throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {
  54662. tryNextLink: false,
  54663. logger: init2.logger
  54664. });
  54665. }
  54666. if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {
  54667. throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {
  54668. tryNextLink: false,
  54669. logger: init2.logger
  54670. });
  54671. }
  54672. profile.sso_region = session.sso_region;
  54673. profile.sso_start_url = session.sso_start_url;
  54674. }
  54675. const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init2.logger);
  54676. return resolveSSOCredentials({
  54677. ssoStartUrl: sso_start_url,
  54678. ssoSession: sso_session,
  54679. ssoAccountId: sso_account_id,
  54680. ssoRegion: sso_region,
  54681. ssoRoleName: sso_role_name,
  54682. ssoClient,
  54683. clientConfig: init2.clientConfig,
  54684. parentClientConfig: init2.parentClientConfig,
  54685. profile: profileName
  54686. });
  54687. } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {
  54688. throw new CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init2.logger });
  54689. } else {
  54690. return resolveSSOCredentials({
  54691. ssoStartUrl,
  54692. ssoSession,
  54693. ssoAccountId,
  54694. ssoRegion,
  54695. ssoRoleName,
  54696. ssoClient,
  54697. clientConfig: init2.clientConfig,
  54698. parentClientConfig: init2.parentClientConfig,
  54699. profile: profileName
  54700. });
  54701. }
  54702. };
  54703. }
  54704. });
  54705. // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js
  54706. var init_types10 = __esm({
  54707. "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js"() {
  54708. "use strict";
  54709. }
  54710. });
  54711. // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js
  54712. var dist_es_exports4 = {};
  54713. __export(dist_es_exports4, {
  54714. fromSSO: () => fromSSO,
  54715. isSsoProfile: () => isSsoProfile,
  54716. validateSsoProfile: () => validateSsoProfile
  54717. });
  54718. var init_dist_es48 = __esm({
  54719. "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js"() {
  54720. "use strict";
  54721. init_fromSSO();
  54722. init_isSsoProfile();
  54723. init_types10();
  54724. init_validateSsoProfile();
  54725. }
  54726. });
  54727. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js
  54728. var resolveCredentialSource, setNamedProvider;
  54729. var init_resolveCredentialSource = __esm({
  54730. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js"() {
  54731. "use strict";
  54732. init_client2();
  54733. init_dist_es21();
  54734. resolveCredentialSource = (credentialSource, profileName, logger2) => {
  54735. const sourceProvidersMap = {
  54736. EcsContainer: async (options) => {
  54737. const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es40(), dist_es_exports3));
  54738. const { fromContainerMetadata: fromContainerMetadata2 } = await Promise.resolve().then(() => (init_dist_es39(), dist_es_exports2));
  54739. logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer");
  54740. return async () => chain(fromHttp2(options ?? {}), fromContainerMetadata2(options))().then(setNamedProvider);
  54741. },
  54742. Ec2InstanceMetadata: async (options) => {
  54743. logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");
  54744. const { fromInstanceMetadata: fromInstanceMetadata2 } = await Promise.resolve().then(() => (init_dist_es39(), dist_es_exports2));
  54745. return async () => fromInstanceMetadata2(options)().then(setNamedProvider);
  54746. },
  54747. Environment: async (options) => {
  54748. logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");
  54749. const { fromEnv: fromEnv3 } = await Promise.resolve().then(() => (init_dist_es38(), dist_es_exports));
  54750. return async () => fromEnv3(options)().then(setNamedProvider);
  54751. }
  54752. };
  54753. if (credentialSource in sourceProvidersMap) {
  54754. return sourceProvidersMap[credentialSource];
  54755. } else {
  54756. throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger: logger2 });
  54757. }
  54758. };
  54759. setNamedProvider = (creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p");
  54760. }
  54761. });
  54762. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js
  54763. function createAwsAuthSigv4HttpAuthOption4(authParameters) {
  54764. return {
  54765. schemeId: "aws.auth#sigv4",
  54766. signingProperties: {
  54767. name: "sts",
  54768. region: authParameters.region
  54769. },
  54770. propertiesExtractor: (config, context) => ({
  54771. signingProperties: {
  54772. config,
  54773. context
  54774. }
  54775. })
  54776. };
  54777. }
  54778. function createSmithyApiNoAuthHttpAuthOption3(authParameters) {
  54779. return {
  54780. schemeId: "smithy.api#noAuth"
  54781. };
  54782. }
  54783. var defaultSTSHttpAuthSchemeParametersProvider, defaultSTSHttpAuthSchemeProvider, resolveStsAuthConfig, resolveHttpAuthSchemeConfig4;
  54784. var init_httpAuthSchemeProvider4 = __esm({
  54785. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js"() {
  54786. "use strict";
  54787. init_dist_es25();
  54788. init_dist_es6();
  54789. init_STSClient();
  54790. defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => {
  54791. return {
  54792. operation: getSmithyContext(context).operation,
  54793. region: await normalizeProvider(config.region)() || (() => {
  54794. throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
  54795. })()
  54796. };
  54797. };
  54798. defaultSTSHttpAuthSchemeProvider = (authParameters) => {
  54799. const options = [];
  54800. switch (authParameters.operation) {
  54801. case "AssumeRoleWithWebIdentity": {
  54802. options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
  54803. break;
  54804. }
  54805. default: {
  54806. options.push(createAwsAuthSigv4HttpAuthOption4(authParameters));
  54807. }
  54808. }
  54809. return options;
  54810. };
  54811. resolveStsAuthConfig = (input) => Object.assign(input, {
  54812. stsClientCtor: STSClient
  54813. });
  54814. resolveHttpAuthSchemeConfig4 = (config) => {
  54815. const config_0 = resolveStsAuthConfig(config);
  54816. const config_1 = resolveAwsSdkSigV4Config(config_0);
  54817. return Object.assign(config_1, {
  54818. authSchemePreference: normalizeProvider(config.authSchemePreference ?? [])
  54819. });
  54820. };
  54821. }
  54822. });
  54823. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js
  54824. var resolveClientEndpointParameters4, commonParams4;
  54825. var init_EndpointParameters4 = __esm({
  54826. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js"() {
  54827. "use strict";
  54828. resolveClientEndpointParameters4 = (options) => {
  54829. return Object.assign(options, {
  54830. useDualstackEndpoint: options.useDualstackEndpoint ?? false,
  54831. useFipsEndpoint: options.useFipsEndpoint ?? false,
  54832. useGlobalEndpoint: options.useGlobalEndpoint ?? false,
  54833. defaultSigningName: "sts"
  54834. });
  54835. };
  54836. commonParams4 = {
  54837. UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
  54838. UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
  54839. Endpoint: { type: "builtInParams", name: "endpoint" },
  54840. Region: { type: "builtInParams", name: "region" },
  54841. UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  54842. };
  54843. }
  54844. });
  54845. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js
  54846. var F2, G, H, I, J, a3, b3, c3, d3, e4, f5, g3, h4, i4, j3, k3, l3, m4, n3, o3, p3, q3, r4, s4, t4, u3, v3, w3, x4, y, z, A2, B, C, D, E, _data3, ruleSet3;
  54847. var init_ruleset3 = __esm({
  54848. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js"() {
  54849. "use strict";
  54850. F2 = "required";
  54851. G = "type";
  54852. H = "fn";
  54853. I = "argv";
  54854. J = "ref";
  54855. a3 = false;
  54856. b3 = true;
  54857. c3 = "booleanEquals";
  54858. d3 = "stringEquals";
  54859. e4 = "sigv4";
  54860. f5 = "sts";
  54861. g3 = "us-east-1";
  54862. h4 = "endpoint";
  54863. i4 = "https://sts.{Region}.{PartitionResult#dnsSuffix}";
  54864. j3 = "tree";
  54865. k3 = "error";
  54866. l3 = "getAttr";
  54867. m4 = { [F2]: false, [G]: "String" };
  54868. n3 = { [F2]: true, "default": false, [G]: "Boolean" };
  54869. o3 = { [J]: "Endpoint" };
  54870. p3 = { [H]: "isSet", [I]: [{ [J]: "Region" }] };
  54871. q3 = { [J]: "Region" };
  54872. r4 = { [H]: "aws.partition", [I]: [q3], "assign": "PartitionResult" };
  54873. s4 = { [J]: "UseFIPS" };
  54874. t4 = { [J]: "UseDualStack" };
  54875. u3 = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e4, "signingName": f5, "signingRegion": g3 }] }, "headers": {} };
  54876. v3 = {};
  54877. w3 = { "conditions": [{ [H]: d3, [I]: [q3, "aws-global"] }], [h4]: u3, [G]: h4 };
  54878. x4 = { [H]: c3, [I]: [s4, true] };
  54879. y = { [H]: c3, [I]: [t4, true] };
  54880. z = { [H]: l3, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] };
  54881. A2 = { [J]: "PartitionResult" };
  54882. B = { [H]: c3, [I]: [true, { [H]: l3, [I]: [A2, "supportsDualStack"] }] };
  54883. C = [{ [H]: "isSet", [I]: [o3] }];
  54884. D = [x4];
  54885. E = [y];
  54886. _data3 = { version: "1.0", parameters: { Region: m4, UseDualStack: n3, UseFIPS: n3, Endpoint: m4, UseGlobalEndpoint: n3 }, rules: [{ conditions: [{ [H]: c3, [I]: [{ [J]: "UseGlobalEndpoint" }, b3] }, { [H]: "not", [I]: C }, p3, r4, { [H]: c3, [I]: [s4, a3] }, { [H]: c3, [I]: [t4, a3] }], rules: [{ conditions: [{ [H]: d3, [I]: [q3, "ap-northeast-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "ap-south-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "ap-southeast-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "ap-southeast-2"] }], endpoint: u3, [G]: h4 }, w3, { conditions: [{ [H]: d3, [I]: [q3, "ca-central-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-central-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-north-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-west-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-west-2"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "eu-west-3"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "sa-east-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, g3] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "us-east-2"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "us-west-1"] }], endpoint: u3, [G]: h4 }, { conditions: [{ [H]: d3, [I]: [q3, "us-west-2"] }], endpoint: u3, [G]: h4 }, { endpoint: { url: i4, properties: { authSchemes: [{ name: e4, signingName: f5, signingRegion: "{Region}" }] }, headers: v3 }, [G]: h4 }], [G]: j3 }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k3 }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k3 }, { endpoint: { url: o3, properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }, { conditions: [p3], rules: [{ conditions: [r4], rules: [{ conditions: [x4, y], rules: [{ conditions: [{ [H]: c3, [I]: [b3, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k3 }], [G]: j3 }, { conditions: D, rules: [{ conditions: [{ [H]: c3, [I]: [z, b3] }], rules: [{ conditions: [{ [H]: d3, [I]: [{ [H]: l3, [I]: [A2, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v3, headers: v3 }, [G]: h4 }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k3 }], [G]: j3 }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k3 }], [G]: j3 }, w3, { endpoint: { url: i4, properties: v3, headers: v3 }, [G]: h4 }], [G]: j3 }], [G]: j3 }, { error: "Invalid Configuration: Missing Region", [G]: k3 }] };
  54887. ruleSet3 = _data3;
  54888. }
  54889. });
  54890. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js
  54891. var cache3, defaultEndpointResolver3;
  54892. var init_endpointResolver3 = __esm({
  54893. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js"() {
  54894. "use strict";
  54895. init_dist_es20();
  54896. init_dist_es19();
  54897. init_ruleset3();
  54898. cache3 = new EndpointCache({
  54899. size: 50,
  54900. params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"]
  54901. });
  54902. defaultEndpointResolver3 = (endpointParams, context = {}) => {
  54903. return cache3.get(endpointParams, () => resolveEndpoint(ruleSet3, {
  54904. endpointParams,
  54905. logger: context.logger
  54906. }));
  54907. };
  54908. customEndpointFunctions.aws = awsEndpointFunctions;
  54909. }
  54910. });
  54911. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js
  54912. var getRuntimeConfig5;
  54913. var init_runtimeConfig_shared3 = __esm({
  54914. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js"() {
  54915. "use strict";
  54916. init_dist_es25();
  54917. init_dist_es18();
  54918. init_dist_es24();
  54919. init_dist_es33();
  54920. init_dist_es11();
  54921. init_dist_es10();
  54922. init_httpAuthSchemeProvider4();
  54923. init_endpointResolver3();
  54924. getRuntimeConfig5 = (config) => {
  54925. return {
  54926. apiVersion: "2011-06-15",
  54927. base64Decoder: config?.base64Decoder ?? fromBase64,
  54928. base64Encoder: config?.base64Encoder ?? toBase64,
  54929. disableHostPrefix: config?.disableHostPrefix ?? false,
  54930. endpointProvider: config?.endpointProvider ?? defaultEndpointResolver3,
  54931. extensions: config?.extensions ?? [],
  54932. httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider,
  54933. httpAuthSchemes: config?.httpAuthSchemes ?? [
  54934. {
  54935. schemeId: "aws.auth#sigv4",
  54936. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
  54937. signer: new AwsSdkSigV4Signer()
  54938. },
  54939. {
  54940. schemeId: "smithy.api#noAuth",
  54941. identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
  54942. signer: new NoAuthSigner()
  54943. }
  54944. ],
  54945. logger: config?.logger ?? new NoOpLogger(),
  54946. serviceId: config?.serviceId ?? "STS",
  54947. urlParser: config?.urlParser ?? parseUrl,
  54948. utf8Decoder: config?.utf8Decoder ?? fromUtf8,
  54949. utf8Encoder: config?.utf8Encoder ?? toUtf8
  54950. };
  54951. };
  54952. }
  54953. });
  54954. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js
  54955. var getRuntimeConfig6;
  54956. var init_runtimeConfig3 = __esm({
  54957. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js"() {
  54958. "use strict";
  54959. init_package2();
  54960. init_dist_es25();
  54961. init_dist_es41();
  54962. init_dist_es28();
  54963. init_dist_es18();
  54964. init_dist_es42();
  54965. init_dist_es37();
  54966. init_dist_es31();
  54967. init_dist_es14();
  54968. init_dist_es43();
  54969. init_dist_es36();
  54970. init_runtimeConfig_shared3();
  54971. init_dist_es24();
  54972. init_dist_es44();
  54973. init_dist_es24();
  54974. getRuntimeConfig6 = (config) => {
  54975. emitWarningIfUnsupportedVersion2(process.version);
  54976. const defaultsMode = resolveDefaultsModeConfig(config);
  54977. const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
  54978. const clientSharedValues = getRuntimeConfig5(config);
  54979. emitWarningIfUnsupportedVersion(process.version);
  54980. const loaderConfig = {
  54981. profile: config?.profile,
  54982. logger: clientSharedValues.logger
  54983. };
  54984. return {
  54985. ...clientSharedValues,
  54986. ...config,
  54987. runtime: "node",
  54988. defaultsMode,
  54989. authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
  54990. bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
  54991. defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }),
  54992. httpAuthSchemes: config?.httpAuthSchemes ?? [
  54993. {
  54994. schemeId: "aws.auth#sigv4",
  54995. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()),
  54996. signer: new AwsSdkSigV4Signer()
  54997. },
  54998. {
  54999. schemeId: "smithy.api#noAuth",
  55000. identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
  55001. signer: new NoAuthSigner()
  55002. }
  55003. ],
  55004. maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
  55005. region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
  55006. requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
  55007. retryMode: config?.retryMode ?? loadConfig({
  55008. ...NODE_RETRY_MODE_CONFIG_OPTIONS,
  55009. default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE
  55010. }, config),
  55011. sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
  55012. streamCollector: config?.streamCollector ?? streamCollector,
  55013. useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  55014. useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  55015. userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
  55016. };
  55017. };
  55018. }
  55019. });
  55020. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js
  55021. var getHttpAuthExtensionConfiguration3, resolveHttpAuthRuntimeConfig3;
  55022. var init_httpAuthExtensionConfiguration3 = __esm({
  55023. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js"() {
  55024. "use strict";
  55025. getHttpAuthExtensionConfiguration3 = (runtimeConfig) => {
  55026. const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
  55027. let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
  55028. let _credentials = runtimeConfig.credentials;
  55029. return {
  55030. setHttpAuthScheme(httpAuthScheme) {
  55031. const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
  55032. if (index6 === -1) {
  55033. _httpAuthSchemes.push(httpAuthScheme);
  55034. } else {
  55035. _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
  55036. }
  55037. },
  55038. httpAuthSchemes() {
  55039. return _httpAuthSchemes;
  55040. },
  55041. setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
  55042. _httpAuthSchemeProvider = httpAuthSchemeProvider;
  55043. },
  55044. httpAuthSchemeProvider() {
  55045. return _httpAuthSchemeProvider;
  55046. },
  55047. setCredentials(credentials2) {
  55048. _credentials = credentials2;
  55049. },
  55050. credentials() {
  55051. return _credentials;
  55052. }
  55053. };
  55054. };
  55055. resolveHttpAuthRuntimeConfig3 = (config) => {
  55056. return {
  55057. httpAuthSchemes: config.httpAuthSchemes(),
  55058. httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
  55059. credentials: config.credentials()
  55060. };
  55061. };
  55062. }
  55063. });
  55064. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js
  55065. var resolveRuntimeExtensions3;
  55066. var init_runtimeExtensions3 = __esm({
  55067. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js"() {
  55068. "use strict";
  55069. init_dist_es45();
  55070. init_dist_es2();
  55071. init_dist_es24();
  55072. init_httpAuthExtensionConfiguration3();
  55073. resolveRuntimeExtensions3 = (runtimeConfig, extensions) => {
  55074. const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration3(runtimeConfig));
  55075. extensions.forEach((extension) => extension.configure(extensionConfiguration));
  55076. return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig3(extensionConfiguration));
  55077. };
  55078. }
  55079. });
  55080. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js
  55081. var STSClient;
  55082. var init_STSClient = __esm({
  55083. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js"() {
  55084. "use strict";
  55085. init_dist_es3();
  55086. init_dist_es4();
  55087. init_dist_es5();
  55088. init_dist_es26();
  55089. init_dist_es28();
  55090. init_dist_es18();
  55091. init_dist_es29();
  55092. init_dist_es34();
  55093. init_dist_es37();
  55094. init_dist_es24();
  55095. init_httpAuthSchemeProvider4();
  55096. init_EndpointParameters4();
  55097. init_runtimeConfig3();
  55098. init_runtimeExtensions3();
  55099. STSClient = class extends Client {
  55100. constructor(...[configuration]) {
  55101. const _config_0 = getRuntimeConfig6(configuration || {});
  55102. super(_config_0);
  55103. __publicField(this, "config");
  55104. this.initConfig = _config_0;
  55105. const _config_1 = resolveClientEndpointParameters4(_config_0);
  55106. const _config_2 = resolveUserAgentConfig(_config_1);
  55107. const _config_3 = resolveRetryConfig(_config_2);
  55108. const _config_4 = resolveRegionConfig(_config_3);
  55109. const _config_5 = resolveHostHeaderConfig(_config_4);
  55110. const _config_6 = resolveEndpointConfig(_config_5);
  55111. const _config_7 = resolveHttpAuthSchemeConfig4(_config_6);
  55112. const _config_8 = resolveRuntimeExtensions3(_config_7, configuration?.extensions || []);
  55113. this.config = _config_8;
  55114. this.middlewareStack.use(getUserAgentPlugin(this.config));
  55115. this.middlewareStack.use(getRetryPlugin(this.config));
  55116. this.middlewareStack.use(getContentLengthPlugin(this.config));
  55117. this.middlewareStack.use(getHostHeaderPlugin(this.config));
  55118. this.middlewareStack.use(getLoggerPlugin(this.config));
  55119. this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
  55120. this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
  55121. httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider,
  55122. identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
  55123. "aws.auth#sigv4": config.credentials
  55124. })
  55125. }));
  55126. this.middlewareStack.use(getHttpSigningPlugin(this.config));
  55127. }
  55128. destroy() {
  55129. super.destroy();
  55130. }
  55131. };
  55132. }
  55133. });
  55134. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js
  55135. var STSServiceException;
  55136. var init_STSServiceException = __esm({
  55137. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js"() {
  55138. "use strict";
  55139. init_dist_es24();
  55140. STSServiceException = class _STSServiceException extends ServiceException {
  55141. constructor(options) {
  55142. super(options);
  55143. Object.setPrototypeOf(this, _STSServiceException.prototype);
  55144. }
  55145. };
  55146. }
  55147. });
  55148. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js
  55149. var CredentialsFilterSensitiveLog, AssumeRoleResponseFilterSensitiveLog, ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog, IDPCommunicationErrorException;
  55150. var init_models_03 = __esm({
  55151. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js"() {
  55152. "use strict";
  55153. init_dist_es24();
  55154. init_STSServiceException();
  55155. CredentialsFilterSensitiveLog = (obj) => ({
  55156. ...obj,
  55157. ...obj.SecretAccessKey && { SecretAccessKey: SENSITIVE_STRING }
  55158. });
  55159. AssumeRoleResponseFilterSensitiveLog = (obj) => ({
  55160. ...obj,
  55161. ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
  55162. });
  55163. ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException {
  55164. constructor(opts) {
  55165. super({
  55166. name: "ExpiredTokenException",
  55167. $fault: "client",
  55168. ...opts
  55169. });
  55170. __publicField(this, "name", "ExpiredTokenException");
  55171. __publicField(this, "$fault", "client");
  55172. Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
  55173. }
  55174. };
  55175. MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException {
  55176. constructor(opts) {
  55177. super({
  55178. name: "MalformedPolicyDocumentException",
  55179. $fault: "client",
  55180. ...opts
  55181. });
  55182. __publicField(this, "name", "MalformedPolicyDocumentException");
  55183. __publicField(this, "$fault", "client");
  55184. Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype);
  55185. }
  55186. };
  55187. PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException {
  55188. constructor(opts) {
  55189. super({
  55190. name: "PackedPolicyTooLargeException",
  55191. $fault: "client",
  55192. ...opts
  55193. });
  55194. __publicField(this, "name", "PackedPolicyTooLargeException");
  55195. __publicField(this, "$fault", "client");
  55196. Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype);
  55197. }
  55198. };
  55199. RegionDisabledException = class _RegionDisabledException extends STSServiceException {
  55200. constructor(opts) {
  55201. super({
  55202. name: "RegionDisabledException",
  55203. $fault: "client",
  55204. ...opts
  55205. });
  55206. __publicField(this, "name", "RegionDisabledException");
  55207. __publicField(this, "$fault", "client");
  55208. Object.setPrototypeOf(this, _RegionDisabledException.prototype);
  55209. }
  55210. };
  55211. IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException {
  55212. constructor(opts) {
  55213. super({
  55214. name: "IDPRejectedClaimException",
  55215. $fault: "client",
  55216. ...opts
  55217. });
  55218. __publicField(this, "name", "IDPRejectedClaimException");
  55219. __publicField(this, "$fault", "client");
  55220. Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype);
  55221. }
  55222. };
  55223. InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException {
  55224. constructor(opts) {
  55225. super({
  55226. name: "InvalidIdentityTokenException",
  55227. $fault: "client",
  55228. ...opts
  55229. });
  55230. __publicField(this, "name", "InvalidIdentityTokenException");
  55231. __publicField(this, "$fault", "client");
  55232. Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype);
  55233. }
  55234. };
  55235. AssumeRoleWithWebIdentityRequestFilterSensitiveLog = (obj) => ({
  55236. ...obj,
  55237. ...obj.WebIdentityToken && { WebIdentityToken: SENSITIVE_STRING }
  55238. });
  55239. AssumeRoleWithWebIdentityResponseFilterSensitiveLog = (obj) => ({
  55240. ...obj,
  55241. ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
  55242. });
  55243. IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException {
  55244. constructor(opts) {
  55245. super({
  55246. name: "IDPCommunicationErrorException",
  55247. $fault: "client",
  55248. ...opts
  55249. });
  55250. __publicField(this, "name", "IDPCommunicationErrorException");
  55251. __publicField(this, "$fault", "client");
  55252. Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype);
  55253. }
  55254. };
  55255. }
  55256. });
  55257. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/protocols/Aws_query.js
  55258. var se_AssumeRoleCommand, se_AssumeRoleWithWebIdentityCommand, de_AssumeRoleCommand, de_AssumeRoleWithWebIdentityCommand, de_CommandError3, de_ExpiredTokenExceptionRes2, de_IDPCommunicationErrorExceptionRes, de_IDPRejectedClaimExceptionRes, de_InvalidIdentityTokenExceptionRes, de_MalformedPolicyDocumentExceptionRes, de_PackedPolicyTooLargeExceptionRes, de_RegionDisabledExceptionRes, se_AssumeRoleRequest, se_AssumeRoleWithWebIdentityRequest, se_policyDescriptorListType, se_PolicyDescriptorType, se_ProvidedContext, se_ProvidedContextsListType, se_Tag, se_tagKeyListType, se_tagListType, de_AssumedRoleUser, de_AssumeRoleResponse, de_AssumeRoleWithWebIdentityResponse, de_Credentials, de_ExpiredTokenException, de_IDPCommunicationErrorException, de_IDPRejectedClaimException, de_InvalidIdentityTokenException, de_MalformedPolicyDocumentException, de_PackedPolicyTooLargeException, de_RegionDisabledException, deserializeMetadata4, throwDefaultError4, buildHttpRpcRequest, SHARED_HEADERS, _2, _A, _AKI, _AR, _ARI, _ARU, _ARWWI, _Ar, _Au, _C, _CA, _DS, _E, _EI, _K, _P, _PA, _PAr, _PC, _PI, _PPS, _Pr, _RA, _RSN, _SAK, _SFWIT, _SI, _SN, _ST, _T, _TC, _TTK, _V, _Va, _WIT, _a14, _m, buildFormUrlencodedString, loadQueryErrorCode;
  55259. var init_Aws_query = __esm({
  55260. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/protocols/Aws_query.js"() {
  55261. "use strict";
  55262. init_dist_es25();
  55263. init_dist_es2();
  55264. init_dist_es24();
  55265. init_models_03();
  55266. init_STSServiceException();
  55267. se_AssumeRoleCommand = async (input, context) => {
  55268. const headers = SHARED_HEADERS;
  55269. let body;
  55270. body = buildFormUrlencodedString({
  55271. ...se_AssumeRoleRequest(input, context),
  55272. [_A]: _AR,
  55273. [_V]: _2
  55274. });
  55275. return buildHttpRpcRequest(context, headers, "/", void 0, body);
  55276. };
  55277. se_AssumeRoleWithWebIdentityCommand = async (input, context) => {
  55278. const headers = SHARED_HEADERS;
  55279. let body;
  55280. body = buildFormUrlencodedString({
  55281. ...se_AssumeRoleWithWebIdentityRequest(input, context),
  55282. [_A]: _ARWWI,
  55283. [_V]: _2
  55284. });
  55285. return buildHttpRpcRequest(context, headers, "/", void 0, body);
  55286. };
  55287. de_AssumeRoleCommand = async (output, context) => {
  55288. if (output.statusCode >= 300) {
  55289. return de_CommandError3(output, context);
  55290. }
  55291. const data = await parseXmlBody(output.body, context);
  55292. let contents = {};
  55293. contents = de_AssumeRoleResponse(data.AssumeRoleResult, context);
  55294. const response = {
  55295. $metadata: deserializeMetadata4(output),
  55296. ...contents
  55297. };
  55298. return response;
  55299. };
  55300. de_AssumeRoleWithWebIdentityCommand = async (output, context) => {
  55301. if (output.statusCode >= 300) {
  55302. return de_CommandError3(output, context);
  55303. }
  55304. const data = await parseXmlBody(output.body, context);
  55305. let contents = {};
  55306. contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context);
  55307. const response = {
  55308. $metadata: deserializeMetadata4(output),
  55309. ...contents
  55310. };
  55311. return response;
  55312. };
  55313. de_CommandError3 = async (output, context) => {
  55314. const parsedOutput = {
  55315. ...output,
  55316. body: await parseXmlErrorBody(output.body, context)
  55317. };
  55318. const errorCode = loadQueryErrorCode(output, parsedOutput.body);
  55319. switch (errorCode) {
  55320. case "ExpiredTokenException":
  55321. case "com.amazonaws.sts#ExpiredTokenException":
  55322. throw await de_ExpiredTokenExceptionRes2(parsedOutput, context);
  55323. case "MalformedPolicyDocument":
  55324. case "com.amazonaws.sts#MalformedPolicyDocumentException":
  55325. throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context);
  55326. case "PackedPolicyTooLarge":
  55327. case "com.amazonaws.sts#PackedPolicyTooLargeException":
  55328. throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context);
  55329. case "RegionDisabledException":
  55330. case "com.amazonaws.sts#RegionDisabledException":
  55331. throw await de_RegionDisabledExceptionRes(parsedOutput, context);
  55332. case "IDPCommunicationError":
  55333. case "com.amazonaws.sts#IDPCommunicationErrorException":
  55334. throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context);
  55335. case "IDPRejectedClaim":
  55336. case "com.amazonaws.sts#IDPRejectedClaimException":
  55337. throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context);
  55338. case "InvalidIdentityToken":
  55339. case "com.amazonaws.sts#InvalidIdentityTokenException":
  55340. throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context);
  55341. default:
  55342. const parsedBody = parsedOutput.body;
  55343. return throwDefaultError4({
  55344. output,
  55345. parsedBody: parsedBody.Error,
  55346. errorCode
  55347. });
  55348. }
  55349. };
  55350. de_ExpiredTokenExceptionRes2 = async (parsedOutput, context) => {
  55351. const body = parsedOutput.body;
  55352. const deserialized = de_ExpiredTokenException(body.Error, context);
  55353. const exception = new ExpiredTokenException2({
  55354. $metadata: deserializeMetadata4(parsedOutput),
  55355. ...deserialized
  55356. });
  55357. return decorateServiceException(exception, body);
  55358. };
  55359. de_IDPCommunicationErrorExceptionRes = async (parsedOutput, context) => {
  55360. const body = parsedOutput.body;
  55361. const deserialized = de_IDPCommunicationErrorException(body.Error, context);
  55362. const exception = new IDPCommunicationErrorException({
  55363. $metadata: deserializeMetadata4(parsedOutput),
  55364. ...deserialized
  55365. });
  55366. return decorateServiceException(exception, body);
  55367. };
  55368. de_IDPRejectedClaimExceptionRes = async (parsedOutput, context) => {
  55369. const body = parsedOutput.body;
  55370. const deserialized = de_IDPRejectedClaimException(body.Error, context);
  55371. const exception = new IDPRejectedClaimException({
  55372. $metadata: deserializeMetadata4(parsedOutput),
  55373. ...deserialized
  55374. });
  55375. return decorateServiceException(exception, body);
  55376. };
  55377. de_InvalidIdentityTokenExceptionRes = async (parsedOutput, context) => {
  55378. const body = parsedOutput.body;
  55379. const deserialized = de_InvalidIdentityTokenException(body.Error, context);
  55380. const exception = new InvalidIdentityTokenException({
  55381. $metadata: deserializeMetadata4(parsedOutput),
  55382. ...deserialized
  55383. });
  55384. return decorateServiceException(exception, body);
  55385. };
  55386. de_MalformedPolicyDocumentExceptionRes = async (parsedOutput, context) => {
  55387. const body = parsedOutput.body;
  55388. const deserialized = de_MalformedPolicyDocumentException(body.Error, context);
  55389. const exception = new MalformedPolicyDocumentException({
  55390. $metadata: deserializeMetadata4(parsedOutput),
  55391. ...deserialized
  55392. });
  55393. return decorateServiceException(exception, body);
  55394. };
  55395. de_PackedPolicyTooLargeExceptionRes = async (parsedOutput, context) => {
  55396. const body = parsedOutput.body;
  55397. const deserialized = de_PackedPolicyTooLargeException(body.Error, context);
  55398. const exception = new PackedPolicyTooLargeException({
  55399. $metadata: deserializeMetadata4(parsedOutput),
  55400. ...deserialized
  55401. });
  55402. return decorateServiceException(exception, body);
  55403. };
  55404. de_RegionDisabledExceptionRes = async (parsedOutput, context) => {
  55405. const body = parsedOutput.body;
  55406. const deserialized = de_RegionDisabledException(body.Error, context);
  55407. const exception = new RegionDisabledException({
  55408. $metadata: deserializeMetadata4(parsedOutput),
  55409. ...deserialized
  55410. });
  55411. return decorateServiceException(exception, body);
  55412. };
  55413. se_AssumeRoleRequest = (input, context) => {
  55414. const entries = {};
  55415. if (input[_RA] != null) {
  55416. entries[_RA] = input[_RA];
  55417. }
  55418. if (input[_RSN] != null) {
  55419. entries[_RSN] = input[_RSN];
  55420. }
  55421. if (input[_PA] != null) {
  55422. const memberEntries = se_policyDescriptorListType(input[_PA], context);
  55423. if (input[_PA]?.length === 0) {
  55424. entries.PolicyArns = [];
  55425. }
  55426. Object.entries(memberEntries).forEach(([key, value]) => {
  55427. const loc = `PolicyArns.${key}`;
  55428. entries[loc] = value;
  55429. });
  55430. }
  55431. if (input[_P] != null) {
  55432. entries[_P] = input[_P];
  55433. }
  55434. if (input[_DS] != null) {
  55435. entries[_DS] = input[_DS];
  55436. }
  55437. if (input[_T] != null) {
  55438. const memberEntries = se_tagListType(input[_T], context);
  55439. if (input[_T]?.length === 0) {
  55440. entries.Tags = [];
  55441. }
  55442. Object.entries(memberEntries).forEach(([key, value]) => {
  55443. const loc = `Tags.${key}`;
  55444. entries[loc] = value;
  55445. });
  55446. }
  55447. if (input[_TTK] != null) {
  55448. const memberEntries = se_tagKeyListType(input[_TTK], context);
  55449. if (input[_TTK]?.length === 0) {
  55450. entries.TransitiveTagKeys = [];
  55451. }
  55452. Object.entries(memberEntries).forEach(([key, value]) => {
  55453. const loc = `TransitiveTagKeys.${key}`;
  55454. entries[loc] = value;
  55455. });
  55456. }
  55457. if (input[_EI] != null) {
  55458. entries[_EI] = input[_EI];
  55459. }
  55460. if (input[_SN] != null) {
  55461. entries[_SN] = input[_SN];
  55462. }
  55463. if (input[_TC] != null) {
  55464. entries[_TC] = input[_TC];
  55465. }
  55466. if (input[_SI] != null) {
  55467. entries[_SI] = input[_SI];
  55468. }
  55469. if (input[_PC] != null) {
  55470. const memberEntries = se_ProvidedContextsListType(input[_PC], context);
  55471. if (input[_PC]?.length === 0) {
  55472. entries.ProvidedContexts = [];
  55473. }
  55474. Object.entries(memberEntries).forEach(([key, value]) => {
  55475. const loc = `ProvidedContexts.${key}`;
  55476. entries[loc] = value;
  55477. });
  55478. }
  55479. return entries;
  55480. };
  55481. se_AssumeRoleWithWebIdentityRequest = (input, context) => {
  55482. const entries = {};
  55483. if (input[_RA] != null) {
  55484. entries[_RA] = input[_RA];
  55485. }
  55486. if (input[_RSN] != null) {
  55487. entries[_RSN] = input[_RSN];
  55488. }
  55489. if (input[_WIT] != null) {
  55490. entries[_WIT] = input[_WIT];
  55491. }
  55492. if (input[_PI] != null) {
  55493. entries[_PI] = input[_PI];
  55494. }
  55495. if (input[_PA] != null) {
  55496. const memberEntries = se_policyDescriptorListType(input[_PA], context);
  55497. if (input[_PA]?.length === 0) {
  55498. entries.PolicyArns = [];
  55499. }
  55500. Object.entries(memberEntries).forEach(([key, value]) => {
  55501. const loc = `PolicyArns.${key}`;
  55502. entries[loc] = value;
  55503. });
  55504. }
  55505. if (input[_P] != null) {
  55506. entries[_P] = input[_P];
  55507. }
  55508. if (input[_DS] != null) {
  55509. entries[_DS] = input[_DS];
  55510. }
  55511. return entries;
  55512. };
  55513. se_policyDescriptorListType = (input, context) => {
  55514. const entries = {};
  55515. let counter = 1;
  55516. for (const entry of input) {
  55517. if (entry === null) {
  55518. continue;
  55519. }
  55520. const memberEntries = se_PolicyDescriptorType(entry, context);
  55521. Object.entries(memberEntries).forEach(([key, value]) => {
  55522. entries[`member.${counter}.${key}`] = value;
  55523. });
  55524. counter++;
  55525. }
  55526. return entries;
  55527. };
  55528. se_PolicyDescriptorType = (input, context) => {
  55529. const entries = {};
  55530. if (input[_a14] != null) {
  55531. entries[_a14] = input[_a14];
  55532. }
  55533. return entries;
  55534. };
  55535. se_ProvidedContext = (input, context) => {
  55536. const entries = {};
  55537. if (input[_PAr] != null) {
  55538. entries[_PAr] = input[_PAr];
  55539. }
  55540. if (input[_CA] != null) {
  55541. entries[_CA] = input[_CA];
  55542. }
  55543. return entries;
  55544. };
  55545. se_ProvidedContextsListType = (input, context) => {
  55546. const entries = {};
  55547. let counter = 1;
  55548. for (const entry of input) {
  55549. if (entry === null) {
  55550. continue;
  55551. }
  55552. const memberEntries = se_ProvidedContext(entry, context);
  55553. Object.entries(memberEntries).forEach(([key, value]) => {
  55554. entries[`member.${counter}.${key}`] = value;
  55555. });
  55556. counter++;
  55557. }
  55558. return entries;
  55559. };
  55560. se_Tag = (input, context) => {
  55561. const entries = {};
  55562. if (input[_K] != null) {
  55563. entries[_K] = input[_K];
  55564. }
  55565. if (input[_Va] != null) {
  55566. entries[_Va] = input[_Va];
  55567. }
  55568. return entries;
  55569. };
  55570. se_tagKeyListType = (input, context) => {
  55571. const entries = {};
  55572. let counter = 1;
  55573. for (const entry of input) {
  55574. if (entry === null) {
  55575. continue;
  55576. }
  55577. entries[`member.${counter}`] = entry;
  55578. counter++;
  55579. }
  55580. return entries;
  55581. };
  55582. se_tagListType = (input, context) => {
  55583. const entries = {};
  55584. let counter = 1;
  55585. for (const entry of input) {
  55586. if (entry === null) {
  55587. continue;
  55588. }
  55589. const memberEntries = se_Tag(entry, context);
  55590. Object.entries(memberEntries).forEach(([key, value]) => {
  55591. entries[`member.${counter}.${key}`] = value;
  55592. });
  55593. counter++;
  55594. }
  55595. return entries;
  55596. };
  55597. de_AssumedRoleUser = (output, context) => {
  55598. const contents = {};
  55599. if (output[_ARI] != null) {
  55600. contents[_ARI] = expectString(output[_ARI]);
  55601. }
  55602. if (output[_Ar] != null) {
  55603. contents[_Ar] = expectString(output[_Ar]);
  55604. }
  55605. return contents;
  55606. };
  55607. de_AssumeRoleResponse = (output, context) => {
  55608. const contents = {};
  55609. if (output[_C] != null) {
  55610. contents[_C] = de_Credentials(output[_C], context);
  55611. }
  55612. if (output[_ARU] != null) {
  55613. contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
  55614. }
  55615. if (output[_PPS] != null) {
  55616. contents[_PPS] = strictParseInt32(output[_PPS]);
  55617. }
  55618. if (output[_SI] != null) {
  55619. contents[_SI] = expectString(output[_SI]);
  55620. }
  55621. return contents;
  55622. };
  55623. de_AssumeRoleWithWebIdentityResponse = (output, context) => {
  55624. const contents = {};
  55625. if (output[_C] != null) {
  55626. contents[_C] = de_Credentials(output[_C], context);
  55627. }
  55628. if (output[_SFWIT] != null) {
  55629. contents[_SFWIT] = expectString(output[_SFWIT]);
  55630. }
  55631. if (output[_ARU] != null) {
  55632. contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
  55633. }
  55634. if (output[_PPS] != null) {
  55635. contents[_PPS] = strictParseInt32(output[_PPS]);
  55636. }
  55637. if (output[_Pr] != null) {
  55638. contents[_Pr] = expectString(output[_Pr]);
  55639. }
  55640. if (output[_Au] != null) {
  55641. contents[_Au] = expectString(output[_Au]);
  55642. }
  55643. if (output[_SI] != null) {
  55644. contents[_SI] = expectString(output[_SI]);
  55645. }
  55646. return contents;
  55647. };
  55648. de_Credentials = (output, context) => {
  55649. const contents = {};
  55650. if (output[_AKI] != null) {
  55651. contents[_AKI] = expectString(output[_AKI]);
  55652. }
  55653. if (output[_SAK] != null) {
  55654. contents[_SAK] = expectString(output[_SAK]);
  55655. }
  55656. if (output[_ST] != null) {
  55657. contents[_ST] = expectString(output[_ST]);
  55658. }
  55659. if (output[_E] != null) {
  55660. contents[_E] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_E]));
  55661. }
  55662. return contents;
  55663. };
  55664. de_ExpiredTokenException = (output, context) => {
  55665. const contents = {};
  55666. if (output[_m] != null) {
  55667. contents[_m] = expectString(output[_m]);
  55668. }
  55669. return contents;
  55670. };
  55671. de_IDPCommunicationErrorException = (output, context) => {
  55672. const contents = {};
  55673. if (output[_m] != null) {
  55674. contents[_m] = expectString(output[_m]);
  55675. }
  55676. return contents;
  55677. };
  55678. de_IDPRejectedClaimException = (output, context) => {
  55679. const contents = {};
  55680. if (output[_m] != null) {
  55681. contents[_m] = expectString(output[_m]);
  55682. }
  55683. return contents;
  55684. };
  55685. de_InvalidIdentityTokenException = (output, context) => {
  55686. const contents = {};
  55687. if (output[_m] != null) {
  55688. contents[_m] = expectString(output[_m]);
  55689. }
  55690. return contents;
  55691. };
  55692. de_MalformedPolicyDocumentException = (output, context) => {
  55693. const contents = {};
  55694. if (output[_m] != null) {
  55695. contents[_m] = expectString(output[_m]);
  55696. }
  55697. return contents;
  55698. };
  55699. de_PackedPolicyTooLargeException = (output, context) => {
  55700. const contents = {};
  55701. if (output[_m] != null) {
  55702. contents[_m] = expectString(output[_m]);
  55703. }
  55704. return contents;
  55705. };
  55706. de_RegionDisabledException = (output, context) => {
  55707. const contents = {};
  55708. if (output[_m] != null) {
  55709. contents[_m] = expectString(output[_m]);
  55710. }
  55711. return contents;
  55712. };
  55713. deserializeMetadata4 = (output) => ({
  55714. httpStatusCode: output.statusCode,
  55715. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  55716. extendedRequestId: output.headers["x-amz-id-2"],
  55717. cfId: output.headers["x-amz-cf-id"]
  55718. });
  55719. throwDefaultError4 = withBaseException(STSServiceException);
  55720. buildHttpRpcRequest = async (context, headers, path3, resolvedHostname, body) => {
  55721. const { hostname, protocol = "https", port, path: basePath } = await context.endpoint();
  55722. const contents = {
  55723. protocol,
  55724. hostname,
  55725. port,
  55726. method: "POST",
  55727. path: basePath.endsWith("/") ? basePath.slice(0, -1) + path3 : basePath + path3,
  55728. headers
  55729. };
  55730. if (resolvedHostname !== void 0) {
  55731. contents.hostname = resolvedHostname;
  55732. }
  55733. if (body !== void 0) {
  55734. contents.body = body;
  55735. }
  55736. return new HttpRequest(contents);
  55737. };
  55738. SHARED_HEADERS = {
  55739. "content-type": "application/x-www-form-urlencoded"
  55740. };
  55741. _2 = "2011-06-15";
  55742. _A = "Action";
  55743. _AKI = "AccessKeyId";
  55744. _AR = "AssumeRole";
  55745. _ARI = "AssumedRoleId";
  55746. _ARU = "AssumedRoleUser";
  55747. _ARWWI = "AssumeRoleWithWebIdentity";
  55748. _Ar = "Arn";
  55749. _Au = "Audience";
  55750. _C = "Credentials";
  55751. _CA = "ContextAssertion";
  55752. _DS = "DurationSeconds";
  55753. _E = "Expiration";
  55754. _EI = "ExternalId";
  55755. _K = "Key";
  55756. _P = "Policy";
  55757. _PA = "PolicyArns";
  55758. _PAr = "ProviderArn";
  55759. _PC = "ProvidedContexts";
  55760. _PI = "ProviderId";
  55761. _PPS = "PackedPolicySize";
  55762. _Pr = "Provider";
  55763. _RA = "RoleArn";
  55764. _RSN = "RoleSessionName";
  55765. _SAK = "SecretAccessKey";
  55766. _SFWIT = "SubjectFromWebIdentityToken";
  55767. _SI = "SourceIdentity";
  55768. _SN = "SerialNumber";
  55769. _ST = "SessionToken";
  55770. _T = "Tags";
  55771. _TC = "TokenCode";
  55772. _TTK = "TransitiveTagKeys";
  55773. _V = "Version";
  55774. _Va = "Value";
  55775. _WIT = "WebIdentityToken";
  55776. _a14 = "arn";
  55777. _m = "message";
  55778. buildFormUrlencodedString = (formEntries) => Object.entries(formEntries).map(([key, value]) => extendedEncodeURIComponent(key) + "=" + extendedEncodeURIComponent(value)).join("&");
  55779. loadQueryErrorCode = (output, data) => {
  55780. if (data.Error?.Code !== void 0) {
  55781. return data.Error.Code;
  55782. }
  55783. if (output.statusCode == 404) {
  55784. return "NotFound";
  55785. }
  55786. };
  55787. }
  55788. });
  55789. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js
  55790. var AssumeRoleCommand;
  55791. var init_AssumeRoleCommand = __esm({
  55792. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js"() {
  55793. "use strict";
  55794. init_dist_es34();
  55795. init_dist_es7();
  55796. init_dist_es24();
  55797. init_EndpointParameters4();
  55798. init_models_03();
  55799. init_Aws_query();
  55800. AssumeRoleCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs, config, o5) {
  55801. return [
  55802. getSerdePlugin(config, this.serialize, this.deserialize),
  55803. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  55804. ];
  55805. }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() {
  55806. };
  55807. }
  55808. });
  55809. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js
  55810. var AssumeRoleWithWebIdentityCommand;
  55811. var init_AssumeRoleWithWebIdentityCommand = __esm({
  55812. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js"() {
  55813. "use strict";
  55814. init_dist_es34();
  55815. init_dist_es7();
  55816. init_dist_es24();
  55817. init_EndpointParameters4();
  55818. init_models_03();
  55819. init_Aws_query();
  55820. AssumeRoleWithWebIdentityCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs, config, o5) {
  55821. return [
  55822. getSerdePlugin(config, this.serialize, this.deserialize),
  55823. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  55824. ];
  55825. }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() {
  55826. };
  55827. }
  55828. });
  55829. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js
  55830. var commands3, STS;
  55831. var init_STS = __esm({
  55832. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js"() {
  55833. "use strict";
  55834. init_dist_es24();
  55835. init_AssumeRoleCommand();
  55836. init_AssumeRoleWithWebIdentityCommand();
  55837. init_STSClient();
  55838. commands3 = {
  55839. AssumeRoleCommand,
  55840. AssumeRoleWithWebIdentityCommand
  55841. };
  55842. STS = class extends STSClient {
  55843. };
  55844. createAggregatedClient(commands3, STS);
  55845. }
  55846. });
  55847. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js
  55848. var init_commands3 = __esm({
  55849. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js"() {
  55850. "use strict";
  55851. init_AssumeRoleCommand();
  55852. init_AssumeRoleWithWebIdentityCommand();
  55853. }
  55854. });
  55855. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/index.js
  55856. var init_models3 = __esm({
  55857. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/index.js"() {
  55858. "use strict";
  55859. init_models_03();
  55860. }
  55861. });
  55862. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js
  55863. var ASSUME_ROLE_DEFAULT_REGION, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
  55864. var init_defaultStsRoleAssumers = __esm({
  55865. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() {
  55866. "use strict";
  55867. init_client2();
  55868. init_AssumeRoleCommand();
  55869. init_AssumeRoleWithWebIdentityCommand();
  55870. ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
  55871. getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
  55872. if (typeof assumedRoleUser?.Arn === "string") {
  55873. const arnComponents = assumedRoleUser.Arn.split(":");
  55874. if (arnComponents.length > 4 && arnComponents[4] !== "") {
  55875. return arnComponents[4];
  55876. }
  55877. }
  55878. return void 0;
  55879. };
  55880. resolveRegion = async (_region, _parentRegion, credentialProviderLogger) => {
  55881. const region = typeof _region === "function" ? await _region() : _region;
  55882. const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
  55883. credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`);
  55884. return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION;
  55885. };
  55886. getDefaultRoleAssumer = (stsOptions, STSClient2) => {
  55887. let stsClient;
  55888. let closureSourceCreds;
  55889. return async (sourceCreds, params) => {
  55890. closureSourceCreds = sourceCreds;
  55891. if (!stsClient) {
  55892. const { logger: logger2 = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
  55893. const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
  55894. const isCompatibleRequestHandler = !isH2(requestHandler);
  55895. stsClient = new STSClient2({
  55896. profile: stsOptions?.parentClientConfig?.profile,
  55897. credentialDefaultProvider: () => async () => closureSourceCreds,
  55898. region: resolvedRegion,
  55899. requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
  55900. logger: logger2
  55901. });
  55902. }
  55903. const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
  55904. if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
  55905. throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
  55906. }
  55907. const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
  55908. const credentials2 = {
  55909. accessKeyId: Credentials.AccessKeyId,
  55910. secretAccessKey: Credentials.SecretAccessKey,
  55911. sessionToken: Credentials.SessionToken,
  55912. expiration: Credentials.Expiration,
  55913. ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
  55914. ...accountId && { accountId }
  55915. };
  55916. setCredentialFeature(credentials2, "CREDENTIALS_STS_ASSUME_ROLE", "i");
  55917. return credentials2;
  55918. };
  55919. };
  55920. getDefaultRoleAssumerWithWebIdentity = (stsOptions, STSClient2) => {
  55921. let stsClient;
  55922. return async (params) => {
  55923. if (!stsClient) {
  55924. const { logger: logger2 = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
  55925. const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
  55926. const isCompatibleRequestHandler = !isH2(requestHandler);
  55927. stsClient = new STSClient2({
  55928. profile: stsOptions?.parentClientConfig?.profile,
  55929. region: resolvedRegion,
  55930. requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
  55931. logger: logger2
  55932. });
  55933. }
  55934. const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
  55935. if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
  55936. throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
  55937. }
  55938. const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
  55939. const credentials2 = {
  55940. accessKeyId: Credentials.AccessKeyId,
  55941. secretAccessKey: Credentials.SecretAccessKey,
  55942. sessionToken: Credentials.SessionToken,
  55943. expiration: Credentials.Expiration,
  55944. ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
  55945. ...accountId && { accountId }
  55946. };
  55947. if (accountId) {
  55948. setCredentialFeature(credentials2, "RESOLVED_ACCOUNT_ID", "T");
  55949. }
  55950. setCredentialFeature(credentials2, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k");
  55951. return credentials2;
  55952. };
  55953. };
  55954. isH2 = (requestHandler) => {
  55955. return requestHandler?.metadata?.handlerProtocol === "h2";
  55956. };
  55957. }
  55958. });
  55959. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js
  55960. var getCustomizableStsClientCtor, getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity2, decorateDefaultCredentialProvider;
  55961. var init_defaultRoleAssumers = __esm({
  55962. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js"() {
  55963. "use strict";
  55964. init_defaultStsRoleAssumers();
  55965. init_STSClient();
  55966. getCustomizableStsClientCtor = (baseCtor, customizations) => {
  55967. if (!customizations)
  55968. return baseCtor;
  55969. else
  55970. return class CustomizableSTSClient extends baseCtor {
  55971. constructor(config) {
  55972. super(config);
  55973. for (const customization of customizations) {
  55974. this.middlewareStack.use(customization);
  55975. }
  55976. }
  55977. };
  55978. };
  55979. getDefaultRoleAssumer2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
  55980. getDefaultRoleAssumerWithWebIdentity2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
  55981. decorateDefaultCredentialProvider = (provider) => (input) => provider({
  55982. roleAssumer: getDefaultRoleAssumer2(input),
  55983. roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input),
  55984. ...input
  55985. });
  55986. }
  55987. });
  55988. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js
  55989. var sts_exports = {};
  55990. __export(sts_exports, {
  55991. $Command: () => Command,
  55992. AssumeRoleCommand: () => AssumeRoleCommand,
  55993. AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog,
  55994. AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand,
  55995. AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog,
  55996. AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog,
  55997. CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog,
  55998. ExpiredTokenException: () => ExpiredTokenException2,
  55999. IDPCommunicationErrorException: () => IDPCommunicationErrorException,
  56000. IDPRejectedClaimException: () => IDPRejectedClaimException,
  56001. InvalidIdentityTokenException: () => InvalidIdentityTokenException,
  56002. MalformedPolicyDocumentException: () => MalformedPolicyDocumentException,
  56003. PackedPolicyTooLargeException: () => PackedPolicyTooLargeException,
  56004. RegionDisabledException: () => RegionDisabledException,
  56005. STS: () => STS,
  56006. STSClient: () => STSClient,
  56007. STSServiceException: () => STSServiceException,
  56008. __Client: () => Client,
  56009. decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider,
  56010. getDefaultRoleAssumer: () => getDefaultRoleAssumer2,
  56011. getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2
  56012. });
  56013. var init_sts = __esm({
  56014. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js"() {
  56015. "use strict";
  56016. init_STSClient();
  56017. init_STS();
  56018. init_commands3();
  56019. init_models3();
  56020. init_defaultRoleAssumers();
  56021. init_STSServiceException();
  56022. }
  56023. });
  56024. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js
  56025. var isAssumeRoleProfile, isAssumeRoleWithSourceProfile, isCredentialSourceProfile, resolveAssumeRoleCredentials, isCredentialSourceWithoutRoleArn;
  56026. var init_resolveAssumeRoleCredentials = __esm({
  56027. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js"() {
  56028. "use strict";
  56029. init_client2();
  56030. init_dist_es21();
  56031. init_dist_es30();
  56032. init_resolveCredentialSource();
  56033. init_resolveProfileData();
  56034. isAssumeRoleProfile = (arg, { profile = "default", logger: logger2 } = {}) => {
  56035. return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger2 }) || isCredentialSourceProfile(arg, { profile, logger: logger2 }));
  56036. };
  56037. isAssumeRoleWithSourceProfile = (arg, { profile, logger: logger2 }) => {
  56038. const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined";
  56039. if (withSourceProfile) {
  56040. logger2?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);
  56041. }
  56042. return withSourceProfile;
  56043. };
  56044. isCredentialSourceProfile = (arg, { profile, logger: logger2 }) => {
  56045. const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined";
  56046. if (withProviderProfile) {
  56047. logger2?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);
  56048. }
  56049. return withProviderProfile;
  56050. };
  56051. resolveAssumeRoleCredentials = async (profileName, profiles, options, visitedProfiles = {}) => {
  56052. options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");
  56053. const profileData = profiles[profileName];
  56054. const { source_profile, region } = profileData;
  56055. if (!options.roleAssumer) {
  56056. const { getDefaultRoleAssumer: getDefaultRoleAssumer3 } = await Promise.resolve().then(() => (init_sts(), sts_exports));
  56057. options.roleAssumer = getDefaultRoleAssumer3({
  56058. ...options.clientConfig,
  56059. credentialProviderLogger: options.logger,
  56060. parentClientConfig: {
  56061. ...options?.parentClientConfig,
  56062. region: region ?? options?.parentClientConfig?.region
  56063. }
  56064. }, options.clientPlugins);
  56065. }
  56066. if (source_profile && source_profile in visitedProfiles) {
  56067. throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${getProfileName(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), { logger: options.logger });
  56068. }
  56069. options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);
  56070. const sourceCredsProvider = source_profile ? resolveProfileData(source_profile, profiles, options, {
  56071. ...visitedProfiles,
  56072. [source_profile]: true
  56073. }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();
  56074. if (isCredentialSourceWithoutRoleArn(profileData)) {
  56075. return sourceCredsProvider.then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
  56076. } else {
  56077. const params = {
  56078. RoleArn: profileData.role_arn,
  56079. RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,
  56080. ExternalId: profileData.external_id,
  56081. DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10)
  56082. };
  56083. const { mfa_serial } = profileData;
  56084. if (mfa_serial) {
  56085. if (!options.mfaCodeProvider) {
  56086. throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false });
  56087. }
  56088. params.SerialNumber = mfa_serial;
  56089. params.TokenCode = await options.mfaCodeProvider(mfa_serial);
  56090. }
  56091. const sourceCreds = await sourceCredsProvider;
  56092. return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
  56093. }
  56094. };
  56095. isCredentialSourceWithoutRoleArn = (section) => {
  56096. return !section.role_arn && !!section.credential_source;
  56097. };
  56098. }
  56099. });
  56100. // ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js
  56101. var getValidatedProcessCredentials;
  56102. var init_getValidatedProcessCredentials = __esm({
  56103. "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js"() {
  56104. "use strict";
  56105. init_client2();
  56106. getValidatedProcessCredentials = (profileName, data, profiles) => {
  56107. if (data.Version !== 1) {
  56108. throw Error(`Profile ${profileName} credential_process did not return Version 1.`);
  56109. }
  56110. if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) {
  56111. throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);
  56112. }
  56113. if (data.Expiration) {
  56114. const currentTime = /* @__PURE__ */ new Date();
  56115. const expireTime = new Date(data.Expiration);
  56116. if (expireTime < currentTime) {
  56117. throw Error(`Profile ${profileName} credential_process returned expired credentials.`);
  56118. }
  56119. }
  56120. let accountId = data.AccountId;
  56121. if (!accountId && profiles?.[profileName]?.aws_account_id) {
  56122. accountId = profiles[profileName].aws_account_id;
  56123. }
  56124. const credentials2 = {
  56125. accessKeyId: data.AccessKeyId,
  56126. secretAccessKey: data.SecretAccessKey,
  56127. ...data.SessionToken && { sessionToken: data.SessionToken },
  56128. ...data.Expiration && { expiration: new Date(data.Expiration) },
  56129. ...data.CredentialScope && { credentialScope: data.CredentialScope },
  56130. ...accountId && { accountId }
  56131. };
  56132. setCredentialFeature(credentials2, "CREDENTIALS_PROCESS", "w");
  56133. return credentials2;
  56134. };
  56135. }
  56136. });
  56137. // ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js
  56138. import { exec as exec2 } from "child_process";
  56139. import { promisify as promisify2 } from "util";
  56140. var resolveProcessCredentials;
  56141. var init_resolveProcessCredentials = __esm({
  56142. "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js"() {
  56143. "use strict";
  56144. init_dist_es21();
  56145. init_getValidatedProcessCredentials();
  56146. resolveProcessCredentials = async (profileName, profiles, logger2) => {
  56147. const profile = profiles[profileName];
  56148. if (profiles[profileName]) {
  56149. const credentialProcess = profile["credential_process"];
  56150. if (credentialProcess !== void 0) {
  56151. const execPromise = promisify2(exec2);
  56152. try {
  56153. const { stdout } = await execPromise(credentialProcess);
  56154. let data;
  56155. try {
  56156. data = JSON.parse(stdout.trim());
  56157. } catch {
  56158. throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);
  56159. }
  56160. return getValidatedProcessCredentials(profileName, data, profiles);
  56161. } catch (error2) {
  56162. throw new CredentialsProviderError(error2.message, { logger: logger2 });
  56163. }
  56164. } else {
  56165. throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger: logger2 });
  56166. }
  56167. } else {
  56168. throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {
  56169. logger: logger2
  56170. });
  56171. }
  56172. };
  56173. }
  56174. });
  56175. // ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js
  56176. var fromProcess;
  56177. var init_fromProcess = __esm({
  56178. "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js"() {
  56179. "use strict";
  56180. init_dist_es30();
  56181. init_resolveProcessCredentials();
  56182. fromProcess = (init2 = {}) => async ({ callerClientConfig } = {}) => {
  56183. init2.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");
  56184. const profiles = await parseKnownFiles(init2);
  56185. return resolveProcessCredentials(getProfileName({
  56186. profile: init2.profile ?? callerClientConfig?.profile
  56187. }), profiles, init2.logger);
  56188. };
  56189. }
  56190. });
  56191. // ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/index.js
  56192. var dist_es_exports5 = {};
  56193. __export(dist_es_exports5, {
  56194. fromProcess: () => fromProcess
  56195. });
  56196. var init_dist_es49 = __esm({
  56197. "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-es/index.js"() {
  56198. "use strict";
  56199. init_fromProcess();
  56200. }
  56201. });
  56202. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js
  56203. var isProcessProfile, resolveProcessCredentials2;
  56204. var init_resolveProcessCredentials2 = __esm({
  56205. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js"() {
  56206. "use strict";
  56207. init_client2();
  56208. isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string";
  56209. resolveProcessCredentials2 = async (options, profile) => Promise.resolve().then(() => (init_dist_es49(), dist_es_exports5)).then(({ fromProcess: fromProcess2 }) => fromProcess2({
  56210. ...options,
  56211. profile
  56212. })().then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v")));
  56213. }
  56214. });
  56215. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js
  56216. var resolveSsoCredentials, isSsoProfile2;
  56217. var init_resolveSsoCredentials = __esm({
  56218. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js"() {
  56219. "use strict";
  56220. init_client2();
  56221. resolveSsoCredentials = async (profile, profileData, options = {}) => {
  56222. const { fromSSO: fromSSO2 } = await Promise.resolve().then(() => (init_dist_es48(), dist_es_exports4));
  56223. return fromSSO2({
  56224. profile,
  56225. logger: options.logger,
  56226. parentClientConfig: options.parentClientConfig,
  56227. clientConfig: options.clientConfig
  56228. })().then((creds) => {
  56229. if (profileData.sso_session) {
  56230. return setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r");
  56231. } else {
  56232. return setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t");
  56233. }
  56234. });
  56235. };
  56236. isSsoProfile2 = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string");
  56237. }
  56238. });
  56239. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js
  56240. var isStaticCredsProfile, resolveStaticCredentials;
  56241. var init_resolveStaticCredentials = __esm({
  56242. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js"() {
  56243. "use strict";
  56244. init_client2();
  56245. isStaticCredsProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1;
  56246. resolveStaticCredentials = async (profile, options) => {
  56247. options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");
  56248. const credentials2 = {
  56249. accessKeyId: profile.aws_access_key_id,
  56250. secretAccessKey: profile.aws_secret_access_key,
  56251. sessionToken: profile.aws_session_token,
  56252. ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope },
  56253. ...profile.aws_account_id && { accountId: profile.aws_account_id }
  56254. };
  56255. return setCredentialFeature(credentials2, "CREDENTIALS_PROFILE", "n");
  56256. };
  56257. }
  56258. });
  56259. // ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js
  56260. var fromWebToken;
  56261. var init_fromWebToken = __esm({
  56262. "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js"() {
  56263. "use strict";
  56264. fromWebToken = (init2) => async (awsIdentityProperties) => {
  56265. init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");
  56266. const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy: policy5, durationSeconds } = init2;
  56267. let { roleAssumerWithWebIdentity } = init2;
  56268. if (!roleAssumerWithWebIdentity) {
  56269. const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => (init_sts(), sts_exports));
  56270. roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({
  56271. ...init2.clientConfig,
  56272. credentialProviderLogger: init2.logger,
  56273. parentClientConfig: {
  56274. ...awsIdentityProperties?.callerClientConfig,
  56275. ...init2.parentClientConfig
  56276. }
  56277. }, init2.clientPlugins);
  56278. }
  56279. return roleAssumerWithWebIdentity({
  56280. RoleArn: roleArn,
  56281. RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,
  56282. WebIdentityToken: webIdentityToken,
  56283. ProviderId: providerId,
  56284. PolicyArns: policyArns,
  56285. Policy: policy5,
  56286. DurationSeconds: durationSeconds
  56287. });
  56288. };
  56289. }
  56290. });
  56291. // ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js
  56292. import { readFileSync } from "fs";
  56293. var ENV_TOKEN_FILE, ENV_ROLE_ARN, ENV_ROLE_SESSION_NAME, fromTokenFile;
  56294. var init_fromTokenFile = __esm({
  56295. "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js"() {
  56296. "use strict";
  56297. init_client2();
  56298. init_dist_es21();
  56299. init_fromWebToken();
  56300. ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
  56301. ENV_ROLE_ARN = "AWS_ROLE_ARN";
  56302. ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";
  56303. fromTokenFile = (init2 = {}) => async () => {
  56304. init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
  56305. const webIdentityTokenFile = init2?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];
  56306. const roleArn = init2?.roleArn ?? process.env[ENV_ROLE_ARN];
  56307. const roleSessionName = init2?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];
  56308. if (!webIdentityTokenFile || !roleArn) {
  56309. throw new CredentialsProviderError("Web identity configuration not specified", {
  56310. logger: init2.logger
  56311. });
  56312. }
  56313. const credentials2 = await fromWebToken({
  56314. ...init2,
  56315. webIdentityToken: readFileSync(webIdentityTokenFile, { encoding: "ascii" }),
  56316. roleArn,
  56317. roleSessionName
  56318. })();
  56319. if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
  56320. setCredentialFeature(credentials2, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
  56321. }
  56322. return credentials2;
  56323. };
  56324. }
  56325. });
  56326. // ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js
  56327. var dist_es_exports6 = {};
  56328. __export(dist_es_exports6, {
  56329. fromTokenFile: () => fromTokenFile,
  56330. fromWebToken: () => fromWebToken
  56331. });
  56332. var init_dist_es50 = __esm({
  56333. "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js"() {
  56334. "use strict";
  56335. init_fromTokenFile();
  56336. init_fromWebToken();
  56337. }
  56338. });
  56339. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js
  56340. var isWebIdentityProfile, resolveWebIdentityCredentials;
  56341. var init_resolveWebIdentityCredentials = __esm({
  56342. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js"() {
  56343. "use strict";
  56344. init_client2();
  56345. isWebIdentityProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1;
  56346. resolveWebIdentityCredentials = async (profile, options) => Promise.resolve().then(() => (init_dist_es50(), dist_es_exports6)).then(({ fromTokenFile: fromTokenFile2 }) => fromTokenFile2({
  56347. webIdentityTokenFile: profile.web_identity_token_file,
  56348. roleArn: profile.role_arn,
  56349. roleSessionName: profile.role_session_name,
  56350. roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,
  56351. logger: options.logger,
  56352. parentClientConfig: options.parentClientConfig
  56353. })().then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")));
  56354. }
  56355. });
  56356. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js
  56357. var resolveProfileData;
  56358. var init_resolveProfileData = __esm({
  56359. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js"() {
  56360. "use strict";
  56361. init_dist_es21();
  56362. init_resolveAssumeRoleCredentials();
  56363. init_resolveProcessCredentials2();
  56364. init_resolveSsoCredentials();
  56365. init_resolveStaticCredentials();
  56366. init_resolveWebIdentityCredentials();
  56367. resolveProfileData = async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {
  56368. const data = profiles[profileName];
  56369. if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {
  56370. return resolveStaticCredentials(data, options);
  56371. }
  56372. if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {
  56373. return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles);
  56374. }
  56375. if (isStaticCredsProfile(data)) {
  56376. return resolveStaticCredentials(data, options);
  56377. }
  56378. if (isWebIdentityProfile(data)) {
  56379. return resolveWebIdentityCredentials(data, options);
  56380. }
  56381. if (isProcessProfile(data)) {
  56382. return resolveProcessCredentials2(options, profileName);
  56383. }
  56384. if (isSsoProfile2(data)) {
  56385. return await resolveSsoCredentials(profileName, data, options);
  56386. }
  56387. throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger });
  56388. };
  56389. }
  56390. });
  56391. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js
  56392. var fromIni;
  56393. var init_fromIni = __esm({
  56394. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js"() {
  56395. "use strict";
  56396. init_dist_es30();
  56397. init_resolveProfileData();
  56398. fromIni = (_init2 = {}) => async ({ callerClientConfig } = {}) => {
  56399. const init2 = {
  56400. ..._init2,
  56401. parentClientConfig: {
  56402. ...callerClientConfig,
  56403. ..._init2.parentClientConfig
  56404. }
  56405. };
  56406. init2.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");
  56407. const profiles = await parseKnownFiles(init2);
  56408. return resolveProfileData(getProfileName({
  56409. profile: _init2.profile ?? callerClientConfig?.profile
  56410. }), profiles, init2);
  56411. };
  56412. }
  56413. });
  56414. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js
  56415. var dist_es_exports7 = {};
  56416. __export(dist_es_exports7, {
  56417. fromIni: () => fromIni
  56418. });
  56419. var init_dist_es51 = __esm({
  56420. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js"() {
  56421. "use strict";
  56422. init_fromIni();
  56423. }
  56424. });
  56425. // ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js
  56426. var multipleCredentialSourceWarningEmitted, defaultProvider, credentialsWillNeedRefresh, credentialsTreatedAsExpired;
  56427. var init_defaultProvider = __esm({
  56428. "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js"() {
  56429. "use strict";
  56430. init_dist_es38();
  56431. init_dist_es21();
  56432. init_dist_es30();
  56433. init_remoteProvider();
  56434. multipleCredentialSourceWarningEmitted = false;
  56435. defaultProvider = (init2 = {}) => memoize(chain(async () => {
  56436. const profile = init2.profile ?? process.env[ENV_PROFILE];
  56437. if (profile) {
  56438. const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET];
  56439. if (envStaticCredentialsAreSet) {
  56440. if (!multipleCredentialSourceWarningEmitted) {
  56441. const warnFn = init2.logger?.warn && init2.logger?.constructor?.name !== "NoOpLogger" ? init2.logger.warn : console.warn;
  56442. warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
  56443. Multiple credential sources detected:
  56444. Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
  56445. This SDK will proceed with the AWS_PROFILE value.
  56446. However, a future version may change this behavior to prefer the ENV static credentials.
  56447. Please ensure that your environment only sets either the AWS_PROFILE or the
  56448. AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
  56449. `);
  56450. multipleCredentialSourceWarningEmitted = true;
  56451. }
  56452. }
  56453. throw new CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
  56454. logger: init2.logger,
  56455. tryNextLink: true
  56456. });
  56457. }
  56458. init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
  56459. return fromEnv2(init2)();
  56460. }, async () => {
  56461. init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
  56462. const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
  56463. if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
  56464. throw new CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init2.logger });
  56465. }
  56466. const { fromSSO: fromSSO2 } = await Promise.resolve().then(() => (init_dist_es48(), dist_es_exports4));
  56467. return fromSSO2(init2)();
  56468. }, async () => {
  56469. init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
  56470. const { fromIni: fromIni2 } = await Promise.resolve().then(() => (init_dist_es51(), dist_es_exports7));
  56471. return fromIni2(init2)();
  56472. }, async () => {
  56473. init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
  56474. const { fromProcess: fromProcess2 } = await Promise.resolve().then(() => (init_dist_es49(), dist_es_exports5));
  56475. return fromProcess2(init2)();
  56476. }, async () => {
  56477. init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
  56478. const { fromTokenFile: fromTokenFile2 } = await Promise.resolve().then(() => (init_dist_es50(), dist_es_exports6));
  56479. return fromTokenFile2(init2)();
  56480. }, async () => {
  56481. init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
  56482. return (await remoteProvider(init2))();
  56483. }, async () => {
  56484. throw new CredentialsProviderError("Could not load credentials from any providers", {
  56485. tryNextLink: false,
  56486. logger: init2.logger
  56487. });
  56488. }), credentialsTreatedAsExpired, credentialsWillNeedRefresh);
  56489. credentialsWillNeedRefresh = (credentials2) => credentials2?.expiration !== void 0;
  56490. credentialsTreatedAsExpired = (credentials2) => credentials2?.expiration !== void 0 && credentials2.expiration.getTime() - Date.now() < 3e5;
  56491. }
  56492. });
  56493. // ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/index.js
  56494. var init_dist_es52 = __esm({
  56495. "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-es/index.js"() {
  56496. "use strict";
  56497. init_defaultProvider();
  56498. }
  56499. });
  56500. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/ruleset.js
  56501. var s5, t5, u4, v5, a4, b4, c4, d4, e5, f6, g4, h5, i5, j4, k4, l4, m5, n4, o4, p4, q4, r5, _data4, ruleSet4;
  56502. var init_ruleset4 = __esm({
  56503. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/ruleset.js"() {
  56504. "use strict";
  56505. s5 = "required";
  56506. t5 = "fn";
  56507. u4 = "argv";
  56508. v5 = "ref";
  56509. a4 = true;
  56510. b4 = "isSet";
  56511. c4 = "booleanEquals";
  56512. d4 = "error";
  56513. e5 = "endpoint";
  56514. f6 = "tree";
  56515. g4 = "PartitionResult";
  56516. h5 = { [s5]: false, "type": "String" };
  56517. i5 = { [s5]: true, "default": false, "type": "Boolean" };
  56518. j4 = { [v5]: "Endpoint" };
  56519. k4 = { [t5]: c4, [u4]: [{ [v5]: "UseFIPS" }, true] };
  56520. l4 = { [t5]: c4, [u4]: [{ [v5]: "UseDualStack" }, true] };
  56521. m5 = {};
  56522. n4 = { [t5]: "getAttr", [u4]: [{ [v5]: g4 }, "supportsFIPS"] };
  56523. o4 = { [t5]: c4, [u4]: [true, { [t5]: "getAttr", [u4]: [{ [v5]: g4 }, "supportsDualStack"] }] };
  56524. p4 = [k4];
  56525. q4 = [l4];
  56526. r5 = [{ [v5]: "Region" }];
  56527. _data4 = { version: "1.0", parameters: { Region: h5, UseDualStack: i5, UseFIPS: i5, Endpoint: h5 }, rules: [{ conditions: [{ [t5]: b4, [u4]: [j4] }], rules: [{ conditions: p4, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d4 }, { conditions: q4, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d4 }, { endpoint: { url: j4, properties: m5, headers: m5 }, type: e5 }], type: f6 }, { conditions: [{ [t5]: b4, [u4]: r5 }], rules: [{ conditions: [{ [t5]: "aws.partition", [u4]: r5, assign: g4 }], rules: [{ conditions: [k4, l4], rules: [{ conditions: [{ [t5]: c4, [u4]: [a4, n4] }, o4], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m5, headers: m5 }, type: e5 }], type: f6 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d4 }], type: f6 }, { conditions: p4, rules: [{ conditions: [{ [t5]: c4, [u4]: [n4, a4] }], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m5, headers: m5 }, type: e5 }], type: f6 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d4 }], type: f6 }, { conditions: q4, rules: [{ conditions: [o4], rules: [{ endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m5, headers: m5 }, type: e5 }], type: f6 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d4 }], type: f6 }, { endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dnsSuffix}", properties: m5, headers: m5 }, type: e5 }], type: f6 }], type: f6 }, { error: "Invalid Configuration: Missing Region", type: d4 }] };
  56528. ruleSet4 = _data4;
  56529. }
  56530. });
  56531. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/endpointResolver.js
  56532. var cache4, defaultEndpointResolver4;
  56533. var init_endpointResolver4 = __esm({
  56534. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/endpoint/endpointResolver.js"() {
  56535. "use strict";
  56536. init_dist_es20();
  56537. init_dist_es19();
  56538. init_ruleset4();
  56539. cache4 = new EndpointCache({
  56540. size: 50,
  56541. params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
  56542. });
  56543. defaultEndpointResolver4 = (endpointParams, context = {}) => {
  56544. return cache4.get(endpointParams, () => resolveEndpoint(ruleSet4, {
  56545. endpointParams,
  56546. logger: context.logger
  56547. }));
  56548. };
  56549. customEndpointFunctions.aws = awsEndpointFunctions;
  56550. }
  56551. });
  56552. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeConfig.shared.js
  56553. var getRuntimeConfig7;
  56554. var init_runtimeConfig_shared4 = __esm({
  56555. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeConfig.shared.js"() {
  56556. "use strict";
  56557. init_dist_es25();
  56558. init_dist_es24();
  56559. init_dist_es33();
  56560. init_dist_es11();
  56561. init_dist_es10();
  56562. init_httpAuthSchemeProvider();
  56563. init_endpointResolver4();
  56564. getRuntimeConfig7 = (config) => {
  56565. return {
  56566. apiVersion: "2018-08-01",
  56567. base64Decoder: config?.base64Decoder ?? fromBase64,
  56568. base64Encoder: config?.base64Encoder ?? toBase64,
  56569. disableHostPrefix: config?.disableHostPrefix ?? false,
  56570. endpointProvider: config?.endpointProvider ?? defaultEndpointResolver4,
  56571. extensions: config?.extensions ?? [],
  56572. httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultRDSDataHttpAuthSchemeProvider,
  56573. httpAuthSchemes: config?.httpAuthSchemes ?? [
  56574. {
  56575. schemeId: "aws.auth#sigv4",
  56576. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
  56577. signer: new AwsSdkSigV4Signer()
  56578. }
  56579. ],
  56580. logger: config?.logger ?? new NoOpLogger(),
  56581. serviceId: config?.serviceId ?? "RDS Data",
  56582. urlParser: config?.urlParser ?? parseUrl,
  56583. utf8Decoder: config?.utf8Decoder ?? fromUtf8,
  56584. utf8Encoder: config?.utf8Encoder ?? toUtf8
  56585. };
  56586. };
  56587. }
  56588. });
  56589. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeConfig.js
  56590. var getRuntimeConfig8;
  56591. var init_runtimeConfig4 = __esm({
  56592. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeConfig.js"() {
  56593. "use strict";
  56594. init_package();
  56595. init_dist_es25();
  56596. init_dist_es52();
  56597. init_dist_es41();
  56598. init_dist_es28();
  56599. init_dist_es42();
  56600. init_dist_es37();
  56601. init_dist_es31();
  56602. init_dist_es14();
  56603. init_dist_es43();
  56604. init_dist_es36();
  56605. init_runtimeConfig_shared4();
  56606. init_dist_es24();
  56607. init_dist_es44();
  56608. init_dist_es24();
  56609. getRuntimeConfig8 = (config) => {
  56610. emitWarningIfUnsupportedVersion2(process.version);
  56611. const defaultsMode = resolveDefaultsModeConfig(config);
  56612. const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
  56613. const clientSharedValues = getRuntimeConfig7(config);
  56614. emitWarningIfUnsupportedVersion(process.version);
  56615. const loaderConfig = {
  56616. profile: config?.profile,
  56617. logger: clientSharedValues.logger
  56618. };
  56619. return {
  56620. ...clientSharedValues,
  56621. ...config,
  56622. runtime: "node",
  56623. defaultsMode,
  56624. authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
  56625. bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
  56626. credentialDefaultProvider: config?.credentialDefaultProvider ?? defaultProvider,
  56627. defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
  56628. maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
  56629. region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
  56630. requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
  56631. retryMode: config?.retryMode ?? loadConfig({
  56632. ...NODE_RETRY_MODE_CONFIG_OPTIONS,
  56633. default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE
  56634. }, config),
  56635. sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
  56636. streamCollector: config?.streamCollector ?? streamCollector,
  56637. useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  56638. useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  56639. userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
  56640. };
  56641. };
  56642. }
  56643. });
  56644. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthExtensionConfiguration.js
  56645. var getHttpAuthExtensionConfiguration4, resolveHttpAuthRuntimeConfig4;
  56646. var init_httpAuthExtensionConfiguration4 = __esm({
  56647. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/auth/httpAuthExtensionConfiguration.js"() {
  56648. "use strict";
  56649. getHttpAuthExtensionConfiguration4 = (runtimeConfig) => {
  56650. const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
  56651. let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
  56652. let _credentials = runtimeConfig.credentials;
  56653. return {
  56654. setHttpAuthScheme(httpAuthScheme) {
  56655. const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
  56656. if (index6 === -1) {
  56657. _httpAuthSchemes.push(httpAuthScheme);
  56658. } else {
  56659. _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
  56660. }
  56661. },
  56662. httpAuthSchemes() {
  56663. return _httpAuthSchemes;
  56664. },
  56665. setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
  56666. _httpAuthSchemeProvider = httpAuthSchemeProvider;
  56667. },
  56668. httpAuthSchemeProvider() {
  56669. return _httpAuthSchemeProvider;
  56670. },
  56671. setCredentials(credentials2) {
  56672. _credentials = credentials2;
  56673. },
  56674. credentials() {
  56675. return _credentials;
  56676. }
  56677. };
  56678. };
  56679. resolveHttpAuthRuntimeConfig4 = (config) => {
  56680. return {
  56681. httpAuthSchemes: config.httpAuthSchemes(),
  56682. httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
  56683. credentials: config.credentials()
  56684. };
  56685. };
  56686. }
  56687. });
  56688. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeExtensions.js
  56689. var resolveRuntimeExtensions4;
  56690. var init_runtimeExtensions4 = __esm({
  56691. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/runtimeExtensions.js"() {
  56692. "use strict";
  56693. init_dist_es45();
  56694. init_dist_es2();
  56695. init_dist_es24();
  56696. init_httpAuthExtensionConfiguration4();
  56697. resolveRuntimeExtensions4 = (runtimeConfig, extensions) => {
  56698. const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration4(runtimeConfig));
  56699. extensions.forEach((extension) => extension.configure(extensionConfiguration));
  56700. return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig4(extensionConfiguration));
  56701. };
  56702. }
  56703. });
  56704. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/RDSDataClient.js
  56705. var RDSDataClient;
  56706. var init_RDSDataClient = __esm({
  56707. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/RDSDataClient.js"() {
  56708. "use strict";
  56709. init_dist_es3();
  56710. init_dist_es4();
  56711. init_dist_es5();
  56712. init_dist_es26();
  56713. init_dist_es28();
  56714. init_dist_es18();
  56715. init_dist_es29();
  56716. init_dist_es34();
  56717. init_dist_es37();
  56718. init_dist_es24();
  56719. init_httpAuthSchemeProvider();
  56720. init_EndpointParameters();
  56721. init_runtimeConfig4();
  56722. init_runtimeExtensions4();
  56723. RDSDataClient = class extends Client {
  56724. constructor(...[configuration]) {
  56725. const _config_0 = getRuntimeConfig8(configuration || {});
  56726. super(_config_0);
  56727. __publicField(this, "config");
  56728. this.initConfig = _config_0;
  56729. const _config_1 = resolveClientEndpointParameters(_config_0);
  56730. const _config_2 = resolveUserAgentConfig(_config_1);
  56731. const _config_3 = resolveRetryConfig(_config_2);
  56732. const _config_4 = resolveRegionConfig(_config_3);
  56733. const _config_5 = resolveHostHeaderConfig(_config_4);
  56734. const _config_6 = resolveEndpointConfig(_config_5);
  56735. const _config_7 = resolveHttpAuthSchemeConfig(_config_6);
  56736. const _config_8 = resolveRuntimeExtensions4(_config_7, configuration?.extensions || []);
  56737. this.config = _config_8;
  56738. this.middlewareStack.use(getUserAgentPlugin(this.config));
  56739. this.middlewareStack.use(getRetryPlugin(this.config));
  56740. this.middlewareStack.use(getContentLengthPlugin(this.config));
  56741. this.middlewareStack.use(getHostHeaderPlugin(this.config));
  56742. this.middlewareStack.use(getLoggerPlugin(this.config));
  56743. this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
  56744. this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
  56745. httpAuthSchemeParametersProvider: defaultRDSDataHttpAuthSchemeParametersProvider,
  56746. identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
  56747. "aws.auth#sigv4": config.credentials
  56748. })
  56749. }));
  56750. this.middlewareStack.use(getHttpSigningPlugin(this.config));
  56751. }
  56752. destroy() {
  56753. super.destroy();
  56754. }
  56755. };
  56756. }
  56757. });
  56758. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/RDSDataServiceException.js
  56759. var RDSDataServiceException;
  56760. var init_RDSDataServiceException = __esm({
  56761. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/RDSDataServiceException.js"() {
  56762. "use strict";
  56763. init_dist_es24();
  56764. RDSDataServiceException = class _RDSDataServiceException extends ServiceException {
  56765. constructor(options) {
  56766. super(options);
  56767. Object.setPrototypeOf(this, _RDSDataServiceException.prototype);
  56768. }
  56769. };
  56770. }
  56771. });
  56772. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/models_0.js
  56773. var AccessDeniedException2, BadRequestException, TypeHint, DatabaseErrorException, DatabaseNotFoundException, DatabaseResumingException, DatabaseUnavailableException, ForbiddenException, HttpEndpointNotEnabledException, InternalServerErrorException, InvalidResourceStateException, InvalidSecretException, SecretsErrorException, ServiceUnavailableError, StatementTimeoutException, TransactionNotFoundException, NotFoundException, DecimalReturnType, RecordsFormatType, LongReturnType, UnsupportedResultException, ArrayValue, Field, Value;
  56774. var init_models_04 = __esm({
  56775. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/models_0.js"() {
  56776. "use strict";
  56777. init_RDSDataServiceException();
  56778. AccessDeniedException2 = class _AccessDeniedException extends RDSDataServiceException {
  56779. constructor(opts) {
  56780. super({
  56781. name: "AccessDeniedException",
  56782. $fault: "client",
  56783. ...opts
  56784. });
  56785. __publicField(this, "name", "AccessDeniedException");
  56786. __publicField(this, "$fault", "client");
  56787. Object.setPrototypeOf(this, _AccessDeniedException.prototype);
  56788. }
  56789. };
  56790. BadRequestException = class _BadRequestException extends RDSDataServiceException {
  56791. constructor(opts) {
  56792. super({
  56793. name: "BadRequestException",
  56794. $fault: "client",
  56795. ...opts
  56796. });
  56797. __publicField(this, "name", "BadRequestException");
  56798. __publicField(this, "$fault", "client");
  56799. Object.setPrototypeOf(this, _BadRequestException.prototype);
  56800. }
  56801. };
  56802. TypeHint = {
  56803. DATE: "DATE",
  56804. DECIMAL: "DECIMAL",
  56805. JSON: "JSON",
  56806. TIME: "TIME",
  56807. TIMESTAMP: "TIMESTAMP",
  56808. UUID: "UUID"
  56809. };
  56810. DatabaseErrorException = class _DatabaseErrorException extends RDSDataServiceException {
  56811. constructor(opts) {
  56812. super({
  56813. name: "DatabaseErrorException",
  56814. $fault: "client",
  56815. ...opts
  56816. });
  56817. __publicField(this, "name", "DatabaseErrorException");
  56818. __publicField(this, "$fault", "client");
  56819. Object.setPrototypeOf(this, _DatabaseErrorException.prototype);
  56820. }
  56821. };
  56822. DatabaseNotFoundException = class _DatabaseNotFoundException extends RDSDataServiceException {
  56823. constructor(opts) {
  56824. super({
  56825. name: "DatabaseNotFoundException",
  56826. $fault: "client",
  56827. ...opts
  56828. });
  56829. __publicField(this, "name", "DatabaseNotFoundException");
  56830. __publicField(this, "$fault", "client");
  56831. Object.setPrototypeOf(this, _DatabaseNotFoundException.prototype);
  56832. }
  56833. };
  56834. DatabaseResumingException = class _DatabaseResumingException extends RDSDataServiceException {
  56835. constructor(opts) {
  56836. super({
  56837. name: "DatabaseResumingException",
  56838. $fault: "client",
  56839. ...opts
  56840. });
  56841. __publicField(this, "name", "DatabaseResumingException");
  56842. __publicField(this, "$fault", "client");
  56843. Object.setPrototypeOf(this, _DatabaseResumingException.prototype);
  56844. }
  56845. };
  56846. DatabaseUnavailableException = class _DatabaseUnavailableException extends RDSDataServiceException {
  56847. constructor(opts) {
  56848. super({
  56849. name: "DatabaseUnavailableException",
  56850. $fault: "server",
  56851. ...opts
  56852. });
  56853. __publicField(this, "name", "DatabaseUnavailableException");
  56854. __publicField(this, "$fault", "server");
  56855. Object.setPrototypeOf(this, _DatabaseUnavailableException.prototype);
  56856. }
  56857. };
  56858. ForbiddenException = class _ForbiddenException extends RDSDataServiceException {
  56859. constructor(opts) {
  56860. super({
  56861. name: "ForbiddenException",
  56862. $fault: "client",
  56863. ...opts
  56864. });
  56865. __publicField(this, "name", "ForbiddenException");
  56866. __publicField(this, "$fault", "client");
  56867. Object.setPrototypeOf(this, _ForbiddenException.prototype);
  56868. }
  56869. };
  56870. HttpEndpointNotEnabledException = class _HttpEndpointNotEnabledException extends RDSDataServiceException {
  56871. constructor(opts) {
  56872. super({
  56873. name: "HttpEndpointNotEnabledException",
  56874. $fault: "client",
  56875. ...opts
  56876. });
  56877. __publicField(this, "name", "HttpEndpointNotEnabledException");
  56878. __publicField(this, "$fault", "client");
  56879. Object.setPrototypeOf(this, _HttpEndpointNotEnabledException.prototype);
  56880. }
  56881. };
  56882. InternalServerErrorException = class _InternalServerErrorException extends RDSDataServiceException {
  56883. constructor(opts) {
  56884. super({
  56885. name: "InternalServerErrorException",
  56886. $fault: "server",
  56887. ...opts
  56888. });
  56889. __publicField(this, "name", "InternalServerErrorException");
  56890. __publicField(this, "$fault", "server");
  56891. Object.setPrototypeOf(this, _InternalServerErrorException.prototype);
  56892. }
  56893. };
  56894. InvalidResourceStateException = class _InvalidResourceStateException extends RDSDataServiceException {
  56895. constructor(opts) {
  56896. super({
  56897. name: "InvalidResourceStateException",
  56898. $fault: "client",
  56899. ...opts
  56900. });
  56901. __publicField(this, "name", "InvalidResourceStateException");
  56902. __publicField(this, "$fault", "client");
  56903. Object.setPrototypeOf(this, _InvalidResourceStateException.prototype);
  56904. }
  56905. };
  56906. InvalidSecretException = class _InvalidSecretException extends RDSDataServiceException {
  56907. constructor(opts) {
  56908. super({
  56909. name: "InvalidSecretException",
  56910. $fault: "client",
  56911. ...opts
  56912. });
  56913. __publicField(this, "name", "InvalidSecretException");
  56914. __publicField(this, "$fault", "client");
  56915. Object.setPrototypeOf(this, _InvalidSecretException.prototype);
  56916. }
  56917. };
  56918. SecretsErrorException = class _SecretsErrorException extends RDSDataServiceException {
  56919. constructor(opts) {
  56920. super({
  56921. name: "SecretsErrorException",
  56922. $fault: "client",
  56923. ...opts
  56924. });
  56925. __publicField(this, "name", "SecretsErrorException");
  56926. __publicField(this, "$fault", "client");
  56927. Object.setPrototypeOf(this, _SecretsErrorException.prototype);
  56928. }
  56929. };
  56930. ServiceUnavailableError = class _ServiceUnavailableError extends RDSDataServiceException {
  56931. constructor(opts) {
  56932. super({
  56933. name: "ServiceUnavailableError",
  56934. $fault: "server",
  56935. ...opts
  56936. });
  56937. __publicField(this, "name", "ServiceUnavailableError");
  56938. __publicField(this, "$fault", "server");
  56939. Object.setPrototypeOf(this, _ServiceUnavailableError.prototype);
  56940. }
  56941. };
  56942. StatementTimeoutException = class _StatementTimeoutException extends RDSDataServiceException {
  56943. constructor(opts) {
  56944. super({
  56945. name: "StatementTimeoutException",
  56946. $fault: "client",
  56947. ...opts
  56948. });
  56949. __publicField(this, "name", "StatementTimeoutException");
  56950. __publicField(this, "$fault", "client");
  56951. __publicField(this, "dbConnectionId");
  56952. Object.setPrototypeOf(this, _StatementTimeoutException.prototype);
  56953. this.dbConnectionId = opts.dbConnectionId;
  56954. }
  56955. };
  56956. TransactionNotFoundException = class _TransactionNotFoundException extends RDSDataServiceException {
  56957. constructor(opts) {
  56958. super({
  56959. name: "TransactionNotFoundException",
  56960. $fault: "client",
  56961. ...opts
  56962. });
  56963. __publicField(this, "name", "TransactionNotFoundException");
  56964. __publicField(this, "$fault", "client");
  56965. Object.setPrototypeOf(this, _TransactionNotFoundException.prototype);
  56966. }
  56967. };
  56968. NotFoundException = class _NotFoundException extends RDSDataServiceException {
  56969. constructor(opts) {
  56970. super({
  56971. name: "NotFoundException",
  56972. $fault: "client",
  56973. ...opts
  56974. });
  56975. __publicField(this, "name", "NotFoundException");
  56976. __publicField(this, "$fault", "client");
  56977. Object.setPrototypeOf(this, _NotFoundException.prototype);
  56978. }
  56979. };
  56980. DecimalReturnType = {
  56981. DOUBLE_OR_LONG: "DOUBLE_OR_LONG",
  56982. STRING: "STRING"
  56983. };
  56984. RecordsFormatType = {
  56985. JSON: "JSON",
  56986. NONE: "NONE"
  56987. };
  56988. LongReturnType = {
  56989. LONG: "LONG",
  56990. STRING: "STRING"
  56991. };
  56992. UnsupportedResultException = class _UnsupportedResultException extends RDSDataServiceException {
  56993. constructor(opts) {
  56994. super({
  56995. name: "UnsupportedResultException",
  56996. $fault: "client",
  56997. ...opts
  56998. });
  56999. __publicField(this, "name", "UnsupportedResultException");
  57000. __publicField(this, "$fault", "client");
  57001. Object.setPrototypeOf(this, _UnsupportedResultException.prototype);
  57002. }
  57003. };
  57004. (function(ArrayValue2) {
  57005. ArrayValue2.visit = (value, visitor) => {
  57006. if (value.booleanValues !== void 0)
  57007. return visitor.booleanValues(value.booleanValues);
  57008. if (value.longValues !== void 0)
  57009. return visitor.longValues(value.longValues);
  57010. if (value.doubleValues !== void 0)
  57011. return visitor.doubleValues(value.doubleValues);
  57012. if (value.stringValues !== void 0)
  57013. return visitor.stringValues(value.stringValues);
  57014. if (value.arrayValues !== void 0)
  57015. return visitor.arrayValues(value.arrayValues);
  57016. return visitor._(value.$unknown[0], value.$unknown[1]);
  57017. };
  57018. })(ArrayValue || (ArrayValue = {}));
  57019. (function(Field2) {
  57020. Field2.visit = (value, visitor) => {
  57021. if (value.isNull !== void 0)
  57022. return visitor.isNull(value.isNull);
  57023. if (value.booleanValue !== void 0)
  57024. return visitor.booleanValue(value.booleanValue);
  57025. if (value.longValue !== void 0)
  57026. return visitor.longValue(value.longValue);
  57027. if (value.doubleValue !== void 0)
  57028. return visitor.doubleValue(value.doubleValue);
  57029. if (value.stringValue !== void 0)
  57030. return visitor.stringValue(value.stringValue);
  57031. if (value.blobValue !== void 0)
  57032. return visitor.blobValue(value.blobValue);
  57033. if (value.arrayValue !== void 0)
  57034. return visitor.arrayValue(value.arrayValue);
  57035. return visitor._(value.$unknown[0], value.$unknown[1]);
  57036. };
  57037. })(Field || (Field = {}));
  57038. (function(Value2) {
  57039. Value2.visit = (value, visitor) => {
  57040. if (value.isNull !== void 0)
  57041. return visitor.isNull(value.isNull);
  57042. if (value.bitValue !== void 0)
  57043. return visitor.bitValue(value.bitValue);
  57044. if (value.bigIntValue !== void 0)
  57045. return visitor.bigIntValue(value.bigIntValue);
  57046. if (value.intValue !== void 0)
  57047. return visitor.intValue(value.intValue);
  57048. if (value.doubleValue !== void 0)
  57049. return visitor.doubleValue(value.doubleValue);
  57050. if (value.realValue !== void 0)
  57051. return visitor.realValue(value.realValue);
  57052. if (value.stringValue !== void 0)
  57053. return visitor.stringValue(value.stringValue);
  57054. if (value.blobValue !== void 0)
  57055. return visitor.blobValue(value.blobValue);
  57056. if (value.arrayValues !== void 0)
  57057. return visitor.arrayValues(value.arrayValues);
  57058. if (value.structValue !== void 0)
  57059. return visitor.structValue(value.structValue);
  57060. return visitor._(value.$unknown[0], value.$unknown[1]);
  57061. };
  57062. })(Value || (Value = {}));
  57063. }
  57064. });
  57065. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/protocols/Aws_restJson1.js
  57066. var se_BatchExecuteStatementCommand, se_BeginTransactionCommand, se_CommitTransactionCommand, se_ExecuteSqlCommand, se_ExecuteStatementCommand, se_RollbackTransactionCommand, de_BatchExecuteStatementCommand, de_BeginTransactionCommand, de_CommitTransactionCommand, de_ExecuteSqlCommand, de_ExecuteStatementCommand, de_RollbackTransactionCommand, de_CommandError4, throwDefaultError5, de_AccessDeniedExceptionRes2, de_BadRequestExceptionRes, de_DatabaseErrorExceptionRes, de_DatabaseNotFoundExceptionRes, de_DatabaseResumingExceptionRes, de_DatabaseUnavailableExceptionRes, de_ForbiddenExceptionRes, de_HttpEndpointNotEnabledExceptionRes, de_InternalServerErrorExceptionRes, de_InvalidResourceStateExceptionRes, de_InvalidSecretExceptionRes, de_NotFoundExceptionRes, de_SecretsErrorExceptionRes, de_ServiceUnavailableErrorRes, de_StatementTimeoutExceptionRes, de_TransactionNotFoundExceptionRes, de_UnsupportedResultExceptionRes, se_ArrayOfArray, se_ArrayValue, se_DoubleArray, se_Field, se_SqlParameter, se_SqlParameterSets, se_SqlParametersList, de_ArrayOfArray, de_ArrayValue, de_ArrayValueList, de_DoubleArray, de_Field, de_FieldList, de__Record, de_Records, de_ResultFrame, de_Row, de_SqlRecords, de_SqlStatementResult, de_SqlStatementResults, de_StructValue, de_UpdateResult, de_UpdateResults, de_Value, deserializeMetadata5;
  57067. var init_Aws_restJson13 = __esm({
  57068. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/protocols/Aws_restJson1.js"() {
  57069. "use strict";
  57070. init_dist_es25();
  57071. init_dist_es18();
  57072. init_dist_es24();
  57073. init_models_04();
  57074. init_RDSDataServiceException();
  57075. se_BatchExecuteStatementCommand = async (input, context) => {
  57076. const b5 = requestBuilder(input, context);
  57077. const headers = {
  57078. "content-type": "application/json"
  57079. };
  57080. b5.bp("/BatchExecute");
  57081. let body;
  57082. body = JSON.stringify(take(input, {
  57083. database: [],
  57084. parameterSets: (_3) => se_SqlParameterSets(_3, context),
  57085. resourceArn: [],
  57086. schema: [],
  57087. secretArn: [],
  57088. sql: [],
  57089. transactionId: []
  57090. }));
  57091. b5.m("POST").h(headers).b(body);
  57092. return b5.build();
  57093. };
  57094. se_BeginTransactionCommand = async (input, context) => {
  57095. const b5 = requestBuilder(input, context);
  57096. const headers = {
  57097. "content-type": "application/json"
  57098. };
  57099. b5.bp("/BeginTransaction");
  57100. let body;
  57101. body = JSON.stringify(take(input, {
  57102. database: [],
  57103. resourceArn: [],
  57104. schema: [],
  57105. secretArn: []
  57106. }));
  57107. b5.m("POST").h(headers).b(body);
  57108. return b5.build();
  57109. };
  57110. se_CommitTransactionCommand = async (input, context) => {
  57111. const b5 = requestBuilder(input, context);
  57112. const headers = {
  57113. "content-type": "application/json"
  57114. };
  57115. b5.bp("/CommitTransaction");
  57116. let body;
  57117. body = JSON.stringify(take(input, {
  57118. resourceArn: [],
  57119. secretArn: [],
  57120. transactionId: []
  57121. }));
  57122. b5.m("POST").h(headers).b(body);
  57123. return b5.build();
  57124. };
  57125. se_ExecuteSqlCommand = async (input, context) => {
  57126. const b5 = requestBuilder(input, context);
  57127. const headers = {
  57128. "content-type": "application/json"
  57129. };
  57130. b5.bp("/ExecuteSql");
  57131. let body;
  57132. body = JSON.stringify(take(input, {
  57133. awsSecretStoreArn: [],
  57134. database: [],
  57135. dbClusterOrInstanceArn: [],
  57136. schema: [],
  57137. sqlStatements: []
  57138. }));
  57139. b5.m("POST").h(headers).b(body);
  57140. return b5.build();
  57141. };
  57142. se_ExecuteStatementCommand = async (input, context) => {
  57143. const b5 = requestBuilder(input, context);
  57144. const headers = {
  57145. "content-type": "application/json"
  57146. };
  57147. b5.bp("/Execute");
  57148. let body;
  57149. body = JSON.stringify(take(input, {
  57150. continueAfterTimeout: [],
  57151. database: [],
  57152. formatRecordsAs: [],
  57153. includeResultMetadata: [],
  57154. parameters: (_3) => se_SqlParametersList(_3, context),
  57155. resourceArn: [],
  57156. resultSetOptions: (_3) => _json(_3),
  57157. schema: [],
  57158. secretArn: [],
  57159. sql: [],
  57160. transactionId: []
  57161. }));
  57162. b5.m("POST").h(headers).b(body);
  57163. return b5.build();
  57164. };
  57165. se_RollbackTransactionCommand = async (input, context) => {
  57166. const b5 = requestBuilder(input, context);
  57167. const headers = {
  57168. "content-type": "application/json"
  57169. };
  57170. b5.bp("/RollbackTransaction");
  57171. let body;
  57172. body = JSON.stringify(take(input, {
  57173. resourceArn: [],
  57174. secretArn: [],
  57175. transactionId: []
  57176. }));
  57177. b5.m("POST").h(headers).b(body);
  57178. return b5.build();
  57179. };
  57180. de_BatchExecuteStatementCommand = async (output, context) => {
  57181. if (output.statusCode !== 200 && output.statusCode >= 300) {
  57182. return de_CommandError4(output, context);
  57183. }
  57184. const contents = map({
  57185. $metadata: deserializeMetadata5(output)
  57186. });
  57187. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  57188. const doc = take(data, {
  57189. updateResults: (_3) => de_UpdateResults(_3, context)
  57190. });
  57191. Object.assign(contents, doc);
  57192. return contents;
  57193. };
  57194. de_BeginTransactionCommand = async (output, context) => {
  57195. if (output.statusCode !== 200 && output.statusCode >= 300) {
  57196. return de_CommandError4(output, context);
  57197. }
  57198. const contents = map({
  57199. $metadata: deserializeMetadata5(output)
  57200. });
  57201. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  57202. const doc = take(data, {
  57203. transactionId: expectString
  57204. });
  57205. Object.assign(contents, doc);
  57206. return contents;
  57207. };
  57208. de_CommitTransactionCommand = async (output, context) => {
  57209. if (output.statusCode !== 200 && output.statusCode >= 300) {
  57210. return de_CommandError4(output, context);
  57211. }
  57212. const contents = map({
  57213. $metadata: deserializeMetadata5(output)
  57214. });
  57215. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  57216. const doc = take(data, {
  57217. transactionStatus: expectString
  57218. });
  57219. Object.assign(contents, doc);
  57220. return contents;
  57221. };
  57222. de_ExecuteSqlCommand = async (output, context) => {
  57223. if (output.statusCode !== 200 && output.statusCode >= 300) {
  57224. return de_CommandError4(output, context);
  57225. }
  57226. const contents = map({
  57227. $metadata: deserializeMetadata5(output)
  57228. });
  57229. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  57230. const doc = take(data, {
  57231. sqlStatementResults: (_3) => de_SqlStatementResults(_3, context)
  57232. });
  57233. Object.assign(contents, doc);
  57234. return contents;
  57235. };
  57236. de_ExecuteStatementCommand = async (output, context) => {
  57237. if (output.statusCode !== 200 && output.statusCode >= 300) {
  57238. return de_CommandError4(output, context);
  57239. }
  57240. const contents = map({
  57241. $metadata: deserializeMetadata5(output)
  57242. });
  57243. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  57244. const doc = take(data, {
  57245. columnMetadata: _json,
  57246. formattedRecords: expectString,
  57247. generatedFields: (_3) => de_FieldList(_3, context),
  57248. numberOfRecordsUpdated: expectLong,
  57249. records: (_3) => de_SqlRecords(_3, context)
  57250. });
  57251. Object.assign(contents, doc);
  57252. return contents;
  57253. };
  57254. de_RollbackTransactionCommand = async (output, context) => {
  57255. if (output.statusCode !== 200 && output.statusCode >= 300) {
  57256. return de_CommandError4(output, context);
  57257. }
  57258. const contents = map({
  57259. $metadata: deserializeMetadata5(output)
  57260. });
  57261. const data = expectNonNull(expectObject(await parseJsonBody(output.body, context)), "body");
  57262. const doc = take(data, {
  57263. transactionStatus: expectString
  57264. });
  57265. Object.assign(contents, doc);
  57266. return contents;
  57267. };
  57268. de_CommandError4 = async (output, context) => {
  57269. const parsedOutput = {
  57270. ...output,
  57271. body: await parseJsonErrorBody(output.body, context)
  57272. };
  57273. const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
  57274. switch (errorCode) {
  57275. case "AccessDeniedException":
  57276. case "com.amazonaws.rdsdata#AccessDeniedException":
  57277. throw await de_AccessDeniedExceptionRes2(parsedOutput, context);
  57278. case "BadRequestException":
  57279. case "com.amazonaws.rdsdata#BadRequestException":
  57280. throw await de_BadRequestExceptionRes(parsedOutput, context);
  57281. case "DatabaseErrorException":
  57282. case "com.amazonaws.rdsdata#DatabaseErrorException":
  57283. throw await de_DatabaseErrorExceptionRes(parsedOutput, context);
  57284. case "DatabaseNotFoundException":
  57285. case "com.amazonaws.rdsdata#DatabaseNotFoundException":
  57286. throw await de_DatabaseNotFoundExceptionRes(parsedOutput, context);
  57287. case "DatabaseResumingException":
  57288. case "com.amazonaws.rdsdata#DatabaseResumingException":
  57289. throw await de_DatabaseResumingExceptionRes(parsedOutput, context);
  57290. case "DatabaseUnavailableException":
  57291. case "com.amazonaws.rdsdata#DatabaseUnavailableException":
  57292. throw await de_DatabaseUnavailableExceptionRes(parsedOutput, context);
  57293. case "ForbiddenException":
  57294. case "com.amazonaws.rdsdata#ForbiddenException":
  57295. throw await de_ForbiddenExceptionRes(parsedOutput, context);
  57296. case "HttpEndpointNotEnabledException":
  57297. case "com.amazonaws.rdsdata#HttpEndpointNotEnabledException":
  57298. throw await de_HttpEndpointNotEnabledExceptionRes(parsedOutput, context);
  57299. case "InternalServerErrorException":
  57300. case "com.amazonaws.rdsdata#InternalServerErrorException":
  57301. throw await de_InternalServerErrorExceptionRes(parsedOutput, context);
  57302. case "InvalidResourceStateException":
  57303. case "com.amazonaws.rdsdata#InvalidResourceStateException":
  57304. throw await de_InvalidResourceStateExceptionRes(parsedOutput, context);
  57305. case "InvalidSecretException":
  57306. case "com.amazonaws.rdsdata#InvalidSecretException":
  57307. throw await de_InvalidSecretExceptionRes(parsedOutput, context);
  57308. case "SecretsErrorException":
  57309. case "com.amazonaws.rdsdata#SecretsErrorException":
  57310. throw await de_SecretsErrorExceptionRes(parsedOutput, context);
  57311. case "ServiceUnavailableError":
  57312. case "com.amazonaws.rdsdata#ServiceUnavailableError":
  57313. throw await de_ServiceUnavailableErrorRes(parsedOutput, context);
  57314. case "StatementTimeoutException":
  57315. case "com.amazonaws.rdsdata#StatementTimeoutException":
  57316. throw await de_StatementTimeoutExceptionRes(parsedOutput, context);
  57317. case "TransactionNotFoundException":
  57318. case "com.amazonaws.rdsdata#TransactionNotFoundException":
  57319. throw await de_TransactionNotFoundExceptionRes(parsedOutput, context);
  57320. case "NotFoundException":
  57321. case "com.amazonaws.rdsdata#NotFoundException":
  57322. throw await de_NotFoundExceptionRes(parsedOutput, context);
  57323. case "UnsupportedResultException":
  57324. case "com.amazonaws.rdsdata#UnsupportedResultException":
  57325. throw await de_UnsupportedResultExceptionRes(parsedOutput, context);
  57326. default:
  57327. const parsedBody = parsedOutput.body;
  57328. return throwDefaultError5({
  57329. output,
  57330. parsedBody,
  57331. errorCode
  57332. });
  57333. }
  57334. };
  57335. throwDefaultError5 = withBaseException(RDSDataServiceException);
  57336. de_AccessDeniedExceptionRes2 = async (parsedOutput, context) => {
  57337. const contents = map({});
  57338. const data = parsedOutput.body;
  57339. const doc = take(data, {
  57340. message: expectString
  57341. });
  57342. Object.assign(contents, doc);
  57343. const exception = new AccessDeniedException2({
  57344. $metadata: deserializeMetadata5(parsedOutput),
  57345. ...contents
  57346. });
  57347. return decorateServiceException(exception, parsedOutput.body);
  57348. };
  57349. de_BadRequestExceptionRes = async (parsedOutput, context) => {
  57350. const contents = map({});
  57351. const data = parsedOutput.body;
  57352. const doc = take(data, {
  57353. message: expectString
  57354. });
  57355. Object.assign(contents, doc);
  57356. const exception = new BadRequestException({
  57357. $metadata: deserializeMetadata5(parsedOutput),
  57358. ...contents
  57359. });
  57360. return decorateServiceException(exception, parsedOutput.body);
  57361. };
  57362. de_DatabaseErrorExceptionRes = async (parsedOutput, context) => {
  57363. const contents = map({});
  57364. const data = parsedOutput.body;
  57365. const doc = take(data, {
  57366. message: expectString
  57367. });
  57368. Object.assign(contents, doc);
  57369. const exception = new DatabaseErrorException({
  57370. $metadata: deserializeMetadata5(parsedOutput),
  57371. ...contents
  57372. });
  57373. return decorateServiceException(exception, parsedOutput.body);
  57374. };
  57375. de_DatabaseNotFoundExceptionRes = async (parsedOutput, context) => {
  57376. const contents = map({});
  57377. const data = parsedOutput.body;
  57378. const doc = take(data, {
  57379. message: expectString
  57380. });
  57381. Object.assign(contents, doc);
  57382. const exception = new DatabaseNotFoundException({
  57383. $metadata: deserializeMetadata5(parsedOutput),
  57384. ...contents
  57385. });
  57386. return decorateServiceException(exception, parsedOutput.body);
  57387. };
  57388. de_DatabaseResumingExceptionRes = async (parsedOutput, context) => {
  57389. const contents = map({});
  57390. const data = parsedOutput.body;
  57391. const doc = take(data, {
  57392. message: expectString
  57393. });
  57394. Object.assign(contents, doc);
  57395. const exception = new DatabaseResumingException({
  57396. $metadata: deserializeMetadata5(parsedOutput),
  57397. ...contents
  57398. });
  57399. return decorateServiceException(exception, parsedOutput.body);
  57400. };
  57401. de_DatabaseUnavailableExceptionRes = async (parsedOutput, context) => {
  57402. const contents = map({});
  57403. const data = parsedOutput.body;
  57404. const doc = take(data, {});
  57405. Object.assign(contents, doc);
  57406. const exception = new DatabaseUnavailableException({
  57407. $metadata: deserializeMetadata5(parsedOutput),
  57408. ...contents
  57409. });
  57410. return decorateServiceException(exception, parsedOutput.body);
  57411. };
  57412. de_ForbiddenExceptionRes = async (parsedOutput, context) => {
  57413. const contents = map({});
  57414. const data = parsedOutput.body;
  57415. const doc = take(data, {
  57416. message: expectString
  57417. });
  57418. Object.assign(contents, doc);
  57419. const exception = new ForbiddenException({
  57420. $metadata: deserializeMetadata5(parsedOutput),
  57421. ...contents
  57422. });
  57423. return decorateServiceException(exception, parsedOutput.body);
  57424. };
  57425. de_HttpEndpointNotEnabledExceptionRes = async (parsedOutput, context) => {
  57426. const contents = map({});
  57427. const data = parsedOutput.body;
  57428. const doc = take(data, {
  57429. message: expectString
  57430. });
  57431. Object.assign(contents, doc);
  57432. const exception = new HttpEndpointNotEnabledException({
  57433. $metadata: deserializeMetadata5(parsedOutput),
  57434. ...contents
  57435. });
  57436. return decorateServiceException(exception, parsedOutput.body);
  57437. };
  57438. de_InternalServerErrorExceptionRes = async (parsedOutput, context) => {
  57439. const contents = map({});
  57440. const data = parsedOutput.body;
  57441. const doc = take(data, {});
  57442. Object.assign(contents, doc);
  57443. const exception = new InternalServerErrorException({
  57444. $metadata: deserializeMetadata5(parsedOutput),
  57445. ...contents
  57446. });
  57447. return decorateServiceException(exception, parsedOutput.body);
  57448. };
  57449. de_InvalidResourceStateExceptionRes = async (parsedOutput, context) => {
  57450. const contents = map({});
  57451. const data = parsedOutput.body;
  57452. const doc = take(data, {
  57453. message: expectString
  57454. });
  57455. Object.assign(contents, doc);
  57456. const exception = new InvalidResourceStateException({
  57457. $metadata: deserializeMetadata5(parsedOutput),
  57458. ...contents
  57459. });
  57460. return decorateServiceException(exception, parsedOutput.body);
  57461. };
  57462. de_InvalidSecretExceptionRes = async (parsedOutput, context) => {
  57463. const contents = map({});
  57464. const data = parsedOutput.body;
  57465. const doc = take(data, {
  57466. message: expectString
  57467. });
  57468. Object.assign(contents, doc);
  57469. const exception = new InvalidSecretException({
  57470. $metadata: deserializeMetadata5(parsedOutput),
  57471. ...contents
  57472. });
  57473. return decorateServiceException(exception, parsedOutput.body);
  57474. };
  57475. de_NotFoundExceptionRes = async (parsedOutput, context) => {
  57476. const contents = map({});
  57477. const data = parsedOutput.body;
  57478. const doc = take(data, {
  57479. message: expectString
  57480. });
  57481. Object.assign(contents, doc);
  57482. const exception = new NotFoundException({
  57483. $metadata: deserializeMetadata5(parsedOutput),
  57484. ...contents
  57485. });
  57486. return decorateServiceException(exception, parsedOutput.body);
  57487. };
  57488. de_SecretsErrorExceptionRes = async (parsedOutput, context) => {
  57489. const contents = map({});
  57490. const data = parsedOutput.body;
  57491. const doc = take(data, {
  57492. message: expectString
  57493. });
  57494. Object.assign(contents, doc);
  57495. const exception = new SecretsErrorException({
  57496. $metadata: deserializeMetadata5(parsedOutput),
  57497. ...contents
  57498. });
  57499. return decorateServiceException(exception, parsedOutput.body);
  57500. };
  57501. de_ServiceUnavailableErrorRes = async (parsedOutput, context) => {
  57502. const contents = map({});
  57503. const data = parsedOutput.body;
  57504. const doc = take(data, {});
  57505. Object.assign(contents, doc);
  57506. const exception = new ServiceUnavailableError({
  57507. $metadata: deserializeMetadata5(parsedOutput),
  57508. ...contents
  57509. });
  57510. return decorateServiceException(exception, parsedOutput.body);
  57511. };
  57512. de_StatementTimeoutExceptionRes = async (parsedOutput, context) => {
  57513. const contents = map({});
  57514. const data = parsedOutput.body;
  57515. const doc = take(data, {
  57516. dbConnectionId: expectLong,
  57517. message: expectString
  57518. });
  57519. Object.assign(contents, doc);
  57520. const exception = new StatementTimeoutException({
  57521. $metadata: deserializeMetadata5(parsedOutput),
  57522. ...contents
  57523. });
  57524. return decorateServiceException(exception, parsedOutput.body);
  57525. };
  57526. de_TransactionNotFoundExceptionRes = async (parsedOutput, context) => {
  57527. const contents = map({});
  57528. const data = parsedOutput.body;
  57529. const doc = take(data, {
  57530. message: expectString
  57531. });
  57532. Object.assign(contents, doc);
  57533. const exception = new TransactionNotFoundException({
  57534. $metadata: deserializeMetadata5(parsedOutput),
  57535. ...contents
  57536. });
  57537. return decorateServiceException(exception, parsedOutput.body);
  57538. };
  57539. de_UnsupportedResultExceptionRes = async (parsedOutput, context) => {
  57540. const contents = map({});
  57541. const data = parsedOutput.body;
  57542. const doc = take(data, {
  57543. message: expectString
  57544. });
  57545. Object.assign(contents, doc);
  57546. const exception = new UnsupportedResultException({
  57547. $metadata: deserializeMetadata5(parsedOutput),
  57548. ...contents
  57549. });
  57550. return decorateServiceException(exception, parsedOutput.body);
  57551. };
  57552. se_ArrayOfArray = (input, context) => {
  57553. return input.filter((e6) => e6 != null).map((entry) => {
  57554. return se_ArrayValue(entry, context);
  57555. });
  57556. };
  57557. se_ArrayValue = (input, context) => {
  57558. return ArrayValue.visit(input, {
  57559. arrayValues: (value) => ({ arrayValues: se_ArrayOfArray(value, context) }),
  57560. booleanValues: (value) => ({ booleanValues: _json(value) }),
  57561. doubleValues: (value) => ({ doubleValues: se_DoubleArray(value, context) }),
  57562. longValues: (value) => ({ longValues: _json(value) }),
  57563. stringValues: (value) => ({ stringValues: _json(value) }),
  57564. _: (name, value) => ({ [name]: value })
  57565. });
  57566. };
  57567. se_DoubleArray = (input, context) => {
  57568. return input.filter((e6) => e6 != null).map((entry) => {
  57569. return serializeFloat(entry);
  57570. });
  57571. };
  57572. se_Field = (input, context) => {
  57573. return Field.visit(input, {
  57574. arrayValue: (value) => ({ arrayValue: se_ArrayValue(value, context) }),
  57575. blobValue: (value) => ({ blobValue: context.base64Encoder(value) }),
  57576. booleanValue: (value) => ({ booleanValue: value }),
  57577. doubleValue: (value) => ({ doubleValue: serializeFloat(value) }),
  57578. isNull: (value) => ({ isNull: value }),
  57579. longValue: (value) => ({ longValue: value }),
  57580. stringValue: (value) => ({ stringValue: value }),
  57581. _: (name, value) => ({ [name]: value })
  57582. });
  57583. };
  57584. se_SqlParameter = (input, context) => {
  57585. return take(input, {
  57586. name: [],
  57587. typeHint: [],
  57588. value: (_3) => se_Field(_3, context)
  57589. });
  57590. };
  57591. se_SqlParameterSets = (input, context) => {
  57592. return input.filter((e6) => e6 != null).map((entry) => {
  57593. return se_SqlParametersList(entry, context);
  57594. });
  57595. };
  57596. se_SqlParametersList = (input, context) => {
  57597. return input.filter((e6) => e6 != null).map((entry) => {
  57598. return se_SqlParameter(entry, context);
  57599. });
  57600. };
  57601. de_ArrayOfArray = (output, context) => {
  57602. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57603. return de_ArrayValue(awsExpectUnion(entry), context);
  57604. });
  57605. return retVal;
  57606. };
  57607. de_ArrayValue = (output, context) => {
  57608. if (output.arrayValues != null) {
  57609. return {
  57610. arrayValues: de_ArrayOfArray(output.arrayValues, context)
  57611. };
  57612. }
  57613. if (output.booleanValues != null) {
  57614. return {
  57615. booleanValues: _json(output.booleanValues)
  57616. };
  57617. }
  57618. if (output.doubleValues != null) {
  57619. return {
  57620. doubleValues: de_DoubleArray(output.doubleValues, context)
  57621. };
  57622. }
  57623. if (output.longValues != null) {
  57624. return {
  57625. longValues: _json(output.longValues)
  57626. };
  57627. }
  57628. if (output.stringValues != null) {
  57629. return {
  57630. stringValues: _json(output.stringValues)
  57631. };
  57632. }
  57633. return { $unknown: Object.entries(output)[0] };
  57634. };
  57635. de_ArrayValueList = (output, context) => {
  57636. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57637. return de_Value(awsExpectUnion(entry), context);
  57638. });
  57639. return retVal;
  57640. };
  57641. de_DoubleArray = (output, context) => {
  57642. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57643. return limitedParseDouble(entry);
  57644. });
  57645. return retVal;
  57646. };
  57647. de_Field = (output, context) => {
  57648. if (output.arrayValue != null) {
  57649. return {
  57650. arrayValue: de_ArrayValue(awsExpectUnion(output.arrayValue), context)
  57651. };
  57652. }
  57653. if (output.blobValue != null) {
  57654. return {
  57655. blobValue: context.base64Decoder(output.blobValue)
  57656. };
  57657. }
  57658. if (expectBoolean(output.booleanValue) !== void 0) {
  57659. return { booleanValue: expectBoolean(output.booleanValue) };
  57660. }
  57661. if (limitedParseDouble(output.doubleValue) !== void 0) {
  57662. return { doubleValue: limitedParseDouble(output.doubleValue) };
  57663. }
  57664. if (expectBoolean(output.isNull) !== void 0) {
  57665. return { isNull: expectBoolean(output.isNull) };
  57666. }
  57667. if (expectLong(output.longValue) !== void 0) {
  57668. return { longValue: expectLong(output.longValue) };
  57669. }
  57670. if (expectString(output.stringValue) !== void 0) {
  57671. return { stringValue: expectString(output.stringValue) };
  57672. }
  57673. return { $unknown: Object.entries(output)[0] };
  57674. };
  57675. de_FieldList = (output, context) => {
  57676. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57677. return de_Field(awsExpectUnion(entry), context);
  57678. });
  57679. return retVal;
  57680. };
  57681. de__Record = (output, context) => {
  57682. return take(output, {
  57683. values: (_3) => de_Row(_3, context)
  57684. });
  57685. };
  57686. de_Records = (output, context) => {
  57687. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57688. return de__Record(entry, context);
  57689. });
  57690. return retVal;
  57691. };
  57692. de_ResultFrame = (output, context) => {
  57693. return take(output, {
  57694. records: (_3) => de_Records(_3, context),
  57695. resultSetMetadata: _json
  57696. });
  57697. };
  57698. de_Row = (output, context) => {
  57699. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57700. return de_Value(awsExpectUnion(entry), context);
  57701. });
  57702. return retVal;
  57703. };
  57704. de_SqlRecords = (output, context) => {
  57705. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57706. return de_FieldList(entry, context);
  57707. });
  57708. return retVal;
  57709. };
  57710. de_SqlStatementResult = (output, context) => {
  57711. return take(output, {
  57712. numberOfRecordsUpdated: expectLong,
  57713. resultFrame: (_3) => de_ResultFrame(_3, context)
  57714. });
  57715. };
  57716. de_SqlStatementResults = (output, context) => {
  57717. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57718. return de_SqlStatementResult(entry, context);
  57719. });
  57720. return retVal;
  57721. };
  57722. de_StructValue = (output, context) => {
  57723. return take(output, {
  57724. attributes: (_3) => de_ArrayValueList(_3, context)
  57725. });
  57726. };
  57727. de_UpdateResult = (output, context) => {
  57728. return take(output, {
  57729. generatedFields: (_3) => de_FieldList(_3, context)
  57730. });
  57731. };
  57732. de_UpdateResults = (output, context) => {
  57733. const retVal = (output || []).filter((e6) => e6 != null).map((entry) => {
  57734. return de_UpdateResult(entry, context);
  57735. });
  57736. return retVal;
  57737. };
  57738. de_Value = (output, context) => {
  57739. if (output.arrayValues != null) {
  57740. return {
  57741. arrayValues: de_ArrayValueList(output.arrayValues, context)
  57742. };
  57743. }
  57744. if (expectLong(output.bigIntValue) !== void 0) {
  57745. return { bigIntValue: expectLong(output.bigIntValue) };
  57746. }
  57747. if (expectBoolean(output.bitValue) !== void 0) {
  57748. return { bitValue: expectBoolean(output.bitValue) };
  57749. }
  57750. if (output.blobValue != null) {
  57751. return {
  57752. blobValue: context.base64Decoder(output.blobValue)
  57753. };
  57754. }
  57755. if (limitedParseDouble(output.doubleValue) !== void 0) {
  57756. return { doubleValue: limitedParseDouble(output.doubleValue) };
  57757. }
  57758. if (expectInt32(output.intValue) !== void 0) {
  57759. return { intValue: expectInt32(output.intValue) };
  57760. }
  57761. if (expectBoolean(output.isNull) !== void 0) {
  57762. return { isNull: expectBoolean(output.isNull) };
  57763. }
  57764. if (limitedParseFloat32(output.realValue) !== void 0) {
  57765. return { realValue: limitedParseFloat32(output.realValue) };
  57766. }
  57767. if (expectString(output.stringValue) !== void 0) {
  57768. return { stringValue: expectString(output.stringValue) };
  57769. }
  57770. if (output.structValue != null) {
  57771. return {
  57772. structValue: de_StructValue(output.structValue, context)
  57773. };
  57774. }
  57775. return { $unknown: Object.entries(output)[0] };
  57776. };
  57777. deserializeMetadata5 = (output) => ({
  57778. httpStatusCode: output.statusCode,
  57779. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  57780. extendedRequestId: output.headers["x-amz-id-2"],
  57781. cfId: output.headers["x-amz-cf-id"]
  57782. });
  57783. }
  57784. });
  57785. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/BatchExecuteStatementCommand.js
  57786. var BatchExecuteStatementCommand;
  57787. var init_BatchExecuteStatementCommand = __esm({
  57788. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/BatchExecuteStatementCommand.js"() {
  57789. "use strict";
  57790. init_dist_es34();
  57791. init_dist_es7();
  57792. init_dist_es24();
  57793. init_EndpointParameters();
  57794. init_Aws_restJson13();
  57795. BatchExecuteStatementCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
  57796. return [
  57797. getSerdePlugin(config, this.serialize, this.deserialize),
  57798. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  57799. ];
  57800. }).s("RdsDataService", "BatchExecuteStatement", {}).n("RDSDataClient", "BatchExecuteStatementCommand").f(void 0, void 0).ser(se_BatchExecuteStatementCommand).de(de_BatchExecuteStatementCommand).build() {
  57801. };
  57802. }
  57803. });
  57804. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/BeginTransactionCommand.js
  57805. var BeginTransactionCommand;
  57806. var init_BeginTransactionCommand = __esm({
  57807. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/BeginTransactionCommand.js"() {
  57808. "use strict";
  57809. init_dist_es34();
  57810. init_dist_es7();
  57811. init_dist_es24();
  57812. init_EndpointParameters();
  57813. init_Aws_restJson13();
  57814. BeginTransactionCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
  57815. return [
  57816. getSerdePlugin(config, this.serialize, this.deserialize),
  57817. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  57818. ];
  57819. }).s("RdsDataService", "BeginTransaction", {}).n("RDSDataClient", "BeginTransactionCommand").f(void 0, void 0).ser(se_BeginTransactionCommand).de(de_BeginTransactionCommand).build() {
  57820. };
  57821. }
  57822. });
  57823. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/CommitTransactionCommand.js
  57824. var CommitTransactionCommand;
  57825. var init_CommitTransactionCommand = __esm({
  57826. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/CommitTransactionCommand.js"() {
  57827. "use strict";
  57828. init_dist_es34();
  57829. init_dist_es7();
  57830. init_dist_es24();
  57831. init_EndpointParameters();
  57832. init_Aws_restJson13();
  57833. CommitTransactionCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
  57834. return [
  57835. getSerdePlugin(config, this.serialize, this.deserialize),
  57836. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  57837. ];
  57838. }).s("RdsDataService", "CommitTransaction", {}).n("RDSDataClient", "CommitTransactionCommand").f(void 0, void 0).ser(se_CommitTransactionCommand).de(de_CommitTransactionCommand).build() {
  57839. };
  57840. }
  57841. });
  57842. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/ExecuteSqlCommand.js
  57843. var ExecuteSqlCommand;
  57844. var init_ExecuteSqlCommand = __esm({
  57845. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/ExecuteSqlCommand.js"() {
  57846. "use strict";
  57847. init_dist_es34();
  57848. init_dist_es7();
  57849. init_dist_es24();
  57850. init_EndpointParameters();
  57851. init_Aws_restJson13();
  57852. ExecuteSqlCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
  57853. return [
  57854. getSerdePlugin(config, this.serialize, this.deserialize),
  57855. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  57856. ];
  57857. }).s("RdsDataService", "ExecuteSql", {}).n("RDSDataClient", "ExecuteSqlCommand").f(void 0, void 0).ser(se_ExecuteSqlCommand).de(de_ExecuteSqlCommand).build() {
  57858. };
  57859. }
  57860. });
  57861. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/ExecuteStatementCommand.js
  57862. var ExecuteStatementCommand;
  57863. var init_ExecuteStatementCommand = __esm({
  57864. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/ExecuteStatementCommand.js"() {
  57865. "use strict";
  57866. init_dist_es34();
  57867. init_dist_es7();
  57868. init_dist_es24();
  57869. init_EndpointParameters();
  57870. init_Aws_restJson13();
  57871. ExecuteStatementCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
  57872. return [
  57873. getSerdePlugin(config, this.serialize, this.deserialize),
  57874. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  57875. ];
  57876. }).s("RdsDataService", "ExecuteStatement", {}).n("RDSDataClient", "ExecuteStatementCommand").f(void 0, void 0).ser(se_ExecuteStatementCommand).de(de_ExecuteStatementCommand).build() {
  57877. };
  57878. }
  57879. });
  57880. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/RollbackTransactionCommand.js
  57881. var RollbackTransactionCommand;
  57882. var init_RollbackTransactionCommand = __esm({
  57883. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/RollbackTransactionCommand.js"() {
  57884. "use strict";
  57885. init_dist_es34();
  57886. init_dist_es7();
  57887. init_dist_es24();
  57888. init_EndpointParameters();
  57889. init_Aws_restJson13();
  57890. RollbackTransactionCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o5) {
  57891. return [
  57892. getSerdePlugin(config, this.serialize, this.deserialize),
  57893. getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
  57894. ];
  57895. }).s("RdsDataService", "RollbackTransaction", {}).n("RDSDataClient", "RollbackTransactionCommand").f(void 0, void 0).ser(se_RollbackTransactionCommand).de(de_RollbackTransactionCommand).build() {
  57896. };
  57897. }
  57898. });
  57899. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/RDSData.js
  57900. var commands4, RDSData;
  57901. var init_RDSData = __esm({
  57902. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/RDSData.js"() {
  57903. "use strict";
  57904. init_dist_es24();
  57905. init_BatchExecuteStatementCommand();
  57906. init_BeginTransactionCommand();
  57907. init_CommitTransactionCommand();
  57908. init_ExecuteSqlCommand();
  57909. init_ExecuteStatementCommand();
  57910. init_RollbackTransactionCommand();
  57911. init_RDSDataClient();
  57912. commands4 = {
  57913. BatchExecuteStatementCommand,
  57914. BeginTransactionCommand,
  57915. CommitTransactionCommand,
  57916. ExecuteSqlCommand,
  57917. ExecuteStatementCommand,
  57918. RollbackTransactionCommand
  57919. };
  57920. RDSData = class extends RDSDataClient {
  57921. };
  57922. createAggregatedClient(commands4, RDSData);
  57923. }
  57924. });
  57925. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/index.js
  57926. var init_commands4 = __esm({
  57927. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/commands/index.js"() {
  57928. "use strict";
  57929. init_BatchExecuteStatementCommand();
  57930. init_BeginTransactionCommand();
  57931. init_CommitTransactionCommand();
  57932. init_ExecuteSqlCommand();
  57933. init_ExecuteStatementCommand();
  57934. init_RollbackTransactionCommand();
  57935. }
  57936. });
  57937. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/index.js
  57938. var init_models4 = __esm({
  57939. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/models/index.js"() {
  57940. "use strict";
  57941. init_models_04();
  57942. }
  57943. });
  57944. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/index.js
  57945. var dist_es_exports8 = {};
  57946. __export(dist_es_exports8, {
  57947. $Command: () => Command,
  57948. AccessDeniedException: () => AccessDeniedException2,
  57949. ArrayValue: () => ArrayValue,
  57950. BadRequestException: () => BadRequestException,
  57951. BatchExecuteStatementCommand: () => BatchExecuteStatementCommand,
  57952. BeginTransactionCommand: () => BeginTransactionCommand,
  57953. CommitTransactionCommand: () => CommitTransactionCommand,
  57954. DatabaseErrorException: () => DatabaseErrorException,
  57955. DatabaseNotFoundException: () => DatabaseNotFoundException,
  57956. DatabaseResumingException: () => DatabaseResumingException,
  57957. DatabaseUnavailableException: () => DatabaseUnavailableException,
  57958. DecimalReturnType: () => DecimalReturnType,
  57959. ExecuteSqlCommand: () => ExecuteSqlCommand,
  57960. ExecuteStatementCommand: () => ExecuteStatementCommand,
  57961. Field: () => Field,
  57962. ForbiddenException: () => ForbiddenException,
  57963. HttpEndpointNotEnabledException: () => HttpEndpointNotEnabledException,
  57964. InternalServerErrorException: () => InternalServerErrorException,
  57965. InvalidResourceStateException: () => InvalidResourceStateException,
  57966. InvalidSecretException: () => InvalidSecretException,
  57967. LongReturnType: () => LongReturnType,
  57968. NotFoundException: () => NotFoundException,
  57969. RDSData: () => RDSData,
  57970. RDSDataClient: () => RDSDataClient,
  57971. RDSDataServiceException: () => RDSDataServiceException,
  57972. RecordsFormatType: () => RecordsFormatType,
  57973. RollbackTransactionCommand: () => RollbackTransactionCommand,
  57974. SecretsErrorException: () => SecretsErrorException,
  57975. ServiceUnavailableError: () => ServiceUnavailableError,
  57976. StatementTimeoutException: () => StatementTimeoutException,
  57977. TransactionNotFoundException: () => TransactionNotFoundException,
  57978. TypeHint: () => TypeHint,
  57979. UnsupportedResultException: () => UnsupportedResultException,
  57980. Value: () => Value,
  57981. __Client: () => Client
  57982. });
  57983. var init_dist_es53 = __esm({
  57984. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-es/index.js"() {
  57985. "use strict";
  57986. init_RDSDataClient();
  57987. init_RDSData();
  57988. init_commands4();
  57989. init_models4();
  57990. init_RDSDataServiceException();
  57991. }
  57992. });
  57993. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/chars.js
  57994. var require_chars = __commonJS({
  57995. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/chars.js"(exports) {
  57996. "use strict";
  57997. Object.defineProperty(exports, "__esModule", { value: true });
  57998. exports.$v = exports.$s = exports.$r = exports.$p = exports.$o = exports.$n = exports.$m = exports.$j = exports.$b = exports.$Z = exports.$Y = exports.$X = exports.$V = exports.$T = exports.$S = exports.$R = exports.$Q = exports.$P = exports.$O = exports.$M = exports.$L = exports.$K = exports.$I = exports.$H = exports.$E = exports.$D = exports.$C = exports.$A = exports.$1 = exports.$0 = void 0;
  57999. exports.ord = ord;
  58000. exports.chr = chr;
  58001. exports.$0 = ord("0");
  58002. exports.$1 = ord("1");
  58003. exports.$A = ord("A");
  58004. exports.$C = ord("C");
  58005. exports.$D = ord("D");
  58006. exports.$E = ord("E");
  58007. exports.$H = ord("H");
  58008. exports.$I = ord("I");
  58009. exports.$K = ord("K");
  58010. exports.$L = ord("L");
  58011. exports.$M = ord("M");
  58012. exports.$O = ord("O");
  58013. exports.$P = ord("P");
  58014. exports.$Q = ord("Q");
  58015. exports.$R = ord("R");
  58016. exports.$S = ord("S");
  58017. exports.$T = ord("T");
  58018. exports.$V = ord("V");
  58019. exports.$X = ord("X");
  58020. exports.$Y = ord("Y");
  58021. exports.$Z = ord("Z");
  58022. exports.$b = ord("b");
  58023. exports.$j = ord("j");
  58024. exports.$m = ord("m");
  58025. exports.$n = ord("n");
  58026. exports.$o = ord("o");
  58027. exports.$p = ord("p");
  58028. exports.$r = ord("r");
  58029. exports.$s = ord("s");
  58030. exports.$v = ord("v");
  58031. function ord(str) {
  58032. const ch = str.charCodeAt(0);
  58033. if (ch <= 0 || ch >= 255) {
  58034. throw new TypeError(`char "${ch}" is outside ASCII`);
  58035. }
  58036. return ch & 255;
  58037. }
  58038. function chr(ch) {
  58039. if (ch <= 0 || ch >= 255) {
  58040. throw new TypeError(`char "${ch}" is outside ASCII`);
  58041. }
  58042. return String.fromCharCode(ch);
  58043. }
  58044. }
  58045. });
  58046. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/buffer.js
  58047. var require_buffer = __commonJS({
  58048. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/buffer.js"(exports) {
  58049. "use strict";
  58050. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  58051. if (k22 === void 0) k22 = k5;
  58052. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  58053. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  58054. desc = { enumerable: true, get: function() {
  58055. return m6[k5];
  58056. } };
  58057. }
  58058. Object.defineProperty(o5, k22, desc);
  58059. } : function(o5, m6, k5, k22) {
  58060. if (k22 === void 0) k22 = k5;
  58061. o5[k22] = m6[k5];
  58062. });
  58063. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  58064. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  58065. } : function(o5, v6) {
  58066. o5["default"] = v6;
  58067. });
  58068. var __importStar = exports && exports.__importStar || function(mod) {
  58069. if (mod && mod.__esModule) return mod;
  58070. var result = {};
  58071. if (mod != null) {
  58072. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  58073. }
  58074. __setModuleDefault(result, mod);
  58075. return result;
  58076. };
  58077. Object.defineProperty(exports, "__esModule", { value: true });
  58078. exports.ReadBuffer = exports.ReadMessageBuffer = exports.WriteMessageBuffer = exports.WriteBuffer = exports.BufferError = exports.encodeB64 = exports.decodeB64 = exports.utf8Decoder = exports.utf8Encoder = void 0;
  58079. exports.uuidToBuffer = uuidToBuffer;
  58080. var chars = __importStar(require_chars());
  58081. exports.utf8Encoder = new TextEncoder();
  58082. exports.utf8Decoder = new TextDecoder("utf8");
  58083. var decodeB64;
  58084. var encodeB64;
  58085. if (typeof Buffer === "function") {
  58086. exports.decodeB64 = decodeB64 = (b64) => {
  58087. return Buffer.from(b64, "base64");
  58088. };
  58089. exports.encodeB64 = encodeB64 = (data) => {
  58090. const buf = !Buffer.isBuffer(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : data;
  58091. return buf.toString("base64");
  58092. };
  58093. } else {
  58094. exports.decodeB64 = decodeB64 = (b64) => {
  58095. const binaryString = atob(b64);
  58096. const size = binaryString.length;
  58097. const bytes = new Uint8Array(size);
  58098. for (let i6 = 0; i6 < size; i6++) {
  58099. bytes[i6] = binaryString.charCodeAt(i6);
  58100. }
  58101. return bytes;
  58102. };
  58103. exports.encodeB64 = encodeB64 = (data) => {
  58104. const binaryString = String.fromCharCode(...data);
  58105. return btoa(binaryString);
  58106. };
  58107. }
  58108. var BUFFER_INC_SIZE = 4096;
  58109. var EMPTY_BUFFER = new Uint8Array(0);
  58110. var BufferError = class extends Error {
  58111. };
  58112. exports.BufferError = BufferError;
  58113. var WriteBuffer = class {
  58114. constructor() {
  58115. __publicField(this, "_rawBuffer");
  58116. __publicField(this, "buffer");
  58117. __publicField(this, "size");
  58118. __publicField(this, "pos");
  58119. this.size = BUFFER_INC_SIZE;
  58120. this.pos = 0;
  58121. this._rawBuffer = new Uint8Array(this.size);
  58122. this.buffer = new DataView(this._rawBuffer.buffer);
  58123. }
  58124. get position() {
  58125. return this.pos;
  58126. }
  58127. reset() {
  58128. this.pos = 0;
  58129. }
  58130. ensureAlloced(extraLength) {
  58131. const newSize = this.pos + extraLength;
  58132. if (newSize > this.size) {
  58133. this.__realloc(newSize);
  58134. }
  58135. }
  58136. __realloc(newSize) {
  58137. newSize += BUFFER_INC_SIZE;
  58138. const newBuffer = new Uint8Array(newSize);
  58139. newBuffer.set(this._rawBuffer);
  58140. this._rawBuffer = newBuffer;
  58141. this.buffer = new DataView(this._rawBuffer.buffer);
  58142. this.size = newSize;
  58143. }
  58144. writeChar(ch) {
  58145. this.ensureAlloced(1);
  58146. this.buffer.setUint8(this.pos, ch);
  58147. this.pos++;
  58148. return this;
  58149. }
  58150. writeString(s6) {
  58151. return this.writeBytes(exports.utf8Encoder.encode(s6));
  58152. }
  58153. writeBytes(buf) {
  58154. this.ensureAlloced(buf.length + 4);
  58155. this.buffer.setInt32(this.pos, buf.length);
  58156. this.pos += 4;
  58157. this._rawBuffer.set(buf, this.pos);
  58158. this.pos += buf.length;
  58159. return this;
  58160. }
  58161. writeInt16(i6) {
  58162. this.ensureAlloced(2);
  58163. this.buffer.setInt16(this.pos, i6);
  58164. this.pos += 2;
  58165. return this;
  58166. }
  58167. writeInt32(i6) {
  58168. this.ensureAlloced(4);
  58169. this.buffer.setInt32(this.pos, i6);
  58170. this.pos += 4;
  58171. return this;
  58172. }
  58173. writeFloat32(i6) {
  58174. this.ensureAlloced(4);
  58175. this.buffer.setFloat32(this.pos, i6);
  58176. this.pos += 4;
  58177. return this;
  58178. }
  58179. writeFloat64(i6) {
  58180. this.ensureAlloced(8);
  58181. this.buffer.setFloat64(this.pos, i6);
  58182. this.pos += 8;
  58183. return this;
  58184. }
  58185. writeUInt8(i6) {
  58186. this.ensureAlloced(1);
  58187. this.buffer.setUint8(this.pos, i6);
  58188. this.pos += 1;
  58189. return this;
  58190. }
  58191. writeUInt16(i6) {
  58192. this.ensureAlloced(2);
  58193. this.buffer.setUint16(this.pos, i6);
  58194. this.pos += 2;
  58195. return this;
  58196. }
  58197. writeUInt32(i6) {
  58198. this.ensureAlloced(4);
  58199. this.buffer.setUint32(this.pos, i6);
  58200. this.pos += 4;
  58201. return this;
  58202. }
  58203. writeInt64(i6) {
  58204. this.ensureAlloced(8);
  58205. const hi = Math.floor(i6 / 4294967296);
  58206. const lo = i6 - hi * 4294967296;
  58207. this.buffer.setInt32(this.pos, hi);
  58208. this.buffer.setUint32(this.pos + 4, lo);
  58209. this.pos += 8;
  58210. return this;
  58211. }
  58212. writeBigInt64(i6) {
  58213. let ii = i6;
  58214. if (ii < 0n) {
  58215. ii = 18446744073709551616n + i6;
  58216. }
  58217. const hi = ii >> 32n;
  58218. const lo = ii & 0xffffffffn;
  58219. this.writeUInt32(Number(hi));
  58220. this.writeUInt32(Number(lo));
  58221. return this;
  58222. }
  58223. writeBuffer(buf) {
  58224. const len = buf.length;
  58225. this.ensureAlloced(len);
  58226. this._rawBuffer.set(buf, this.pos);
  58227. this.pos += len;
  58228. return this;
  58229. }
  58230. writeDeferredSize() {
  58231. const startPos = this.pos;
  58232. this.writeInt32(0);
  58233. return () => {
  58234. this.buffer.setInt32(startPos, this.pos - (startPos + 4));
  58235. };
  58236. }
  58237. unwrap() {
  58238. return this._rawBuffer.subarray(0, this.pos);
  58239. }
  58240. };
  58241. exports.WriteBuffer = WriteBuffer;
  58242. var WriteMessageBuffer = class {
  58243. constructor() {
  58244. __publicField(this, "buffer");
  58245. __publicField(this, "messagePos");
  58246. this.messagePos = -1;
  58247. this.buffer = new WriteBuffer();
  58248. }
  58249. reset() {
  58250. this.messagePos = -1;
  58251. this.buffer.reset();
  58252. return this;
  58253. }
  58254. beginMessage(mtype) {
  58255. if (this.messagePos >= 0) {
  58256. throw new BufferError("cannot begin a new message: the previous message is not finished");
  58257. }
  58258. this.messagePos = this.buffer.position;
  58259. this.buffer.writeChar(mtype);
  58260. this.buffer.writeInt32(0);
  58261. return this;
  58262. }
  58263. endMessage() {
  58264. if (this.messagePos < 0) {
  58265. throw new BufferError("cannot end the message: no current message");
  58266. }
  58267. this.buffer.buffer.setInt32(this.messagePos + 1, this.buffer.position - this.messagePos - 1);
  58268. this.messagePos = -1;
  58269. return this;
  58270. }
  58271. writeChar(ch) {
  58272. if (this.messagePos < 0) {
  58273. throw new BufferError("cannot writeChar: no current message");
  58274. }
  58275. this.buffer.writeChar(ch);
  58276. return this;
  58277. }
  58278. writeString(s6) {
  58279. if (this.messagePos < 0) {
  58280. throw new BufferError("cannot writeString: no current message");
  58281. }
  58282. this.buffer.writeString(s6);
  58283. return this;
  58284. }
  58285. writeBytes(val2) {
  58286. if (this.messagePos < 0) {
  58287. throw new BufferError("cannot writeBytes: no current message");
  58288. }
  58289. this.buffer.writeBytes(val2);
  58290. return this;
  58291. }
  58292. writeInt16(i6) {
  58293. if (this.messagePos < 0) {
  58294. throw new BufferError("cannot writeInt16: no current message");
  58295. }
  58296. this.buffer.writeInt16(i6);
  58297. return this;
  58298. }
  58299. writeInt32(i6) {
  58300. if (this.messagePos < 0) {
  58301. throw new BufferError("cannot writeInt32: no current message");
  58302. }
  58303. this.buffer.writeInt32(i6);
  58304. return this;
  58305. }
  58306. writeUInt16(i6) {
  58307. if (this.messagePos < 0) {
  58308. throw new BufferError("cannot writeInt16: no current message");
  58309. }
  58310. this.buffer.writeUInt16(i6);
  58311. return this;
  58312. }
  58313. writeUInt32(i6) {
  58314. if (this.messagePos < 0) {
  58315. throw new BufferError("cannot writeInt32: no current message");
  58316. }
  58317. this.buffer.writeUInt32(i6);
  58318. return this;
  58319. }
  58320. writeBigInt64(i6) {
  58321. if (this.messagePos < 0) {
  58322. throw new BufferError("cannot writeChar: no current message");
  58323. }
  58324. this.buffer.writeBigInt64(i6);
  58325. return this;
  58326. }
  58327. writeFlags(h6, l5) {
  58328. if (this.messagePos < 0) {
  58329. throw new BufferError("cannot writeChar: no current message");
  58330. }
  58331. this.buffer.writeUInt32(h6);
  58332. this.buffer.writeUInt32(l5);
  58333. return this;
  58334. }
  58335. writeBuffer(buf) {
  58336. if (this.messagePos < 0) {
  58337. throw new BufferError("cannot writeBuffer: no current message");
  58338. }
  58339. this.buffer.writeBuffer(buf);
  58340. return this;
  58341. }
  58342. writeSync() {
  58343. if (this.messagePos >= 0) {
  58344. throw new BufferError("cannot writeSync: the previous message is not finished");
  58345. }
  58346. this.buffer.writeBuffer(SYNC_MESSAGE);
  58347. return this;
  58348. }
  58349. writeFlush() {
  58350. if (this.messagePos >= 0) {
  58351. throw new BufferError("cannot writeFlush: the previous message is not finished");
  58352. }
  58353. this.buffer.writeBuffer(FLUSH_MESSAGE);
  58354. return this;
  58355. }
  58356. unwrap() {
  58357. if (this.messagePos >= 0) {
  58358. throw new BufferError("cannot unwrap: an unfinished message is in the buffer");
  58359. }
  58360. return this.buffer.unwrap();
  58361. }
  58362. };
  58363. exports.WriteMessageBuffer = WriteMessageBuffer;
  58364. var SYNC_MESSAGE = new WriteMessageBuffer().beginMessage(chars.$S).endMessage().unwrap();
  58365. var FLUSH_MESSAGE = new WriteMessageBuffer().beginMessage(chars.$H).endMessage().unwrap();
  58366. var byteToHex2 = [];
  58367. for (let i6 = 0; i6 < 256; ++i6) {
  58368. byteToHex2.push((i6 + 256).toString(16).slice(1));
  58369. }
  58370. function uuidToBuffer(uuid) {
  58371. const buf = new Uint8Array(16);
  58372. for (let i6 = 0; i6 < 16; i6++) {
  58373. buf[i6] = parseInt(uuid.slice(i6 * 2, i6 * 2 + 2), 16);
  58374. }
  58375. return buf;
  58376. }
  58377. var ReadMessageBuffer = class {
  58378. constructor() {
  58379. __publicField(this, "bufs");
  58380. __publicField(this, "len");
  58381. __publicField(this, "buf0");
  58382. __publicField(this, "pos0");
  58383. __publicField(this, "len0");
  58384. __publicField(this, "curMessageType");
  58385. __publicField(this, "curMessageLen");
  58386. __publicField(this, "curMessageLenUnread");
  58387. __publicField(this, "curMessageReady");
  58388. this.bufs = [];
  58389. this.buf0 = null;
  58390. this.pos0 = 0;
  58391. this.len0 = 0;
  58392. this.len = 0;
  58393. this.curMessageType = 0;
  58394. this.curMessageLen = 0;
  58395. this.curMessageLenUnread = 0;
  58396. this.curMessageReady = false;
  58397. }
  58398. get length() {
  58399. return this.len;
  58400. }
  58401. feed(buf) {
  58402. if (this.buf0 == null || this.pos0 === this.len0 && this.bufs.length === 0) {
  58403. this.buf0 = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
  58404. this.len0 = buf.byteLength;
  58405. this.pos0 = 0;
  58406. this.len = this.len0;
  58407. } else {
  58408. this.feedEnqueue(buf);
  58409. }
  58410. }
  58411. feedEnqueue(buf) {
  58412. this.bufs.push(buf);
  58413. this.len += buf.byteLength;
  58414. }
  58415. ensureFirstBuf() {
  58416. if (this.pos0 === this.len0) {
  58417. this.__nextBuf();
  58418. }
  58419. const buf0 = this.buf0;
  58420. if (buf0 == null || buf0.byteLength < 1) {
  58421. throw new BufferError("empty buffer");
  58422. }
  58423. return buf0;
  58424. }
  58425. checkOverread(size) {
  58426. if (this.curMessageLenUnread < size || size > this.len) {
  58427. throw new BufferError("buffer overread");
  58428. }
  58429. }
  58430. __nextBuf() {
  58431. const nextBuf = this.bufs.shift();
  58432. if (nextBuf == null) {
  58433. throw new BufferError("buffer overread");
  58434. }
  58435. this.buf0 = new DataView(nextBuf.buffer, nextBuf.byteOffset, nextBuf.byteLength);
  58436. this.pos0 = 0;
  58437. this.len0 = nextBuf.byteLength;
  58438. }
  58439. discardBuffer(size) {
  58440. this.ensureFirstBuf();
  58441. while (true) {
  58442. if (this.pos0 + size > this.len0) {
  58443. const nread = this.len0 - this.pos0;
  58444. this.pos0 = this.len0;
  58445. this.len -= nread;
  58446. size -= nread;
  58447. this.ensureFirstBuf();
  58448. } else {
  58449. this.pos0 += size;
  58450. this.len -= size;
  58451. break;
  58452. }
  58453. }
  58454. }
  58455. _finishMessage() {
  58456. this.curMessageLen = 0;
  58457. this.curMessageLenUnread = 0;
  58458. this.curMessageReady = false;
  58459. this.curMessageType = 0;
  58460. }
  58461. __readBufferCopy(buf0, size) {
  58462. const ret = new Uint8Array(size);
  58463. let retPos = 0;
  58464. while (true) {
  58465. if (this.pos0 + size > this.len0) {
  58466. const nread = this.len0 - this.pos0;
  58467. ret.set(new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, nread), retPos);
  58468. retPos += nread;
  58469. this.pos0 = this.len0;
  58470. this.len -= nread;
  58471. size -= nread;
  58472. buf0 = this.ensureFirstBuf();
  58473. } else {
  58474. ret.set(new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, size), retPos);
  58475. this.pos0 += size;
  58476. this.len -= size;
  58477. break;
  58478. }
  58479. }
  58480. return ret;
  58481. }
  58482. _readBuffer(size) {
  58483. if (size === 0) {
  58484. return EMPTY_BUFFER;
  58485. }
  58486. const buf0 = this.ensureFirstBuf();
  58487. if (this.pos0 + size <= this.len0) {
  58488. const ret = new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, size);
  58489. this.pos0 += size;
  58490. this.len -= size;
  58491. return ret;
  58492. }
  58493. return this.__readBufferCopy(buf0, size);
  58494. }
  58495. readBuffer(size) {
  58496. this.checkOverread(size);
  58497. const buf = this._readBuffer(size);
  58498. this.curMessageLenUnread -= size;
  58499. return buf;
  58500. }
  58501. readUUID() {
  58502. const buf = this.readBuffer(16);
  58503. return byteToHex2[buf[0]] + byteToHex2[buf[1]] + byteToHex2[buf[2]] + byteToHex2[buf[3]] + byteToHex2[buf[4]] + byteToHex2[buf[5]] + byteToHex2[buf[6]] + byteToHex2[buf[7]] + byteToHex2[buf[8]] + byteToHex2[buf[9]] + byteToHex2[buf[10]] + byteToHex2[buf[11]] + byteToHex2[buf[12]] + byteToHex2[buf[13]] + byteToHex2[buf[14]] + byteToHex2[buf[15]];
  58504. }
  58505. readChar() {
  58506. this.checkOverread(1);
  58507. const buf0 = this.ensureFirstBuf();
  58508. const ret = buf0.getUint8(this.pos0);
  58509. this.pos0++;
  58510. this.curMessageLenUnread--;
  58511. this.len--;
  58512. return ret;
  58513. }
  58514. readInt16() {
  58515. this.checkOverread(2);
  58516. const buf0 = this.ensureFirstBuf();
  58517. if (this.pos0 + 2 <= this.len0) {
  58518. const ret = buf0.getInt16(this.pos0);
  58519. this.pos0 += 2;
  58520. this.curMessageLenUnread -= 2;
  58521. this.len -= 2;
  58522. return ret;
  58523. }
  58524. const buf = this._readBuffer(2);
  58525. this.curMessageLenUnread -= 2;
  58526. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt16(0);
  58527. }
  58528. readInt32() {
  58529. this.checkOverread(4);
  58530. const buf0 = this.ensureFirstBuf();
  58531. if (this.pos0 + 4 <= this.len0) {
  58532. const ret = buf0.getInt32(this.pos0);
  58533. this.pos0 += 4;
  58534. this.curMessageLenUnread -= 4;
  58535. this.len -= 4;
  58536. return ret;
  58537. }
  58538. const buf = this._readBuffer(4);
  58539. this.curMessageLenUnread -= 4;
  58540. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt32(0);
  58541. }
  58542. readUInt16() {
  58543. this.checkOverread(2);
  58544. const buf0 = this.ensureFirstBuf();
  58545. if (this.pos0 + 2 <= this.len0) {
  58546. const ret = buf0.getUint16(this.pos0);
  58547. this.pos0 += 2;
  58548. this.curMessageLenUnread -= 2;
  58549. this.len -= 2;
  58550. return ret;
  58551. }
  58552. const buf = this._readBuffer(2);
  58553. this.curMessageLenUnread -= 2;
  58554. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getUint16(0);
  58555. }
  58556. readUInt32() {
  58557. this.checkOverread(4);
  58558. const buf0 = this.ensureFirstBuf();
  58559. if (this.pos0 + 4 <= this.len0) {
  58560. const ret = buf0.getUint32(this.pos0);
  58561. this.pos0 += 4;
  58562. this.curMessageLenUnread -= 4;
  58563. this.len -= 4;
  58564. return ret;
  58565. }
  58566. const buf = this._readBuffer(4);
  58567. this.curMessageLenUnread -= 4;
  58568. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getUint32(0);
  58569. }
  58570. readBigInt64() {
  58571. this.checkOverread(8);
  58572. const buf0 = this.ensureFirstBuf();
  58573. if (this.pos0 + 8 <= this.len0) {
  58574. const ret = buf0.getBigInt64(this.pos0);
  58575. this.pos0 += 8;
  58576. this.curMessageLenUnread -= 8;
  58577. this.len -= 8;
  58578. return ret;
  58579. }
  58580. const buf = this._readBuffer(8);
  58581. this.curMessageLenUnread -= 8;
  58582. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getBigInt64(0);
  58583. }
  58584. readString() {
  58585. const len = this.readInt32();
  58586. const buf = this.readBuffer(len);
  58587. return exports.utf8Decoder.decode(buf);
  58588. }
  58589. readLenPrefixedBuffer() {
  58590. const len = this.readInt32();
  58591. return this.readBuffer(len);
  58592. }
  58593. takeMessage() {
  58594. if (this.curMessageReady) {
  58595. return true;
  58596. }
  58597. if (this.curMessageType === 0) {
  58598. if (this.len < 1) {
  58599. return false;
  58600. }
  58601. const buf0 = this.ensureFirstBuf();
  58602. this.curMessageType = buf0.getUint8(this.pos0);
  58603. this.pos0++;
  58604. this.len--;
  58605. }
  58606. if (this.curMessageLen === 0) {
  58607. if (this.len < 4) {
  58608. return false;
  58609. }
  58610. const buf0 = this.ensureFirstBuf();
  58611. if (this.pos0 + 4 <= this.len0) {
  58612. this.curMessageLen = buf0.getInt32(this.pos0);
  58613. this.pos0 += 4;
  58614. this.len -= 4;
  58615. } else {
  58616. const buf = this._readBuffer(4);
  58617. this.curMessageLen = new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt32(0);
  58618. }
  58619. this.curMessageLenUnread = this.curMessageLen - 4;
  58620. }
  58621. if (this.len < this.curMessageLenUnread) {
  58622. return false;
  58623. }
  58624. this.curMessageReady = true;
  58625. return true;
  58626. }
  58627. getMessageType() {
  58628. return this.curMessageType;
  58629. }
  58630. takeMessageType(mtype) {
  58631. if (this.curMessageReady) {
  58632. return this.curMessageType === mtype;
  58633. }
  58634. if (this.len >= 1) {
  58635. const buf0 = this.ensureFirstBuf();
  58636. const unreadMessageType = buf0.getUint8(this.pos0);
  58637. return mtype === unreadMessageType && this.takeMessage();
  58638. }
  58639. return false;
  58640. }
  58641. putMessage() {
  58642. if (!this.curMessageReady) {
  58643. throw new BufferError("cannot put message: no message taken");
  58644. }
  58645. if (this.curMessageLenUnread !== this.curMessageLen - 4) {
  58646. throw new BufferError("cannot put message: message is partially read");
  58647. }
  58648. this.curMessageReady = false;
  58649. }
  58650. discardMessage() {
  58651. if (!this.curMessageReady) {
  58652. throw new BufferError("no message to discard");
  58653. }
  58654. if (this.curMessageLenUnread > 0) {
  58655. this.discardBuffer(this.curMessageLenUnread);
  58656. }
  58657. this._finishMessage();
  58658. }
  58659. consumeMessage() {
  58660. if (!this.curMessageReady) {
  58661. throw new BufferError("no message to consume");
  58662. }
  58663. let buf;
  58664. if (this.curMessageLenUnread > 0) {
  58665. buf = this._readBuffer(this.curMessageLenUnread);
  58666. this.curMessageLenUnread = 0;
  58667. } else {
  58668. buf = EMPTY_BUFFER;
  58669. }
  58670. this._finishMessage();
  58671. return buf;
  58672. }
  58673. consumeMessageInto(frb) {
  58674. if (!this.curMessageReady) {
  58675. throw new BufferError("no message to consume");
  58676. }
  58677. if (this.curMessageLenUnread > 0) {
  58678. if (this.pos0 + this.curMessageLenUnread <= this.len0) {
  58679. ReadBuffer.init(frb, new Uint8Array(this.buf0.buffer, this.buf0.byteOffset + this.pos0, this.curMessageLenUnread));
  58680. this.pos0 += this.curMessageLenUnread;
  58681. this.len -= this.curMessageLenUnread;
  58682. } else {
  58683. const buf = this._readBuffer(this.curMessageLenUnread);
  58684. ReadBuffer.init(frb, buf);
  58685. }
  58686. this.curMessageLenUnread = 0;
  58687. } else {
  58688. ReadBuffer.init(frb, EMPTY_BUFFER);
  58689. }
  58690. this._finishMessage();
  58691. }
  58692. finishMessage() {
  58693. if (this.curMessageType === 0 || !this.curMessageReady) {
  58694. return;
  58695. }
  58696. if (this.curMessageLenUnread) {
  58697. throw new BufferError(`cannot finishMessage: unread data in message "${chars.chr(this.curMessageType)}"`);
  58698. }
  58699. this._finishMessage();
  58700. }
  58701. };
  58702. exports.ReadMessageBuffer = ReadMessageBuffer;
  58703. var ReadBuffer = class {
  58704. constructor(buf) {
  58705. __publicField(this, "_rawBuffer");
  58706. __publicField(this, "buffer");
  58707. __publicField(this, "pos");
  58708. __publicField(this, "len");
  58709. this._rawBuffer = buf;
  58710. this.buffer = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
  58711. this.len = buf.length;
  58712. this.pos = 0;
  58713. }
  58714. get position() {
  58715. return this.pos;
  58716. }
  58717. get length() {
  58718. return this.len - this.pos;
  58719. }
  58720. finish(message) {
  58721. if (this.len !== this.pos) {
  58722. throw new BufferError(message ?? "unexpected trailing data in buffer");
  58723. }
  58724. }
  58725. discard(size) {
  58726. if (this.pos + size > this.len) {
  58727. throw new BufferError("buffer overread");
  58728. }
  58729. this.pos += size;
  58730. }
  58731. readUInt8() {
  58732. if (this.pos + 1 > this.len) {
  58733. throw new BufferError("buffer overread");
  58734. }
  58735. const num = this.buffer.getUint8(this.pos);
  58736. this.pos++;
  58737. return num;
  58738. }
  58739. readUInt16() {
  58740. if (this.pos + 2 > this.len) {
  58741. throw new BufferError("buffer overread");
  58742. }
  58743. const num = this.buffer.getUint16(this.pos);
  58744. this.pos += 2;
  58745. return num;
  58746. }
  58747. readInt8() {
  58748. if (this.pos + 1 > this.len) {
  58749. throw new BufferError("buffer overread");
  58750. }
  58751. const num = this.buffer.getInt8(this.pos);
  58752. this.pos++;
  58753. return num;
  58754. }
  58755. readInt16() {
  58756. if (this.pos + 2 > this.len) {
  58757. throw new BufferError("buffer overread");
  58758. }
  58759. const num = this.buffer.getInt16(this.pos);
  58760. this.pos += 2;
  58761. return num;
  58762. }
  58763. readInt32() {
  58764. if (this.pos + 4 > this.len) {
  58765. throw new BufferError("buffer overread");
  58766. }
  58767. const num = this.buffer.getInt32(this.pos);
  58768. this.pos += 4;
  58769. return num;
  58770. }
  58771. readFloat32() {
  58772. if (this.pos + 4 > this.len) {
  58773. throw new BufferError("buffer overread");
  58774. }
  58775. const num = this.buffer.getFloat32(this.pos);
  58776. this.pos += 4;
  58777. return num;
  58778. }
  58779. readFloat64(le) {
  58780. if (this.pos + 8 > this.len) {
  58781. throw new BufferError("buffer overread");
  58782. }
  58783. const num = this.buffer.getFloat64(this.pos, le);
  58784. this.pos += 8;
  58785. return num;
  58786. }
  58787. readUInt32(le) {
  58788. if (this.pos + 4 > this.len) {
  58789. throw new BufferError("buffer overread");
  58790. }
  58791. const num = this.buffer.getUint32(this.pos, le);
  58792. this.pos += 4;
  58793. return num;
  58794. }
  58795. reportInt64Overflow(hi, lo) {
  58796. const bhi = BigInt(hi);
  58797. const blo = BigInt(lo >>> 0);
  58798. const num = bhi * BigInt(4294967296) + blo;
  58799. throw new BufferError(`integer overflow: cannot unpack <std::int64>'${num.toString()}' into JavaScript Number type without losing precision`);
  58800. }
  58801. readInt64() {
  58802. if (this.pos + 8 > this.len) {
  58803. throw new BufferError("buffer overread");
  58804. }
  58805. const hi = this.buffer.getInt32(this.pos);
  58806. const lo = this.buffer.getInt32(this.pos + 4);
  58807. this.pos += 8;
  58808. if (hi === 0) {
  58809. return lo >>> 0;
  58810. } else if (hi >= -2097152 && hi < 2097152) {
  58811. return hi * 4294967296 + (lo >>> 0);
  58812. }
  58813. return this.reportInt64Overflow(hi, lo);
  58814. }
  58815. readBigInt64() {
  58816. if (this.pos + 8 > this.len) {
  58817. throw new BufferError("buffer overread");
  58818. }
  58819. const ret = this.buffer.getBigInt64(this.pos);
  58820. this.pos += 8;
  58821. return ret;
  58822. }
  58823. readBoolean() {
  58824. return this.readUInt8() !== 0;
  58825. }
  58826. readBuffer(size) {
  58827. if (this.pos + size > this.len) {
  58828. throw new BufferError("buffer overread");
  58829. }
  58830. const buf = this._rawBuffer.subarray(this.pos, this.pos + size);
  58831. this.pos += size;
  58832. return buf;
  58833. }
  58834. readUUIDBytes() {
  58835. return this.readBuffer(16);
  58836. }
  58837. readUUID(dash = "") {
  58838. if (this.pos + 16 > this.len) {
  58839. throw new BufferError("buffer overread");
  58840. }
  58841. const buf = this._rawBuffer;
  58842. const pos = this.pos;
  58843. const uuid = byteToHex2[buf[pos + 0]] + byteToHex2[buf[pos + 1]] + byteToHex2[buf[pos + 2]] + byteToHex2[buf[pos + 3]] + dash + byteToHex2[buf[pos + 4]] + byteToHex2[buf[pos + 5]] + dash + byteToHex2[buf[pos + 6]] + byteToHex2[buf[pos + 7]] + dash + byteToHex2[buf[pos + 8]] + byteToHex2[buf[pos + 9]] + dash + byteToHex2[buf[pos + 10]] + byteToHex2[buf[pos + 11]] + byteToHex2[buf[pos + 12]] + byteToHex2[buf[pos + 13]] + byteToHex2[buf[pos + 14]] + byteToHex2[buf[pos + 15]];
  58844. this.pos += 16;
  58845. return uuid;
  58846. }
  58847. readString() {
  58848. const len = this.readUInt32();
  58849. const buf = this.readBuffer(len);
  58850. return exports.utf8Decoder.decode(buf);
  58851. }
  58852. consumeAsString() {
  58853. if (this.pos === this.len) {
  58854. return "";
  58855. }
  58856. const res = exports.utf8Decoder.decode(this._rawBuffer.subarray(this.pos, this.len));
  58857. this.pos = this.len;
  58858. return res;
  58859. }
  58860. consumeAsBuffer() {
  58861. const res = this._rawBuffer.subarray(this.pos, this.len);
  58862. this.pos = this.len;
  58863. return res;
  58864. }
  58865. sliceInto(frb, size) {
  58866. if (this.pos + size > this.len) {
  58867. throw new BufferError("buffer overread");
  58868. }
  58869. frb._rawBuffer = this._rawBuffer;
  58870. frb.buffer = this.buffer;
  58871. frb.pos = this.pos;
  58872. frb.len = this.pos + size;
  58873. this.pos += size;
  58874. }
  58875. static init(frb, buffer) {
  58876. frb._rawBuffer = buffer;
  58877. frb.buffer = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  58878. frb.pos = 0;
  58879. frb.len = buffer.byteLength;
  58880. }
  58881. static alloc() {
  58882. return new this(EMPTY_BUFFER);
  58883. }
  58884. };
  58885. exports.ReadBuffer = ReadBuffer;
  58886. }
  58887. });
  58888. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/base.js
  58889. var require_base = __commonJS({
  58890. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/base.js"(exports) {
  58891. "use strict";
  58892. Object.defineProperty(exports, "__esModule", { value: true });
  58893. exports.ErrorAttr = exports.GelError = void 0;
  58894. exports.prettyPrintError = prettyPrintError;
  58895. var buffer_1 = require_buffer();
  58896. var GelError = class extends Error {
  58897. constructor(message, options) {
  58898. super(void 0, options);
  58899. __publicField(this, "_message");
  58900. __publicField(this, "_query");
  58901. __publicField(this, "_attrs");
  58902. Object.defineProperties(this, {
  58903. _message: { writable: true, enumerable: false },
  58904. _query: { writable: true, enumerable: false },
  58905. _attrs: { writable: true, enumerable: false }
  58906. });
  58907. this._message = message ?? "";
  58908. }
  58909. get message() {
  58910. return this._message + (this._query && this._attrs ? prettyPrintError(this._attrs, this._query) : "");
  58911. }
  58912. get name() {
  58913. return this.constructor.name;
  58914. }
  58915. hasTag(tag) {
  58916. const error_type = this.constructor;
  58917. return error_type.tags[tag] ?? false;
  58918. }
  58919. };
  58920. __publicField(GelError, "tags", {});
  58921. exports.GelError = GelError;
  58922. var ErrorAttr;
  58923. (function(ErrorAttr2) {
  58924. ErrorAttr2[ErrorAttr2["hint"] = 1] = "hint";
  58925. ErrorAttr2[ErrorAttr2["details"] = 2] = "details";
  58926. ErrorAttr2[ErrorAttr2["serverTraceback"] = 257] = "serverTraceback";
  58927. ErrorAttr2[ErrorAttr2["positionStart"] = -15] = "positionStart";
  58928. ErrorAttr2[ErrorAttr2["positionEnd"] = -14] = "positionEnd";
  58929. ErrorAttr2[ErrorAttr2["lineStart"] = -13] = "lineStart";
  58930. ErrorAttr2[ErrorAttr2["columnStart"] = -12] = "columnStart";
  58931. ErrorAttr2[ErrorAttr2["utf16ColumnStart"] = -11] = "utf16ColumnStart";
  58932. ErrorAttr2[ErrorAttr2["lineEnd"] = -10] = "lineEnd";
  58933. ErrorAttr2[ErrorAttr2["columnEnd"] = -9] = "columnEnd";
  58934. ErrorAttr2[ErrorAttr2["utf16ColumnEnd"] = -8] = "utf16ColumnEnd";
  58935. ErrorAttr2[ErrorAttr2["characterStart"] = -7] = "characterStart";
  58936. ErrorAttr2[ErrorAttr2["characterEnd"] = -6] = "characterEnd";
  58937. })(ErrorAttr || (exports.ErrorAttr = ErrorAttr = {}));
  58938. function tryParseInt(val2) {
  58939. if (val2 == null)
  58940. return null;
  58941. try {
  58942. return parseInt(val2 instanceof Uint8Array ? buffer_1.utf8Decoder.decode(val2) : val2, 10);
  58943. } catch {
  58944. return null;
  58945. }
  58946. }
  58947. function readAttrStr(val2) {
  58948. return val2 instanceof Uint8Array ? buffer_1.utf8Decoder.decode(val2) : val2 ?? "";
  58949. }
  58950. function prettyPrintError(attrs, query) {
  58951. let errMessage = "\n";
  58952. const lineStart = tryParseInt(attrs.get(ErrorAttr.lineStart));
  58953. const lineEnd = tryParseInt(attrs.get(ErrorAttr.lineEnd));
  58954. const colStart = tryParseInt(attrs.get(ErrorAttr.utf16ColumnStart));
  58955. const colEnd = tryParseInt(attrs.get(ErrorAttr.utf16ColumnEnd));
  58956. if (lineStart != null && lineEnd != null && colStart != null && colEnd != null) {
  58957. const queryLines = query.split("\n");
  58958. const lineNoWidth = lineEnd.toString().length;
  58959. errMessage += "|".padStart(lineNoWidth + 3) + "\n";
  58960. for (let i6 = lineStart; i6 < lineEnd + 1; i6++) {
  58961. const line = queryLines[i6 - 1];
  58962. const start = i6 === lineStart ? colStart : 0;
  58963. const end = i6 === lineEnd ? colEnd : line.length;
  58964. errMessage += ` ${i6.toString().padStart(lineNoWidth)} | ${line}
  58965. `;
  58966. errMessage += `${"|".padStart(lineNoWidth + 3)} ${"".padStart(end - start, "^").padStart(end)}
  58967. `;
  58968. }
  58969. }
  58970. if (attrs.has(ErrorAttr.details)) {
  58971. errMessage += `Details: ${readAttrStr(attrs.get(ErrorAttr.details))}
  58972. `;
  58973. }
  58974. if (attrs.has(ErrorAttr.hint)) {
  58975. errMessage += `Hint: ${readAttrStr(attrs.get(ErrorAttr.hint))}
  58976. `;
  58977. }
  58978. return errMessage;
  58979. }
  58980. }
  58981. });
  58982. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/tags.js
  58983. var require_tags = __commonJS({
  58984. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/tags.js"(exports) {
  58985. "use strict";
  58986. Object.defineProperty(exports, "__esModule", { value: true });
  58987. exports.SHOULD_RETRY = exports.SHOULD_RECONNECT = void 0;
  58988. exports.SHOULD_RECONNECT = Symbol("SHOULD_RECONNECT");
  58989. exports.SHOULD_RETRY = Symbol("SHOULD_RETRY");
  58990. }
  58991. });
  58992. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/index.js
  58993. var require_errors = __commonJS({
  58994. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/index.js"(exports) {
  58995. "use strict";
  58996. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  58997. if (k22 === void 0) k22 = k5;
  58998. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  58999. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  59000. desc = { enumerable: true, get: function() {
  59001. return m6[k5];
  59002. } };
  59003. }
  59004. Object.defineProperty(o5, k22, desc);
  59005. } : function(o5, m6, k5, k22) {
  59006. if (k22 === void 0) k22 = k5;
  59007. o5[k22] = m6[k5];
  59008. });
  59009. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  59010. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  59011. } : function(o5, v6) {
  59012. o5["default"] = v6;
  59013. });
  59014. var __importStar = exports && exports.__importStar || function(mod) {
  59015. if (mod && mod.__esModule) return mod;
  59016. var result = {};
  59017. if (mod != null) {
  59018. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  59019. }
  59020. __setModuleDefault(result, mod);
  59021. return result;
  59022. };
  59023. var __exportStar = exports && exports.__exportStar || function(m6, exports2) {
  59024. for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p5)) __createBinding(exports2, m6, p5);
  59025. };
  59026. Object.defineProperty(exports, "__esModule", { value: true });
  59027. exports.DuplicatePropertyDefinitionError = exports.DuplicateLinkDefinitionError = exports.DuplicateModuleDefinitionError = exports.DuplicateDefinitionError = exports.InvalidCastDefinitionError = exports.InvalidConstraintDefinitionError = exports.InvalidFunctionDefinitionError = exports.InvalidAliasDefinitionError = exports.InvalidOperatorDefinitionError = exports.InvalidDatabaseDefinitionError = exports.InvalidUserDefinitionError = exports.InvalidPropertyDefinitionError = exports.InvalidLinkDefinitionError = exports.InvalidModuleDefinitionError = exports.InvalidDefinitionError = exports.SchemaDefinitionError = exports.SchemaError = exports.DeprecatedScopingError = exports.UnknownParameterError = exports.UnknownDatabaseError = exports.UnknownUserError = exports.UnknownPropertyError = exports.UnknownLinkError = exports.UnknownModuleError = exports.InvalidReferenceError = exports.InvalidPropertyTargetError = exports.InvalidLinkTargetError = exports.InvalidTargetError = exports.InvalidTypeError = exports.GraphQLSyntaxError = exports.SchemaSyntaxError = exports.EdgeQLSyntaxError = exports.InvalidSyntaxError = exports.QueryError = exports.UnsafeIsolationLevelError = exports.DisabledCapabilityError = exports.UnsupportedCapabilityError = exports.CapabilityError = exports.ResultCardinalityMismatchError = exports.StateMismatchError = exports.ParameterTypeMismatchError = exports.InputDataError = exports.UnexpectedMessageError = exports.TypeSpecNotFoundError = exports.UnsupportedProtocolVersionError = exports.BinaryProtocolError = exports.ProtocolError = exports.UnsupportedFeatureError = exports.InternalServerError = exports.GelError = void 0;
  59028. exports.QueryArgumentError = exports.InterfaceError = exports.ClientConnectionClosedError = exports.ClientConnectionTimeoutError = exports.ClientConnectionFailedTemporarilyError = exports.ClientConnectionFailedError = exports.ClientConnectionError = exports.ClientError = exports.MigrationStatusMessage = exports.StatusMessage = exports.WarningMessage = exports.LogMessage = exports.UnsupportedBackendFeatureError = exports.BackendError = exports.ServerBlockedError = exports.UnknownTenantError = exports.ServerOfflineError = exports.BackendUnavailableError = exports.AvailabilityError = exports.AuthenticationError = exports.AccessError = exports.ConfigurationError = exports.WatchError = exports.TransactionDeadlockError = exports.TransactionSerializationError = exports.TransactionConflictError = exports.TransactionError = exports.MissingRequiredError = exports.CardinalityViolationError = exports.ConstraintViolationError = exports.IntegrityError = exports.QueryAssertionError = exports.AccessPolicyError = exports.NumericOutOfRangeError = exports.DivisionByZeroError = exports.InvalidValueError = exports.ExecutionError = exports.IdleTransactionTimeoutError = exports.TransactionTimeoutError = exports.QueryTimeoutError = exports.IdleSessionTimeoutError = exports.SessionTimeoutError = exports.DuplicateMigrationError = exports.DuplicateCastDefinitionError = exports.DuplicateConstraintDefinitionError = exports.DuplicateFunctionDefinitionError = exports.DuplicateViewDefinitionError = exports.DuplicateOperatorDefinitionError = exports.DuplicateDatabaseDefinitionError = exports.DuplicateUserDefinitionError = void 0;
  59029. exports.InternalClientError = exports.NoDataError = exports.InvalidArgumentError = exports.UnknownArgumentError = exports.MissingArgumentError = void 0;
  59030. var base_1 = require_base();
  59031. var tags = __importStar(require_tags());
  59032. var base_2 = require_base();
  59033. Object.defineProperty(exports, "GelError", { enumerable: true, get: function() {
  59034. return base_2.GelError;
  59035. } });
  59036. __exportStar(require_tags(), exports);
  59037. var InternalServerError = class extends base_1.GelError {
  59038. get code() {
  59039. return 16777216;
  59040. }
  59041. };
  59042. exports.InternalServerError = InternalServerError;
  59043. var UnsupportedFeatureError = class extends base_1.GelError {
  59044. get code() {
  59045. return 33554432;
  59046. }
  59047. };
  59048. exports.UnsupportedFeatureError = UnsupportedFeatureError;
  59049. var ProtocolError = class extends base_1.GelError {
  59050. get code() {
  59051. return 50331648;
  59052. }
  59053. };
  59054. exports.ProtocolError = ProtocolError;
  59055. var BinaryProtocolError = class extends ProtocolError {
  59056. get code() {
  59057. return 50397184;
  59058. }
  59059. };
  59060. exports.BinaryProtocolError = BinaryProtocolError;
  59061. var UnsupportedProtocolVersionError = class extends BinaryProtocolError {
  59062. get code() {
  59063. return 50397185;
  59064. }
  59065. };
  59066. exports.UnsupportedProtocolVersionError = UnsupportedProtocolVersionError;
  59067. var TypeSpecNotFoundError = class extends BinaryProtocolError {
  59068. get code() {
  59069. return 50397186;
  59070. }
  59071. };
  59072. exports.TypeSpecNotFoundError = TypeSpecNotFoundError;
  59073. var UnexpectedMessageError = class extends BinaryProtocolError {
  59074. get code() {
  59075. return 50397187;
  59076. }
  59077. };
  59078. exports.UnexpectedMessageError = UnexpectedMessageError;
  59079. var InputDataError = class extends ProtocolError {
  59080. get code() {
  59081. return 50462720;
  59082. }
  59083. };
  59084. exports.InputDataError = InputDataError;
  59085. var ParameterTypeMismatchError = class extends InputDataError {
  59086. get code() {
  59087. return 50462976;
  59088. }
  59089. };
  59090. exports.ParameterTypeMismatchError = ParameterTypeMismatchError;
  59091. var StateMismatchError = class extends InputDataError {
  59092. get code() {
  59093. return 50463232;
  59094. }
  59095. };
  59096. __publicField(StateMismatchError, "tags", { [tags.SHOULD_RETRY]: true });
  59097. exports.StateMismatchError = StateMismatchError;
  59098. var ResultCardinalityMismatchError = class extends ProtocolError {
  59099. get code() {
  59100. return 50528256;
  59101. }
  59102. };
  59103. exports.ResultCardinalityMismatchError = ResultCardinalityMismatchError;
  59104. var CapabilityError = class extends ProtocolError {
  59105. get code() {
  59106. return 50593792;
  59107. }
  59108. };
  59109. exports.CapabilityError = CapabilityError;
  59110. var UnsupportedCapabilityError = class extends CapabilityError {
  59111. get code() {
  59112. return 50594048;
  59113. }
  59114. };
  59115. exports.UnsupportedCapabilityError = UnsupportedCapabilityError;
  59116. var DisabledCapabilityError = class extends CapabilityError {
  59117. get code() {
  59118. return 50594304;
  59119. }
  59120. };
  59121. exports.DisabledCapabilityError = DisabledCapabilityError;
  59122. var UnsafeIsolationLevelError = class extends CapabilityError {
  59123. get code() {
  59124. return 50594560;
  59125. }
  59126. };
  59127. exports.UnsafeIsolationLevelError = UnsafeIsolationLevelError;
  59128. var QueryError = class extends base_1.GelError {
  59129. get code() {
  59130. return 67108864;
  59131. }
  59132. };
  59133. exports.QueryError = QueryError;
  59134. var InvalidSyntaxError = class extends QueryError {
  59135. get code() {
  59136. return 67174400;
  59137. }
  59138. };
  59139. exports.InvalidSyntaxError = InvalidSyntaxError;
  59140. var EdgeQLSyntaxError = class extends InvalidSyntaxError {
  59141. get code() {
  59142. return 67174656;
  59143. }
  59144. };
  59145. exports.EdgeQLSyntaxError = EdgeQLSyntaxError;
  59146. var SchemaSyntaxError = class extends InvalidSyntaxError {
  59147. get code() {
  59148. return 67174912;
  59149. }
  59150. };
  59151. exports.SchemaSyntaxError = SchemaSyntaxError;
  59152. var GraphQLSyntaxError = class extends InvalidSyntaxError {
  59153. get code() {
  59154. return 67175168;
  59155. }
  59156. };
  59157. exports.GraphQLSyntaxError = GraphQLSyntaxError;
  59158. var InvalidTypeError = class extends QueryError {
  59159. get code() {
  59160. return 67239936;
  59161. }
  59162. };
  59163. exports.InvalidTypeError = InvalidTypeError;
  59164. var InvalidTargetError = class extends InvalidTypeError {
  59165. get code() {
  59166. return 67240192;
  59167. }
  59168. };
  59169. exports.InvalidTargetError = InvalidTargetError;
  59170. var InvalidLinkTargetError = class extends InvalidTargetError {
  59171. get code() {
  59172. return 67240193;
  59173. }
  59174. };
  59175. exports.InvalidLinkTargetError = InvalidLinkTargetError;
  59176. var InvalidPropertyTargetError = class extends InvalidTargetError {
  59177. get code() {
  59178. return 67240194;
  59179. }
  59180. };
  59181. exports.InvalidPropertyTargetError = InvalidPropertyTargetError;
  59182. var InvalidReferenceError = class extends QueryError {
  59183. get code() {
  59184. return 67305472;
  59185. }
  59186. };
  59187. exports.InvalidReferenceError = InvalidReferenceError;
  59188. var UnknownModuleError = class extends InvalidReferenceError {
  59189. get code() {
  59190. return 67305473;
  59191. }
  59192. };
  59193. exports.UnknownModuleError = UnknownModuleError;
  59194. var UnknownLinkError = class extends InvalidReferenceError {
  59195. get code() {
  59196. return 67305474;
  59197. }
  59198. };
  59199. exports.UnknownLinkError = UnknownLinkError;
  59200. var UnknownPropertyError = class extends InvalidReferenceError {
  59201. get code() {
  59202. return 67305475;
  59203. }
  59204. };
  59205. exports.UnknownPropertyError = UnknownPropertyError;
  59206. var UnknownUserError = class extends InvalidReferenceError {
  59207. get code() {
  59208. return 67305476;
  59209. }
  59210. };
  59211. exports.UnknownUserError = UnknownUserError;
  59212. var UnknownDatabaseError = class extends InvalidReferenceError {
  59213. get code() {
  59214. return 67305477;
  59215. }
  59216. };
  59217. exports.UnknownDatabaseError = UnknownDatabaseError;
  59218. var UnknownParameterError = class extends InvalidReferenceError {
  59219. get code() {
  59220. return 67305478;
  59221. }
  59222. };
  59223. exports.UnknownParameterError = UnknownParameterError;
  59224. var DeprecatedScopingError = class extends InvalidReferenceError {
  59225. get code() {
  59226. return 67305479;
  59227. }
  59228. };
  59229. exports.DeprecatedScopingError = DeprecatedScopingError;
  59230. var SchemaError = class extends QueryError {
  59231. get code() {
  59232. return 67371008;
  59233. }
  59234. };
  59235. exports.SchemaError = SchemaError;
  59236. var SchemaDefinitionError = class extends QueryError {
  59237. get code() {
  59238. return 67436544;
  59239. }
  59240. };
  59241. exports.SchemaDefinitionError = SchemaDefinitionError;
  59242. var InvalidDefinitionError = class extends SchemaDefinitionError {
  59243. get code() {
  59244. return 67436800;
  59245. }
  59246. };
  59247. exports.InvalidDefinitionError = InvalidDefinitionError;
  59248. var InvalidModuleDefinitionError = class extends InvalidDefinitionError {
  59249. get code() {
  59250. return 67436801;
  59251. }
  59252. };
  59253. exports.InvalidModuleDefinitionError = InvalidModuleDefinitionError;
  59254. var InvalidLinkDefinitionError = class extends InvalidDefinitionError {
  59255. get code() {
  59256. return 67436802;
  59257. }
  59258. };
  59259. exports.InvalidLinkDefinitionError = InvalidLinkDefinitionError;
  59260. var InvalidPropertyDefinitionError = class extends InvalidDefinitionError {
  59261. get code() {
  59262. return 67436803;
  59263. }
  59264. };
  59265. exports.InvalidPropertyDefinitionError = InvalidPropertyDefinitionError;
  59266. var InvalidUserDefinitionError = class extends InvalidDefinitionError {
  59267. get code() {
  59268. return 67436804;
  59269. }
  59270. };
  59271. exports.InvalidUserDefinitionError = InvalidUserDefinitionError;
  59272. var InvalidDatabaseDefinitionError = class extends InvalidDefinitionError {
  59273. get code() {
  59274. return 67436805;
  59275. }
  59276. };
  59277. exports.InvalidDatabaseDefinitionError = InvalidDatabaseDefinitionError;
  59278. var InvalidOperatorDefinitionError = class extends InvalidDefinitionError {
  59279. get code() {
  59280. return 67436806;
  59281. }
  59282. };
  59283. exports.InvalidOperatorDefinitionError = InvalidOperatorDefinitionError;
  59284. var InvalidAliasDefinitionError = class extends InvalidDefinitionError {
  59285. get code() {
  59286. return 67436807;
  59287. }
  59288. };
  59289. exports.InvalidAliasDefinitionError = InvalidAliasDefinitionError;
  59290. var InvalidFunctionDefinitionError = class extends InvalidDefinitionError {
  59291. get code() {
  59292. return 67436808;
  59293. }
  59294. };
  59295. exports.InvalidFunctionDefinitionError = InvalidFunctionDefinitionError;
  59296. var InvalidConstraintDefinitionError = class extends InvalidDefinitionError {
  59297. get code() {
  59298. return 67436809;
  59299. }
  59300. };
  59301. exports.InvalidConstraintDefinitionError = InvalidConstraintDefinitionError;
  59302. var InvalidCastDefinitionError = class extends InvalidDefinitionError {
  59303. get code() {
  59304. return 67436810;
  59305. }
  59306. };
  59307. exports.InvalidCastDefinitionError = InvalidCastDefinitionError;
  59308. var DuplicateDefinitionError = class extends SchemaDefinitionError {
  59309. get code() {
  59310. return 67437056;
  59311. }
  59312. };
  59313. exports.DuplicateDefinitionError = DuplicateDefinitionError;
  59314. var DuplicateModuleDefinitionError = class extends DuplicateDefinitionError {
  59315. get code() {
  59316. return 67437057;
  59317. }
  59318. };
  59319. exports.DuplicateModuleDefinitionError = DuplicateModuleDefinitionError;
  59320. var DuplicateLinkDefinitionError = class extends DuplicateDefinitionError {
  59321. get code() {
  59322. return 67437058;
  59323. }
  59324. };
  59325. exports.DuplicateLinkDefinitionError = DuplicateLinkDefinitionError;
  59326. var DuplicatePropertyDefinitionError = class extends DuplicateDefinitionError {
  59327. get code() {
  59328. return 67437059;
  59329. }
  59330. };
  59331. exports.DuplicatePropertyDefinitionError = DuplicatePropertyDefinitionError;
  59332. var DuplicateUserDefinitionError = class extends DuplicateDefinitionError {
  59333. get code() {
  59334. return 67437060;
  59335. }
  59336. };
  59337. exports.DuplicateUserDefinitionError = DuplicateUserDefinitionError;
  59338. var DuplicateDatabaseDefinitionError = class extends DuplicateDefinitionError {
  59339. get code() {
  59340. return 67437061;
  59341. }
  59342. };
  59343. exports.DuplicateDatabaseDefinitionError = DuplicateDatabaseDefinitionError;
  59344. var DuplicateOperatorDefinitionError = class extends DuplicateDefinitionError {
  59345. get code() {
  59346. return 67437062;
  59347. }
  59348. };
  59349. exports.DuplicateOperatorDefinitionError = DuplicateOperatorDefinitionError;
  59350. var DuplicateViewDefinitionError = class extends DuplicateDefinitionError {
  59351. get code() {
  59352. return 67437063;
  59353. }
  59354. };
  59355. exports.DuplicateViewDefinitionError = DuplicateViewDefinitionError;
  59356. var DuplicateFunctionDefinitionError = class extends DuplicateDefinitionError {
  59357. get code() {
  59358. return 67437064;
  59359. }
  59360. };
  59361. exports.DuplicateFunctionDefinitionError = DuplicateFunctionDefinitionError;
  59362. var DuplicateConstraintDefinitionError = class extends DuplicateDefinitionError {
  59363. get code() {
  59364. return 67437065;
  59365. }
  59366. };
  59367. exports.DuplicateConstraintDefinitionError = DuplicateConstraintDefinitionError;
  59368. var DuplicateCastDefinitionError = class extends DuplicateDefinitionError {
  59369. get code() {
  59370. return 67437066;
  59371. }
  59372. };
  59373. exports.DuplicateCastDefinitionError = DuplicateCastDefinitionError;
  59374. var DuplicateMigrationError = class extends DuplicateDefinitionError {
  59375. get code() {
  59376. return 67437067;
  59377. }
  59378. };
  59379. exports.DuplicateMigrationError = DuplicateMigrationError;
  59380. var SessionTimeoutError = class extends QueryError {
  59381. get code() {
  59382. return 67502080;
  59383. }
  59384. };
  59385. exports.SessionTimeoutError = SessionTimeoutError;
  59386. var IdleSessionTimeoutError = class extends SessionTimeoutError {
  59387. get code() {
  59388. return 67502336;
  59389. }
  59390. };
  59391. __publicField(IdleSessionTimeoutError, "tags", { [tags.SHOULD_RETRY]: true });
  59392. exports.IdleSessionTimeoutError = IdleSessionTimeoutError;
  59393. var QueryTimeoutError = class extends SessionTimeoutError {
  59394. get code() {
  59395. return 67502592;
  59396. }
  59397. };
  59398. exports.QueryTimeoutError = QueryTimeoutError;
  59399. var TransactionTimeoutError = class extends SessionTimeoutError {
  59400. get code() {
  59401. return 67504640;
  59402. }
  59403. };
  59404. exports.TransactionTimeoutError = TransactionTimeoutError;
  59405. var IdleTransactionTimeoutError = class extends TransactionTimeoutError {
  59406. get code() {
  59407. return 67504641;
  59408. }
  59409. };
  59410. exports.IdleTransactionTimeoutError = IdleTransactionTimeoutError;
  59411. var ExecutionError = class extends base_1.GelError {
  59412. get code() {
  59413. return 83886080;
  59414. }
  59415. };
  59416. exports.ExecutionError = ExecutionError;
  59417. var InvalidValueError = class extends ExecutionError {
  59418. get code() {
  59419. return 83951616;
  59420. }
  59421. };
  59422. exports.InvalidValueError = InvalidValueError;
  59423. var DivisionByZeroError = class extends InvalidValueError {
  59424. get code() {
  59425. return 83951617;
  59426. }
  59427. };
  59428. exports.DivisionByZeroError = DivisionByZeroError;
  59429. var NumericOutOfRangeError = class extends InvalidValueError {
  59430. get code() {
  59431. return 83951618;
  59432. }
  59433. };
  59434. exports.NumericOutOfRangeError = NumericOutOfRangeError;
  59435. var AccessPolicyError = class extends InvalidValueError {
  59436. get code() {
  59437. return 83951619;
  59438. }
  59439. };
  59440. exports.AccessPolicyError = AccessPolicyError;
  59441. var QueryAssertionError = class extends InvalidValueError {
  59442. get code() {
  59443. return 83951620;
  59444. }
  59445. };
  59446. exports.QueryAssertionError = QueryAssertionError;
  59447. var IntegrityError = class extends ExecutionError {
  59448. get code() {
  59449. return 84017152;
  59450. }
  59451. };
  59452. exports.IntegrityError = IntegrityError;
  59453. var ConstraintViolationError = class extends IntegrityError {
  59454. get code() {
  59455. return 84017153;
  59456. }
  59457. };
  59458. exports.ConstraintViolationError = ConstraintViolationError;
  59459. var CardinalityViolationError = class extends IntegrityError {
  59460. get code() {
  59461. return 84017154;
  59462. }
  59463. };
  59464. exports.CardinalityViolationError = CardinalityViolationError;
  59465. var MissingRequiredError = class extends IntegrityError {
  59466. get code() {
  59467. return 84017155;
  59468. }
  59469. };
  59470. exports.MissingRequiredError = MissingRequiredError;
  59471. var TransactionError = class extends ExecutionError {
  59472. get code() {
  59473. return 84082688;
  59474. }
  59475. };
  59476. exports.TransactionError = TransactionError;
  59477. var TransactionConflictError = class extends TransactionError {
  59478. get code() {
  59479. return 84082944;
  59480. }
  59481. };
  59482. __publicField(TransactionConflictError, "tags", { [tags.SHOULD_RETRY]: true });
  59483. exports.TransactionConflictError = TransactionConflictError;
  59484. var TransactionSerializationError = class extends TransactionConflictError {
  59485. get code() {
  59486. return 84082945;
  59487. }
  59488. };
  59489. __publicField(TransactionSerializationError, "tags", { [tags.SHOULD_RETRY]: true });
  59490. exports.TransactionSerializationError = TransactionSerializationError;
  59491. var TransactionDeadlockError = class extends TransactionConflictError {
  59492. get code() {
  59493. return 84082946;
  59494. }
  59495. };
  59496. __publicField(TransactionDeadlockError, "tags", { [tags.SHOULD_RETRY]: true });
  59497. exports.TransactionDeadlockError = TransactionDeadlockError;
  59498. var WatchError = class extends ExecutionError {
  59499. get code() {
  59500. return 84148224;
  59501. }
  59502. };
  59503. exports.WatchError = WatchError;
  59504. var ConfigurationError = class extends base_1.GelError {
  59505. get code() {
  59506. return 100663296;
  59507. }
  59508. };
  59509. exports.ConfigurationError = ConfigurationError;
  59510. var AccessError = class extends base_1.GelError {
  59511. get code() {
  59512. return 117440512;
  59513. }
  59514. };
  59515. exports.AccessError = AccessError;
  59516. var AuthenticationError = class extends AccessError {
  59517. get code() {
  59518. return 117506048;
  59519. }
  59520. };
  59521. exports.AuthenticationError = AuthenticationError;
  59522. var AvailabilityError = class extends base_1.GelError {
  59523. get code() {
  59524. return 134217728;
  59525. }
  59526. };
  59527. exports.AvailabilityError = AvailabilityError;
  59528. var BackendUnavailableError = class extends AvailabilityError {
  59529. get code() {
  59530. return 134217729;
  59531. }
  59532. };
  59533. __publicField(BackendUnavailableError, "tags", { [tags.SHOULD_RETRY]: true });
  59534. exports.BackendUnavailableError = BackendUnavailableError;
  59535. var ServerOfflineError = class extends AvailabilityError {
  59536. get code() {
  59537. return 134217730;
  59538. }
  59539. };
  59540. __publicField(ServerOfflineError, "tags", {
  59541. [tags.SHOULD_RECONNECT]: true,
  59542. [tags.SHOULD_RETRY]: true
  59543. });
  59544. exports.ServerOfflineError = ServerOfflineError;
  59545. var UnknownTenantError = class extends AvailabilityError {
  59546. get code() {
  59547. return 134217731;
  59548. }
  59549. };
  59550. __publicField(UnknownTenantError, "tags", {
  59551. [tags.SHOULD_RECONNECT]: true,
  59552. [tags.SHOULD_RETRY]: true
  59553. });
  59554. exports.UnknownTenantError = UnknownTenantError;
  59555. var ServerBlockedError = class extends AvailabilityError {
  59556. get code() {
  59557. return 134217732;
  59558. }
  59559. };
  59560. exports.ServerBlockedError = ServerBlockedError;
  59561. var BackendError = class extends base_1.GelError {
  59562. get code() {
  59563. return 150994944;
  59564. }
  59565. };
  59566. exports.BackendError = BackendError;
  59567. var UnsupportedBackendFeatureError = class extends BackendError {
  59568. get code() {
  59569. return 150995200;
  59570. }
  59571. };
  59572. exports.UnsupportedBackendFeatureError = UnsupportedBackendFeatureError;
  59573. var LogMessage = class extends base_1.GelError {
  59574. get code() {
  59575. return 4026531840;
  59576. }
  59577. };
  59578. exports.LogMessage = LogMessage;
  59579. var WarningMessage = class extends LogMessage {
  59580. get code() {
  59581. return 4026597376;
  59582. }
  59583. };
  59584. exports.WarningMessage = WarningMessage;
  59585. var StatusMessage = class extends LogMessage {
  59586. get code() {
  59587. return 4026662912;
  59588. }
  59589. };
  59590. exports.StatusMessage = StatusMessage;
  59591. var MigrationStatusMessage = class extends StatusMessage {
  59592. get code() {
  59593. return 4026662913;
  59594. }
  59595. };
  59596. exports.MigrationStatusMessage = MigrationStatusMessage;
  59597. var ClientError = class extends base_1.GelError {
  59598. get code() {
  59599. return 4278190080;
  59600. }
  59601. };
  59602. exports.ClientError = ClientError;
  59603. var ClientConnectionError = class extends ClientError {
  59604. get code() {
  59605. return 4278255616;
  59606. }
  59607. };
  59608. exports.ClientConnectionError = ClientConnectionError;
  59609. var ClientConnectionFailedError = class extends ClientConnectionError {
  59610. get code() {
  59611. return 4278255872;
  59612. }
  59613. };
  59614. exports.ClientConnectionFailedError = ClientConnectionFailedError;
  59615. var ClientConnectionFailedTemporarilyError = class extends ClientConnectionFailedError {
  59616. get code() {
  59617. return 4278255873;
  59618. }
  59619. };
  59620. __publicField(ClientConnectionFailedTemporarilyError, "tags", {
  59621. [tags.SHOULD_RECONNECT]: true,
  59622. [tags.SHOULD_RETRY]: true
  59623. });
  59624. exports.ClientConnectionFailedTemporarilyError = ClientConnectionFailedTemporarilyError;
  59625. var ClientConnectionTimeoutError = class extends ClientConnectionError {
  59626. get code() {
  59627. return 4278256128;
  59628. }
  59629. };
  59630. __publicField(ClientConnectionTimeoutError, "tags", {
  59631. [tags.SHOULD_RECONNECT]: true,
  59632. [tags.SHOULD_RETRY]: true
  59633. });
  59634. exports.ClientConnectionTimeoutError = ClientConnectionTimeoutError;
  59635. var ClientConnectionClosedError = class extends ClientConnectionError {
  59636. get code() {
  59637. return 4278256384;
  59638. }
  59639. };
  59640. __publicField(ClientConnectionClosedError, "tags", {
  59641. [tags.SHOULD_RECONNECT]: true,
  59642. [tags.SHOULD_RETRY]: true
  59643. });
  59644. exports.ClientConnectionClosedError = ClientConnectionClosedError;
  59645. var InterfaceError = class extends ClientError {
  59646. get code() {
  59647. return 4278321152;
  59648. }
  59649. };
  59650. exports.InterfaceError = InterfaceError;
  59651. var QueryArgumentError = class extends InterfaceError {
  59652. get code() {
  59653. return 4278321408;
  59654. }
  59655. };
  59656. exports.QueryArgumentError = QueryArgumentError;
  59657. var MissingArgumentError = class extends QueryArgumentError {
  59658. get code() {
  59659. return 4278321409;
  59660. }
  59661. };
  59662. exports.MissingArgumentError = MissingArgumentError;
  59663. var UnknownArgumentError = class extends QueryArgumentError {
  59664. get code() {
  59665. return 4278321410;
  59666. }
  59667. };
  59668. exports.UnknownArgumentError = UnknownArgumentError;
  59669. var InvalidArgumentError = class extends QueryArgumentError {
  59670. get code() {
  59671. return 4278321411;
  59672. }
  59673. };
  59674. exports.InvalidArgumentError = InvalidArgumentError;
  59675. var NoDataError = class extends ClientError {
  59676. get code() {
  59677. return 4278386688;
  59678. }
  59679. };
  59680. exports.NoDataError = NoDataError;
  59681. var InternalClientError = class extends ClientError {
  59682. get code() {
  59683. return 4278452224;
  59684. }
  59685. };
  59686. exports.InternalClientError = InternalClientError;
  59687. }
  59688. });
  59689. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/lru.js
  59690. var require_lru = __commonJS({
  59691. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/lru.js"(exports) {
  59692. "use strict";
  59693. Object.defineProperty(exports, "__esModule", { value: true });
  59694. var errors_1 = require_errors();
  59695. var Node3 = class {
  59696. constructor(key, value) {
  59697. __publicField(this, "key");
  59698. __publicField(this, "value");
  59699. __publicField(this, "next");
  59700. __publicField(this, "prev");
  59701. this.key = key;
  59702. this.value = value;
  59703. this.next = null;
  59704. this.prev = null;
  59705. }
  59706. };
  59707. var Deque = class {
  59708. constructor() {
  59709. __publicField(this, "head");
  59710. __publicField(this, "tail");
  59711. __publicField(this, "len");
  59712. this.head = null;
  59713. this.tail = null;
  59714. this.len = 0;
  59715. }
  59716. get length() {
  59717. return this.len;
  59718. }
  59719. push(key, value) {
  59720. const node = new Node3(key, value);
  59721. if (this.head == null) {
  59722. this.head = node;
  59723. this.tail = node;
  59724. } else {
  59725. this.head.prev = node;
  59726. node.next = this.head;
  59727. this.head = node;
  59728. }
  59729. this.len++;
  59730. return node;
  59731. }
  59732. moveToTop(node) {
  59733. if (node.prev == null) {
  59734. return;
  59735. }
  59736. const prev = node.prev;
  59737. const next = node.next;
  59738. prev.next = next;
  59739. if (next != null) {
  59740. next.prev = prev;
  59741. }
  59742. if (this.tail === node) {
  59743. this.tail = prev;
  59744. }
  59745. node.prev = null;
  59746. node.next = this.head;
  59747. this.head.prev = node;
  59748. this.head = node;
  59749. }
  59750. deleteBottom() {
  59751. if (!this.len || !this.tail || !this.head) {
  59752. return null;
  59753. }
  59754. if (this.tail === this.head) {
  59755. this.len = 0;
  59756. const node = this.tail;
  59757. this.tail = null;
  59758. this.head = null;
  59759. return node;
  59760. }
  59761. const tail = this.tail;
  59762. const beforeLast = this.tail.prev;
  59763. beforeLast.next = null;
  59764. this.tail.prev = null;
  59765. this.tail.next = null;
  59766. this.tail = beforeLast;
  59767. this.len--;
  59768. return tail;
  59769. }
  59770. };
  59771. var LRU = class {
  59772. constructor({ capacity }) {
  59773. __publicField(this, "capacity");
  59774. __publicField(this, "map");
  59775. __publicField(this, "deque");
  59776. if (capacity <= 0) {
  59777. throw new TypeError("capacity is expected to be greater than 0");
  59778. }
  59779. this.capacity = capacity;
  59780. this.map = /* @__PURE__ */ new Map();
  59781. this.deque = new Deque();
  59782. }
  59783. get length() {
  59784. const len = this.map.size;
  59785. if (len !== this.deque.length) {
  59786. throw new errors_1.InternalClientError("deque & map disagree on elements count");
  59787. }
  59788. return len;
  59789. }
  59790. has(key) {
  59791. return this.map.has(key);
  59792. }
  59793. get(key) {
  59794. const node = this.map.get(key);
  59795. if (node != null) {
  59796. this.deque.moveToTop(node);
  59797. return node.value;
  59798. }
  59799. return void 0;
  59800. }
  59801. set(key, value) {
  59802. const existingNode = this.map.get(key);
  59803. if (existingNode != null) {
  59804. existingNode.value = value;
  59805. this.deque.moveToTop(existingNode);
  59806. } else {
  59807. const newNode = this.deque.push(key, value);
  59808. this.map.set(key, newNode);
  59809. while (this.deque.length > this.capacity) {
  59810. const bottomNode = this.deque.deleteBottom();
  59811. this.map.delete(bottomNode.key);
  59812. }
  59813. }
  59814. }
  59815. *keys() {
  59816. let node = this.deque.head;
  59817. while (node != null) {
  59818. yield node.key;
  59819. node = node.next;
  59820. }
  59821. }
  59822. *entries() {
  59823. let node = this.deque.head;
  59824. while (node != null) {
  59825. yield [node.key, node.value];
  59826. node = node.next;
  59827. }
  59828. }
  59829. *values() {
  59830. let node = this.deque.head;
  59831. while (node != null) {
  59832. yield node.value;
  59833. node = node.next;
  59834. }
  59835. }
  59836. };
  59837. exports.default = LRU;
  59838. }
  59839. });
  59840. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/consts.js
  59841. var require_consts = __commonJS({
  59842. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/consts.js"(exports) {
  59843. "use strict";
  59844. Object.defineProperty(exports, "__esModule", { value: true });
  59845. exports.KNOWN_TYPENAMES = exports.KNOWN_TYPES = exports.INVALID_CODEC_ID = exports.NULL_CODEC_ID = void 0;
  59846. exports.NULL_CODEC_ID = "00000000000000000000000000000000";
  59847. exports.INVALID_CODEC_ID = "ffffffffffffffffffffffffffffffff";
  59848. exports.KNOWN_TYPES = /* @__PURE__ */ new Map([
  59849. ["00000000000000000000000000000001", "anytype"],
  59850. ["00000000000000000000000000000002", "anytuple"],
  59851. ["00000000000000000000000000000003", "anyobject"],
  59852. ["000000000000000000000000000000f0", "std"],
  59853. ["000000000000000000000000000000ff", "empty-tuple"],
  59854. ["00000000000000000000000000000100", "std::uuid"],
  59855. ["00000000000000000000000000000101", "std::str"],
  59856. ["00000000000000000000000000000102", "std::bytes"],
  59857. ["00000000000000000000000000000103", "std::int16"],
  59858. ["00000000000000000000000000000104", "std::int32"],
  59859. ["00000000000000000000000000000105", "std::int64"],
  59860. ["00000000000000000000000000000106", "std::float32"],
  59861. ["00000000000000000000000000000107", "std::float64"],
  59862. ["00000000000000000000000000000108", "std::decimal"],
  59863. ["00000000000000000000000000000109", "std::bool"],
  59864. ["0000000000000000000000000000010a", "std::datetime"],
  59865. ["0000000000000000000000000000010b", "cal::local_datetime"],
  59866. ["0000000000000000000000000000010c", "cal::local_date"],
  59867. ["0000000000000000000000000000010d", "cal::local_time"],
  59868. ["0000000000000000000000000000010e", "std::duration"],
  59869. ["0000000000000000000000000000010f", "std::json"],
  59870. ["00000000000000000000000000000110", "std::bigint"],
  59871. ["00000000000000000000000000000111", "cal::relative_duration"],
  59872. ["00000000000000000000000000000112", "cal::date_duration"],
  59873. ["00000000000000000000000000000130", "cfg::memory"],
  59874. ["00000000000000000000000001000001", "std::pg::json"],
  59875. ["00000000000000000000000001000002", "std::pg::timestamptz"],
  59876. ["00000000000000000000000001000003", "std::pg::timestamp"],
  59877. ["00000000000000000000000001000004", "std::pg::date"],
  59878. ["00000000000000000000000001000005", "std::pg::interval"],
  59879. ["9565dd8804f511eea6910b6ebe179825", "ext::pgvector::vector"],
  59880. ["4ba84534188e43b4a7cecea2af0f405b", "ext::pgvector::halfvec"],
  59881. ["003e434dcac2430ab238fb39d73447d2", "ext::pgvector::sparsevec"],
  59882. ["44c901c0d922489483c8061bd05e4840", "ext::postgis::geometry"],
  59883. ["4d7388783a5f4821ab769d8e7d6b32c4", "ext::postgis::geography"],
  59884. ["7fae553663114f608eb9096a5d972f48", "ext::postgis::box2d"],
  59885. ["c1a50ff8fded48b085c24905a8481433", "ext::postgis::box3d"]
  59886. ]);
  59887. exports.KNOWN_TYPENAMES = (() => {
  59888. const res = /* @__PURE__ */ new Map();
  59889. for (const [id, name] of exports.KNOWN_TYPES.entries()) {
  59890. res.set(name, id);
  59891. }
  59892. return res;
  59893. })();
  59894. }
  59895. });
  59896. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/ifaces.js
  59897. var require_ifaces = __commonJS({
  59898. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/ifaces.js"(exports) {
  59899. "use strict";
  59900. Object.defineProperty(exports, "__esModule", { value: true });
  59901. exports.ScalarCodec = exports.Codec = void 0;
  59902. var buffer_1 = require_buffer();
  59903. var consts_1 = require_consts();
  59904. var Codec = class {
  59905. constructor(tid) {
  59906. __publicField(this, "tid");
  59907. __publicField(this, "tidBuffer");
  59908. this.tid = tid;
  59909. this.tidBuffer = (0, buffer_1.uuidToBuffer)(tid);
  59910. }
  59911. getKnownTypeName() {
  59912. return "anytype";
  59913. }
  59914. };
  59915. exports.Codec = Codec;
  59916. var ScalarCodec = class extends Codec {
  59917. constructor(tid, typeName) {
  59918. super(tid);
  59919. __publicField(this, "typeName");
  59920. __publicField(this, "ancestors", null);
  59921. __publicField(this, "tsType", "unknown");
  59922. __publicField(this, "tsModule", null);
  59923. this.typeName = typeName;
  59924. }
  59925. derive(tid, typeName, ancestors) {
  59926. const self2 = this.constructor;
  59927. const codec = new self2(tid, typeName);
  59928. codec.ancestors = ancestors;
  59929. return codec;
  59930. }
  59931. getSubcodecs() {
  59932. return [];
  59933. }
  59934. getKind() {
  59935. return "scalar";
  59936. }
  59937. getKnownTypeName() {
  59938. if (this.typeName) {
  59939. return this.typeName;
  59940. }
  59941. return consts_1.KNOWN_TYPES.get(this.tid) || "anytype";
  59942. }
  59943. };
  59944. exports.ScalarCodec = ScalarCodec;
  59945. }
  59946. });
  59947. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/boolean.js
  59948. var require_boolean = __commonJS({
  59949. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/boolean.js"(exports) {
  59950. "use strict";
  59951. Object.defineProperty(exports, "__esModule", { value: true });
  59952. exports.BoolCodec = void 0;
  59953. var ifaces_1 = require_ifaces();
  59954. var errors_1 = require_errors();
  59955. var BoolCodec = class extends ifaces_1.ScalarCodec {
  59956. constructor() {
  59957. super(...arguments);
  59958. __publicField(this, "tsType", "boolean");
  59959. }
  59960. encode(buf, object, ctx) {
  59961. const val2 = ctx.preEncode(this, object);
  59962. const typeOf = typeof val2;
  59963. if (typeOf !== "boolean" && typeOf !== "number") {
  59964. throw new errors_1.InvalidArgumentError(`a boolean or a number was expected, got "${val2}"`);
  59965. }
  59966. buf.writeInt32(1);
  59967. buf.writeChar(val2 ? 1 : 0);
  59968. }
  59969. decode(buf, ctx) {
  59970. return ctx.postDecode(this, buf.readUInt8() !== 0);
  59971. }
  59972. };
  59973. exports.BoolCodec = BoolCodec;
  59974. }
  59975. });
  59976. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numbers.js
  59977. var require_numbers = __commonJS({
  59978. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numbers.js"(exports) {
  59979. "use strict";
  59980. Object.defineProperty(exports, "__esModule", { value: true });
  59981. exports.Float64Codec = exports.Float32Codec = exports.Int16Codec = exports.Int32Codec = exports.Int64Codec = void 0;
  59982. var ifaces_1 = require_ifaces();
  59983. var errors_1 = require_errors();
  59984. var Int64Codec = class extends ifaces_1.ScalarCodec {
  59985. constructor() {
  59986. super(...arguments);
  59987. __publicField(this, "tsType", "number");
  59988. }
  59989. encode(buf, object, ctx) {
  59990. if (ctx.hasOverload(this)) {
  59991. const val2 = ctx.preEncode(this, object);
  59992. buf.writeInt32(8);
  59993. buf.writeBigInt64(val2);
  59994. return;
  59995. }
  59996. if (typeof object !== "number") {
  59997. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  59998. }
  59999. buf.writeInt32(8);
  60000. buf.writeInt64(object);
  60001. }
  60002. decode(buf, ctx) {
  60003. if (ctx.hasOverload(this)) {
  60004. return ctx.postDecode(this, buf.readBigInt64());
  60005. }
  60006. return buf.readInt64();
  60007. }
  60008. };
  60009. exports.Int64Codec = Int64Codec;
  60010. var Int32Codec = class extends ifaces_1.ScalarCodec {
  60011. constructor() {
  60012. super(...arguments);
  60013. __publicField(this, "tsType", "number");
  60014. }
  60015. encode(buf, object, ctx) {
  60016. object = ctx.preEncode(this, object);
  60017. if (typeof object !== "number") {
  60018. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  60019. }
  60020. buf.writeInt32(4);
  60021. buf.writeInt32(object);
  60022. }
  60023. decode(buf, ctx) {
  60024. return ctx.postDecode(this, buf.readInt32());
  60025. }
  60026. };
  60027. exports.Int32Codec = Int32Codec;
  60028. var Int16Codec = class extends ifaces_1.ScalarCodec {
  60029. constructor() {
  60030. super(...arguments);
  60031. __publicField(this, "tsType", "number");
  60032. }
  60033. encode(buf, object, ctx) {
  60034. object = ctx.preEncode(this, object);
  60035. if (typeof object !== "number") {
  60036. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  60037. }
  60038. buf.writeInt32(2);
  60039. buf.writeInt16(object);
  60040. }
  60041. decode(buf, ctx) {
  60042. return ctx.postDecode(this, buf.readInt16());
  60043. }
  60044. };
  60045. exports.Int16Codec = Int16Codec;
  60046. var Float32Codec = class extends ifaces_1.ScalarCodec {
  60047. constructor() {
  60048. super(...arguments);
  60049. __publicField(this, "tsType", "number");
  60050. }
  60051. encode(buf, object, ctx) {
  60052. object = ctx.preEncode(this, object);
  60053. if (typeof object !== "number") {
  60054. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  60055. }
  60056. buf.writeInt32(4);
  60057. buf.writeFloat32(object);
  60058. }
  60059. decode(buf, ctx) {
  60060. return ctx.postDecode(this, buf.readFloat32());
  60061. }
  60062. };
  60063. exports.Float32Codec = Float32Codec;
  60064. var Float64Codec = class extends ifaces_1.ScalarCodec {
  60065. constructor() {
  60066. super(...arguments);
  60067. __publicField(this, "tsType", "number");
  60068. }
  60069. encode(buf, object, ctx) {
  60070. object = ctx.preEncode(this, object);
  60071. if (typeof object !== "number") {
  60072. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  60073. }
  60074. buf.writeInt32(8);
  60075. buf.writeFloat64(object);
  60076. }
  60077. decode(buf, ctx) {
  60078. return ctx.postDecode(this, buf.readFloat64());
  60079. }
  60080. };
  60081. exports.Float64Codec = Float64Codec;
  60082. }
  60083. });
  60084. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numerics.js
  60085. var require_numerics = __commonJS({
  60086. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numerics.js"(exports) {
  60087. "use strict";
  60088. Object.defineProperty(exports, "__esModule", { value: true });
  60089. exports.DecimalStringCodec = exports.BigIntCodec = void 0;
  60090. var ifaces_1 = require_ifaces();
  60091. var errors_1 = require_errors();
  60092. var NUMERIC_POS = 0;
  60093. var NUMERIC_NEG = 16384;
  60094. var BigIntCodec = class extends ifaces_1.ScalarCodec {
  60095. constructor() {
  60096. super(...arguments);
  60097. __publicField(this, "tsType", "bigint");
  60098. }
  60099. encode(buf, object, ctx) {
  60100. object = ctx.preEncode(this, object);
  60101. if (typeof object !== "bigint") {
  60102. throw new errors_1.InvalidArgumentError(`a bigint was expected, got "${object}"`);
  60103. }
  60104. const digits = [];
  60105. let sign = NUMERIC_POS;
  60106. let uval = object;
  60107. if (object === 0n) {
  60108. buf.writeUInt32(8);
  60109. buf.writeUInt32(0);
  60110. buf.writeUInt16(NUMERIC_POS);
  60111. buf.writeUInt16(0);
  60112. return;
  60113. }
  60114. if (object < 0n) {
  60115. sign = NUMERIC_NEG;
  60116. uval = -uval;
  60117. }
  60118. while (uval) {
  60119. const mod = uval % 10000n;
  60120. uval /= 10000n;
  60121. digits.push(mod);
  60122. }
  60123. buf.writeUInt32(8 + digits.length * 2);
  60124. buf.writeUInt16(digits.length);
  60125. buf.writeUInt16(digits.length - 1);
  60126. buf.writeUInt16(sign);
  60127. buf.writeUInt16(0);
  60128. for (let i6 = digits.length - 1; i6 >= 0; i6--) {
  60129. buf.writeUInt16(Number(digits[i6]));
  60130. }
  60131. }
  60132. decode(buf, ctx) {
  60133. const val2 = BigInt(decodeBigIntToString(buf));
  60134. return ctx.postDecode(this, val2);
  60135. }
  60136. };
  60137. exports.BigIntCodec = BigIntCodec;
  60138. var DecimalStringCodec = class extends ifaces_1.ScalarCodec {
  60139. constructor() {
  60140. super(...arguments);
  60141. __publicField(this, "tsType", "string");
  60142. }
  60143. encode(buf, object, ctx) {
  60144. object = ctx.preEncode(this, object);
  60145. if (typeof object !== "string") {
  60146. throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
  60147. }
  60148. const match2 = object.match(/^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([-+]?[0-9]+))?$/);
  60149. if (!match2) {
  60150. throw new errors_1.InvalidArgumentError(`invalid decimal string "${object}"`);
  60151. }
  60152. const [_3, sign, int, _frac, _exp] = match2;
  60153. const frac = _frac ?? "";
  60154. const exp = _exp ? parseInt(_exp, 10) : 0;
  60155. const sdigits = int.padStart(Math.ceil(int.length / 4) * 4, "0") + frac.padEnd(Math.ceil(frac.length / 4) * 4, "0");
  60156. const digits = [];
  60157. for (let i6 = 0, len = sdigits.length; i6 < len; i6 += 4) {
  60158. digits.push(parseInt(sdigits.slice(i6, i6 + 4), 10));
  60159. }
  60160. buf.writeUInt32(8 + digits.length * 2);
  60161. buf.writeUInt16(digits.length);
  60162. buf.writeInt16(Math.ceil((int.length + exp) / 4) - 1);
  60163. buf.writeUInt16(sign === "-" ? NUMERIC_NEG : NUMERIC_POS);
  60164. buf.writeUInt16(Math.max(frac.length - exp, 0));
  60165. for (let i6 = 0, len = digits.length; i6 < len; i6++) {
  60166. buf.writeUInt16(digits[i6]);
  60167. }
  60168. }
  60169. decode(buf, ctx) {
  60170. if (ctx.hasOverload(this)) {
  60171. return ctx.postDecode(this, decodeDecimalToString(buf));
  60172. }
  60173. return decodeDecimalToString(buf);
  60174. }
  60175. };
  60176. exports.DecimalStringCodec = DecimalStringCodec;
  60177. function decodeBigIntToString(buf) {
  60178. const ndigits = buf.readUInt16();
  60179. const weight = buf.readInt16();
  60180. const sign = buf.readUInt16();
  60181. const dscale = buf.readUInt16();
  60182. let result = "";
  60183. switch (sign) {
  60184. case NUMERIC_POS:
  60185. break;
  60186. case NUMERIC_NEG:
  60187. result += "-";
  60188. break;
  60189. default:
  60190. throw new errors_1.ProtocolError("bad bigint sign data");
  60191. }
  60192. if (dscale !== 0) {
  60193. throw new errors_1.ProtocolError("bigint data has fractional part");
  60194. }
  60195. if (ndigits === 0) {
  60196. return "0";
  60197. }
  60198. let i6 = weight;
  60199. let d5 = 0;
  60200. while (i6 >= 0) {
  60201. if (i6 <= weight && d5 < ndigits) {
  60202. const digit = buf.readUInt16().toString();
  60203. result += d5 > 0 ? digit.padStart(4, "0") : digit;
  60204. d5++;
  60205. } else {
  60206. result += "0000";
  60207. }
  60208. i6--;
  60209. }
  60210. return result;
  60211. }
  60212. function decodeDecimalToString(buf) {
  60213. const ndigits = buf.readUInt16();
  60214. const weight = buf.readInt16();
  60215. const sign = buf.readUInt16();
  60216. const dscale = buf.readUInt16();
  60217. let result = "";
  60218. switch (sign) {
  60219. case NUMERIC_POS:
  60220. break;
  60221. case NUMERIC_NEG:
  60222. result += "-";
  60223. break;
  60224. default:
  60225. throw new errors_1.ProtocolError("bad decimal sign data");
  60226. }
  60227. let d5 = 0;
  60228. if (weight < 0) {
  60229. d5 = weight + 1;
  60230. result += "0";
  60231. } else {
  60232. for (d5 = 0; d5 <= weight; d5++) {
  60233. const digit = d5 < ndigits ? buf.readUInt16() : 0;
  60234. let sdigit = digit.toString();
  60235. if (d5 > 0) {
  60236. sdigit = sdigit.padStart(4, "0");
  60237. }
  60238. result += sdigit;
  60239. }
  60240. }
  60241. if (dscale > 0) {
  60242. result += ".";
  60243. const end = result.length + dscale;
  60244. for (let i6 = 0; i6 < dscale; d5++, i6 += 4) {
  60245. const digit = d5 >= 0 && d5 < ndigits ? buf.readUInt16() : 0;
  60246. result += digit.toString().padStart(4, "0");
  60247. }
  60248. result = result.slice(0, end);
  60249. }
  60250. return result;
  60251. }
  60252. }
  60253. });
  60254. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/text.js
  60255. var require_text = __commonJS({
  60256. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/text.js"(exports) {
  60257. "use strict";
  60258. Object.defineProperty(exports, "__esModule", { value: true });
  60259. exports.StrCodec = void 0;
  60260. var buffer_1 = require_buffer();
  60261. var ifaces_1 = require_ifaces();
  60262. var errors_1 = require_errors();
  60263. var StrCodec = class extends ifaces_1.ScalarCodec {
  60264. constructor() {
  60265. super(...arguments);
  60266. __publicField(this, "tsType", "string");
  60267. }
  60268. encode(buf, object, ctx) {
  60269. object = ctx.preEncode(this, object);
  60270. if (typeof object !== "string") {
  60271. throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
  60272. }
  60273. const val2 = object;
  60274. const strbuf = buffer_1.utf8Encoder.encode(val2);
  60275. buf.writeInt32(strbuf.length);
  60276. buf.writeBuffer(strbuf);
  60277. }
  60278. decode(buf, ctx) {
  60279. return ctx.postDecode(this, buf.consumeAsString());
  60280. }
  60281. };
  60282. exports.StrCodec = StrCodec;
  60283. }
  60284. });
  60285. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/uuid.js
  60286. var require_uuid = __commonJS({
  60287. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/uuid.js"(exports) {
  60288. "use strict";
  60289. Object.defineProperty(exports, "__esModule", { value: true });
  60290. exports.UUIDCodec = void 0;
  60291. var buffer_1 = require_buffer();
  60292. var ifaces_1 = require_ifaces();
  60293. var errors_1 = require_errors();
  60294. function UUIDBufferFromString(uuid) {
  60295. let uuidClean = uuid;
  60296. if (uuidClean.length !== 32) {
  60297. uuidClean = uuidClean.replace(/-/g, "");
  60298. if (uuidClean.length !== 32) {
  60299. throw new TypeError(`invalid UUID "${uuid}"`);
  60300. }
  60301. }
  60302. try {
  60303. return (0, buffer_1.uuidToBuffer)(uuidClean);
  60304. } catch {
  60305. throw new TypeError(`invalid UUID "${uuid}"`);
  60306. }
  60307. }
  60308. var UUIDCodec = class extends ifaces_1.ScalarCodec {
  60309. constructor() {
  60310. super(...arguments);
  60311. __publicField(this, "tsType", "string");
  60312. }
  60313. encode(buf, object, ctx) {
  60314. if (ctx.hasOverload(this)) {
  60315. const val2 = ctx.preEncode(this, object);
  60316. if (!(val2 instanceof Uint8Array)) {
  60317. throw new errors_1.InvalidArgumentError(`a Uint8Array was expected from a custom UUID codec`);
  60318. }
  60319. if (val2.length != 16) {
  60320. throw new errors_1.InvalidArgumentError(`a 16-element long Uint8Array was expected from a custom UUID codec`);
  60321. }
  60322. buf.writeInt32(16);
  60323. buf.writeBuffer(val2);
  60324. return;
  60325. }
  60326. if (typeof object === "string") {
  60327. const ubuf = UUIDBufferFromString(object);
  60328. buf.writeInt32(16);
  60329. buf.writeBuffer(ubuf);
  60330. } else {
  60331. throw new errors_1.InvalidArgumentError(`cannot encode UUID "${object}": invalid type`);
  60332. }
  60333. }
  60334. decode(buf, ctx) {
  60335. if (ctx.hasOverload(this)) {
  60336. return ctx.postDecode(this, buf.readUUIDBytes());
  60337. }
  60338. return buf.readUUID("-");
  60339. }
  60340. };
  60341. exports.UUIDCodec = UUIDCodec;
  60342. }
  60343. });
  60344. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/bytes.js
  60345. var require_bytes = __commonJS({
  60346. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/bytes.js"(exports) {
  60347. "use strict";
  60348. Object.defineProperty(exports, "__esModule", { value: true });
  60349. exports.BytesCodec = void 0;
  60350. var ifaces_1 = require_ifaces();
  60351. var errors_1 = require_errors();
  60352. var BytesCodec = class extends ifaces_1.ScalarCodec {
  60353. constructor() {
  60354. super(...arguments);
  60355. __publicField(this, "tsType", "Uint8Array");
  60356. }
  60357. encode(buf, object, ctx) {
  60358. const val2 = ctx.preEncode(this, object);
  60359. if (!(val2 instanceof Uint8Array)) {
  60360. throw new errors_1.InvalidArgumentError(`a Uint8Array or Buffer was expected, got "${val2}"`);
  60361. }
  60362. buf.writeInt32(val2.length);
  60363. buf.writeBuffer(val2);
  60364. }
  60365. decode(buf, ctx) {
  60366. return ctx.postDecode(this, buf.consumeAsBuffer());
  60367. }
  60368. };
  60369. exports.BytesCodec = BytesCodec;
  60370. }
  60371. });
  60372. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/json.js
  60373. var require_json = __commonJS({
  60374. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/json.js"(exports) {
  60375. "use strict";
  60376. Object.defineProperty(exports, "__esModule", { value: true });
  60377. exports.PgTextJSONStringCodec = exports.PgTextJSONCodec = exports.JSONCodec = void 0;
  60378. var buffer_1 = require_buffer();
  60379. var ifaces_1 = require_ifaces();
  60380. var errors_1 = require_errors();
  60381. var JSONCodec = class extends ifaces_1.ScalarCodec {
  60382. constructor() {
  60383. super(...arguments);
  60384. __publicField(this, "tsType", "unknown");
  60385. __publicField(this, "jsonFormat", 1);
  60386. }
  60387. encode(buf, object, ctx) {
  60388. let val2;
  60389. if (ctx.hasOverload(this)) {
  60390. val2 = ctx.preEncode(this, object);
  60391. } else {
  60392. try {
  60393. val2 = JSON.stringify(object);
  60394. } catch (_err) {
  60395. throw new errors_1.InvalidArgumentError(`a JSON-serializable value was expected, got "${object}"`);
  60396. }
  60397. }
  60398. if (typeof val2 !== "string") {
  60399. throw new errors_1.InvalidArgumentError(`a JSON-serializable value was expected, got "${object}"`);
  60400. }
  60401. const strbuf = buffer_1.utf8Encoder.encode(val2);
  60402. if (this.jsonFormat !== null) {
  60403. buf.writeInt32(strbuf.length + 1);
  60404. buf.writeChar(this.jsonFormat);
  60405. } else {
  60406. buf.writeInt32(strbuf.length);
  60407. }
  60408. buf.writeBuffer(strbuf);
  60409. }
  60410. decode(buf, ctx) {
  60411. if (this.jsonFormat !== null) {
  60412. const format = buf.readUInt8();
  60413. if (format !== this.jsonFormat) {
  60414. throw new errors_1.ProtocolError(`unexpected JSON format ${format}`);
  60415. }
  60416. }
  60417. if (ctx.hasOverload(this)) {
  60418. return ctx.postDecode(this, buf.consumeAsString());
  60419. } else {
  60420. return JSON.parse(buf.consumeAsString());
  60421. }
  60422. }
  60423. };
  60424. exports.JSONCodec = JSONCodec;
  60425. var PgTextJSONCodec = class extends JSONCodec {
  60426. constructor() {
  60427. super(...arguments);
  60428. __publicField(this, "jsonFormat", null);
  60429. }
  60430. };
  60431. exports.PgTextJSONCodec = PgTextJSONCodec;
  60432. var PgTextJSONStringCodec = class extends ifaces_1.ScalarCodec {
  60433. encode(buf, object, ctx) {
  60434. if (ctx.hasOverload(this)) {
  60435. object = ctx.preEncode(this, object);
  60436. }
  60437. if (typeof object !== "string") {
  60438. throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
  60439. }
  60440. const strbuf = buffer_1.utf8Encoder.encode(object);
  60441. buf.writeInt32(strbuf.length);
  60442. buf.writeBuffer(strbuf);
  60443. }
  60444. decode(buf, ctx) {
  60445. return ctx.postDecode(this, buf.consumeAsString());
  60446. }
  60447. };
  60448. exports.PgTextJSONStringCodec = PgTextJSONStringCodec;
  60449. }
  60450. });
  60451. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/dateutil.js
  60452. var require_dateutil = __commonJS({
  60453. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/dateutil.js"(exports) {
  60454. "use strict";
  60455. Object.defineProperty(exports, "__esModule", { value: true });
  60456. exports.isLeapYear = isLeapYear2;
  60457. exports.daysInMonth = daysInMonth;
  60458. exports.daysBeforeMonth = daysBeforeMonth;
  60459. exports.ymd2ord = ymd2ord;
  60460. exports.ord2ymd = ord2ymd;
  60461. function isLeapYear2(year) {
  60462. return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  60463. }
  60464. function daysInMonth(year, month) {
  60465. if (month === 2 && isLeapYear2(year)) {
  60466. return 29;
  60467. }
  60468. return _DAYS_IN_MONTH[month];
  60469. }
  60470. function daysBeforeYear(year) {
  60471. const y2 = year - 1;
  60472. return y2 * 365 + Math.trunc(y2 / 4) - Math.trunc(y2 / 100) + Math.trunc(y2 / 400);
  60473. }
  60474. function daysBeforeMonth(year, month) {
  60475. return _DAYS_BEFORE_MONTH[month] + (month > 2 && isLeapYear2(year) ? 1 : 0);
  60476. }
  60477. var _DI400Y = daysBeforeYear(401);
  60478. var _DI100Y = daysBeforeYear(101);
  60479. var _DI4Y = daysBeforeYear(5);
  60480. var _DAYS_IN_MONTH = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  60481. var _DAYS_BEFORE_MONTH = (() => {
  60482. const dbf = [-1];
  60483. let dbm = 0;
  60484. for (let i6 = 1; i6 < _DAYS_IN_MONTH.length; i6++) {
  60485. const dim = _DAYS_IN_MONTH[i6];
  60486. dbf.push(dbm);
  60487. dbm += dim;
  60488. }
  60489. return dbf;
  60490. })();
  60491. function ymd2ord(year, month, day) {
  60492. return daysBeforeYear(year) + daysBeforeMonth(year, month) + day;
  60493. }
  60494. function divmod(dividend, divisor) {
  60495. const quotient = Math.floor(dividend / divisor);
  60496. return [quotient, dividend - divisor * quotient];
  60497. }
  60498. function ord2ymd(n5) {
  60499. n5--;
  60500. let n400;
  60501. [n400, n5] = divmod(n5, _DI400Y);
  60502. let year = n400 * 400 + 1;
  60503. let n100;
  60504. [n100, n5] = divmod(n5, _DI100Y);
  60505. let n42;
  60506. [n42, n5] = divmod(n5, _DI4Y);
  60507. let n1;
  60508. [n1, n5] = divmod(n5, 365);
  60509. year += n100 * 100 + n42 * 4 + n1;
  60510. if (n1 === 4 || n100 === 4) {
  60511. return [year - 1, 12, 31];
  60512. }
  60513. const leapyear = n1 === 3 && (n42 !== 24 || n100 === 3);
  60514. let month = n5 + 50 >> 5;
  60515. let preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 && leapyear ? 1 : 0);
  60516. if (preceding > n5) {
  60517. month -= 1;
  60518. preceding -= _DAYS_IN_MONTH[month] + (month === 2 && leapyear ? 1 : 0);
  60519. }
  60520. n5 -= preceding;
  60521. return [year, month, n5 + 1];
  60522. }
  60523. }
  60524. });
  60525. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/datetime.js
  60526. var require_datetime = __commonJS({
  60527. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/datetime.js"(exports) {
  60528. "use strict";
  60529. Object.defineProperty(exports, "__esModule", { value: true });
  60530. exports.DateDuration = exports.RelativeDuration = exports.Duration = exports.LocalDateTime = exports.LocalDate = exports.localDateInstances = exports.LocalTime = exports.localTimeInstances = exports.DATE_PRIVATE = void 0;
  60531. exports.LocalDateToOrdinal = LocalDateToOrdinal;
  60532. exports.LocalDateFromOrdinal = LocalDateFromOrdinal;
  60533. exports.parseHumanDurationString = parseHumanDurationString;
  60534. var dateutil_1 = require_dateutil();
  60535. exports.DATE_PRIVATE = Symbol.for("gel.datetime");
  60536. function toNumber(val2) {
  60537. const n5 = Number(val2);
  60538. if (Number.isNaN(n5)) {
  60539. return 0;
  60540. }
  60541. return n5;
  60542. }
  60543. function assertInteger(val2) {
  60544. if (!Number.isInteger(val2)) {
  60545. throw new RangeError(`unsupported fractional value ${val2}`);
  60546. }
  60547. return val2;
  60548. }
  60549. exports.localTimeInstances = /* @__PURE__ */ new WeakMap();
  60550. var LocalTime = class {
  60551. constructor(isoHour = 0, isoMinute = 0, isoSecond = 0, isoMillisecond = 0, isoMicrosecond = 0, isoNanosecond = 0) {
  60552. __publicField(this, "hour");
  60553. __publicField(this, "minute");
  60554. __publicField(this, "second");
  60555. __publicField(this, "millisecond");
  60556. __publicField(this, "microsecond");
  60557. __publicField(this, "nanosecond");
  60558. isoHour = Math.floor(toNumber(isoHour));
  60559. isoMinute = Math.floor(toNumber(isoMinute));
  60560. isoSecond = Math.floor(toNumber(isoSecond));
  60561. isoMillisecond = Math.floor(toNumber(isoMillisecond));
  60562. isoMicrosecond = Math.floor(toNumber(isoMicrosecond));
  60563. isoNanosecond = Math.floor(toNumber(isoNanosecond));
  60564. if (isoHour < 0 || isoHour > 23) {
  60565. throw new RangeError(`invalid number of hours ${isoHour}: expected a value in 0-23 range`);
  60566. }
  60567. if (isoMinute < 0 || isoMinute > 59) {
  60568. throw new RangeError(`invalid number of minutes ${isoMinute}: expected a value in 0-59 range`);
  60569. }
  60570. if (isoSecond < 0 || isoSecond > 59) {
  60571. throw new RangeError(`invalid number of seconds ${isoSecond}: expected a value in 0-59 range`);
  60572. }
  60573. if (isoMillisecond < 0 || isoMillisecond > 999) {
  60574. throw new RangeError(`invalid number of milliseconds ${isoMillisecond}: expected a value in 0-999 range`);
  60575. }
  60576. if (isoMicrosecond < 0 || isoMicrosecond > 999) {
  60577. throw new RangeError(`invalid number of microseconds ${isoMicrosecond}: expected a value in 0-999 range`);
  60578. }
  60579. if (isoNanosecond < 0 || isoNanosecond > 999) {
  60580. throw new RangeError(`invalid number of nanoseconds ${isoNanosecond}: expected a value in 0-999 range`);
  60581. }
  60582. this.hour = isoHour;
  60583. this.minute = isoMinute;
  60584. this.second = isoSecond;
  60585. this.millisecond = isoMillisecond;
  60586. this.microsecond = isoMicrosecond;
  60587. this.nanosecond = isoNanosecond;
  60588. forwardJsonAsToString(this);
  60589. throwOnValueOf(this, "LocalTime");
  60590. }
  60591. toString() {
  60592. const hh = this.hour.toString().padStart(2, "0");
  60593. const mm = this.minute.toString().padStart(2, "0");
  60594. const ss = this.second.toString().padStart(2, "0");
  60595. let repr = `${hh}:${mm}:${ss}`;
  60596. if (this.millisecond || this.microsecond || this.nanosecond) {
  60597. repr += `.${this.millisecond.toString().padStart(3, "0")}${this.microsecond.toString().padStart(3, "0")}${this.nanosecond.toString().padStart(3, "0")}`.replace(/(?:0+)$/, "");
  60598. }
  60599. return repr;
  60600. }
  60601. };
  60602. exports.LocalTime = LocalTime;
  60603. exports.localDateInstances = /* @__PURE__ */ new WeakMap();
  60604. var LocalDate = class {
  60605. constructor(isoYear, isoMonth, isoDay) {
  60606. isoYear = Math.trunc(toNumber(isoYear));
  60607. isoMonth = Math.floor(toNumber(isoMonth));
  60608. isoDay = Math.floor(toNumber(isoDay));
  60609. if (isoYear < -271820 || isoYear > 275759) {
  60610. throw new RangeError(`invalid year ${isoYear}: expected a value in -271820-275759 range`);
  60611. }
  60612. if (isoMonth < 1 || isoMonth > 12) {
  60613. throw new RangeError(`invalid month ${isoMonth}: expected a value in 1-12 range`);
  60614. }
  60615. const maxDays = (0, dateutil_1.daysInMonth)(isoYear, isoMonth);
  60616. if (isoDay < 1 || isoDay > maxDays) {
  60617. throw new RangeError(`invalid number of days ${isoDay}: expected a value in 1-${maxDays} range`);
  60618. }
  60619. const date = new Date(Date.UTC(isoYear, isoMonth - 1, isoDay));
  60620. if (isoYear >= 0 && isoYear <= 99) {
  60621. date.setUTCFullYear(isoYear);
  60622. }
  60623. exports.localDateInstances.set(this, date);
  60624. forwardJsonAsToString(this);
  60625. throwOnValueOf(this, "LocalDate");
  60626. }
  60627. get year() {
  60628. return exports.localDateInstances.get(this).getUTCFullYear();
  60629. }
  60630. get month() {
  60631. return exports.localDateInstances.get(this).getUTCMonth() + 1;
  60632. }
  60633. get day() {
  60634. return exports.localDateInstances.get(this).getUTCDate();
  60635. }
  60636. get dayOfWeek() {
  60637. return (exports.localDateInstances.get(this).getUTCDay() + 6) % 7 + 1;
  60638. }
  60639. get dayOfYear() {
  60640. const date = exports.localDateInstances.get(this);
  60641. return (0, dateutil_1.daysBeforeMonth)(date.getUTCFullYear(), date.getUTCMonth() + 1) + date.getUTCDate();
  60642. }
  60643. get daysInWeek() {
  60644. return 7;
  60645. }
  60646. get daysInMonth() {
  60647. const date = exports.localDateInstances.get(this);
  60648. return (0, dateutil_1.daysInMonth)(date.getUTCFullYear(), date.getUTCMonth() + 1);
  60649. }
  60650. get daysInYear() {
  60651. return this.inLeapYear ? 366 : 365;
  60652. }
  60653. get monthsInYear() {
  60654. return 12;
  60655. }
  60656. get inLeapYear() {
  60657. return (0, dateutil_1.isLeapYear)(exports.localDateInstances.get(this).getUTCFullYear());
  60658. }
  60659. toString() {
  60660. const year = this.year < 0 || this.year > 9999 ? (this.year < 0 ? "-" : "+") + Math.abs(this.year).toString().padStart(6, "0") : this.year.toString().padStart(4, "0");
  60661. const month = this.month.toString().padStart(2, "0");
  60662. const day = this.day.toString().padStart(2, "0");
  60663. return `${year}-${month}-${day}`;
  60664. }
  60665. };
  60666. exports.LocalDate = LocalDate;
  60667. function LocalDateToOrdinal(localdate) {
  60668. return (0, dateutil_1.ymd2ord)(localdate.year, localdate.month, localdate.day);
  60669. }
  60670. function LocalDateFromOrdinal(ordinal) {
  60671. const [year, month, day] = (0, dateutil_1.ord2ymd)(ordinal);
  60672. return new LocalDate(year, month, day);
  60673. }
  60674. var LocalDateTime = class extends LocalDate {
  60675. constructor(isoYear, isoMonth, isoDay, isoHour = 0, isoMinute = 0, isoSecond = 0, isoMillisecond = 0, isoMicrosecond = 0, isoNanosecond = 0) {
  60676. super(isoYear, isoMonth, isoDay);
  60677. const time = new LocalTime(isoHour, isoMinute, isoSecond, isoMillisecond, isoMicrosecond, isoNanosecond);
  60678. exports.localTimeInstances.set(this, time);
  60679. throwOnValueOf(this, "LocalDateTime");
  60680. }
  60681. get hour() {
  60682. return exports.localTimeInstances.get(this).hour;
  60683. }
  60684. get minute() {
  60685. return exports.localTimeInstances.get(this).minute;
  60686. }
  60687. get second() {
  60688. return exports.localTimeInstances.get(this).second;
  60689. }
  60690. get millisecond() {
  60691. return exports.localTimeInstances.get(this).millisecond;
  60692. }
  60693. get microsecond() {
  60694. return exports.localTimeInstances.get(this).microsecond;
  60695. }
  60696. get nanosecond() {
  60697. return exports.localTimeInstances.get(this).nanosecond;
  60698. }
  60699. toString() {
  60700. return `${super.toString()}T${exports.localTimeInstances.get(this).toString()}`;
  60701. }
  60702. };
  60703. exports.LocalDateTime = LocalDateTime;
  60704. var durationRegex2 = new RegExp(`^(\\-|\\+)?P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(T(?:(\\d+)(\\.\\d{1,10})?H)?(?:(\\d+)(\\.\\d{1,10})?M)?(?:(\\d+)(\\.\\d{1,9})?S)?)?$`, "i");
  60705. var Duration = class _Duration {
  60706. constructor(years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0, nanoseconds = 0) {
  60707. __publicField(this, "years");
  60708. __publicField(this, "months");
  60709. __publicField(this, "weeks");
  60710. __publicField(this, "days");
  60711. __publicField(this, "hours");
  60712. __publicField(this, "minutes");
  60713. __publicField(this, "seconds");
  60714. __publicField(this, "milliseconds");
  60715. __publicField(this, "microseconds");
  60716. __publicField(this, "nanoseconds");
  60717. __publicField(this, "sign");
  60718. years = assertInteger(toNumber(years));
  60719. months = assertInteger(toNumber(months));
  60720. weeks = assertInteger(toNumber(weeks));
  60721. days = assertInteger(toNumber(days));
  60722. hours = assertInteger(toNumber(hours));
  60723. minutes = assertInteger(toNumber(minutes));
  60724. seconds = assertInteger(toNumber(seconds));
  60725. milliseconds = assertInteger(toNumber(milliseconds));
  60726. microseconds = assertInteger(toNumber(microseconds));
  60727. nanoseconds = assertInteger(toNumber(nanoseconds));
  60728. const fields = [
  60729. years,
  60730. months,
  60731. weeks,
  60732. days,
  60733. hours,
  60734. minutes,
  60735. seconds,
  60736. milliseconds,
  60737. microseconds,
  60738. nanoseconds
  60739. ];
  60740. let sign = 0;
  60741. for (const field of fields) {
  60742. if (field === Infinity || field === -Infinity) {
  60743. throw new RangeError("infinite values not allowed as duration fields");
  60744. }
  60745. const fieldSign = Math.sign(field);
  60746. if (sign && fieldSign && fieldSign !== sign) {
  60747. throw new RangeError("mixed-sign values not allowed as duration fields");
  60748. }
  60749. sign = sign || fieldSign;
  60750. }
  60751. this.years = years || 0;
  60752. this.months = months || 0;
  60753. this.weeks = weeks || 0;
  60754. this.days = days || 0;
  60755. this.hours = hours || 0;
  60756. this.minutes = minutes || 0;
  60757. this.seconds = seconds || 0;
  60758. this.milliseconds = milliseconds || 0;
  60759. this.microseconds = microseconds || 0;
  60760. this.nanoseconds = nanoseconds || 0;
  60761. this.sign = sign || 0;
  60762. forwardJsonAsToString(this);
  60763. throwOnValueOf(this, "TemporalDuration");
  60764. }
  60765. get blank() {
  60766. return this.sign === 0;
  60767. }
  60768. toString() {
  60769. let dateParts = "";
  60770. if (this.years) {
  60771. dateParts += BigInt(Math.abs(this.years)) + "Y";
  60772. }
  60773. if (this.months) {
  60774. dateParts += BigInt(Math.abs(this.months)) + "M";
  60775. }
  60776. if (this.weeks) {
  60777. dateParts += BigInt(Math.abs(this.weeks)) + "W";
  60778. }
  60779. if (this.days) {
  60780. dateParts += BigInt(Math.abs(this.days)) + "D";
  60781. }
  60782. let timeParts = "";
  60783. if (this.hours) {
  60784. timeParts += BigInt(Math.abs(this.hours)) + "H";
  60785. }
  60786. if (this.minutes) {
  60787. timeParts += BigInt(Math.abs(this.minutes)) + "M";
  60788. }
  60789. if (!dateParts && !timeParts || this.seconds || this.milliseconds || this.microseconds || this.nanoseconds) {
  60790. const totalNanoseconds = (BigInt(Math.abs(this.seconds)) * BigInt(1e9) + BigInt(Math.abs(this.milliseconds)) * BigInt(1e6) + BigInt(Math.abs(this.microseconds)) * BigInt(1e3) + BigInt(Math.abs(this.nanoseconds))).toString().padStart(10, "0");
  60791. const seconds = totalNanoseconds.slice(0, -9);
  60792. const fracSeconds = totalNanoseconds.slice(-9).replace(/0+$/, "");
  60793. timeParts += seconds + (fracSeconds.length ? "." + fracSeconds : "") + "S";
  60794. }
  60795. return (this.sign === -1 ? "-" : "") + "P" + dateParts + (timeParts ? "T" + timeParts : "");
  60796. }
  60797. static from(item) {
  60798. let result;
  60799. if (item instanceof _Duration) {
  60800. result = item;
  60801. }
  60802. if (typeof item === "object") {
  60803. if (item.years === void 0 && item.months === void 0 && item.weeks === void 0 && item.days === void 0 && item.hours === void 0 && item.minutes === void 0 && item.seconds === void 0 && item.milliseconds === void 0 && item.microseconds === void 0 && item.nanoseconds === void 0) {
  60804. throw new TypeError(`invalid duration-like`);
  60805. }
  60806. result = item;
  60807. } else {
  60808. const str = String(item);
  60809. const matches = str.match(durationRegex2);
  60810. if (!matches) {
  60811. throw new RangeError(`invalid duration: ${str}`);
  60812. }
  60813. const [_duration, _sign, years, months, weeks, days, _time, hours, fHours, minutes, fMinutes, seconds, fSeconds] = matches;
  60814. if (_duration.length < 3 || _time.length === 1) {
  60815. throw new RangeError(`invalid duration: ${str}`);
  60816. }
  60817. const sign = _sign === "-" ? -1 : 1;
  60818. result = {};
  60819. if (years) {
  60820. result.years = sign * Number(years);
  60821. }
  60822. if (months) {
  60823. result.months = sign * Number(months);
  60824. }
  60825. if (weeks) {
  60826. result.weeks = sign * Number(weeks);
  60827. }
  60828. if (days) {
  60829. result.days = sign * Number(days);
  60830. }
  60831. if (hours) {
  60832. result.hours = sign * Number(hours);
  60833. }
  60834. if (fHours) {
  60835. if (minutes || fMinutes || seconds || fSeconds) {
  60836. throw new RangeError("only the smallest unit can be fractional");
  60837. }
  60838. result.minutes = Number(fHours) * 60;
  60839. } else {
  60840. result.minutes = toNumber(minutes);
  60841. }
  60842. if (fMinutes) {
  60843. if (seconds || fSeconds) {
  60844. throw new RangeError("only the smallest unit can be fractional");
  60845. }
  60846. result.seconds = Number(fMinutes) * 60;
  60847. } else if (seconds) {
  60848. result.seconds = Number(seconds);
  60849. } else {
  60850. result.seconds = result.minutes % 1 * 60;
  60851. }
  60852. if (fSeconds) {
  60853. const ns = fSeconds.slice(1).padEnd(9, "0");
  60854. result.milliseconds = Number(ns.slice(0, 3));
  60855. result.microseconds = Number(ns.slice(3, 6));
  60856. result.nanoseconds = sign * Number(ns.slice(6));
  60857. } else {
  60858. result.milliseconds = result.seconds % 1 * 1e3;
  60859. result.microseconds = result.milliseconds % 1 * 1e3;
  60860. result.nanoseconds = sign * Math.floor(result.microseconds % 1 * 1e3);
  60861. }
  60862. result.minutes = sign * Math.floor(result.minutes);
  60863. result.seconds = sign * Math.floor(result.seconds);
  60864. result.milliseconds = sign * Math.floor(result.milliseconds);
  60865. result.microseconds = sign * Math.floor(result.microseconds);
  60866. }
  60867. return new _Duration(result.years, result.months, result.weeks, result.days, result.hours, result.minutes, result.seconds, result.milliseconds, result.microseconds, result.nanoseconds);
  60868. }
  60869. };
  60870. exports.Duration = Duration;
  60871. var RelativeDuration = class {
  60872. constructor(years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0) {
  60873. __publicField(this, "years");
  60874. __publicField(this, "months");
  60875. __publicField(this, "weeks");
  60876. __publicField(this, "days");
  60877. __publicField(this, "hours");
  60878. __publicField(this, "minutes");
  60879. __publicField(this, "seconds");
  60880. __publicField(this, "milliseconds");
  60881. __publicField(this, "microseconds");
  60882. this.years = Math.trunc(years) || 0;
  60883. this.months = Math.trunc(months) || 0;
  60884. this.weeks = Math.trunc(weeks) || 0;
  60885. this.days = Math.trunc(days) || 0;
  60886. this.hours = Math.trunc(hours) || 0;
  60887. this.minutes = Math.trunc(minutes) || 0;
  60888. this.seconds = Math.trunc(seconds) || 0;
  60889. this.milliseconds = Math.trunc(milliseconds) || 0;
  60890. this.microseconds = Math.trunc(microseconds) || 0;
  60891. forwardJsonAsToString(this);
  60892. throwOnValueOf(this, "RelativeDuration");
  60893. }
  60894. toString() {
  60895. let str = "P";
  60896. if (this.years) {
  60897. str += `${this.years}Y`;
  60898. }
  60899. if (this.months) {
  60900. str += `${this.months}M`;
  60901. }
  60902. const days = this.days + 7 * this.weeks;
  60903. if (days) {
  60904. str += `${days}D`;
  60905. }
  60906. let timeParts = "";
  60907. if (this.hours) {
  60908. timeParts += `${this.hours}H`;
  60909. }
  60910. if (this.minutes) {
  60911. timeParts += `${this.minutes}M`;
  60912. }
  60913. const seconds = this.seconds + this.milliseconds / 1e3 + this.microseconds / 1e6;
  60914. if (seconds !== 0) {
  60915. timeParts += `${seconds}S`;
  60916. }
  60917. if (timeParts) {
  60918. str += `T${timeParts}`;
  60919. }
  60920. if (str === "P") {
  60921. return "PT0S";
  60922. }
  60923. return str;
  60924. }
  60925. };
  60926. exports.RelativeDuration = RelativeDuration;
  60927. var DateDuration = class {
  60928. constructor(years = 0, months = 0, weeks = 0, days = 0) {
  60929. __publicField(this, "years");
  60930. __publicField(this, "months");
  60931. __publicField(this, "weeks");
  60932. __publicField(this, "days");
  60933. this.years = Math.trunc(years) || 0;
  60934. this.months = Math.trunc(months) || 0;
  60935. this.weeks = Math.trunc(weeks) || 0;
  60936. this.days = Math.trunc(days) || 0;
  60937. forwardJsonAsToString(this);
  60938. throwOnValueOf(this, "DateDuration");
  60939. }
  60940. toString() {
  60941. let str = "P";
  60942. if (this.years) {
  60943. str += `${this.years}Y`;
  60944. }
  60945. if (this.months) {
  60946. str += `${this.months}M`;
  60947. }
  60948. const days = this.days + 7 * this.weeks;
  60949. if (days) {
  60950. str += `${days}D`;
  60951. }
  60952. if (str === "P") {
  60953. return "PT0S";
  60954. }
  60955. return str;
  60956. }
  60957. };
  60958. exports.DateDuration = DateDuration;
  60959. var humanDurationPrefixes = {
  60960. h: 36e5,
  60961. hou: 36e5,
  60962. m: 6e4,
  60963. min: 6e4,
  60964. s: 1e3,
  60965. sec: 1e3,
  60966. ms: 1,
  60967. mil: 1
  60968. };
  60969. function parseHumanDurationString(durationStr) {
  60970. const regex = /(\d+|\d+\.\d+|\.\d+)\s*(hours?|minutes?|seconds?|milliseconds?|ms|h|m|s)\s*/g;
  60971. let duration = 0;
  60972. const seen = /* @__PURE__ */ new Set();
  60973. let match2 = regex.exec(durationStr);
  60974. let lastIndex = 0;
  60975. while (match2) {
  60976. if (match2.index !== lastIndex) {
  60977. throw new Error(`invalid duration "${durationStr}"`);
  60978. }
  60979. const mult = humanDurationPrefixes[match2[2].slice(0, 3)];
  60980. if (seen.has(mult)) {
  60981. throw new Error(`invalid duration "${durationStr}"`);
  60982. }
  60983. duration += Number(match2[1]) * mult;
  60984. seen.add(mult);
  60985. lastIndex = regex.lastIndex;
  60986. match2 = regex.exec(durationStr);
  60987. }
  60988. if (lastIndex !== durationStr.length) {
  60989. throw new Error(`invalid duration "${durationStr}"`);
  60990. }
  60991. return duration;
  60992. }
  60993. var forwardJsonAsToString = (obj) => {
  60994. Object.defineProperty(obj, "toJSON", {
  60995. value: () => obj.toString(),
  60996. enumerable: false,
  60997. configurable: true
  60998. });
  60999. };
  61000. var throwOnValueOf = (obj, typename) => {
  61001. Object.defineProperty(obj, "valueOf", {
  61002. value: () => {
  61003. throw new TypeError(`Not possible to compare ${typename}`);
  61004. },
  61005. enumerable: false,
  61006. configurable: true
  61007. });
  61008. };
  61009. }
  61010. });
  61011. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/datetime.js
  61012. var require_datetime2 = __commonJS({
  61013. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/datetime.js"(exports) {
  61014. "use strict";
  61015. Object.defineProperty(exports, "__esModule", { value: true });
  61016. exports.DateDurationCodec = exports.RelativeDurationCodec = exports.DurationCodec = exports.LocalTimeCodec = exports.LocalDateCodec = exports.LocalDateTimeCodec = exports.DateTimeCodec = void 0;
  61017. exports.checkValidGelDuration = checkValidGelDuration;
  61018. var ifaces_1 = require_ifaces();
  61019. var datetime_1 = require_datetime();
  61020. var dateutil_1 = require_dateutil();
  61021. var errors_1 = require_errors();
  61022. var TIMESHIFT = 9466848e5;
  61023. var BI_TIMESHIFT_US = BigInt(TIMESHIFT) * 1000n;
  61024. var DATESHIFT_ORD = (0, dateutil_1.ymd2ord)(2e3, 1, 1);
  61025. var DateTimeCodec = class extends ifaces_1.ScalarCodec {
  61026. constructor() {
  61027. super(...arguments);
  61028. __publicField(this, "tsType", "Date");
  61029. }
  61030. encode(buf, object, ctx) {
  61031. if (ctx.hasOverload(this)) {
  61032. const val2 = ctx.preEncode(this, object);
  61033. if (typeof val2 != "bigint") {
  61034. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom std::datetime codec`);
  61035. }
  61036. buf.writeInt32(8);
  61037. buf.writeBigInt64(val2 - BI_TIMESHIFT_US);
  61038. return;
  61039. }
  61040. if (!(object instanceof Date)) {
  61041. throw new errors_1.InvalidArgumentError(`a Date instance was expected, got "${object}"`);
  61042. }
  61043. const ms = object.getTime() - TIMESHIFT;
  61044. const us = ms * 1e3;
  61045. buf.writeInt32(8);
  61046. buf.writeInt64(us);
  61047. }
  61048. decode(buf, ctx) {
  61049. if (ctx.hasOverload(this)) {
  61050. const us2 = buf.readBigInt64();
  61051. return ctx.postDecode(this, us2 + BI_TIMESHIFT_US);
  61052. }
  61053. const us = Number(buf.readBigInt64());
  61054. let ms = Math.round(us / 1e3);
  61055. if (Math.abs(us % 1e3) === 500 && Math.abs(ms) % 2 === 1) {
  61056. ms -= 1;
  61057. }
  61058. ms += TIMESHIFT;
  61059. return new Date(ms);
  61060. }
  61061. };
  61062. exports.DateTimeCodec = DateTimeCodec;
  61063. var LocalDateTimeCodec = class extends ifaces_1.ScalarCodec {
  61064. constructor() {
  61065. super(...arguments);
  61066. __publicField(this, "tsType", "LocalDateTime");
  61067. __publicField(this, "tsModule", "gel");
  61068. }
  61069. encode(buf, object, ctx) {
  61070. if (ctx.hasOverload(this)) {
  61071. let us2 = ctx.preEncode(this, object);
  61072. if (typeof us2 != "bigint") {
  61073. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cal::local_datetime codec`);
  61074. }
  61075. us2 -= BI_TIMESHIFT_US;
  61076. buf.writeInt32(8);
  61077. buf.writeBigInt64(us2);
  61078. return;
  61079. }
  61080. if (!(object instanceof datetime_1.LocalDateTime)) {
  61081. throw new errors_1.InvalidArgumentError(`a LocalDateTime instance was expected, got "${object}"`);
  61082. }
  61083. const ms = BigInt(datetime_1.localDateInstances.get(object).getTime() - TIMESHIFT);
  61084. let us = ms * 1000n + BigInt(object.hour * 36e8 + object.minute * 6e7 + object.second * 1e6 + object.millisecond * 1e3 + object.microsecond);
  61085. if (object.nanosecond === 500 && Math.abs(object.microsecond) % 2 === 1 || object.nanosecond > 500) {
  61086. us += 1n;
  61087. }
  61088. buf.writeInt32(8);
  61089. buf.writeBigInt64(us);
  61090. }
  61091. decode(buf, ctx) {
  61092. const bi_us = buf.readBigInt64();
  61093. if (ctx.hasOverload(this)) {
  61094. return ctx.postDecode(this, BigInt(bi_us + BI_TIMESHIFT_US));
  61095. }
  61096. const bi_ms = bi_us / 1000n;
  61097. let us = Number(bi_us - bi_ms * 1000n);
  61098. let ms = Number(bi_ms);
  61099. if (us < 0) {
  61100. us += 1e3;
  61101. ms -= 1;
  61102. }
  61103. ms += TIMESHIFT;
  61104. const date = new Date(ms);
  61105. return new datetime_1.LocalDateTime(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds(), us);
  61106. }
  61107. };
  61108. exports.LocalDateTimeCodec = LocalDateTimeCodec;
  61109. var LocalDateCodec = class extends ifaces_1.ScalarCodec {
  61110. constructor() {
  61111. super(...arguments);
  61112. __publicField(this, "tsType", "LocalDate");
  61113. __publicField(this, "tsModule", "gel");
  61114. }
  61115. encode(buf, object, ctx) {
  61116. if (ctx.hasOverload(this)) {
  61117. const ret = ctx.preEncode(this, object);
  61118. const ord2 = (0, dateutil_1.ymd2ord)(...ret);
  61119. buf.writeInt32(4);
  61120. buf.writeInt32(ord2 - DATESHIFT_ORD);
  61121. return;
  61122. }
  61123. if (!(object instanceof datetime_1.LocalDate)) {
  61124. throw new errors_1.InvalidArgumentError(`a LocalDate instance was expected, got "${object}"`);
  61125. }
  61126. const ord = (0, datetime_1.LocalDateToOrdinal)(object);
  61127. buf.writeInt32(4);
  61128. buf.writeInt32(ord - DATESHIFT_ORD);
  61129. }
  61130. decode(buf, ctx) {
  61131. const ord = buf.readInt32() + DATESHIFT_ORD;
  61132. if (ctx.hasOverload(this)) {
  61133. return ctx.postDecode(this, (0, dateutil_1.ord2ymd)(ord));
  61134. }
  61135. return (0, datetime_1.LocalDateFromOrdinal)(ord);
  61136. }
  61137. };
  61138. exports.LocalDateCodec = LocalDateCodec;
  61139. var LocalTimeCodec = class extends ifaces_1.ScalarCodec {
  61140. constructor() {
  61141. super(...arguments);
  61142. __publicField(this, "tsType", "LocalTime");
  61143. __publicField(this, "tsModule", "gel");
  61144. }
  61145. encode(buf, object, ctx) {
  61146. if (ctx.hasOverload(this)) {
  61147. const us2 = ctx.preEncode(this, object);
  61148. if (typeof us2 != "bigint") {
  61149. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cal::local_time codec`);
  61150. }
  61151. buf.writeInt32(8);
  61152. buf.writeBigInt64(us2);
  61153. return;
  61154. }
  61155. if (!(object instanceof datetime_1.LocalTime)) {
  61156. throw new errors_1.InvalidArgumentError(`a LocalTime instance was expected, got "${object}"`);
  61157. }
  61158. let us = object.hour * 36e8 + object.minute * 6e7 + object.second * 1e6 + object.millisecond * 1e3 + object.microsecond;
  61159. if (object.nanosecond === 500 && us % 2 === 1 || object.nanosecond > 500) {
  61160. us += 1;
  61161. }
  61162. buf.writeInt32(8);
  61163. buf.writeInt64(us);
  61164. }
  61165. decode(buf, ctx) {
  61166. const bius = buf.readBigInt64();
  61167. if (ctx.hasOverload(this)) {
  61168. return ctx.postDecode(this, bius);
  61169. }
  61170. let us = Number(bius);
  61171. let seconds = Math.floor(us / 1e6);
  61172. const ms = Math.floor(us % 1e6 / 1e3);
  61173. us = us % 1e6 - ms * 1e3;
  61174. let minutes = Math.floor(seconds / 60);
  61175. seconds = Math.floor(seconds % 60);
  61176. const hours = Math.floor(minutes / 60);
  61177. minutes = Math.floor(minutes % 60);
  61178. return new datetime_1.LocalTime(hours, minutes, seconds, ms, us);
  61179. }
  61180. };
  61181. exports.LocalTimeCodec = LocalTimeCodec;
  61182. var unencodableDurationFields = [
  61183. "years",
  61184. "months",
  61185. "weeks",
  61186. "days"
  61187. ];
  61188. function checkValidGelDuration(duration) {
  61189. for (const field of unencodableDurationFields) {
  61190. if (duration[field] !== 0) {
  61191. return field;
  61192. }
  61193. }
  61194. return null;
  61195. }
  61196. var DurationCodec = class extends ifaces_1.ScalarCodec {
  61197. constructor() {
  61198. super(...arguments);
  61199. __publicField(this, "tsType", "Duration");
  61200. __publicField(this, "tsModule", "gel");
  61201. }
  61202. encode(buf, object, ctx) {
  61203. if (ctx.hasOverload(this)) {
  61204. const us2 = ctx.preEncode(this, object);
  61205. if (typeof us2 != "bigint") {
  61206. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom std::duration codec`);
  61207. }
  61208. buf.writeInt32(16);
  61209. buf.writeBigInt64(us2);
  61210. buf.writeInt32(0);
  61211. buf.writeInt32(0);
  61212. return;
  61213. }
  61214. if (!(object instanceof datetime_1.Duration)) {
  61215. throw new errors_1.InvalidArgumentError(`a Duration instance was expected, got "${object}"`);
  61216. }
  61217. const invalidField = checkValidGelDuration(object);
  61218. if (invalidField) {
  61219. throw new errors_1.InvalidArgumentError(`Cannot encode a 'Duration' with a non-zero number of ${invalidField}`);
  61220. }
  61221. let us = BigInt(Math.abs(object.microseconds));
  61222. us += BigInt(Math.abs(object.milliseconds)) * BigInt(1e3);
  61223. us += BigInt(Math.abs(object.seconds)) * BigInt(1e6);
  61224. us += BigInt(Math.abs(object.minutes)) * BigInt(6e7);
  61225. us += BigInt(Math.abs(object.hours)) * BigInt(36e8);
  61226. if (Math.abs(object.nanoseconds) === 500 && Math.abs(object.microseconds) % 2 === 1 || Math.abs(object.nanoseconds) > 500) {
  61227. us += 1n;
  61228. }
  61229. if (object.sign < 0) {
  61230. us *= -1n;
  61231. }
  61232. buf.writeInt32(16);
  61233. buf.writeBigInt64(us);
  61234. buf.writeInt32(0);
  61235. buf.writeInt32(0);
  61236. }
  61237. decode(buf, ctx) {
  61238. let bius = buf.readBigInt64();
  61239. const days = buf.readInt32();
  61240. const months = buf.readInt32();
  61241. if (days !== 0) {
  61242. throw new errors_1.ProtocolError("non-zero reserved bytes in duration");
  61243. }
  61244. if (months !== 0) {
  61245. throw new errors_1.ProtocolError("non-zero reserved bytes in duration");
  61246. }
  61247. if (ctx.hasOverload(this)) {
  61248. return ctx.postDecode(this, bius);
  61249. }
  61250. let sign = 1;
  61251. if (Number(bius) < 0) {
  61252. sign = -1;
  61253. bius *= -1n;
  61254. }
  61255. const biMillion = 1000000n;
  61256. const biSeconds = bius / biMillion;
  61257. let us = Number(bius - biSeconds * biMillion);
  61258. const ms = Math.floor(us / 1e3);
  61259. us = us % 1e3;
  61260. let seconds = Number(biSeconds);
  61261. let minutes = Math.floor(seconds / 60);
  61262. seconds = Math.floor(seconds % 60);
  61263. const hours = Math.floor(minutes / 60);
  61264. minutes = Math.floor(minutes % 60);
  61265. return new datetime_1.Duration(0, 0, 0, 0, hours * sign, minutes * sign, seconds * sign, ms * sign, us * sign);
  61266. }
  61267. };
  61268. exports.DurationCodec = DurationCodec;
  61269. var RelativeDurationCodec = class extends ifaces_1.ScalarCodec {
  61270. constructor() {
  61271. super(...arguments);
  61272. __publicField(this, "tsType", "RelativeDuration");
  61273. __publicField(this, "tsModule", "gel");
  61274. }
  61275. encode(buf, object, ctx) {
  61276. if (ctx.hasOverload(this)) {
  61277. const ret = ctx.preEncode(this, object);
  61278. buf.writeInt32(16);
  61279. buf.writeBigInt64(ret[2]);
  61280. buf.writeInt32(ret[1]);
  61281. buf.writeInt32(ret[0]);
  61282. return;
  61283. }
  61284. if (!(object instanceof datetime_1.RelativeDuration)) {
  61285. throw new errors_1.InvalidArgumentError(`
  61286. a RelativeDuration instance was expected, got "${object}"
  61287. `);
  61288. }
  61289. const us = BigInt(object.microseconds) + BigInt(object.milliseconds) * BigInt(1e3) + BigInt(object.seconds) * BigInt(1e6) + BigInt(object.minutes) * BigInt(6e7) + BigInt(object.hours) * BigInt(36e8);
  61290. buf.writeInt32(16);
  61291. buf.writeBigInt64(us);
  61292. buf.writeInt32(object.days + 7 * object.weeks);
  61293. buf.writeInt32(object.months + 12 * object.years);
  61294. }
  61295. decode(buf, ctx) {
  61296. let bius = buf.readBigInt64();
  61297. let days = buf.readInt32();
  61298. let months = buf.readInt32();
  61299. if (ctx.hasOverload(this)) {
  61300. return ctx.postDecode(this, [
  61301. months,
  61302. days,
  61303. bius
  61304. ]);
  61305. }
  61306. let sign = 1;
  61307. if (Number(bius) < 0) {
  61308. sign = -1;
  61309. bius *= -1n;
  61310. }
  61311. const million = BigInt(1e6);
  61312. const biSeconds = bius / million;
  61313. let us = Number(bius - biSeconds * million);
  61314. const ms = Math.trunc(us / 1e3);
  61315. us = us % 1e3;
  61316. let seconds = Number(biSeconds);
  61317. let minutes = Math.trunc(seconds / 60);
  61318. seconds = Math.trunc(seconds % 60);
  61319. const hours = Math.trunc(minutes / 60);
  61320. minutes = Math.trunc(minutes % 60);
  61321. const weeks = Math.trunc(days / 7);
  61322. days = Math.trunc(days % 7);
  61323. const years = Math.trunc(months / 12);
  61324. months = Math.trunc(months % 12);
  61325. return new datetime_1.RelativeDuration(years, months, weeks, days, hours * sign, minutes * sign, seconds * sign, ms * sign, us * sign);
  61326. }
  61327. };
  61328. exports.RelativeDurationCodec = RelativeDurationCodec;
  61329. var DateDurationCodec = class extends ifaces_1.ScalarCodec {
  61330. constructor() {
  61331. super(...arguments);
  61332. __publicField(this, "tsType", "DateDuration");
  61333. __publicField(this, "tsModule", "gel");
  61334. }
  61335. encode(buf, object, ctx) {
  61336. if (ctx.hasOverload(this)) {
  61337. const ret = ctx.preEncode(this, object);
  61338. buf.writeInt32(16);
  61339. buf.writeInt64(0);
  61340. buf.writeInt32(ret[1]);
  61341. buf.writeInt32(ret[0]);
  61342. return;
  61343. }
  61344. if (!(object instanceof datetime_1.DateDuration)) {
  61345. throw new errors_1.InvalidArgumentError(`
  61346. a DateDuration instance was expected, got "${object}"
  61347. `);
  61348. }
  61349. buf.writeInt32(16);
  61350. buf.writeInt64(0);
  61351. buf.writeInt32(object.days + 7 * object.weeks);
  61352. buf.writeInt32(object.months + 12 * object.years);
  61353. }
  61354. decode(buf, ctx) {
  61355. buf.discard(8);
  61356. let days = buf.readInt32();
  61357. let months = buf.readInt32();
  61358. if (ctx.hasOverload(this)) {
  61359. return ctx.postDecode(this, [months, days]);
  61360. }
  61361. const weeks = Math.trunc(days / 7);
  61362. days = Math.trunc(days % 7);
  61363. const years = Math.trunc(months / 12);
  61364. months = Math.trunc(months % 12);
  61365. return new datetime_1.DateDuration(years, months, weeks, days);
  61366. }
  61367. };
  61368. exports.DateDurationCodec = DateDurationCodec;
  61369. }
  61370. });
  61371. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/memory.js
  61372. var require_memory = __commonJS({
  61373. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/memory.js"(exports) {
  61374. "use strict";
  61375. Object.defineProperty(exports, "__esModule", { value: true });
  61376. exports.ConfigMemory = void 0;
  61377. var KiB = 1024;
  61378. var MiB = 1024 * KiB;
  61379. var GiB = 1024 * MiB;
  61380. var TiB = 1024 * GiB;
  61381. var PiB = 1024 * TiB;
  61382. var ConfigMemory = class {
  61383. constructor(bytes) {
  61384. __publicField(this, "_bytes");
  61385. this._bytes = bytes;
  61386. }
  61387. get bytes() {
  61388. return Number(this._bytes);
  61389. }
  61390. get bytesBigInt() {
  61391. return this._bytes;
  61392. }
  61393. get kibibytes() {
  61394. return Number(this._bytes) / KiB;
  61395. }
  61396. get mebibytes() {
  61397. return Number(this._bytes) / MiB;
  61398. }
  61399. get gibibytes() {
  61400. return Number(this._bytes) / GiB;
  61401. }
  61402. get tebibytes() {
  61403. return Number(this._bytes) / TiB;
  61404. }
  61405. get pebibytes() {
  61406. return Number(this._bytes) / PiB;
  61407. }
  61408. toString() {
  61409. const bytes = this._bytes;
  61410. const bigPiB = BigInt(PiB);
  61411. if (bytes >= bigPiB && Number(bytes % bigPiB) === 0) {
  61412. return `${bytes / bigPiB}PiB`;
  61413. }
  61414. const bigTiB = BigInt(TiB);
  61415. if (bytes >= bigTiB && Number(bytes % bigTiB) === 0) {
  61416. return `${bytes / bigTiB}TiB`;
  61417. }
  61418. const bigGiB = BigInt(GiB);
  61419. if (bytes >= bigGiB && Number(bytes % bigGiB) === 0) {
  61420. return `${bytes / bigGiB}GiB`;
  61421. }
  61422. const bigMiB = BigInt(MiB);
  61423. if (bytes >= bigMiB && Number(bytes % bigMiB) === 0) {
  61424. return `${bytes / bigMiB}MiB`;
  61425. }
  61426. const bigKiB = BigInt(KiB);
  61427. if (bytes >= bigKiB && Number(bytes % bigKiB) === 0) {
  61428. return `${bytes / bigKiB}KiB`;
  61429. }
  61430. return `${bytes}B`;
  61431. }
  61432. };
  61433. exports.ConfigMemory = ConfigMemory;
  61434. }
  61435. });
  61436. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/memory.js
  61437. var require_memory2 = __commonJS({
  61438. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/memory.js"(exports) {
  61439. "use strict";
  61440. Object.defineProperty(exports, "__esModule", { value: true });
  61441. exports.ConfigMemoryCodec = void 0;
  61442. var ifaces_1 = require_ifaces();
  61443. var memory_1 = require_memory();
  61444. var errors_1 = require_errors();
  61445. var ConfigMemoryCodec = class extends ifaces_1.ScalarCodec {
  61446. constructor() {
  61447. super(...arguments);
  61448. __publicField(this, "tsType", "ConfigMemory");
  61449. __publicField(this, "tsModule", "gel");
  61450. }
  61451. encode(buf, object, ctx) {
  61452. if (ctx.hasOverload(this)) {
  61453. const val2 = ctx.preEncode(this, object);
  61454. if (typeof val2 != "bigint") {
  61455. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cfg::memory codec`);
  61456. }
  61457. buf.writeInt32(8);
  61458. buf.writeBigInt64(val2);
  61459. return;
  61460. }
  61461. if (!(object instanceof memory_1.ConfigMemory)) {
  61462. throw new errors_1.InvalidArgumentError(`a ConfigMemory instance was expected, got "${object}"`);
  61463. }
  61464. buf.writeInt32(8);
  61465. buf.writeBigInt64(object._bytes);
  61466. }
  61467. decode(buf, ctx) {
  61468. const val2 = buf.readBigInt64();
  61469. if (ctx.hasOverload(this)) {
  61470. return ctx.postDecode(this, val2);
  61471. }
  61472. return new memory_1.ConfigMemory(val2);
  61473. }
  61474. };
  61475. exports.ConfigMemoryCodec = ConfigMemoryCodec;
  61476. }
  61477. });
  61478. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/messages.cjs
  61479. var require_messages = __commonJS({
  61480. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/messages.cjs"(exports) {
  61481. "use strict";
  61482. Object.defineProperty(exports, "__esModule", {
  61483. value: true
  61484. });
  61485. var THIS_IS_NOT_AN_OBJECT = exports.THIS_IS_NOT_AN_OBJECT = "This is not an object";
  61486. var THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = exports.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = "This is not a Float16Array object";
  61487. var THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = exports.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = "This constructor is not a subclass of Float16Array";
  61488. var THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = exports.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = "The constructor property value is not an object";
  61489. var SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = exports.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = "Species constructor didn't return TypedArray object";
  61490. var DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = exports.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = "Derived constructor created TypedArray object which was too small length";
  61491. var ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = exports.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = "Attempting to access detached ArrayBuffer";
  61492. var CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = exports.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = "Cannot convert undefined or null to object";
  61493. var CANNOT_MIX_BIGINT_AND_OTHER_TYPES = exports.CANNOT_MIX_BIGINT_AND_OTHER_TYPES = "Cannot mix BigInt and other types, use explicit conversions";
  61494. var ITERATOR_PROPERTY_IS_NOT_CALLABLE = exports.ITERATOR_PROPERTY_IS_NOT_CALLABLE = "@@iterator property is not callable";
  61495. var REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = exports.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = "Reduce of empty array with no initial value";
  61496. var THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = exports.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = "The comparison function must be either a function or undefined";
  61497. var OFFSET_IS_OUT_OF_BOUNDS = exports.OFFSET_IS_OUT_OF_BOUNDS = "Offset is out of bounds";
  61498. }
  61499. });
  61500. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/primordials.cjs
  61501. var require_primordials = __commonJS({
  61502. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/primordials.cjs"(exports) {
  61503. "use strict";
  61504. Object.defineProperty(exports, "__esModule", {
  61505. value: true
  61506. });
  61507. var _messages = require_messages();
  61508. function uncurryThis(target) {
  61509. return (thisArg, ...args) => {
  61510. return ReflectApply(target, thisArg, args);
  61511. };
  61512. }
  61513. function uncurryThisGetter(target, key) {
  61514. return uncurryThis(ReflectGetOwnPropertyDescriptor(target, key).get);
  61515. }
  61516. var {
  61517. apply: ReflectApply,
  61518. construct: ReflectConstruct,
  61519. defineProperty: ReflectDefineProperty,
  61520. get: ReflectGet,
  61521. getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
  61522. getPrototypeOf: ReflectGetPrototypeOf,
  61523. has: ReflectHas,
  61524. ownKeys: ReflectOwnKeys,
  61525. set: ReflectSet,
  61526. setPrototypeOf: ReflectSetPrototypeOf
  61527. } = Reflect;
  61528. exports.ReflectSetPrototypeOf = ReflectSetPrototypeOf;
  61529. exports.ReflectSet = ReflectSet;
  61530. exports.ReflectOwnKeys = ReflectOwnKeys;
  61531. exports.ReflectHas = ReflectHas;
  61532. exports.ReflectGetPrototypeOf = ReflectGetPrototypeOf;
  61533. exports.ReflectGetOwnPropertyDescriptor = ReflectGetOwnPropertyDescriptor;
  61534. exports.ReflectGet = ReflectGet;
  61535. exports.ReflectDefineProperty = ReflectDefineProperty;
  61536. exports.ReflectConstruct = ReflectConstruct;
  61537. exports.ReflectApply = ReflectApply;
  61538. var NativeProxy = exports.NativeProxy = Proxy;
  61539. var {
  61540. EPSILON,
  61541. MAX_SAFE_INTEGER,
  61542. isFinite: NumberIsFinite,
  61543. isNaN: NumberIsNaN
  61544. } = Number;
  61545. exports.NumberIsNaN = NumberIsNaN;
  61546. exports.NumberIsFinite = NumberIsFinite;
  61547. exports.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
  61548. exports.EPSILON = EPSILON;
  61549. var {
  61550. iterator: SymbolIterator,
  61551. species: SymbolSpecies,
  61552. toStringTag: SymbolToStringTag,
  61553. for: SymbolFor
  61554. } = Symbol;
  61555. exports.SymbolFor = SymbolFor;
  61556. exports.SymbolToStringTag = SymbolToStringTag;
  61557. exports.SymbolSpecies = SymbolSpecies;
  61558. exports.SymbolIterator = SymbolIterator;
  61559. var NativeObject = exports.NativeObject = Object;
  61560. var {
  61561. create: ObjectCreate,
  61562. defineProperty: ObjectDefineProperty,
  61563. freeze: ObjectFreeze,
  61564. is: ObjectIs
  61565. } = NativeObject;
  61566. exports.ObjectIs = ObjectIs;
  61567. exports.ObjectFreeze = ObjectFreeze;
  61568. exports.ObjectDefineProperty = ObjectDefineProperty;
  61569. exports.ObjectCreate = ObjectCreate;
  61570. var ObjectPrototype = NativeObject.prototype;
  61571. var ObjectPrototype__lookupGetter__ = exports.ObjectPrototype__lookupGetter__ = ObjectPrototype.__lookupGetter__ ? uncurryThis(ObjectPrototype.__lookupGetter__) : (object, key) => {
  61572. if (object == null) {
  61573. throw NativeTypeError(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
  61574. }
  61575. let target = NativeObject(object);
  61576. do {
  61577. const descriptor = ReflectGetOwnPropertyDescriptor(target, key);
  61578. if (descriptor !== void 0) {
  61579. if (ObjectHasOwn(descriptor, "get")) {
  61580. return descriptor.get;
  61581. }
  61582. return;
  61583. }
  61584. } while ((target = ReflectGetPrototypeOf(target)) !== null);
  61585. };
  61586. var ObjectHasOwn = exports.ObjectHasOwn = NativeObject.hasOwn || uncurryThis(ObjectPrototype.hasOwnProperty);
  61587. var NativeArray = Array;
  61588. var ArrayIsArray = exports.ArrayIsArray = NativeArray.isArray;
  61589. var ArrayPrototype = NativeArray.prototype;
  61590. var ArrayPrototypeJoin = exports.ArrayPrototypeJoin = uncurryThis(ArrayPrototype.join);
  61591. var ArrayPrototypePush = exports.ArrayPrototypePush = uncurryThis(ArrayPrototype.push);
  61592. var ArrayPrototypeToLocaleString = exports.ArrayPrototypeToLocaleString = uncurryThis(ArrayPrototype.toLocaleString);
  61593. var NativeArrayPrototypeSymbolIterator = exports.NativeArrayPrototypeSymbolIterator = ArrayPrototype[SymbolIterator];
  61594. var ArrayPrototypeSymbolIterator = exports.ArrayPrototypeSymbolIterator = uncurryThis(NativeArrayPrototypeSymbolIterator);
  61595. var {
  61596. abs: MathAbs,
  61597. trunc: MathTrunc
  61598. } = Math;
  61599. exports.MathTrunc = MathTrunc;
  61600. exports.MathAbs = MathAbs;
  61601. var NativeArrayBuffer = exports.NativeArrayBuffer = ArrayBuffer;
  61602. var ArrayBufferIsView = exports.ArrayBufferIsView = NativeArrayBuffer.isView;
  61603. var ArrayBufferPrototype = NativeArrayBuffer.prototype;
  61604. var ArrayBufferPrototypeSlice = exports.ArrayBufferPrototypeSlice = uncurryThis(ArrayBufferPrototype.slice);
  61605. var ArrayBufferPrototypeGetByteLength = exports.ArrayBufferPrototypeGetByteLength = uncurryThisGetter(ArrayBufferPrototype, "byteLength");
  61606. var NativeSharedArrayBuffer = exports.NativeSharedArrayBuffer = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : null;
  61607. var SharedArrayBufferPrototypeGetByteLength = exports.SharedArrayBufferPrototypeGetByteLength = NativeSharedArrayBuffer && uncurryThisGetter(NativeSharedArrayBuffer.prototype, "byteLength");
  61608. var TypedArray = exports.TypedArray = ReflectGetPrototypeOf(Uint8Array);
  61609. var TypedArrayFrom = TypedArray.from;
  61610. var TypedArrayPrototype = exports.TypedArrayPrototype = TypedArray.prototype;
  61611. var NativeTypedArrayPrototypeSymbolIterator = exports.NativeTypedArrayPrototypeSymbolIterator = TypedArrayPrototype[SymbolIterator];
  61612. var TypedArrayPrototypeKeys = exports.TypedArrayPrototypeKeys = uncurryThis(TypedArrayPrototype.keys);
  61613. var TypedArrayPrototypeValues = exports.TypedArrayPrototypeValues = uncurryThis(TypedArrayPrototype.values);
  61614. var TypedArrayPrototypeEntries = exports.TypedArrayPrototypeEntries = uncurryThis(TypedArrayPrototype.entries);
  61615. var TypedArrayPrototypeSet = exports.TypedArrayPrototypeSet = uncurryThis(TypedArrayPrototype.set);
  61616. var TypedArrayPrototypeReverse = exports.TypedArrayPrototypeReverse = uncurryThis(TypedArrayPrototype.reverse);
  61617. var TypedArrayPrototypeFill = exports.TypedArrayPrototypeFill = uncurryThis(TypedArrayPrototype.fill);
  61618. var TypedArrayPrototypeCopyWithin = exports.TypedArrayPrototypeCopyWithin = uncurryThis(TypedArrayPrototype.copyWithin);
  61619. var TypedArrayPrototypeSort = exports.TypedArrayPrototypeSort = uncurryThis(TypedArrayPrototype.sort);
  61620. var TypedArrayPrototypeSlice = exports.TypedArrayPrototypeSlice = uncurryThis(TypedArrayPrototype.slice);
  61621. var TypedArrayPrototypeSubarray = exports.TypedArrayPrototypeSubarray = uncurryThis(TypedArrayPrototype.subarray);
  61622. var TypedArrayPrototypeGetBuffer = exports.TypedArrayPrototypeGetBuffer = uncurryThisGetter(TypedArrayPrototype, "buffer");
  61623. var TypedArrayPrototypeGetByteOffset = exports.TypedArrayPrototypeGetByteOffset = uncurryThisGetter(TypedArrayPrototype, "byteOffset");
  61624. var TypedArrayPrototypeGetLength = exports.TypedArrayPrototypeGetLength = uncurryThisGetter(TypedArrayPrototype, "length");
  61625. var TypedArrayPrototypeGetSymbolToStringTag = exports.TypedArrayPrototypeGetSymbolToStringTag = uncurryThisGetter(TypedArrayPrototype, SymbolToStringTag);
  61626. var NativeUint8Array = exports.NativeUint8Array = Uint8Array;
  61627. var NativeUint16Array = exports.NativeUint16Array = Uint16Array;
  61628. var Uint16ArrayFrom = (...args) => {
  61629. return ReflectApply(TypedArrayFrom, NativeUint16Array, args);
  61630. };
  61631. exports.Uint16ArrayFrom = Uint16ArrayFrom;
  61632. var NativeUint32Array = exports.NativeUint32Array = Uint32Array;
  61633. var NativeFloat32Array = exports.NativeFloat32Array = Float32Array;
  61634. var ArrayIteratorPrototype = exports.ArrayIteratorPrototype = ReflectGetPrototypeOf([][SymbolIterator]());
  61635. var ArrayIteratorPrototypeNext = exports.ArrayIteratorPrototypeNext = uncurryThis(ArrayIteratorPrototype.next);
  61636. var GeneratorPrototypeNext = exports.GeneratorPrototypeNext = uncurryThis(function* () {
  61637. }().next);
  61638. var IteratorPrototype = exports.IteratorPrototype = ReflectGetPrototypeOf(ArrayIteratorPrototype);
  61639. var DataViewPrototype = DataView.prototype;
  61640. var DataViewPrototypeGetUint16 = exports.DataViewPrototypeGetUint16 = uncurryThis(DataViewPrototype.getUint16);
  61641. var DataViewPrototypeSetUint16 = exports.DataViewPrototypeSetUint16 = uncurryThis(DataViewPrototype.setUint16);
  61642. var NativeTypeError = exports.NativeTypeError = TypeError;
  61643. var NativeRangeError = exports.NativeRangeError = RangeError;
  61644. var NativeWeakSet = exports.NativeWeakSet = WeakSet;
  61645. var WeakSetPrototype = NativeWeakSet.prototype;
  61646. var WeakSetPrototypeAdd = exports.WeakSetPrototypeAdd = uncurryThis(WeakSetPrototype.add);
  61647. var WeakSetPrototypeHas = exports.WeakSetPrototypeHas = uncurryThis(WeakSetPrototype.has);
  61648. var NativeWeakMap = exports.NativeWeakMap = WeakMap;
  61649. var WeakMapPrototype = NativeWeakMap.prototype;
  61650. var WeakMapPrototypeGet = exports.WeakMapPrototypeGet = uncurryThis(WeakMapPrototype.get);
  61651. var WeakMapPrototypeHas = exports.WeakMapPrototypeHas = uncurryThis(WeakMapPrototype.has);
  61652. var WeakMapPrototypeSet = exports.WeakMapPrototypeSet = uncurryThis(WeakMapPrototype.set);
  61653. }
  61654. });
  61655. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/arrayIterator.cjs
  61656. var require_arrayIterator = __commonJS({
  61657. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/arrayIterator.cjs"(exports) {
  61658. "use strict";
  61659. Object.defineProperty(exports, "__esModule", {
  61660. value: true
  61661. });
  61662. exports.safeIfNeeded = safeIfNeeded;
  61663. exports.wrap = wrap;
  61664. var _primordials = require_primordials();
  61665. var arrayIterators = new _primordials.NativeWeakMap();
  61666. var SafeIteratorPrototype = (0, _primordials.ObjectCreate)(null, {
  61667. next: {
  61668. value: function next() {
  61669. const arrayIterator = (0, _primordials.WeakMapPrototypeGet)(arrayIterators, this);
  61670. return (0, _primordials.ArrayIteratorPrototypeNext)(arrayIterator);
  61671. }
  61672. },
  61673. [_primordials.SymbolIterator]: {
  61674. value: function values() {
  61675. return this;
  61676. }
  61677. }
  61678. });
  61679. function safeIfNeeded(array2) {
  61680. if (array2[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext) {
  61681. return array2;
  61682. }
  61683. const safe = (0, _primordials.ObjectCreate)(SafeIteratorPrototype);
  61684. (0, _primordials.WeakMapPrototypeSet)(arrayIterators, safe, (0, _primordials.ArrayPrototypeSymbolIterator)(array2));
  61685. return safe;
  61686. }
  61687. var generators = new _primordials.NativeWeakMap();
  61688. var DummyArrayIteratorPrototype = (0, _primordials.ObjectCreate)(_primordials.IteratorPrototype, {
  61689. next: {
  61690. value: function next() {
  61691. const generator = (0, _primordials.WeakMapPrototypeGet)(generators, this);
  61692. return (0, _primordials.GeneratorPrototypeNext)(generator);
  61693. },
  61694. writable: true,
  61695. configurable: true
  61696. }
  61697. });
  61698. for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.ArrayIteratorPrototype)) {
  61699. if (key === "next") {
  61700. continue;
  61701. }
  61702. (0, _primordials.ObjectDefineProperty)(DummyArrayIteratorPrototype, key, (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.ArrayIteratorPrototype, key));
  61703. }
  61704. function wrap(generator) {
  61705. const dummy = (0, _primordials.ObjectCreate)(DummyArrayIteratorPrototype);
  61706. (0, _primordials.WeakMapPrototypeSet)(generators, dummy, generator);
  61707. return dummy;
  61708. }
  61709. }
  61710. });
  61711. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/is.cjs
  61712. var require_is = __commonJS({
  61713. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/is.cjs"(exports) {
  61714. "use strict";
  61715. Object.defineProperty(exports, "__esModule", {
  61716. value: true
  61717. });
  61718. exports.isAnyArrayBuffer = isAnyArrayBuffer;
  61719. exports.isCanonicalIntegerIndexString = isCanonicalIntegerIndexString;
  61720. exports.isNativeBigIntTypedArray = isNativeBigIntTypedArray;
  61721. exports.isNativeTypedArray = isNativeTypedArray;
  61722. exports.isObject = isObject;
  61723. exports.isObjectLike = isObjectLike;
  61724. exports.isOrdinaryArray = isOrdinaryArray;
  61725. exports.isOrdinaryNativeTypedArray = isOrdinaryNativeTypedArray;
  61726. exports.isSharedArrayBuffer = isSharedArrayBuffer;
  61727. var _primordials = require_primordials();
  61728. function isObject(value) {
  61729. return value !== null && typeof value === "object" || typeof value === "function";
  61730. }
  61731. function isObjectLike(value) {
  61732. return value !== null && typeof value === "object";
  61733. }
  61734. function isNativeTypedArray(value) {
  61735. return (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value) !== void 0;
  61736. }
  61737. function isNativeBigIntTypedArray(value) {
  61738. const typedArrayName = (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value);
  61739. return typedArrayName === "BigInt64Array" || typedArrayName === "BigUint64Array";
  61740. }
  61741. function isArrayBuffer2(value) {
  61742. try {
  61743. if ((0, _primordials.ArrayIsArray)(value)) {
  61744. return false;
  61745. }
  61746. (0, _primordials.ArrayBufferPrototypeGetByteLength)(value);
  61747. return true;
  61748. } catch (e6) {
  61749. return false;
  61750. }
  61751. }
  61752. function isSharedArrayBuffer(value) {
  61753. if (_primordials.NativeSharedArrayBuffer === null) {
  61754. return false;
  61755. }
  61756. try {
  61757. (0, _primordials.SharedArrayBufferPrototypeGetByteLength)(value);
  61758. return true;
  61759. } catch (e6) {
  61760. return false;
  61761. }
  61762. }
  61763. function isAnyArrayBuffer(value) {
  61764. return isArrayBuffer2(value) || isSharedArrayBuffer(value);
  61765. }
  61766. function isOrdinaryArray(value) {
  61767. if (!(0, _primordials.ArrayIsArray)(value)) {
  61768. return false;
  61769. }
  61770. return value[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
  61771. }
  61772. function isOrdinaryNativeTypedArray(value) {
  61773. if (!isNativeTypedArray(value)) {
  61774. return false;
  61775. }
  61776. return value[_primordials.SymbolIterator] === _primordials.NativeTypedArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
  61777. }
  61778. function isCanonicalIntegerIndexString(value) {
  61779. if (typeof value !== "string") {
  61780. return false;
  61781. }
  61782. const number = +value;
  61783. if (value !== number + "") {
  61784. return false;
  61785. }
  61786. if (!(0, _primordials.NumberIsFinite)(number)) {
  61787. return false;
  61788. }
  61789. return number === (0, _primordials.MathTrunc)(number);
  61790. }
  61791. }
  61792. });
  61793. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/brand.cjs
  61794. var require_brand = __commonJS({
  61795. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/brand.cjs"(exports) {
  61796. "use strict";
  61797. Object.defineProperty(exports, "__esModule", {
  61798. value: true
  61799. });
  61800. exports.hasFloat16ArrayBrand = hasFloat16ArrayBrand;
  61801. var _is = require_is();
  61802. var _messages = require_messages();
  61803. var _primordials = require_primordials();
  61804. var brand = exports.brand = (0, _primordials.SymbolFor)("__Float16Array__");
  61805. function hasFloat16ArrayBrand(target) {
  61806. if (!(0, _is.isObjectLike)(target)) {
  61807. return false;
  61808. }
  61809. const prototype = (0, _primordials.ReflectGetPrototypeOf)(target);
  61810. if (!(0, _is.isObjectLike)(prototype)) {
  61811. return false;
  61812. }
  61813. const constructor = prototype.constructor;
  61814. if (constructor === void 0) {
  61815. return false;
  61816. }
  61817. if (!(0, _is.isObject)(constructor)) {
  61818. throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
  61819. }
  61820. return (0, _primordials.ReflectHas)(constructor, brand);
  61821. }
  61822. }
  61823. });
  61824. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/converter.cjs
  61825. var require_converter = __commonJS({
  61826. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/converter.cjs"(exports) {
  61827. "use strict";
  61828. Object.defineProperty(exports, "__esModule", {
  61829. value: true
  61830. });
  61831. exports.convertToNumber = convertToNumber;
  61832. exports.roundToFloat16 = roundToFloat16;
  61833. exports.roundToFloat16Bits = roundToFloat16Bits;
  61834. var _primordials = require_primordials();
  61835. var INVERSE_OF_EPSILON = 1 / _primordials.EPSILON;
  61836. function roundTiesToEven(num) {
  61837. return num + INVERSE_OF_EPSILON - INVERSE_OF_EPSILON;
  61838. }
  61839. var FLOAT16_MIN_VALUE = 6103515625e-14;
  61840. var FLOAT16_MAX_VALUE = 65504;
  61841. var FLOAT16_EPSILON = 9765625e-10;
  61842. var FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE = FLOAT16_EPSILON * FLOAT16_MIN_VALUE;
  61843. var FLOAT16_EPSILON_DEVIDED_BY_EPSILON = FLOAT16_EPSILON * INVERSE_OF_EPSILON;
  61844. function roundToFloat16(num) {
  61845. const number = +num;
  61846. if (!(0, _primordials.NumberIsFinite)(number) || number === 0) {
  61847. return number;
  61848. }
  61849. const sign = number > 0 ? 1 : -1;
  61850. const absolute = (0, _primordials.MathAbs)(number);
  61851. if (absolute < FLOAT16_MIN_VALUE) {
  61852. return sign * roundTiesToEven(absolute / FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE) * FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE;
  61853. }
  61854. const temp = (1 + FLOAT16_EPSILON_DEVIDED_BY_EPSILON) * absolute;
  61855. const result = temp - (temp - absolute);
  61856. if (result > FLOAT16_MAX_VALUE || (0, _primordials.NumberIsNaN)(result)) {
  61857. return sign * Infinity;
  61858. }
  61859. return sign * result;
  61860. }
  61861. var buffer = new _primordials.NativeArrayBuffer(4);
  61862. var floatView = new _primordials.NativeFloat32Array(buffer);
  61863. var uint32View = new _primordials.NativeUint32Array(buffer);
  61864. var baseTable = new _primordials.NativeUint16Array(512);
  61865. var shiftTable = new _primordials.NativeUint8Array(512);
  61866. for (let i6 = 0; i6 < 256; ++i6) {
  61867. const e6 = i6 - 127;
  61868. if (e6 < -24) {
  61869. baseTable[i6] = 0;
  61870. baseTable[i6 | 256] = 32768;
  61871. shiftTable[i6] = 24;
  61872. shiftTable[i6 | 256] = 24;
  61873. } else if (e6 < -14) {
  61874. baseTable[i6] = 1024 >> -e6 - 14;
  61875. baseTable[i6 | 256] = 1024 >> -e6 - 14 | 32768;
  61876. shiftTable[i6] = -e6 - 1;
  61877. shiftTable[i6 | 256] = -e6 - 1;
  61878. } else if (e6 <= 15) {
  61879. baseTable[i6] = e6 + 15 << 10;
  61880. baseTable[i6 | 256] = e6 + 15 << 10 | 32768;
  61881. shiftTable[i6] = 13;
  61882. shiftTable[i6 | 256] = 13;
  61883. } else if (e6 < 128) {
  61884. baseTable[i6] = 31744;
  61885. baseTable[i6 | 256] = 64512;
  61886. shiftTable[i6] = 24;
  61887. shiftTable[i6 | 256] = 24;
  61888. } else {
  61889. baseTable[i6] = 31744;
  61890. baseTable[i6 | 256] = 64512;
  61891. shiftTable[i6] = 13;
  61892. shiftTable[i6 | 256] = 13;
  61893. }
  61894. }
  61895. function roundToFloat16Bits(num) {
  61896. floatView[0] = roundToFloat16(num);
  61897. const f7 = uint32View[0];
  61898. const e6 = f7 >> 23 & 511;
  61899. return baseTable[e6] + ((f7 & 8388607) >> shiftTable[e6]);
  61900. }
  61901. var mantissaTable = new _primordials.NativeUint32Array(2048);
  61902. for (let i6 = 1; i6 < 1024; ++i6) {
  61903. let m6 = i6 << 13;
  61904. let e6 = 0;
  61905. while ((m6 & 8388608) === 0) {
  61906. m6 <<= 1;
  61907. e6 -= 8388608;
  61908. }
  61909. m6 &= ~8388608;
  61910. e6 += 947912704;
  61911. mantissaTable[i6] = m6 | e6;
  61912. }
  61913. for (let i6 = 1024; i6 < 2048; ++i6) {
  61914. mantissaTable[i6] = 939524096 + (i6 - 1024 << 13);
  61915. }
  61916. var exponentTable = new _primordials.NativeUint32Array(64);
  61917. for (let i6 = 1; i6 < 31; ++i6) {
  61918. exponentTable[i6] = i6 << 23;
  61919. }
  61920. exponentTable[31] = 1199570944;
  61921. exponentTable[32] = 2147483648;
  61922. for (let i6 = 33; i6 < 63; ++i6) {
  61923. exponentTable[i6] = 2147483648 + (i6 - 32 << 23);
  61924. }
  61925. exponentTable[63] = 3347054592;
  61926. var offsetTable = new _primordials.NativeUint16Array(64);
  61927. for (let i6 = 1; i6 < 64; ++i6) {
  61928. if (i6 !== 32) {
  61929. offsetTable[i6] = 1024;
  61930. }
  61931. }
  61932. function convertToNumber(float16bits) {
  61933. const i6 = float16bits >> 10;
  61934. uint32View[0] = mantissaTable[offsetTable[i6] + (float16bits & 1023)] + exponentTable[i6];
  61935. return floatView[0];
  61936. }
  61937. }
  61938. });
  61939. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/spec.cjs
  61940. var require_spec = __commonJS({
  61941. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/spec.cjs"(exports) {
  61942. "use strict";
  61943. Object.defineProperty(exports, "__esModule", {
  61944. value: true
  61945. });
  61946. exports.IsDetachedBuffer = IsDetachedBuffer;
  61947. exports.SpeciesConstructor = SpeciesConstructor;
  61948. exports.ToIntegerOrInfinity = ToIntegerOrInfinity;
  61949. exports.ToLength = ToLength;
  61950. exports.defaultCompare = defaultCompare;
  61951. var _is = require_is();
  61952. var _messages = require_messages();
  61953. var _primordials = require_primordials();
  61954. function ToIntegerOrInfinity(target) {
  61955. const number = +target;
  61956. if ((0, _primordials.NumberIsNaN)(number) || number === 0) {
  61957. return 0;
  61958. }
  61959. return (0, _primordials.MathTrunc)(number);
  61960. }
  61961. function ToLength(target) {
  61962. const length = ToIntegerOrInfinity(target);
  61963. if (length < 0) {
  61964. return 0;
  61965. }
  61966. return length < _primordials.MAX_SAFE_INTEGER ? length : _primordials.MAX_SAFE_INTEGER;
  61967. }
  61968. function SpeciesConstructor(target, defaultConstructor) {
  61969. if (!(0, _is.isObject)(target)) {
  61970. throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_AN_OBJECT);
  61971. }
  61972. const constructor = target.constructor;
  61973. if (constructor === void 0) {
  61974. return defaultConstructor;
  61975. }
  61976. if (!(0, _is.isObject)(constructor)) {
  61977. throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
  61978. }
  61979. const species = constructor[_primordials.SymbolSpecies];
  61980. if (species == null) {
  61981. return defaultConstructor;
  61982. }
  61983. return species;
  61984. }
  61985. function IsDetachedBuffer(buffer) {
  61986. if ((0, _is.isSharedArrayBuffer)(buffer)) {
  61987. return false;
  61988. }
  61989. try {
  61990. (0, _primordials.ArrayBufferPrototypeSlice)(buffer, 0, 0);
  61991. return false;
  61992. } catch (e6) {
  61993. }
  61994. return true;
  61995. }
  61996. function defaultCompare(x5, y2) {
  61997. const isXNaN = (0, _primordials.NumberIsNaN)(x5);
  61998. const isYNaN = (0, _primordials.NumberIsNaN)(y2);
  61999. if (isXNaN && isYNaN) {
  62000. return 0;
  62001. }
  62002. if (isXNaN) {
  62003. return 1;
  62004. }
  62005. if (isYNaN) {
  62006. return -1;
  62007. }
  62008. if (x5 < y2) {
  62009. return -1;
  62010. }
  62011. if (x5 > y2) {
  62012. return 1;
  62013. }
  62014. if (x5 === 0 && y2 === 0) {
  62015. const isXPlusZero = (0, _primordials.ObjectIs)(x5, 0);
  62016. const isYPlusZero = (0, _primordials.ObjectIs)(y2, 0);
  62017. if (!isXPlusZero && isYPlusZero) {
  62018. return -1;
  62019. }
  62020. if (isXPlusZero && !isYPlusZero) {
  62021. return 1;
  62022. }
  62023. }
  62024. return 0;
  62025. }
  62026. }
  62027. });
  62028. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/Float16Array.cjs
  62029. var require_Float16Array = __commonJS({
  62030. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/Float16Array.cjs"(exports) {
  62031. "use strict";
  62032. Object.defineProperty(exports, "__esModule", {
  62033. value: true
  62034. });
  62035. exports.isFloat16Array = isFloat16Array;
  62036. var _arrayIterator = require_arrayIterator();
  62037. var _brand = require_brand();
  62038. var _converter = require_converter();
  62039. var _is = require_is();
  62040. var _messages = require_messages();
  62041. var _primordials = require_primordials();
  62042. var _spec = require_spec();
  62043. var BYTES_PER_ELEMENT = 2;
  62044. var float16bitsArrays = new _primordials.NativeWeakMap();
  62045. function isFloat16Array(target) {
  62046. return (0, _primordials.WeakMapPrototypeHas)(float16bitsArrays, target) || !(0, _primordials.ArrayBufferIsView)(target) && (0, _brand.hasFloat16ArrayBrand)(target);
  62047. }
  62048. function assertFloat16Array(target) {
  62049. if (!isFloat16Array(target)) {
  62050. throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT);
  62051. }
  62052. }
  62053. function assertSpeciesTypedArray(target, count) {
  62054. const isTargetFloat16Array = isFloat16Array(target);
  62055. const isTargetTypedArray = (0, _is.isNativeTypedArray)(target);
  62056. if (!isTargetFloat16Array && !isTargetTypedArray) {
  62057. throw (0, _primordials.NativeTypeError)(_messages.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT);
  62058. }
  62059. if (typeof count === "number") {
  62060. let length;
  62061. if (isTargetFloat16Array) {
  62062. const float16bitsArray = getFloat16BitsArray(target);
  62063. length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62064. } else {
  62065. length = (0, _primordials.TypedArrayPrototypeGetLength)(target);
  62066. }
  62067. if (length < count) {
  62068. throw (0, _primordials.NativeTypeError)(_messages.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH);
  62069. }
  62070. }
  62071. if ((0, _is.isNativeBigIntTypedArray)(target)) {
  62072. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
  62073. }
  62074. }
  62075. function getFloat16BitsArray(float16) {
  62076. const float16bitsArray = (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, float16);
  62077. if (float16bitsArray !== void 0) {
  62078. const buffer2 = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
  62079. if ((0, _spec.IsDetachedBuffer)(buffer2)) {
  62080. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  62081. }
  62082. return float16bitsArray;
  62083. }
  62084. const buffer = float16.buffer;
  62085. if ((0, _spec.IsDetachedBuffer)(buffer)) {
  62086. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  62087. }
  62088. const cloned = (0, _primordials.ReflectConstruct)(Float16Array, [buffer, float16.byteOffset, float16.length], float16.constructor);
  62089. return (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, cloned);
  62090. }
  62091. function copyToArray(float16bitsArray) {
  62092. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62093. const array2 = [];
  62094. for (let i6 = 0; i6 < length; ++i6) {
  62095. array2[i6] = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62096. }
  62097. return array2;
  62098. }
  62099. var TypedArrayPrototypeGetters = new _primordials.NativeWeakSet();
  62100. for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.TypedArrayPrototype)) {
  62101. if (key === _primordials.SymbolToStringTag) {
  62102. continue;
  62103. }
  62104. const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.TypedArrayPrototype, key);
  62105. if ((0, _primordials.ObjectHasOwn)(descriptor, "get") && typeof descriptor.get === "function") {
  62106. (0, _primordials.WeakSetPrototypeAdd)(TypedArrayPrototypeGetters, descriptor.get);
  62107. }
  62108. }
  62109. var handler = (0, _primordials.ObjectFreeze)({
  62110. get(target, key, receiver) {
  62111. if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
  62112. return (0, _converter.convertToNumber)((0, _primordials.ReflectGet)(target, key));
  62113. }
  62114. if ((0, _primordials.WeakSetPrototypeHas)(TypedArrayPrototypeGetters, (0, _primordials.ObjectPrototype__lookupGetter__)(target, key))) {
  62115. return (0, _primordials.ReflectGet)(target, key);
  62116. }
  62117. return (0, _primordials.ReflectGet)(target, key, receiver);
  62118. },
  62119. set(target, key, value, receiver) {
  62120. if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
  62121. return (0, _primordials.ReflectSet)(target, key, (0, _converter.roundToFloat16Bits)(value));
  62122. }
  62123. return (0, _primordials.ReflectSet)(target, key, value, receiver);
  62124. },
  62125. getOwnPropertyDescriptor(target, key) {
  62126. if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
  62127. const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
  62128. descriptor.value = (0, _converter.convertToNumber)(descriptor.value);
  62129. return descriptor;
  62130. }
  62131. return (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
  62132. },
  62133. defineProperty(target, key, descriptor) {
  62134. if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key) && (0, _primordials.ObjectHasOwn)(descriptor, "value")) {
  62135. descriptor.value = (0, _converter.roundToFloat16Bits)(descriptor.value);
  62136. return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
  62137. }
  62138. return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
  62139. }
  62140. });
  62141. var Float16Array = class _Float16Array {
  62142. constructor(input, _byteOffset, _length) {
  62143. let float16bitsArray;
  62144. if (isFloat16Array(input)) {
  62145. float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [getFloat16BitsArray(input)], new.target);
  62146. } else if ((0, _is.isObject)(input) && !(0, _is.isAnyArrayBuffer)(input)) {
  62147. let list;
  62148. let length;
  62149. if ((0, _is.isNativeTypedArray)(input)) {
  62150. list = input;
  62151. length = (0, _primordials.TypedArrayPrototypeGetLength)(input);
  62152. const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
  62153. if ((0, _spec.IsDetachedBuffer)(buffer)) {
  62154. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  62155. }
  62156. if ((0, _is.isNativeBigIntTypedArray)(input)) {
  62157. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
  62158. }
  62159. const data = new _primordials.NativeArrayBuffer(length * BYTES_PER_ELEMENT);
  62160. float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [data], new.target);
  62161. } else {
  62162. const iterator = input[_primordials.SymbolIterator];
  62163. if (iterator != null && typeof iterator !== "function") {
  62164. throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
  62165. }
  62166. if (iterator != null) {
  62167. if ((0, _is.isOrdinaryArray)(input)) {
  62168. list = input;
  62169. length = input.length;
  62170. } else {
  62171. list = [...input];
  62172. length = list.length;
  62173. }
  62174. } else {
  62175. list = input;
  62176. length = (0, _spec.ToLength)(list.length);
  62177. }
  62178. float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [length], new.target);
  62179. }
  62180. for (let i6 = 0; i6 < length; ++i6) {
  62181. float16bitsArray[i6] = (0, _converter.roundToFloat16Bits)(list[i6]);
  62182. }
  62183. } else {
  62184. float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, arguments, new.target);
  62185. }
  62186. const proxy = new _primordials.NativeProxy(float16bitsArray, handler);
  62187. (0, _primordials.WeakMapPrototypeSet)(float16bitsArrays, proxy, float16bitsArray);
  62188. return proxy;
  62189. }
  62190. static from(src, ...opts) {
  62191. const Constructor = this;
  62192. if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
  62193. throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
  62194. }
  62195. if (Constructor === _Float16Array) {
  62196. if (isFloat16Array(src) && opts.length === 0) {
  62197. const float16bitsArray = getFloat16BitsArray(src);
  62198. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  62199. return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
  62200. }
  62201. if (opts.length === 0) {
  62202. return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, _converter.roundToFloat16Bits)));
  62203. }
  62204. const mapFunc = opts[0];
  62205. const thisArg = opts[1];
  62206. return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, function(val2, ...args) {
  62207. return (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(mapFunc, this, [val2, ...(0, _arrayIterator.safeIfNeeded)(args)]));
  62208. }, thisArg)));
  62209. }
  62210. let list;
  62211. let length;
  62212. const iterator = src[_primordials.SymbolIterator];
  62213. if (iterator != null && typeof iterator !== "function") {
  62214. throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
  62215. }
  62216. if (iterator != null) {
  62217. if ((0, _is.isOrdinaryArray)(src)) {
  62218. list = src;
  62219. length = src.length;
  62220. } else if ((0, _is.isOrdinaryNativeTypedArray)(src)) {
  62221. list = src;
  62222. length = (0, _primordials.TypedArrayPrototypeGetLength)(src);
  62223. } else {
  62224. list = [...src];
  62225. length = list.length;
  62226. }
  62227. } else {
  62228. if (src == null) {
  62229. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
  62230. }
  62231. list = (0, _primordials.NativeObject)(src);
  62232. length = (0, _spec.ToLength)(list.length);
  62233. }
  62234. const array2 = new Constructor(length);
  62235. if (opts.length === 0) {
  62236. for (let i6 = 0; i6 < length; ++i6) {
  62237. array2[i6] = list[i6];
  62238. }
  62239. } else {
  62240. const mapFunc = opts[0];
  62241. const thisArg = opts[1];
  62242. for (let i6 = 0; i6 < length; ++i6) {
  62243. array2[i6] = (0, _primordials.ReflectApply)(mapFunc, thisArg, [list[i6], i6]);
  62244. }
  62245. }
  62246. return array2;
  62247. }
  62248. static of(...items) {
  62249. const Constructor = this;
  62250. if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
  62251. throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
  62252. }
  62253. const length = items.length;
  62254. if (Constructor === _Float16Array) {
  62255. const proxy = new _Float16Array(length);
  62256. const float16bitsArray = getFloat16BitsArray(proxy);
  62257. for (let i6 = 0; i6 < length; ++i6) {
  62258. float16bitsArray[i6] = (0, _converter.roundToFloat16Bits)(items[i6]);
  62259. }
  62260. return proxy;
  62261. }
  62262. const array2 = new Constructor(length);
  62263. for (let i6 = 0; i6 < length; ++i6) {
  62264. array2[i6] = items[i6];
  62265. }
  62266. return array2;
  62267. }
  62268. keys() {
  62269. assertFloat16Array(this);
  62270. const float16bitsArray = getFloat16BitsArray(this);
  62271. return (0, _primordials.TypedArrayPrototypeKeys)(float16bitsArray);
  62272. }
  62273. values() {
  62274. assertFloat16Array(this);
  62275. const float16bitsArray = getFloat16BitsArray(this);
  62276. return (0, _arrayIterator.wrap)(function* () {
  62277. for (const val2 of (0, _primordials.TypedArrayPrototypeValues)(float16bitsArray)) {
  62278. yield (0, _converter.convertToNumber)(val2);
  62279. }
  62280. }());
  62281. }
  62282. entries() {
  62283. assertFloat16Array(this);
  62284. const float16bitsArray = getFloat16BitsArray(this);
  62285. return (0, _arrayIterator.wrap)(function* () {
  62286. for (const [i6, val2] of (0, _primordials.TypedArrayPrototypeEntries)(float16bitsArray)) {
  62287. yield [i6, (0, _converter.convertToNumber)(val2)];
  62288. }
  62289. }());
  62290. }
  62291. at(index6) {
  62292. assertFloat16Array(this);
  62293. const float16bitsArray = getFloat16BitsArray(this);
  62294. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62295. const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index6);
  62296. const k5 = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
  62297. if (k5 < 0 || k5 >= length) {
  62298. return;
  62299. }
  62300. return (0, _converter.convertToNumber)(float16bitsArray[k5]);
  62301. }
  62302. with(index6, value) {
  62303. assertFloat16Array(this);
  62304. const float16bitsArray = getFloat16BitsArray(this);
  62305. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62306. const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index6);
  62307. const k5 = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
  62308. const number = +value;
  62309. if (k5 < 0 || k5 >= length) {
  62310. throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
  62311. }
  62312. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  62313. const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
  62314. const array2 = getFloat16BitsArray(cloned);
  62315. array2[k5] = (0, _converter.roundToFloat16Bits)(number);
  62316. return cloned;
  62317. }
  62318. map(callback, ...opts) {
  62319. assertFloat16Array(this);
  62320. const float16bitsArray = getFloat16BitsArray(this);
  62321. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62322. const thisArg = opts[0];
  62323. const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
  62324. if (Constructor === _Float16Array) {
  62325. const proxy = new _Float16Array(length);
  62326. const array3 = getFloat16BitsArray(proxy);
  62327. for (let i6 = 0; i6 < length; ++i6) {
  62328. const val2 = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62329. array3[i6] = (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(callback, thisArg, [val2, i6, this]));
  62330. }
  62331. return proxy;
  62332. }
  62333. const array2 = new Constructor(length);
  62334. assertSpeciesTypedArray(array2, length);
  62335. for (let i6 = 0; i6 < length; ++i6) {
  62336. const val2 = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62337. array2[i6] = (0, _primordials.ReflectApply)(callback, thisArg, [val2, i6, this]);
  62338. }
  62339. return array2;
  62340. }
  62341. filter(callback, ...opts) {
  62342. assertFloat16Array(this);
  62343. const float16bitsArray = getFloat16BitsArray(this);
  62344. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62345. const thisArg = opts[0];
  62346. const kept = [];
  62347. for (let i6 = 0; i6 < length; ++i6) {
  62348. const val2 = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62349. if ((0, _primordials.ReflectApply)(callback, thisArg, [val2, i6, this])) {
  62350. (0, _primordials.ArrayPrototypePush)(kept, val2);
  62351. }
  62352. }
  62353. const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
  62354. const array2 = new Constructor(kept);
  62355. assertSpeciesTypedArray(array2);
  62356. return array2;
  62357. }
  62358. reduce(callback, ...opts) {
  62359. assertFloat16Array(this);
  62360. const float16bitsArray = getFloat16BitsArray(this);
  62361. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62362. if (length === 0 && opts.length === 0) {
  62363. throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
  62364. }
  62365. let accumulator, start;
  62366. if (opts.length === 0) {
  62367. accumulator = (0, _converter.convertToNumber)(float16bitsArray[0]);
  62368. start = 1;
  62369. } else {
  62370. accumulator = opts[0];
  62371. start = 0;
  62372. }
  62373. for (let i6 = start; i6 < length; ++i6) {
  62374. accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this);
  62375. }
  62376. return accumulator;
  62377. }
  62378. reduceRight(callback, ...opts) {
  62379. assertFloat16Array(this);
  62380. const float16bitsArray = getFloat16BitsArray(this);
  62381. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62382. if (length === 0 && opts.length === 0) {
  62383. throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
  62384. }
  62385. let accumulator, start;
  62386. if (opts.length === 0) {
  62387. accumulator = (0, _converter.convertToNumber)(float16bitsArray[length - 1]);
  62388. start = length - 2;
  62389. } else {
  62390. accumulator = opts[0];
  62391. start = length - 1;
  62392. }
  62393. for (let i6 = start; i6 >= 0; --i6) {
  62394. accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this);
  62395. }
  62396. return accumulator;
  62397. }
  62398. forEach(callback, ...opts) {
  62399. assertFloat16Array(this);
  62400. const float16bitsArray = getFloat16BitsArray(this);
  62401. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62402. const thisArg = opts[0];
  62403. for (let i6 = 0; i6 < length; ++i6) {
  62404. (0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this]);
  62405. }
  62406. }
  62407. find(callback, ...opts) {
  62408. assertFloat16Array(this);
  62409. const float16bitsArray = getFloat16BitsArray(this);
  62410. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62411. const thisArg = opts[0];
  62412. for (let i6 = 0; i6 < length; ++i6) {
  62413. const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62414. if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i6, this])) {
  62415. return value;
  62416. }
  62417. }
  62418. }
  62419. findIndex(callback, ...opts) {
  62420. assertFloat16Array(this);
  62421. const float16bitsArray = getFloat16BitsArray(this);
  62422. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62423. const thisArg = opts[0];
  62424. for (let i6 = 0; i6 < length; ++i6) {
  62425. const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62426. if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i6, this])) {
  62427. return i6;
  62428. }
  62429. }
  62430. return -1;
  62431. }
  62432. findLast(callback, ...opts) {
  62433. assertFloat16Array(this);
  62434. const float16bitsArray = getFloat16BitsArray(this);
  62435. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62436. const thisArg = opts[0];
  62437. for (let i6 = length - 1; i6 >= 0; --i6) {
  62438. const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62439. if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i6, this])) {
  62440. return value;
  62441. }
  62442. }
  62443. }
  62444. findLastIndex(callback, ...opts) {
  62445. assertFloat16Array(this);
  62446. const float16bitsArray = getFloat16BitsArray(this);
  62447. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62448. const thisArg = opts[0];
  62449. for (let i6 = length - 1; i6 >= 0; --i6) {
  62450. const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62451. if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i6, this])) {
  62452. return i6;
  62453. }
  62454. }
  62455. return -1;
  62456. }
  62457. every(callback, ...opts) {
  62458. assertFloat16Array(this);
  62459. const float16bitsArray = getFloat16BitsArray(this);
  62460. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62461. const thisArg = opts[0];
  62462. for (let i6 = 0; i6 < length; ++i6) {
  62463. if (!(0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this])) {
  62464. return false;
  62465. }
  62466. }
  62467. return true;
  62468. }
  62469. some(callback, ...opts) {
  62470. assertFloat16Array(this);
  62471. const float16bitsArray = getFloat16BitsArray(this);
  62472. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62473. const thisArg = opts[0];
  62474. for (let i6 = 0; i6 < length; ++i6) {
  62475. if ((0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i6]), i6, this])) {
  62476. return true;
  62477. }
  62478. }
  62479. return false;
  62480. }
  62481. set(input, ...opts) {
  62482. assertFloat16Array(this);
  62483. const float16bitsArray = getFloat16BitsArray(this);
  62484. const targetOffset = (0, _spec.ToIntegerOrInfinity)(opts[0]);
  62485. if (targetOffset < 0) {
  62486. throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
  62487. }
  62488. if (input == null) {
  62489. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
  62490. }
  62491. if ((0, _is.isNativeBigIntTypedArray)(input)) {
  62492. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
  62493. }
  62494. if (isFloat16Array(input)) {
  62495. return (0, _primordials.TypedArrayPrototypeSet)(getFloat16BitsArray(this), getFloat16BitsArray(input), targetOffset);
  62496. }
  62497. if ((0, _is.isNativeTypedArray)(input)) {
  62498. const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
  62499. if ((0, _spec.IsDetachedBuffer)(buffer)) {
  62500. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  62501. }
  62502. }
  62503. const targetLength = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62504. const src = (0, _primordials.NativeObject)(input);
  62505. const srcLength = (0, _spec.ToLength)(src.length);
  62506. if (targetOffset === Infinity || srcLength + targetOffset > targetLength) {
  62507. throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
  62508. }
  62509. for (let i6 = 0; i6 < srcLength; ++i6) {
  62510. float16bitsArray[i6 + targetOffset] = (0, _converter.roundToFloat16Bits)(src[i6]);
  62511. }
  62512. }
  62513. reverse() {
  62514. assertFloat16Array(this);
  62515. const float16bitsArray = getFloat16BitsArray(this);
  62516. (0, _primordials.TypedArrayPrototypeReverse)(float16bitsArray);
  62517. return this;
  62518. }
  62519. toReversed() {
  62520. assertFloat16Array(this);
  62521. const float16bitsArray = getFloat16BitsArray(this);
  62522. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  62523. const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
  62524. const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
  62525. (0, _primordials.TypedArrayPrototypeReverse)(clonedFloat16bitsArray);
  62526. return cloned;
  62527. }
  62528. fill(value, ...opts) {
  62529. assertFloat16Array(this);
  62530. const float16bitsArray = getFloat16BitsArray(this);
  62531. (0, _primordials.TypedArrayPrototypeFill)(float16bitsArray, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
  62532. return this;
  62533. }
  62534. copyWithin(target, start, ...opts) {
  62535. assertFloat16Array(this);
  62536. const float16bitsArray = getFloat16BitsArray(this);
  62537. (0, _primordials.TypedArrayPrototypeCopyWithin)(float16bitsArray, target, start, ...(0, _arrayIterator.safeIfNeeded)(opts));
  62538. return this;
  62539. }
  62540. sort(compareFn) {
  62541. assertFloat16Array(this);
  62542. const float16bitsArray = getFloat16BitsArray(this);
  62543. const sortCompare = compareFn !== void 0 ? compareFn : _spec.defaultCompare;
  62544. (0, _primordials.TypedArrayPrototypeSort)(float16bitsArray, (x5, y2) => {
  62545. return sortCompare((0, _converter.convertToNumber)(x5), (0, _converter.convertToNumber)(y2));
  62546. });
  62547. return this;
  62548. }
  62549. toSorted(compareFn) {
  62550. assertFloat16Array(this);
  62551. const float16bitsArray = getFloat16BitsArray(this);
  62552. if (compareFn !== void 0 && typeof compareFn !== "function") {
  62553. throw new _primordials.NativeTypeError(_messages.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED);
  62554. }
  62555. const sortCompare = compareFn !== void 0 ? compareFn : _spec.defaultCompare;
  62556. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  62557. const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
  62558. const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
  62559. (0, _primordials.TypedArrayPrototypeSort)(clonedFloat16bitsArray, (x5, y2) => {
  62560. return sortCompare((0, _converter.convertToNumber)(x5), (0, _converter.convertToNumber)(y2));
  62561. });
  62562. return cloned;
  62563. }
  62564. slice(start, end) {
  62565. assertFloat16Array(this);
  62566. const float16bitsArray = getFloat16BitsArray(this);
  62567. const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
  62568. if (Constructor === _Float16Array) {
  62569. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  62570. return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16, start, end)));
  62571. }
  62572. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62573. const relativeStart = (0, _spec.ToIntegerOrInfinity)(start);
  62574. const relativeEnd = end === void 0 ? length : (0, _spec.ToIntegerOrInfinity)(end);
  62575. let k5;
  62576. if (relativeStart === -Infinity) {
  62577. k5 = 0;
  62578. } else if (relativeStart < 0) {
  62579. k5 = length + relativeStart > 0 ? length + relativeStart : 0;
  62580. } else {
  62581. k5 = length < relativeStart ? length : relativeStart;
  62582. }
  62583. let final;
  62584. if (relativeEnd === -Infinity) {
  62585. final = 0;
  62586. } else if (relativeEnd < 0) {
  62587. final = length + relativeEnd > 0 ? length + relativeEnd : 0;
  62588. } else {
  62589. final = length < relativeEnd ? length : relativeEnd;
  62590. }
  62591. const count = final - k5 > 0 ? final - k5 : 0;
  62592. const array2 = new Constructor(count);
  62593. assertSpeciesTypedArray(array2, count);
  62594. if (count === 0) {
  62595. return array2;
  62596. }
  62597. const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
  62598. if ((0, _spec.IsDetachedBuffer)(buffer)) {
  62599. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  62600. }
  62601. let n5 = 0;
  62602. while (k5 < final) {
  62603. array2[n5] = (0, _converter.convertToNumber)(float16bitsArray[k5]);
  62604. ++k5;
  62605. ++n5;
  62606. }
  62607. return array2;
  62608. }
  62609. subarray(begin, end) {
  62610. assertFloat16Array(this);
  62611. const float16bitsArray = getFloat16BitsArray(this);
  62612. const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
  62613. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  62614. const uint16Subarray = (0, _primordials.TypedArrayPrototypeSubarray)(uint16, begin, end);
  62615. const array2 = new Constructor((0, _primordials.TypedArrayPrototypeGetBuffer)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetLength)(uint16Subarray));
  62616. assertSpeciesTypedArray(array2);
  62617. return array2;
  62618. }
  62619. indexOf(element, ...opts) {
  62620. assertFloat16Array(this);
  62621. const float16bitsArray = getFloat16BitsArray(this);
  62622. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62623. let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
  62624. if (from === Infinity) {
  62625. return -1;
  62626. }
  62627. if (from < 0) {
  62628. from += length;
  62629. if (from < 0) {
  62630. from = 0;
  62631. }
  62632. }
  62633. for (let i6 = from; i6 < length; ++i6) {
  62634. if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i6) && (0, _converter.convertToNumber)(float16bitsArray[i6]) === element) {
  62635. return i6;
  62636. }
  62637. }
  62638. return -1;
  62639. }
  62640. lastIndexOf(element, ...opts) {
  62641. assertFloat16Array(this);
  62642. const float16bitsArray = getFloat16BitsArray(this);
  62643. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62644. let from = opts.length >= 1 ? (0, _spec.ToIntegerOrInfinity)(opts[0]) : length - 1;
  62645. if (from === -Infinity) {
  62646. return -1;
  62647. }
  62648. if (from >= 0) {
  62649. from = from < length - 1 ? from : length - 1;
  62650. } else {
  62651. from += length;
  62652. }
  62653. for (let i6 = from; i6 >= 0; --i6) {
  62654. if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i6) && (0, _converter.convertToNumber)(float16bitsArray[i6]) === element) {
  62655. return i6;
  62656. }
  62657. }
  62658. return -1;
  62659. }
  62660. includes(element, ...opts) {
  62661. assertFloat16Array(this);
  62662. const float16bitsArray = getFloat16BitsArray(this);
  62663. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  62664. let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
  62665. if (from === Infinity) {
  62666. return false;
  62667. }
  62668. if (from < 0) {
  62669. from += length;
  62670. if (from < 0) {
  62671. from = 0;
  62672. }
  62673. }
  62674. const isNaN2 = (0, _primordials.NumberIsNaN)(element);
  62675. for (let i6 = from; i6 < length; ++i6) {
  62676. const value = (0, _converter.convertToNumber)(float16bitsArray[i6]);
  62677. if (isNaN2 && (0, _primordials.NumberIsNaN)(value)) {
  62678. return true;
  62679. }
  62680. if (value === element) {
  62681. return true;
  62682. }
  62683. }
  62684. return false;
  62685. }
  62686. join(separator) {
  62687. assertFloat16Array(this);
  62688. const float16bitsArray = getFloat16BitsArray(this);
  62689. const array2 = copyToArray(float16bitsArray);
  62690. return (0, _primordials.ArrayPrototypeJoin)(array2, separator);
  62691. }
  62692. toLocaleString(...opts) {
  62693. assertFloat16Array(this);
  62694. const float16bitsArray = getFloat16BitsArray(this);
  62695. const array2 = copyToArray(float16bitsArray);
  62696. return (0, _primordials.ArrayPrototypeToLocaleString)(array2, ...(0, _arrayIterator.safeIfNeeded)(opts));
  62697. }
  62698. get [_primordials.SymbolToStringTag]() {
  62699. if (isFloat16Array(this)) {
  62700. return "Float16Array";
  62701. }
  62702. }
  62703. };
  62704. exports.Float16Array = Float16Array;
  62705. (0, _primordials.ObjectDefineProperty)(Float16Array, "BYTES_PER_ELEMENT", {
  62706. value: BYTES_PER_ELEMENT
  62707. });
  62708. (0, _primordials.ObjectDefineProperty)(Float16Array, _brand.brand, {});
  62709. (0, _primordials.ReflectSetPrototypeOf)(Float16Array, _primordials.TypedArray);
  62710. var Float16ArrayPrototype = Float16Array.prototype;
  62711. (0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, "BYTES_PER_ELEMENT", {
  62712. value: BYTES_PER_ELEMENT
  62713. });
  62714. (0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, _primordials.SymbolIterator, {
  62715. value: Float16ArrayPrototype.values,
  62716. writable: true,
  62717. configurable: true
  62718. });
  62719. (0, _primordials.ReflectSetPrototypeOf)(Float16ArrayPrototype, _primordials.TypedArrayPrototype);
  62720. }
  62721. });
  62722. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/isTypedArray.cjs
  62723. var require_isTypedArray = __commonJS({
  62724. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/isTypedArray.cjs"(exports) {
  62725. "use strict";
  62726. Object.defineProperty(exports, "__esModule", {
  62727. value: true
  62728. });
  62729. exports.isTypedArray = isTypedArray;
  62730. var _Float16Array = require_Float16Array();
  62731. var _is = require_is();
  62732. function isTypedArray(target) {
  62733. return (0, _is.isNativeTypedArray)(target) || (0, _Float16Array.isFloat16Array)(target);
  62734. }
  62735. }
  62736. });
  62737. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/DataView.cjs
  62738. var require_DataView = __commonJS({
  62739. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/DataView.cjs"(exports) {
  62740. "use strict";
  62741. Object.defineProperty(exports, "__esModule", {
  62742. value: true
  62743. });
  62744. exports.getFloat16 = getFloat16;
  62745. exports.setFloat16 = setFloat16;
  62746. var _arrayIterator = require_arrayIterator();
  62747. var _converter = require_converter();
  62748. var _primordials = require_primordials();
  62749. function getFloat16(dataView, byteOffset, ...opts) {
  62750. return (0, _converter.convertToNumber)((0, _primordials.DataViewPrototypeGetUint16)(dataView, byteOffset, ...(0, _arrayIterator.safeIfNeeded)(opts)));
  62751. }
  62752. function setFloat16(dataView, byteOffset, value, ...opts) {
  62753. return (0, _primordials.DataViewPrototypeSetUint16)(dataView, byteOffset, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
  62754. }
  62755. }
  62756. });
  62757. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/f16round.cjs
  62758. var require_f16round = __commonJS({
  62759. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/f16round.cjs"(exports) {
  62760. "use strict";
  62761. Object.defineProperty(exports, "__esModule", {
  62762. value: true
  62763. });
  62764. exports.f16round = f16round;
  62765. var _converter = require_converter();
  62766. function f16round(x5) {
  62767. return (0, _converter.roundToFloat16)(x5);
  62768. }
  62769. }
  62770. });
  62771. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/index.cjs
  62772. var require_lib2 = __commonJS({
  62773. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/index.cjs"(exports) {
  62774. "use strict";
  62775. Object.defineProperty(exports, "__esModule", {
  62776. value: true
  62777. });
  62778. var _Float16Array = require_Float16Array();
  62779. exports.Float16Array = _Float16Array.Float16Array;
  62780. exports.isFloat16Array = _Float16Array.isFloat16Array;
  62781. var _isTypedArray = require_isTypedArray();
  62782. exports.isTypedArray = _isTypedArray.isTypedArray;
  62783. var _DataView = require_DataView();
  62784. exports.getFloat16 = _DataView.getFloat16;
  62785. exports.setFloat16 = _DataView.setFloat16;
  62786. var _f16round = require_f16round();
  62787. exports.f16round = _f16round.f16round;
  62788. exports.hfround = _f16round.f16round;
  62789. }
  62790. });
  62791. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/utils.js
  62792. var require_utils2 = __commonJS({
  62793. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/utils.js"(exports) {
  62794. "use strict";
  62795. Object.defineProperty(exports, "__esModule", { value: true });
  62796. exports.setFloat16 = exports.isFloat16Array = exports.getFloat16 = exports.Float16Array = void 0;
  62797. exports.getUniqueId = getUniqueId;
  62798. exports.sleep = sleep;
  62799. exports.versionEqual = versionEqual;
  62800. exports.versionGreaterThan = versionGreaterThan;
  62801. exports.versionGreaterThanOrEqual = versionGreaterThanOrEqual;
  62802. exports.getAuthenticatedFetch = getAuthenticatedFetch;
  62803. var float16_1 = require_lib2();
  62804. Object.defineProperty(exports, "Float16Array", { enumerable: true, get: function() {
  62805. return float16_1.Float16Array;
  62806. } });
  62807. Object.defineProperty(exports, "getFloat16", { enumerable: true, get: function() {
  62808. return float16_1.getFloat16;
  62809. } });
  62810. Object.defineProperty(exports, "isFloat16Array", { enumerable: true, get: function() {
  62811. return float16_1.isFloat16Array;
  62812. } });
  62813. Object.defineProperty(exports, "setFloat16", { enumerable: true, get: function() {
  62814. return float16_1.setFloat16;
  62815. } });
  62816. var idCounter = {};
  62817. function getUniqueId(prefix2 = "") {
  62818. if (!idCounter[prefix2]) {
  62819. idCounter[prefix2] = 0;
  62820. }
  62821. const id = ++idCounter[prefix2];
  62822. return `_gel_${prefix2}_${id.toString(16)}_`;
  62823. }
  62824. function sleep(durationMillis) {
  62825. return new Promise((accept) => {
  62826. setTimeout(() => accept(), durationMillis);
  62827. });
  62828. }
  62829. function versionEqual(left, right) {
  62830. return left[0] === right[0] && left[1] === right[1];
  62831. }
  62832. function versionGreaterThan(left, right) {
  62833. if (left[0] > right[0]) {
  62834. return true;
  62835. }
  62836. if (left[0] < right[0]) {
  62837. return false;
  62838. }
  62839. return left[1] > right[1];
  62840. }
  62841. function versionGreaterThanOrEqual(left, right) {
  62842. if (left[0] === right[0] && left[1] === right[1]) {
  62843. return true;
  62844. }
  62845. return versionGreaterThan(left, right);
  62846. }
  62847. var _tokens = /* @__PURE__ */ new WeakMap();
  62848. async function getAuthenticatedFetch(config, httpSCRAMAuth, basePath) {
  62849. let token = config.secretKey ?? _tokens.get(config);
  62850. const { address, tlsSecurity, database } = config;
  62851. const protocol = tlsSecurity === "insecure" ? "http" : "https";
  62852. const baseUrl = `${protocol}://${address[0]}:${address[1]}`;
  62853. const databaseUrl = `${baseUrl}/db/${database}/${basePath ?? ""}`;
  62854. if (!token && config.password != null) {
  62855. token = await httpSCRAMAuth(baseUrl, config.user, config.password);
  62856. _tokens.set(config, token);
  62857. }
  62858. return (input, init2) => {
  62859. let path3;
  62860. if (typeof input === "string") {
  62861. path3 = input;
  62862. } else if (input instanceof Request) {
  62863. path3 = input.url;
  62864. } else
  62865. path3 = input.toString();
  62866. const url = new URL(path3, databaseUrl);
  62867. const headers = new Headers(init2?.headers);
  62868. if (config.user !== void 0) {
  62869. headers.append("X-EdgeDB-User", config.user);
  62870. }
  62871. if (token !== void 0) {
  62872. headers.append("Authorization", `Bearer ${token}`);
  62873. }
  62874. return fetch(url, {
  62875. ...init2,
  62876. headers
  62877. });
  62878. };
  62879. }
  62880. }
  62881. });
  62882. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/pgvector.js
  62883. var require_pgvector = __commonJS({
  62884. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/pgvector.js"(exports) {
  62885. "use strict";
  62886. Object.defineProperty(exports, "__esModule", { value: true });
  62887. exports.SparseVector = void 0;
  62888. var SparseVector = class {
  62889. constructor(length, indexesOrMap, values) {
  62890. __publicField(this, "length");
  62891. __publicField(this, "indexes");
  62892. __publicField(this, "values");
  62893. this.length = length;
  62894. if (indexesOrMap instanceof Uint32Array) {
  62895. if (indexesOrMap.length !== values?.length) {
  62896. throw new Error("indexes array must be the same length as the data array");
  62897. }
  62898. if (indexesOrMap.length > length) {
  62899. throw new Error("length of data cannot be larger than length of sparse vector");
  62900. }
  62901. this.values = values;
  62902. this.indexes = indexesOrMap;
  62903. } else {
  62904. const entries = Object.entries(indexesOrMap);
  62905. if (entries.length > length) {
  62906. throw new Error("length of data cannot be larger than length of sparse vector");
  62907. }
  62908. this.indexes = new Uint32Array(entries.length);
  62909. this.values = new Float32Array(entries.length);
  62910. for (let i6 = 0; i6 < entries.length; i6++) {
  62911. const index6 = parseInt(entries[i6][0], 10);
  62912. const val2 = entries[i6][1];
  62913. if (Number.isNaN(index6)) {
  62914. throw new Error(`key ${entries[i6][0]} in data map is not an integer`);
  62915. }
  62916. if (index6 < 0 || index6 >= length) {
  62917. throw new Error(`index ${index6} is out of range of sparse vector length`);
  62918. }
  62919. this.indexes[i6] = index6;
  62920. if (typeof val2 !== "number") {
  62921. throw new Error(`expected value at index ${index6} to be number, got ${typeof val2} ${val2}`);
  62922. }
  62923. if (val2 === 0) {
  62924. throw new Error("elements in sparse vector cannot be 0");
  62925. }
  62926. this.values[i6] = val2;
  62927. }
  62928. }
  62929. return new Proxy(this, {
  62930. get(target, p5) {
  62931. const index6 = typeof p5 === "string" ? parseInt(p5, 10) : NaN;
  62932. if (!Number.isNaN(index6)) {
  62933. if (index6 < 0 || index6 >= target.length)
  62934. return void 0;
  62935. const dataIndex = target.indexes.indexOf(index6);
  62936. return dataIndex === -1 ? 0 : target.values[dataIndex];
  62937. }
  62938. return target[p5];
  62939. }
  62940. });
  62941. }
  62942. *[Symbol.iterator]() {
  62943. let nextIndex = 0;
  62944. for (let i6 = 0; i6 < this.length; i6++) {
  62945. yield this.indexes[nextIndex] === i6 ? this.values[nextIndex++] : 0;
  62946. }
  62947. }
  62948. };
  62949. exports.SparseVector = SparseVector;
  62950. }
  62951. });
  62952. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/pgvector.js
  62953. var require_pgvector2 = __commonJS({
  62954. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/pgvector.js"(exports) {
  62955. "use strict";
  62956. Object.defineProperty(exports, "__esModule", { value: true });
  62957. exports.PgVectorSparseVecCodec = exports.PgVectorHalfVecCodec = exports.PgVectorCodec = exports.PG_VECTOR_MAX_DIM = void 0;
  62958. var ifaces_1 = require_ifaces();
  62959. var errors_1 = require_errors();
  62960. var utils_1 = require_utils2();
  62961. var pgvector_1 = require_pgvector();
  62962. exports.PG_VECTOR_MAX_DIM = (1 << 16) - 1;
  62963. var PgVectorCodec = class extends ifaces_1.ScalarCodec {
  62964. constructor() {
  62965. super(...arguments);
  62966. __publicField(this, "tsType", "Float32Array");
  62967. }
  62968. encode(buf, object, ctx) {
  62969. object = ctx.preEncode(this, object);
  62970. if (!(object instanceof Float32Array || Array.isArray(object))) {
  62971. throw new errors_1.InvalidArgumentError(`a Float32Array or array of numbers was expected, got "${object}"`);
  62972. }
  62973. if (object.length > exports.PG_VECTOR_MAX_DIM) {
  62974. throw new errors_1.InvalidArgumentError("too many elements in array to encode into pgvector");
  62975. }
  62976. buf.writeInt32(4 + object.length * 4).writeUInt16(object.length).writeUInt16(0);
  62977. if (object instanceof Float32Array) {
  62978. for (const el of object) {
  62979. buf.writeFloat32(el);
  62980. }
  62981. } else {
  62982. for (const el of object) {
  62983. if (typeof el !== "number") {
  62984. throw new errors_1.InvalidArgumentError(`elements of vector array expected to be a numbers, got "${el}"`);
  62985. }
  62986. buf.writeFloat32(el);
  62987. }
  62988. }
  62989. }
  62990. decode(buf, ctx) {
  62991. const dim = buf.readUInt16();
  62992. buf.discard(2);
  62993. const vecBuf = buf.readBuffer(dim * 4);
  62994. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  62995. const vec = new Float32Array(dim);
  62996. for (let i6 = 0; i6 < dim; i6++) {
  62997. vec[i6] = data.getFloat32(i6 * 4);
  62998. }
  62999. return ctx.postDecode(this, vec);
  63000. }
  63001. };
  63002. exports.PgVectorCodec = PgVectorCodec;
  63003. var PgVectorHalfVecCodec = class extends ifaces_1.ScalarCodec {
  63004. constructor() {
  63005. super(...arguments);
  63006. __publicField(this, "tsType", "Float16Array");
  63007. __publicField(this, "tsModule", "gel");
  63008. }
  63009. encode(buf, object, ctx) {
  63010. object = ctx.preEncode(this, object);
  63011. if (!((0, utils_1.isFloat16Array)(object) || Array.isArray(object))) {
  63012. throw new errors_1.InvalidArgumentError(`a Float16Array or array of numbers was expected, got "${object}"`);
  63013. }
  63014. if (object.length > exports.PG_VECTOR_MAX_DIM) {
  63015. throw new errors_1.InvalidArgumentError("too many elements in array to encode into pgvector");
  63016. }
  63017. buf.writeInt32(4 + object.length * 2).writeUInt16(object.length).writeUInt16(0);
  63018. const vecBuf = new Uint8Array(object.length * 2);
  63019. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  63020. if ((0, utils_1.isFloat16Array)(object)) {
  63021. for (let i6 = 0; i6 < object.length; i6++) {
  63022. (0, utils_1.setFloat16)(data, i6 * 2, object[i6]);
  63023. }
  63024. } else {
  63025. for (let i6 = 0; i6 < object.length; i6++) {
  63026. if (typeof object[i6] !== "number") {
  63027. throw new errors_1.InvalidArgumentError(`elements of vector array expected to be a numbers, got "${object[i6]}"`);
  63028. }
  63029. (0, utils_1.setFloat16)(data, i6 * 2, object[i6]);
  63030. }
  63031. }
  63032. buf.writeBuffer(vecBuf);
  63033. }
  63034. decode(buf, ctx) {
  63035. const dim = buf.readUInt16();
  63036. buf.discard(2);
  63037. const vecBuf = buf.readBuffer(dim * 2);
  63038. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  63039. const vec = new utils_1.Float16Array(dim);
  63040. for (let i6 = 0; i6 < dim; i6++) {
  63041. vec[i6] = (0, utils_1.getFloat16)(data, i6 * 2);
  63042. }
  63043. return ctx.postDecode(this, vec);
  63044. }
  63045. };
  63046. exports.PgVectorHalfVecCodec = PgVectorHalfVecCodec;
  63047. var PgVectorSparseVecCodec = class extends ifaces_1.ScalarCodec {
  63048. constructor() {
  63049. super(...arguments);
  63050. __publicField(this, "tsType", "SparseVector");
  63051. __publicField(this, "tsModule", "gel");
  63052. }
  63053. encode(buf, object, ctx) {
  63054. let dims;
  63055. let indexes;
  63056. let values;
  63057. if (ctx.hasOverload(this)) {
  63058. [dims, indexes, values] = ctx.preEncode(this, object);
  63059. } else {
  63060. if (!(object instanceof pgvector_1.SparseVector)) {
  63061. throw new errors_1.InvalidArgumentError(`a SparseVector was expected, got "${object}"`);
  63062. }
  63063. dims = object.length;
  63064. indexes = object.indexes;
  63065. values = object.values;
  63066. }
  63067. const indexesLength = indexes.length;
  63068. if (indexesLength > exports.PG_VECTOR_MAX_DIM || indexesLength > dims) {
  63069. throw new errors_1.InvalidArgumentError("too many elements in sparse vector value");
  63070. }
  63071. buf.writeUInt32(4 * (3 + indexesLength * 2)).writeUInt32(dims).writeUInt32(indexesLength).writeUInt32(0);
  63072. const vecBuf = new Uint8Array(indexesLength * 8);
  63073. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  63074. for (let i6 = 0; i6 < indexesLength; i6++) {
  63075. data.setUint32(i6 * 4, indexes[i6]);
  63076. }
  63077. for (let i6 = 0; i6 < indexesLength; i6++) {
  63078. data.setFloat32((indexesLength + i6) * 4, values[i6]);
  63079. }
  63080. buf.writeBuffer(vecBuf);
  63081. }
  63082. decode(buf, ctx) {
  63083. const dim = buf.readUInt32();
  63084. const nnz = buf.readUInt32();
  63085. buf.discard(4);
  63086. const vecBuf = buf.readBuffer(nnz * 8);
  63087. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  63088. const indexes = new Uint32Array(nnz);
  63089. for (let i6 = 0; i6 < nnz; i6++) {
  63090. indexes[i6] = data.getUint32(i6 * 4);
  63091. }
  63092. const vecData = new Float32Array(nnz);
  63093. for (let i6 = 0; i6 < nnz; i6++) {
  63094. vecData[i6] = data.getFloat32((i6 + nnz) * 4);
  63095. }
  63096. if (ctx.hasOverload(this)) {
  63097. return ctx.postDecode(this, [
  63098. dim,
  63099. indexes,
  63100. vecData
  63101. ]);
  63102. }
  63103. return new pgvector_1.SparseVector(dim, indexes, vecData);
  63104. }
  63105. };
  63106. exports.PgVectorSparseVecCodec = PgVectorSparseVecCodec;
  63107. }
  63108. });
  63109. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/postgis.js
  63110. var require_postgis = __commonJS({
  63111. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/postgis.js"(exports) {
  63112. "use strict";
  63113. Object.defineProperty(exports, "__esModule", { value: true });
  63114. exports.Box3D = exports.Box2D = exports.GeometryCollection = exports.MultiSurface = exports.TriangulatedIrregularNetwork = exports.PolyhedralSurface = exports.MultiPolygon = exports.CurvePolygon = exports.Triangle = exports.Polygon = exports.MultiCurve = exports.CompoundCurve = exports.MultiLineString = exports.CircularString = exports.LineString = exports.MultiPoint = exports.Point = exports.Geometry = void 0;
  63115. var Geometry = class {
  63116. };
  63117. exports.Geometry = Geometry;
  63118. function _pointToWKT(p5) {
  63119. return `${p5.x} ${p5.y}${p5.z !== null ? ` ${p5.z}` : ""}${p5.m !== null ? ` ${p5.m}` : ""}`;
  63120. }
  63121. function _flagsToWKT(z2, m6) {
  63122. return (z2 || m6 ? " " : "") + (z2 ? "Z" : "") + (m6 ? "M" : "");
  63123. }
  63124. function _sridWKTPrefix(srid, depth) {
  63125. return srid !== null && depth === 0 ? `SRID=${srid}; ` : "";
  63126. }
  63127. function _indent(indent, depth) {
  63128. if (!indent)
  63129. return "";
  63130. return "\n" + " ".repeat(indent * depth);
  63131. }
  63132. var Point = class extends Geometry {
  63133. constructor(x5, y2, z2 = null, m6 = null, srid = null) {
  63134. super();
  63135. __publicField(this, "x");
  63136. __publicField(this, "y");
  63137. __publicField(this, "z");
  63138. __publicField(this, "m");
  63139. __publicField(this, "srid");
  63140. this.x = x5;
  63141. this.y = y2;
  63142. this.z = z2;
  63143. this.m = m6;
  63144. this.srid = srid;
  63145. }
  63146. get hasZ() {
  63147. return this.z !== null;
  63148. }
  63149. get hasM() {
  63150. return this.m !== null;
  63151. }
  63152. toWKT(_indent2, _truncate = Infinity, depth = 0) {
  63153. return `${_sridWKTPrefix(this.srid, depth)}POINT${_flagsToWKT(this.z !== null, this.m !== null)} ${Number.isNaN(this.x) ? "EMPTY" : "(" + _pointToWKT(this) + ")"}`;
  63154. }
  63155. equals(other) {
  63156. return this.srid === other.srid && (Number.isNaN(this.x) ? this.hasZ === other.hasZ && this.hasM === other.hasM : this.x === other.x && this.y === other.y && this.z === other.z && this.m === other.m);
  63157. }
  63158. };
  63159. exports.Point = Point;
  63160. var MultiPoint = class extends Geometry {
  63161. constructor(geometries, hasZ, hasM, srid) {
  63162. super();
  63163. __publicField(this, "geometries");
  63164. __publicField(this, "hasZ");
  63165. __publicField(this, "hasM");
  63166. __publicField(this, "srid");
  63167. this.geometries = geometries;
  63168. this.hasZ = hasZ;
  63169. this.hasM = hasM;
  63170. this.srid = srid;
  63171. }
  63172. toWKT(indent, truncate = Infinity, depth = 0) {
  63173. let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTIPOINT${_flagsToWKT(this.hasZ, this.hasM)} `;
  63174. if (this.geometries.length === 0) {
  63175. return wkt + "EMPTY";
  63176. }
  63177. wkt += `(`;
  63178. let i6 = 0;
  63179. while (i6 < this.geometries.length && wkt.length < truncate) {
  63180. wkt += _indent(indent, depth + 1) + "(" + _pointToWKT(this.geometries[i6++]) + (i6 < this.geometries.length ? "), " : ")");
  63181. }
  63182. return wkt + _indent(indent, depth) + ")";
  63183. }
  63184. };
  63185. exports.MultiPoint = MultiPoint;
  63186. function _linestringToWKT(points, indent, truncate = Infinity, depth = 0) {
  63187. let wkt = `(`;
  63188. let i6 = 0;
  63189. while (i6 < points.length && wkt.length < truncate) {
  63190. wkt += _indent(indent, depth + 1) + _pointToWKT(points[i6++]) + (i6 < points.length ? ", " : "");
  63191. }
  63192. return wkt + _indent(indent, depth) + ")";
  63193. }
  63194. var LineString = class extends Geometry {
  63195. constructor(points, hasZ, hasM, srid) {
  63196. super();
  63197. __publicField(this, "points");
  63198. __publicField(this, "hasZ");
  63199. __publicField(this, "hasM");
  63200. __publicField(this, "srid");
  63201. this.points = points;
  63202. this.hasZ = hasZ;
  63203. this.hasM = hasM;
  63204. this.srid = srid;
  63205. this._validate();
  63206. }
  63207. _validate() {
  63208. if (this.points.length === 1) {
  63209. throw new Error(`expected zero, or 2 or more points in LineString`);
  63210. }
  63211. }
  63212. toWKT(indent, truncate = Infinity, depth = 0) {
  63213. const wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
  63214. if (this.points.length === 0) {
  63215. return wkt + "EMPTY";
  63216. }
  63217. return wkt + _linestringToWKT(this.points, indent, truncate - wkt.length, depth);
  63218. }
  63219. };
  63220. __publicField(LineString, "_wktName", "LINESTRING");
  63221. exports.LineString = LineString;
  63222. var CircularString = class extends LineString {
  63223. _validate() {
  63224. if (this.points.length !== 0 && (this.points.length <= 1 || this.points.length % 2 !== 1)) {
  63225. throw new Error(`expected zero points, or odd number of points greater than 1 in CircularString`);
  63226. }
  63227. }
  63228. };
  63229. __publicField(CircularString, "_wktName", "CIRCULARSTRING");
  63230. exports.CircularString = CircularString;
  63231. function _multilinestringToWKT(lineStrings, indent, truncate = Infinity, depth = 0) {
  63232. let wkt = `(`;
  63233. let i6 = 0;
  63234. while (i6 < lineStrings.length && wkt.length < truncate) {
  63235. wkt += _indent(indent, depth + 1) + _linestringToWKT(lineStrings[i6++].points, indent, truncate - wkt.length, depth + 1) + (i6 < lineStrings.length ? ", " : "");
  63236. }
  63237. return wkt + _indent(indent, depth) + ")";
  63238. }
  63239. var MultiLineString = class extends Geometry {
  63240. constructor(geometries, hasZ, hasM, srid) {
  63241. super();
  63242. __publicField(this, "geometries");
  63243. __publicField(this, "hasZ");
  63244. __publicField(this, "hasM");
  63245. __publicField(this, "srid");
  63246. this.geometries = geometries;
  63247. this.hasZ = hasZ;
  63248. this.hasM = hasM;
  63249. this.srid = srid;
  63250. }
  63251. toWKT(indent, truncate = Infinity, depth = 0) {
  63252. const wkt = `${_sridWKTPrefix(this.srid, depth)}MULTILINESTRING${_flagsToWKT(this.hasZ, this.hasM)} `;
  63253. if (this.geometries.length === 0) {
  63254. return wkt + "EMPTY";
  63255. }
  63256. return wkt + _multilinestringToWKT(this.geometries, indent, truncate - wkt.length, depth);
  63257. }
  63258. };
  63259. exports.MultiLineString = MultiLineString;
  63260. var CompoundCurve = class extends Geometry {
  63261. constructor(geometries, hasZ, hasM, srid) {
  63262. super();
  63263. __publicField(this, "geometries");
  63264. __publicField(this, "hasZ");
  63265. __publicField(this, "hasM");
  63266. __publicField(this, "srid");
  63267. this.geometries = geometries;
  63268. this.hasZ = hasZ;
  63269. this.hasM = hasM;
  63270. this.srid = srid;
  63271. let lastPoint = null;
  63272. for (const segment of geometries) {
  63273. if (lastPoint && !segment.points[0].equals(lastPoint)) {
  63274. throw new Error("segments in CompoundCurve do not join");
  63275. }
  63276. lastPoint = segment.points[segment.points.length - 1];
  63277. }
  63278. }
  63279. toWKT(indent, truncate = Infinity, depth = 0) {
  63280. let wkt = `${_sridWKTPrefix(this.srid, depth)}COMPOUNDCURVE${_flagsToWKT(this.hasZ, this.hasM)} `;
  63281. if (this.geometries.length === 0) {
  63282. return wkt + "EMPTY";
  63283. }
  63284. wkt += "(";
  63285. let i6 = 0;
  63286. while (i6 < this.geometries.length && wkt.length < truncate) {
  63287. wkt += _indent(indent, depth + 1) + (this.geometries[i6] instanceof CircularString ? "CIRCULARSTRING " : "LINESTRING ") + _linestringToWKT(this.geometries[i6++].points, indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
  63288. }
  63289. return wkt + _indent(indent, depth) + ")";
  63290. }
  63291. };
  63292. exports.CompoundCurve = CompoundCurve;
  63293. var MultiCurve = class extends Geometry {
  63294. constructor(geometries, hasZ, hasM, srid) {
  63295. super();
  63296. __publicField(this, "geometries");
  63297. __publicField(this, "hasZ");
  63298. __publicField(this, "hasM");
  63299. __publicField(this, "srid");
  63300. this.geometries = geometries;
  63301. this.hasZ = hasZ;
  63302. this.hasM = hasM;
  63303. this.srid = srid;
  63304. }
  63305. toWKT(indent, truncate = Infinity, depth = 0) {
  63306. let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTICURVE${_flagsToWKT(this.hasZ, this.hasM)} `;
  63307. if (this.geometries.length === 0) {
  63308. return wkt + "EMPTY";
  63309. }
  63310. wkt += `(`;
  63311. let i6 = 0;
  63312. while (i6 < this.geometries.length && wkt.length < truncate) {
  63313. wkt += _indent(indent, depth + 1) + this.geometries[i6++].toWKT(indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
  63314. }
  63315. return wkt + _indent(indent, depth) + ")";
  63316. }
  63317. };
  63318. exports.MultiCurve = MultiCurve;
  63319. var Polygon = class extends Geometry {
  63320. constructor(rings, hasZ, hasM, srid) {
  63321. super();
  63322. __publicField(this, "rings");
  63323. __publicField(this, "hasZ");
  63324. __publicField(this, "hasM");
  63325. __publicField(this, "srid");
  63326. this.rings = rings;
  63327. this.hasZ = hasZ;
  63328. this.hasM = hasM;
  63329. this.srid = srid;
  63330. this._validate();
  63331. }
  63332. _validate() {
  63333. if (this.rings.some((ring) => ring.points.length < 4 || !ring.points[0].equals(ring.points[ring.points.length - 1]))) {
  63334. throw new Error("expected rings in Polygon to be closed and to have at least 4 points");
  63335. }
  63336. }
  63337. toWKT(indent, truncate = Infinity, depth = 0) {
  63338. const wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
  63339. if (this.rings.length === 0) {
  63340. return wkt + "EMPTY";
  63341. }
  63342. return wkt + _multilinestringToWKT(this.rings, indent, truncate - wkt.length, depth);
  63343. }
  63344. };
  63345. __publicField(Polygon, "_wktName", "POLYGON");
  63346. exports.Polygon = Polygon;
  63347. var Triangle = class extends Polygon {
  63348. _validate() {
  63349. if (this.rings.length > 1) {
  63350. throw new Error("Triangle can only contain a single ring");
  63351. }
  63352. if (this.rings.some((ring) => ring.points.length !== 4 || !ring.points[0].equals(ring.points[ring.points.length - 1]))) {
  63353. throw new Error("expected Triangle to be closed and to have exactly 4 points");
  63354. }
  63355. }
  63356. };
  63357. __publicField(Triangle, "_wktName", "TRIANGLE");
  63358. exports.Triangle = Triangle;
  63359. var CurvePolygon = class extends Geometry {
  63360. constructor(geometries, hasZ, hasM, srid) {
  63361. super();
  63362. __publicField(this, "geometries");
  63363. __publicField(this, "hasZ");
  63364. __publicField(this, "hasM");
  63365. __publicField(this, "srid");
  63366. this.geometries = geometries;
  63367. this.hasZ = hasZ;
  63368. this.hasM = hasM;
  63369. this.srid = srid;
  63370. if (this.geometries.some((ring) => ring instanceof LineString && ring.points.length < 4 || (ring instanceof CompoundCurve ? !ring.geometries[0].points[0].equals(ring.geometries[ring.geometries.length - 1].points[ring.geometries[ring.geometries.length - 1].points.length - 1]) : !ring.points[0].equals(ring.points[ring.points.length - 1])))) {
  63371. throw new Error("expected rings in CurvePolygon to be closed and LinearRings to have at least 4 points");
  63372. }
  63373. }
  63374. toWKT(indent, truncate = Infinity, depth = 0) {
  63375. let wkt = `${_sridWKTPrefix(this.srid, depth)}CURVEPOLYGON${_flagsToWKT(this.hasZ, this.hasM)} `;
  63376. if (this.geometries.length === 0) {
  63377. return wkt + "EMPTY";
  63378. }
  63379. wkt += `(`;
  63380. let i6 = 0;
  63381. while (i6 < this.geometries.length && wkt.length < truncate) {
  63382. wkt += _indent(indent, depth + 1) + this.geometries[i6++].toWKT(indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
  63383. }
  63384. return wkt + _indent(indent, depth) + ")";
  63385. }
  63386. };
  63387. exports.CurvePolygon = CurvePolygon;
  63388. var MultiPolygon = class extends Geometry {
  63389. constructor(geometries, hasZ, hasM, srid) {
  63390. super();
  63391. __publicField(this, "geometries");
  63392. __publicField(this, "hasZ");
  63393. __publicField(this, "hasM");
  63394. __publicField(this, "srid");
  63395. this.geometries = geometries;
  63396. this.hasZ = hasZ;
  63397. this.hasM = hasM;
  63398. this.srid = srid;
  63399. }
  63400. toWKT(indent, truncate = Infinity, depth = 0) {
  63401. let wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
  63402. if (this.geometries.length === 0) {
  63403. return wkt + "EMPTY";
  63404. }
  63405. wkt += `(`;
  63406. let i6 = 0;
  63407. while (i6 < this.geometries.length && wkt.length < truncate) {
  63408. wkt += _indent(indent, depth + 1) + _multilinestringToWKT(this.geometries[i6++].rings, indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
  63409. }
  63410. return wkt + _indent(indent, depth) + ")";
  63411. }
  63412. };
  63413. __publicField(MultiPolygon, "_wktName", "MULTIPOLYGON");
  63414. exports.MultiPolygon = MultiPolygon;
  63415. var PolyhedralSurface = class extends MultiPolygon {
  63416. };
  63417. __publicField(PolyhedralSurface, "_wktName", "POLYHEDRALSURFACE");
  63418. exports.PolyhedralSurface = PolyhedralSurface;
  63419. var TriangulatedIrregularNetwork = class extends MultiPolygon {
  63420. };
  63421. __publicField(TriangulatedIrregularNetwork, "_wktName", "TIN");
  63422. exports.TriangulatedIrregularNetwork = TriangulatedIrregularNetwork;
  63423. var MultiSurface = class extends Geometry {
  63424. constructor(geometries, hasZ, hasM, srid) {
  63425. super();
  63426. __publicField(this, "geometries");
  63427. __publicField(this, "hasZ");
  63428. __publicField(this, "hasM");
  63429. __publicField(this, "srid");
  63430. this.geometries = geometries;
  63431. this.hasZ = hasZ;
  63432. this.hasM = hasM;
  63433. this.srid = srid;
  63434. }
  63435. toWKT(indent, truncate = Infinity, depth = 0) {
  63436. let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTISURFACE${_flagsToWKT(this.hasZ, this.hasM)} `;
  63437. if (this.geometries.length === 0) {
  63438. return wkt + "EMPTY";
  63439. }
  63440. wkt += `(`;
  63441. let i6 = 0;
  63442. while (i6 < this.geometries.length && wkt.length < truncate) {
  63443. wkt += _indent(indent, depth + 1) + this.geometries[i6++].toWKT(indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
  63444. }
  63445. return wkt + _indent(indent, depth) + ")";
  63446. }
  63447. };
  63448. exports.MultiSurface = MultiSurface;
  63449. var GeometryCollection = class extends Geometry {
  63450. constructor(geometries, hasZ, hasM, srid) {
  63451. super();
  63452. __publicField(this, "geometries");
  63453. __publicField(this, "hasZ");
  63454. __publicField(this, "hasM");
  63455. __publicField(this, "srid");
  63456. this.geometries = geometries;
  63457. this.hasZ = hasZ;
  63458. this.hasM = hasM;
  63459. this.srid = srid;
  63460. }
  63461. toWKT(indent, truncate = Infinity, depth = 0) {
  63462. let wkt = `${_sridWKTPrefix(this.srid, depth)}GEOMETRYCOLLECTION${_flagsToWKT(this.hasZ, this.hasM)} `;
  63463. if (this.geometries.length === 0) {
  63464. return wkt + "EMPTY";
  63465. }
  63466. wkt += `(`;
  63467. let i6 = 0;
  63468. while (i6 < this.geometries.length && wkt.length < truncate) {
  63469. wkt += _indent(indent, depth + 1) + this.geometries[i6++].toWKT(indent, truncate - wkt.length, depth + 1) + (i6 < this.geometries.length ? ", " : "");
  63470. }
  63471. return wkt + _indent(indent, depth) + ")";
  63472. }
  63473. };
  63474. exports.GeometryCollection = GeometryCollection;
  63475. var Box2D = class {
  63476. constructor(min, max) {
  63477. __publicField(this, "min");
  63478. __publicField(this, "max");
  63479. this.min = min;
  63480. this.max = max;
  63481. }
  63482. toString() {
  63483. return `BOX(${this.min[0]} ${this.min[1]}, ${this.max[0]} ${this.max[1]})`;
  63484. }
  63485. };
  63486. exports.Box2D = Box2D;
  63487. var Box3D = class {
  63488. constructor(min, max) {
  63489. __publicField(this, "min");
  63490. __publicField(this, "max");
  63491. this.min = min;
  63492. this.max = max;
  63493. }
  63494. toString() {
  63495. return `BOX3D(${this.min[0]} ${this.min[1]} ${this.min[2]}, ${this.max[0]} ${this.max[1]} ${this.max[2]})`;
  63496. }
  63497. };
  63498. exports.Box3D = Box3D;
  63499. }
  63500. });
  63501. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/postgis.js
  63502. var require_postgis2 = __commonJS({
  63503. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/postgis.js"(exports) {
  63504. "use strict";
  63505. Object.defineProperty(exports, "__esModule", { value: true });
  63506. exports.PostgisBox3dCodec = exports.PostgisBox2dCodec = exports.PostgisGeometryCodec = void 0;
  63507. var postgis_1 = require_postgis();
  63508. var errors_1 = require_errors();
  63509. var ifaces_1 = require_ifaces();
  63510. var PostgisGeometryCodec = class extends ifaces_1.ScalarCodec {
  63511. encode(buf, object, ctx) {
  63512. if (ctx.hasOverload(this)) {
  63513. const geomBuf = ctx.preEncode(this, object);
  63514. buf.writeBytes(geomBuf);
  63515. } else {
  63516. if (!(object instanceof postgis_1.Geometry)) {
  63517. throw new errors_1.InvalidArgumentError(`a Geometry object was expected, got "${object}"`);
  63518. }
  63519. const finalise = buf.writeDeferredSize();
  63520. _encodeGeometry(buf, object);
  63521. finalise();
  63522. }
  63523. }
  63524. decode(buf, ctx) {
  63525. if (ctx.hasOverload(this)) {
  63526. return ctx.postDecode(this, buf.consumeAsBuffer());
  63527. }
  63528. return _parseGeometry(buf);
  63529. }
  63530. };
  63531. exports.PostgisGeometryCodec = PostgisGeometryCodec;
  63532. var PostgisBox2dCodec = class extends ifaces_1.ScalarCodec {
  63533. encode(buf, object, ctx) {
  63534. let min;
  63535. let max;
  63536. if (ctx.hasOverload(this)) {
  63537. [min, max] = ctx.preEncode(this, object);
  63538. } else {
  63539. if (!(object instanceof postgis_1.Box2D)) {
  63540. throw new errors_1.InvalidArgumentError(`a Box2D object was expected, got "${object}"`);
  63541. }
  63542. min = object.min;
  63543. max = object.max;
  63544. }
  63545. const finalise = buf.writeDeferredSize();
  63546. _encodeGeometry(buf, new postgis_1.Polygon([
  63547. new postgis_1.LineString([
  63548. new postgis_1.Point(min[0], min[1]),
  63549. new postgis_1.Point(min[0], max[1]),
  63550. new postgis_1.Point(max[0], max[1]),
  63551. new postgis_1.Point(min[0], min[1])
  63552. ], false, false, null)
  63553. ], false, false, null));
  63554. finalise();
  63555. }
  63556. decode(buf, ctx) {
  63557. const poly = _parseGeometry(buf);
  63558. if (poly.constructor !== postgis_1.Polygon || poly.hasZ || poly.rings.length !== 1 || poly.rings[0].points.length !== 5) {
  63559. throw new errors_1.InternalClientError(`failed to decode ext::postgis::box2d type`);
  63560. }
  63561. const points = poly.rings[0].points;
  63562. const min = [points[0].x, points[0].y];
  63563. const max = [points[2].x, points[2].y];
  63564. if (ctx.hasOverload(this)) {
  63565. return ctx.postDecode(this, [min, max]);
  63566. }
  63567. return new postgis_1.Box2D(min, max);
  63568. }
  63569. };
  63570. exports.PostgisBox2dCodec = PostgisBox2dCodec;
  63571. var PostgisBox3dCodec = class extends ifaces_1.ScalarCodec {
  63572. encode(buf, object, ctx) {
  63573. let min;
  63574. let max;
  63575. if (ctx.hasOverload(this)) {
  63576. [min, max] = ctx.preEncode(this, object);
  63577. } else {
  63578. if (!(object instanceof postgis_1.Box3D)) {
  63579. throw new errors_1.InvalidArgumentError(`a Box3D object was expected, got "${object}"`);
  63580. }
  63581. min = object.min;
  63582. max = object.max;
  63583. }
  63584. const finalise = buf.writeDeferredSize();
  63585. _encodeGeometry(buf, new postgis_1.Polygon([
  63586. new postgis_1.LineString([
  63587. new postgis_1.Point(min[0], min[1], min[2]),
  63588. new postgis_1.Point(min[0], max[1], max[2]),
  63589. new postgis_1.Point(max[0], max[1], max[2]),
  63590. new postgis_1.Point(min[0], min[1], min[2])
  63591. ], true, false, null)
  63592. ], true, false, null));
  63593. finalise();
  63594. }
  63595. decode(buf, ctx) {
  63596. const poly = _parseGeometry(buf);
  63597. let min;
  63598. let max;
  63599. if (poly.constructor === postgis_1.Polygon && poly.rings.length === 1 && poly.rings[0].points.length === 5) {
  63600. const points = poly.rings[0].points;
  63601. min = points[0];
  63602. max = points[2];
  63603. } else if (poly.constructor === postgis_1.PolyhedralSurface && poly.geometries.length === 6 && poly.geometries[0].rings.length === 1 && poly.geometries[0].rings[0].points.length === 5) {
  63604. min = poly.geometries[0].rings[0].points[0];
  63605. max = poly.geometries[5].rings[0].points[2];
  63606. } else {
  63607. throw new errors_1.InternalClientError(`failed to decode ext::postgis::box3d type`);
  63608. }
  63609. if (ctx.hasOverload(this)) {
  63610. return ctx.postDecode(this, [
  63611. [min.x, min.y, min.z ?? 0],
  63612. [max.x, max.y, max.z ?? 0]
  63613. ]);
  63614. }
  63615. return new postgis_1.Box3D([min.x, min.y, min.z ?? 0], [max.x, max.y, max.z ?? 0]);
  63616. }
  63617. };
  63618. exports.PostgisBox3dCodec = PostgisBox3dCodec;
  63619. var zFlag = 2147483648;
  63620. var mFlag = 1073741824;
  63621. var sridFlag = 536870912;
  63622. var allFlags = zFlag | mFlag | sridFlag;
  63623. function _parseGeometry(buf, srid = null) {
  63624. const le = buf.readUInt8() === 1;
  63625. let type = buf.readUInt32(le);
  63626. const z2 = (type & zFlag) !== 0;
  63627. const m6 = (type & mFlag) !== 0;
  63628. if ((type & sridFlag) !== 0) {
  63629. srid = buf.readUInt32(le);
  63630. }
  63631. type = type & ~allFlags;
  63632. switch (type) {
  63633. case 1:
  63634. return _parsePoint(buf, le, z2, m6, srid);
  63635. case 2:
  63636. return _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
  63637. case 3:
  63638. return _parsePolygon(buf, postgis_1.Polygon, le, z2, m6, srid);
  63639. case 4:
  63640. return _parseMultiPoint(buf, le, z2, m6, srid);
  63641. case 5:
  63642. return _parseMultiLineString(buf, le, z2, m6, srid);
  63643. case 6:
  63644. return _parseMultiPolygon(buf, postgis_1.MultiPolygon, le, z2, m6, srid);
  63645. case 7:
  63646. return _parseGeometryCollection(buf, le, z2, m6, srid);
  63647. case 8:
  63648. return _parseLineString(buf, postgis_1.CircularString, le, z2, m6, srid);
  63649. case 9:
  63650. return _parseCompoundCurve(buf, le, z2, m6, srid);
  63651. case 10:
  63652. return _parseMultiCurve(buf, postgis_1.CurvePolygon, le, z2, m6, srid);
  63653. case 11:
  63654. return _parseMultiCurve(buf, postgis_1.MultiCurve, le, z2, m6, srid);
  63655. case 12:
  63656. return _parseMultiSurface(buf, le, z2, m6, srid);
  63657. case 15:
  63658. return _parseMultiPolygon(buf, postgis_1.PolyhedralSurface, le, z2, m6, srid);
  63659. case 16:
  63660. return _parseMultiPolygon(buf, postgis_1.TriangulatedIrregularNetwork, le, z2, m6, srid);
  63661. case 17:
  63662. return _parsePolygon(buf, postgis_1.Triangle, le, z2, m6, srid);
  63663. default:
  63664. throw new Error(`unsupported wkb type: ${type}`);
  63665. }
  63666. }
  63667. function _parsePoint(buf, le, z2, m6, srid) {
  63668. return new postgis_1.Point(buf.readFloat64(le), buf.readFloat64(le), z2 ? buf.readFloat64(le) : null, m6 ? buf.readFloat64(le) : null, srid);
  63669. }
  63670. function _parseLineString(buf, cls, le, z2, m6, srid) {
  63671. const pointCount = buf.readUInt32(le);
  63672. const points = new Array(pointCount);
  63673. for (let i6 = 0; i6 < pointCount; i6++) {
  63674. points[i6] = _parsePoint(buf, le, z2, m6, srid);
  63675. }
  63676. return new cls(points, z2, m6, srid);
  63677. }
  63678. function _parsePolygon(buf, cls, le, z2, m6, srid) {
  63679. const ringCount = buf.readUInt32(le);
  63680. const rings = new Array(ringCount);
  63681. for (let i6 = 0; i6 < ringCount; i6++) {
  63682. rings[i6] = _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
  63683. }
  63684. return new cls(rings, z2, m6, srid);
  63685. }
  63686. function _parseMultiPoint(buf, le, z2, m6, srid) {
  63687. const pointCount = buf.readUInt32(le);
  63688. const points = new Array(pointCount);
  63689. for (let i6 = 0; i6 < pointCount; i6++) {
  63690. buf.discard(5);
  63691. points[i6] = _parsePoint(buf, le, z2, m6, srid);
  63692. }
  63693. return new postgis_1.MultiPoint(points, z2, m6, srid);
  63694. }
  63695. function _parseMultiLineString(buf, le, z2, m6, srid) {
  63696. const lineStringCount = buf.readUInt32(le);
  63697. const lineStrings = new Array(lineStringCount);
  63698. for (let i6 = 0; i6 < lineStringCount; i6++) {
  63699. buf.discard(5);
  63700. lineStrings[i6] = _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
  63701. }
  63702. return new postgis_1.MultiLineString(lineStrings, z2, m6, srid);
  63703. }
  63704. function _parseCompoundCurve(buf, le, z2, m6, srid) {
  63705. const curveCount = buf.readUInt32(le);
  63706. const curves = new Array(curveCount);
  63707. for (let i6 = 0; i6 < curveCount; i6++) {
  63708. buf.discard(1);
  63709. const type = buf.readUInt32(le) & ~allFlags;
  63710. switch (type) {
  63711. case 2:
  63712. curves[i6] = _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
  63713. break;
  63714. case 8:
  63715. curves[i6] = _parseLineString(buf, postgis_1.CircularString, le, z2, m6, srid);
  63716. break;
  63717. default:
  63718. throw new Error(`unexpected type ${type} in CompoundCurve`);
  63719. }
  63720. }
  63721. return new postgis_1.CompoundCurve(curves, z2, m6, srid);
  63722. }
  63723. function _parseMultiCurve(buf, cls, le, z2, m6, srid) {
  63724. const curveCount = buf.readUInt32(le);
  63725. const curves = new Array(curveCount);
  63726. for (let i6 = 0; i6 < curveCount; i6++) {
  63727. buf.discard(1);
  63728. const type = buf.readUInt32(le) & ~allFlags;
  63729. switch (type) {
  63730. case 2:
  63731. curves[i6] = _parseLineString(buf, postgis_1.LineString, le, z2, m6, srid);
  63732. break;
  63733. case 8:
  63734. curves[i6] = _parseLineString(buf, postgis_1.CircularString, le, z2, m6, srid);
  63735. break;
  63736. case 9:
  63737. curves[i6] = _parseCompoundCurve(buf, le, z2, m6, srid);
  63738. break;
  63739. default:
  63740. throw new Error(`unexpected type ${type} in MultiCurve/CurvePolygon`);
  63741. }
  63742. }
  63743. return new cls(curves, z2, m6, srid);
  63744. }
  63745. function _parseMultiPolygon(buf, cls, le, z2, m6, srid) {
  63746. const polyCls = cls === postgis_1.TriangulatedIrregularNetwork ? postgis_1.Triangle : postgis_1.Polygon;
  63747. const polyCount = buf.readUInt32(le);
  63748. const polys = new Array(polyCount);
  63749. for (let i6 = 0; i6 < polyCount; i6++) {
  63750. buf.discard(5);
  63751. polys[i6] = _parsePolygon(buf, polyCls, le, z2, m6, srid);
  63752. }
  63753. return new cls(polys, z2, m6, srid);
  63754. }
  63755. function _parseMultiSurface(buf, le, z2, m6, srid) {
  63756. const surfaceCount = buf.readUInt32(le);
  63757. const surfaces = new Array(surfaceCount);
  63758. for (let i6 = 0; i6 < surfaceCount; i6++) {
  63759. buf.discard(1);
  63760. const type = buf.readUInt32(le) & ~allFlags;
  63761. switch (type) {
  63762. case 3:
  63763. surfaces[i6] = _parsePolygon(buf, postgis_1.Polygon, le, z2, m6, srid);
  63764. break;
  63765. case 10:
  63766. surfaces[i6] = _parseMultiCurve(buf, postgis_1.CurvePolygon, le, z2, m6, srid);
  63767. break;
  63768. default:
  63769. throw new Error(`unexpected type ${type} in MultiSurface`);
  63770. }
  63771. }
  63772. return new postgis_1.MultiSurface(surfaces, z2, m6, srid);
  63773. }
  63774. function _parseGeometryCollection(buf, le, z2, m6, srid) {
  63775. const geometryCount = buf.readUInt32(le);
  63776. const geometries = new Array(geometryCount);
  63777. for (let i6 = 0; i6 < geometryCount; i6++) {
  63778. geometries[i6] = _parseGeometry(buf, srid);
  63779. }
  63780. return new postgis_1.GeometryCollection(geometries, z2, m6, srid);
  63781. }
  63782. var geomTypes = /* @__PURE__ */ new Map([
  63783. [postgis_1.Point, 1],
  63784. [postgis_1.LineString, 2],
  63785. [postgis_1.Polygon, 3],
  63786. [postgis_1.MultiPoint, 4],
  63787. [postgis_1.MultiLineString, 5],
  63788. [postgis_1.MultiPolygon, 6],
  63789. [postgis_1.GeometryCollection, 7],
  63790. [postgis_1.CircularString, 8],
  63791. [postgis_1.CompoundCurve, 9],
  63792. [postgis_1.CurvePolygon, 10],
  63793. [postgis_1.MultiCurve, 11],
  63794. [postgis_1.MultiSurface, 12],
  63795. [postgis_1.PolyhedralSurface, 15],
  63796. [postgis_1.TriangulatedIrregularNetwork, 16],
  63797. [postgis_1.Triangle, 17]
  63798. ]);
  63799. function _encodeGeometry(buf, geom) {
  63800. buf.writeUInt8(0);
  63801. const type = geomTypes.get(geom.constructor);
  63802. if (!type) {
  63803. throw new Error(`unknown geometry type ${geom}`);
  63804. }
  63805. buf.writeUInt32(type | (geom.hasZ ? zFlag : 0) | (geom.hasM ? mFlag : 0) | (geom.srid !== null ? sridFlag : 0));
  63806. if (geom.srid !== null) {
  63807. buf.writeUInt32(geom.srid);
  63808. }
  63809. if (geom instanceof postgis_1.Point) {
  63810. _encodePoint(buf, geom);
  63811. return;
  63812. }
  63813. if (geom instanceof postgis_1.LineString) {
  63814. _encodeLineString(buf, geom);
  63815. return;
  63816. }
  63817. if (geom instanceof postgis_1.Polygon) {
  63818. buf.writeUInt32(geom.rings.length);
  63819. for (const ring of geom.rings) {
  63820. _encodeLineString(buf, ring);
  63821. }
  63822. return;
  63823. }
  63824. buf.writeUInt32(geom.geometries.length);
  63825. for (const point of geom.geometries) {
  63826. _encodeGeometry(buf, point);
  63827. }
  63828. }
  63829. function _encodePoint(buf, point) {
  63830. buf.writeFloat64(point.x);
  63831. buf.writeFloat64(point.y);
  63832. if (point.z !== null)
  63833. buf.writeFloat64(point.z);
  63834. if (point.m !== null)
  63835. buf.writeFloat64(point.m);
  63836. }
  63837. function _encodeLineString(buf, linestring) {
  63838. buf.writeUInt32(linestring.points.length);
  63839. for (const point of linestring.points) {
  63840. _encodePoint(buf, point);
  63841. }
  63842. }
  63843. }
  63844. });
  63845. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/codecs.js
  63846. var require_codecs = __commonJS({
  63847. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/codecs.js"(exports) {
  63848. "use strict";
  63849. Object.defineProperty(exports, "__esModule", { value: true });
  63850. exports.INVALID_CODEC = exports.NULL_CODEC = exports.SCALAR_CODECS = exports.NullCodec = void 0;
  63851. var buffer_1 = require_buffer();
  63852. var boolean_1 = require_boolean();
  63853. var ifaces_1 = require_ifaces();
  63854. var numbers_1 = require_numbers();
  63855. var numerics_1 = require_numerics();
  63856. var text_1 = require_text();
  63857. var uuid_1 = require_uuid();
  63858. var bytes_1 = require_bytes();
  63859. var json_1 = require_json();
  63860. var datetime_1 = require_datetime2();
  63861. var memory_1 = require_memory2();
  63862. var pgvector_1 = require_pgvector2();
  63863. var postgis_1 = require_postgis2();
  63864. var errors_1 = require_errors();
  63865. var consts_1 = require_consts();
  63866. var NullCodec = class extends ifaces_1.Codec {
  63867. encode(_buf, _object) {
  63868. throw new errors_1.InternalClientError("null codec cannot used to encode data");
  63869. }
  63870. decode(_buf, _ctx) {
  63871. throw new errors_1.InternalClientError("null codec cannot used to decode data");
  63872. }
  63873. getSubcodecs() {
  63874. return [];
  63875. }
  63876. getKind() {
  63877. return "scalar";
  63878. }
  63879. };
  63880. __publicField(NullCodec, "BUFFER", new buffer_1.WriteBuffer().writeInt32(0).unwrap());
  63881. exports.NullCodec = NullCodec;
  63882. exports.SCALAR_CODECS = /* @__PURE__ */ new Map();
  63883. exports.NULL_CODEC = new NullCodec(consts_1.NULL_CODEC_ID);
  63884. exports.INVALID_CODEC = new NullCodec(consts_1.INVALID_CODEC_ID);
  63885. function registerScalarCodecs(codecs) {
  63886. for (const [typename, type] of Object.entries(codecs)) {
  63887. const id = consts_1.KNOWN_TYPENAMES.get(typename);
  63888. if (id == null) {
  63889. throw new errors_1.InternalClientError("unknown type name");
  63890. }
  63891. exports.SCALAR_CODECS.set(id, new type(id, typename));
  63892. }
  63893. }
  63894. registerScalarCodecs({
  63895. "std::int16": numbers_1.Int16Codec,
  63896. "std::int32": numbers_1.Int32Codec,
  63897. "std::int64": numbers_1.Int64Codec,
  63898. "std::float32": numbers_1.Float32Codec,
  63899. "std::float64": numbers_1.Float64Codec,
  63900. "std::bigint": numerics_1.BigIntCodec,
  63901. "std::decimal": numerics_1.DecimalStringCodec,
  63902. "std::bool": boolean_1.BoolCodec,
  63903. "std::json": json_1.JSONCodec,
  63904. "std::str": text_1.StrCodec,
  63905. "std::bytes": bytes_1.BytesCodec,
  63906. "std::uuid": uuid_1.UUIDCodec,
  63907. "cal::local_date": datetime_1.LocalDateCodec,
  63908. "cal::local_time": datetime_1.LocalTimeCodec,
  63909. "cal::local_datetime": datetime_1.LocalDateTimeCodec,
  63910. "std::datetime": datetime_1.DateTimeCodec,
  63911. "std::duration": datetime_1.DurationCodec,
  63912. "cal::relative_duration": datetime_1.RelativeDurationCodec,
  63913. "cal::date_duration": datetime_1.DateDurationCodec,
  63914. "cfg::memory": memory_1.ConfigMemoryCodec,
  63915. "std::pg::json": json_1.PgTextJSONCodec,
  63916. "std::pg::timestamptz": datetime_1.DateTimeCodec,
  63917. "std::pg::timestamp": datetime_1.LocalDateTimeCodec,
  63918. "std::pg::date": datetime_1.LocalDateCodec,
  63919. "std::pg::interval": datetime_1.RelativeDurationCodec,
  63920. "ext::pgvector::vector": pgvector_1.PgVectorCodec,
  63921. "ext::pgvector::halfvec": pgvector_1.PgVectorHalfVecCodec,
  63922. "ext::pgvector::sparsevec": pgvector_1.PgVectorSparseVecCodec,
  63923. "ext::postgis::geometry": postgis_1.PostgisGeometryCodec,
  63924. "ext::postgis::geography": postgis_1.PostgisGeometryCodec,
  63925. "ext::postgis::box2d": postgis_1.PostgisBox2dCodec,
  63926. "ext::postgis::box3d": postgis_1.PostgisBox3dCodec
  63927. });
  63928. }
  63929. });
  63930. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/tuple.js
  63931. var require_tuple = __commonJS({
  63932. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/tuple.js"(exports) {
  63933. "use strict";
  63934. Object.defineProperty(exports, "__esModule", { value: true });
  63935. exports.EMPTY_TUPLE_CODEC = exports.EMPTY_TUPLE_CODEC_ID = exports.EmptyTupleCodec = exports.TupleCodec = void 0;
  63936. var consts_1 = require_consts();
  63937. var ifaces_1 = require_ifaces();
  63938. var buffer_1 = require_buffer();
  63939. var errors_1 = require_errors();
  63940. var TupleCodec = class extends ifaces_1.Codec {
  63941. constructor(tid, typeName, codecs) {
  63942. super(tid);
  63943. __publicField(this, "subCodecs");
  63944. __publicField(this, "typeName");
  63945. this.subCodecs = codecs;
  63946. this.typeName = typeName;
  63947. }
  63948. encode(buf, object, ctx) {
  63949. if (!Array.isArray(object)) {
  63950. throw new errors_1.InvalidArgumentError(`an array was expected, got "${object}"`);
  63951. }
  63952. const codecs = this.subCodecs;
  63953. const codecsLen = codecs.length;
  63954. if (object.length !== codecsLen) {
  63955. throw new errors_1.InvalidArgumentError(`expected ${codecsLen} tuple item${codecsLen === 1 ? "" : "s"}, got ${object.length}`);
  63956. }
  63957. if (!codecsLen) {
  63958. buf.writeBuffer(EmptyTupleCodec.BUFFER);
  63959. }
  63960. const elemData = new buffer_1.WriteBuffer();
  63961. for (let i6 = 0; i6 < codecsLen; i6++) {
  63962. const elem = object[i6];
  63963. elemData.writeInt32(0);
  63964. if (elem == null) {
  63965. throw new errors_1.MissingArgumentError(`element at index ${i6} in tuple cannot be 'null'`);
  63966. } else {
  63967. try {
  63968. codecs[i6].encode(elemData, elem, ctx);
  63969. } catch (e6) {
  63970. if (e6 instanceof errors_1.QueryArgumentError) {
  63971. throw new errors_1.InvalidArgumentError(`invalid element at index ${i6} in tuple: ${e6.message}`);
  63972. } else {
  63973. throw e6;
  63974. }
  63975. }
  63976. }
  63977. }
  63978. const elemBuf = elemData.unwrap();
  63979. buf.writeInt32(4 + elemBuf.length);
  63980. buf.writeInt32(codecsLen);
  63981. buf.writeBuffer(elemBuf);
  63982. }
  63983. decode(buf, ctx) {
  63984. const els = buf.readUInt32();
  63985. const subCodecs = this.subCodecs;
  63986. if (els !== subCodecs.length) {
  63987. throw new errors_1.ProtocolError(`cannot decode Tuple: expected ${subCodecs.length} elements, got ${els}`);
  63988. }
  63989. const elemBuf = buffer_1.ReadBuffer.alloc();
  63990. const result = new Array(els);
  63991. for (let i6 = 0; i6 < els; i6++) {
  63992. buf.discard(4);
  63993. const elemLen = buf.readInt32();
  63994. if (elemLen === -1) {
  63995. result[i6] = null;
  63996. } else {
  63997. buf.sliceInto(elemBuf, elemLen);
  63998. result[i6] = subCodecs[i6].decode(elemBuf, ctx);
  63999. elemBuf.finish();
  64000. }
  64001. }
  64002. return result;
  64003. }
  64004. getSubcodecs() {
  64005. return Array.from(this.subCodecs);
  64006. }
  64007. getKind() {
  64008. return "tuple";
  64009. }
  64010. };
  64011. exports.TupleCodec = TupleCodec;
  64012. var EmptyTupleCodec = class extends ifaces_1.Codec {
  64013. encode(buf, object, _ctx) {
  64014. if (!Array.isArray(object)) {
  64015. throw new errors_1.InvalidArgumentError("cannot encode empty Tuple: expected an array");
  64016. }
  64017. if (object.length) {
  64018. throw new errors_1.InvalidArgumentError(`cannot encode empty Tuple: expected 0 elements got ${object.length}`);
  64019. }
  64020. buf.writeInt32(4);
  64021. buf.writeInt32(0);
  64022. }
  64023. decode(buf) {
  64024. const els = buf.readInt32();
  64025. if (els !== 0) {
  64026. throw new errors_1.ProtocolError(`cannot decode empty Tuple: expected 0 elements, received ${els}`);
  64027. }
  64028. return [];
  64029. }
  64030. getSubcodecs() {
  64031. return [];
  64032. }
  64033. getKind() {
  64034. return "tuple";
  64035. }
  64036. };
  64037. __publicField(EmptyTupleCodec, "BUFFER", new buffer_1.WriteBuffer().writeInt32(4).writeInt32(0).unwrap());
  64038. exports.EmptyTupleCodec = EmptyTupleCodec;
  64039. exports.EMPTY_TUPLE_CODEC_ID = consts_1.KNOWN_TYPENAMES.get("empty-tuple");
  64040. exports.EMPTY_TUPLE_CODEC = new EmptyTupleCodec(exports.EMPTY_TUPLE_CODEC_ID);
  64041. }
  64042. });
  64043. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/range.js
  64044. var require_range2 = __commonJS({
  64045. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/range.js"(exports) {
  64046. "use strict";
  64047. Object.defineProperty(exports, "__esModule", { value: true });
  64048. exports.MultiRange = exports.Range = void 0;
  64049. var Range = class _Range {
  64050. constructor(_lower, _upper, _incLower = _lower != null, _incUpper = false) {
  64051. __publicField(this, "_lower");
  64052. __publicField(this, "_upper");
  64053. __publicField(this, "_incLower");
  64054. __publicField(this, "_incUpper");
  64055. __publicField(this, "_isEmpty", false);
  64056. this._lower = _lower;
  64057. this._upper = _upper;
  64058. this._incLower = _incLower;
  64059. this._incUpper = _incUpper;
  64060. }
  64061. get lower() {
  64062. return this._lower;
  64063. }
  64064. get upper() {
  64065. return this._upper;
  64066. }
  64067. get incLower() {
  64068. return this._incLower;
  64069. }
  64070. get incUpper() {
  64071. return this._incUpper;
  64072. }
  64073. get isEmpty() {
  64074. return this._isEmpty;
  64075. }
  64076. static empty() {
  64077. const range = new _Range(null, null);
  64078. range._isEmpty = true;
  64079. return range;
  64080. }
  64081. toJSON() {
  64082. return this.isEmpty ? { empty: true } : {
  64083. lower: this._lower,
  64084. upper: this._upper,
  64085. inc_lower: this._incLower,
  64086. inc_upper: this._incUpper
  64087. };
  64088. }
  64089. };
  64090. exports.Range = Range;
  64091. var MultiRange = class {
  64092. constructor(ranges = []) {
  64093. __publicField(this, "_ranges");
  64094. this._ranges = [...ranges];
  64095. }
  64096. get length() {
  64097. return this._ranges.length;
  64098. }
  64099. *[Symbol.iterator]() {
  64100. for (const range of this._ranges) {
  64101. yield range;
  64102. }
  64103. }
  64104. toJSON() {
  64105. return [...this._ranges];
  64106. }
  64107. };
  64108. exports.MultiRange = MultiRange;
  64109. }
  64110. });
  64111. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/range.js
  64112. var require_range3 = __commonJS({
  64113. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/range.js"(exports) {
  64114. "use strict";
  64115. Object.defineProperty(exports, "__esModule", { value: true });
  64116. exports.MultiRangeCodec = exports.RangeCodec = void 0;
  64117. var ifaces_1 = require_ifaces();
  64118. var buffer_1 = require_buffer();
  64119. var range_1 = require_range2();
  64120. var errors_1 = require_errors();
  64121. var RangeFlags;
  64122. (function(RangeFlags2) {
  64123. RangeFlags2[RangeFlags2["EMPTY"] = 1] = "EMPTY";
  64124. RangeFlags2[RangeFlags2["INC_LOWER"] = 2] = "INC_LOWER";
  64125. RangeFlags2[RangeFlags2["INC_UPPER"] = 4] = "INC_UPPER";
  64126. RangeFlags2[RangeFlags2["EMPTY_LOWER"] = 8] = "EMPTY_LOWER";
  64127. RangeFlags2[RangeFlags2["EMPTY_UPPER"] = 16] = "EMPTY_UPPER";
  64128. })(RangeFlags || (RangeFlags = {}));
  64129. var MAXINT32 = 2147483647;
  64130. function encodeRange(buf, obj, subCodec, ctx) {
  64131. if (!(obj instanceof range_1.Range)) {
  64132. throw new errors_1.InvalidArgumentError("a Range was expected");
  64133. }
  64134. const elemData = new buffer_1.WriteBuffer();
  64135. if (obj.lower !== null) {
  64136. subCodec.encode(elemData, obj.lower, ctx);
  64137. }
  64138. if (obj.upper !== null) {
  64139. subCodec.encode(elemData, obj.upper, ctx);
  64140. }
  64141. const elemBuf = elemData.unwrap();
  64142. buf.writeInt32(1 + elemBuf.length);
  64143. buf.writeUInt8(obj.isEmpty ? RangeFlags.EMPTY : (obj.incLower ? RangeFlags.INC_LOWER : 0) | (obj.incUpper ? RangeFlags.INC_UPPER : 0) | (obj.lower === null ? RangeFlags.EMPTY_LOWER : 0) | (obj.upper === null ? RangeFlags.EMPTY_UPPER : 0));
  64144. buf.writeBuffer(elemBuf);
  64145. }
  64146. function decodeRange(buf, subCodec, ctx) {
  64147. const flags = buf.readUInt8();
  64148. if (flags & RangeFlags.EMPTY) {
  64149. return range_1.Range.empty();
  64150. }
  64151. const elemBuf = buffer_1.ReadBuffer.alloc();
  64152. let lower2 = null;
  64153. let upper = null;
  64154. if (!(flags & RangeFlags.EMPTY_LOWER)) {
  64155. buf.sliceInto(elemBuf, buf.readInt32());
  64156. lower2 = subCodec.decode(elemBuf, ctx);
  64157. elemBuf.finish();
  64158. }
  64159. if (!(flags & RangeFlags.EMPTY_UPPER)) {
  64160. buf.sliceInto(elemBuf, buf.readInt32());
  64161. upper = subCodec.decode(elemBuf, ctx);
  64162. elemBuf.finish();
  64163. }
  64164. return new range_1.Range(lower2, upper, !!(flags & RangeFlags.INC_LOWER), !!(flags & RangeFlags.INC_UPPER));
  64165. }
  64166. var RangeCodec = class extends ifaces_1.Codec {
  64167. constructor(tid, typeName, subCodec) {
  64168. super(tid);
  64169. __publicField(this, "tsType", "Range");
  64170. __publicField(this, "tsModule", "gel");
  64171. __publicField(this, "subCodec");
  64172. __publicField(this, "typeName");
  64173. this.subCodec = subCodec;
  64174. this.typeName = typeName;
  64175. }
  64176. encode(buf, obj, ctx) {
  64177. return encodeRange(buf, obj, this.subCodec, ctx);
  64178. }
  64179. decode(buf, ctx) {
  64180. return decodeRange(buf, this.subCodec, ctx);
  64181. }
  64182. getSubcodecs() {
  64183. return [this.subCodec];
  64184. }
  64185. getKind() {
  64186. return "range";
  64187. }
  64188. };
  64189. exports.RangeCodec = RangeCodec;
  64190. var MultiRangeCodec = class extends ifaces_1.Codec {
  64191. constructor(tid, typeName, subCodec) {
  64192. super(tid);
  64193. __publicField(this, "tsType", "MultiRange");
  64194. __publicField(this, "tsModule", "gel");
  64195. __publicField(this, "subCodec");
  64196. __publicField(this, "typeName");
  64197. this.subCodec = subCodec;
  64198. this.typeName = typeName;
  64199. }
  64200. encode(buf, obj, ctx) {
  64201. if (!(obj instanceof range_1.MultiRange)) {
  64202. throw new TypeError(`a MultiRange expected (got type ${obj.constructor.name})`);
  64203. }
  64204. const objLen = obj.length;
  64205. if (objLen > MAXINT32) {
  64206. throw new errors_1.InvalidArgumentError("too many elements in array");
  64207. }
  64208. const elemData = new buffer_1.WriteBuffer();
  64209. for (const item of obj) {
  64210. try {
  64211. encodeRange(elemData, item, this.subCodec, ctx);
  64212. } catch (e6) {
  64213. if (e6 instanceof errors_1.InvalidArgumentError) {
  64214. throw new errors_1.InvalidArgumentError(`invalid multirange element: ${e6.message}`);
  64215. } else {
  64216. throw e6;
  64217. }
  64218. }
  64219. }
  64220. const elemBuf = elemData.unwrap();
  64221. const elemDataLen = elemBuf.length;
  64222. if (elemDataLen > MAXINT32 - 4) {
  64223. throw new errors_1.InvalidArgumentError(`size of encoded multirange datum exceeds the maximum allowed ${MAXINT32 - 4} bytes`);
  64224. }
  64225. buf.writeInt32(4 + elemDataLen);
  64226. buf.writeInt32(objLen);
  64227. buf.writeBuffer(elemBuf);
  64228. }
  64229. decode(buf, ctx) {
  64230. const elemCount = buf.readInt32();
  64231. const result = new Array(elemCount);
  64232. const elemBuf = buffer_1.ReadBuffer.alloc();
  64233. const subCodec = this.subCodec;
  64234. for (let i6 = 0; i6 < elemCount; i6++) {
  64235. const elemLen = buf.readInt32();
  64236. if (elemLen === -1) {
  64237. throw new errors_1.ProtocolError("unexpected NULL element in multirange value");
  64238. } else {
  64239. buf.sliceInto(elemBuf, elemLen);
  64240. const elem = decodeRange(elemBuf, subCodec, ctx);
  64241. if (elemBuf.length) {
  64242. throw new errors_1.ProtocolError(`unexpected trailing data in buffer after multirange element decoding: ${elemBuf.length}`);
  64243. }
  64244. result[i6] = elem;
  64245. elemBuf.finish();
  64246. }
  64247. }
  64248. return new range_1.MultiRange(result);
  64249. }
  64250. getSubcodecs() {
  64251. return [this.subCodec];
  64252. }
  64253. getKind() {
  64254. return "multirange";
  64255. }
  64256. };
  64257. exports.MultiRangeCodec = MultiRangeCodec;
  64258. }
  64259. });
  64260. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/namedtuple.js
  64261. var require_namedtuple = __commonJS({
  64262. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/namedtuple.js"(exports) {
  64263. "use strict";
  64264. Object.defineProperty(exports, "__esModule", { value: true });
  64265. exports.NamedTupleCodec = void 0;
  64266. var ifaces_1 = require_ifaces();
  64267. var buffer_1 = require_buffer();
  64268. var errors_1 = require_errors();
  64269. var NamedTupleCodec = class extends ifaces_1.Codec {
  64270. constructor(tid, typeName, codecs, names) {
  64271. super(tid);
  64272. __publicField(this, "subCodecs");
  64273. __publicField(this, "names");
  64274. __publicField(this, "typeName");
  64275. this.subCodecs = codecs;
  64276. this.names = names;
  64277. this.typeName = typeName;
  64278. }
  64279. encode(buf, object, ctx) {
  64280. if (typeof object !== "object" || Array.isArray(object)) {
  64281. throw new errors_1.InvalidArgumentError(`an object was expected, got "${object}"`);
  64282. }
  64283. const codecsLen = this.subCodecs.length;
  64284. if (Object.keys(object).length !== codecsLen) {
  64285. throw new errors_1.QueryArgumentError(`expected ${codecsLen} element${codecsLen === 1 ? "" : "s"} in named tuple, got ${Object.keys(object).length}`);
  64286. }
  64287. const elemData = new buffer_1.WriteBuffer();
  64288. for (let i6 = 0; i6 < codecsLen; i6++) {
  64289. const key = this.names[i6];
  64290. const val2 = object[key];
  64291. if (val2 == null) {
  64292. throw new errors_1.MissingArgumentError(`element '${key}' in named tuple cannot be 'null'`);
  64293. } else {
  64294. elemData.writeInt32(0);
  64295. try {
  64296. this.subCodecs[i6].encode(elemData, val2, ctx);
  64297. } catch (e6) {
  64298. if (e6 instanceof errors_1.QueryArgumentError) {
  64299. throw new errors_1.InvalidArgumentError(`invalid element '${key}' in named tuple: ${e6.message}`);
  64300. } else {
  64301. throw e6;
  64302. }
  64303. }
  64304. }
  64305. }
  64306. const elemBuf = elemData.unwrap();
  64307. buf.writeInt32(4 + elemBuf.length);
  64308. buf.writeInt32(codecsLen);
  64309. buf.writeBuffer(elemBuf);
  64310. }
  64311. decode(buf, ctx) {
  64312. const els = buf.readUInt32();
  64313. const subCodecs = this.subCodecs;
  64314. if (els !== subCodecs.length) {
  64315. throw new errors_1.ProtocolError(`cannot decode NamedTuple: expected ${subCodecs.length} elements, got ${els}`);
  64316. }
  64317. const elemBuf = buffer_1.ReadBuffer.alloc();
  64318. const names = this.names;
  64319. const result = {};
  64320. for (let i6 = 0; i6 < els; i6++) {
  64321. buf.discard(4);
  64322. const elemLen = buf.readInt32();
  64323. let val2 = null;
  64324. if (elemLen !== -1) {
  64325. buf.sliceInto(elemBuf, elemLen);
  64326. val2 = subCodecs[i6].decode(elemBuf, ctx);
  64327. elemBuf.finish();
  64328. }
  64329. result[names[i6]] = val2;
  64330. }
  64331. return result;
  64332. }
  64333. getSubcodecs() {
  64334. return Array.from(this.subCodecs);
  64335. }
  64336. getNames() {
  64337. return Array.from(this.names);
  64338. }
  64339. getKind() {
  64340. return "namedtuple";
  64341. }
  64342. };
  64343. exports.NamedTupleCodec = NamedTupleCodec;
  64344. }
  64345. });
  64346. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/array.js
  64347. var require_array = __commonJS({
  64348. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/array.js"(exports) {
  64349. "use strict";
  64350. Object.defineProperty(exports, "__esModule", { value: true });
  64351. exports.ArrayCodec = void 0;
  64352. var ifaces_1 = require_ifaces();
  64353. var buffer_1 = require_buffer();
  64354. var tuple_1 = require_tuple();
  64355. var range_1 = require_range3();
  64356. var errors_1 = require_errors();
  64357. var namedtuple_1 = require_namedtuple();
  64358. var ArrayCodec = class extends ifaces_1.Codec {
  64359. constructor(tid, typeName, subCodec, len) {
  64360. super(tid);
  64361. __publicField(this, "subCodec");
  64362. __publicField(this, "len");
  64363. __publicField(this, "typeName");
  64364. this.subCodec = subCodec;
  64365. this.len = len;
  64366. this.typeName = typeName;
  64367. }
  64368. encode(buf, obj, ctx) {
  64369. if (!(this.subCodec instanceof ifaces_1.ScalarCodec || this.subCodec instanceof tuple_1.TupleCodec || this.subCodec instanceof namedtuple_1.NamedTupleCodec || this.subCodec instanceof range_1.RangeCodec || this.subCodec instanceof range_1.MultiRangeCodec)) {
  64370. throw new errors_1.InvalidArgumentError("only arrays of scalars or tuples are supported");
  64371. }
  64372. if (!Array.isArray(obj) && !isTypedArray(obj)) {
  64373. throw new errors_1.InvalidArgumentError(`an array was expected (got type ${obj.constructor.name})`);
  64374. }
  64375. const subCodec = this.subCodec;
  64376. const elemData = new buffer_1.WriteBuffer();
  64377. const objLen = obj.length;
  64378. if (objLen > 2147483647) {
  64379. throw new errors_1.InvalidArgumentError("too many elements in array");
  64380. }
  64381. for (let i6 = 0; i6 < objLen; i6++) {
  64382. const item = obj[i6];
  64383. if (item == null) {
  64384. elemData.writeInt32(-1);
  64385. } else {
  64386. subCodec.encode(elemData, item, ctx);
  64387. }
  64388. }
  64389. const elemBuf = elemData.unwrap();
  64390. buf.writeInt32(12 + 8 + elemBuf.length);
  64391. buf.writeInt32(1);
  64392. buf.writeInt32(0);
  64393. buf.writeInt32(0);
  64394. buf.writeInt32(objLen);
  64395. buf.writeInt32(1);
  64396. buf.writeBuffer(elemBuf);
  64397. }
  64398. decode(buf, ctx) {
  64399. const ndims = buf.readInt32();
  64400. buf.discard(4);
  64401. buf.discard(4);
  64402. if (ndims === 0) {
  64403. return [];
  64404. }
  64405. if (ndims !== 1) {
  64406. throw new errors_1.ProtocolError("only 1-dimensional arrays are supported");
  64407. }
  64408. const len = buf.readUInt32();
  64409. if (this.len !== -1 && len !== this.len) {
  64410. throw new errors_1.ProtocolError(`invalid array size: received ${len}, expected ${this.len}`);
  64411. }
  64412. buf.discard(4);
  64413. const result = new Array(len);
  64414. const elemBuf = buffer_1.ReadBuffer.alloc();
  64415. const subCodec = this.subCodec;
  64416. for (let i6 = 0; i6 < len; i6++) {
  64417. const elemLen = buf.readInt32();
  64418. if (elemLen === -1) {
  64419. result[i6] = null;
  64420. } else {
  64421. buf.sliceInto(elemBuf, elemLen);
  64422. result[i6] = subCodec.decode(elemBuf, ctx);
  64423. elemBuf.finish();
  64424. }
  64425. }
  64426. return result;
  64427. }
  64428. getSubcodecs() {
  64429. return [this.subCodec];
  64430. }
  64431. getKind() {
  64432. return "array";
  64433. }
  64434. };
  64435. exports.ArrayCodec = ArrayCodec;
  64436. function isTypedArray(obj) {
  64437. return !!(obj.buffer instanceof ArrayBuffer && obj.BYTES_PER_ELEMENT);
  64438. }
  64439. }
  64440. });
  64441. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/enum.js
  64442. var require_enum = __commonJS({
  64443. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/enum.js"(exports) {
  64444. "use strict";
  64445. Object.defineProperty(exports, "__esModule", { value: true });
  64446. exports.EnumCodec = void 0;
  64447. var text_1 = require_text();
  64448. var EnumCodec = class extends text_1.StrCodec {
  64449. constructor(tid, typeName, values) {
  64450. super(tid, typeName);
  64451. __publicField(this, "values");
  64452. this.values = values;
  64453. }
  64454. };
  64455. exports.EnumCodec = EnumCodec;
  64456. }
  64457. });
  64458. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/ifaces.js
  64459. var require_ifaces2 = __commonJS({
  64460. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/ifaces.js"(exports) {
  64461. "use strict";
  64462. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  64463. if (k22 === void 0) k22 = k5;
  64464. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  64465. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  64466. desc = { enumerable: true, get: function() {
  64467. return m6[k5];
  64468. } };
  64469. }
  64470. Object.defineProperty(o5, k22, desc);
  64471. } : function(o5, m6, k5, k22) {
  64472. if (k22 === void 0) k22 = k5;
  64473. o5[k22] = m6[k5];
  64474. });
  64475. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  64476. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  64477. } : function(o5, v6) {
  64478. o5["default"] = v6;
  64479. });
  64480. var __importStar = exports && exports.__importStar || function(mod) {
  64481. if (mod && mod.__esModule) return mod;
  64482. var result = {};
  64483. if (mod != null) {
  64484. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  64485. }
  64486. __setModuleDefault(result, mod);
  64487. return result;
  64488. };
  64489. Object.defineProperty(exports, "__esModule", { value: true });
  64490. exports.Language = exports.Cardinality = exports.OutputFormat = void 0;
  64491. var chars = __importStar(require_chars());
  64492. var OutputFormat;
  64493. (function(OutputFormat2) {
  64494. OutputFormat2[OutputFormat2["BINARY"] = chars.$b] = "BINARY";
  64495. OutputFormat2[OutputFormat2["JSON"] = chars.$j] = "JSON";
  64496. OutputFormat2[OutputFormat2["NONE"] = chars.$n] = "NONE";
  64497. })(OutputFormat || (exports.OutputFormat = OutputFormat = {}));
  64498. var Cardinality;
  64499. (function(Cardinality2) {
  64500. Cardinality2[Cardinality2["NO_RESULT"] = chars.$n] = "NO_RESULT";
  64501. Cardinality2[Cardinality2["AT_MOST_ONE"] = chars.$o] = "AT_MOST_ONE";
  64502. Cardinality2[Cardinality2["ONE"] = chars.$A] = "ONE";
  64503. Cardinality2[Cardinality2["MANY"] = chars.$m] = "MANY";
  64504. Cardinality2[Cardinality2["AT_LEAST_ONE"] = chars.$M] = "AT_LEAST_ONE";
  64505. })(Cardinality || (exports.Cardinality = Cardinality = {}));
  64506. var Language;
  64507. (function(Language2) {
  64508. Language2[Language2["EDGEQL"] = chars.$E] = "EDGEQL";
  64509. Language2[Language2["SQL"] = chars.$S] = "SQL";
  64510. })(Language || (exports.Language = Language = {}));
  64511. }
  64512. });
  64513. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/object.js
  64514. var require_object = __commonJS({
  64515. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/object.js"(exports) {
  64516. "use strict";
  64517. Object.defineProperty(exports, "__esModule", { value: true });
  64518. exports.ObjectCodec = void 0;
  64519. var ifaces_1 = require_ifaces2();
  64520. var ifaces_2 = require_ifaces();
  64521. var buffer_1 = require_buffer();
  64522. var errors_1 = require_errors();
  64523. var EDGE_POINTER_IS_IMPLICIT = 1 << 0;
  64524. var EDGE_POINTER_IS_LINKPROP = 1 << 1;
  64525. var ObjectCodec = class extends ifaces_2.Codec {
  64526. constructor(tid, codecs, names, flags, cards) {
  64527. super(tid);
  64528. __publicField(this, "codecs");
  64529. __publicField(this, "fields");
  64530. __publicField(this, "namesSet");
  64531. __publicField(this, "cardinalities");
  64532. this.codecs = codecs;
  64533. this.fields = new Array(names.length);
  64534. this.namesSet = /* @__PURE__ */ new Set();
  64535. this.cardinalities = cards;
  64536. for (let i6 = 0; i6 < names.length; i6++) {
  64537. const isLinkprop = !!(flags[i6] & EDGE_POINTER_IS_LINKPROP);
  64538. const name = isLinkprop ? `@${names[i6]}` : names[i6];
  64539. this.fields[i6] = {
  64540. name,
  64541. implicit: !!(flags[i6] & EDGE_POINTER_IS_IMPLICIT),
  64542. linkprop: isLinkprop,
  64543. cardinality: cards[i6]
  64544. };
  64545. this.namesSet.add(name);
  64546. }
  64547. }
  64548. encode(_buf, _object) {
  64549. throw new errors_1.InvalidArgumentError("Objects cannot be passed as arguments");
  64550. }
  64551. encodeArgs(args, ctx) {
  64552. if (this.fields[0].name === "0" || this.fields[0].name === "1") {
  64553. return this._encodePositionalArgs(args, ctx);
  64554. }
  64555. return this._encodeNamedArgs(args, ctx);
  64556. }
  64557. _encodePositionalArgs(args, ctx) {
  64558. if (!Array.isArray(args)) {
  64559. throw new errors_1.InvalidArgumentError("an array of arguments was expected");
  64560. }
  64561. const codecs = this.codecs;
  64562. const codecsLen = codecs.length;
  64563. if (args.length !== codecsLen) {
  64564. throw new errors_1.QueryArgumentError(`expected ${codecsLen} argument${codecsLen === 1 ? "" : "s"}, got ${args.length}`);
  64565. }
  64566. const elemData = new buffer_1.WriteBuffer();
  64567. for (let i6 = 0; i6 < codecsLen; i6++) {
  64568. elemData.writeInt32(0);
  64569. const arg = args[i6];
  64570. if (arg == null) {
  64571. const card = this.cardinalities[i6];
  64572. if (card === ifaces_1.Cardinality.ONE || card === ifaces_1.Cardinality.AT_LEAST_ONE) {
  64573. throw new errors_1.MissingArgumentError(`argument ${this.fields[i6].name} is required, but received ${arg}`);
  64574. }
  64575. elemData.writeInt32(-1);
  64576. } else {
  64577. const codec = codecs[i6];
  64578. codec.encode(elemData, arg, ctx);
  64579. }
  64580. }
  64581. const elemBuf = elemData.unwrap();
  64582. const buf = new buffer_1.WriteBuffer();
  64583. buf.writeInt32(4 + elemBuf.length);
  64584. buf.writeInt32(codecsLen);
  64585. buf.writeBuffer(elemBuf);
  64586. return buf.unwrap();
  64587. }
  64588. _encodeNamedArgs(args, ctx) {
  64589. if (args == null) {
  64590. throw new errors_1.MissingArgumentError("One or more named arguments expected, received null");
  64591. }
  64592. const keys = Object.keys(args);
  64593. const fields = this.fields;
  64594. const namesSet = this.namesSet;
  64595. const codecs = this.codecs;
  64596. const codecsLen = codecs.length;
  64597. if (keys.length > codecsLen) {
  64598. const extraKeys = keys.filter((key) => !namesSet.has(key));
  64599. throw new errors_1.UnknownArgumentError(`Unused named argument${extraKeys.length === 1 ? "" : "s"}: "${extraKeys.join('", "')}"`);
  64600. }
  64601. const elemData = new buffer_1.WriteBuffer();
  64602. for (let i6 = 0; i6 < codecsLen; i6++) {
  64603. const key = fields[i6].name;
  64604. const val2 = args[key];
  64605. elemData.writeInt32(0);
  64606. if (val2 == null) {
  64607. const card = this.cardinalities[i6];
  64608. if (card === ifaces_1.Cardinality.ONE || card === ifaces_1.Cardinality.AT_LEAST_ONE) {
  64609. throw new errors_1.MissingArgumentError(`argument ${this.fields[i6].name} is required, but received ${val2}`);
  64610. }
  64611. elemData.writeInt32(-1);
  64612. } else {
  64613. const codec = codecs[i6];
  64614. codec.encode(elemData, val2, ctx);
  64615. }
  64616. }
  64617. const elemBuf = elemData.unwrap();
  64618. const buf = new buffer_1.WriteBuffer();
  64619. buf.writeInt32(4 + elemBuf.length);
  64620. buf.writeInt32(codecsLen);
  64621. buf.writeBuffer(elemBuf);
  64622. return buf.unwrap();
  64623. }
  64624. decode(buf, ctx) {
  64625. const codecs = this.codecs;
  64626. const fields = this.fields;
  64627. const els = buf.readUInt32();
  64628. if (els !== codecs.length) {
  64629. throw new errors_1.ProtocolError(`cannot decode Object: expected ${codecs.length} elements, got ${els}`);
  64630. }
  64631. const elemBuf = buffer_1.ReadBuffer.alloc();
  64632. const result = {};
  64633. for (let i6 = 0; i6 < els; i6++) {
  64634. buf.discard(4);
  64635. const elemLen = buf.readInt32();
  64636. const name = fields[i6].name;
  64637. let val2 = null;
  64638. if (elemLen !== -1) {
  64639. buf.sliceInto(elemBuf, elemLen);
  64640. val2 = codecs[i6].decode(elemBuf, ctx);
  64641. elemBuf.finish();
  64642. }
  64643. result[name] = val2;
  64644. }
  64645. return result;
  64646. }
  64647. getSubcodecs() {
  64648. return Array.from(this.codecs);
  64649. }
  64650. getFields() {
  64651. return Array.from(this.fields);
  64652. }
  64653. getKind() {
  64654. return "object";
  64655. }
  64656. };
  64657. exports.ObjectCodec = ObjectCodec;
  64658. }
  64659. });
  64660. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/set.js
  64661. var require_set = __commonJS({
  64662. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/set.js"(exports) {
  64663. "use strict";
  64664. Object.defineProperty(exports, "__esModule", { value: true });
  64665. exports.SetCodec = void 0;
  64666. var ifaces_1 = require_ifaces();
  64667. var buffer_1 = require_buffer();
  64668. var array_1 = require_array();
  64669. var errors_1 = require_errors();
  64670. var SetCodec = class extends ifaces_1.Codec {
  64671. constructor(tid, subCodec) {
  64672. super(tid);
  64673. __publicField(this, "subCodec");
  64674. this.subCodec = subCodec;
  64675. }
  64676. encode(_buf, _obj) {
  64677. throw new errors_1.InvalidArgumentError("Sets cannot be passed in query arguments");
  64678. }
  64679. decode(buf, ctx) {
  64680. if (this.subCodec instanceof array_1.ArrayCodec) {
  64681. return this.decodeSetOfArrays(buf, ctx);
  64682. } else {
  64683. return this.decodeSet(buf, ctx);
  64684. }
  64685. }
  64686. decodeSetOfArrays(buf, ctx) {
  64687. const ndims = buf.readInt32();
  64688. buf.discard(4);
  64689. buf.discard(4);
  64690. if (ndims === 0) {
  64691. return [];
  64692. }
  64693. if (ndims !== 1) {
  64694. throw new errors_1.ProtocolError(`expected 1-dimensional array of records of arrays`);
  64695. }
  64696. const len = buf.readUInt32();
  64697. buf.discard(4);
  64698. const result = new Array(len);
  64699. const elemBuf = buffer_1.ReadBuffer.alloc();
  64700. const subCodec = this.subCodec;
  64701. for (let i6 = 0; i6 < len; i6++) {
  64702. buf.discard(4);
  64703. const recSize = buf.readUInt32();
  64704. if (recSize !== 1) {
  64705. throw new errors_1.ProtocolError("expected a record with a single element as an array set element envelope");
  64706. }
  64707. buf.discard(4);
  64708. const elemLen = buf.readInt32();
  64709. if (elemLen === -1) {
  64710. throw new errors_1.ProtocolError("unexpected NULL value in array set element");
  64711. }
  64712. buf.sliceInto(elemBuf, elemLen);
  64713. result[i6] = subCodec.decode(elemBuf, ctx);
  64714. elemBuf.finish();
  64715. }
  64716. return result;
  64717. }
  64718. decodeSet(buf, ctx) {
  64719. const ndims = buf.readInt32();
  64720. buf.discard(4);
  64721. buf.discard(4);
  64722. if (ndims === 0) {
  64723. return [];
  64724. }
  64725. if (ndims !== 1) {
  64726. throw new errors_1.ProtocolError(`invalid set dimensinality: ${ndims}`);
  64727. }
  64728. const len = buf.readUInt32();
  64729. buf.discard(4);
  64730. const result = new Array(len);
  64731. const elemBuf = buffer_1.ReadBuffer.alloc();
  64732. const subCodec = this.subCodec;
  64733. for (let i6 = 0; i6 < len; i6++) {
  64734. const elemLen = buf.readInt32();
  64735. if (elemLen === -1) {
  64736. result[i6] = null;
  64737. } else {
  64738. buf.sliceInto(elemBuf, elemLen);
  64739. result[i6] = subCodec.decode(elemBuf, ctx);
  64740. elemBuf.finish();
  64741. }
  64742. }
  64743. return result;
  64744. }
  64745. getSubcodecs() {
  64746. return [this.subCodec];
  64747. }
  64748. getKind() {
  64749. return "set";
  64750. }
  64751. };
  64752. exports.SetCodec = SetCodec;
  64753. }
  64754. });
  64755. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/record.js
  64756. var require_record = __commonJS({
  64757. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/record.js"(exports) {
  64758. "use strict";
  64759. Object.defineProperty(exports, "__esModule", { value: true });
  64760. exports.RecordCodec = exports.SQLRowModeObject = exports.SQLRowModeArray = void 0;
  64761. var ifaces_1 = require_ifaces();
  64762. var buffer_1 = require_buffer();
  64763. var errors_1 = require_errors();
  64764. var SQLRowArrayCodec = {
  64765. fromDatabase(values, _desc) {
  64766. return values;
  64767. },
  64768. toDatabase() {
  64769. throw new errors_1.InternalClientError("cannot encode SQL record as a query argument");
  64770. }
  64771. };
  64772. var SQLRowObjectCodec = {
  64773. fromDatabase(values, { names }) {
  64774. return Object.fromEntries(names.map((key, index6) => [key, values[index6]]));
  64775. },
  64776. toDatabase() {
  64777. throw new errors_1.InternalClientError("cannot encode SQL record as a query argument");
  64778. }
  64779. };
  64780. exports.SQLRowModeArray = {
  64781. _private_sql_row: SQLRowArrayCodec
  64782. };
  64783. exports.SQLRowModeObject = {
  64784. _private_sql_row: SQLRowObjectCodec
  64785. };
  64786. var RecordCodec = class extends ifaces_1.Codec {
  64787. constructor(tid, codecs, names) {
  64788. super(tid);
  64789. __publicField(this, "subCodecs");
  64790. __publicField(this, "names");
  64791. this.subCodecs = codecs;
  64792. this.names = names;
  64793. }
  64794. encode(_buf, _object) {
  64795. throw new errors_1.InvalidArgumentError("SQL records cannot be passed as arguments");
  64796. }
  64797. decode(buf, ctx) {
  64798. const els = buf.readUInt32();
  64799. const subCodecs = this.subCodecs;
  64800. if (els !== subCodecs.length) {
  64801. throw new errors_1.ProtocolError(`cannot decode Record: expected ${subCodecs.length} elements, got ${els}`);
  64802. }
  64803. const elemBuf = buffer_1.ReadBuffer.alloc();
  64804. const overload = ctx.getContainerOverload("_private_sql_row");
  64805. if (overload != null && overload !== SQLRowObjectCodec) {
  64806. const result = new Array(els);
  64807. for (let i6 = 0; i6 < els; i6++) {
  64808. buf.discard(4);
  64809. const elemLen = buf.readInt32();
  64810. let val2 = null;
  64811. if (elemLen !== -1) {
  64812. buf.sliceInto(elemBuf, elemLen);
  64813. val2 = subCodecs[i6].decode(elemBuf, ctx);
  64814. elemBuf.finish();
  64815. }
  64816. result[i6] = val2;
  64817. }
  64818. if (overload !== SQLRowArrayCodec) {
  64819. return overload.fromDatabase(result, { names: this.names });
  64820. }
  64821. return result;
  64822. } else {
  64823. const names = this.names;
  64824. const result = {};
  64825. for (let i6 = 0; i6 < els; i6++) {
  64826. buf.discard(4);
  64827. const elemLen = buf.readInt32();
  64828. let val2 = null;
  64829. if (elemLen !== -1) {
  64830. buf.sliceInto(elemBuf, elemLen);
  64831. val2 = subCodecs[i6].decode(elemBuf, ctx);
  64832. elemBuf.finish();
  64833. }
  64834. result[names[i6]] = val2;
  64835. }
  64836. return result;
  64837. }
  64838. }
  64839. getSubcodecs() {
  64840. return Array.from(this.subCodecs);
  64841. }
  64842. getNames() {
  64843. return Array.from(this.names);
  64844. }
  64845. getKind() {
  64846. return "record";
  64847. }
  64848. };
  64849. exports.RecordCodec = RecordCodec;
  64850. }
  64851. });
  64852. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/sparseObject.js
  64853. var require_sparseObject = __commonJS({
  64854. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/sparseObject.js"(exports) {
  64855. "use strict";
  64856. Object.defineProperty(exports, "__esModule", { value: true });
  64857. exports.SparseObjectCodec = void 0;
  64858. var ifaces_1 = require_ifaces();
  64859. var buffer_1 = require_buffer();
  64860. var errors_1 = require_errors();
  64861. var SparseObjectCodec = class extends ifaces_1.Codec {
  64862. constructor(tid, codecs, names) {
  64863. super(tid);
  64864. __publicField(this, "codecs");
  64865. __publicField(this, "names");
  64866. this.codecs = codecs;
  64867. this.names = names;
  64868. }
  64869. encode(buf, object, ctx) {
  64870. const elemBuf = new buffer_1.WriteBuffer();
  64871. let objLen = 0;
  64872. for (const [key, val2] of Object.entries(object)) {
  64873. if (val2 !== void 0) {
  64874. const i6 = this.names.indexOf(key);
  64875. if (i6 === -1) {
  64876. throw new errors_1.UnknownArgumentError(this.names.length ? `invalid global '${key}', valid globals are ${this.names.map((n5) => `'${n5}'`).join(", ")}` : `invalid global '${key}', no valid globals exist`);
  64877. }
  64878. objLen += 1;
  64879. elemBuf.writeInt32(i6);
  64880. if (val2 === null) {
  64881. elemBuf.writeInt32(-1);
  64882. } else {
  64883. this.codecs[i6].encode(elemBuf, val2, ctx);
  64884. }
  64885. }
  64886. }
  64887. const elemData = elemBuf.unwrap();
  64888. buf.writeInt32(4 + elemData.length);
  64889. buf.writeInt32(objLen);
  64890. buf.writeBuffer(elemData);
  64891. }
  64892. decode(buf, ctx) {
  64893. const codecs = this.codecs;
  64894. const names = this.names;
  64895. const els = buf.readUInt32();
  64896. const elemBuf = buffer_1.ReadBuffer.alloc();
  64897. const result = {};
  64898. for (let _3 = 0; _3 < els; _3++) {
  64899. const i6 = buf.readUInt32();
  64900. const elemLen = buf.readInt32();
  64901. const name = names[i6];
  64902. let val2 = null;
  64903. if (elemLen !== -1) {
  64904. buf.sliceInto(elemBuf, elemLen);
  64905. val2 = codecs[i6].decode(elemBuf, ctx);
  64906. elemBuf.finish();
  64907. }
  64908. result[name] = val2;
  64909. }
  64910. return result;
  64911. }
  64912. getSubcodecs() {
  64913. return Array.from(this.codecs);
  64914. }
  64915. getKind() {
  64916. return "sparse_object";
  64917. }
  64918. };
  64919. exports.SparseObjectCodec = SparseObjectCodec;
  64920. }
  64921. });
  64922. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/registry.js
  64923. var require_registry = __commonJS({
  64924. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/registry.js"(exports) {
  64925. "use strict";
  64926. var __importDefault = exports && exports.__importDefault || function(mod) {
  64927. return mod && mod.__esModule ? mod : { "default": mod };
  64928. };
  64929. Object.defineProperty(exports, "__esModule", { value: true });
  64930. exports.CodecsRegistry = void 0;
  64931. var buffer_1 = require_buffer();
  64932. var lru_1 = __importDefault(require_lru());
  64933. var ifaces_1 = require_ifaces();
  64934. var codecs_1 = require_codecs();
  64935. var consts_1 = require_consts();
  64936. var tuple_1 = require_tuple();
  64937. var array_1 = require_array();
  64938. var namedtuple_1 = require_namedtuple();
  64939. var enum_1 = require_enum();
  64940. var object_1 = require_object();
  64941. var set_1 = require_set();
  64942. var record_1 = require_record();
  64943. var range_1 = require_range3();
  64944. var utils_1 = require_utils2();
  64945. var sparseObject_1 = require_sparseObject();
  64946. var errors_1 = require_errors();
  64947. var CODECS_CACHE_SIZE = 1e3;
  64948. var CODECS_BUILD_CACHE_SIZE = 200;
  64949. var CTYPE_SET = 0;
  64950. var CTYPE_SHAPE = 1;
  64951. var CTYPE_BASE_SCALAR = 2;
  64952. var CTYPE_SCALAR = 3;
  64953. var CTYPE_TUPLE = 4;
  64954. var CTYPE_NAMEDTUPLE = 5;
  64955. var CTYPE_ARRAY = 6;
  64956. var CTYPE_ENUM = 7;
  64957. var CTYPE_INPUT_SHAPE = 8;
  64958. var CTYPE_RANGE = 9;
  64959. var CTYPE_OBJECT = 10;
  64960. var CTYPE_COMPOUND = 11;
  64961. var CTYPE_MULTIRANGE = 12;
  64962. var CTYPE_RECORD = 13;
  64963. var CodecsRegistry = class {
  64964. constructor() {
  64965. __publicField(this, "codecsBuildCache");
  64966. __publicField(this, "codecs");
  64967. this.codecs = new lru_1.default({ capacity: CODECS_CACHE_SIZE });
  64968. this.codecsBuildCache = new lru_1.default({ capacity: CODECS_BUILD_CACHE_SIZE });
  64969. }
  64970. hasCodec(typeId) {
  64971. if (this.codecs.has(typeId)) {
  64972. return true;
  64973. }
  64974. return typeId === consts_1.NULL_CODEC_ID || typeId === tuple_1.EMPTY_TUPLE_CODEC_ID;
  64975. }
  64976. getCodec(typeId) {
  64977. const codec = this.codecs.get(typeId);
  64978. if (codec != null) {
  64979. return codec;
  64980. }
  64981. if (typeId === tuple_1.EMPTY_TUPLE_CODEC_ID) {
  64982. return tuple_1.EMPTY_TUPLE_CODEC;
  64983. }
  64984. if (typeId === consts_1.NULL_CODEC_ID) {
  64985. return codecs_1.NULL_CODEC;
  64986. }
  64987. return null;
  64988. }
  64989. buildCodec(spec, protocolVersion) {
  64990. if (!(0, utils_1.versionGreaterThanOrEqual)(protocolVersion, [2, 0])) {
  64991. throw new errors_1.UnsupportedProtocolVersionError("unsupported old protocol version v1; downgrade to the previous version of gel-js");
  64992. }
  64993. const frb = new buffer_1.ReadBuffer(spec);
  64994. const codecsList = [];
  64995. let codec = null;
  64996. while (frb.length) {
  64997. const descLen = frb.readInt32();
  64998. const descBuf = buffer_1.ReadBuffer.alloc();
  64999. frb.sliceInto(descBuf, descLen);
  65000. codec = this._buildCodec(descBuf, codecsList);
  65001. descBuf.finish("unexpected trailing data in type descriptor buffer");
  65002. if (codec == null) {
  65003. continue;
  65004. }
  65005. codecsList.push(codec);
  65006. this.codecs.set(codec.tid, codec);
  65007. }
  65008. if (!codecsList.length) {
  65009. throw new errors_1.InternalClientError("could not build a codec");
  65010. }
  65011. return codecsList[codecsList.length - 1];
  65012. }
  65013. _buildCodec(frb, cl) {
  65014. const t6 = frb.readUInt8();
  65015. const tid = frb.readUUID();
  65016. let res = this.codecs.get(tid);
  65017. if (res == null) {
  65018. res = this.codecsBuildCache.get(tid);
  65019. }
  65020. if (res != null) {
  65021. frb.discard(frb.length);
  65022. return res;
  65023. }
  65024. switch (t6) {
  65025. case CTYPE_BASE_SCALAR: {
  65026. res = codecs_1.SCALAR_CODECS.get(tid);
  65027. if (!res) {
  65028. if (consts_1.KNOWN_TYPES.has(tid)) {
  65029. throw new errors_1.InternalClientError(`no JS codec for ${consts_1.KNOWN_TYPES.get(tid)}`);
  65030. }
  65031. throw new errors_1.InternalClientError(`no JS codec for the type with ID ${tid}`);
  65032. }
  65033. if (!(res instanceof ifaces_1.ScalarCodec)) {
  65034. throw new errors_1.ProtocolError("could not build scalar codec: base scalar is a non-scalar codec");
  65035. }
  65036. break;
  65037. }
  65038. case CTYPE_SHAPE:
  65039. case CTYPE_INPUT_SHAPE: {
  65040. if (t6 === CTYPE_SHAPE) {
  65041. frb.readBoolean();
  65042. frb.readUInt16();
  65043. }
  65044. const els = frb.readUInt16();
  65045. const codecs = new Array(els);
  65046. const names = new Array(els);
  65047. const flags = new Array(els);
  65048. const cards = new Array(els);
  65049. for (let i6 = 0; i6 < els; i6++) {
  65050. const flag = frb.readUInt32();
  65051. const card = frb.readUInt8();
  65052. const name = frb.readString();
  65053. const pos = frb.readUInt16();
  65054. const subCodec = cl[pos];
  65055. if (subCodec == null) {
  65056. throw new errors_1.ProtocolError("could not build object codec: missing subcodec");
  65057. }
  65058. codecs[i6] = subCodec;
  65059. names[i6] = name;
  65060. flags[i6] = flag;
  65061. cards[i6] = card;
  65062. if (t6 === CTYPE_SHAPE) {
  65063. frb.readUInt16();
  65064. }
  65065. }
  65066. res = t6 === CTYPE_INPUT_SHAPE ? new sparseObject_1.SparseObjectCodec(tid, codecs, names) : new object_1.ObjectCodec(tid, codecs, names, flags, cards);
  65067. break;
  65068. }
  65069. case CTYPE_SET: {
  65070. const pos = frb.readUInt16();
  65071. const subCodec = cl[pos];
  65072. if (subCodec == null) {
  65073. throw new errors_1.ProtocolError("could not build set codec: missing subcodec");
  65074. }
  65075. res = new set_1.SetCodec(tid, subCodec);
  65076. break;
  65077. }
  65078. case CTYPE_SCALAR: {
  65079. const typeName = frb.readString();
  65080. frb.readBoolean();
  65081. const ancestorCount = frb.readUInt16();
  65082. const ancestors = [];
  65083. for (let i6 = 0; i6 < ancestorCount; i6++) {
  65084. const ancestorPos = frb.readUInt16();
  65085. const ancestorCodec = cl[ancestorPos];
  65086. if (ancestorCodec == null) {
  65087. throw new errors_1.ProtocolError("could not build scalar codec: missing a codec for base scalar");
  65088. }
  65089. if (!(ancestorCodec instanceof ifaces_1.ScalarCodec)) {
  65090. throw new errors_1.ProtocolError(`a scalar codec expected for base scalar type, got ${ancestorCodec}`);
  65091. }
  65092. ancestors.push(ancestorCodec);
  65093. }
  65094. if (ancestorCount === 0) {
  65095. res = codecs_1.SCALAR_CODECS.get(tid);
  65096. if (res == null) {
  65097. if (consts_1.KNOWN_TYPES.has(tid)) {
  65098. throw new errors_1.InternalClientError(`no JS codec for ${consts_1.KNOWN_TYPES.get(tid)}`);
  65099. }
  65100. throw new errors_1.InternalClientError(`no JS codec for the type with ID ${tid}`);
  65101. }
  65102. } else {
  65103. const baseCodec = ancestors[ancestors.length - 1];
  65104. res = baseCodec.derive(tid, typeName, ancestors);
  65105. }
  65106. break;
  65107. }
  65108. case CTYPE_ARRAY: {
  65109. const typeName = frb.readString();
  65110. frb.readBoolean();
  65111. const ancestorCount = frb.readUInt16();
  65112. for (let i6 = 0; i6 < ancestorCount; i6++) {
  65113. frb.readUInt16();
  65114. }
  65115. const pos = frb.readUInt16();
  65116. const els = frb.readUInt16();
  65117. if (els !== 1) {
  65118. throw new errors_1.ProtocolError("cannot handle arrays with more than one dimension");
  65119. }
  65120. const dimLen = frb.readInt32();
  65121. const subCodec = cl[pos];
  65122. if (subCodec == null) {
  65123. throw new errors_1.ProtocolError("could not build array codec: missing subcodec");
  65124. }
  65125. res = new array_1.ArrayCodec(tid, typeName, subCodec, dimLen);
  65126. break;
  65127. }
  65128. case CTYPE_TUPLE: {
  65129. const typeName = frb.readString();
  65130. frb.readBoolean();
  65131. const ancestorCount = frb.readUInt16();
  65132. for (let i6 = 0; i6 < ancestorCount; i6++) {
  65133. frb.readUInt16();
  65134. }
  65135. const els = frb.readUInt16();
  65136. if (els === 0) {
  65137. res = tuple_1.EMPTY_TUPLE_CODEC;
  65138. } else {
  65139. const codecs = new Array(els);
  65140. for (let i6 = 0; i6 < els; i6++) {
  65141. const pos = frb.readUInt16();
  65142. const subCodec = cl[pos];
  65143. if (subCodec == null) {
  65144. throw new errors_1.ProtocolError("could not build tuple codec: missing subcodec");
  65145. }
  65146. codecs[i6] = subCodec;
  65147. }
  65148. res = new tuple_1.TupleCodec(tid, typeName, codecs);
  65149. }
  65150. break;
  65151. }
  65152. case CTYPE_NAMEDTUPLE: {
  65153. const typeName = frb.readString();
  65154. frb.readBoolean();
  65155. const ancestorCount = frb.readUInt16();
  65156. for (let i6 = 0; i6 < ancestorCount; i6++) {
  65157. frb.readUInt16();
  65158. }
  65159. const els = frb.readUInt16();
  65160. const codecs = new Array(els);
  65161. const names = new Array(els);
  65162. for (let i6 = 0; i6 < els; i6++) {
  65163. names[i6] = frb.readString();
  65164. const pos = frb.readUInt16();
  65165. const subCodec = cl[pos];
  65166. if (subCodec == null) {
  65167. throw new errors_1.ProtocolError("could not build namedtuple codec: missing subcodec");
  65168. }
  65169. codecs[i6] = subCodec;
  65170. }
  65171. res = new namedtuple_1.NamedTupleCodec(tid, typeName, codecs, names);
  65172. break;
  65173. }
  65174. case CTYPE_RECORD: {
  65175. const els = frb.readUInt16();
  65176. const codecs = new Array(els);
  65177. const names = new Array(els);
  65178. for (let i6 = 0; i6 < els; i6++) {
  65179. names[i6] = frb.readString();
  65180. const pos = frb.readUInt16();
  65181. const subCodec = cl[pos];
  65182. if (subCodec == null) {
  65183. throw new errors_1.ProtocolError("could not build record codec: missing subcodec");
  65184. }
  65185. codecs[i6] = subCodec;
  65186. }
  65187. res = new record_1.RecordCodec(tid, codecs, names);
  65188. break;
  65189. }
  65190. case CTYPE_ENUM: {
  65191. const typeName = frb.readString();
  65192. frb.readBoolean();
  65193. const ancestorCount = frb.readUInt16();
  65194. for (let i6 = 0; i6 < ancestorCount; i6++) {
  65195. frb.readUInt16();
  65196. }
  65197. const els = frb.readUInt16();
  65198. const values = [];
  65199. for (let i6 = 0; i6 < els; i6++) {
  65200. values.push(frb.readString());
  65201. }
  65202. res = new enum_1.EnumCodec(tid, typeName, values);
  65203. break;
  65204. }
  65205. case CTYPE_RANGE: {
  65206. const typeName = frb.readString();
  65207. frb.readBoolean();
  65208. const ancestorCount = frb.readUInt16();
  65209. for (let i6 = 0; i6 < ancestorCount; i6++) {
  65210. frb.readUInt16();
  65211. }
  65212. const pos = frb.readUInt16();
  65213. const subCodec = cl[pos];
  65214. if (subCodec == null) {
  65215. throw new errors_1.ProtocolError("could not build range codec: missing subcodec");
  65216. }
  65217. res = new range_1.RangeCodec(tid, typeName, subCodec);
  65218. break;
  65219. }
  65220. case CTYPE_OBJECT: {
  65221. frb.discard(frb.length);
  65222. res = codecs_1.NULL_CODEC;
  65223. break;
  65224. }
  65225. case CTYPE_COMPOUND: {
  65226. frb.discard(frb.length);
  65227. res = codecs_1.NULL_CODEC;
  65228. break;
  65229. }
  65230. case CTYPE_MULTIRANGE: {
  65231. const typeName = frb.readString();
  65232. frb.readBoolean();
  65233. const ancestorCount = frb.readUInt16();
  65234. for (let i6 = 0; i6 < ancestorCount; i6++) {
  65235. frb.readUInt16();
  65236. }
  65237. const pos = frb.readUInt16();
  65238. const subCodec = cl[pos];
  65239. if (subCodec == null) {
  65240. throw new errors_1.ProtocolError("could not build range codec: missing subcodec");
  65241. }
  65242. res = new range_1.MultiRangeCodec(tid, typeName, subCodec);
  65243. break;
  65244. }
  65245. }
  65246. if (res == null) {
  65247. if (consts_1.KNOWN_TYPES.has(tid)) {
  65248. throw new errors_1.InternalClientError(`could not build a codec for ${consts_1.KNOWN_TYPES.get(tid)} type`);
  65249. } else {
  65250. throw new errors_1.InternalClientError(`could not build a codec for ${tid} type`);
  65251. }
  65252. }
  65253. this.codecsBuildCache.set(tid, res);
  65254. return res;
  65255. }
  65256. };
  65257. exports.CodecsRegistry = CodecsRegistry;
  65258. }
  65259. });
  65260. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/context.js
  65261. var require_context = __commonJS({
  65262. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/context.js"(exports) {
  65263. "use strict";
  65264. Object.defineProperty(exports, "__esModule", { value: true });
  65265. exports.NOOP_CODEC_CONTEXT = exports.CodecContext = void 0;
  65266. var NOOP = {
  65267. toDatabase(data) {
  65268. return data;
  65269. },
  65270. fromDatabase(data) {
  65271. return data;
  65272. }
  65273. };
  65274. var CodecContext = class {
  65275. constructor(spec) {
  65276. __publicField(this, "spec");
  65277. __publicField(this, "map");
  65278. if (spec === null || spec.size === 0) {
  65279. this.spec = null;
  65280. } else {
  65281. this.spec = spec;
  65282. }
  65283. this.map = /* @__PURE__ */ new Map();
  65284. }
  65285. initCodec(codec) {
  65286. const specMap = this.spec;
  65287. const targetTypeName = codec.typeName;
  65288. const s6 = specMap.get(targetTypeName);
  65289. if (s6 != null) {
  65290. this.map.set(targetTypeName, s6);
  65291. return s6;
  65292. }
  65293. const ancestors = codec.ancestors;
  65294. if (ancestors == null) {
  65295. this.map.set(targetTypeName, NOOP);
  65296. return NOOP;
  65297. }
  65298. for (let i6 = 0; i6 < ancestors.length; i6++) {
  65299. const parent = ancestors[i6];
  65300. const s7 = specMap.get(parent.typeName);
  65301. if (s7 != null) {
  65302. this.map.set(targetTypeName, s7);
  65303. return s7;
  65304. }
  65305. }
  65306. this.map.set(targetTypeName, NOOP);
  65307. return NOOP;
  65308. }
  65309. getContainerOverload(kind) {
  65310. if (this.spec === null || !this.spec.size) {
  65311. return;
  65312. }
  65313. return this.spec.get(kind);
  65314. }
  65315. hasOverload(codec) {
  65316. if (this.spec === null || !this.spec.size) {
  65317. return false;
  65318. }
  65319. const op = this.map.get(codec.typeName);
  65320. if (op === NOOP) {
  65321. return false;
  65322. }
  65323. if (op != null) {
  65324. return true;
  65325. }
  65326. return this.initCodec(codec) !== NOOP;
  65327. }
  65328. postDecode(codec, value) {
  65329. if (this.spec === null || !this.spec.size) {
  65330. return value;
  65331. }
  65332. let op = this.map.get(codec.typeName);
  65333. if (op === NOOP) {
  65334. return value;
  65335. }
  65336. if (op == null) {
  65337. op = this.initCodec(codec);
  65338. }
  65339. return op.fromDatabase(value);
  65340. }
  65341. preEncode(codec, value) {
  65342. if (this.spec === null || !this.spec.size) {
  65343. return value;
  65344. }
  65345. let op = this.map.get(codec.typeName);
  65346. if (op === NOOP) {
  65347. return value;
  65348. }
  65349. if (op == null) {
  65350. op = this.initCodec(codec);
  65351. }
  65352. return op.toDatabase(value);
  65353. }
  65354. };
  65355. exports.CodecContext = CodecContext;
  65356. exports.NOOP_CODEC_CONTEXT = new CodecContext(null);
  65357. }
  65358. });
  65359. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/options.js
  65360. var require_options = __commonJS({
  65361. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/options.js"(exports) {
  65362. "use strict";
  65363. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  65364. if (k22 === void 0) k22 = k5;
  65365. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  65366. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  65367. desc = { enumerable: true, get: function() {
  65368. return m6[k5];
  65369. } };
  65370. }
  65371. Object.defineProperty(o5, k22, desc);
  65372. } : function(o5, m6, k5, k22) {
  65373. if (k22 === void 0) k22 = k5;
  65374. o5[k22] = m6[k5];
  65375. });
  65376. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  65377. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  65378. } : function(o5, v6) {
  65379. o5["default"] = v6;
  65380. });
  65381. var __importStar = exports && exports.__importStar || function(mod) {
  65382. if (mod && mod.__esModule) return mod;
  65383. var result = {};
  65384. if (mod != null) {
  65385. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  65386. }
  65387. __setModuleDefault(result, mod);
  65388. return result;
  65389. };
  65390. Object.defineProperty(exports, "__esModule", { value: true });
  65391. exports.Options = exports.TransactionOptions = exports.RetryOptions = exports.logWarnings = exports.throwWarnings = exports.RetryCondition = exports.IsolationLevel = void 0;
  65392. exports.defaultBackoff = defaultBackoff;
  65393. var errors = __importStar(require_errors());
  65394. var buffer_1 = require_buffer();
  65395. var record_1 = require_record();
  65396. var context_1 = require_context();
  65397. function defaultBackoff(attempt) {
  65398. return 2 ** attempt * 100 + Math.random() * 100;
  65399. }
  65400. var IsolationLevel;
  65401. (function(IsolationLevel2) {
  65402. IsolationLevel2["Serializable"] = "Serializable";
  65403. IsolationLevel2["RepeatableRead"] = "RepeatableRead";
  65404. IsolationLevel2["PreferRepeatableRead"] = "PreferRepeatableRead";
  65405. })(IsolationLevel || (exports.IsolationLevel = IsolationLevel = {}));
  65406. var RetryCondition;
  65407. (function(RetryCondition2) {
  65408. RetryCondition2[RetryCondition2["TransactionConflict"] = 0] = "TransactionConflict";
  65409. RetryCondition2[RetryCondition2["NetworkError"] = 1] = "NetworkError";
  65410. })(RetryCondition || (exports.RetryCondition = RetryCondition = {}));
  65411. var RetryRule = class {
  65412. constructor(attempts, backoff) {
  65413. __publicField(this, "attempts");
  65414. __publicField(this, "backoff");
  65415. this.attempts = attempts;
  65416. this.backoff = backoff;
  65417. }
  65418. };
  65419. var throwWarnings = (warnings) => {
  65420. throw new AggregateError(warnings, formatWarnings(warnings));
  65421. };
  65422. exports.throwWarnings = throwWarnings;
  65423. var logWarnings = (warnings) => {
  65424. const merged = new Error(formatWarnings(warnings));
  65425. console.warn(Object.assign(merged, { name: "" }));
  65426. };
  65427. exports.logWarnings = logWarnings;
  65428. var formatWarnings = (warnings) => `warnings occurred while running query:
  65429. ${warnings.map((warn) => warn.message).join("\n")}`;
  65430. var RetryOptions = class _RetryOptions {
  65431. constructor(attempts = 3, backoff = defaultBackoff) {
  65432. __publicField(this, "default");
  65433. __publicField(this, "overrides");
  65434. this.default = new RetryRule(attempts, backoff);
  65435. this.overrides = /* @__PURE__ */ new Map();
  65436. }
  65437. withRule(condition, attempts, backoff) {
  65438. const def = this.default;
  65439. const overrides = new Map(this.overrides);
  65440. overrides.set(condition, new RetryRule(attempts ?? def.attempts, backoff ?? def.backoff));
  65441. const result = Object.create(_RetryOptions.prototype);
  65442. result.default = def;
  65443. result.overrides = overrides;
  65444. return result;
  65445. }
  65446. getRuleForException(err2) {
  65447. let result;
  65448. if (err2 instanceof errors.TransactionConflictError) {
  65449. result = this.overrides.get(RetryCondition.TransactionConflict);
  65450. } else if (err2 instanceof errors.ClientError) {
  65451. result = this.overrides.get(RetryCondition.NetworkError);
  65452. }
  65453. return result ?? this.default;
  65454. }
  65455. static defaults() {
  65456. return _retryOptionsDefault;
  65457. }
  65458. };
  65459. exports.RetryOptions = RetryOptions;
  65460. var _retryOptionsDefault = new RetryOptions();
  65461. var TransactionOptions = class {
  65462. constructor({ isolation, readonly, deferrable } = {}) {
  65463. __publicField(this, "isolation");
  65464. __publicField(this, "readonly");
  65465. __publicField(this, "deferrable");
  65466. this.isolation = isolation;
  65467. this.readonly = readonly;
  65468. this.deferrable = deferrable;
  65469. }
  65470. isDefault() {
  65471. return this.isolation === void 0 && this.readonly === void 0 && this.deferrable === void 0;
  65472. }
  65473. static defaults() {
  65474. return _defaultTransactionOptions;
  65475. }
  65476. };
  65477. exports.TransactionOptions = TransactionOptions;
  65478. var _defaultTransactionOptions = new TransactionOptions();
  65479. var TAG_ANNOTATION_KEY = "tag";
  65480. var _Options = class _Options {
  65481. constructor({ retryOptions = RetryOptions.defaults(), transactionOptions = TransactionOptions.defaults(), warningHandler = exports.logWarnings, module: module2 = "default", moduleAliases = {}, config = {}, globals = {}, codecs = {} } = {}) {
  65482. __publicField(this, "module");
  65483. __publicField(this, "moduleAliases");
  65484. __publicField(this, "config");
  65485. __publicField(this, "globals");
  65486. __publicField(this, "retryOptions");
  65487. __publicField(this, "transactionOptions");
  65488. __publicField(this, "codecs");
  65489. __publicField(this, "warningHandler");
  65490. __publicField(this, "annotations", /* @__PURE__ */ new Map());
  65491. __publicField(this, "cachedCodecContext", null);
  65492. __publicField(this, "cachedCodecContextVer", -1);
  65493. this.retryOptions = retryOptions;
  65494. this.transactionOptions = transactionOptions;
  65495. this.warningHandler = warningHandler;
  65496. this.module = module2;
  65497. this.moduleAliases = new Map(Object.entries(moduleAliases));
  65498. this.config = new Map(Object.entries(config));
  65499. this.globals = new Map(Object.entries(globals));
  65500. this.codecs = new Map(Object.entries(codecs));
  65501. }
  65502. get tag() {
  65503. return this.annotations.get(TAG_ANNOTATION_KEY) ?? null;
  65504. }
  65505. static signalSchemaChange() {
  65506. this.schemaVersion += 1;
  65507. }
  65508. makeCodecContext() {
  65509. if (this.codecs.size === 0) {
  65510. return context_1.NOOP_CODEC_CONTEXT;
  65511. }
  65512. if (this.cachedCodecContextVer === _Options.schemaVersion) {
  65513. return this.cachedCodecContext;
  65514. }
  65515. const ctx = new context_1.CodecContext(this.codecs);
  65516. this.cachedCodecContext = ctx;
  65517. this.cachedCodecContextVer = _Options.schemaVersion;
  65518. return ctx;
  65519. }
  65520. _cloneWith(mergeOptions) {
  65521. const clone2 = Object.create(_Options.prototype);
  65522. clone2.annotations = this.annotations;
  65523. clone2.retryOptions = mergeOptions.retryOptions ?? this.retryOptions;
  65524. clone2.transactionOptions = mergeOptions.transactionOptions ?? this.transactionOptions;
  65525. clone2.warningHandler = mergeOptions.warningHandler ?? this.warningHandler;
  65526. if (mergeOptions.config != null) {
  65527. clone2.config = new Map([
  65528. ...this.config,
  65529. ...Object.entries(mergeOptions.config)
  65530. ]);
  65531. } else {
  65532. clone2.config = this.config;
  65533. }
  65534. if (mergeOptions.globals != null) {
  65535. clone2.globals = new Map([
  65536. ...this.globals,
  65537. ...Object.entries(mergeOptions.globals)
  65538. ]);
  65539. } else {
  65540. clone2.globals = this.globals;
  65541. }
  65542. if (mergeOptions.moduleAliases != null) {
  65543. clone2.moduleAliases = new Map([
  65544. ...this.moduleAliases,
  65545. ...Object.entries(mergeOptions.moduleAliases)
  65546. ]);
  65547. } else {
  65548. clone2.moduleAliases = this.moduleAliases;
  65549. }
  65550. if (mergeOptions.codecs != null) {
  65551. clone2.codecs = new Map([
  65552. ...this.codecs,
  65553. ...Object.entries(mergeOptions.codecs)
  65554. ]);
  65555. } else {
  65556. clone2.codecs = this.codecs;
  65557. clone2.cachedCodecContext = this.cachedCodecContext;
  65558. clone2.cachedCodecContextVer = this.cachedCodecContextVer;
  65559. }
  65560. if (mergeOptions._dropSQLRowCodec && clone2.codecs.has("_private_sql_row")) {
  65561. if (clone2.codecs === this.codecs) {
  65562. clone2.codecs = new Map(clone2.codecs);
  65563. clone2.cachedCodecContext = null;
  65564. clone2.cachedCodecContextVer = -1;
  65565. }
  65566. clone2.codecs.delete("_private_sql_row");
  65567. }
  65568. clone2.module = mergeOptions.module ?? this.module;
  65569. return clone2;
  65570. }
  65571. _serialise() {
  65572. const state2 = {};
  65573. if (this.module !== "default") {
  65574. state2.module = this.module;
  65575. }
  65576. if (this.moduleAliases.size) {
  65577. state2.aliases = Array.from(this.moduleAliases.entries());
  65578. }
  65579. if (this.config.size) {
  65580. state2.config = Object.fromEntries(this.config.entries());
  65581. }
  65582. if (this.globals.size) {
  65583. const globs = {};
  65584. for (const [key, val2] of this.globals.entries()) {
  65585. globs[key.includes("::") ? key : `${this.module}::${key}`] = val2;
  65586. }
  65587. state2.globals = globs;
  65588. }
  65589. return state2;
  65590. }
  65591. withModuleAliases({ module: module2, ...aliases }) {
  65592. return this._cloneWith({
  65593. module: module2 ?? this.module,
  65594. moduleAliases: aliases
  65595. });
  65596. }
  65597. withConfig(config) {
  65598. return this._cloneWith({ config });
  65599. }
  65600. withCodecs(codecs) {
  65601. return this._cloneWith({ codecs });
  65602. }
  65603. withSQLRowMode(mode) {
  65604. if (mode === "object") {
  65605. return this._cloneWith({ _dropSQLRowCodec: true });
  65606. } else if (mode === "array") {
  65607. return this._cloneWith({ codecs: record_1.SQLRowModeArray });
  65608. } else {
  65609. throw new errors.InterfaceError(`invalid mode=${mode}`);
  65610. }
  65611. }
  65612. withGlobals(globals) {
  65613. return this._cloneWith({
  65614. globals: { ...this.globals, ...globals }
  65615. });
  65616. }
  65617. withQueryTag(tag) {
  65618. const annos = new Map(this.annotations);
  65619. if (tag != null) {
  65620. if (tag.startsWith("edgedb/")) {
  65621. throw new errors.InterfaceError("reserved tag: edgedb/*");
  65622. }
  65623. if (tag.startsWith("gel/")) {
  65624. throw new errors.InterfaceError("reserved tag: gel/*");
  65625. }
  65626. if (buffer_1.utf8Encoder.encode(tag).length > 128) {
  65627. throw new errors.InterfaceError("tag too long (> 128 bytes)");
  65628. }
  65629. annos.set(TAG_ANNOTATION_KEY, tag);
  65630. } else {
  65631. annos.delete(TAG_ANNOTATION_KEY);
  65632. }
  65633. const clone2 = this._cloneWith({});
  65634. clone2.annotations = annos;
  65635. return clone2;
  65636. }
  65637. withTransactionOptions(opt) {
  65638. return this._cloneWith({
  65639. transactionOptions: opt instanceof TransactionOptions ? opt : new TransactionOptions(opt)
  65640. });
  65641. }
  65642. withRetryOptions(opt) {
  65643. return this._cloneWith({
  65644. retryOptions: opt instanceof RetryOptions ? opt : new RetryOptions(opt.attempts, opt.backoff)
  65645. });
  65646. }
  65647. withWarningHandler(handler) {
  65648. return this._cloneWith({ warningHandler: handler });
  65649. }
  65650. isDefaultSession() {
  65651. return this.config.size === 0 && this.globals.size === 0 && this.moduleAliases.size === 0 && this.module === "default" && this.transactionOptions.isDefault();
  65652. }
  65653. static defaults() {
  65654. return _defaultOptions;
  65655. }
  65656. };
  65657. __publicField(_Options, "schemaVersion", 0);
  65658. var Options = _Options;
  65659. exports.Options = Options;
  65660. var _defaultOptions = new Options();
  65661. }
  65662. });
  65663. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/event.js
  65664. var require_event = __commonJS({
  65665. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/event.js"(exports) {
  65666. "use strict";
  65667. Object.defineProperty(exports, "__esModule", { value: true });
  65668. var errors_1 = require_errors();
  65669. var Event = class {
  65670. constructor() {
  65671. __publicField(this, "_promise");
  65672. __publicField(this, "_resolve");
  65673. __publicField(this, "_reject");
  65674. __publicField(this, "_done");
  65675. this._done = false;
  65676. let futReject = null;
  65677. let futResolve = null;
  65678. this._promise = new Promise((resolve, reject) => {
  65679. futReject = (reason) => {
  65680. this._done = true;
  65681. reject(reason);
  65682. };
  65683. futResolve = (value) => {
  65684. this._done = true;
  65685. resolve(value);
  65686. };
  65687. });
  65688. if (!futReject || !futResolve) {
  65689. throw new errors_1.InternalClientError("Promise executor was not called synchronously");
  65690. }
  65691. this._reject = futReject;
  65692. this._resolve = futResolve;
  65693. }
  65694. async wait() {
  65695. await this._promise;
  65696. }
  65697. then(..._args) {
  65698. throw new errors_1.InternalClientError("Event objects cannot be awaited on directly; use Event.wait()");
  65699. }
  65700. get done() {
  65701. return this._done;
  65702. }
  65703. set() {
  65704. if (this._done) {
  65705. throw new errors_1.InternalClientError("emit(): the Event is already set");
  65706. }
  65707. this._resolve(true);
  65708. }
  65709. setError(reason) {
  65710. if (this._done) {
  65711. throw new errors_1.InternalClientError("emitError(): the Event is already set");
  65712. }
  65713. this._reject(reason);
  65714. }
  65715. };
  65716. exports.default = Event;
  65717. }
  65718. });
  65719. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/queues.js
  65720. var require_queues = __commonJS({
  65721. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/queues.js"(exports) {
  65722. "use strict";
  65723. Object.defineProperty(exports, "__esModule", { value: true });
  65724. exports.LifoQueue = void 0;
  65725. var errors_1 = require_errors();
  65726. var LifoQueue = class {
  65727. constructor() {
  65728. __publicField(this, "_promises");
  65729. __publicField(this, "_resolvers");
  65730. __publicField(this, "_rejecters");
  65731. this._resolvers = [];
  65732. this._rejecters = [];
  65733. this._promises = [];
  65734. }
  65735. _add() {
  65736. this._promises.push(new Promise((resolve, reject) => {
  65737. this._resolvers.push(resolve);
  65738. this._rejecters.push(reject);
  65739. }));
  65740. }
  65741. push(item) {
  65742. if (!this._resolvers.length) {
  65743. this._add();
  65744. }
  65745. const resolve = this._resolvers.shift();
  65746. this._rejecters.shift();
  65747. if (!resolve) {
  65748. throw new errors_1.InternalClientError("resolve function was null or undefined when attempting to push.");
  65749. }
  65750. resolve(item);
  65751. }
  65752. get() {
  65753. if (!this._promises.length) {
  65754. this._add();
  65755. }
  65756. const promise = this._promises.pop();
  65757. if (!promise) {
  65758. throw new errors_1.InternalClientError("promise was null or undefined when attempting to get.");
  65759. }
  65760. return promise;
  65761. }
  65762. cancelAllPending(err2) {
  65763. const rejecters = this._rejecters;
  65764. this._rejecters = [];
  65765. this._resolvers = [];
  65766. for (const reject of rejecters) {
  65767. reject(err2);
  65768. }
  65769. }
  65770. get length() {
  65771. return this._promises.length - this._resolvers.length;
  65772. }
  65773. get pending() {
  65774. return Math.max(0, this._resolvers.length - this._promises.length);
  65775. }
  65776. };
  65777. exports.LifoQueue = LifoQueue;
  65778. }
  65779. });
  65780. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/retry.js
  65781. var require_retry = __commonJS({
  65782. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/retry.js"(exports) {
  65783. "use strict";
  65784. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  65785. if (k22 === void 0) k22 = k5;
  65786. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  65787. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  65788. desc = { enumerable: true, get: function() {
  65789. return m6[k5];
  65790. } };
  65791. }
  65792. Object.defineProperty(o5, k22, desc);
  65793. } : function(o5, m6, k5, k22) {
  65794. if (k22 === void 0) k22 = k5;
  65795. o5[k22] = m6[k5];
  65796. });
  65797. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  65798. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  65799. } : function(o5, v6) {
  65800. o5["default"] = v6;
  65801. });
  65802. var __importStar = exports && exports.__importStar || function(mod) {
  65803. if (mod && mod.__esModule) return mod;
  65804. var result = {};
  65805. if (mod != null) {
  65806. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  65807. }
  65808. __setModuleDefault(result, mod);
  65809. return result;
  65810. };
  65811. Object.defineProperty(exports, "__esModule", { value: true });
  65812. exports.retryingConnect = retryingConnect;
  65813. var errors = __importStar(require_errors());
  65814. var utils_1 = require_utils2();
  65815. var lastLoggingAt = 0;
  65816. async function retryingConnect(connectWithTimeout, config, registry) {
  65817. const maxTime = config.connectionParams.waitUntilAvailable === 0 ? 0 : Date.now() + config.connectionParams.waitUntilAvailable;
  65818. while (true) {
  65819. try {
  65820. return await connectWithTimeout(config, registry);
  65821. } catch (e6) {
  65822. if (e6 instanceof errors.ClientConnectionError) {
  65823. if (e6.hasTag(errors.SHOULD_RECONNECT)) {
  65824. const now = Date.now();
  65825. if (now > maxTime) {
  65826. throw e6;
  65827. }
  65828. if (config.logging && (!lastLoggingAt || now - lastLoggingAt > 5e3)) {
  65829. lastLoggingAt = now;
  65830. const logMsg = [
  65831. `A client connection error occurred; reconnecting because of "waitUntilAvailable=${config.connectionParams.waitUntilAvailable}".`,
  65832. e6
  65833. ];
  65834. if (!config.fromProject && !config.fromEnv && await config.inProject()) {
  65835. logMsg.push(`
  65836. Hint: it looks like the program is running from a directory initialized with "gel project init". Consider calling "gel.connect()" without arguments.
  65837. `);
  65838. }
  65839. console.warn(...logMsg);
  65840. }
  65841. } else {
  65842. throw e6;
  65843. }
  65844. } else {
  65845. console.error("Unexpected connection error:", e6);
  65846. throw e6;
  65847. }
  65848. }
  65849. await (0, utils_1.sleep)(Math.trunc(10 + Math.random() * 200));
  65850. }
  65851. }
  65852. }
  65853. });
  65854. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/enums.js
  65855. var require_enums = __commonJS({
  65856. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/enums.js"(exports) {
  65857. "use strict";
  65858. Object.defineProperty(exports, "__esModule", { value: true });
  65859. exports.OperatorKind = exports.SelectModifierKind = exports.ExpressionKind = exports.TypeKind = exports.Cardinality = void 0;
  65860. var Cardinality;
  65861. (function(Cardinality2) {
  65862. Cardinality2["AtMostOne"] = "AtMostOne";
  65863. Cardinality2["One"] = "One";
  65864. Cardinality2["Many"] = "Many";
  65865. Cardinality2["AtLeastOne"] = "AtLeastOne";
  65866. Cardinality2["Empty"] = "Empty";
  65867. })(Cardinality || (exports.Cardinality = Cardinality = {}));
  65868. var TypeKind;
  65869. (function(TypeKind2) {
  65870. TypeKind2["scalar"] = "scalar";
  65871. TypeKind2["enum"] = "enum";
  65872. TypeKind2["object"] = "object";
  65873. TypeKind2["namedtuple"] = "namedtuple";
  65874. TypeKind2["tuple"] = "tuple";
  65875. TypeKind2["array"] = "array";
  65876. TypeKind2["range"] = "range";
  65877. TypeKind2["multirange"] = "multirange";
  65878. })(TypeKind || (exports.TypeKind = TypeKind = {}));
  65879. var ExpressionKind;
  65880. (function(ExpressionKind2) {
  65881. ExpressionKind2["Set"] = "Set";
  65882. ExpressionKind2["Array"] = "Array";
  65883. ExpressionKind2["Tuple"] = "Tuple";
  65884. ExpressionKind2["NamedTuple"] = "NamedTuple";
  65885. ExpressionKind2["TuplePath"] = "TuplePath";
  65886. ExpressionKind2["PathNode"] = "PathNode";
  65887. ExpressionKind2["PathLeaf"] = "PathLeaf";
  65888. ExpressionKind2["Literal"] = "Literal";
  65889. ExpressionKind2["Cast"] = "Cast";
  65890. ExpressionKind2["Select"] = "Select";
  65891. ExpressionKind2["Update"] = "Update";
  65892. ExpressionKind2["Delete"] = "Delete";
  65893. ExpressionKind2["Insert"] = "Insert";
  65894. ExpressionKind2["InsertUnlessConflict"] = "InsertUnlessConflict";
  65895. ExpressionKind2["Function"] = "Function";
  65896. ExpressionKind2["Operator"] = "Operator";
  65897. ExpressionKind2["For"] = "For";
  65898. ExpressionKind2["ForVar"] = "ForVar";
  65899. ExpressionKind2["TypeIntersection"] = "TypeIntersection";
  65900. ExpressionKind2["Alias"] = "Alias";
  65901. ExpressionKind2["With"] = "With";
  65902. ExpressionKind2["WithParams"] = "WithParams";
  65903. ExpressionKind2["Param"] = "Param";
  65904. ExpressionKind2["OptionalParam"] = "OptionalParam";
  65905. ExpressionKind2["Detached"] = "Detached";
  65906. ExpressionKind2["Global"] = "Global";
  65907. ExpressionKind2["PolyShapeElement"] = "PolyShapeElement";
  65908. ExpressionKind2["Group"] = "Group";
  65909. })(ExpressionKind || (exports.ExpressionKind = ExpressionKind = {}));
  65910. var SelectModifierKind;
  65911. (function(SelectModifierKind2) {
  65912. SelectModifierKind2["filter"] = "filter";
  65913. SelectModifierKind2["order_by"] = "order_by";
  65914. SelectModifierKind2["offset"] = "offset";
  65915. SelectModifierKind2["limit"] = "limit";
  65916. })(SelectModifierKind || (exports.SelectModifierKind = SelectModifierKind = {}));
  65917. var OperatorKind;
  65918. (function(OperatorKind2) {
  65919. OperatorKind2["Infix"] = "Infix";
  65920. OperatorKind2["Postfix"] = "Postfix";
  65921. OperatorKind2["Prefix"] = "Prefix";
  65922. OperatorKind2["Ternary"] = "Ternary";
  65923. })(OperatorKind || (exports.OperatorKind = OperatorKind = {}));
  65924. }
  65925. });
  65926. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/util.js
  65927. var require_util3 = __commonJS({
  65928. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/util.js"(exports) {
  65929. "use strict";
  65930. Object.defineProperty(exports, "__esModule", { value: true });
  65931. exports.util = void 0;
  65932. var ifaces_1 = require_ifaces2();
  65933. var enums_1 = require_enums();
  65934. var util2;
  65935. (function(util3) {
  65936. function assertNever(arg, error2) {
  65937. throw error2 ?? new Error(`${arg} is supposed to be of "never" type`);
  65938. }
  65939. util3.assertNever = assertNever;
  65940. function splitName(name) {
  65941. if (!name.includes("::"))
  65942. throw new Error(`Invalid FQN ${name}`);
  65943. const parts = name.split("::");
  65944. return {
  65945. mod: parts.slice(0, -1).join("::"),
  65946. name: parts[parts.length - 1]
  65947. };
  65948. }
  65949. util3.splitName = splitName;
  65950. function toIdent(name) {
  65951. if (name.includes("::")) {
  65952. throw new Error(`toIdent: invalid name ${name}`);
  65953. }
  65954. return name.replace(/([^a-zA-Z0-9_]+)/g, "_");
  65955. }
  65956. util3.toIdent = toIdent;
  65957. util3.deduplicate = (args) => [...new Set(args)];
  65958. util3.getFromArrayMap = (map2, id) => {
  65959. return map2[id] || [];
  65960. };
  65961. util3.defineProperty = (obj, name, def) => {
  65962. return Object.defineProperty(obj, name, def);
  65963. };
  65964. util3.defineGetter = (obj, name, getter) => {
  65965. return Object.defineProperty(obj, name, {
  65966. get: getter,
  65967. enumerable: true
  65968. });
  65969. };
  65970. util3.defineMethod = (obj, name, method) => {
  65971. obj[name] = method.bind(obj);
  65972. return obj;
  65973. };
  65974. function flatMap(array2, callbackfn) {
  65975. return Array.prototype.concat(...array2.map(callbackfn));
  65976. }
  65977. util3.flatMap = flatMap;
  65978. function omitDollarPrefixed(object) {
  65979. const obj = {};
  65980. for (const key of Object.keys(object)) {
  65981. if (!key.startsWith("$")) {
  65982. obj[key] = object[key];
  65983. }
  65984. }
  65985. return obj;
  65986. }
  65987. util3.omitDollarPrefixed = omitDollarPrefixed;
  65988. util3.parseCardinality = (cardinality) => {
  65989. switch (cardinality) {
  65990. case ifaces_1.Cardinality.MANY:
  65991. return enums_1.Cardinality.Many;
  65992. case ifaces_1.Cardinality.ONE:
  65993. return enums_1.Cardinality.One;
  65994. case ifaces_1.Cardinality.AT_MOST_ONE:
  65995. return enums_1.Cardinality.AtMostOne;
  65996. case ifaces_1.Cardinality.AT_LEAST_ONE:
  65997. return enums_1.Cardinality.AtLeastOne;
  65998. case ifaces_1.Cardinality.NO_RESULT:
  65999. return enums_1.Cardinality.Empty;
  66000. }
  66001. throw new Error(`Unexpected cardinality: ${cardinality}`);
  66002. };
  66003. })(util2 || (exports.util = util2 = {}));
  66004. }
  66005. });
  66006. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/transaction.js
  66007. var require_transaction = __commonJS({
  66008. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/transaction.js"(exports) {
  66009. "use strict";
  66010. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  66011. if (k22 === void 0) k22 = k5;
  66012. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  66013. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  66014. desc = { enumerable: true, get: function() {
  66015. return m6[k5];
  66016. } };
  66017. }
  66018. Object.defineProperty(o5, k22, desc);
  66019. } : function(o5, m6, k5, k22) {
  66020. if (k22 === void 0) k22 = k5;
  66021. o5[k22] = m6[k5];
  66022. });
  66023. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  66024. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  66025. } : function(o5, v6) {
  66026. o5["default"] = v6;
  66027. });
  66028. var __importStar = exports && exports.__importStar || function(mod) {
  66029. if (mod && mod.__esModule) return mod;
  66030. var result = {};
  66031. if (mod != null) {
  66032. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  66033. }
  66034. __setModuleDefault(result, mod);
  66035. return result;
  66036. };
  66037. Object.defineProperty(exports, "__esModule", { value: true });
  66038. exports.Transaction = exports.TransactionImpl = exports.TransactionState = void 0;
  66039. var errors = __importStar(require_errors());
  66040. var ifaces_1 = require_ifaces2();
  66041. var options_1 = require_options();
  66042. var TransactionState;
  66043. (function(TransactionState2) {
  66044. TransactionState2[TransactionState2["ACTIVE"] = 0] = "ACTIVE";
  66045. TransactionState2[TransactionState2["COMMITTED"] = 1] = "COMMITTED";
  66046. TransactionState2[TransactionState2["ROLLEDBACK"] = 2] = "ROLLEDBACK";
  66047. TransactionState2[TransactionState2["FAILED"] = 3] = "FAILED";
  66048. })(TransactionState || (exports.TransactionState = TransactionState = {}));
  66049. var TransactionImpl = class _TransactionImpl {
  66050. constructor(holder, rawConn) {
  66051. __publicField(this, "_holder");
  66052. __publicField(this, "_rawConn");
  66053. __publicField(this, "_state");
  66054. __publicField(this, "_opInProgress");
  66055. this._holder = holder;
  66056. this._rawConn = rawConn;
  66057. this._state = TransactionState.ACTIVE;
  66058. this._opInProgress = false;
  66059. }
  66060. static async _startTransaction(holder, optimisticRepeatableRead) {
  66061. const rawConn = await holder._getConnection();
  66062. await rawConn.resetState();
  66063. const options = holder.options.transactionOptions;
  66064. const txOptions = [];
  66065. if (options.isolation === options_1.IsolationLevel.RepeatableRead) {
  66066. txOptions.push(`ISOLATION REPEATABLE READ`);
  66067. } else if (options.isolation === options_1.IsolationLevel.Serializable) {
  66068. txOptions.push(`ISOLATION SERIALIZABLE`);
  66069. } else if (options.isolation === options_1.IsolationLevel.PreferRepeatableRead) {
  66070. if (optimisticRepeatableRead) {
  66071. txOptions.push(`ISOLATION REPEATABLE READ`);
  66072. } else {
  66073. txOptions.push(`ISOLATION SERIALIZABLE`);
  66074. }
  66075. } else if (options.isolation != null) {
  66076. throw new errors.InterfaceError(`Invalid isolation level: ${options.isolation}`);
  66077. }
  66078. if (options.readonly !== void 0) {
  66079. txOptions.push(options.readonly ? "READ ONLY" : "READ WRITE");
  66080. }
  66081. if (options.deferrable !== void 0) {
  66082. txOptions.push(options.deferrable ? "DEFERRABLE" : "NOT DEFERRABLE");
  66083. }
  66084. await rawConn.fetch(`START TRANSACTION ${txOptions.join(", ")};`, void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, holder.options, true);
  66085. return new _TransactionImpl(holder, rawConn);
  66086. }
  66087. async _waitForConnAbort() {
  66088. await this._rawConn.connAbortWaiter.wait();
  66089. const abortError = this._rawConn.getConnAbortError();
  66090. if (abortError instanceof errors.GelError && abortError.cause instanceof errors.TransactionTimeoutError) {
  66091. throw abortError.cause;
  66092. } else {
  66093. throw abortError;
  66094. }
  66095. }
  66096. async _runOp(opname, op, errMessage) {
  66097. if (this._opInProgress) {
  66098. throw new errors.InterfaceError(errMessage ?? "Another query is in progress. Use the query methods on 'Client' to run queries concurrently.");
  66099. }
  66100. if (this._state !== TransactionState.ACTIVE) {
  66101. throw new errors.InterfaceError(`cannot ${opname}; the transaction is ${this._state === TransactionState.COMMITTED ? "already committed" : this._state === TransactionState.ROLLEDBACK ? "already rolled back" : "in error state"}`);
  66102. }
  66103. this._opInProgress = true;
  66104. try {
  66105. return await op();
  66106. } finally {
  66107. this._opInProgress = false;
  66108. }
  66109. }
  66110. async _runFetchOp(opName, ...args) {
  66111. const { result, warnings } = await this._runOp(opName, () => this._rawConn.fetch(...args));
  66112. if (warnings.length) {
  66113. this._holder.options.warningHandler(warnings);
  66114. }
  66115. return result;
  66116. }
  66117. async _commit() {
  66118. await this._runOp("commit", async () => {
  66119. await this._rawConn.fetch("COMMIT", void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this._holder.options, true);
  66120. this._state = TransactionState.COMMITTED;
  66121. }, "A query is still in progress after transaction block has returned.");
  66122. }
  66123. async _rollback() {
  66124. await this._runOp("rollback", async () => {
  66125. await this._rawConn.fetch("ROLLBACK", void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this._holder.options, true);
  66126. this._state = TransactionState.ROLLEDBACK;
  66127. }, "A query is still in progress after transaction block has returned.");
  66128. }
  66129. };
  66130. exports.TransactionImpl = TransactionImpl;
  66131. var Transaction = class _Transaction {
  66132. constructor(impl, options) {
  66133. __publicField(this, "impl");
  66134. __publicField(this, "options");
  66135. this.impl = impl;
  66136. this.options = options;
  66137. }
  66138. withSQLRowMode(mode) {
  66139. return new _Transaction(this.impl, this.options.withSQLRowMode(mode));
  66140. }
  66141. async execute(query, args) {
  66142. await this.impl._runFetchOp("execute", query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this.options);
  66143. }
  66144. async executeSQL(query, args) {
  66145. await this.impl._runFetchOp("execute", query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this.options, false, ifaces_1.Language.SQL);
  66146. }
  66147. async query(query, args) {
  66148. return this.impl._runFetchOp("query", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options);
  66149. }
  66150. async querySQL(query, args) {
  66151. return this.impl._runFetchOp("query", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options, false, ifaces_1.Language.SQL);
  66152. }
  66153. async queryJSON(query, args) {
  66154. return this.impl._runFetchOp("queryJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.MANY, this.options);
  66155. }
  66156. async querySingle(query, args) {
  66157. return this.impl._runFetchOp("querySingle", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_MOST_ONE, this.options);
  66158. }
  66159. async querySingleJSON(query, args) {
  66160. return this.impl._runFetchOp("querySingleJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_MOST_ONE, this.options);
  66161. }
  66162. async queryRequired(query, args) {
  66163. return this.impl._runFetchOp("queryRequired", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_LEAST_ONE, this.options);
  66164. }
  66165. async queryRequiredJSON(query, args) {
  66166. return this.impl._runFetchOp("queryRequiredJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_LEAST_ONE, this.options);
  66167. }
  66168. async queryRequiredSingle(query, args) {
  66169. return this.impl._runFetchOp("queryRequiredSingle", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.ONE, this.options);
  66170. }
  66171. async queryRequiredSingleJSON(query, args) {
  66172. return this.impl._runFetchOp("queryRequiredSingleJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.ONE, this.options);
  66173. }
  66174. };
  66175. exports.Transaction = Transaction;
  66176. }
  66177. });
  66178. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseClient.js
  66179. var require_baseClient = __commonJS({
  66180. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseClient.js"(exports) {
  66181. "use strict";
  66182. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  66183. if (k22 === void 0) k22 = k5;
  66184. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  66185. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  66186. desc = { enumerable: true, get: function() {
  66187. return m6[k5];
  66188. } };
  66189. }
  66190. Object.defineProperty(o5, k22, desc);
  66191. } : function(o5, m6, k5, k22) {
  66192. if (k22 === void 0) k22 = k5;
  66193. o5[k22] = m6[k5];
  66194. });
  66195. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  66196. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  66197. } : function(o5, v6) {
  66198. o5["default"] = v6;
  66199. });
  66200. var __importStar = exports && exports.__importStar || function(mod) {
  66201. if (mod && mod.__esModule) return mod;
  66202. var result = {};
  66203. if (mod != null) {
  66204. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  66205. }
  66206. __setModuleDefault(result, mod);
  66207. return result;
  66208. };
  66209. var __importDefault = exports && exports.__importDefault || function(mod) {
  66210. return mod && mod.__esModule ? mod : { "default": mod };
  66211. };
  66212. Object.defineProperty(exports, "__esModule", { value: true });
  66213. exports.Client = exports.BaseClientPool = exports.ClientConnectionHolder = void 0;
  66214. var registry_1 = require_registry();
  66215. var errors = __importStar(require_errors());
  66216. var ifaces_1 = require_ifaces2();
  66217. var options_1 = require_options();
  66218. var event_1 = __importDefault(require_event());
  66219. var queues_1 = require_queues();
  66220. var retry_1 = require_retry();
  66221. var util_1 = require_util3();
  66222. var transaction_1 = require_transaction();
  66223. var utils_1 = require_utils2();
  66224. var ClientConnectionHolder = class {
  66225. constructor(pool) {
  66226. __publicField(this, "_pool");
  66227. __publicField(this, "_connection");
  66228. __publicField(this, "_options");
  66229. __publicField(this, "_inUse");
  66230. this._pool = pool;
  66231. this._connection = null;
  66232. this._options = null;
  66233. this._inUse = null;
  66234. }
  66235. get options() {
  66236. return this._options ?? options_1.Options.defaults();
  66237. }
  66238. async _getConnection() {
  66239. if (!this._connection || this._connection.isClosed()) {
  66240. this._connection = await this._pool.getNewConnection();
  66241. }
  66242. return this._connection;
  66243. }
  66244. get connectionOpen() {
  66245. return this._connection !== null && !this._connection.isClosed();
  66246. }
  66247. async acquire(options) {
  66248. if (this._inUse) {
  66249. throw new errors.InternalClientError("ClientConnectionHolder cannot be acquired, already in use");
  66250. }
  66251. this._options = options;
  66252. this._inUse = new event_1.default();
  66253. return this;
  66254. }
  66255. async release() {
  66256. if (this._inUse === null) {
  66257. throw new errors.ClientError("ClientConnectionHolder.release() called on a free connection holder");
  66258. }
  66259. this._options = null;
  66260. await this._connection?.resetState();
  66261. if (!this._inUse.done) {
  66262. this._inUse.set();
  66263. }
  66264. this._inUse = null;
  66265. this._pool.enqueue(this);
  66266. }
  66267. async _waitUntilReleasedAndClose() {
  66268. if (this._inUse) {
  66269. await this._inUse.wait();
  66270. }
  66271. await this._connection?.close();
  66272. }
  66273. terminate() {
  66274. this._connection?.close();
  66275. }
  66276. async transaction(action) {
  66277. let result;
  66278. let optimisticRepeatableRead = true;
  66279. for (let iteration = 0; ; ++iteration) {
  66280. const transaction = await transaction_1.TransactionImpl._startTransaction(this, optimisticRepeatableRead);
  66281. const clientTx = new transaction_1.Transaction(transaction, this.options);
  66282. let commitFailed = false;
  66283. try {
  66284. result = await Promise.race([
  66285. action(clientTx),
  66286. transaction._waitForConnAbort()
  66287. ]);
  66288. try {
  66289. await transaction._commit();
  66290. } catch (err2) {
  66291. commitFailed = true;
  66292. throw err2;
  66293. }
  66294. } catch (err2) {
  66295. try {
  66296. if (!commitFailed) {
  66297. await transaction._rollback();
  66298. }
  66299. } catch (rollback_err) {
  66300. if (!(rollback_err instanceof errors.GelError)) {
  66301. throw rollback_err;
  66302. }
  66303. }
  66304. if (err2 instanceof errors.CapabilityError && err2.message && err2.message.includes("REPEATABLE READ") && optimisticRepeatableRead) {
  66305. optimisticRepeatableRead = false;
  66306. iteration--;
  66307. continue;
  66308. }
  66309. if (err2 instanceof errors.GelError && err2.hasTag(errors.SHOULD_RETRY) && !(commitFailed && err2 instanceof errors.ClientConnectionError)) {
  66310. const rule = this.options.retryOptions.getRuleForException(err2);
  66311. if (iteration + 1 >= rule.attempts) {
  66312. throw err2;
  66313. }
  66314. await (0, utils_1.sleep)(rule.backoff(iteration + 1));
  66315. continue;
  66316. }
  66317. throw err2;
  66318. }
  66319. return result;
  66320. }
  66321. }
  66322. async retryingFetch(query, args, outputFormat, expectedCardinality, language = ifaces_1.Language.EDGEQL) {
  66323. for (let iteration = 0; ; ++iteration) {
  66324. const conn = await this._getConnection();
  66325. try {
  66326. const { result, warnings } = await conn.fetch(query, args, outputFormat, expectedCardinality, this.options, false, language);
  66327. if (warnings.length) {
  66328. this.options.warningHandler(warnings);
  66329. }
  66330. return result;
  66331. } catch (err2) {
  66332. if (err2 instanceof errors.GelError && err2.hasTag(errors.SHOULD_RETRY) && (conn.getQueryCapabilities(query, outputFormat, expectedCardinality) === 0 || err2 instanceof errors.TransactionConflictError)) {
  66333. const rule = this.options.retryOptions.getRuleForException(err2);
  66334. if (iteration + 1 >= rule.attempts) {
  66335. throw err2;
  66336. }
  66337. await (0, utils_1.sleep)(rule.backoff(iteration + 1));
  66338. continue;
  66339. }
  66340. throw err2;
  66341. }
  66342. }
  66343. }
  66344. async execute(query, args) {
  66345. await this.retryingFetch(query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT);
  66346. }
  66347. async executeSQL(query, args) {
  66348. await this.retryingFetch(query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, ifaces_1.Language.SQL);
  66349. }
  66350. async query(query, args) {
  66351. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY);
  66352. }
  66353. async querySQL(query, args) {
  66354. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, ifaces_1.Language.SQL);
  66355. }
  66356. async queryJSON(query, args) {
  66357. return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.MANY);
  66358. }
  66359. async querySingle(query, args) {
  66360. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_MOST_ONE);
  66361. }
  66362. async querySingleJSON(query, args) {
  66363. return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_MOST_ONE);
  66364. }
  66365. async queryRequired(query, args) {
  66366. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_LEAST_ONE);
  66367. }
  66368. async queryRequiredJSON(query, args) {
  66369. return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_LEAST_ONE);
  66370. }
  66371. async queryRequiredSingle(query, args) {
  66372. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.ONE);
  66373. }
  66374. async queryRequiredSingleJSON(query, args) {
  66375. return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.ONE);
  66376. }
  66377. };
  66378. exports.ClientConnectionHolder = ClientConnectionHolder;
  66379. var BaseClientPool = class {
  66380. constructor(_parseConnectArguments, options) {
  66381. __publicField(this, "_parseConnectArguments");
  66382. __publicField(this, "_closing");
  66383. __publicField(this, "_queue");
  66384. __publicField(this, "_holders");
  66385. __publicField(this, "_userConcurrency");
  66386. __publicField(this, "_suggestedConcurrency");
  66387. __publicField(this, "_connectConfig");
  66388. __publicField(this, "_codecsRegistry");
  66389. __publicField(this, "__normalizedConnectConfig", null);
  66390. this._parseConnectArguments = _parseConnectArguments;
  66391. this.validateClientOptions(options);
  66392. this._codecsRegistry = new registry_1.CodecsRegistry();
  66393. this._queue = new queues_1.LifoQueue();
  66394. this._holders = [];
  66395. this._userConcurrency = options.concurrency ?? null;
  66396. this._suggestedConcurrency = null;
  66397. this._closing = null;
  66398. this._connectConfig = { ...options };
  66399. this._resizeHolderPool();
  66400. }
  66401. validateClientOptions(opts) {
  66402. if (opts.concurrency != null && (typeof opts.concurrency !== "number" || !Number.isInteger(opts.concurrency) || opts.concurrency < 0)) {
  66403. throw new errors.InterfaceError(`invalid 'concurrency' value: expected integer greater than 0 (got ${JSON.stringify(opts.concurrency)})`);
  66404. }
  66405. }
  66406. _getStats() {
  66407. return {
  66408. queueLength: this._queue.pending,
  66409. openConnections: this._holders.filter((holder) => holder.connectionOpen).length
  66410. };
  66411. }
  66412. async ensureConnected() {
  66413. if (this._closing) {
  66414. throw new errors.InterfaceError(this._closing.done ? "The client is closed" : "The client is closing");
  66415. }
  66416. if (this._getStats().openConnections > 0) {
  66417. return;
  66418. }
  66419. const connHolder = await this._queue.get();
  66420. try {
  66421. await connHolder._getConnection();
  66422. } finally {
  66423. this._queue.push(connHolder);
  66424. }
  66425. }
  66426. get _concurrency() {
  66427. return this._userConcurrency ?? this._suggestedConcurrency ?? 1;
  66428. }
  66429. _resizeHolderPool() {
  66430. const holdersDiff = this._concurrency - this._holders.length;
  66431. if (holdersDiff > 0) {
  66432. for (let i6 = 0; i6 < holdersDiff; i6++) {
  66433. const connectionHolder = new ClientConnectionHolder(this);
  66434. this._holders.push(connectionHolder);
  66435. this._queue.push(connectionHolder);
  66436. }
  66437. } else if (holdersDiff < 0) {
  66438. }
  66439. }
  66440. _getNormalizedConnectConfig() {
  66441. return this.__normalizedConnectConfig ?? (this.__normalizedConnectConfig = this._parseConnectArguments(this._connectConfig));
  66442. }
  66443. async resolveConnectionParams() {
  66444. const config = await this._getNormalizedConnectConfig();
  66445. return config.connectionParams;
  66446. }
  66447. async getNewConnection() {
  66448. if (this._closing?.done) {
  66449. throw new errors.InterfaceError("The client is closed");
  66450. }
  66451. const config = await this._getNormalizedConnectConfig();
  66452. const connection = await (0, retry_1.retryingConnect)(this._connectWithTimeout, config, this._codecsRegistry);
  66453. const suggestedConcurrency = connection.serverSettings.suggested_pool_concurrency;
  66454. if (suggestedConcurrency && suggestedConcurrency !== this._suggestedConcurrency) {
  66455. this._suggestedConcurrency = suggestedConcurrency;
  66456. this._resizeHolderPool();
  66457. }
  66458. return connection;
  66459. }
  66460. async acquireHolder(options) {
  66461. if (this._closing) {
  66462. throw new errors.InterfaceError(this._closing.done ? "The client is closed" : "The client is closing");
  66463. }
  66464. const connectionHolder = await this._queue.get();
  66465. try {
  66466. return await connectionHolder.acquire(options);
  66467. } catch (error2) {
  66468. this._queue.push(connectionHolder);
  66469. throw error2;
  66470. }
  66471. }
  66472. enqueue(holder) {
  66473. this._queue.push(holder);
  66474. }
  66475. async close() {
  66476. if (this._closing) {
  66477. return await this._closing.wait();
  66478. }
  66479. this._closing = new event_1.default();
  66480. this._queue.cancelAllPending(new errors.InterfaceError(`The client is closing`));
  66481. const warningTimeoutId = setTimeout(() => {
  66482. console.warn("Client.close() is taking over 60 seconds to complete. Check if you have any unreleased connections left.");
  66483. }, 6e4);
  66484. try {
  66485. await Promise.all(this._holders.map((connectionHolder) => connectionHolder._waitUntilReleasedAndClose()));
  66486. } catch (err2) {
  66487. this._terminate();
  66488. this._closing.setError(err2);
  66489. throw err2;
  66490. } finally {
  66491. clearTimeout(warningTimeoutId);
  66492. }
  66493. this._closing.set();
  66494. }
  66495. _terminate() {
  66496. for (const connectionHolder of this._holders) {
  66497. connectionHolder.terminate();
  66498. }
  66499. }
  66500. terminate() {
  66501. if (this._closing?.done) {
  66502. return;
  66503. }
  66504. this._queue.cancelAllPending(new errors.InterfaceError(`The client is closed`));
  66505. this._terminate();
  66506. if (!this._closing) {
  66507. this._closing = new event_1.default();
  66508. this._closing.set();
  66509. }
  66510. }
  66511. isClosed() {
  66512. return !!this._closing;
  66513. }
  66514. };
  66515. exports.BaseClientPool = BaseClientPool;
  66516. var Client2 = class _Client {
  66517. constructor(pool, options) {
  66518. __publicField(this, "pool");
  66519. __publicField(this, "options");
  66520. this.pool = pool;
  66521. this.options = options;
  66522. }
  66523. withTransactionOptions(opts) {
  66524. return new _Client(this.pool, this.options.withTransactionOptions(opts));
  66525. }
  66526. withRetryOptions(opts) {
  66527. return new _Client(this.pool, this.options.withRetryOptions(opts));
  66528. }
  66529. withModuleAliases(aliases) {
  66530. return new _Client(this.pool, this.options.withModuleAliases(aliases));
  66531. }
  66532. withConfig(config) {
  66533. return new _Client(this.pool, this.options.withConfig(config));
  66534. }
  66535. withCodecs(codecs) {
  66536. return new _Client(this.pool, this.options.withCodecs(codecs));
  66537. }
  66538. withSQLRowMode(mode) {
  66539. return new _Client(this.pool, this.options.withSQLRowMode(mode));
  66540. }
  66541. withGlobals(globals) {
  66542. return new _Client(this.pool, this.options.withGlobals(globals));
  66543. }
  66544. withQueryTag(tag) {
  66545. return new _Client(this.pool, this.options.withQueryTag(tag));
  66546. }
  66547. withWarningHandler(handler) {
  66548. return new _Client(this.pool, this.options.withWarningHandler(handler));
  66549. }
  66550. async ensureConnected() {
  66551. await this.pool.ensureConnected();
  66552. return this;
  66553. }
  66554. async resolveConnectionParams() {
  66555. return this.pool.resolveConnectionParams();
  66556. }
  66557. isClosed() {
  66558. return this.pool.isClosed();
  66559. }
  66560. async close() {
  66561. await this.pool.close();
  66562. }
  66563. terminate() {
  66564. this.pool.terminate();
  66565. }
  66566. async transaction(action) {
  66567. if (this.pool.isStateless) {
  66568. throw new errors.GelError(`cannot use 'transaction()' API on HTTP client`);
  66569. }
  66570. const holder = await this.pool.acquireHolder(this.options);
  66571. try {
  66572. return await holder.transaction(action);
  66573. } finally {
  66574. await holder.release();
  66575. }
  66576. }
  66577. async execute(query, args) {
  66578. const holder = await this.pool.acquireHolder(this.options);
  66579. try {
  66580. return await holder.execute(query, args);
  66581. } finally {
  66582. await holder.release();
  66583. }
  66584. }
  66585. async executeSQL(query, args) {
  66586. const holder = await this.pool.acquireHolder(this.options);
  66587. try {
  66588. return await holder.executeSQL(query, args);
  66589. } finally {
  66590. await holder.release();
  66591. }
  66592. }
  66593. async query(query, args) {
  66594. const holder = await this.pool.acquireHolder(this.options);
  66595. try {
  66596. return await holder.query(query, args);
  66597. } finally {
  66598. await holder.release();
  66599. }
  66600. }
  66601. async querySQL(query, args) {
  66602. const holder = await this.pool.acquireHolder(this.options);
  66603. try {
  66604. return await holder.querySQL(query, args);
  66605. } finally {
  66606. await holder.release();
  66607. }
  66608. }
  66609. async queryJSON(query, args) {
  66610. const holder = await this.pool.acquireHolder(this.options);
  66611. try {
  66612. return await holder.queryJSON(query, args);
  66613. } finally {
  66614. await holder.release();
  66615. }
  66616. }
  66617. async querySingle(query, args) {
  66618. const holder = await this.pool.acquireHolder(this.options);
  66619. try {
  66620. return await holder.querySingle(query, args);
  66621. } finally {
  66622. await holder.release();
  66623. }
  66624. }
  66625. async querySingleJSON(query, args) {
  66626. const holder = await this.pool.acquireHolder(this.options);
  66627. try {
  66628. return await holder.querySingleJSON(query, args);
  66629. } finally {
  66630. await holder.release();
  66631. }
  66632. }
  66633. async queryRequired(query, args) {
  66634. const holder = await this.pool.acquireHolder(this.options);
  66635. try {
  66636. return await holder.queryRequired(query, args);
  66637. } finally {
  66638. await holder.release();
  66639. }
  66640. }
  66641. async queryRequiredJSON(query, args) {
  66642. const holder = await this.pool.acquireHolder(this.options);
  66643. try {
  66644. return await holder.queryRequiredJSON(query, args);
  66645. } finally {
  66646. await holder.release();
  66647. }
  66648. }
  66649. async queryRequiredSingle(query, args) {
  66650. const holder = await this.pool.acquireHolder(this.options);
  66651. try {
  66652. return await holder.queryRequiredSingle(query, args);
  66653. } finally {
  66654. await holder.release();
  66655. }
  66656. }
  66657. async queryRequiredSingleJSON(query, args) {
  66658. const holder = await this.pool.acquireHolder(this.options);
  66659. try {
  66660. return await holder.queryRequiredSingleJSON(query, args);
  66661. } finally {
  66662. await holder.release();
  66663. }
  66664. }
  66665. async describe(query) {
  66666. const holder = await this.pool.acquireHolder(this.options);
  66667. try {
  66668. const cxn = await holder._getConnection();
  66669. const result = await cxn._parse(ifaces_1.Language.EDGEQL, query, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options);
  66670. const cardinality = util_1.util.parseCardinality(result[0]);
  66671. return {
  66672. in: result[1],
  66673. out: result[2],
  66674. cardinality,
  66675. capabilities: result[3]
  66676. };
  66677. } finally {
  66678. await holder.release();
  66679. }
  66680. }
  66681. async parse(query) {
  66682. return await this.describe(query);
  66683. }
  66684. };
  66685. exports.Client = Client2;
  66686. }
  66687. });
  66688. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/systemUtils.js
  66689. var require_systemUtils = __commonJS({
  66690. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/systemUtils.js"(exports) {
  66691. "use strict";
  66692. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  66693. if (k22 === void 0) k22 = k5;
  66694. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  66695. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  66696. desc = { enumerable: true, get: function() {
  66697. return m6[k5];
  66698. } };
  66699. }
  66700. Object.defineProperty(o5, k22, desc);
  66701. } : function(o5, m6, k5, k22) {
  66702. if (k22 === void 0) k22 = k5;
  66703. o5[k22] = m6[k5];
  66704. });
  66705. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  66706. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  66707. } : function(o5, v6) {
  66708. o5["default"] = v6;
  66709. });
  66710. var __importStar = exports && exports.__importStar || function(mod) {
  66711. if (mod && mod.__esModule) return mod;
  66712. var result = {};
  66713. if (mod != null) {
  66714. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  66715. }
  66716. __setModuleDefault(result, mod);
  66717. return result;
  66718. };
  66719. var __importDefault = exports && exports.__importDefault || function(mod) {
  66720. return mod && mod.__esModule ? mod : { "default": mod };
  66721. };
  66722. Object.defineProperty(exports, "__esModule", { value: true });
  66723. exports.readFileUtf8 = readFileUtf8;
  66724. exports.hasFSReadPermission = hasFSReadPermission;
  66725. exports.hashSHA1toHex = hashSHA1toHex;
  66726. exports.walk = walk;
  66727. exports.exists = exists;
  66728. exports.input = input;
  66729. var crypto5 = __importStar(__require("crypto"));
  66730. var node_fs_1 = __require("fs");
  66731. var node_path_1 = __importDefault(__require("path"));
  66732. var node_process_1 = __importDefault(__require("process"));
  66733. var readline = __importStar(__require("readline"));
  66734. var node_stream_1 = __require("stream");
  66735. async function readFileUtf8(...pathParts) {
  66736. return await node_fs_1.promises.readFile(node_path_1.default.join(...pathParts), { encoding: "utf8" });
  66737. }
  66738. function hasFSReadPermission() {
  66739. if (typeof Deno !== "undefined") {
  66740. return Deno.permissions.querySync({ name: "read" }).state === "granted";
  66741. }
  66742. return true;
  66743. }
  66744. function hashSHA1toHex(msg) {
  66745. return crypto5.createHash("sha1").update(msg).digest("hex");
  66746. }
  66747. async function walk(dir, params) {
  66748. const { match: match2, skip = [] } = params || {};
  66749. try {
  66750. await node_fs_1.promises.access(dir);
  66751. } catch (_err) {
  66752. return [];
  66753. }
  66754. const dirents = await node_fs_1.promises.readdir(dir, { withFileTypes: true });
  66755. const files = await Promise.all(dirents.map((dirent) => {
  66756. const fspath = node_path_1.default.resolve(dir, dirent.name);
  66757. if (skip) {
  66758. if (skip.some((re) => re.test(fspath))) {
  66759. return [];
  66760. }
  66761. }
  66762. if (dirent.isDirectory()) {
  66763. return walk(fspath, params);
  66764. }
  66765. if (match2) {
  66766. if (!match2.some((re) => re.test(fspath))) {
  66767. return [];
  66768. }
  66769. }
  66770. return [fspath];
  66771. }));
  66772. return Array.prototype.concat(...files);
  66773. }
  66774. async function exists(filepath) {
  66775. try {
  66776. await node_fs_1.promises.access(filepath);
  66777. return true;
  66778. } catch {
  66779. return false;
  66780. }
  66781. }
  66782. async function input(message, params) {
  66783. let silent = false;
  66784. const output = params?.silent ? new node_stream_1.Writable({
  66785. write(chunk, encoding, callback) {
  66786. if (!silent)
  66787. node_process_1.default.stdout.write(chunk, encoding);
  66788. callback();
  66789. }
  66790. }) : node_process_1.default.stdout;
  66791. const rl = readline.createInterface({
  66792. input: node_process_1.default.stdin,
  66793. output
  66794. });
  66795. return new Promise((resolve) => {
  66796. rl.question(message, (val2) => {
  66797. rl.close();
  66798. resolve(val2);
  66799. });
  66800. silent = true;
  66801. });
  66802. }
  66803. }
  66804. });
  66805. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/platform.js
  66806. var require_platform = __commonJS({
  66807. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/platform.js"(exports) {
  66808. "use strict";
  66809. var __importDefault = exports && exports.__importDefault || function(mod) {
  66810. return mod && mod.__esModule ? mod : { "default": mod };
  66811. };
  66812. Object.defineProperty(exports, "__esModule", { value: true });
  66813. exports.isWindows = void 0;
  66814. exports.searchConfigDir = searchConfigDir;
  66815. var node_path_1 = __importDefault(__require("path"));
  66816. var node_os_1 = __importDefault(__require("os"));
  66817. var systemUtils_1 = require_systemUtils();
  66818. exports.isWindows = process.platform === "win32";
  66819. var homeDir = node_os_1.default.homedir;
  66820. var _configDir;
  66821. if (process.platform === "darwin") {
  66822. _configDir = () => {
  66823. return node_path_1.default.join(homeDir(), "Library", "Application Support", "edgedb");
  66824. };
  66825. } else if (process.platform === "win32") {
  66826. _configDir = () => {
  66827. const localAppDataDir = process.env.LOCALAPPDATA ?? node_path_1.default.join(homeDir(), "AppData", "Local");
  66828. return node_path_1.default.join(localAppDataDir, "EdgeDB", "config");
  66829. };
  66830. } else {
  66831. _configDir = () => {
  66832. let xdgConfigDir = process.env.XDG_CONFIG_HOME;
  66833. if (!xdgConfigDir || !node_path_1.default.isAbsolute(xdgConfigDir)) {
  66834. xdgConfigDir = node_path_1.default.join(homeDir(), ".config");
  66835. }
  66836. return node_path_1.default.join(xdgConfigDir, "edgedb");
  66837. };
  66838. }
  66839. async function searchConfigDir(...configPath) {
  66840. const filePath = node_path_1.default.join(_configDir(), ...configPath);
  66841. if (await (0, systemUtils_1.exists)(filePath)) {
  66842. return filePath;
  66843. }
  66844. const fallbackPath = node_path_1.default.join(homeDir(), ".edgedb", ...configPath);
  66845. if (await (0, systemUtils_1.exists)(fallbackPath)) {
  66846. return fallbackPath;
  66847. }
  66848. return filePath;
  66849. }
  66850. }
  66851. });
  66852. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/credentials.js
  66853. var require_credentials = __commonJS({
  66854. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/credentials.js"(exports) {
  66855. "use strict";
  66856. Object.defineProperty(exports, "__esModule", { value: true });
  66857. exports.getCredentialsPath = getCredentialsPath;
  66858. exports.readCredentialsFile = readCredentialsFile;
  66859. exports.validateCredentials = validateCredentials;
  66860. var conUtils_1 = require_conUtils();
  66861. var errors_1 = require_errors();
  66862. async function getCredentialsPath(instanceName, serverUtils) {
  66863. return serverUtils.searchConfigDir("credentials", instanceName + ".json");
  66864. }
  66865. async function readCredentialsFile(file, serverUtils) {
  66866. try {
  66867. const data = await serverUtils.readFileUtf8(file);
  66868. return validateCredentials(JSON.parse(data));
  66869. } catch (e6) {
  66870. throw new errors_1.InterfaceError(`cannot read credentials file ${file}: ${e6}`);
  66871. }
  66872. }
  66873. function validateCredentials(data) {
  66874. const port = data.port;
  66875. if (port != null && (typeof port !== "number" || port < 1 || port > 65535)) {
  66876. throw new errors_1.InterfaceError("invalid `port` value");
  66877. }
  66878. const user = data.user;
  66879. if (user == null) {
  66880. throw new errors_1.InterfaceError("`user` key is required");
  66881. }
  66882. if (typeof user !== "string") {
  66883. throw new errors_1.InterfaceError("`user` must be string");
  66884. }
  66885. const result = { user, port };
  66886. const host = data.host;
  66887. if (host != null) {
  66888. if (typeof host !== "string") {
  66889. throw new errors_1.InterfaceError("`host` must be string");
  66890. }
  66891. result.host = host;
  66892. }
  66893. const database = data.database;
  66894. if (database != null) {
  66895. if (typeof database !== "string") {
  66896. throw new errors_1.InterfaceError("`database` must be string");
  66897. }
  66898. result.database = database;
  66899. }
  66900. const branch = data.branch;
  66901. if (branch != null) {
  66902. if (typeof branch !== "string") {
  66903. throw new errors_1.InterfaceError("`branch` must be string");
  66904. }
  66905. if (database != null && branch !== database) {
  66906. throw new errors_1.InterfaceError("`database` and `branch` cannot both be set");
  66907. }
  66908. result.branch = branch;
  66909. }
  66910. const password = data.password;
  66911. if (password != null) {
  66912. if (typeof password !== "string") {
  66913. throw new errors_1.InterfaceError("`password` must be string");
  66914. }
  66915. result.password = password;
  66916. }
  66917. const caData = data.tls_ca;
  66918. if (caData != null) {
  66919. if (typeof caData !== "string") {
  66920. throw new errors_1.InterfaceError("`tls_ca` must be string");
  66921. }
  66922. result.tlsCAData = caData;
  66923. }
  66924. const certData = data.tls_cert_data;
  66925. if (certData != null) {
  66926. if (typeof certData !== "string") {
  66927. throw new errors_1.InterfaceError("`tls_cert_data` must be string");
  66928. }
  66929. if (caData != null && certData !== caData) {
  66930. throw new errors_1.InterfaceError(`both 'tls_ca' and 'tls_cert_data' are defined, and are not in agreement`);
  66931. }
  66932. result.tlsCAData = certData;
  66933. }
  66934. let verifyHostname = data.tls_verify_hostname;
  66935. const tlsSecurity = data.tls_security;
  66936. if (verifyHostname != null) {
  66937. if (typeof verifyHostname === "boolean") {
  66938. verifyHostname = verifyHostname ? "strict" : "no_host_verification";
  66939. } else {
  66940. throw new errors_1.InterfaceError("`tls_verify_hostname` must be boolean");
  66941. }
  66942. }
  66943. if (tlsSecurity != null && (typeof tlsSecurity !== "string" || !conUtils_1.validTlsSecurityValues.includes(tlsSecurity))) {
  66944. throw new errors_1.InterfaceError(`\`tls_security\` must be one of ${conUtils_1.validTlsSecurityValues.map((val2) => `"${val2}"`).join(", ")}`);
  66945. }
  66946. if (verifyHostname && tlsSecurity && verifyHostname !== tlsSecurity && !(verifyHostname === "no_host_verification" && tlsSecurity === "insecure")) {
  66947. throw new errors_1.InterfaceError(`both 'tls_security' and 'tls_verify_hostname' are defined, and are not in agreement`);
  66948. }
  66949. if (tlsSecurity || verifyHostname) {
  66950. result.tlsSecurity = tlsSecurity ?? verifyHostname;
  66951. }
  66952. return result;
  66953. }
  66954. }
  66955. });
  66956. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/crcHqx.js
  66957. var require_crcHqx = __commonJS({
  66958. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/crcHqx.js"(exports) {
  66959. "use strict";
  66960. Object.defineProperty(exports, "__esModule", { value: true });
  66961. exports.crcHqx = crcHqx;
  66962. var crctabHqx = new Uint16Array([
  66963. 0,
  66964. 4129,
  66965. 8258,
  66966. 12387,
  66967. 16516,
  66968. 20645,
  66969. 24774,
  66970. 28903,
  66971. 33032,
  66972. 37161,
  66973. 41290,
  66974. 45419,
  66975. 49548,
  66976. 53677,
  66977. 57806,
  66978. 61935,
  66979. 4657,
  66980. 528,
  66981. 12915,
  66982. 8786,
  66983. 21173,
  66984. 17044,
  66985. 29431,
  66986. 25302,
  66987. 37689,
  66988. 33560,
  66989. 45947,
  66990. 41818,
  66991. 54205,
  66992. 50076,
  66993. 62463,
  66994. 58334,
  66995. 9314,
  66996. 13379,
  66997. 1056,
  66998. 5121,
  66999. 25830,
  67000. 29895,
  67001. 17572,
  67002. 21637,
  67003. 42346,
  67004. 46411,
  67005. 34088,
  67006. 38153,
  67007. 58862,
  67008. 62927,
  67009. 50604,
  67010. 54669,
  67011. 13907,
  67012. 9842,
  67013. 5649,
  67014. 1584,
  67015. 30423,
  67016. 26358,
  67017. 22165,
  67018. 18100,
  67019. 46939,
  67020. 42874,
  67021. 38681,
  67022. 34616,
  67023. 63455,
  67024. 59390,
  67025. 55197,
  67026. 51132,
  67027. 18628,
  67028. 22757,
  67029. 26758,
  67030. 30887,
  67031. 2112,
  67032. 6241,
  67033. 10242,
  67034. 14371,
  67035. 51660,
  67036. 55789,
  67037. 59790,
  67038. 63919,
  67039. 35144,
  67040. 39273,
  67041. 43274,
  67042. 47403,
  67043. 23285,
  67044. 19156,
  67045. 31415,
  67046. 27286,
  67047. 6769,
  67048. 2640,
  67049. 14899,
  67050. 10770,
  67051. 56317,
  67052. 52188,
  67053. 64447,
  67054. 60318,
  67055. 39801,
  67056. 35672,
  67057. 47931,
  67058. 43802,
  67059. 27814,
  67060. 31879,
  67061. 19684,
  67062. 23749,
  67063. 11298,
  67064. 15363,
  67065. 3168,
  67066. 7233,
  67067. 60846,
  67068. 64911,
  67069. 52716,
  67070. 56781,
  67071. 44330,
  67072. 48395,
  67073. 36200,
  67074. 40265,
  67075. 32407,
  67076. 28342,
  67077. 24277,
  67078. 20212,
  67079. 15891,
  67080. 11826,
  67081. 7761,
  67082. 3696,
  67083. 65439,
  67084. 61374,
  67085. 57309,
  67086. 53244,
  67087. 48923,
  67088. 44858,
  67089. 40793,
  67090. 36728,
  67091. 37256,
  67092. 33193,
  67093. 45514,
  67094. 41451,
  67095. 53516,
  67096. 49453,
  67097. 61774,
  67098. 57711,
  67099. 4224,
  67100. 161,
  67101. 12482,
  67102. 8419,
  67103. 20484,
  67104. 16421,
  67105. 28742,
  67106. 24679,
  67107. 33721,
  67108. 37784,
  67109. 41979,
  67110. 46042,
  67111. 49981,
  67112. 54044,
  67113. 58239,
  67114. 62302,
  67115. 689,
  67116. 4752,
  67117. 8947,
  67118. 13010,
  67119. 16949,
  67120. 21012,
  67121. 25207,
  67122. 29270,
  67123. 46570,
  67124. 42443,
  67125. 38312,
  67126. 34185,
  67127. 62830,
  67128. 58703,
  67129. 54572,
  67130. 50445,
  67131. 13538,
  67132. 9411,
  67133. 5280,
  67134. 1153,
  67135. 29798,
  67136. 25671,
  67137. 21540,
  67138. 17413,
  67139. 42971,
  67140. 47098,
  67141. 34713,
  67142. 38840,
  67143. 59231,
  67144. 63358,
  67145. 50973,
  67146. 55100,
  67147. 9939,
  67148. 14066,
  67149. 1681,
  67150. 5808,
  67151. 26199,
  67152. 30326,
  67153. 17941,
  67154. 22068,
  67155. 55628,
  67156. 51565,
  67157. 63758,
  67158. 59695,
  67159. 39368,
  67160. 35305,
  67161. 47498,
  67162. 43435,
  67163. 22596,
  67164. 18533,
  67165. 30726,
  67166. 26663,
  67167. 6336,
  67168. 2273,
  67169. 14466,
  67170. 10403,
  67171. 52093,
  67172. 56156,
  67173. 60223,
  67174. 64286,
  67175. 35833,
  67176. 39896,
  67177. 43963,
  67178. 48026,
  67179. 19061,
  67180. 23124,
  67181. 27191,
  67182. 31254,
  67183. 2801,
  67184. 6864,
  67185. 10931,
  67186. 14994,
  67187. 64814,
  67188. 60687,
  67189. 56684,
  67190. 52557,
  67191. 48554,
  67192. 44427,
  67193. 40424,
  67194. 36297,
  67195. 31782,
  67196. 27655,
  67197. 23652,
  67198. 19525,
  67199. 15522,
  67200. 11395,
  67201. 7392,
  67202. 3265,
  67203. 61215,
  67204. 65342,
  67205. 53085,
  67206. 57212,
  67207. 44955,
  67208. 49082,
  67209. 36825,
  67210. 40952,
  67211. 28183,
  67212. 32310,
  67213. 20053,
  67214. 24180,
  67215. 11923,
  67216. 16050,
  67217. 3793,
  67218. 7920
  67219. ]);
  67220. function crcHqx(data, crc) {
  67221. crc &= 65535;
  67222. const len = data.length;
  67223. let i6 = 0;
  67224. while (i6 < len) {
  67225. crc = crc << 8 & 65280 ^ crctabHqx[crc >> 8 ^ data[i6++]];
  67226. }
  67227. return crc;
  67228. }
  67229. }
  67230. });
  67231. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.js
  67232. var require_conUtils = __commonJS({
  67233. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.js"(exports) {
  67234. "use strict";
  67235. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  67236. if (k22 === void 0) k22 = k5;
  67237. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  67238. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  67239. desc = { enumerable: true, get: function() {
  67240. return m6[k5];
  67241. } };
  67242. }
  67243. Object.defineProperty(o5, k22, desc);
  67244. } : function(o5, m6, k5, k22) {
  67245. if (k22 === void 0) k22 = k5;
  67246. o5[k22] = m6[k5];
  67247. });
  67248. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  67249. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  67250. } : function(o5, v6) {
  67251. o5["default"] = v6;
  67252. });
  67253. var __importStar = exports && exports.__importStar || function(mod) {
  67254. if (mod && mod.__esModule) return mod;
  67255. var result = {};
  67256. if (mod != null) {
  67257. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  67258. }
  67259. __setModuleDefault(result, mod);
  67260. return result;
  67261. };
  67262. Object.defineProperty(exports, "__esModule", { value: true });
  67263. exports.ResolvedConnectConfig = exports.validTlsSecurityValues = void 0;
  67264. exports.isValidTlsSecurityValue = isValidTlsSecurityValue;
  67265. exports.getConnectArgumentsParser = getConnectArgumentsParser;
  67266. exports.parseDuration = parseDuration;
  67267. var errors = __importStar(require_errors());
  67268. var credentials_1 = require_credentials();
  67269. var datetime_1 = require_datetime();
  67270. var datetime_2 = require_datetime2();
  67271. var errors_1 = require_errors();
  67272. var buffer_1 = require_buffer();
  67273. var crcHqx_1 = require_crcHqx();
  67274. var DOMAIN_NAME_MAX_LEN = 63;
  67275. exports.validTlsSecurityValues = [
  67276. "insecure",
  67277. "no_host_verification",
  67278. "strict",
  67279. "default"
  67280. ];
  67281. function isValidTlsSecurityValue(candidate) {
  67282. return typeof candidate === "string" && exports.validTlsSecurityValues.includes(candidate);
  67283. }
  67284. function getConnectArgumentsParser(utils) {
  67285. return async (opts) => {
  67286. return {
  67287. ...await parseConnectDsnAndArgs(opts, utils),
  67288. connectTimeout: opts.timeout,
  67289. logging: opts.logging ?? true
  67290. };
  67291. };
  67292. }
  67293. function getEnv(envName, _required = false) {
  67294. const gelEnv = envName;
  67295. const edgedbEnv = envName.replace(/^GEL_/, "EDGEDB_");
  67296. const gelValue = process.env[gelEnv];
  67297. const edgedbValue = process.env[edgedbEnv];
  67298. if (gelValue !== void 0 && edgedbValue !== void 0) {
  67299. console.warn(`Both GEL_w+ and EDGEDB_w+ are set; EDGEDB_w+ will be ignored`);
  67300. }
  67301. return gelValue ?? edgedbValue;
  67302. }
  67303. var ResolvedConnectConfig = class {
  67304. constructor() {
  67305. __publicField(this, "_host", null);
  67306. __publicField(this, "_hostSource", null);
  67307. __publicField(this, "_port", null);
  67308. __publicField(this, "_portSource", null);
  67309. __publicField(this, "_database", null);
  67310. __publicField(this, "_databaseSource", null);
  67311. __publicField(this, "_branch", null);
  67312. __publicField(this, "_branchSource", null);
  67313. __publicField(this, "_user", null);
  67314. __publicField(this, "_userSource", null);
  67315. __publicField(this, "_password", null);
  67316. __publicField(this, "_passwordSource", null);
  67317. __publicField(this, "_secretKey", null);
  67318. __publicField(this, "_secretKeySource", null);
  67319. __publicField(this, "_cloudProfile", null);
  67320. __publicField(this, "_cloudProfileSource", null);
  67321. __publicField(this, "_tlsCAData", null);
  67322. __publicField(this, "_tlsCADataSource", null);
  67323. __publicField(this, "_tlsSecurity", null);
  67324. __publicField(this, "_tlsSecuritySource", null);
  67325. __publicField(this, "_tlsServerName", null);
  67326. __publicField(this, "_tlsServerNameSource", null);
  67327. __publicField(this, "_waitUntilAvailable", null);
  67328. __publicField(this, "_waitUntilAvailableSource", null);
  67329. __publicField(this, "serverSettings", {});
  67330. this.setHost = this.setHost.bind(this);
  67331. this.setPort = this.setPort.bind(this);
  67332. this.setDatabase = this.setDatabase.bind(this);
  67333. this.setBranch = this.setBranch.bind(this);
  67334. this.setUser = this.setUser.bind(this);
  67335. this.setPassword = this.setPassword.bind(this);
  67336. this.setSecretKey = this.setSecretKey.bind(this);
  67337. this.setTlsCAData = this.setTlsCAData.bind(this);
  67338. this.setTlsCAFile = this.setTlsCAFile.bind(this);
  67339. this.setTlsServerName = this.setTlsServerName.bind(this);
  67340. this.setTlsSecurity = this.setTlsSecurity.bind(this);
  67341. this.setWaitUntilAvailable = this.setWaitUntilAvailable.bind(this);
  67342. }
  67343. _setParam(param, value, source, validator2) {
  67344. if (this[`_${param}`] === null) {
  67345. this[`_${param}Source`] = source;
  67346. if (value !== null) {
  67347. this[`_${param}`] = validator2 ? validator2(value) : value;
  67348. return true;
  67349. }
  67350. }
  67351. return false;
  67352. }
  67353. async _setParamAsync(param, value, source, validator2) {
  67354. if (this[`_${param}`] === null) {
  67355. this[`_${param}Source`] = source;
  67356. if (value !== null) {
  67357. this[`_${param}`] = validator2 ? await validator2(value) : value;
  67358. return true;
  67359. }
  67360. }
  67361. return false;
  67362. }
  67363. setHost(host, source) {
  67364. return this._setParam("host", host, source, validateHost);
  67365. }
  67366. setPort(port, source) {
  67367. return this._setParam("port", port, source, parseValidatePort);
  67368. }
  67369. setDatabase(database, source) {
  67370. return this._setParam("database", database, source, (db) => {
  67371. if (db === "") {
  67372. throw new errors_1.InterfaceError(`invalid database name: '${db}'`);
  67373. }
  67374. return db;
  67375. });
  67376. }
  67377. setBranch(branch, source) {
  67378. return this._setParam("branch", branch, source, (branchName) => {
  67379. if (branchName === "") {
  67380. throw new errors_1.InterfaceError(`invalid branch name: '${branchName}'`);
  67381. }
  67382. return branchName;
  67383. });
  67384. }
  67385. setUser(user, source) {
  67386. return this._setParam("user", user, source, (_user) => {
  67387. if (_user === "") {
  67388. throw new errors_1.InterfaceError(`invalid user name: '${_user}'`);
  67389. }
  67390. return _user;
  67391. });
  67392. }
  67393. setPassword(password, source) {
  67394. return this._setParam("password", password, source);
  67395. }
  67396. setSecretKey(secretKey, source) {
  67397. return this._setParam("secretKey", secretKey, source);
  67398. }
  67399. setCloudProfile(cloudProfile, source) {
  67400. return this._setParam("cloudProfile", cloudProfile, source);
  67401. }
  67402. setTlsCAData(caData, source) {
  67403. return this._setParam("tlsCAData", caData, source);
  67404. }
  67405. setTlsCAFile(caFile, source, readFile4) {
  67406. return this._setParamAsync("tlsCAData", caFile, source, (caFilePath) => readFile4(caFilePath));
  67407. }
  67408. setTlsServerName(serverName, source) {
  67409. return this._setParam("tlsServerName", serverName, source, validateHost);
  67410. }
  67411. setTlsSecurity(tlsSecurity, source) {
  67412. return this._setParam("tlsSecurity", tlsSecurity, source, (_tlsSecurity) => {
  67413. if (!exports.validTlsSecurityValues.includes(_tlsSecurity)) {
  67414. throw new errors_1.InterfaceError(`invalid 'tlsSecurity' value: '${_tlsSecurity}', must be one of ${exports.validTlsSecurityValues.map((val2) => `'${val2}'`).join(", ")}`);
  67415. }
  67416. const clientSecurity = getEnv("GEL_CLIENT_SECURITY");
  67417. if (clientSecurity !== void 0) {
  67418. if (!["default", "insecure_dev_mode", "strict"].includes(clientSecurity)) {
  67419. throw new errors_1.InterfaceError(`invalid GEL_CLIENT_SECURITY value: '${clientSecurity}', must be one of 'default', 'insecure_dev_mode' or 'strict'`);
  67420. }
  67421. if (clientSecurity === "insecure_dev_mode") {
  67422. if (_tlsSecurity === "default") {
  67423. _tlsSecurity = "insecure";
  67424. }
  67425. } else if (clientSecurity === "strict") {
  67426. if (_tlsSecurity === "insecure" || _tlsSecurity === "no_host_verification") {
  67427. throw new errors_1.InterfaceError(`'tlsSecurity' value (${_tlsSecurity}) conflicts with GEL_CLIENT_SECURITY value (${clientSecurity}), 'tlsSecurity' value cannot be lower than security level set by GEL_CLIENT_SECURITY`);
  67428. }
  67429. _tlsSecurity = "strict";
  67430. }
  67431. }
  67432. return _tlsSecurity;
  67433. });
  67434. }
  67435. setWaitUntilAvailable(duration, source) {
  67436. return this._setParam("waitUntilAvailable", duration, source, parseDuration);
  67437. }
  67438. addServerSettings(settings) {
  67439. this.serverSettings = {
  67440. ...settings,
  67441. ...this.serverSettings
  67442. };
  67443. }
  67444. get address() {
  67445. return [this._host ?? "localhost", this._port ?? 5656];
  67446. }
  67447. get database() {
  67448. return this._database ?? this._branch ?? "edgedb";
  67449. }
  67450. get branch() {
  67451. return this._branch ?? this._database ?? "__default__";
  67452. }
  67453. get user() {
  67454. return this._user ?? "edgedb";
  67455. }
  67456. get password() {
  67457. return this._password ?? void 0;
  67458. }
  67459. get secretKey() {
  67460. return this._secretKey ?? void 0;
  67461. }
  67462. get cloudProfile() {
  67463. return this._cloudProfile ?? "default";
  67464. }
  67465. get tlsServerName() {
  67466. return this._tlsServerName ?? void 0;
  67467. }
  67468. get tlsSecurity() {
  67469. return this._tlsSecurity && this._tlsSecurity !== "default" ? this._tlsSecurity : this._tlsCAData !== null ? "no_host_verification" : "strict";
  67470. }
  67471. get waitUntilAvailable() {
  67472. return this._waitUntilAvailable ?? 3e4;
  67473. }
  67474. explainConfig() {
  67475. const output = [
  67476. `Parameter Value Source`,
  67477. `--------- ----- ------`
  67478. ];
  67479. const outputLine = (param, val2, rawVal, source) => {
  67480. const isDefault = rawVal === null;
  67481. const maxValLength = 40 - (isDefault ? 10 : 0);
  67482. let value = String(val2);
  67483. if (value.length > maxValLength) {
  67484. value = value.slice(0, maxValLength - 3) + "...";
  67485. }
  67486. output.push(param.padEnd(19, " ") + (value + (isDefault ? " (default)" : "")).padEnd(42, " ") + (source ?? "default"));
  67487. };
  67488. outputLine("host", this.address[0], this._host, this._hostSource);
  67489. outputLine("port", this.address[1], this._port, this._portSource);
  67490. outputLine("database", this.database, this._database, this._databaseSource);
  67491. outputLine("branch", this.branch, this._branch, this._branchSource);
  67492. outputLine("user", this.user, this._user, this._userSource);
  67493. outputLine("password", this.password && this.password.slice(0, 3).padEnd(this.password.length, "*"), this._password, this._passwordSource);
  67494. outputLine("tlsCAData", this._tlsCAData && this._tlsCAData.replace(/\r\n?|\n/, ""), this._tlsCAData, this._tlsCADataSource);
  67495. outputLine("tlsSecurity", this.tlsSecurity, this._tlsSecurity, this._tlsSecuritySource);
  67496. outputLine("tlsServerName", this.tlsServerName, this._tlsServerName, this._tlsServerNameSource);
  67497. outputLine("waitUntilAvailable", this.waitUntilAvailable, this._waitUntilAvailable, this._waitUntilAvailableSource);
  67498. return output.join("\n");
  67499. }
  67500. };
  67501. exports.ResolvedConnectConfig = ResolvedConnectConfig;
  67502. function parseValidatePort(port) {
  67503. let parsedPort;
  67504. if (typeof port === "string") {
  67505. if (!/^\d*$/.test(port)) {
  67506. throw new errors_1.InterfaceError(`invalid port: ${port}`);
  67507. }
  67508. parsedPort = parseInt(port, 10);
  67509. if (Number.isNaN(parsedPort)) {
  67510. throw new errors_1.InterfaceError(`invalid port: ${port}`);
  67511. }
  67512. } else {
  67513. parsedPort = port;
  67514. }
  67515. if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
  67516. throw new errors_1.InterfaceError(`invalid port: ${port}`);
  67517. }
  67518. return parsedPort;
  67519. }
  67520. function validateHost(host) {
  67521. if (host.includes("/")) {
  67522. throw new errors_1.InterfaceError(`unix socket paths not supported`);
  67523. }
  67524. if (!host.length || host.includes(",")) {
  67525. throw new errors_1.InterfaceError(`invalid host: '${host}'`);
  67526. }
  67527. return host;
  67528. }
  67529. function parseDuration(duration) {
  67530. if (typeof duration === "number") {
  67531. if (duration < 0) {
  67532. throw new errors_1.InterfaceError("invalid waitUntilAvailable duration, must be >= 0");
  67533. }
  67534. return duration;
  67535. }
  67536. if (typeof duration === "string") {
  67537. if (duration.startsWith("P")) {
  67538. duration = datetime_1.Duration.from(duration);
  67539. } else {
  67540. return (0, datetime_1.parseHumanDurationString)(duration);
  67541. }
  67542. }
  67543. if (duration instanceof datetime_1.Duration) {
  67544. const invalidField = (0, datetime_2.checkValidGelDuration)(duration);
  67545. if (invalidField) {
  67546. throw new errors_1.InterfaceError(`invalid waitUntilAvailable duration, cannot have a '${invalidField}' value`);
  67547. }
  67548. if (duration.sign < 0) {
  67549. throw new errors_1.InterfaceError("invalid waitUntilAvailable duration, must be >= 0");
  67550. }
  67551. return duration.milliseconds + duration.seconds * 1e3 + duration.minutes * 6e4 + duration.hours * 36e5;
  67552. }
  67553. throw new errors_1.InterfaceError(`invalid duration`);
  67554. }
  67555. async function parseConnectDsnAndArgs(config, serverUtils) {
  67556. const resolvedConfig = new ResolvedConnectConfig();
  67557. let fromEnv3 = false;
  67558. let fromProject = false;
  67559. const [dsn, instanceName] = config.instanceName == null && config.dsn != null && !/^[a-z]+:\/\//i.test(config.dsn) ? [void 0, config.dsn] : [config.dsn, config.instanceName];
  67560. let { hasCompoundOptions } = await resolveConfigOptions(resolvedConfig, {
  67561. dsn,
  67562. instanceName,
  67563. credentials: config.credentials,
  67564. credentialsFile: config.credentialsFile,
  67565. host: config.host,
  67566. port: config.port,
  67567. database: config.database,
  67568. branch: config.branch,
  67569. user: config.user,
  67570. password: config.password,
  67571. secretKey: config.secretKey,
  67572. cloudProfile: getEnv("GEL_CLOUD_PROFILE"),
  67573. tlsCA: config.tlsCA,
  67574. tlsCAFile: config.tlsCAFile,
  67575. tlsServerName: config.tlsServerName,
  67576. tlsSecurity: config.tlsSecurity,
  67577. serverSettings: config.serverSettings,
  67578. waitUntilAvailable: config.waitUntilAvailable
  67579. }, {
  67580. dsn: `'dsnOrInstanceName' option (parsed as dsn)`,
  67581. instanceName: config.instanceName != null ? `'instanceName' option` : `'dsnOrInstanceName' option (parsed as instance name)`,
  67582. credentials: `'credentials' option`,
  67583. credentialsFile: `'credentialsFile' option`,
  67584. host: `'host' option`,
  67585. port: `'port' option`,
  67586. database: `'database' option`,
  67587. branch: `'branch' option`,
  67588. user: `'user' option`,
  67589. password: `'password' option`,
  67590. secretKey: `'secretKey' option`,
  67591. cloudProfile: `'GEL_CLOUD_PROFILE' environment variable`,
  67592. tlsCA: `'tlsCA' option`,
  67593. tlsCAFile: `'tlsCAFile' option`,
  67594. tlsSecurity: `'tlsSecurity' option`,
  67595. tlsServerName: `'tlsServerName' option`,
  67596. serverSettings: `'serverSettings' option`,
  67597. waitUntilAvailable: `'waitUntilAvailable' option`
  67598. }, `Cannot have more than one of the following connection options: 'dsn', 'instanceName', 'credentials', 'credentialsFile' or 'host'/'port'`, serverUtils);
  67599. if (!hasCompoundOptions) {
  67600. let port = getEnv("GEL_PORT");
  67601. if (resolvedConfig._port === null && port?.startsWith("tcp://")) {
  67602. console.warn(`GEL_PORT in 'tcp://host:port' format, so will be ignored`);
  67603. port = void 0;
  67604. }
  67605. ({ hasCompoundOptions, anyOptionsUsed: fromEnv3 } = await resolveConfigOptions(resolvedConfig, {
  67606. dsn: getEnv("GEL_DSN"),
  67607. instanceName: getEnv("GEL_INSTANCE"),
  67608. credentials: getEnv("GEL_CREDENTIALS"),
  67609. credentialsFile: getEnv("GEL_CREDENTIALS_FILE"),
  67610. host: getEnv("GEL_HOST"),
  67611. port,
  67612. database: getEnv("GEL_DATABASE"),
  67613. branch: getEnv("GEL_BRANCH"),
  67614. user: getEnv("GEL_USER"),
  67615. password: getEnv("GEL_PASSWORD"),
  67616. secretKey: getEnv("GEL_SECRET_KEY"),
  67617. tlsCA: getEnv("GEL_TLS_CA"),
  67618. tlsCAFile: getEnv("GEL_TLS_CA_FILE"),
  67619. tlsServerName: getEnv("GEL_TLS_SERVER_NAME"),
  67620. tlsSecurity: getEnv("GEL_CLIENT_TLS_SECURITY"),
  67621. waitUntilAvailable: getEnv("GEL_WAIT_UNTIL_AVAILABLE")
  67622. }, {
  67623. dsn: `'GEL_DSN' environment variable`,
  67624. instanceName: `'GEL_INSTANCE' environment variable`,
  67625. credentials: `'GEL_CREDENTIALS' environment variable`,
  67626. credentialsFile: `'GEL_CREDENTIALS_FILE' environment variable`,
  67627. host: `'GEL_HOST' environment variable`,
  67628. port: `'GEL_PORT' environment variable`,
  67629. database: `'GEL_DATABASE' environment variable`,
  67630. branch: `'GEL_BRANCH' environment variable`,
  67631. user: `'GEL_USER' environment variable`,
  67632. password: `'GEL_PASSWORD' environment variable`,
  67633. secretKey: `'GEL_SECRET_KEY' environment variable`,
  67634. tlsCA: `'GEL_TLS_CA' environment variable`,
  67635. tlsCAFile: `'GEL_TLS_CA_FILE' environment variable`,
  67636. tlsServerName: `'GEL_TLS_SERVER_NAME' environment variable`,
  67637. tlsSecurity: `'GEL_CLIENT_TLS_SECURITY' environment variable`,
  67638. waitUntilAvailable: `'GEL_WAIT_UNTIL_AVAILABLE' environment variable`
  67639. }, `Cannot have more than one of the following connection environment variables: 'GEL_DSN', 'GEL_INSTANCE', 'GEL_CREDENTIALS', 'GEL_CREDENTIALS_FILE' or 'GEL_HOST'`, serverUtils));
  67640. }
  67641. if (!hasCompoundOptions) {
  67642. if (!serverUtils) {
  67643. throw new errors.ClientConnectionError("no connection options specified either by arguments to `createClient` API or environment variables; also cannot resolve from project config file in browser (or edge runtime) environment");
  67644. }
  67645. const projectDir = await serverUtils?.findProjectDir();
  67646. if (!projectDir) {
  67647. throw new errors.ClientConnectionError("no project config file found and no connection options specified either via arguments to `createClient()` API or via environment variables GEL_HOST, GEL_INSTANCE, GEL_DSN, GEL_CREDENTIALS or GEL_CREDENTIALS_FILE");
  67648. }
  67649. const stashDir = await serverUtils.findStashPath(projectDir);
  67650. const instName = await serverUtils.readFileUtf8(stashDir, "instance-name").then((name) => name.trim()).catch(() => null);
  67651. if (instName !== null) {
  67652. const [cloudProfile, _database, branch] = await Promise.all([
  67653. serverUtils.readFileUtf8(stashDir, "cloud-profile").then((name) => name.trim()).catch(() => void 0),
  67654. serverUtils.readFileUtf8(stashDir, "database").then((name) => name.trim()).catch(() => void 0),
  67655. serverUtils.readFileUtf8(stashDir, "branch").then((name) => name.trim()).catch(() => void 0)
  67656. ]);
  67657. let database = _database;
  67658. if (database !== void 0 && branch !== void 0) {
  67659. if (database !== branch) {
  67660. throw new errors_1.InterfaceError("Both database and branch exist in the config dir and don't match.");
  67661. } else {
  67662. database = void 0;
  67663. }
  67664. }
  67665. await resolveConfigOptions(resolvedConfig, { instanceName: instName, cloudProfile, database, branch }, {
  67666. instanceName: `project linked instance ('${instName}')`,
  67667. cloudProfile: `project defined cloud instance ('${cloudProfile}')`,
  67668. database: `project default database`,
  67669. branch: `project default branch`
  67670. }, "", serverUtils);
  67671. fromProject = true;
  67672. } else {
  67673. throw new errors.ClientConnectionError("Found project config file but the project is not initialized. Run 'gel project init'.");
  67674. }
  67675. }
  67676. resolvedConfig.setTlsSecurity("default", "default");
  67677. return {
  67678. connectionParams: resolvedConfig,
  67679. inProject: async () => await serverUtils?.findProjectDir(false) != null,
  67680. fromEnv: fromEnv3,
  67681. fromProject
  67682. };
  67683. }
  67684. async function resolveConfigOptions(resolvedConfig, config, sources, compoundParamsError, serverUtils) {
  67685. let anyOptionsUsed = false;
  67686. const readFile4 = serverUtils?.readFileUtf8 ?? ((fn) => {
  67687. throw new errors_1.InterfaceError(`cannot read file "${fn}" in browser (or edge runtime) environment`);
  67688. });
  67689. if (config.tlsCA != null && config.tlsCAFile != null) {
  67690. throw new errors_1.InterfaceError(`Cannot specify both ${sources.tlsCA} and ${sources.tlsCAFile}`);
  67691. }
  67692. if (config.database != null) {
  67693. if (config.branch != null) {
  67694. throw new errors_1.InterfaceError(`${sources.database} and ${sources.branch} are mutually exclusive`);
  67695. }
  67696. if (resolvedConfig._branch == null) {
  67697. anyOptionsUsed = resolvedConfig.setDatabase(config.database ?? null, sources.database) || anyOptionsUsed;
  67698. }
  67699. }
  67700. if (config.branch != null) {
  67701. if (resolvedConfig._database == null) {
  67702. anyOptionsUsed = resolvedConfig.setBranch(config.branch ?? null, sources.branch) || anyOptionsUsed;
  67703. }
  67704. }
  67705. anyOptionsUsed = resolvedConfig.setUser(config.user ?? null, sources.user) || anyOptionsUsed;
  67706. anyOptionsUsed = resolvedConfig.setPassword(config.password ?? null, sources.password) || anyOptionsUsed;
  67707. anyOptionsUsed = resolvedConfig.setSecretKey(config.secretKey ?? null, sources.secretKey) || anyOptionsUsed;
  67708. anyOptionsUsed = resolvedConfig.setCloudProfile(config.cloudProfile ?? null, sources.cloudProfile) || anyOptionsUsed;
  67709. anyOptionsUsed = resolvedConfig.setTlsCAData(config.tlsCA ?? null, sources.tlsCA) || anyOptionsUsed;
  67710. anyOptionsUsed = await resolvedConfig.setTlsCAFile(config.tlsCAFile ?? null, sources.tlsCAFile, readFile4) || anyOptionsUsed;
  67711. anyOptionsUsed = resolvedConfig.setTlsServerName(config.tlsServerName ?? null, sources.tlsServerName) || anyOptionsUsed;
  67712. anyOptionsUsed = resolvedConfig.setTlsSecurity(config.tlsSecurity ?? null, sources.tlsSecurity) || anyOptionsUsed;
  67713. anyOptionsUsed = resolvedConfig.setWaitUntilAvailable(config.waitUntilAvailable ?? null, sources.waitUntilAvailable) || anyOptionsUsed;
  67714. resolvedConfig.addServerSettings(config.serverSettings ?? {});
  67715. const compoundParamsCount = [
  67716. config.dsn,
  67717. config.instanceName,
  67718. config.credentials,
  67719. config.credentialsFile,
  67720. config.host ?? config.port
  67721. ].filter((param) => param !== void 0).length;
  67722. if (compoundParamsCount > 1) {
  67723. throw new errors_1.InterfaceError(compoundParamsError);
  67724. }
  67725. if (compoundParamsCount === 1) {
  67726. if (config.dsn !== void 0 || config.host !== void 0 || config.port !== void 0) {
  67727. let dsn = config.dsn;
  67728. if (dsn === void 0) {
  67729. if (config.port !== void 0) {
  67730. resolvedConfig.setPort(config.port, sources.port);
  67731. }
  67732. const host = config.host != null ? validateHost(config.host) : "";
  67733. dsn = `edgedb://${host.includes(":") ? `[${encodeURI(host)}]` : host}`;
  67734. }
  67735. await parseDSNIntoConfig(dsn, resolvedConfig, config.dsn ? sources.dsn : config.host !== void 0 ? sources.host : sources.port, readFile4);
  67736. } else {
  67737. let creds;
  67738. let source;
  67739. if (config.credentials != null) {
  67740. creds = (0, credentials_1.validateCredentials)(JSON.parse(config.credentials));
  67741. source = sources.credentials;
  67742. } else {
  67743. if (!serverUtils && !config.instanceName?.includes("/")) {
  67744. throw new errors_1.InterfaceError(`cannot ${config.credentialsFile ? `read credentials file "${config.credentialsFile}"` : `resolve instance name "${config.instanceName}"`} in browser (or edge runtime) environment`);
  67745. }
  67746. let credentialsFile = config.credentialsFile;
  67747. if (credentialsFile === void 0) {
  67748. if (/^\w(-?\w)*$/.test(config.instanceName)) {
  67749. credentialsFile = await (0, credentials_1.getCredentialsPath)(config.instanceName, serverUtils);
  67750. source = sources.instanceName;
  67751. } else {
  67752. if (!/^([A-Za-z0-9_-](-?[A-Za-z0-9_])*)\/([A-Za-z0-9](-?[A-Za-z0-9])*)$/.test(config.instanceName)) {
  67753. throw new errors_1.InterfaceError(`invalid DSN or instance name: '${config.instanceName}'`);
  67754. }
  67755. await parseCloudInstanceNameIntoConfig(resolvedConfig, config.instanceName, sources.instanceName, serverUtils);
  67756. return { hasCompoundOptions: true, anyOptionsUsed: true };
  67757. }
  67758. } else {
  67759. source = sources.credentialsFile;
  67760. }
  67761. creds = await (0, credentials_1.readCredentialsFile)(credentialsFile, serverUtils);
  67762. }
  67763. resolvedConfig.setHost(creds.host ?? null, source);
  67764. resolvedConfig.setPort(creds.port ?? null, source);
  67765. if (creds.database != null) {
  67766. if (resolvedConfig._branch == null) {
  67767. resolvedConfig.setDatabase(creds.database ?? null, source);
  67768. }
  67769. } else if (creds.branch != null) {
  67770. if (resolvedConfig._database == null) {
  67771. resolvedConfig.setBranch(creds.branch ?? null, source);
  67772. }
  67773. }
  67774. resolvedConfig.setUser(creds.user ?? null, source);
  67775. resolvedConfig.setPassword(creds.password ?? null, source);
  67776. resolvedConfig.setTlsCAData(creds.tlsCAData ?? null, source);
  67777. resolvedConfig.setTlsSecurity(creds.tlsSecurity ?? null, source);
  67778. }
  67779. return { hasCompoundOptions: true, anyOptionsUsed: true };
  67780. }
  67781. return { hasCompoundOptions: false, anyOptionsUsed };
  67782. }
  67783. async function parseDSNIntoConfig(_dsnString, config, source, readFile4) {
  67784. let dsnString = _dsnString;
  67785. let regexHostname = null;
  67786. let zoneId = "";
  67787. const regexResult = /\[(.*?)(%25.+?)\]/.exec(_dsnString);
  67788. if (regexResult) {
  67789. regexHostname = regexResult[1];
  67790. zoneId = decodeURI(regexResult[2]);
  67791. dsnString = dsnString.slice(0, regexResult.index + regexHostname.length + 1) + dsnString.slice(regexResult.index + regexHostname.length + regexResult[2].length + 1);
  67792. }
  67793. let parsed;
  67794. try {
  67795. parsed = new URL(dsnString);
  67796. if (regexHostname !== null && parsed.hostname !== `[${regexHostname}]`) {
  67797. throw new Error();
  67798. }
  67799. } catch (_3) {
  67800. throw new errors_1.InterfaceError(`invalid DSN or instance name: '${_dsnString}'`);
  67801. }
  67802. if (parsed.protocol !== "edgedb:" && parsed.protocol !== "gel:") {
  67803. throw new errors_1.InterfaceError(`invalid DSN: scheme is expected to be 'gel', got '${parsed.protocol.slice(0, -1)}'`);
  67804. }
  67805. const searchParams = /* @__PURE__ */ new Map();
  67806. for (const [key, value] of parsed.searchParams) {
  67807. if (searchParams.has(key)) {
  67808. throw new errors_1.InterfaceError(`invalid DSN: duplicate query parameter '${key}'`);
  67809. }
  67810. searchParams.set(key, value);
  67811. }
  67812. async function handleDSNPart(paramName, value, currentValue, setter, formatter = (val2) => val2) {
  67813. if ([
  67814. value || null,
  67815. searchParams.get(paramName),
  67816. searchParams.get(`${paramName}_env`),
  67817. searchParams.get(`${paramName}_file`)
  67818. ].filter((param) => param != null).length > 1) {
  67819. throw new errors_1.InterfaceError(`invalid DSN: more than one of ${value !== null ? `'${paramName}', ` : ""}'?${paramName}=', '?${paramName}_env=' or '?${paramName}_file=' was specified ${dsnString}`);
  67820. }
  67821. if (currentValue === null) {
  67822. let param = value || (searchParams.get(paramName) ?? null);
  67823. let paramSource = source;
  67824. if (param === null) {
  67825. const env4 = searchParams.get(`${paramName}_env`);
  67826. if (env4 != null) {
  67827. param = getEnv(env4, true) ?? null;
  67828. if (param === null) {
  67829. throw new errors_1.InterfaceError(`'${paramName}_env' environment variable '${env4}' doesn't exist`);
  67830. }
  67831. paramSource += ` (${paramName}_env: ${env4})`;
  67832. }
  67833. }
  67834. if (param === null) {
  67835. const file = searchParams.get(`${paramName}_file`);
  67836. if (file != null) {
  67837. param = await readFile4(file);
  67838. paramSource += ` (${paramName}_file: ${file})`;
  67839. }
  67840. }
  67841. param = param !== null ? formatter(param) : null;
  67842. await setter(param, paramSource);
  67843. }
  67844. searchParams.delete(paramName);
  67845. searchParams.delete(`${paramName}_env`);
  67846. searchParams.delete(`${paramName}_file`);
  67847. }
  67848. const hostname = /^\[.*\]$/.test(parsed.hostname) ? parsed.hostname.slice(1, -1) + zoneId : parsed.hostname;
  67849. await handleDSNPart("host", hostname, config._host, config.setHost);
  67850. await handleDSNPart("port", parsed.port, config._port, config.setPort);
  67851. const stripLeadingSlash = (str) => str.replace(/^\//, "");
  67852. const searchParamsContainsDatabase = searchParams.has("database") || searchParams.has("database_env") || searchParams.has("database_file");
  67853. const searchParamsContainsBranch = searchParams.has("branch") || searchParams.has("branch_env") || searchParams.has("branch_file");
  67854. if (searchParamsContainsBranch) {
  67855. if (searchParamsContainsDatabase) {
  67856. throw new errors_1.InterfaceError(`invalid DSN: cannot specify both 'database' and 'branch'`);
  67857. }
  67858. if (config._database === null) {
  67859. await handleDSNPart("branch", stripLeadingSlash(parsed.pathname), config._branch, config.setBranch, stripLeadingSlash);
  67860. } else {
  67861. searchParams.delete("branch");
  67862. searchParams.delete("branch_env");
  67863. searchParams.delete("branch_file");
  67864. }
  67865. } else {
  67866. if (config._branch === null) {
  67867. await handleDSNPart("database", stripLeadingSlash(parsed.pathname), config._database, config.setDatabase, stripLeadingSlash);
  67868. } else {
  67869. searchParams.delete("database");
  67870. searchParams.delete("database_env");
  67871. searchParams.delete("database_file");
  67872. }
  67873. }
  67874. await handleDSNPart("user", parsed.username, config._user, config.setUser);
  67875. await handleDSNPart("password", parsed.password, config._password, config.setPassword);
  67876. await handleDSNPart("secret_key", null, config._secretKey, config.setSecretKey);
  67877. await handleDSNPart("tls_ca", null, config._tlsCAData, config.setTlsCAData);
  67878. await handleDSNPart("tls_ca_file", null, config._tlsCAData, (val2, _source) => config.setTlsCAFile(val2, _source, readFile4));
  67879. await handleDSNPart("tls_server_name", null, config._tlsServerName, config.setTlsServerName);
  67880. await handleDSNPart("tls_security", null, config._tlsSecurity, config.setTlsSecurity);
  67881. await handleDSNPart("wait_until_available", null, config._waitUntilAvailable, config.setWaitUntilAvailable);
  67882. const serverSettings = {};
  67883. for (const [key, value] of searchParams) {
  67884. serverSettings[key] = value;
  67885. }
  67886. config.addServerSettings(serverSettings);
  67887. }
  67888. async function parseCloudInstanceNameIntoConfig(config, cloudInstanceName, source, serverUtils) {
  67889. const normInstanceName = cloudInstanceName.toLowerCase();
  67890. const [org, instanceName] = normInstanceName.split("/");
  67891. const domainName = `${instanceName}--${org}`;
  67892. if (domainName.length > DOMAIN_NAME_MAX_LEN) {
  67893. throw new errors_1.InterfaceError(`invalid instance name: cloud instance name length cannot exceed ${DOMAIN_NAME_MAX_LEN - 1} characters: ${cloudInstanceName}`);
  67894. }
  67895. let secretKey = config.secretKey;
  67896. if (secretKey == null) {
  67897. try {
  67898. if (!serverUtils) {
  67899. throw new errors_1.InterfaceError(`Cannot get secret key from cloud profile in browser (or edge runtime) environment`);
  67900. }
  67901. const profile = config.cloudProfile;
  67902. const profilePath = await serverUtils.searchConfigDir("cloud-credentials", `${profile}.json`);
  67903. const fileData = await serverUtils.readFileUtf8(profilePath);
  67904. secretKey = JSON.parse(fileData)["secret_key"];
  67905. if (!secretKey) {
  67906. throw new errors_1.InterfaceError(`Cloud profile '${profile}' doesn't contain a secret key`);
  67907. }
  67908. config.setSecretKey(secretKey, `cloud-credentials/${profile}.json`);
  67909. } catch (e6) {
  67910. throw new errors_1.InterfaceError(`Cannot connect to cloud instances without a secret key: ${e6}`);
  67911. }
  67912. }
  67913. try {
  67914. const keyParts = secretKey.split(".");
  67915. if (keyParts.length < 2) {
  67916. throw new errors_1.InterfaceError("Invalid secret key: does not contain payload");
  67917. }
  67918. const dnsZone = _jwtBase64Decode(keyParts[1])["iss"];
  67919. if (!dnsZone) {
  67920. throw new errors_1.InterfaceError("Invalid secret key: payload does not contain 'iss' value");
  67921. }
  67922. const dnsBucket = ((0, crcHqx_1.crcHqx)(buffer_1.utf8Encoder.encode(normInstanceName), 0) % 100).toString(10).padStart(2, "0");
  67923. const host = `${domainName}.c-${dnsBucket}.i.${dnsZone}`;
  67924. config.setHost(host, `resolved from 'secretKey' and ${source}`);
  67925. } catch (e6) {
  67926. if (e6 instanceof errors.GelError) {
  67927. throw e6;
  67928. } else {
  67929. throw new errors_1.InterfaceError(`Invalid secret key: ${e6}`);
  67930. }
  67931. }
  67932. }
  67933. function _jwtBase64Decode(payload) {
  67934. return JSON.parse(buffer_1.utf8Decoder.decode((0, buffer_1.decodeB64)(payload.padEnd(Math.ceil(payload.length / 4) * 4, "="))));
  67935. }
  67936. }
  67937. });
  67938. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.server.js
  67939. var require_conUtils_server = __commonJS({
  67940. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.server.js"(exports) {
  67941. "use strict";
  67942. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  67943. if (k22 === void 0) k22 = k5;
  67944. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  67945. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  67946. desc = { enumerable: true, get: function() {
  67947. return m6[k5];
  67948. } };
  67949. }
  67950. Object.defineProperty(o5, k22, desc);
  67951. } : function(o5, m6, k5, k22) {
  67952. if (k22 === void 0) k22 = k5;
  67953. o5[k22] = m6[k5];
  67954. });
  67955. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  67956. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  67957. } : function(o5, v6) {
  67958. o5["default"] = v6;
  67959. });
  67960. var __importStar = exports && exports.__importStar || function(mod) {
  67961. if (mod && mod.__esModule) return mod;
  67962. var result = {};
  67963. if (mod != null) {
  67964. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  67965. }
  67966. __setModuleDefault(result, mod);
  67967. return result;
  67968. };
  67969. var __importDefault = exports && exports.__importDefault || function(mod) {
  67970. return mod && mod.__esModule ? mod : { "default": mod };
  67971. };
  67972. Object.defineProperty(exports, "__esModule", { value: true });
  67973. exports.parseConnectArguments = exports.serverUtils = void 0;
  67974. exports.findStashPath = findStashPath;
  67975. var platform2 = __importStar(require_platform());
  67976. var node_fs_1 = __require("fs");
  67977. var node_path_1 = __importDefault(__require("path"));
  67978. var systemUtils_1 = require_systemUtils();
  67979. var conUtils_1 = require_conUtils();
  67980. var projectDirCache = /* @__PURE__ */ new Map();
  67981. async function findProjectDir(required = true) {
  67982. if (!required && !(0, systemUtils_1.hasFSReadPermission)()) {
  67983. return null;
  67984. }
  67985. const workingDir = process.cwd();
  67986. if (projectDirCache.has(workingDir)) {
  67987. return projectDirCache.get(workingDir);
  67988. }
  67989. let dir = workingDir;
  67990. const cwdDev = (await node_fs_1.promises.stat(dir)).dev;
  67991. while (true) {
  67992. if (await (0, systemUtils_1.exists)(node_path_1.default.join(dir, "edgedb.toml")) || await (0, systemUtils_1.exists)(node_path_1.default.join(dir, "gel.toml"))) {
  67993. projectDirCache.set(workingDir, dir);
  67994. return dir;
  67995. }
  67996. const parentDir = node_path_1.default.join(dir, "..");
  67997. if (parentDir === dir || (await node_fs_1.promises.stat(parentDir)).dev !== cwdDev) {
  67998. projectDirCache.set(workingDir, null);
  67999. return null;
  68000. }
  68001. dir = parentDir;
  68002. }
  68003. }
  68004. async function findStashPath(projectDir) {
  68005. let projectPath = await node_fs_1.promises.realpath(projectDir);
  68006. if (platform2.isWindows && !projectPath.startsWith("\\\\")) {
  68007. projectPath = "\\\\?\\" + projectPath;
  68008. }
  68009. const hash = (0, systemUtils_1.hashSHA1toHex)(projectPath);
  68010. const baseName = node_path_1.default.basename(projectPath);
  68011. const dirName = baseName + "-" + hash;
  68012. return platform2.searchConfigDir("projects", dirName);
  68013. }
  68014. exports.serverUtils = {
  68015. findProjectDir,
  68016. findStashPath,
  68017. readFileUtf8: systemUtils_1.readFileUtf8,
  68018. searchConfigDir: platform2.searchConfigDir
  68019. };
  68020. exports.parseConnectArguments = (0, conUtils_1.getConnectArgumentsParser)(exports.serverUtils);
  68021. }
  68022. });
  68023. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/map.js
  68024. var require_map = __commonJS({
  68025. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/map.js"(exports) {
  68026. "use strict";
  68027. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  68028. if (k22 === void 0) k22 = k5;
  68029. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  68030. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  68031. desc = { enumerable: true, get: function() {
  68032. return m6[k5];
  68033. } };
  68034. }
  68035. Object.defineProperty(o5, k22, desc);
  68036. } : function(o5, m6, k5, k22) {
  68037. if (k22 === void 0) k22 = k5;
  68038. o5[k22] = m6[k5];
  68039. });
  68040. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  68041. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  68042. } : function(o5, v6) {
  68043. o5["default"] = v6;
  68044. });
  68045. var __importStar = exports && exports.__importStar || function(mod) {
  68046. if (mod && mod.__esModule) return mod;
  68047. var result = {};
  68048. if (mod != null) {
  68049. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  68050. }
  68051. __setModuleDefault(result, mod);
  68052. return result;
  68053. };
  68054. Object.defineProperty(exports, "__esModule", { value: true });
  68055. exports.errorMapping = void 0;
  68056. var errors = __importStar(require_errors());
  68057. exports.errorMapping = /* @__PURE__ */ new Map();
  68058. exports.errorMapping.set(16777216, errors.InternalServerError);
  68059. exports.errorMapping.set(33554432, errors.UnsupportedFeatureError);
  68060. exports.errorMapping.set(50331648, errors.ProtocolError);
  68061. exports.errorMapping.set(50397184, errors.BinaryProtocolError);
  68062. exports.errorMapping.set(50397185, errors.UnsupportedProtocolVersionError);
  68063. exports.errorMapping.set(50397186, errors.TypeSpecNotFoundError);
  68064. exports.errorMapping.set(50397187, errors.UnexpectedMessageError);
  68065. exports.errorMapping.set(50462720, errors.InputDataError);
  68066. exports.errorMapping.set(50462976, errors.ParameterTypeMismatchError);
  68067. exports.errorMapping.set(50463232, errors.StateMismatchError);
  68068. exports.errorMapping.set(50528256, errors.ResultCardinalityMismatchError);
  68069. exports.errorMapping.set(50593792, errors.CapabilityError);
  68070. exports.errorMapping.set(50594048, errors.UnsupportedCapabilityError);
  68071. exports.errorMapping.set(50594304, errors.DisabledCapabilityError);
  68072. exports.errorMapping.set(50594560, errors.UnsafeIsolationLevelError);
  68073. exports.errorMapping.set(67108864, errors.QueryError);
  68074. exports.errorMapping.set(67174400, errors.InvalidSyntaxError);
  68075. exports.errorMapping.set(67174656, errors.EdgeQLSyntaxError);
  68076. exports.errorMapping.set(67174912, errors.SchemaSyntaxError);
  68077. exports.errorMapping.set(67175168, errors.GraphQLSyntaxError);
  68078. exports.errorMapping.set(67239936, errors.InvalidTypeError);
  68079. exports.errorMapping.set(67240192, errors.InvalidTargetError);
  68080. exports.errorMapping.set(67240193, errors.InvalidLinkTargetError);
  68081. exports.errorMapping.set(67240194, errors.InvalidPropertyTargetError);
  68082. exports.errorMapping.set(67305472, errors.InvalidReferenceError);
  68083. exports.errorMapping.set(67305473, errors.UnknownModuleError);
  68084. exports.errorMapping.set(67305474, errors.UnknownLinkError);
  68085. exports.errorMapping.set(67305475, errors.UnknownPropertyError);
  68086. exports.errorMapping.set(67305476, errors.UnknownUserError);
  68087. exports.errorMapping.set(67305477, errors.UnknownDatabaseError);
  68088. exports.errorMapping.set(67305478, errors.UnknownParameterError);
  68089. exports.errorMapping.set(67305479, errors.DeprecatedScopingError);
  68090. exports.errorMapping.set(67371008, errors.SchemaError);
  68091. exports.errorMapping.set(67436544, errors.SchemaDefinitionError);
  68092. exports.errorMapping.set(67436800, errors.InvalidDefinitionError);
  68093. exports.errorMapping.set(67436801, errors.InvalidModuleDefinitionError);
  68094. exports.errorMapping.set(67436802, errors.InvalidLinkDefinitionError);
  68095. exports.errorMapping.set(67436803, errors.InvalidPropertyDefinitionError);
  68096. exports.errorMapping.set(67436804, errors.InvalidUserDefinitionError);
  68097. exports.errorMapping.set(67436805, errors.InvalidDatabaseDefinitionError);
  68098. exports.errorMapping.set(67436806, errors.InvalidOperatorDefinitionError);
  68099. exports.errorMapping.set(67436807, errors.InvalidAliasDefinitionError);
  68100. exports.errorMapping.set(67436808, errors.InvalidFunctionDefinitionError);
  68101. exports.errorMapping.set(67436809, errors.InvalidConstraintDefinitionError);
  68102. exports.errorMapping.set(67436810, errors.InvalidCastDefinitionError);
  68103. exports.errorMapping.set(67437056, errors.DuplicateDefinitionError);
  68104. exports.errorMapping.set(67437057, errors.DuplicateModuleDefinitionError);
  68105. exports.errorMapping.set(67437058, errors.DuplicateLinkDefinitionError);
  68106. exports.errorMapping.set(67437059, errors.DuplicatePropertyDefinitionError);
  68107. exports.errorMapping.set(67437060, errors.DuplicateUserDefinitionError);
  68108. exports.errorMapping.set(67437061, errors.DuplicateDatabaseDefinitionError);
  68109. exports.errorMapping.set(67437062, errors.DuplicateOperatorDefinitionError);
  68110. exports.errorMapping.set(67437063, errors.DuplicateViewDefinitionError);
  68111. exports.errorMapping.set(67437064, errors.DuplicateFunctionDefinitionError);
  68112. exports.errorMapping.set(67437065, errors.DuplicateConstraintDefinitionError);
  68113. exports.errorMapping.set(67437066, errors.DuplicateCastDefinitionError);
  68114. exports.errorMapping.set(67437067, errors.DuplicateMigrationError);
  68115. exports.errorMapping.set(67502080, errors.SessionTimeoutError);
  68116. exports.errorMapping.set(67502336, errors.IdleSessionTimeoutError);
  68117. exports.errorMapping.set(67502592, errors.QueryTimeoutError);
  68118. exports.errorMapping.set(67504640, errors.TransactionTimeoutError);
  68119. exports.errorMapping.set(67504641, errors.IdleTransactionTimeoutError);
  68120. exports.errorMapping.set(83886080, errors.ExecutionError);
  68121. exports.errorMapping.set(83951616, errors.InvalidValueError);
  68122. exports.errorMapping.set(83951617, errors.DivisionByZeroError);
  68123. exports.errorMapping.set(83951618, errors.NumericOutOfRangeError);
  68124. exports.errorMapping.set(83951619, errors.AccessPolicyError);
  68125. exports.errorMapping.set(83951620, errors.QueryAssertionError);
  68126. exports.errorMapping.set(84017152, errors.IntegrityError);
  68127. exports.errorMapping.set(84017153, errors.ConstraintViolationError);
  68128. exports.errorMapping.set(84017154, errors.CardinalityViolationError);
  68129. exports.errorMapping.set(84017155, errors.MissingRequiredError);
  68130. exports.errorMapping.set(84082688, errors.TransactionError);
  68131. exports.errorMapping.set(84082944, errors.TransactionConflictError);
  68132. exports.errorMapping.set(84082945, errors.TransactionSerializationError);
  68133. exports.errorMapping.set(84082946, errors.TransactionDeadlockError);
  68134. exports.errorMapping.set(84148224, errors.WatchError);
  68135. exports.errorMapping.set(100663296, errors.ConfigurationError);
  68136. exports.errorMapping.set(117440512, errors.AccessError);
  68137. exports.errorMapping.set(117506048, errors.AuthenticationError);
  68138. exports.errorMapping.set(134217728, errors.AvailabilityError);
  68139. exports.errorMapping.set(134217729, errors.BackendUnavailableError);
  68140. exports.errorMapping.set(134217730, errors.ServerOfflineError);
  68141. exports.errorMapping.set(134217731, errors.UnknownTenantError);
  68142. exports.errorMapping.set(134217732, errors.ServerBlockedError);
  68143. exports.errorMapping.set(150994944, errors.BackendError);
  68144. exports.errorMapping.set(150995200, errors.UnsupportedBackendFeatureError);
  68145. exports.errorMapping.set(4026531840, errors.LogMessage);
  68146. exports.errorMapping.set(4026597376, errors.WarningMessage);
  68147. exports.errorMapping.set(4026662912, errors.StatusMessage);
  68148. exports.errorMapping.set(4026662913, errors.MigrationStatusMessage);
  68149. exports.errorMapping.set(4278190080, errors.ClientError);
  68150. exports.errorMapping.set(4278255616, errors.ClientConnectionError);
  68151. exports.errorMapping.set(4278255872, errors.ClientConnectionFailedError);
  68152. exports.errorMapping.set(4278255873, errors.ClientConnectionFailedTemporarilyError);
  68153. exports.errorMapping.set(4278256128, errors.ClientConnectionTimeoutError);
  68154. exports.errorMapping.set(4278256384, errors.ClientConnectionClosedError);
  68155. exports.errorMapping.set(4278321152, errors.InterfaceError);
  68156. exports.errorMapping.set(4278321408, errors.QueryArgumentError);
  68157. exports.errorMapping.set(4278321409, errors.MissingArgumentError);
  68158. exports.errorMapping.set(4278321410, errors.UnknownArgumentError);
  68159. exports.errorMapping.set(4278321411, errors.InvalidArgumentError);
  68160. exports.errorMapping.set(4278386688, errors.NoDataError);
  68161. exports.errorMapping.set(4278452224, errors.InternalClientError);
  68162. }
  68163. });
  68164. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/resolve.js
  68165. var require_resolve = __commonJS({
  68166. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/resolve.js"(exports) {
  68167. "use strict";
  68168. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  68169. if (k22 === void 0) k22 = k5;
  68170. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  68171. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  68172. desc = { enumerable: true, get: function() {
  68173. return m6[k5];
  68174. } };
  68175. }
  68176. Object.defineProperty(o5, k22, desc);
  68177. } : function(o5, m6, k5, k22) {
  68178. if (k22 === void 0) k22 = k5;
  68179. o5[k22] = m6[k5];
  68180. });
  68181. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  68182. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  68183. } : function(o5, v6) {
  68184. o5["default"] = v6;
  68185. });
  68186. var __importStar = exports && exports.__importStar || function(mod) {
  68187. if (mod && mod.__esModule) return mod;
  68188. var result = {};
  68189. if (mod != null) {
  68190. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  68191. }
  68192. __setModuleDefault(result, mod);
  68193. return result;
  68194. };
  68195. Object.defineProperty(exports, "__esModule", { value: true });
  68196. exports.resolveErrorCode = resolveErrorCode;
  68197. exports.errorFromJSON = errorFromJSON;
  68198. var errors = __importStar(require_errors());
  68199. var base_1 = require_base();
  68200. var map_1 = require_map();
  68201. function resolveErrorCode(code) {
  68202. let result;
  68203. result = map_1.errorMapping.get(code);
  68204. if (result) {
  68205. return result;
  68206. }
  68207. code = code & 4294967040;
  68208. result = map_1.errorMapping.get(code);
  68209. if (result) {
  68210. return result;
  68211. }
  68212. code = code & 4294901760;
  68213. result = map_1.errorMapping.get(code);
  68214. if (result) {
  68215. return result;
  68216. }
  68217. code = code & 4278190080;
  68218. result = map_1.errorMapping.get(code);
  68219. if (result) {
  68220. return result;
  68221. }
  68222. return errors.GelError;
  68223. }
  68224. var _JSON_FIELDS = {
  68225. hint: base_1.ErrorAttr.hint,
  68226. details: base_1.ErrorAttr.details,
  68227. start: base_1.ErrorAttr.characterStart,
  68228. end: base_1.ErrorAttr.characterEnd,
  68229. line: base_1.ErrorAttr.lineStart,
  68230. col: base_1.ErrorAttr.columnStart
  68231. };
  68232. function errorFromJSON(data) {
  68233. const errType = resolveErrorCode(data.code);
  68234. const err2 = new errType(data.message);
  68235. const attrs = /* @__PURE__ */ new Map();
  68236. for (const [name, field] of Object.entries(_JSON_FIELDS)) {
  68237. if (data[name] != null) {
  68238. attrs.set(field, data[name]);
  68239. }
  68240. }
  68241. err2._attrs = attrs;
  68242. return err2;
  68243. }
  68244. }
  68245. });
  68246. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseConn.js
  68247. var require_baseConn = __commonJS({
  68248. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseConn.js"(exports) {
  68249. "use strict";
  68250. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  68251. if (k22 === void 0) k22 = k5;
  68252. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  68253. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  68254. desc = { enumerable: true, get: function() {
  68255. return m6[k5];
  68256. } };
  68257. }
  68258. Object.defineProperty(o5, k22, desc);
  68259. } : function(o5, m6, k5, k22) {
  68260. if (k22 === void 0) k22 = k5;
  68261. o5[k22] = m6[k5];
  68262. });
  68263. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  68264. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  68265. } : function(o5, v6) {
  68266. o5["default"] = v6;
  68267. });
  68268. var __importStar = exports && exports.__importStar || function(mod) {
  68269. if (mod && mod.__esModule) return mod;
  68270. var result = {};
  68271. if (mod != null) {
  68272. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  68273. }
  68274. __setModuleDefault(result, mod);
  68275. return result;
  68276. };
  68277. var __importDefault = exports && exports.__importDefault || function(mod) {
  68278. return mod && mod.__esModule ? mod : { "default": mod };
  68279. };
  68280. Object.defineProperty(exports, "__esModule", { value: true });
  68281. exports.BaseRawConnection = exports.RESTRICTED_CAPABILITIES = exports.Capabilities = exports.PROTO_VER_MIN = exports.PROTO_VER = void 0;
  68282. var codecs_1 = require_codecs();
  68283. var object_1 = require_object();
  68284. var utils_1 = require_utils2();
  68285. var errors = __importStar(require_errors());
  68286. var resolve_1 = require_resolve();
  68287. var context_1 = require_context();
  68288. var ifaces_1 = require_ifaces2();
  68289. var buffer_1 = require_buffer();
  68290. var chars = __importStar(require_chars());
  68291. var event_1 = __importDefault(require_event());
  68292. var lru_1 = __importDefault(require_lru());
  68293. var options_1 = require_options();
  68294. exports.PROTO_VER = [3, 0];
  68295. exports.PROTO_VER_MIN = [0, 9];
  68296. var TransactionStatus;
  68297. (function(TransactionStatus2) {
  68298. TransactionStatus2[TransactionStatus2["TRANS_IDLE"] = 0] = "TRANS_IDLE";
  68299. TransactionStatus2[TransactionStatus2["TRANS_ACTIVE"] = 1] = "TRANS_ACTIVE";
  68300. TransactionStatus2[TransactionStatus2["TRANS_INTRANS"] = 2] = "TRANS_INTRANS";
  68301. TransactionStatus2[TransactionStatus2["TRANS_INERROR"] = 3] = "TRANS_INERROR";
  68302. TransactionStatus2[TransactionStatus2["TRANS_UNKNOWN"] = 4] = "TRANS_UNKNOWN";
  68303. })(TransactionStatus || (TransactionStatus = {}));
  68304. var Capabilities;
  68305. (function(Capabilities2) {
  68306. Capabilities2[Capabilities2["NONE"] = 0] = "NONE";
  68307. Capabilities2[Capabilities2["MODIFICATONS"] = 1] = "MODIFICATONS";
  68308. Capabilities2[Capabilities2["SESSION_CONFIG"] = 2] = "SESSION_CONFIG";
  68309. Capabilities2[Capabilities2["TRANSACTION"] = 4] = "TRANSACTION";
  68310. Capabilities2[Capabilities2["DDL"] = 8] = "DDL";
  68311. Capabilities2[Capabilities2["PERSISTENT_CONFIG"] = 16] = "PERSISTENT_CONFIG";
  68312. Capabilities2[Capabilities2["SET_GLOBAL"] = 32] = "SET_GLOBAL";
  68313. Capabilities2[Capabilities2["ALL"] = 4294967295] = "ALL";
  68314. })(Capabilities || (exports.Capabilities = Capabilities = {}));
  68315. var NO_TRANSACTION_CAPABILITIES = (Capabilities.ALL & ~Capabilities.TRANSACTION) >>> 0;
  68316. var NO_TRANSACTION_CAPABILITIES_BYTES = new Uint8Array(Array(8).fill(255));
  68317. new DataView(NO_TRANSACTION_CAPABILITIES_BYTES.buffer).setUint32(4, NO_TRANSACTION_CAPABILITIES);
  68318. exports.RESTRICTED_CAPABILITIES = (Capabilities.ALL & ~Capabilities.TRANSACTION & ~Capabilities.SESSION_CONFIG & ~Capabilities.SET_GLOBAL) >>> 0;
  68319. var CompilationFlag;
  68320. (function(CompilationFlag2) {
  68321. CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_TYPE_IDS"] = 1] = "INJECT_OUTPUT_TYPE_IDS";
  68322. CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_TYPE_NAMES"] = 2] = "INJECT_OUTPUT_TYPE_NAMES";
  68323. CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_OBJECT_IDS"] = 4] = "INJECT_OUTPUT_OBJECT_IDS";
  68324. })(CompilationFlag || (CompilationFlag = {}));
  68325. var OLD_ERROR_CODES = /* @__PURE__ */ new Map([
  68326. [84082689, 84082945],
  68327. [84082690, 84082946]
  68328. ]);
  68329. var BaseRawConnection = class {
  68330. constructor(registry) {
  68331. __publicField(this, "connected", false);
  68332. __publicField(this, "lastStatus");
  68333. __publicField(this, "codecsRegistry");
  68334. __publicField(this, "queryCodecCache");
  68335. __publicField(this, "serverSecret");
  68336. __publicField(this, "serverSettings");
  68337. __publicField(this, "serverXactStatus");
  68338. __publicField(this, "buffer");
  68339. __publicField(this, "messageWaiter");
  68340. __publicField(this, "connWaiter");
  68341. __publicField(this, "connAbortWaiter");
  68342. __publicField(this, "_abortedWith", null);
  68343. __publicField(this, "protocolVersion", exports.PROTO_VER);
  68344. __publicField(this, "stateCodec", codecs_1.INVALID_CODEC);
  68345. __publicField(this, "stateCache", /* @__PURE__ */ new WeakMap());
  68346. __publicField(this, "lastStateUpdate", null);
  68347. __publicField(this, "adminUIMode", false);
  68348. this.buffer = new buffer_1.ReadMessageBuffer();
  68349. this.codecsRegistry = registry;
  68350. this.queryCodecCache = new lru_1.default({ capacity: 1e3 });
  68351. this.lastStatus = null;
  68352. this.serverSecret = null;
  68353. this.serverSettings = {};
  68354. this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN;
  68355. this.messageWaiter = null;
  68356. this.connWaiter = new event_1.default();
  68357. this.connAbortWaiter = new event_1.default();
  68358. }
  68359. throwNotImplemented(method) {
  68360. throw new errors.InternalClientError(`method ${method} is not implemented`);
  68361. }
  68362. async _waitForMessage() {
  68363. this.throwNotImplemented("_waitForMessage");
  68364. }
  68365. _sendData(_data5) {
  68366. this.throwNotImplemented("_sendData");
  68367. }
  68368. getConnAbortError() {
  68369. return this._abortedWith ?? new errors.InterfaceError(`client has been closed`);
  68370. }
  68371. _checkState() {
  68372. if (this.isClosed()) {
  68373. throw this.getConnAbortError();
  68374. }
  68375. }
  68376. _abortWithError(err2) {
  68377. this._abortedWith = err2;
  68378. this._abort();
  68379. }
  68380. _ignoreHeaders() {
  68381. let numFields = this.buffer.readInt16();
  68382. while (numFields) {
  68383. this.buffer.readInt16();
  68384. this.buffer.readLenPrefixedBuffer();
  68385. numFields--;
  68386. }
  68387. }
  68388. _readHeaders() {
  68389. const numFields = this.buffer.readInt16();
  68390. const headers = {};
  68391. for (let i6 = 0; i6 < numFields; i6++) {
  68392. const key = this.buffer.readString();
  68393. const value = this.buffer.readString();
  68394. headers[key] = value;
  68395. }
  68396. return headers;
  68397. }
  68398. _abortWaiters(err2) {
  68399. if (!this.connWaiter.done) {
  68400. this.connWaiter.setError(err2);
  68401. }
  68402. this.messageWaiter?.setError(err2);
  68403. this.messageWaiter = null;
  68404. }
  68405. _parseHeaders() {
  68406. const ret = /* @__PURE__ */ new Map();
  68407. let numFields = this.buffer.readInt16();
  68408. while (numFields) {
  68409. const key = this.buffer.readInt16();
  68410. const value = this.buffer.readLenPrefixedBuffer();
  68411. ret.set(key, value);
  68412. numFields--;
  68413. }
  68414. return ret;
  68415. }
  68416. _parseDescribeTypeMessage(query) {
  68417. let capabilities = -1;
  68418. let warnings = [];
  68419. let unsafeIsolationDangers = [];
  68420. const headers = this._readHeaders();
  68421. if (headers.warnings != null) {
  68422. warnings = JSON.parse(headers.warnings).map((warning3) => {
  68423. const err2 = (0, resolve_1.errorFromJSON)(warning3);
  68424. err2._query = query;
  68425. return err2;
  68426. });
  68427. }
  68428. if (headers.unsafe_isolation_dangers != null) {
  68429. unsafeIsolationDangers = JSON.parse(headers.unsafe_isolation_dangers).map((danger) => {
  68430. const err2 = (0, resolve_1.errorFromJSON)(danger);
  68431. err2._query = query;
  68432. return err2;
  68433. });
  68434. }
  68435. capabilities = Number(this.buffer.readBigInt64());
  68436. const cardinality = this.buffer.readChar();
  68437. const inTypeId = this.buffer.readUUID();
  68438. const inTypeData = this.buffer.readLenPrefixedBuffer();
  68439. const outTypeId = this.buffer.readUUID();
  68440. const outTypeData = this.buffer.readLenPrefixedBuffer();
  68441. this.buffer.finishMessage();
  68442. let inCodec = this.codecsRegistry.getCodec(inTypeId);
  68443. if (inCodec == null) {
  68444. inCodec = this.codecsRegistry.buildCodec(inTypeData, this.protocolVersion);
  68445. }
  68446. let outCodec = this.codecsRegistry.getCodec(outTypeId);
  68447. if (outCodec == null) {
  68448. outCodec = this.codecsRegistry.buildCodec(outTypeData, this.protocolVersion);
  68449. }
  68450. return [
  68451. cardinality,
  68452. inCodec,
  68453. outCodec,
  68454. capabilities,
  68455. inTypeData,
  68456. outTypeData,
  68457. warnings,
  68458. unsafeIsolationDangers
  68459. ];
  68460. }
  68461. _parseCommandCompleteMessage() {
  68462. this._ignoreHeaders();
  68463. this.buffer.readBigInt64();
  68464. const status = this.buffer.readString();
  68465. const stateTypeId = this.buffer.readUUID();
  68466. const stateData = this.buffer.readLenPrefixedBuffer();
  68467. if (this.adminUIMode && stateTypeId === this.stateCodec.tid) {
  68468. this.lastStateUpdate = this.stateCodec.decode(new buffer_1.ReadBuffer(stateData), context_1.NOOP_CODEC_CONTEXT);
  68469. }
  68470. this.buffer.finishMessage();
  68471. return status;
  68472. }
  68473. _parseErrorMessage() {
  68474. this.buffer.readChar();
  68475. const code = this.buffer.readUInt32();
  68476. const message = this.buffer.readString();
  68477. const errorType = (0, resolve_1.resolveErrorCode)(OLD_ERROR_CODES.get(code) ?? code);
  68478. const err2 = new errorType(message);
  68479. err2._attrs = this._parseHeaders();
  68480. this.buffer.finishMessage();
  68481. if (err2 instanceof errors.AuthenticationError) {
  68482. throw err2;
  68483. }
  68484. return err2;
  68485. }
  68486. _parseSyncMessage() {
  68487. this._parseHeaders();
  68488. const status = this.buffer.readChar();
  68489. switch (status) {
  68490. case chars.$I:
  68491. this.serverXactStatus = TransactionStatus.TRANS_IDLE;
  68492. break;
  68493. case chars.$T:
  68494. this.serverXactStatus = TransactionStatus.TRANS_INTRANS;
  68495. break;
  68496. case chars.$E:
  68497. this.serverXactStatus = TransactionStatus.TRANS_INERROR;
  68498. break;
  68499. default:
  68500. this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN;
  68501. }
  68502. this.buffer.finishMessage();
  68503. }
  68504. _redirectDataMessages(result) {
  68505. const $D = chars.$D;
  68506. const buffer = this.buffer;
  68507. while (buffer.takeMessageType($D)) {
  68508. const msg = buffer.consumeMessage();
  68509. result.writeChar($D);
  68510. result.writeInt32(msg.length + 4);
  68511. result.writeBuffer(msg);
  68512. }
  68513. }
  68514. _parseDataMessages(codec, result, ctx) {
  68515. const frb = buffer_1.ReadBuffer.alloc();
  68516. const $D = chars.$D;
  68517. const buffer = this.buffer;
  68518. if (Array.isArray(result)) {
  68519. while (buffer.takeMessageType($D)) {
  68520. buffer.consumeMessageInto(frb);
  68521. frb.discard(6);
  68522. result.push(codec.decode(frb, ctx));
  68523. frb.finish();
  68524. }
  68525. } else {
  68526. this._redirectDataMessages(result);
  68527. }
  68528. }
  68529. _parseServerSettings(name, value) {
  68530. switch (name) {
  68531. case "suggested_pool_concurrency": {
  68532. this.serverSettings.suggested_pool_concurrency = parseInt(buffer_1.utf8Decoder.decode(value), 10);
  68533. break;
  68534. }
  68535. case "system_config": {
  68536. const buf = new buffer_1.ReadBuffer(value);
  68537. const typedescLen = buf.readInt32() - 16;
  68538. const typedescId = buf.readUUID();
  68539. const typedesc = buf.readBuffer(typedescLen);
  68540. let codec = this.codecsRegistry.getCodec(typedescId);
  68541. if (codec === null) {
  68542. codec = this.codecsRegistry.buildCodec(typedesc, this.protocolVersion);
  68543. }
  68544. buf.discard(4);
  68545. const data = codec.decode(buf, context_1.NOOP_CODEC_CONTEXT);
  68546. buf.finish();
  68547. this.serverSettings.system_config = data;
  68548. break;
  68549. }
  68550. default:
  68551. this.serverSettings[name] = value;
  68552. break;
  68553. }
  68554. }
  68555. _parseDescribeStateMessage() {
  68556. const typedescId = this.buffer.readUUID();
  68557. const typedesc = this.buffer.readBuffer(this.buffer.readInt32());
  68558. let codec = this.codecsRegistry.getCodec(typedescId);
  68559. if (codec === null) {
  68560. codec = this.codecsRegistry.buildCodec(typedesc, this.protocolVersion);
  68561. }
  68562. this.stateCodec = codec;
  68563. this.stateCache = /* @__PURE__ */ new WeakMap();
  68564. this.buffer.finishMessage();
  68565. }
  68566. _fallthrough() {
  68567. const mtype = this.buffer.getMessageType();
  68568. switch (mtype) {
  68569. case chars.$S: {
  68570. const name = this.buffer.readString();
  68571. const value = this.buffer.readLenPrefixedBuffer();
  68572. this._parseServerSettings(name, value);
  68573. this.buffer.finishMessage();
  68574. break;
  68575. }
  68576. case chars.$L: {
  68577. const severity = this.buffer.readChar();
  68578. const code = this.buffer.readUInt32();
  68579. const message = this.buffer.readString();
  68580. this._parseHeaders();
  68581. this.buffer.finishMessage();
  68582. console.info("SERVER MESSAGE", severity, code, message);
  68583. break;
  68584. }
  68585. default:
  68586. throw new errors.UnexpectedMessageError(`unexpected message type ${mtype} ("${chars.chr(mtype)}")`);
  68587. }
  68588. }
  68589. _encodeArgs(args, inCodec, ctx) {
  68590. if (inCodec === codecs_1.NULL_CODEC) {
  68591. if (args != null) {
  68592. throw new errors.QueryArgumentError(`This query does not contain any query parameters, but query arguments were provided to the 'query*()' method`);
  68593. }
  68594. return codecs_1.NullCodec.BUFFER;
  68595. }
  68596. if (inCodec instanceof object_1.ObjectCodec) {
  68597. return inCodec.encodeArgs(args, ctx);
  68598. }
  68599. throw new errors.ProtocolError("invalid input codec");
  68600. }
  68601. _isInTransaction() {
  68602. return this.serverXactStatus === TransactionStatus.TRANS_INTRANS || this.serverXactStatus === TransactionStatus.TRANS_ACTIVE;
  68603. }
  68604. _setStateCodec(state2) {
  68605. let encodedState = this.stateCache.get(state2);
  68606. if (encodedState) {
  68607. return encodedState;
  68608. }
  68609. const buf = new buffer_1.WriteBuffer();
  68610. this.stateCodec.encode(buf, state2._serialise(), context_1.NOOP_CODEC_CONTEXT);
  68611. encodedState = buf.unwrap();
  68612. this.stateCache.set(state2, encodedState);
  68613. return encodedState;
  68614. }
  68615. _encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, isExecute, unsafeIsolationDangers) {
  68616. if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0])) {
  68617. if (state2.annotations.size >= 1 << 16) {
  68618. throw new errors.InternalClientError("too many annotations");
  68619. }
  68620. wb.writeUInt16(state2.annotations.size);
  68621. for (const [name, value] of state2.annotations) {
  68622. wb.writeString(name);
  68623. wb.writeString(value);
  68624. }
  68625. } else {
  68626. wb.writeUInt16(0);
  68627. }
  68628. wb.writeFlags(4294967295, capabilitiesFlags);
  68629. wb.writeFlags(0, 0 | (options?.injectObjectids ? CompilationFlag.INJECT_OUTPUT_OBJECT_IDS : 0) | (options?.injectTypeids ? CompilationFlag.INJECT_OUTPUT_TYPE_IDS : 0) | (options?.injectTypenames ? CompilationFlag.INJECT_OUTPUT_TYPE_NAMES : 0));
  68630. wb.writeBigInt64(options?.implicitLimit ?? BigInt(0));
  68631. if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0])) {
  68632. wb.writeChar(language);
  68633. }
  68634. wb.writeChar(outputFormat);
  68635. wb.writeChar(expectedCardinality === ifaces_1.Cardinality.ONE || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE ? ifaces_1.Cardinality.AT_MOST_ONE : ifaces_1.Cardinality.MANY);
  68636. wb.writeString(query);
  68637. if (!this.adminUIMode && state2.isDefaultSession()) {
  68638. wb.writeBuffer(codecs_1.NULL_CODEC.tidBuffer);
  68639. wb.writeInt32(0);
  68640. } else {
  68641. wb.writeBuffer(this.stateCodec.tidBuffer);
  68642. if (this.stateCodec === codecs_1.INVALID_CODEC || this.stateCodec === codecs_1.NULL_CODEC) {
  68643. wb.writeInt32(0);
  68644. } else {
  68645. if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0]) && isExecute && !this._isInTransaction()) {
  68646. const isolation = state2.transactionOptions.isolation === options_1.IsolationLevel.PreferRepeatableRead ? unsafeIsolationDangers.length === 0 ? options_1.IsolationLevel.RepeatableRead : options_1.IsolationLevel.Serializable : state2.transactionOptions.isolation;
  68647. if (isolation !== state2.config.get("default_transaction_isolation")) {
  68648. state2 = state2.withConfig({
  68649. default_transaction_isolation: isolation
  68650. }).withTransactionOptions({
  68651. isolation
  68652. });
  68653. }
  68654. if (state2.transactionOptions.readonly !== state2.config.get("default_transaction_access_mode")) {
  68655. state2 = state2.withConfig({
  68656. default_transaction_access_mode: state2.transactionOptions.readonly ? "ReadOnly" : "ReadWrite"
  68657. });
  68658. }
  68659. }
  68660. const encodedState = this._setStateCodec(state2);
  68661. wb.writeBuffer(encodedState);
  68662. }
  68663. }
  68664. }
  68665. async _parse(language, query, outputFormat, expectedCardinality, state2, capabilitiesFlags = exports.RESTRICTED_CAPABILITIES, options, unsafeIsolationDangers = []) {
  68666. const wb = new buffer_1.WriteMessageBuffer();
  68667. wb.beginMessage(chars.$P);
  68668. this._encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, false, unsafeIsolationDangers);
  68669. wb.endMessage();
  68670. wb.writeSync();
  68671. this._sendData(wb.unwrap());
  68672. let parsing = true;
  68673. let error2 = null;
  68674. let newCard = null;
  68675. let capabilities = -1;
  68676. let inCodec = null;
  68677. let outCodec = null;
  68678. let inCodecBuf = null;
  68679. let outCodecBuf = null;
  68680. let warnings = [];
  68681. while (parsing) {
  68682. if (!this.buffer.takeMessage()) {
  68683. await this._waitForMessage();
  68684. }
  68685. const mtype = this.buffer.getMessageType();
  68686. switch (mtype) {
  68687. case chars.$T: {
  68688. try {
  68689. [
  68690. newCard,
  68691. inCodec,
  68692. outCodec,
  68693. capabilities,
  68694. inCodecBuf,
  68695. outCodecBuf,
  68696. warnings,
  68697. unsafeIsolationDangers
  68698. ] = this._parseDescribeTypeMessage(query);
  68699. const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
  68700. this.queryCodecCache.set(key, [
  68701. newCard,
  68702. inCodec,
  68703. outCodec,
  68704. capabilities,
  68705. unsafeIsolationDangers
  68706. ]);
  68707. } catch (e6) {
  68708. error2 = e6;
  68709. }
  68710. break;
  68711. }
  68712. case chars.$E: {
  68713. error2 = this._parseErrorMessage();
  68714. error2._query = query;
  68715. break;
  68716. }
  68717. case chars.$s: {
  68718. options_1.Options.signalSchemaChange();
  68719. this._parseDescribeStateMessage();
  68720. break;
  68721. }
  68722. case chars.$Z: {
  68723. this._parseSyncMessage();
  68724. parsing = false;
  68725. break;
  68726. }
  68727. default:
  68728. this._fallthrough();
  68729. }
  68730. }
  68731. if (error2 !== null) {
  68732. if (error2 instanceof errors.StateMismatchError) {
  68733. return this._parse(language, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, unsafeIsolationDangers);
  68734. }
  68735. throw error2;
  68736. }
  68737. return [
  68738. newCard,
  68739. inCodec,
  68740. outCodec,
  68741. capabilities,
  68742. inCodecBuf,
  68743. outCodecBuf,
  68744. warnings,
  68745. unsafeIsolationDangers
  68746. ];
  68747. }
  68748. async _executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec, outCodec, result, capabilitiesFlags = exports.RESTRICTED_CAPABILITIES, options, unsafeIsolationDangers = []) {
  68749. let currentUnsafeIsolationDangers = unsafeIsolationDangers;
  68750. let ctx = state2.makeCodecContext();
  68751. const wb = new buffer_1.WriteMessageBuffer();
  68752. wb.beginMessage(chars.$O);
  68753. this._encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, true, currentUnsafeIsolationDangers);
  68754. wb.writeBuffer(inCodec.tidBuffer);
  68755. wb.writeBuffer(outCodec.tidBuffer);
  68756. if (inCodec) {
  68757. wb.writeBuffer(this._encodeArgs(args, inCodec, ctx));
  68758. } else {
  68759. wb.writeInt32(0);
  68760. }
  68761. wb.endMessage();
  68762. wb.writeSync();
  68763. this._sendData(wb.unwrap());
  68764. let error2 = null;
  68765. let parsing = true;
  68766. let currentWarnings = [];
  68767. while (parsing) {
  68768. if (!this.buffer.takeMessage()) {
  68769. await this._waitForMessage();
  68770. }
  68771. const mtype = this.buffer.getMessageType();
  68772. switch (mtype) {
  68773. case chars.$D: {
  68774. if (error2 == null) {
  68775. try {
  68776. this._parseDataMessages(outCodec, result, ctx);
  68777. } catch (e6) {
  68778. error2 = e6;
  68779. this.buffer.finishMessage();
  68780. }
  68781. } else {
  68782. this.buffer.discardMessage();
  68783. }
  68784. break;
  68785. }
  68786. case chars.$C: {
  68787. this.lastStatus = this._parseCommandCompleteMessage();
  68788. break;
  68789. }
  68790. case chars.$Z: {
  68791. this._parseSyncMessage();
  68792. parsing = false;
  68793. break;
  68794. }
  68795. case chars.$T: {
  68796. try {
  68797. ctx = state2.makeCodecContext();
  68798. const [newCard, newInCodec, newOutCodec, capabilities, _3, __, _warnings, _dangers] = this._parseDescribeTypeMessage(query);
  68799. if (outCodec !== codecs_1.NULL_CODEC && outCodec.tid !== newOutCodec.tid || inCodec !== codecs_1.NULL_CODEC && inCodec.tid !== newInCodec.tid) {
  68800. options_1.Options.signalSchemaChange();
  68801. ctx = state2.makeCodecContext();
  68802. }
  68803. const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
  68804. this.queryCodecCache.set(key, [
  68805. newCard,
  68806. newInCodec,
  68807. newOutCodec,
  68808. capabilities,
  68809. _dangers
  68810. ]);
  68811. outCodec = newOutCodec;
  68812. currentWarnings = _warnings;
  68813. currentUnsafeIsolationDangers = _dangers;
  68814. } catch (e6) {
  68815. options_1.Options.signalSchemaChange();
  68816. error2 = e6;
  68817. }
  68818. break;
  68819. }
  68820. case chars.$s: {
  68821. options_1.Options.signalSchemaChange();
  68822. this._parseDescribeStateMessage();
  68823. break;
  68824. }
  68825. case chars.$E: {
  68826. error2 = this._parseErrorMessage();
  68827. error2._query = query;
  68828. break;
  68829. }
  68830. default:
  68831. this._fallthrough();
  68832. }
  68833. }
  68834. if (error2 != null) {
  68835. if (error2 instanceof errors.StateMismatchError) {
  68836. return this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec, outCodec, result, capabilitiesFlags, options, currentUnsafeIsolationDangers);
  68837. }
  68838. throw error2;
  68839. }
  68840. return [currentWarnings, currentUnsafeIsolationDangers];
  68841. }
  68842. _getQueryCacheKey(query, outputFormat, expectedCardinality, language = ifaces_1.Language.EDGEQL) {
  68843. const expectOne = expectedCardinality === ifaces_1.Cardinality.ONE || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE;
  68844. return [language, outputFormat, expectOne, query.length, query].join(";");
  68845. }
  68846. _validateFetchCardinality(card, outputFormat, expectedCardinality) {
  68847. if (expectedCardinality === ifaces_1.Cardinality.ONE && card === ifaces_1.Cardinality.NO_RESULT) {
  68848. throw new errors.NoDataError(`query executed via queryRequiredSingle${outputFormat === ifaces_1.OutputFormat.JSON ? "JSON" : ""}() returned no data`);
  68849. }
  68850. }
  68851. async fetch(query, args = null, outputFormat, expectedCardinality, state2, privilegedMode = false, language = ifaces_1.Language.EDGEQL) {
  68852. if (language !== ifaces_1.Language.EDGEQL && (0, utils_1.versionGreaterThan)([3, 0], this.protocolVersion)) {
  68853. throw new errors.UnsupportedFeatureError(`the server does not support SQL queries, upgrade to 6.0 or newer`);
  68854. }
  68855. this._checkState();
  68856. const requiredOne = expectedCardinality === ifaces_1.Cardinality.ONE;
  68857. const expectOne = requiredOne || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE;
  68858. const asJson = outputFormat === ifaces_1.OutputFormat.JSON;
  68859. const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality, language);
  68860. const ret = [];
  68861. let warnings = [];
  68862. let [card, inCodec, outCodec, , unsafeIsolationDangers] = this.queryCodecCache.get(key) ?? [];
  68863. if (card) {
  68864. this._validateFetchCardinality(card, outputFormat, expectedCardinality);
  68865. }
  68866. if (!inCodec && args !== null || this.stateCodec === codecs_1.INVALID_CODEC && !state2.isDefaultSession()) {
  68867. [card, inCodec, outCodec, , , , warnings, unsafeIsolationDangers] = await this._parse(language, query, outputFormat, expectedCardinality, state2, privilegedMode ? Capabilities.ALL : void 0, void 0, unsafeIsolationDangers);
  68868. this._validateFetchCardinality(card, outputFormat, expectedCardinality);
  68869. }
  68870. try {
  68871. [warnings, unsafeIsolationDangers] = await this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, ret, privilegedMode ? Capabilities.ALL : void 0, void 0, unsafeIsolationDangers);
  68872. } catch (e6) {
  68873. if (e6 instanceof errors.ParameterTypeMismatchError) {
  68874. [card, inCodec, outCodec, , unsafeIsolationDangers] = this.queryCodecCache.get(key);
  68875. [warnings, unsafeIsolationDangers] = await this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, ret, privilegedMode ? Capabilities.ALL : void 0);
  68876. } else {
  68877. throw e6;
  68878. }
  68879. }
  68880. if (outputFormat === ifaces_1.OutputFormat.NONE) {
  68881. return { result: null, warnings, unsafeIsolationDangers };
  68882. }
  68883. if (expectOne) {
  68884. if (requiredOne && !ret.length) {
  68885. throw new errors.NoDataError("query returned no data");
  68886. } else {
  68887. return {
  68888. result: ret[0] ?? (asJson ? "null" : null),
  68889. warnings,
  68890. unsafeIsolationDangers
  68891. };
  68892. }
  68893. } else {
  68894. if (ret && ret.length) {
  68895. if (asJson) {
  68896. return { result: ret[0], warnings, unsafeIsolationDangers };
  68897. } else {
  68898. return { result: ret, warnings, unsafeIsolationDangers };
  68899. }
  68900. } else {
  68901. if (asJson) {
  68902. return { result: "[]", warnings, unsafeIsolationDangers };
  68903. } else {
  68904. return { result: ret, warnings, unsafeIsolationDangers };
  68905. }
  68906. }
  68907. }
  68908. }
  68909. getQueryCapabilities(query, outputFormat, expectedCardinality) {
  68910. const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
  68911. return this.queryCodecCache.get(key)?.[3] ?? null;
  68912. }
  68913. async resetState() {
  68914. if (this.connected && this.serverXactStatus !== TransactionStatus.TRANS_IDLE) {
  68915. try {
  68916. await this.fetch(`rollback`, void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, options_1.Options.defaults(), true);
  68917. } catch {
  68918. this._abortWithError(new errors.ClientConnectionClosedError("failed to reset state"));
  68919. }
  68920. }
  68921. }
  68922. _abort() {
  68923. this.connected = false;
  68924. this._abortWaiters(this.getConnAbortError());
  68925. if (!this.connAbortWaiter.done) {
  68926. this.connAbortWaiter.set();
  68927. }
  68928. }
  68929. isClosed() {
  68930. return !this.connected;
  68931. }
  68932. async close() {
  68933. this._abort();
  68934. }
  68935. };
  68936. exports.BaseRawConnection = BaseRawConnection;
  68937. }
  68938. });
  68939. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/scram.js
  68940. var require_scram = __commonJS({
  68941. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/scram.js"(exports) {
  68942. "use strict";
  68943. Object.defineProperty(exports, "__esModule", { value: true });
  68944. exports.saslprep = saslprep;
  68945. exports.getSCRAM = getSCRAM;
  68946. var buffer_1 = require_buffer();
  68947. var errors_1 = require_errors();
  68948. var RAW_NONCE_LENGTH = 18;
  68949. function saslprep(str) {
  68950. return str.normalize("NFKC");
  68951. }
  68952. function getSCRAM({ randomBytes, H: H2, HMAC, makeKey }) {
  68953. function bufferEquals(a5, b5) {
  68954. if (a5.length !== b5.length) {
  68955. return false;
  68956. }
  68957. for (let i6 = 0, len = a5.length; i6 < len; i6++) {
  68958. if (a5[i6] !== b5[i6]) {
  68959. return false;
  68960. }
  68961. }
  68962. return true;
  68963. }
  68964. function generateNonce(length = RAW_NONCE_LENGTH) {
  68965. return randomBytes(length);
  68966. }
  68967. function buildClientFirstMessage(clientNonce, username) {
  68968. const bare = `n=${saslprep(username)},r=${(0, buffer_1.encodeB64)(clientNonce)}`;
  68969. return [`n,,${bare}`, bare];
  68970. }
  68971. function parseServerFirstMessage(msg) {
  68972. const attrs = msg.split(",");
  68973. if (attrs.length < 3) {
  68974. throw new errors_1.ProtocolError("malformed SCRAM message");
  68975. }
  68976. const nonceAttr = attrs[0];
  68977. if (!nonceAttr || nonceAttr[0] !== "r") {
  68978. throw new errors_1.ProtocolError("malformed SCRAM message");
  68979. }
  68980. const nonceB64 = nonceAttr.split("=", 2)[1];
  68981. if (!nonceB64) {
  68982. throw new errors_1.ProtocolError("malformed SCRAM message");
  68983. }
  68984. const nonce = (0, buffer_1.decodeB64)(nonceB64);
  68985. const saltAttr = attrs[1];
  68986. if (!saltAttr || saltAttr[0] !== "s") {
  68987. throw new errors_1.ProtocolError("malformed SCRAM message");
  68988. }
  68989. const saltB64 = saltAttr.split("=", 2)[1];
  68990. if (!saltB64) {
  68991. throw new errors_1.ProtocolError("malformed SCRAM message");
  68992. }
  68993. const salt = (0, buffer_1.decodeB64)(saltB64);
  68994. const iterAttr = attrs[2];
  68995. if (!iterAttr || iterAttr[0] !== "i") {
  68996. throw new errors_1.ProtocolError("malformed SCRAM message");
  68997. }
  68998. const iter = iterAttr.split("=", 2)[1];
  68999. if (!iter || !iter.match(/^[0-9]*$/)) {
  69000. throw new errors_1.ProtocolError("malformed SCRAM message");
  69001. }
  69002. const iterCount = parseInt(iter, 10);
  69003. if (iterCount <= 0) {
  69004. throw new errors_1.ProtocolError("malformed SCRAM message");
  69005. }
  69006. return [nonce, salt, iterCount];
  69007. }
  69008. function parseServerFinalMessage(msg) {
  69009. const attrs = msg.split(",");
  69010. if (attrs.length < 1) {
  69011. throw new errors_1.ProtocolError("malformed SCRAM message");
  69012. }
  69013. const nonceAttr = attrs[0];
  69014. if (!nonceAttr || nonceAttr[0] !== "v") {
  69015. throw new errors_1.ProtocolError("malformed SCRAM message");
  69016. }
  69017. const signatureB64 = nonceAttr.split("=", 2)[1];
  69018. if (!signatureB64) {
  69019. throw new errors_1.ProtocolError("malformed SCRAM message");
  69020. }
  69021. return (0, buffer_1.decodeB64)(signatureB64);
  69022. }
  69023. async function buildClientFinalMessage(password, salt, iterations, clientFirstBare, serverFirst, serverNonce) {
  69024. const clientFinal = `c=biws,r=${(0, buffer_1.encodeB64)(serverNonce)}`;
  69025. const authMessage = buffer_1.utf8Encoder.encode(`${clientFirstBare},${serverFirst},${clientFinal}`);
  69026. const saltedPassword = await _getSaltedPassword(buffer_1.utf8Encoder.encode(saslprep(password)), salt, iterations);
  69027. const clientKey = await _getClientKey(saltedPassword);
  69028. const storedKey = await H2(clientKey);
  69029. const clientSignature = await HMAC(storedKey, authMessage);
  69030. const clientProof = _XOR(clientKey, clientSignature);
  69031. const serverKey = await _getServerKey(saltedPassword);
  69032. const serverProof = await HMAC(serverKey, authMessage);
  69033. return [`${clientFinal},p=${(0, buffer_1.encodeB64)(clientProof)}`, serverProof];
  69034. }
  69035. async function _getSaltedPassword(password, salt, iterations) {
  69036. const msg = new Uint8Array(salt.length + 4);
  69037. msg.set(salt);
  69038. msg.set([0, 0, 0, 1], salt.length);
  69039. const keyFromPassword = await makeKey(password);
  69040. let Hi = await HMAC(keyFromPassword, msg);
  69041. let Ui = Hi;
  69042. for (let _3 = 0; _3 < iterations - 1; _3++) {
  69043. Ui = await HMAC(keyFromPassword, Ui);
  69044. Hi = _XOR(Hi, Ui);
  69045. }
  69046. return Hi;
  69047. }
  69048. function _getClientKey(saltedPassword) {
  69049. return HMAC(saltedPassword, buffer_1.utf8Encoder.encode("Client Key"));
  69050. }
  69051. function _getServerKey(saltedPassword) {
  69052. return HMAC(saltedPassword, buffer_1.utf8Encoder.encode("Server Key"));
  69053. }
  69054. function _XOR(a5, b5) {
  69055. const len = a5.length;
  69056. if (len !== b5.length) {
  69057. throw new errors_1.ProtocolError("scram.XOR: buffers are of different lengths");
  69058. }
  69059. const res = new Uint8Array(len);
  69060. for (let i6 = 0; i6 < len; i6++) {
  69061. res[i6] = a5[i6] ^ b5[i6];
  69062. }
  69063. return res;
  69064. }
  69065. return {
  69066. bufferEquals,
  69067. generateNonce,
  69068. buildClientFirstMessage,
  69069. parseServerFirstMessage,
  69070. parseServerFinalMessage,
  69071. buildClientFinalMessage,
  69072. _getSaltedPassword,
  69073. _getClientKey,
  69074. _getServerKey,
  69075. _XOR
  69076. };
  69077. }
  69078. }
  69079. });
  69080. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/browserCrypto.js
  69081. var require_browserCrypto = __commonJS({
  69082. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/browserCrypto.js"(exports) {
  69083. "use strict";
  69084. Object.defineProperty(exports, "__esModule", { value: true });
  69085. exports.cryptoUtils = void 0;
  69086. async function makeKey(key) {
  69087. return await crypto.subtle.importKey("raw", key, {
  69088. name: "HMAC",
  69089. hash: { name: "SHA-256" }
  69090. }, false, ["sign"]);
  69091. }
  69092. function randomBytes(size) {
  69093. return crypto.getRandomValues(new Uint8Array(size));
  69094. }
  69095. async function H2(msg) {
  69096. return new Uint8Array(await crypto.subtle.digest("SHA-256", msg));
  69097. }
  69098. async function HMAC(key, msg) {
  69099. const cryptoKey = key instanceof Uint8Array ? await makeKey(key) : key;
  69100. return new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, msg));
  69101. }
  69102. exports.cryptoUtils = {
  69103. makeKey,
  69104. randomBytes,
  69105. H: H2,
  69106. HMAC
  69107. };
  69108. }
  69109. });
  69110. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeCrypto.js
  69111. var require_nodeCrypto = __commonJS({
  69112. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeCrypto.js"(exports) {
  69113. "use strict";
  69114. var __importDefault = exports && exports.__importDefault || function(mod) {
  69115. return mod && mod.__esModule ? mod : { "default": mod };
  69116. };
  69117. Object.defineProperty(exports, "__esModule", { value: true });
  69118. exports.cryptoUtils = void 0;
  69119. var node_crypto_1 = __importDefault(__require("crypto"));
  69120. function makeKey(keyBytes) {
  69121. return Promise.resolve(keyBytes);
  69122. }
  69123. function randomBytes(size) {
  69124. return node_crypto_1.default.randomBytes(size);
  69125. }
  69126. async function H2(msg) {
  69127. const sign = node_crypto_1.default.createHash("sha256");
  69128. sign.update(msg);
  69129. return sign.digest();
  69130. }
  69131. async function HMAC(key, msg) {
  69132. const cryptoKey = key instanceof Uint8Array ? key : node_crypto_1.default.KeyObject.from(key);
  69133. const hm = node_crypto_1.default.createHmac("sha256", cryptoKey);
  69134. hm.update(msg);
  69135. return hm.digest();
  69136. }
  69137. exports.cryptoUtils = {
  69138. makeKey,
  69139. randomBytes,
  69140. H: H2,
  69141. HMAC
  69142. };
  69143. }
  69144. });
  69145. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/cryptoUtils.js
  69146. var require_cryptoUtils = __commonJS({
  69147. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/cryptoUtils.js"(exports) {
  69148. "use strict";
  69149. Object.defineProperty(exports, "__esModule", { value: true });
  69150. var browserCrypto_1 = require_browserCrypto();
  69151. var isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
  69152. var cryptoUtils;
  69153. function loadCrypto() {
  69154. if (isNode) {
  69155. try {
  69156. __require("crypto");
  69157. cryptoUtils = require_nodeCrypto().cryptoUtils;
  69158. } catch (_3) {
  69159. if (typeof globalThis.crypto !== "undefined") {
  69160. cryptoUtils = browserCrypto_1.cryptoUtils;
  69161. } else {
  69162. throw new Error("No crypto implementation found");
  69163. }
  69164. }
  69165. } else {
  69166. cryptoUtils = browserCrypto_1.cryptoUtils;
  69167. }
  69168. }
  69169. loadCrypto();
  69170. exports.default = cryptoUtils;
  69171. }
  69172. });
  69173. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/rawConn.js
  69174. var require_rawConn = __commonJS({
  69175. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/rawConn.js"(exports) {
  69176. "use strict";
  69177. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  69178. if (k22 === void 0) k22 = k5;
  69179. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  69180. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  69181. desc = { enumerable: true, get: function() {
  69182. return m6[k5];
  69183. } };
  69184. }
  69185. Object.defineProperty(o5, k22, desc);
  69186. } : function(o5, m6, k5, k22) {
  69187. if (k22 === void 0) k22 = k5;
  69188. o5[k22] = m6[k5];
  69189. });
  69190. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  69191. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  69192. } : function(o5, v6) {
  69193. o5["default"] = v6;
  69194. });
  69195. var __importStar = exports && exports.__importStar || function(mod) {
  69196. if (mod && mod.__esModule) return mod;
  69197. var result = {};
  69198. if (mod != null) {
  69199. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  69200. }
  69201. __setModuleDefault(result, mod);
  69202. return result;
  69203. };
  69204. var __importDefault = exports && exports.__importDefault || function(mod) {
  69205. return mod && mod.__esModule ? mod : { "default": mod };
  69206. };
  69207. Object.defineProperty(exports, "__esModule", { value: true });
  69208. exports.RawConnection = void 0;
  69209. var node_net_1 = __importDefault(__require("net"));
  69210. var tls = __importStar(__require("tls"));
  69211. var baseConn_1 = require_baseConn();
  69212. var utils_1 = require_utils2();
  69213. var buffer_1 = require_buffer();
  69214. var event_1 = __importDefault(require_event());
  69215. var chars = __importStar(require_chars());
  69216. var scram_1 = require_scram();
  69217. var errors = __importStar(require_errors());
  69218. var cryptoUtils_1 = __importDefault(require_cryptoUtils());
  69219. var AuthenticationStatuses;
  69220. (function(AuthenticationStatuses2) {
  69221. AuthenticationStatuses2[AuthenticationStatuses2["AUTH_OK"] = 0] = "AUTH_OK";
  69222. AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL"] = 10] = "AUTH_SASL";
  69223. AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL_CONTINUE"] = 11] = "AUTH_SASL_CONTINUE";
  69224. AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL_FINAL"] = 12] = "AUTH_SASL_FINAL";
  69225. })(AuthenticationStatuses || (AuthenticationStatuses = {}));
  69226. var scram = (0, scram_1.getSCRAM)(cryptoUtils_1.default);
  69227. var _tlsOptions = /* @__PURE__ */ new WeakMap();
  69228. function getTlsOptions(config) {
  69229. if (_tlsOptions.has(config)) {
  69230. return _tlsOptions.get(config);
  69231. }
  69232. const tlsSecurity = config.tlsSecurity;
  69233. const tlsOptions = {
  69234. ALPNProtocols: ["edgedb-binary"],
  69235. rejectUnauthorized: tlsSecurity !== "insecure"
  69236. };
  69237. const isIPAddress = node_net_1.default.isIP(config.address[0]) !== 0;
  69238. if (!isIPAddress) {
  69239. tlsOptions.servername = config.tlsServerName || config.address[0];
  69240. }
  69241. _tlsOptions.set(config, tlsOptions);
  69242. if (config._tlsCAData !== null) {
  69243. tlsOptions.ca = config._tlsCAData;
  69244. }
  69245. if (tlsSecurity === "no_host_verification") {
  69246. tlsOptions.checkServerIdentity = (hostname, cert) => {
  69247. const err2 = tls.checkServerIdentity(hostname, cert);
  69248. if (err2 === void 0) {
  69249. return void 0;
  69250. }
  69251. if (err2.message.startsWith("Hostname/IP does not match certificate")) {
  69252. return void 0;
  69253. }
  69254. return err2;
  69255. };
  69256. }
  69257. return tlsOptions;
  69258. }
  69259. var RawConnection = class extends baseConn_1.BaseRawConnection {
  69260. constructor(sock, config, registry) {
  69261. super(registry);
  69262. __publicField(this, "config");
  69263. __publicField(this, "sock");
  69264. __publicField(this, "paused");
  69265. this.config = config;
  69266. this.paused = false;
  69267. this.sock = sock;
  69268. this.sock.setNoDelay();
  69269. this.sock.on("error", this._onError.bind(this));
  69270. this.sock.on("data", this._onData.bind(this));
  69271. if (tls.TLSSocket && this.sock instanceof tls.TLSSocket) {
  69272. this.sock.on("secureConnect", this._onConnect.bind(this));
  69273. } else {
  69274. this.sock.on("connect", this._onConnect.bind(this));
  69275. }
  69276. this.sock.on("close", this._onClose.bind(this));
  69277. }
  69278. _onConnect() {
  69279. this.connWaiter.set();
  69280. }
  69281. _onClose() {
  69282. if (!this.connected) {
  69283. return;
  69284. }
  69285. const newErr = new errors.ClientConnectionClosedError(`the connection has been aborted`);
  69286. if (!this.connWaiter.done || this.messageWaiter) {
  69287. this._abortWaiters(newErr);
  69288. }
  69289. if (this.buffer.takeMessage() && this.buffer.getMessageType() === chars.$E) {
  69290. Object.defineProperty(newErr, "cause", {
  69291. enumerable: false,
  69292. value: this._parseErrorMessage()
  69293. });
  69294. }
  69295. this._abortWithError(newErr);
  69296. }
  69297. _onError(err2) {
  69298. const newErr = new errors.ClientConnectionClosedError(`network error: ${err2}`, { cause: err2 });
  69299. try {
  69300. this._abortWaiters(newErr);
  69301. } finally {
  69302. this._abortWithError(newErr);
  69303. }
  69304. }
  69305. _onData(data) {
  69306. try {
  69307. this.buffer.feed(data);
  69308. } catch (e6) {
  69309. if (this.messageWaiter) {
  69310. this.messageWaiter.setError(e6);
  69311. this.messageWaiter = null;
  69312. }
  69313. this._abortWithError(e6);
  69314. }
  69315. if (this.messageWaiter) {
  69316. if (this.buffer.takeMessage()) {
  69317. this.messageWaiter.set();
  69318. this.messageWaiter = null;
  69319. }
  69320. }
  69321. }
  69322. async _waitForMessage() {
  69323. if (this.buffer.takeMessage()) {
  69324. return;
  69325. }
  69326. if (this.paused) {
  69327. this.paused = false;
  69328. this.sock.resume();
  69329. }
  69330. this.sock.ref();
  69331. this.messageWaiter = new event_1.default();
  69332. try {
  69333. await this.messageWaiter.wait();
  69334. } finally {
  69335. this.sock.unref();
  69336. }
  69337. }
  69338. _sendData(data) {
  69339. this.sock.write(data);
  69340. }
  69341. static newSock(addr, options) {
  69342. if (typeof addr === "string") {
  69343. return node_net_1.default.createConnection(addr);
  69344. }
  69345. const [host, port] = addr;
  69346. if (options == null) {
  69347. return node_net_1.default.createConnection(port, host);
  69348. }
  69349. const opts = { ...options, host, port };
  69350. return tls.connect(opts);
  69351. }
  69352. _abort() {
  69353. if (this.sock && this.connected) {
  69354. this.sock.destroy();
  69355. }
  69356. super._abort();
  69357. }
  69358. async close() {
  69359. if (this.sock && this.connected) {
  69360. this.sock.write(new buffer_1.WriteMessageBuffer().beginMessage(chars.$X).endMessage().unwrap());
  69361. }
  69362. return await super.close();
  69363. }
  69364. static async connectWithTimeout(config, registry, useTls = true) {
  69365. const sock = this.newSock(config.connectionParams.address, useTls ? getTlsOptions(config.connectionParams) : void 0);
  69366. const conn = new this(sock, config, registry);
  69367. const connPromise = conn.connect();
  69368. let timeoutCb = null;
  69369. let timeoutHappened = false;
  69370. if (config.connectTimeout) {
  69371. timeoutCb = setTimeout(() => {
  69372. if (!conn.connected) {
  69373. timeoutHappened = true;
  69374. conn.sock.destroy(new errors.ClientConnectionTimeoutError(`connection timed out (${config.connectTimeout}ms)`));
  69375. }
  69376. }, config.connectTimeout);
  69377. }
  69378. try {
  69379. await connPromise;
  69380. } catch (e6) {
  69381. conn._abort();
  69382. if (timeoutHappened && e6 instanceof errors.ClientConnectionClosedError) {
  69383. throw new errors.ClientConnectionTimeoutError(`connection timed out (${config.connectTimeout}ms)`);
  69384. }
  69385. if (e6 instanceof errors.GelError) {
  69386. throw e6;
  69387. } else {
  69388. let err2;
  69389. switch (e6.code) {
  69390. case "EPROTO":
  69391. if (useTls === true) {
  69392. try {
  69393. return this.connectWithTimeout(config, registry, false);
  69394. } catch {
  69395. }
  69396. }
  69397. err2 = new errors.ClientConnectionFailedError(`${e6.message}
  69398. Attempted to connect using the following credentials:
  69399. ${config.connectionParams.explainConfig()}
  69400. `, { cause: e6 });
  69401. break;
  69402. case "ECONNREFUSED":
  69403. case "ECONNABORTED":
  69404. case "ECONNRESET":
  69405. case "ENOTFOUND":
  69406. case "ENOENT":
  69407. err2 = new errors.ClientConnectionFailedTemporarilyError(`${e6.message}
  69408. Attempted to connect using the following credentials:
  69409. ${config.connectionParams.explainConfig()}
  69410. `, { cause: e6 });
  69411. break;
  69412. default:
  69413. err2 = new errors.ClientConnectionFailedError(`${e6.message}
  69414. Attempted to connect using the following credentials:
  69415. ${config.connectionParams.explainConfig()}
  69416. `, { cause: e6 });
  69417. break;
  69418. }
  69419. throw err2;
  69420. }
  69421. } finally {
  69422. if (timeoutCb != null) {
  69423. clearTimeout(timeoutCb);
  69424. }
  69425. }
  69426. return conn;
  69427. }
  69428. async connect() {
  69429. await this.connWaiter.wait();
  69430. if (this.sock instanceof tls.TLSSocket) {
  69431. if (this.sock.alpnProtocol !== "edgedb-binary") {
  69432. throw new errors.ClientConnectionFailedError("The server doesn't support the edgedb-binary protocol.");
  69433. }
  69434. }
  69435. const handshake = new buffer_1.WriteMessageBuffer();
  69436. handshake.beginMessage(chars.$V).writeInt16(this.protocolVersion[0]).writeInt16(this.protocolVersion[1]);
  69437. const clientHandshakeOptions = {
  69438. user: this.config.connectionParams.user,
  69439. database: this.config.connectionParams.database
  69440. };
  69441. if (this.config.connectionParams.secretKey != null) {
  69442. clientHandshakeOptions.secret_key = this.config.connectionParams.secretKey;
  69443. }
  69444. handshake.writeInt16(Object.keys(clientHandshakeOptions).length);
  69445. for (const [key, value] of Object.entries(clientHandshakeOptions)) {
  69446. handshake.writeString(key).writeString(value);
  69447. }
  69448. handshake.writeInt16(0);
  69449. handshake.endMessage();
  69450. this.sock.write(handshake.unwrap());
  69451. while (true) {
  69452. if (!this.buffer.takeMessage()) {
  69453. await this._waitForMessage();
  69454. }
  69455. const mtype = this.buffer.getMessageType();
  69456. switch (mtype) {
  69457. case chars.$v: {
  69458. const hi = this.buffer.readInt16();
  69459. const lo = this.buffer.readInt16();
  69460. this._parseHeaders();
  69461. this.buffer.finishMessage();
  69462. const proposed = [hi, lo];
  69463. if ((0, utils_1.versionGreaterThan)(proposed, baseConn_1.PROTO_VER) || (0, utils_1.versionGreaterThan)(baseConn_1.PROTO_VER_MIN, proposed)) {
  69464. throw new errors.UnsupportedProtocolVersionError(`the server requested an unsupported version of the protocol ${hi}.${lo}`);
  69465. }
  69466. this.protocolVersion = [hi, lo];
  69467. break;
  69468. }
  69469. case chars.$R: {
  69470. const status = this.buffer.readInt32();
  69471. if (status === AuthenticationStatuses.AUTH_OK) {
  69472. this.buffer.finishMessage();
  69473. } else if (status === AuthenticationStatuses.AUTH_SASL) {
  69474. await this._authSasl();
  69475. } else {
  69476. throw new errors.ProtocolError(`unsupported authentication method requested by the server: ${status}`);
  69477. }
  69478. break;
  69479. }
  69480. case chars.$K: {
  69481. this.serverSecret = this.buffer.readBuffer(32);
  69482. this.buffer.finishMessage();
  69483. break;
  69484. }
  69485. case chars.$E: {
  69486. throw this._parseErrorMessage();
  69487. }
  69488. case chars.$s: {
  69489. this._parseDescribeStateMessage();
  69490. break;
  69491. }
  69492. case chars.$Z: {
  69493. this._parseSyncMessage();
  69494. if (!(this.sock instanceof tls.TLSSocket) && typeof Deno === "undefined") {
  69495. const [major, minor] = this.protocolVersion;
  69496. throw new errors.ProtocolError(`the protocol version requires TLS: ${major}.${minor}`);
  69497. }
  69498. this.connected = true;
  69499. return;
  69500. }
  69501. default:
  69502. this._fallthrough();
  69503. }
  69504. }
  69505. }
  69506. async _authSasl() {
  69507. const numMethods = this.buffer.readInt32();
  69508. if (numMethods <= 0) {
  69509. throw new errors.ProtocolError("the server requested SASL authentication but did not offer any methods");
  69510. }
  69511. const methods = [];
  69512. let foundScram256 = false;
  69513. for (let _3 = 0; _3 < numMethods; _3++) {
  69514. const method = this.buffer.readString();
  69515. if (method === "SCRAM-SHA-256") {
  69516. foundScram256 = true;
  69517. }
  69518. methods.push(method);
  69519. }
  69520. this.buffer.finishMessage();
  69521. if (!foundScram256) {
  69522. throw new errors.ProtocolError(`the server offered the following SASL authentication methods: ${methods.join(", ")}, neither are supported.`);
  69523. }
  69524. const clientNonce = scram.generateNonce();
  69525. const [clientFirst, clientFirstBare] = scram.buildClientFirstMessage(clientNonce, this.config.connectionParams.user);
  69526. const wb = new buffer_1.WriteMessageBuffer();
  69527. wb.beginMessage(chars.$p).writeString("SCRAM-SHA-256").writeString(clientFirst).endMessage();
  69528. this.sock.write(wb.unwrap());
  69529. await this._ensureMessage(chars.$R, "SASLContinue");
  69530. let status = this.buffer.readInt32();
  69531. if (status !== AuthenticationStatuses.AUTH_SASL_CONTINUE) {
  69532. throw new errors.ProtocolError(`expected SASLContinue from the server, received ${status}`);
  69533. }
  69534. const serverFirst = this.buffer.readString();
  69535. this.buffer.finishMessage();
  69536. const [serverNonce, salt, itercount] = scram.parseServerFirstMessage(serverFirst);
  69537. const [clientFinal, expectedServerSig] = await scram.buildClientFinalMessage(this.config.connectionParams.password || "", salt, itercount, clientFirstBare, serverFirst, serverNonce);
  69538. wb.reset().beginMessage(chars.$r).writeString(clientFinal).endMessage();
  69539. this.sock.write(wb.unwrap());
  69540. await this._ensureMessage(chars.$R, "SASLFinal");
  69541. status = this.buffer.readInt32();
  69542. if (status !== AuthenticationStatuses.AUTH_SASL_FINAL) {
  69543. throw new errors.ProtocolError(`expected SASLFinal from the server, received ${status}`);
  69544. }
  69545. const serverFinal = this.buffer.readString();
  69546. this.buffer.finishMessage();
  69547. const serverSig = scram.parseServerFinalMessage(serverFinal);
  69548. if (!scram.bufferEquals(serverSig, expectedServerSig)) {
  69549. throw new errors.ProtocolError("server SCRAM proof does not match");
  69550. }
  69551. }
  69552. async _ensureMessage(expectedMtype, err2) {
  69553. if (!this.buffer.takeMessage()) {
  69554. await this._waitForMessage();
  69555. }
  69556. const mtype = this.buffer.getMessageType();
  69557. switch (mtype) {
  69558. case chars.$E: {
  69559. throw this._parseErrorMessage();
  69560. }
  69561. case expectedMtype: {
  69562. return;
  69563. }
  69564. default: {
  69565. throw new errors.UnexpectedMessageError(`expected ${err2} from the server, received ${chars.chr(mtype)}`);
  69566. }
  69567. }
  69568. }
  69569. };
  69570. exports.RawConnection = RawConnection;
  69571. }
  69572. });
  69573. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/fetchConn.js
  69574. var require_fetchConn = __commonJS({
  69575. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/fetchConn.js"(exports) {
  69576. "use strict";
  69577. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  69578. if (k22 === void 0) k22 = k5;
  69579. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  69580. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  69581. desc = { enumerable: true, get: function() {
  69582. return m6[k5];
  69583. } };
  69584. }
  69585. Object.defineProperty(o5, k22, desc);
  69586. } : function(o5, m6, k5, k22) {
  69587. if (k22 === void 0) k22 = k5;
  69588. o5[k22] = m6[k5];
  69589. });
  69590. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  69591. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  69592. } : function(o5, v6) {
  69593. o5["default"] = v6;
  69594. });
  69595. var __importStar = exports && exports.__importStar || function(mod) {
  69596. if (mod && mod.__esModule) return mod;
  69597. var result = {};
  69598. if (mod != null) {
  69599. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  69600. }
  69601. __setModuleDefault(result, mod);
  69602. return result;
  69603. };
  69604. var __importDefault = exports && exports.__importDefault || function(mod) {
  69605. return mod && mod.__esModule ? mod : { "default": mod };
  69606. };
  69607. Object.defineProperty(exports, "__esModule", { value: true });
  69608. exports.FetchConnection = exports.AdminUIFetchConnection = void 0;
  69609. var baseConn_1 = require_baseConn();
  69610. var codecs_1 = require_codecs();
  69611. var errors_1 = require_errors();
  69612. var ifaces_1 = require_ifaces2();
  69613. var buffer_1 = require_buffer();
  69614. var chars = __importStar(require_chars());
  69615. var event_1 = __importDefault(require_event());
  69616. var utils_1 = require_utils2();
  69617. var PROTO_MIME = `application/x.edgedb.v_${baseConn_1.PROTO_VER[0]}_${baseConn_1.PROTO_VER[1]}.binary'`;
  69618. var PROTO_MIME_RE = /application\/x\.edgedb\.v_(\d+)_(\d+)\.binary/;
  69619. var STUDIO_CAPABILITIES = (baseConn_1.RESTRICTED_CAPABILITIES | baseConn_1.Capabilities.SESSION_CONFIG | baseConn_1.Capabilities.SET_GLOBAL) >>> 0;
  69620. var BaseFetchConnection = class extends baseConn_1.BaseRawConnection {
  69621. constructor(fetch3, registry) {
  69622. super(registry);
  69623. __publicField(this, "authenticatedFetch");
  69624. __publicField(this, "abortSignal", null);
  69625. this.authenticatedFetch = fetch3;
  69626. }
  69627. async _waitForMessage() {
  69628. if (this.buffer.takeMessage()) {
  69629. return;
  69630. }
  69631. if (this.messageWaiter == null || this.messageWaiter.done) {
  69632. throw new errors_1.InternalClientError(`message waiter was not initialized before waiting for response`);
  69633. }
  69634. await this.messageWaiter.wait();
  69635. }
  69636. async __sendData(data) {
  69637. if (this.buffer.takeMessage()) {
  69638. const mtype = this.buffer.getMessageType();
  69639. throw new errors_1.InternalClientError(`sending request before reading all data of the previous one: ${chars.chr(mtype)}`);
  69640. }
  69641. if (this.messageWaiter != null && !this.messageWaiter.done) {
  69642. throw new errors_1.InternalClientError(`sending request before waiting for completion of the previous one`);
  69643. }
  69644. this.messageWaiter = new event_1.default();
  69645. try {
  69646. const resp = await this.authenticatedFetch("", {
  69647. method: "post",
  69648. body: data,
  69649. headers: {
  69650. "Content-Type": PROTO_MIME
  69651. },
  69652. signal: this.abortSignal
  69653. });
  69654. if (!resp.ok) {
  69655. throw new errors_1.ProtocolError(`fetch failed with status code ${resp.status}: ${resp.statusText}`);
  69656. }
  69657. const contentType = resp.headers.get("content-type");
  69658. const matchProtoVer = contentType?.match(PROTO_MIME_RE);
  69659. if (matchProtoVer) {
  69660. this.protocolVersion = [+matchProtoVer[1], +matchProtoVer[2]];
  69661. }
  69662. const respData = await resp.arrayBuffer();
  69663. const buf = new Uint8Array(respData);
  69664. try {
  69665. this.buffer.feed(buf);
  69666. } catch (e6) {
  69667. this.messageWaiter.setError(e6);
  69668. }
  69669. if (!this.buffer.takeMessage()) {
  69670. throw new errors_1.ProtocolError("no binary protocol messages in the response");
  69671. }
  69672. this.messageWaiter.set();
  69673. } catch (e6) {
  69674. this.messageWaiter.setError(e6);
  69675. } finally {
  69676. this.messageWaiter = null;
  69677. }
  69678. }
  69679. _sendData(data) {
  69680. this.__sendData(data);
  69681. }
  69682. async fetch(...args) {
  69683. const protoVer = this.protocolVersion;
  69684. try {
  69685. return await super.fetch(...args);
  69686. } catch (err2) {
  69687. if (err2 instanceof errors_1.BinaryProtocolError && !(0, utils_1.versionEqual)(protoVer, this.protocolVersion)) {
  69688. return await super.fetch(...args);
  69689. }
  69690. throw err2;
  69691. }
  69692. }
  69693. static create(fetch3, registry) {
  69694. const conn = new this(fetch3, registry);
  69695. conn.connected = true;
  69696. conn.connWaiter.set();
  69697. return conn;
  69698. }
  69699. };
  69700. var AdminUIFetchConnection = class extends BaseFetchConnection {
  69701. constructor() {
  69702. super(...arguments);
  69703. __publicField(this, "adminUIMode", true);
  69704. }
  69705. static create(fetch3, registry, knownServerVersion) {
  69706. const conn = super.create(fetch3, registry);
  69707. if (knownServerVersion && knownServerVersion[0] < 6) {
  69708. conn.protocolVersion = [2, 0];
  69709. }
  69710. return conn;
  69711. }
  69712. async rawParse(language, query, state2, options, abortSignal) {
  69713. this.abortSignal = abortSignal ?? null;
  69714. const result = await this._parse(language, query, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, state2, STUDIO_CAPABILITIES, options);
  69715. return [this.protocolVersion, ...result];
  69716. }
  69717. async rawExecute(language, query, state2, outCodec, options, inCodec, args = null, abortSignal) {
  69718. this.abortSignal = abortSignal ?? null;
  69719. const result = new buffer_1.WriteBuffer();
  69720. const [warnings] = await this._executeFlow(language, query, args, outCodec ? ifaces_1.OutputFormat.BINARY : ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.MANY, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, result, STUDIO_CAPABILITIES, options);
  69721. return [result.unwrap(), warnings];
  69722. }
  69723. };
  69724. exports.AdminUIFetchConnection = AdminUIFetchConnection;
  69725. var FetchConnection = class _FetchConnection extends BaseFetchConnection {
  69726. static createConnectWithTimeout(httpSCRAMAuth) {
  69727. return async function connectWithTimeout(config, registry) {
  69728. const fetch3 = await (0, utils_1.getAuthenticatedFetch)(config.connectionParams, httpSCRAMAuth);
  69729. const conn = new _FetchConnection(fetch3, registry);
  69730. conn.connected = true;
  69731. conn.connWaiter.set();
  69732. return conn;
  69733. };
  69734. }
  69735. };
  69736. exports.FetchConnection = FetchConnection;
  69737. }
  69738. });
  69739. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/httpScram.js
  69740. var require_httpScram = __commonJS({
  69741. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/httpScram.js"(exports) {
  69742. "use strict";
  69743. Object.defineProperty(exports, "__esModule", { value: true });
  69744. exports.getHTTPSCRAMAuth = getHTTPSCRAMAuth;
  69745. var errors_1 = require_errors();
  69746. var buffer_1 = require_buffer();
  69747. var scram_1 = require_scram();
  69748. var AUTH_ENDPOINT = "/auth/token";
  69749. function getHTTPSCRAMAuth(cryptoUtils) {
  69750. const { bufferEquals, generateNonce, buildClientFirstMessage, buildClientFinalMessage, parseServerFirstMessage, parseServerFinalMessage } = (0, scram_1.getSCRAM)(cryptoUtils);
  69751. return async function HTTPSCRAMAuth(baseUrl, username, password) {
  69752. const authUrl = baseUrl + AUTH_ENDPOINT;
  69753. const clientNonce = generateNonce();
  69754. const [clientFirst, clientFirstBare] = buildClientFirstMessage(clientNonce, username);
  69755. const serverFirstRes = await fetch(authUrl, {
  69756. headers: {
  69757. Authorization: `SCRAM-SHA-256 data=${utf8ToB64(clientFirst)}`
  69758. }
  69759. });
  69760. const authenticateHeader = serverFirstRes.headers.get("WWW-Authenticate");
  69761. if (serverFirstRes.status !== 401 || !authenticateHeader) {
  69762. const body = await serverFirstRes.text();
  69763. throw new errors_1.ProtocolError(`authentication failed: ${body}`);
  69764. }
  69765. if (!authenticateHeader.startsWith("SCRAM-SHA-256")) {
  69766. throw new errors_1.ProtocolError(`unsupported authentication scheme: ${authenticateHeader}`);
  69767. }
  69768. const authParams = authenticateHeader.split(/ (.+)?/, 2)[1] ?? "";
  69769. if (authParams.length === 0) {
  69770. const body = await serverFirstRes.text();
  69771. throw new errors_1.ProtocolError(`authentication failed: ${body}`);
  69772. }
  69773. const { sid, data: serverFirst } = parseScramAttrs(authParams);
  69774. if (!sid || !serverFirst) {
  69775. throw new errors_1.ProtocolError(`authentication challenge missing attributes: expected "sid" and "data", got '${authParams}'`);
  69776. }
  69777. const [serverNonce, salt, iterCount] = parseServerFirstMessage(serverFirst);
  69778. const [clientFinal, expectedServerSig] = await buildClientFinalMessage(password, salt, iterCount, clientFirstBare, serverFirst, serverNonce);
  69779. const serverFinalRes = await fetch(authUrl, {
  69780. headers: {
  69781. Authorization: `SCRAM-SHA-256 sid=${sid}, data=${utf8ToB64(clientFinal)}`
  69782. }
  69783. });
  69784. const authInfoHeader = serverFinalRes.headers.get("Authentication-Info");
  69785. if (!serverFinalRes.ok || !authInfoHeader) {
  69786. const body = await serverFinalRes.text();
  69787. throw new errors_1.ProtocolError(`authentication failed: ${body}`);
  69788. }
  69789. const { data: serverFinal, sid: sidFinal } = parseScramAttrs(authInfoHeader);
  69790. if (!sidFinal || !serverFinal) {
  69791. throw new errors_1.ProtocolError(`authentication info missing attributes: expected "sid" and "data", got '${authInfoHeader}'`);
  69792. }
  69793. if (sidFinal !== sid) {
  69794. throw new errors_1.ProtocolError("SCRAM session id does not match");
  69795. }
  69796. const serverSig = parseServerFinalMessage(serverFinal);
  69797. if (!bufferEquals(serverSig, expectedServerSig)) {
  69798. throw new errors_1.ProtocolError("server SCRAM proof does not match");
  69799. }
  69800. const authToken = await serverFinalRes.text();
  69801. return authToken;
  69802. };
  69803. }
  69804. function utf8ToB64(str) {
  69805. return (0, buffer_1.encodeB64)(buffer_1.utf8Encoder.encode(str));
  69806. }
  69807. function b64ToUtf8(str) {
  69808. return buffer_1.utf8Decoder.decode((0, buffer_1.decodeB64)(str));
  69809. }
  69810. function parseScramAttrs(paramsStr) {
  69811. const params = new Map(paramsStr.length > 0 ? paramsStr.split(",").map((attr) => attr.split(/=(.+)?/, 2)).map(([key, val2]) => [key.trim(), val2.trim()]) : []);
  69812. const sid = params.get("sid") ?? null;
  69813. const rawData = params.get("data");
  69814. const data = rawData ? b64ToUtf8(rawData) : null;
  69815. return { sid, data };
  69816. }
  69817. }
  69818. });
  69819. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeClient.js
  69820. var require_nodeClient = __commonJS({
  69821. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeClient.js"(exports) {
  69822. "use strict";
  69823. var __importDefault = exports && exports.__importDefault || function(mod) {
  69824. return mod && mod.__esModule ? mod : { "default": mod };
  69825. };
  69826. Object.defineProperty(exports, "__esModule", { value: true });
  69827. exports.createClient = createClient;
  69828. exports.createHttpClient = createHttpClient;
  69829. var baseClient_1 = require_baseClient();
  69830. var conUtils_server_1 = require_conUtils_server();
  69831. var options_1 = require_options();
  69832. var rawConn_1 = require_rawConn();
  69833. var fetchConn_1 = require_fetchConn();
  69834. var httpScram_1 = require_httpScram();
  69835. var cryptoUtils_1 = __importDefault(require_cryptoUtils());
  69836. var ClientPool = class extends baseClient_1.BaseClientPool {
  69837. constructor() {
  69838. super(...arguments);
  69839. __publicField(this, "isStateless", false);
  69840. __publicField(this, "_connectWithTimeout", rawConn_1.RawConnection.connectWithTimeout.bind(rawConn_1.RawConnection));
  69841. }
  69842. };
  69843. function createClient(options) {
  69844. return new baseClient_1.Client(new ClientPool(conUtils_server_1.parseConnectArguments, typeof options === "string" ? { dsn: options } : options ?? {}), options_1.Options.defaults());
  69845. }
  69846. var httpSCRAMAuth = (0, httpScram_1.getHTTPSCRAMAuth)(cryptoUtils_1.default);
  69847. var FetchClientPool = class extends baseClient_1.BaseClientPool {
  69848. constructor() {
  69849. super(...arguments);
  69850. __publicField(this, "isStateless", true);
  69851. __publicField(this, "_connectWithTimeout", fetchConn_1.FetchConnection.createConnectWithTimeout(httpSCRAMAuth));
  69852. }
  69853. };
  69854. function createHttpClient(options) {
  69855. return new baseClient_1.Client(new FetchClientPool(conUtils_server_1.parseConnectArguments, typeof options === "string" ? { dsn: options } : options ?? {}), options_1.Options.defaults());
  69856. }
  69857. }
  69858. });
  69859. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/wkt.js
  69860. var require_wkt = __commonJS({
  69861. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/wkt.js"(exports) {
  69862. "use strict";
  69863. Object.defineProperty(exports, "__esModule", { value: true });
  69864. exports.parseWKT = parseWKT;
  69865. var postgis_1 = require_postgis();
  69866. var sridRegex = /\s*SRID=([0-9]+)\s*;/iy;
  69867. var endRegex = /\s*$/y;
  69868. var geomTypes = [
  69869. "POINT",
  69870. "LINESTRING",
  69871. "POLYGON",
  69872. "MULTIPOINT",
  69873. "MULTILINESTRING",
  69874. "MULTIPOLYGON",
  69875. "GEOMETRYCOLLECTION",
  69876. "POLYHEDRALSURFACE",
  69877. "TRIANGLE",
  69878. "TIN",
  69879. "CIRCULARSTRING",
  69880. "COMPOUNDCURVE",
  69881. "CURVEPOLYGON",
  69882. "MULTICURVE",
  69883. "MULTISURFACE"
  69884. ];
  69885. var geomTypeRegex = new RegExp(`\\s*(${geomTypes.join("|")})`, "iy");
  69886. var zmFlagsRegex = /\s+(ZM|Z|M)/iy;
  69887. var emptyOrOpenRegex = /\s+(EMPTY)|\s*\(/iy;
  69888. var openRegex = /\s*\(/y;
  69889. var closeRegex = /\s*\)/y;
  69890. var commaRegex = /\s*,/y;
  69891. var _num = "-?[0-9]+(?:\\.[0-9]+)?";
  69892. var pointRegex = new RegExp(`\\s*(${_num})\\s+(${_num})(?:\\s+(${_num}))?(?:\\s+(${_num}))?`, "y");
  69893. function parseWKT(wkt) {
  69894. let i6 = 0;
  69895. let hasZ = null;
  69896. let hasM = null;
  69897. let srid = null;
  69898. sridRegex.lastIndex = i6;
  69899. const _srid = sridRegex.exec(wkt);
  69900. if (_srid) {
  69901. srid = parseInt(_srid[1], 10);
  69902. i6 += _srid[0].length;
  69903. }
  69904. const geom = _parseGeom();
  69905. endRegex.lastIndex = i6;
  69906. if (endRegex.exec(wkt) === null) {
  69907. throw createParseError(wkt, i6, "expected end of wkt");
  69908. }
  69909. return geom;
  69910. function _parseGeom(unnamedGeom = null, allowedGeoms = null) {
  69911. geomTypeRegex.lastIndex = i6;
  69912. const _geomType = geomTypeRegex.exec(wkt);
  69913. const type = _geomType?.[1].toUpperCase() ?? unnamedGeom;
  69914. if (!type || allowedGeoms && !allowedGeoms.includes(type)) {
  69915. throw createParseError(wkt, i6, `expected one of ${(allowedGeoms ? ["(", ...allowedGeoms] : geomTypes).join(", ")}`);
  69916. }
  69917. i6 += _geomType?.[0].length ?? 0;
  69918. if (_geomType !== null) {
  69919. zmFlagsRegex.lastIndex = i6;
  69920. const _zmFlags = zmFlagsRegex.exec(wkt);
  69921. if (_zmFlags !== null) {
  69922. const zm = _zmFlags[1].toLowerCase();
  69923. hasZ = zm === "zm" || zm === "z";
  69924. hasM = zm === "zm" || zm === "m";
  69925. i6 += _zmFlags[0].length;
  69926. } else {
  69927. hasZ = null;
  69928. hasM = null;
  69929. }
  69930. }
  69931. const open = _geomType === null ? openRegex : emptyOrOpenRegex;
  69932. open.lastIndex = i6;
  69933. const _emptyOrOpen = open.exec(wkt);
  69934. if (_emptyOrOpen === null) {
  69935. throw createParseError(wkt, i6, _geomType === null ? `expected (` : `expected EMPTY or (`);
  69936. }
  69937. i6 += _emptyOrOpen[0].length;
  69938. const empty = _emptyOrOpen[1] != null;
  69939. let geom2;
  69940. switch (type) {
  69941. case "POINT":
  69942. geom2 = _parsePoint(empty);
  69943. break;
  69944. case "LINESTRING":
  69945. case "CIRCULARSTRING":
  69946. geom2 = _parseLineString(empty, type === "CIRCULARSTRING" ? postgis_1.CircularString : postgis_1.LineString);
  69947. break;
  69948. case "POLYGON":
  69949. case "TRIANGLE":
  69950. geom2 = _parsePolygon(empty, type === "TRIANGLE" ? postgis_1.Triangle : postgis_1.Polygon);
  69951. break;
  69952. case "MULTIPOINT":
  69953. geom2 = new postgis_1.MultiPoint(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parsePoint)), hasZ ?? false, hasM ?? false, srid);
  69954. break;
  69955. case "MULTILINESTRING":
  69956. geom2 = new postgis_1.MultiLineString(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parseLineString)), hasZ ?? false, hasM ?? false, srid);
  69957. break;
  69958. case "MULTIPOLYGON":
  69959. case "POLYHEDRALSURFACE":
  69960. case "TIN":
  69961. {
  69962. const Geom = type === "TIN" ? postgis_1.TriangulatedIrregularNetwork : type === "POLYHEDRALSURFACE" ? postgis_1.PolyhedralSurface : postgis_1.MultiPolygon;
  69963. geom2 = new Geom(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(() => _parsePolygon(false, type === "TIN" ? postgis_1.Triangle : postgis_1.Polygon))), hasZ ?? false, hasM ?? false, srid);
  69964. }
  69965. break;
  69966. case "GEOMETRYCOLLECTION": {
  69967. geom2 = new postgis_1.GeometryCollection(empty ? [] : _checkDimensions(() => _parseCommaSep(_parseGeom)), hasZ ?? false, hasM ?? false, srid);
  69968. break;
  69969. }
  69970. case "COMPOUNDCURVE":
  69971. {
  69972. const segments = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("LINESTRING", ["LINESTRING", "CIRCULARSTRING"])));
  69973. geom2 = new postgis_1.CompoundCurve(segments, hasZ ?? false, hasM ?? false, srid);
  69974. }
  69975. break;
  69976. case "CURVEPOLYGON":
  69977. case "MULTICURVE":
  69978. {
  69979. const rings = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("LINESTRING", [
  69980. "LINESTRING",
  69981. "CIRCULARSTRING",
  69982. "COMPOUNDCURVE"
  69983. ])));
  69984. const Geom = type === "MULTICURVE" ? postgis_1.MultiCurve : postgis_1.CurvePolygon;
  69985. geom2 = new Geom(rings, hasZ ?? false, hasM ?? false, srid);
  69986. }
  69987. break;
  69988. case "MULTISURFACE":
  69989. {
  69990. const surfaces = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("POLYGON", ["POLYGON", "CURVEPOLYGON"])));
  69991. geom2 = new postgis_1.MultiSurface(surfaces, hasZ ?? false, hasM ?? false, srid);
  69992. }
  69993. break;
  69994. default:
  69995. assertNever(type, `unknown geometry type ${type}`);
  69996. }
  69997. if (!empty) {
  69998. closeRegex.lastIndex = i6;
  69999. const _close = closeRegex.exec(wkt);
  70000. if (_close === null) {
  70001. throw createParseError(wkt, i6, `expected )`);
  70002. }
  70003. i6 += _close[0].length;
  70004. }
  70005. return geom2;
  70006. }
  70007. function _parsePoint(empty = false) {
  70008. if (empty) {
  70009. return new postgis_1.Point(NaN, NaN, hasZ ? NaN : null, hasM ? NaN : null, srid);
  70010. }
  70011. pointRegex.lastIndex = i6;
  70012. const coords = pointRegex.exec(wkt);
  70013. if (coords === null) {
  70014. throw createParseError(wkt, i6, `expected between 2 to 4 coordinates`);
  70015. }
  70016. const x5 = parseFloat(coords[1]);
  70017. const y2 = parseFloat(coords[2]);
  70018. const z2 = coords[3] ? parseFloat(coords[3]) : null;
  70019. const m6 = coords[4] ? parseFloat(coords[4]) : null;
  70020. if (hasZ === null) {
  70021. hasZ = z2 !== null;
  70022. hasM = m6 !== null;
  70023. } else {
  70024. if (m6 === null) {
  70025. if (hasZ && hasM) {
  70026. throw createParseError(wkt, i6, `expected M coordinate`);
  70027. }
  70028. } else {
  70029. if (!hasM) {
  70030. throw createParseError(wkt, i6, `unexpected M coordinate`);
  70031. }
  70032. }
  70033. if (z2 === null) {
  70034. if (hasZ || hasM) {
  70035. throw createParseError(wkt, i6, `expected ${hasZ ? "Z" : "M"} coordinate`);
  70036. }
  70037. } else {
  70038. if (!hasZ && (!hasM || m6 !== null)) {
  70039. throw createParseError(wkt, i6, `unexpected Z coordinate`);
  70040. }
  70041. }
  70042. }
  70043. i6 += coords[0].length;
  70044. return new postgis_1.Point(x5, y2, hasZ ? z2 : null, hasZ ? m6 : z2, srid);
  70045. }
  70046. function _parseLineString(empty = false, Geom = postgis_1.LineString) {
  70047. return new Geom(empty ? [] : _parseCommaSep(_parsePoint), hasZ ?? false, hasM ?? false, srid);
  70048. }
  70049. function _parsePolygon(empty = false, Geom = postgis_1.Polygon) {
  70050. return new Geom(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parseLineString)), hasZ ?? false, hasM ?? false, srid);
  70051. }
  70052. function _parseCommaSep(parseGeom) {
  70053. const geoms = [parseGeom()];
  70054. while (true) {
  70055. commaRegex.lastIndex = i6;
  70056. const comma = commaRegex.exec(wkt);
  70057. if (comma === null) {
  70058. break;
  70059. }
  70060. i6 += comma[0].length;
  70061. geoms.push(parseGeom());
  70062. }
  70063. return geoms;
  70064. }
  70065. function _parseBracketedGeom(parseGeom) {
  70066. openRegex.lastIndex = i6;
  70067. const open = openRegex.exec(wkt);
  70068. if (open === null) {
  70069. throw createParseError(wkt, i6, `expected (`);
  70070. }
  70071. i6 += open[0].length;
  70072. const geom2 = parseGeom();
  70073. closeRegex.lastIndex = i6;
  70074. const close = closeRegex.exec(wkt);
  70075. if (close === null) {
  70076. throw createParseError(wkt, i6, `expected )`);
  70077. }
  70078. i6 += close[0].length;
  70079. return geom2;
  70080. }
  70081. function _checkDimensions(parseChildren) {
  70082. const parentZ = hasZ;
  70083. const parentM = hasM;
  70084. const geoms = parseChildren();
  70085. hasZ = parentZ ?? geoms[0].hasZ ?? false;
  70086. hasM = parentM ?? geoms[0].hasM ?? false;
  70087. if (geoms.some((geom2) => geom2.hasZ !== hasZ || geom2.hasM !== hasM)) {
  70088. throw createParseError(wkt, i6, `child geometries have mixed dimensions`);
  70089. }
  70090. return geoms;
  70091. }
  70092. }
  70093. function createParseError(_wkt, index6, error2) {
  70094. return new Error(`${error2} at position ${index6}`);
  70095. }
  70096. function assertNever(_type2, message) {
  70097. throw new Error(message);
  70098. }
  70099. }
  70100. });
  70101. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.shared.js
  70102. var require_index_shared = __commonJS({
  70103. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.shared.js"(exports) {
  70104. "use strict";
  70105. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  70106. if (k22 === void 0) k22 = k5;
  70107. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  70108. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  70109. desc = { enumerable: true, get: function() {
  70110. return m6[k5];
  70111. } };
  70112. }
  70113. Object.defineProperty(o5, k22, desc);
  70114. } : function(o5, m6, k5, k22) {
  70115. if (k22 === void 0) k22 = k5;
  70116. o5[k22] = m6[k5];
  70117. });
  70118. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  70119. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  70120. } : function(o5, v6) {
  70121. o5["default"] = v6;
  70122. });
  70123. var __exportStar = exports && exports.__exportStar || function(m6, exports2) {
  70124. for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p5)) __createBinding(exports2, m6, p5);
  70125. };
  70126. var __importStar = exports && exports.__importStar || function(mod) {
  70127. if (mod && mod.__esModule) return mod;
  70128. var result = {};
  70129. if (mod != null) {
  70130. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  70131. }
  70132. __setModuleDefault(result, mod);
  70133. return result;
  70134. };
  70135. Object.defineProperty(exports, "__esModule", { value: true });
  70136. exports._ReadBuffer = exports._CodecsRegistry = exports.throwWarnings = exports.logWarnings = exports.defaultBackoff = exports.Options = exports.RetryOptions = exports.RetryCondition = exports.IsolationLevel = exports.parseWKT = exports.Float16Array = exports.SparseVector = exports.MultiRange = exports.Range = exports.ConfigMemory = exports.DateDuration = exports.RelativeDuration = exports.Duration = exports.LocalTime = exports.LocalDate = exports.LocalDateTime = void 0;
  70137. var datetime_1 = require_datetime();
  70138. Object.defineProperty(exports, "LocalDateTime", { enumerable: true, get: function() {
  70139. return datetime_1.LocalDateTime;
  70140. } });
  70141. Object.defineProperty(exports, "LocalDate", { enumerable: true, get: function() {
  70142. return datetime_1.LocalDate;
  70143. } });
  70144. Object.defineProperty(exports, "LocalTime", { enumerable: true, get: function() {
  70145. return datetime_1.LocalTime;
  70146. } });
  70147. Object.defineProperty(exports, "Duration", { enumerable: true, get: function() {
  70148. return datetime_1.Duration;
  70149. } });
  70150. Object.defineProperty(exports, "RelativeDuration", { enumerable: true, get: function() {
  70151. return datetime_1.RelativeDuration;
  70152. } });
  70153. Object.defineProperty(exports, "DateDuration", { enumerable: true, get: function() {
  70154. return datetime_1.DateDuration;
  70155. } });
  70156. var memory_1 = require_memory();
  70157. Object.defineProperty(exports, "ConfigMemory", { enumerable: true, get: function() {
  70158. return memory_1.ConfigMemory;
  70159. } });
  70160. var range_1 = require_range2();
  70161. Object.defineProperty(exports, "Range", { enumerable: true, get: function() {
  70162. return range_1.Range;
  70163. } });
  70164. Object.defineProperty(exports, "MultiRange", { enumerable: true, get: function() {
  70165. return range_1.MultiRange;
  70166. } });
  70167. var pgvector_1 = require_pgvector();
  70168. Object.defineProperty(exports, "SparseVector", { enumerable: true, get: function() {
  70169. return pgvector_1.SparseVector;
  70170. } });
  70171. var utils_1 = require_utils2();
  70172. Object.defineProperty(exports, "Float16Array", { enumerable: true, get: function() {
  70173. return utils_1.Float16Array;
  70174. } });
  70175. __exportStar(require_postgis(), exports);
  70176. var wkt_1 = require_wkt();
  70177. Object.defineProperty(exports, "parseWKT", { enumerable: true, get: function() {
  70178. return wkt_1.parseWKT;
  70179. } });
  70180. var options_1 = require_options();
  70181. Object.defineProperty(exports, "IsolationLevel", { enumerable: true, get: function() {
  70182. return options_1.IsolationLevel;
  70183. } });
  70184. Object.defineProperty(exports, "RetryCondition", { enumerable: true, get: function() {
  70185. return options_1.RetryCondition;
  70186. } });
  70187. Object.defineProperty(exports, "RetryOptions", { enumerable: true, get: function() {
  70188. return options_1.RetryOptions;
  70189. } });
  70190. Object.defineProperty(exports, "Options", { enumerable: true, get: function() {
  70191. return options_1.Options;
  70192. } });
  70193. Object.defineProperty(exports, "defaultBackoff", { enumerable: true, get: function() {
  70194. return options_1.defaultBackoff;
  70195. } });
  70196. Object.defineProperty(exports, "logWarnings", { enumerable: true, get: function() {
  70197. return options_1.logWarnings;
  70198. } });
  70199. Object.defineProperty(exports, "throwWarnings", { enumerable: true, get: function() {
  70200. return options_1.throwWarnings;
  70201. } });
  70202. __exportStar(require_errors(), exports);
  70203. var reg = __importStar(require_registry());
  70204. var buf = __importStar(require_buffer());
  70205. exports._CodecsRegistry = reg.CodecsRegistry;
  70206. exports._ReadBuffer = buf.ReadBuffer;
  70207. }
  70208. });
  70209. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/typeutil.js
  70210. var require_typeutil = __commonJS({
  70211. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/typeutil.js"(exports) {
  70212. "use strict";
  70213. Object.defineProperty(exports, "__esModule", { value: true });
  70214. }
  70215. });
  70216. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/strictMap.js
  70217. var require_strictMap = __commonJS({
  70218. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/strictMap.js"(exports) {
  70219. "use strict";
  70220. Object.defineProperty(exports, "__esModule", { value: true });
  70221. exports.StrictMapSet = exports.StrictMap = void 0;
  70222. var StrictMap = class extends Map {
  70223. get(key) {
  70224. if (!this.has(key)) {
  70225. throw new Error(`key "${key}" is not found`);
  70226. }
  70227. return super.get(key);
  70228. }
  70229. };
  70230. exports.StrictMap = StrictMap;
  70231. var StrictMapSet = class extends StrictMap {
  70232. appendAt(key, value) {
  70233. const set = this.has(key) ? this.get(key) : /* @__PURE__ */ new Set();
  70234. set.add(value);
  70235. this.set(key, set);
  70236. }
  70237. };
  70238. exports.StrictMapSet = StrictMapSet;
  70239. }
  70240. });
  70241. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/reservedKeywords.js
  70242. var require_reservedKeywords = __commonJS({
  70243. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/reservedKeywords.js"(exports) {
  70244. "use strict";
  70245. Object.defineProperty(exports, "__esModule", { value: true });
  70246. exports.reservedKeywords = void 0;
  70247. exports.reservedKeywords = /* @__PURE__ */ new Set([
  70248. "__edgedbsys__",
  70249. "__edgedbtpl__",
  70250. "__source__",
  70251. "__std__",
  70252. "__subject__",
  70253. "__type__",
  70254. "abort",
  70255. "alter",
  70256. "analyze",
  70257. "and",
  70258. "anyarray",
  70259. "anytuple",
  70260. "anytype",
  70261. "anyobject",
  70262. "begin",
  70263. "case",
  70264. "check",
  70265. "commit",
  70266. "configure",
  70267. "create",
  70268. "deallocate",
  70269. "declare",
  70270. "delete",
  70271. "describe",
  70272. "detached",
  70273. "discard",
  70274. "distinct",
  70275. "do",
  70276. "drop",
  70277. "else",
  70278. "empty",
  70279. "end",
  70280. "execute",
  70281. "exists",
  70282. "explain",
  70283. "extending",
  70284. "fetch",
  70285. "filter",
  70286. "for",
  70287. "get",
  70288. "global",
  70289. "grant",
  70290. "group",
  70291. "if",
  70292. "ilike",
  70293. "import",
  70294. "in",
  70295. "insert",
  70296. "introspect",
  70297. "is",
  70298. "like",
  70299. "limit",
  70300. "listen",
  70301. "load",
  70302. "lock",
  70303. "match",
  70304. "module",
  70305. "move",
  70306. "not",
  70307. "notify",
  70308. "offset",
  70309. "optional",
  70310. "or",
  70311. "order",
  70312. "over",
  70313. "partition",
  70314. "policy",
  70315. "populate",
  70316. "prepare",
  70317. "raise",
  70318. "refresh",
  70319. "reindex",
  70320. "release",
  70321. "reset",
  70322. "revoke",
  70323. "rollback",
  70324. "select",
  70325. "set",
  70326. "single",
  70327. "start",
  70328. "typeof",
  70329. "union",
  70330. "update",
  70331. "variadic",
  70332. "when",
  70333. "window",
  70334. "with"
  70335. ]);
  70336. }
  70337. });
  70338. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/types.js
  70339. var require_types = __commonJS({
  70340. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/types.js"(exports) {
  70341. "use strict";
  70342. Object.defineProperty(exports, "__esModule", { value: true });
  70343. exports.typeMapping = void 0;
  70344. exports.getTypes = getTypes;
  70345. exports.types = getTypes;
  70346. exports.topoSort = topoSort;
  70347. exports.getTypes = getTypes;
  70348. exports.types = getTypes;
  70349. var strictMap_1 = require_strictMap();
  70350. var numberType2 = {
  70351. id: "00000000-0000-0000-0000-0000000001ff",
  70352. name: "std::number",
  70353. is_abstract: false,
  70354. is_seq: false,
  70355. kind: "scalar",
  70356. enum_values: null,
  70357. material_id: null,
  70358. bases: []
  70359. };
  70360. exports.typeMapping = /* @__PURE__ */ new Map([
  70361. [
  70362. "00000000-0000-0000-0000-000000000103",
  70363. numberType2
  70364. ],
  70365. [
  70366. "00000000-0000-0000-0000-000000000104",
  70367. numberType2
  70368. ],
  70369. [
  70370. "00000000-0000-0000-0000-000000000105",
  70371. numberType2
  70372. ],
  70373. [
  70374. "00000000-0000-0000-0000-000000000106",
  70375. numberType2
  70376. ],
  70377. [
  70378. "00000000-0000-0000-0000-000000000107",
  70379. numberType2
  70380. ]
  70381. ]);
  70382. async function getTypes(cxn, params) {
  70383. const debug = params?.debug === true;
  70384. const version = await cxn.queryRequiredSingle(`select sys::get_version().major;`);
  70385. const v2Plus = version >= 2;
  70386. const v4Plus = version >= 4;
  70387. const QUERY = `
  70388. WITH
  70389. MODULE schema,
  70390. material_scalars := (
  70391. SELECT ScalarType
  70392. FILTER NOT .abstract
  70393. AND NOT EXISTS .enum_values
  70394. AND NOT EXISTS (SELECT .ancestors FILTER NOT .abstract)
  70395. )
  70396. SELECT Type {
  70397. id,
  70398. name :=
  70399. array_join(array_agg([IS ObjectType].union_of.name), ' | ')
  70400. IF EXISTS [IS ObjectType].union_of
  70401. ELSE .name,
  70402. is_abstract := .abstract,
  70403. kind := 'object' IF Type IS ObjectType ELSE
  70404. 'scalar' IF Type IS ScalarType ELSE
  70405. 'array' IF Type IS Array ELSE
  70406. 'tuple' IF Type IS Tuple ELSE
  70407. ${v2Plus ? `'range' IF Type IS Range ELSE` : ``}
  70408. ${v4Plus ? `'multirange' IF Type IS MultiRange ELSE` : ``}
  70409. 'unknown',
  70410. [IS ScalarType].enum_values,
  70411. is_seq := 'std::sequence' in [IS ScalarType].ancestors.name,
  70412. # for sequence (abstract type that has non-abstract ancestor)
  70413. single material_id := (
  70414. SELECT x := Type[IS ScalarType].ancestors
  70415. FILTER x IN material_scalars
  70416. LIMIT 1
  70417. ).id,
  70418. [IS InheritingObject].bases: {
  70419. id
  70420. } ORDER BY @index ASC,
  70421. [IS ObjectType].union_of,
  70422. [IS ObjectType].intersection_of,
  70423. [IS ObjectType].pointers: {
  70424. card := ("One" IF .required ELSE "AtMostOne") IF <str>.cardinality = "One" ELSE ("AtLeastOne" IF .required ELSE "Many"),
  70425. name,
  70426. target_id := .target.id,
  70427. kind := 'link' IF .__type__.name = 'schema::Link' ELSE 'property',
  70428. is_exclusive := exists (select .constraints filter .name = 'std::exclusive'),
  70429. is_computed := len(.computed_fields) != 0,
  70430. is_readonly := .readonly,
  70431. has_default := EXISTS .default or ("std::sequence" in .target[IS ScalarType].ancestors.name),
  70432. [IS Link].pointers: {
  70433. card := ("One" IF .required ELSE "AtMostOne") IF <str>.cardinality = "One" ELSE ("AtLeastOne" IF .required ELSE "Many"),
  70434. name := '@' ++ .name,
  70435. target_id := .target.id,
  70436. kind := 'link' IF .__type__.name = 'schema::Link' ELSE 'property',
  70437. is_computed := len(.computed_fields) != 0,
  70438. is_readonly := .readonly
  70439. } filter .name != '@source' and .name != '@target',
  70440. } FILTER any(@is_owned),
  70441. exclusives := assert_distinct((
  70442. [is schema::ObjectType].constraints
  70443. union
  70444. [is schema::ObjectType].pointers.constraints
  70445. ) {
  70446. target := (.subject[is schema::Property].name ?? .subject[is schema::Link].name ?? .subjectexpr)
  70447. } filter .name = 'std::exclusive'),
  70448. backlinks := (
  70449. SELECT DETACHED Link
  70450. FILTER .target = Type
  70451. AND NOT EXISTS .source[IS ObjectType].union_of
  70452. ) {
  70453. card := "AtMostOne"
  70454. IF
  70455. EXISTS (select .constraints filter .name = 'std::exclusive')
  70456. ELSE
  70457. "Many",
  70458. name := '<' ++ .name ++ '[is ' ++ assert_exists(.source.name) ++ ']',
  70459. stub := .name,
  70460. target_id := .source.id,
  70461. kind := 'link',
  70462. is_exclusive := (EXISTS (select .constraints filter .name = 'std::exclusive')) AND <str>.cardinality = "One",
  70463. },
  70464. backlink_stubs := array_agg((
  70465. WITH
  70466. stubs := DISTINCT (SELECT DETACHED Link FILTER .target = Type).name,
  70467. baseObjectId := (SELECT DETACHED ObjectType FILTER .name = 'std::BaseObject' LIMIT 1).id
  70468. FOR stub in { stubs }
  70469. UNION (
  70470. SELECT {
  70471. card := "Many",
  70472. name := '<' ++ stub,
  70473. target_id := baseObjectId,
  70474. kind := 'link',
  70475. is_exclusive := false,
  70476. }
  70477. )
  70478. )),
  70479. array_element_id := [IS Array].element_type.id,
  70480. tuple_elements := (SELECT [IS Tuple].element_types {
  70481. target_id := .type.id,
  70482. name
  70483. } ORDER BY @index ASC),
  70484. ${v2Plus ? `range_element_id := [IS Range].element_type.id,` : ``}
  70485. ${v4Plus ? `multirange_element_id := [IS MultiRange].element_type.id,` : ``}
  70486. }
  70487. ORDER BY .name;
  70488. `;
  70489. const _types = JSON.parse(await cxn.queryJSON(QUERY));
  70490. if (debug)
  70491. console.log(JSON.stringify(_types, null, 2));
  70492. for (const type of _types) {
  70493. if (Array.isArray(type.backlinks)) {
  70494. for (const backlink of type.backlinks) {
  70495. const isName = backlink.name.match(/\[is (.+)\]/)[1];
  70496. if (isName.split("::").length === 2 && isName.startsWith("default::")) {
  70497. backlink.name = backlink.name.replace(/\[is (.+)\]/, `[is ${isName.slice(9)}]`);
  70498. }
  70499. }
  70500. }
  70501. switch (type.kind) {
  70502. case "scalar":
  70503. if (exports.typeMapping.has(type.id)) {
  70504. type.cast_type = exports.typeMapping.get(type.id).id;
  70505. }
  70506. if (type.is_seq) {
  70507. type.cast_type = numberType2.id;
  70508. }
  70509. if (type.name !== "std::sequence" && type.bases[0]?.id === type.material_id) {
  70510. type.cast_type = exports.typeMapping.get(type.material_id)?.id ?? type.material_id;
  70511. }
  70512. break;
  70513. case "multirange":
  70514. type.multirange_element_id = exports.typeMapping.get(type.multirange_element_id)?.id ?? type.multirange_element_id;
  70515. break;
  70516. case "range":
  70517. type.range_element_id = exports.typeMapping.get(type.range_element_id)?.id ?? type.range_element_id;
  70518. break;
  70519. case "object": {
  70520. const ptrs = {};
  70521. for (const ptr of type.pointers) {
  70522. ptrs[ptr.name] = ptr;
  70523. }
  70524. const rawExclusives = type.exclusives;
  70525. const exclusives = [];
  70526. for (const ex of rawExclusives) {
  70527. const target = ex.target;
  70528. if (target in ptrs) {
  70529. exclusives.push({ [ex.target]: ptrs[ex.target] });
  70530. }
  70531. if (target[0] === "(" && target[target.length - 1] === ")") {
  70532. const targets = target.slice(1, -1).split(" ").map((t6) => {
  70533. t6 = t6.trim();
  70534. if (t6[0] === ".")
  70535. t6 = t6.slice(1);
  70536. if (t6[t6.length - 1] === ",")
  70537. t6 = t6.slice(0, -1);
  70538. return t6;
  70539. });
  70540. const newEx = {};
  70541. if (!targets.every((t6) => t6 in ptrs)) {
  70542. continue;
  70543. }
  70544. for (const t6 of targets) {
  70545. newEx[t6] = ptrs[t6];
  70546. }
  70547. exclusives.push(newEx);
  70548. }
  70549. }
  70550. type.exclusives = exclusives;
  70551. break;
  70552. }
  70553. }
  70554. }
  70555. _types.push(numberType2);
  70556. const types3 = topoSort(_types);
  70557. for (const [_3, type] of types3) {
  70558. if (type.kind === "object" && type.union_of.length) {
  70559. const unionTypes = type.union_of.map(({ id }) => {
  70560. const t6 = types3.get(id);
  70561. if (t6.kind !== "object") {
  70562. throw new Error(`type '${t6.name}' of union '${type.name}' is not an object type`);
  70563. }
  70564. return t6;
  70565. });
  70566. const [first, ...rest] = unionTypes;
  70567. const restPointerNames = rest.map((t6) => new Set(t6.pointers.map((p5) => p5.name)));
  70568. for (const pointer of first.pointers) {
  70569. if (restPointerNames.every((names) => names.has(pointer.name))) {
  70570. type.pointers.push(pointer);
  70571. }
  70572. }
  70573. type.backlinks = [];
  70574. type.backlink_stubs = [];
  70575. }
  70576. }
  70577. return types3;
  70578. }
  70579. function topoSort(types3) {
  70580. const graph = new strictMap_1.StrictMap();
  70581. const adj = new strictMap_1.StrictMap();
  70582. for (const type of types3) {
  70583. graph.set(type.id, type);
  70584. }
  70585. for (const type of types3) {
  70586. if (type.kind !== "object" && type.kind !== "scalar") {
  70587. continue;
  70588. }
  70589. for (const { id: base } of type.bases) {
  70590. if (!graph.has(base)) {
  70591. throw new Error(`reference to an unknown object type: ${base}`);
  70592. }
  70593. if (!adj.has(type.id)) {
  70594. adj.set(type.id, /* @__PURE__ */ new Set());
  70595. }
  70596. adj.get(type.id).add(base);
  70597. }
  70598. }
  70599. const visiting = /* @__PURE__ */ new Set();
  70600. const visited = /* @__PURE__ */ new Set();
  70601. const sorted = new strictMap_1.StrictMap();
  70602. const visit = (type) => {
  70603. if (visiting.has(type.name)) {
  70604. const last = Array.from(visiting).slice(1, 2);
  70605. throw new Error(`dependency cycle between ${type.name} and ${last}`);
  70606. }
  70607. if (!visited.has(type.id)) {
  70608. visiting.add(type.name);
  70609. if (adj.has(type.id)) {
  70610. for (const adjId of adj.get(type.id).values()) {
  70611. visit(graph.get(adjId));
  70612. }
  70613. }
  70614. sorted.set(type.id, type);
  70615. visited.add(type.id);
  70616. visiting.delete(type.name);
  70617. }
  70618. };
  70619. for (const type of types3) {
  70620. visit(type);
  70621. }
  70622. return sorted;
  70623. }
  70624. }
  70625. });
  70626. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/casts.js
  70627. var require_casts = __commonJS({
  70628. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/casts.js"(exports) {
  70629. "use strict";
  70630. Object.defineProperty(exports, "__esModule", { value: true });
  70631. exports.casts = void 0;
  70632. var types_1 = require_types();
  70633. var reachableFrom = (source, adj, seen = /* @__PURE__ */ new Set()) => {
  70634. const reachable = /* @__PURE__ */ new Set();
  70635. if (seen.has(source))
  70636. return [];
  70637. seen.add(source);
  70638. (adj[source] || []).map((cast) => {
  70639. reachable.add(cast);
  70640. for (const item of reachableFrom(cast, adj, seen)) {
  70641. reachable.add(item);
  70642. }
  70643. });
  70644. return [...reachable];
  70645. };
  70646. var casts = async (cxn, params) => {
  70647. const allCastsRaw = await cxn.queryJSON(`WITH MODULE schema
  70648. SELECT Cast {
  70649. id,
  70650. source := .from_type { id, name },
  70651. target := .to_type { id, name },
  70652. allow_assignment,
  70653. allow_implicit,
  70654. }
  70655. FILTER .from_type IS ScalarType
  70656. AND .to_type IS ScalarType
  70657. # AND .from_type.is_abstract = false
  70658. # AND .to_type.is_abstract = false
  70659. `);
  70660. const allCasts = JSON.parse(allCastsRaw);
  70661. const types3 = /* @__PURE__ */ new Set();
  70662. const typesById = {};
  70663. const castsById = {};
  70664. const castsBySource = {};
  70665. const implicitCastsBySource = {};
  70666. const implicitCastsByTarget = {};
  70667. const assignmentCastsBySource = {};
  70668. const assignmentCastsByTarget = {};
  70669. for (const cast of allCasts) {
  70670. if (types_1.typeMapping.has(cast.source.id) || types_1.typeMapping.has(cast.target.id)) {
  70671. cast.allow_implicit = false;
  70672. cast.allow_assignment = false;
  70673. }
  70674. typesById[cast.source.id] = cast.source;
  70675. typesById[cast.target.id] = cast.target;
  70676. types3.add(cast.source.id);
  70677. types3.add(cast.target.id);
  70678. castsById[cast.id] = cast;
  70679. castsBySource[cast.source.id] = castsBySource[cast.source.id] || [];
  70680. castsBySource[cast.source.id].push(cast.target.id);
  70681. if (cast.allow_assignment || cast.allow_implicit) {
  70682. assignmentCastsBySource[cast.source.id] ??= [];
  70683. assignmentCastsBySource[cast.source.id].push(cast.target.id);
  70684. assignmentCastsByTarget[cast.target.id] ??= [];
  70685. assignmentCastsByTarget[cast.target.id].push(cast.source.id);
  70686. }
  70687. if (cast.allow_implicit) {
  70688. implicitCastsBySource[cast.source.id] ??= [];
  70689. implicitCastsBySource[cast.source.id].push(cast.target.id);
  70690. implicitCastsByTarget[cast.target.id] ??= [];
  70691. implicitCastsByTarget[cast.target.id].push(cast.source.id);
  70692. }
  70693. }
  70694. const castMap = {};
  70695. const implicitCastMap = {};
  70696. const implicitCastFromMap = {};
  70697. const assignmentCastMap = {};
  70698. const assignableByMap = {};
  70699. for (const type of [...types3]) {
  70700. castMap[type] = castsBySource[type] || [];
  70701. implicitCastMap[type] = reachableFrom(type, implicitCastsBySource);
  70702. implicitCastFromMap[type] = reachableFrom(type, implicitCastsByTarget);
  70703. assignmentCastMap[type] = reachableFrom(type, assignmentCastsBySource);
  70704. assignableByMap[type] = reachableFrom(type, assignmentCastsByTarget);
  70705. }
  70706. if (params?.debug === true) {
  70707. console.log(`
  70708. IMPLICIT`);
  70709. for (const [fromId, castArr] of Object.entries(implicitCastMap)) {
  70710. console.log(`${typesById[fromId].name} implicitly castable to: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
  70711. }
  70712. console.log("");
  70713. for (const [fromId, castArr] of Object.entries(implicitCastFromMap)) {
  70714. console.log(`${typesById[fromId].name} implicitly castable from: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
  70715. }
  70716. console.log(`
  70717. ASSIGNABLE TO`);
  70718. for (const [fromId, castArr] of Object.entries(assignmentCastMap)) {
  70719. console.log(`${typesById[fromId].name} assignable to: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
  70720. }
  70721. console.log(`
  70722. ASSIGNABLE BY`);
  70723. for (const [fromId, castArr] of Object.entries(assignableByMap)) {
  70724. console.log(`${typesById[fromId].name} assignable by: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
  70725. }
  70726. console.log(`
  70727. EXPLICIT`);
  70728. for (const [fromId, castArr] of Object.entries(castMap)) {
  70729. console.log(`${typesById[fromId].name} castable to: [${castArr.map((id) => {
  70730. return typesById[id].name;
  70731. }).join(", ")}]`);
  70732. }
  70733. }
  70734. return {
  70735. castsById,
  70736. typesById,
  70737. castMap,
  70738. implicitCastMap,
  70739. implicitCastFromMap,
  70740. assignmentCastMap,
  70741. assignableByMap
  70742. };
  70743. };
  70744. exports.casts = casts;
  70745. }
  70746. });
  70747. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/functions.js
  70748. var require_functions = __commonJS({
  70749. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/functions.js"(exports) {
  70750. "use strict";
  70751. Object.defineProperty(exports, "__esModule", { value: true });
  70752. exports.functions = void 0;
  70753. exports.replaceNumberTypes = replaceNumberTypes;
  70754. var strictMap_1 = require_strictMap();
  70755. var types_1 = require_types();
  70756. var functions = async (cxn) => {
  70757. const functionsJson = await cxn.queryJSON(`
  70758. with module schema
  70759. select Function {
  70760. id,
  70761. name,
  70762. annotations: {
  70763. name,
  70764. @value
  70765. } filter .name = 'std::description',
  70766. return_type: {id, name},
  70767. return_typemod,
  70768. params: {
  70769. name,
  70770. type: {id, name},
  70771. kind,
  70772. typemod,
  70773. hasDefault := exists .default,
  70774. } order by @index,
  70775. preserves_optionality,
  70776. } filter .internal = false
  70777. `);
  70778. const functionMap = new strictMap_1.StrictMap();
  70779. const seenFuncDefHashes = /* @__PURE__ */ new Set();
  70780. for (const func of JSON.parse(functionsJson)) {
  70781. const { name } = func;
  70782. const funcDef = {
  70783. ...func,
  70784. description: func.annotations[0]?.["@value"]
  70785. };
  70786. replaceNumberTypes(funcDef);
  70787. const hash = hashFuncDef(funcDef);
  70788. if (!seenFuncDefHashes.has(hash)) {
  70789. if (!functionMap.has(name)) {
  70790. functionMap.set(name, [funcDef]);
  70791. } else {
  70792. functionMap.get(name).push(funcDef);
  70793. }
  70794. seenFuncDefHashes.add(hash);
  70795. }
  70796. }
  70797. return functionMap;
  70798. };
  70799. exports.functions = functions;
  70800. function replaceNumberTypes(def) {
  70801. if (types_1.typeMapping.has(def.return_type.id)) {
  70802. const type = types_1.typeMapping.get(def.return_type.id);
  70803. def.return_type = {
  70804. id: type.id,
  70805. name: type.name
  70806. };
  70807. }
  70808. for (const param of def.params) {
  70809. if (types_1.typeMapping.has(param.type.id)) {
  70810. const type = types_1.typeMapping.get(param.type.id);
  70811. param.type = {
  70812. id: type.id,
  70813. name: type.name
  70814. };
  70815. }
  70816. }
  70817. }
  70818. function hashFuncDef(def) {
  70819. return JSON.stringify({
  70820. name: def.name,
  70821. return_type: def.return_type.id,
  70822. return_typemod: def.return_typemod,
  70823. params: def.params.map((param) => JSON.stringify({
  70824. kind: param.kind,
  70825. type: param.type.id,
  70826. typemod: param.typemod,
  70827. hasDefault: !!param.hasDefault
  70828. })).sort(),
  70829. preserves_optionality: def.preserves_optionality
  70830. });
  70831. }
  70832. }
  70833. });
  70834. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/globals.js
  70835. var require_globals = __commonJS({
  70836. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/globals.js"(exports) {
  70837. "use strict";
  70838. Object.defineProperty(exports, "__esModule", { value: true });
  70839. exports.globals = globals;
  70840. async function globals(cxn) {
  70841. const globalsMap = /* @__PURE__ */ new Map();
  70842. const version = await cxn.queryRequiredSingle(`select sys::get_version().major;`);
  70843. if (version === 1) {
  70844. return globalsMap;
  70845. }
  70846. const QUERY = `
  70847. WITH
  70848. MODULE schema
  70849. SELECT schema::Global {
  70850. id,
  70851. name,
  70852. target_id := .target.id,
  70853. card := ("One" IF .required ELSE "One" IF EXISTS .default ELSE "AtMostOne")
  70854. IF <str>.cardinality = "One" ELSE
  70855. ("AtLeastOne" IF .required ELSE "Many"),
  70856. has_default := exists .default,
  70857. }
  70858. ORDER BY .name;
  70859. `;
  70860. const allGlobals = JSON.parse(await cxn.queryJSON(QUERY));
  70861. for (const g5 of allGlobals) {
  70862. globalsMap.set(g5.id, g5);
  70863. }
  70864. return globalsMap;
  70865. }
  70866. }
  70867. });
  70868. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/operators.js
  70869. var require_operators = __commonJS({
  70870. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/operators.js"(exports) {
  70871. "use strict";
  70872. Object.defineProperty(exports, "__esModule", { value: true });
  70873. exports.operators = void 0;
  70874. var strictMap_1 = require_strictMap();
  70875. var functions_1 = require_functions();
  70876. var util_1 = require_util3();
  70877. var _operators = async (cxn) => {
  70878. const operatorsJson = await cxn.queryJSON(`
  70879. with module schema
  70880. select Operator {
  70881. id,
  70882. name,
  70883. annotations: {
  70884. name,
  70885. @value
  70886. } filter .name in {'std::identifier', 'std::description'},
  70887. operator_kind,
  70888. return_type: {id, name},
  70889. return_typemod,
  70890. params: {
  70891. name,
  70892. type: {id, name},
  70893. kind,
  70894. typemod,
  70895. } order by @index,
  70896. } filter not .internal and not .abstract
  70897. `);
  70898. const operators = new strictMap_1.StrictMap();
  70899. const seenOpDefHashes = /* @__PURE__ */ new Set();
  70900. for (const op of JSON.parse(operatorsJson)) {
  70901. const identifier = op.annotations.find((anno) => anno.name === "std::identifier")?.["@value"];
  70902. if (!identifier) {
  70903. continue;
  70904. }
  70905. const { mod } = util_1.util.splitName(op.name);
  70906. const name = `${mod}::${identifier}`;
  70907. const opDef = {
  70908. ...op,
  70909. name,
  70910. kind: op.operator_kind,
  70911. originalName: op.name,
  70912. description: op.annotations.find((anno) => anno.name === "std::description")?.["@value"],
  70913. annotations: void 0
  70914. };
  70915. (0, functions_1.replaceNumberTypes)(opDef);
  70916. const hash = hashOpDef(opDef);
  70917. if (!seenOpDefHashes.has(hash)) {
  70918. if (!operators.has(name)) {
  70919. operators.set(name, [opDef]);
  70920. } else {
  70921. operators.get(name).push(opDef);
  70922. }
  70923. seenOpDefHashes.add(hash);
  70924. }
  70925. }
  70926. return operators;
  70927. };
  70928. exports.operators = _operators;
  70929. function hashOpDef(def) {
  70930. return JSON.stringify({
  70931. name: def.name,
  70932. return_type: def.return_type.id,
  70933. return_typemod: def.return_typemod,
  70934. params: def.params.map((param) => JSON.stringify({
  70935. kind: param.kind,
  70936. type: param.type.id,
  70937. typemod: param.typemod,
  70938. hasDefault: !!param.hasDefault
  70939. })).sort(),
  70940. operator_kind: def.operator_kind
  70941. });
  70942. }
  70943. }
  70944. });
  70945. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/scalars.js
  70946. var require_scalars = __commonJS({
  70947. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/scalars.js"(exports) {
  70948. "use strict";
  70949. Object.defineProperty(exports, "__esModule", { value: true });
  70950. exports.scalars = void 0;
  70951. var strictMap_1 = require_strictMap();
  70952. var _scalars = async (cxn) => {
  70953. const scalarArray = await cxn.queryJSON(`with module schema
  70954. select InheritingObject {
  70955. id,
  70956. name,
  70957. is_abstract,
  70958. bases: { id, name },
  70959. ancestors: { id, name },
  70960. children := .<bases[IS Type] { id, name },
  70961. descendants := .<ancestors[IS Type] { id, name }
  70962. }
  70963. FILTER
  70964. InheritingObject IS ScalarType OR
  70965. InheritingObject IS ObjectType;
  70966. `);
  70967. const scalars = new strictMap_1.StrictMap();
  70968. for (const type of JSON.parse(scalarArray)) {
  70969. scalars.set(type.id, type);
  70970. }
  70971. return scalars;
  70972. };
  70973. exports.scalars = _scalars;
  70974. }
  70975. });
  70976. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries.js
  70977. var require_queries = __commonJS({
  70978. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries.js"(exports) {
  70979. "use strict";
  70980. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  70981. if (k22 === void 0) k22 = k5;
  70982. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  70983. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  70984. desc = { enumerable: true, get: function() {
  70985. return m6[k5];
  70986. } };
  70987. }
  70988. Object.defineProperty(o5, k22, desc);
  70989. } : function(o5, m6, k5, k22) {
  70990. if (k22 === void 0) k22 = k5;
  70991. o5[k22] = m6[k5];
  70992. });
  70993. var __exportStar = exports && exports.__exportStar || function(m6, exports2) {
  70994. for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p5)) __createBinding(exports2, m6, p5);
  70995. };
  70996. Object.defineProperty(exports, "__esModule", { value: true });
  70997. __exportStar(require_casts(), exports);
  70998. __exportStar(require_functions(), exports);
  70999. __exportStar(require_globals(), exports);
  71000. __exportStar(require_operators(), exports);
  71001. __exportStar(require_scalars(), exports);
  71002. __exportStar(require_types(), exports);
  71003. }
  71004. });
  71005. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/analyzeQuery.js
  71006. var require_analyzeQuery = __commonJS({
  71007. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/analyzeQuery.js"(exports) {
  71008. "use strict";
  71009. Object.defineProperty(exports, "__esModule", { value: true });
  71010. exports.ImportMap = exports.defaultApplyCardinalityToTsType = exports.generateTsObjectField = exports.generateTsObject = exports.defaultCodecGenerators = exports.defineCodecGeneratorTuple = exports.generateTSTypeFromCodec = void 0;
  71011. exports.analyzeQuery = analyzeQuery;
  71012. var array_1 = require_array();
  71013. var enum_1 = require_enum();
  71014. var ifaces_1 = require_ifaces();
  71015. var namedtuple_1 = require_namedtuple();
  71016. var object_1 = require_object();
  71017. var range_1 = require_range3();
  71018. var codecs_1 = require_codecs();
  71019. var set_1 = require_set();
  71020. var tuple_1 = require_tuple();
  71021. var enums_1 = require_enums();
  71022. var util_1 = require_util3();
  71023. async function analyzeQuery(client, query) {
  71024. const { cardinality, capabilities, in: inCodec, out: outCodec } = await client.describe(query);
  71025. const args = (0, exports.generateTSTypeFromCodec)(inCodec, enums_1.Cardinality.One, {
  71026. optionalNulls: true,
  71027. readonly: true
  71028. });
  71029. const result = (0, exports.generateTSTypeFromCodec)(outCodec, cardinality);
  71030. const imports = args.imports.merge(result.imports);
  71031. return {
  71032. result: result.type,
  71033. args: args.type,
  71034. cardinality,
  71035. capabilities,
  71036. query,
  71037. importMap: imports,
  71038. imports: imports.get("gel") ?? /* @__PURE__ */ new Set()
  71039. };
  71040. }
  71041. var generateTSTypeFromCodec = (codec, cardinality = enums_1.Cardinality.One, options = {}) => {
  71042. const optionsWithDefaults = {
  71043. indent: "",
  71044. optionalNulls: false,
  71045. readonly: false,
  71046. ...options
  71047. };
  71048. const context = {
  71049. ...optionsWithDefaults,
  71050. generators: exports.defaultCodecGenerators,
  71051. applyCardinality: (0, exports.defaultApplyCardinalityToTsType)(optionsWithDefaults),
  71052. ...options,
  71053. imports: new ImportMap(),
  71054. walk: (codec2, innerContext) => {
  71055. innerContext ??= context;
  71056. for (const [type2, generator] of innerContext.generators) {
  71057. if (codec2 instanceof type2) {
  71058. return generator(codec2, innerContext);
  71059. }
  71060. }
  71061. throw new Error(`Unexpected codec kind: ${codec2.getKind()}`);
  71062. }
  71063. };
  71064. const type = context.applyCardinality(context.walk(codec, context), cardinality);
  71065. return {
  71066. type,
  71067. imports: context.imports
  71068. };
  71069. };
  71070. exports.generateTSTypeFromCodec = generateTSTypeFromCodec;
  71071. var genDef = (codecType, generator) => [codecType, generator];
  71072. exports.defineCodecGeneratorTuple = genDef;
  71073. exports.defaultCodecGenerators = new Map([
  71074. genDef(codecs_1.NullCodec, () => "null"),
  71075. genDef(enum_1.EnumCodec, (codec) => {
  71076. return `(${codec.values.map((val2) => JSON.stringify(val2)).join(" | ")})`;
  71077. }),
  71078. genDef(ifaces_1.ScalarCodec, (codec, ctx) => {
  71079. if (codec.tsModule) {
  71080. ctx.imports.add(codec.tsModule, codec.tsType);
  71081. }
  71082. return codec.tsType;
  71083. }),
  71084. genDef(object_1.ObjectCodec, (codec, ctx) => {
  71085. const subCodecs = codec.getSubcodecs();
  71086. const fields = codec.getFields().map((field, i6) => ({
  71087. name: field.name,
  71088. codec: subCodecs[i6],
  71089. cardinality: util_1.util.parseCardinality(field.cardinality)
  71090. }));
  71091. return (0, exports.generateTsObject)(fields, ctx);
  71092. }),
  71093. genDef(namedtuple_1.NamedTupleCodec, (codec, ctx) => {
  71094. const subCodecs = codec.getSubcodecs();
  71095. const fields = codec.getNames().map((name, i6) => ({
  71096. name,
  71097. codec: subCodecs[i6],
  71098. cardinality: enums_1.Cardinality.One
  71099. }));
  71100. return (0, exports.generateTsObject)(fields, ctx);
  71101. }),
  71102. genDef(tuple_1.TupleCodec, (codec, ctx) => {
  71103. const subCodecs = codec.getSubcodecs().map((subCodec) => ctx.walk(subCodec));
  71104. const tuple = `[${subCodecs.join(", ")}]`;
  71105. return ctx.readonly ? `(readonly ${tuple})` : tuple;
  71106. }),
  71107. genDef(array_1.ArrayCodec, (codec, ctx) => ctx.applyCardinality(ctx.walk(codec.getSubcodecs()[0]), enums_1.Cardinality.Many)),
  71108. genDef(range_1.RangeCodec, (codec, ctx) => {
  71109. const subCodec = codec.getSubcodecs()[0];
  71110. if (!(subCodec instanceof ifaces_1.ScalarCodec)) {
  71111. throw Error("expected range subtype to be scalar type");
  71112. }
  71113. ctx.imports.add(codec.tsModule, codec.tsType);
  71114. return `${codec.tsType}<${ctx.walk(subCodec)}>`;
  71115. }),
  71116. genDef(range_1.MultiRangeCodec, (codec, ctx) => {
  71117. const subCodec = codec.getSubcodecs()[0];
  71118. if (!(subCodec instanceof ifaces_1.ScalarCodec)) {
  71119. throw Error("expected multirange subtype to be scalar type");
  71120. }
  71121. ctx.imports.add(codec.tsModule, codec.tsType);
  71122. return `${codec.tsType}<${ctx.walk(subCodec)}>`;
  71123. })
  71124. ]);
  71125. var generateTsObject = (fields, ctx) => {
  71126. const properties = fields.map((field) => (0, exports.generateTsObjectField)(field, ctx));
  71127. return `{
  71128. ${properties.join("\n")}
  71129. ${ctx.indent}}`;
  71130. };
  71131. exports.generateTsObject = generateTsObject;
  71132. var generateTsObjectField = (field, ctx) => {
  71133. const codec = unwrapSetCodec(field.codec, field.cardinality);
  71134. const name = JSON.stringify(field.name);
  71135. const value = ctx.applyCardinality(ctx.walk(codec, { ...ctx, indent: ctx.indent + " " }), field.cardinality);
  71136. const optional = ctx.optionalNulls && field.cardinality === enums_1.Cardinality.AtMostOne;
  71137. const questionMark = optional ? "?" : "";
  71138. const isReadonly = ctx.readonly ? "readonly " : "";
  71139. return `${ctx.indent} ${isReadonly}${name}${questionMark}: ${value};`;
  71140. };
  71141. exports.generateTsObjectField = generateTsObjectField;
  71142. function unwrapSetCodec(codec, cardinality) {
  71143. if (!(codec instanceof set_1.SetCodec)) {
  71144. return codec;
  71145. }
  71146. if (cardinality === enums_1.Cardinality.Many || cardinality === enums_1.Cardinality.AtLeastOne) {
  71147. return codec.getSubcodecs()[0];
  71148. }
  71149. throw new Error("Sub-codec is SetCodec, but upper cardinality is one");
  71150. }
  71151. var defaultApplyCardinalityToTsType = (ctx) => (type, cardinality) => {
  71152. switch (cardinality) {
  71153. case enums_1.Cardinality.Many:
  71154. return `${ctx.readonly ? "Readonly" : ""}Array<${type}>`;
  71155. case enums_1.Cardinality.One:
  71156. return type;
  71157. case enums_1.Cardinality.AtMostOne:
  71158. return `${type} | null`;
  71159. case enums_1.Cardinality.AtLeastOne: {
  71160. const tuple = `[(${type}), ...(${type})[]]`;
  71161. return ctx.readonly ? `(readonly ${tuple})` : tuple;
  71162. }
  71163. }
  71164. throw new Error(`Unexpected cardinality: ${cardinality}`);
  71165. };
  71166. exports.defaultApplyCardinalityToTsType = defaultApplyCardinalityToTsType;
  71167. var ImportMap = class _ImportMap extends Map {
  71168. add(module2, specifier) {
  71169. if (!this.has(module2)) {
  71170. this.set(module2, /* @__PURE__ */ new Set());
  71171. }
  71172. this.get(module2).add(specifier);
  71173. return this;
  71174. }
  71175. merge(map2) {
  71176. const out = new _ImportMap();
  71177. for (const [mod, specifiers] of [...this, ...map2]) {
  71178. for (const specifier of specifiers) {
  71179. out.add(mod, specifier);
  71180. }
  71181. }
  71182. return out;
  71183. }
  71184. };
  71185. exports.ImportMap = ImportMap;
  71186. }
  71187. });
  71188. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/index.js
  71189. var require_reflection = __commonJS({
  71190. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/index.js"(exports) {
  71191. "use strict";
  71192. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  71193. if (k22 === void 0) k22 = k5;
  71194. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  71195. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  71196. desc = { enumerable: true, get: function() {
  71197. return m6[k5];
  71198. } };
  71199. }
  71200. Object.defineProperty(o5, k22, desc);
  71201. } : function(o5, m6, k5, k22) {
  71202. if (k22 === void 0) k22 = k5;
  71203. o5[k22] = m6[k5];
  71204. });
  71205. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  71206. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  71207. } : function(o5, v6) {
  71208. o5["default"] = v6;
  71209. });
  71210. var __exportStar = exports && exports.__exportStar || function(m6, exports2) {
  71211. for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p5)) __createBinding(exports2, m6, p5);
  71212. };
  71213. var __importStar = exports && exports.__importStar || function(mod) {
  71214. if (mod && mod.__esModule) return mod;
  71215. var result = {};
  71216. if (mod != null) {
  71217. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  71218. }
  71219. __setModuleDefault(result, mod);
  71220. return result;
  71221. };
  71222. Object.defineProperty(exports, "__esModule", { value: true });
  71223. exports.Capabilities = exports.introspect = void 0;
  71224. __exportStar(require_enums(), exports);
  71225. __exportStar(require_util3(), exports);
  71226. __exportStar(require_typeutil(), exports);
  71227. __exportStar(require_util3(), exports);
  71228. __exportStar(require_strictMap(), exports);
  71229. __exportStar(require_reservedKeywords(), exports);
  71230. exports.introspect = __importStar(require_queries());
  71231. __exportStar(require_analyzeQuery(), exports);
  71232. var baseConn_1 = require_baseConn();
  71233. Object.defineProperty(exports, "Capabilities", { enumerable: true, get: function() {
  71234. return baseConn_1.Capabilities;
  71235. } });
  71236. }
  71237. });
  71238. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.node.js
  71239. var require_index_node = __commonJS({
  71240. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.node.js"(exports) {
  71241. "use strict";
  71242. var __createBinding = exports && exports.__createBinding || (Object.create ? function(o5, m6, k5, k22) {
  71243. if (k22 === void 0) k22 = k5;
  71244. var desc = Object.getOwnPropertyDescriptor(m6, k5);
  71245. if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
  71246. desc = { enumerable: true, get: function() {
  71247. return m6[k5];
  71248. } };
  71249. }
  71250. Object.defineProperty(o5, k22, desc);
  71251. } : function(o5, m6, k5, k22) {
  71252. if (k22 === void 0) k22 = k5;
  71253. o5[k22] = m6[k5];
  71254. });
  71255. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
  71256. Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
  71257. } : function(o5, v6) {
  71258. o5["default"] = v6;
  71259. });
  71260. var __importStar = exports && exports.__importStar || function(mod) {
  71261. if (mod && mod.__esModule) return mod;
  71262. var result = {};
  71263. if (mod != null) {
  71264. for (var k5 in mod) if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) __createBinding(result, mod, k5);
  71265. }
  71266. __setModuleDefault(result, mod);
  71267. return result;
  71268. };
  71269. var __exportStar = exports && exports.__exportStar || function(m6, exports2) {
  71270. for (var p5 in m6) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p5)) __createBinding(exports2, m6, p5);
  71271. };
  71272. Object.defineProperty(exports, "__esModule", { value: true });
  71273. exports.$ = exports.Client = exports.ResolvedConnectConfig = exports._RawConnection = exports.systemUtils = exports.createHttpClient = exports.createClient = void 0;
  71274. var nodeClient_1 = require_nodeClient();
  71275. exports.default = nodeClient_1.createClient;
  71276. var nodeClient_2 = require_nodeClient();
  71277. Object.defineProperty(exports, "createClient", { enumerable: true, get: function() {
  71278. return nodeClient_2.createClient;
  71279. } });
  71280. Object.defineProperty(exports, "createHttpClient", { enumerable: true, get: function() {
  71281. return nodeClient_2.createHttpClient;
  71282. } });
  71283. var systemUtils = __importStar(require_systemUtils());
  71284. exports.systemUtils = systemUtils;
  71285. var rawConn_1 = require_rawConn();
  71286. Object.defineProperty(exports, "_RawConnection", { enumerable: true, get: function() {
  71287. return rawConn_1.RawConnection;
  71288. } });
  71289. var conUtils_1 = require_conUtils();
  71290. Object.defineProperty(exports, "ResolvedConnectConfig", { enumerable: true, get: function() {
  71291. return conUtils_1.ResolvedConnectConfig;
  71292. } });
  71293. var baseClient_1 = require_baseClient();
  71294. Object.defineProperty(exports, "Client", { enumerable: true, get: function() {
  71295. return baseClient_1.Client;
  71296. } });
  71297. __exportStar(require_index_shared(), exports);
  71298. exports.$ = __importStar(require_reflection());
  71299. }
  71300. });
  71301. // src/cli/connections.ts
  71302. var connections_exports = {};
  71303. __export(connections_exports, {
  71304. connectToD1: () => connectToD1,
  71305. connectToLibSQL: () => connectToLibSQL,
  71306. connectToMySQL: () => connectToMySQL,
  71307. connectToSQLite: () => connectToSQLite,
  71308. connectToSingleStore: () => connectToSingleStore,
  71309. prepareGelDB: () => prepareGelDB,
  71310. preparePostgresDB: () => preparePostgresDB
  71311. });
  71312. var preparePostgresDB, prepareGelDB, parseSingleStoreCredentials, connectToSingleStore, parseMysqlCredentials, connectToMySQL, prepareSqliteParams, preparePGliteParams, connectToD1, connectToSQLite, connectToLibSQL;
  71313. var init_connections = __esm({
  71314. "src/cli/connections.ts"() {
  71315. "use strict";
  71316. init_src();
  71317. init_wrapper();
  71318. init_global();
  71319. init_utils();
  71320. init_utils4();
  71321. init_outputs();
  71322. preparePostgresDB = async (credentials2) => {
  71323. if ("driver" in credentials2) {
  71324. const { driver: driver2 } = credentials2;
  71325. if (driver2 === "aws-data-api") {
  71326. assertPackages("@aws-sdk/client-rds-data");
  71327. const { RDSDataClient: RDSDataClient2, ExecuteStatementCommand: ExecuteStatementCommand2, TypeHint: TypeHint2 } = await Promise.resolve().then(() => (init_dist_es53(), dist_es_exports8));
  71328. const { AwsDataApiSession, drizzle } = await import("drizzle-orm/aws-data-api/pg");
  71329. const { migrate } = await import("drizzle-orm/aws-data-api/pg/migrator");
  71330. const { PgDialect: PgDialect2 } = await import("drizzle-orm/pg-core");
  71331. const config = {
  71332. database: credentials2.database,
  71333. resourceArn: credentials2.resourceArn,
  71334. secretArn: credentials2.secretArn
  71335. };
  71336. const rdsClient = new RDSDataClient2();
  71337. const session = new AwsDataApiSession(
  71338. rdsClient,
  71339. new PgDialect2(),
  71340. void 0,
  71341. config,
  71342. void 0
  71343. );
  71344. const db = drizzle(rdsClient, config);
  71345. const migrateFn = async (config2) => {
  71346. return migrate(db, config2);
  71347. };
  71348. const query = async (sql, params) => {
  71349. const prepared = session.prepareQuery(
  71350. { sql, params: params ?? [] },
  71351. void 0,
  71352. void 0,
  71353. false
  71354. );
  71355. const result = await prepared.all();
  71356. return result;
  71357. };
  71358. const proxy = async (params) => {
  71359. const prepared = session.prepareQuery(
  71360. {
  71361. sql: params.sql,
  71362. params: params.params ?? [],
  71363. typings: params.typings
  71364. },
  71365. void 0,
  71366. void 0,
  71367. params.mode === "array"
  71368. );
  71369. if (params.mode === "array") {
  71370. const result2 = await prepared.values();
  71371. return result2.rows;
  71372. }
  71373. const result = await prepared.execute();
  71374. return result.rows;
  71375. };
  71376. const transactionProxy = async (queries) => {
  71377. throw new Error("Transaction not supported");
  71378. };
  71379. return {
  71380. packageName: "@aws-sdk/client-rds-data",
  71381. query,
  71382. proxy,
  71383. transactionProxy,
  71384. migrate: migrateFn
  71385. };
  71386. }
  71387. if (driver2 === "pglite") {
  71388. assertPackages("@electric-sql/pglite");
  71389. const { PGlite, types: types3 } = await import("@electric-sql/pglite");
  71390. const { drizzle } = await import("drizzle-orm/pglite");
  71391. const { migrate } = await import("drizzle-orm/pglite/migrator");
  71392. const pglite = "client" in credentials2 ? credentials2.client : new PGlite(normalisePGliteUrl(credentials2.url));
  71393. await pglite.waitReady;
  71394. const drzl = drizzle(pglite);
  71395. const migrateFn = async (config) => {
  71396. return migrate(drzl, config);
  71397. };
  71398. const parsers = {
  71399. [types3.TIMESTAMP]: (value) => value,
  71400. [types3.TIMESTAMPTZ]: (value) => value,
  71401. [types3.INTERVAL]: (value) => value,
  71402. [types3.DATE]: (value) => value
  71403. };
  71404. const query = async (sql, params = []) => {
  71405. const result = await pglite.query(sql, params, {
  71406. parsers
  71407. });
  71408. return result.rows;
  71409. };
  71410. const proxy = async (params) => {
  71411. const preparedParams = preparePGliteParams(params.params || []);
  71412. const result = await pglite.query(params.sql, preparedParams, {
  71413. rowMode: params.mode,
  71414. parsers
  71415. });
  71416. return result.rows;
  71417. };
  71418. const transactionProxy = async (queries) => {
  71419. const results = [];
  71420. try {
  71421. await pglite.transaction(async (tx) => {
  71422. for (const query2 of queries) {
  71423. const result = await tx.query(query2.sql, void 0, {
  71424. parsers
  71425. });
  71426. results.push(result.rows);
  71427. }
  71428. });
  71429. } catch (error2) {
  71430. results.push(error2);
  71431. }
  71432. return results;
  71433. };
  71434. return { packageName: "pglite", query, proxy, transactionProxy, migrate: migrateFn };
  71435. }
  71436. assertUnreachable(driver2);
  71437. }
  71438. if (await checkPackage("pg")) {
  71439. console.log(withStyle.info(`Using 'pg' driver for database querying`));
  71440. const { default: pg } = await import("pg");
  71441. const { drizzle } = await import("drizzle-orm/node-postgres");
  71442. const { migrate } = await import("drizzle-orm/node-postgres/migrator");
  71443. const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
  71444. const types3 = {
  71445. // @ts-ignore
  71446. getTypeParser: (typeId, format) => {
  71447. if (typeId === pg.types.builtins.TIMESTAMPTZ) {
  71448. return (val2) => val2;
  71449. }
  71450. if (typeId === pg.types.builtins.TIMESTAMP) {
  71451. return (val2) => val2;
  71452. }
  71453. if (typeId === pg.types.builtins.DATE) {
  71454. return (val2) => val2;
  71455. }
  71456. if (typeId === pg.types.builtins.INTERVAL) {
  71457. return (val2) => val2;
  71458. }
  71459. return pg.types.getTypeParser(typeId, format);
  71460. }
  71461. };
  71462. const client = "url" in credentials2 ? new pg.Pool({ connectionString: credentials2.url, max: 1 }) : new pg.Pool({ ...credentials2, ssl, max: 1 });
  71463. const db = drizzle(client);
  71464. const migrateFn = async (config) => {
  71465. return migrate(db, config);
  71466. };
  71467. const query = async (sql, params) => {
  71468. const result = await client.query({
  71469. text: sql,
  71470. values: params ?? [],
  71471. types: types3
  71472. });
  71473. return result.rows;
  71474. };
  71475. const proxy = async (params) => {
  71476. const result = await client.query({
  71477. text: params.sql,
  71478. values: params.params,
  71479. ...params.mode === "array" && { rowMode: "array" },
  71480. types: types3
  71481. });
  71482. return result.rows;
  71483. };
  71484. const transactionProxy = async (queries) => {
  71485. const results = [];
  71486. const tx = await client.connect();
  71487. try {
  71488. await tx.query("BEGIN");
  71489. for (const query2 of queries) {
  71490. const result = await tx.query({
  71491. text: query2.sql,
  71492. types: types3
  71493. });
  71494. results.push(result.rows);
  71495. }
  71496. await tx.query("COMMIT");
  71497. } catch (error2) {
  71498. await tx.query("ROLLBACK");
  71499. results.push(error2);
  71500. } finally {
  71501. tx.release();
  71502. }
  71503. return results;
  71504. };
  71505. return { packageName: "pg", query, proxy, transactionProxy, migrate: migrateFn };
  71506. }
  71507. if (await checkPackage("postgres")) {
  71508. console.log(
  71509. withStyle.info(`Using 'postgres' driver for database querying`)
  71510. );
  71511. const postgres = await import("postgres");
  71512. const { drizzle } = await import("drizzle-orm/postgres-js");
  71513. const { migrate } = await import("drizzle-orm/postgres-js/migrator");
  71514. const client = "url" in credentials2 ? postgres.default(credentials2.url, { max: 1 }) : postgres.default({ ...credentials2, max: 1 });
  71515. const transparentParser = (val2) => val2;
  71516. for (const type of ["1184", "1082", "1083", "1114"]) {
  71517. client.options.parsers[type] = transparentParser;
  71518. client.options.serializers[type] = transparentParser;
  71519. }
  71520. client.options.serializers["114"] = transparentParser;
  71521. client.options.serializers["3802"] = transparentParser;
  71522. const db = drizzle(client);
  71523. const migrateFn = async (config) => {
  71524. return migrate(db, config);
  71525. };
  71526. const query = async (sql, params) => {
  71527. const result = await client.unsafe(sql, params ?? []);
  71528. return result;
  71529. };
  71530. const proxy = async (params) => {
  71531. if (params.mode === "array") {
  71532. return await client.unsafe(params.sql, params.params).values();
  71533. }
  71534. return await client.unsafe(params.sql, params.params);
  71535. };
  71536. const transactionProxy = async (queries) => {
  71537. const results = [];
  71538. try {
  71539. await client.begin(async (sql) => {
  71540. for (const query2 of queries) {
  71541. const result = await sql.unsafe(query2.sql);
  71542. results.push(result);
  71543. }
  71544. });
  71545. } catch (error2) {
  71546. results.push(error2);
  71547. }
  71548. return results;
  71549. };
  71550. return { packageName: "postgres", query, proxy, transactionProxy, migrate: migrateFn };
  71551. }
  71552. if (await checkPackage("@vercel/postgres")) {
  71553. console.log(
  71554. withStyle.info(`Using '@vercel/postgres' driver for database querying`)
  71555. );
  71556. console.log(
  71557. withStyle.fullWarning(
  71558. "'@vercel/postgres' can only connect to remote Neon/Vercel Postgres/Supabase instances through a websocket"
  71559. )
  71560. );
  71561. const { VercelPool, types: pgTypes } = await import("@vercel/postgres");
  71562. const { drizzle } = await import("drizzle-orm/vercel-postgres");
  71563. const { migrate } = await import("drizzle-orm/vercel-postgres/migrator");
  71564. const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
  71565. const types3 = {
  71566. // @ts-ignore
  71567. getTypeParser: (typeId, format) => {
  71568. if (typeId === pgTypes.builtins.TIMESTAMPTZ) {
  71569. return (val2) => val2;
  71570. }
  71571. if (typeId === pgTypes.builtins.TIMESTAMP) {
  71572. return (val2) => val2;
  71573. }
  71574. if (typeId === pgTypes.builtins.DATE) {
  71575. return (val2) => val2;
  71576. }
  71577. if (typeId === pgTypes.builtins.INTERVAL) {
  71578. return (val2) => val2;
  71579. }
  71580. return pgTypes.getTypeParser(typeId, format);
  71581. }
  71582. };
  71583. const client = "url" in credentials2 ? new VercelPool({ connectionString: credentials2.url }) : new VercelPool({ ...credentials2, ssl });
  71584. await client.connect();
  71585. const db = drizzle(client);
  71586. const migrateFn = async (config) => {
  71587. return migrate(db, config);
  71588. };
  71589. const query = async (sql, params) => {
  71590. const result = await client.query({
  71591. text: sql,
  71592. values: params ?? [],
  71593. types: types3
  71594. });
  71595. return result.rows;
  71596. };
  71597. const proxy = async (params) => {
  71598. const result = await client.query({
  71599. text: params.sql,
  71600. values: params.params,
  71601. ...params.mode === "array" && { rowMode: "array" },
  71602. types: types3
  71603. });
  71604. return result.rows;
  71605. };
  71606. const transactionProxy = async (queries) => {
  71607. const results = [];
  71608. const tx = await client.connect();
  71609. try {
  71610. await tx.query("BEGIN");
  71611. for (const query2 of queries) {
  71612. const result = await tx.query({
  71613. text: query2.sql,
  71614. types: types3
  71615. });
  71616. results.push(result.rows);
  71617. }
  71618. await tx.query("COMMIT");
  71619. } catch (error2) {
  71620. await tx.query("ROLLBACK");
  71621. results.push(error2);
  71622. } finally {
  71623. tx.release();
  71624. }
  71625. return results;
  71626. };
  71627. return { packageName: "@vercel/postgres", query, proxy, transactionProxy, migrate: migrateFn };
  71628. }
  71629. if (await checkPackage("@neondatabase/serverless")) {
  71630. console.log(
  71631. withStyle.info(
  71632. `Using '@neondatabase/serverless' driver for database querying`
  71633. )
  71634. );
  71635. console.log(
  71636. withStyle.fullWarning(
  71637. "'@neondatabase/serverless' can only connect to remote Neon/Vercel Postgres/Supabase instances through a websocket"
  71638. )
  71639. );
  71640. const { Pool, neonConfig, types: pgTypes } = await import("@neondatabase/serverless");
  71641. const { drizzle } = await import("drizzle-orm/neon-serverless");
  71642. const { migrate } = await import("drizzle-orm/neon-serverless/migrator");
  71643. const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
  71644. const types3 = {
  71645. // @ts-ignore
  71646. getTypeParser: (typeId, format) => {
  71647. if (typeId === pgTypes.builtins.TIMESTAMPTZ) {
  71648. return (val2) => val2;
  71649. }
  71650. if (typeId === pgTypes.builtins.TIMESTAMP) {
  71651. return (val2) => val2;
  71652. }
  71653. if (typeId === pgTypes.builtins.DATE) {
  71654. return (val2) => val2;
  71655. }
  71656. if (typeId === pgTypes.builtins.INTERVAL) {
  71657. return (val2) => val2;
  71658. }
  71659. return pgTypes.getTypeParser(typeId, format);
  71660. }
  71661. };
  71662. const client = "url" in credentials2 ? new Pool({ connectionString: credentials2.url, max: 1 }) : new Pool({ ...credentials2, max: 1, ssl });
  71663. neonConfig.webSocketConstructor = wrapper_default;
  71664. const db = drizzle(client);
  71665. const migrateFn = async (config) => {
  71666. return migrate(db, config);
  71667. };
  71668. const query = async (sql, params) => {
  71669. const result = await client.query({
  71670. text: sql,
  71671. values: params ?? [],
  71672. types: types3
  71673. });
  71674. return result.rows;
  71675. };
  71676. const proxy = async (params) => {
  71677. const result = await client.query({
  71678. text: params.sql,
  71679. values: params.params,
  71680. ...params.mode === "array" && { rowMode: "array" },
  71681. types: types3
  71682. });
  71683. return result.rows;
  71684. };
  71685. const transactionProxy = async (queries) => {
  71686. const results = [];
  71687. const tx = await client.connect();
  71688. try {
  71689. await tx.query("BEGIN");
  71690. for (const query2 of queries) {
  71691. const result = await tx.query({
  71692. text: query2.sql,
  71693. types: types3
  71694. });
  71695. results.push(result.rows);
  71696. }
  71697. await tx.query("COMMIT");
  71698. } catch (error2) {
  71699. await tx.query("ROLLBACK");
  71700. results.push(error2);
  71701. } finally {
  71702. tx.release();
  71703. }
  71704. return results;
  71705. };
  71706. return { packageName: "@neondatabase/serverless", query, proxy, transactionProxy, migrate: migrateFn };
  71707. }
  71708. console.error(
  71709. "To connect to Postgres database - please install either of 'pg', 'postgres', '@neondatabase/serverless' or '@vercel/postgres' drivers"
  71710. );
  71711. process.exit(1);
  71712. };
  71713. prepareGelDB = async (credentials2) => {
  71714. if (await checkPackage("gel")) {
  71715. const gel = await Promise.resolve().then(() => __toESM(require_index_node()));
  71716. let client;
  71717. if (!credentials2) {
  71718. client = gel.createClient();
  71719. try {
  71720. await client.querySQL(`select 1;`);
  71721. } catch (error2) {
  71722. if (error2 instanceof gel.ClientConnectionError) {
  71723. console.error(
  71724. `It looks like you forgot to link the Gel project or provide the database credentials.
  71725. To link your project, please refer https://docs.geldata.com/reference/cli/gel_instance/gel_instance_link, or add the dbCredentials to your configuration file.`
  71726. );
  71727. process.exit(1);
  71728. }
  71729. throw error2;
  71730. }
  71731. } else if ("url" in credentials2) {
  71732. "tlsSecurity" in credentials2 ? client = gel.createClient({ dsn: credentials2.url, tlsSecurity: credentials2.tlsSecurity, concurrency: 1 }) : client = gel.createClient({ dsn: credentials2.url, concurrency: 1 });
  71733. } else {
  71734. gel.createClient({ ...credentials2, concurrency: 1 });
  71735. }
  71736. const query = async (sql, params) => {
  71737. const result = params?.length ? await client.querySQL(sql, params) : await client.querySQL(sql);
  71738. return result;
  71739. };
  71740. const proxy = async (params) => {
  71741. const { method, mode, params: sqlParams, sql, typings } = params;
  71742. let result;
  71743. switch (mode) {
  71744. case "array":
  71745. result = sqlParams?.length ? await client.withSQLRowMode("array").querySQL(sql, sqlParams) : await client.withSQLRowMode("array").querySQL(sql);
  71746. break;
  71747. case "object":
  71748. result = sqlParams?.length ? await client.querySQL(sql, sqlParams) : await client.querySQL(sql);
  71749. break;
  71750. }
  71751. return result;
  71752. };
  71753. const transactionProxy = async (queries) => {
  71754. const result = [];
  71755. try {
  71756. await client.transaction(async (tx) => {
  71757. for (const query2 of queries) {
  71758. const res = await tx.querySQL(query2.sql);
  71759. result.push(res);
  71760. }
  71761. });
  71762. } catch (error2) {
  71763. result.push(error2);
  71764. }
  71765. return result;
  71766. };
  71767. return { packageName: "gel", query, proxy, transactionProxy };
  71768. }
  71769. console.error(
  71770. "To connect to gel database - please install 'edgedb' driver"
  71771. );
  71772. process.exit(1);
  71773. };
  71774. parseSingleStoreCredentials = (credentials2) => {
  71775. if ("url" in credentials2) {
  71776. const url = credentials2.url;
  71777. const connectionUrl = new URL(url);
  71778. const pathname = connectionUrl.pathname;
  71779. const database = pathname.split("/")[pathname.split("/").length - 1];
  71780. if (!database) {
  71781. console.error(
  71782. "You should specify a database name in connection string (singlestore://USER:PASSWORD@HOST:PORT/DATABASE)"
  71783. );
  71784. process.exit(1);
  71785. }
  71786. return { database, url };
  71787. } else {
  71788. return {
  71789. database: credentials2.database,
  71790. credentials: credentials2
  71791. };
  71792. }
  71793. };
  71794. connectToSingleStore = async (it) => {
  71795. const result = parseSingleStoreCredentials(it);
  71796. if (await checkPackage("mysql2")) {
  71797. const { createConnection } = await import("mysql2/promise");
  71798. const { drizzle } = await import("drizzle-orm/singlestore");
  71799. const { migrate } = await import("drizzle-orm/singlestore/migrator");
  71800. const connection = result.url ? await createConnection(result.url) : await createConnection(result.credentials);
  71801. const db = drizzle(connection);
  71802. const migrateFn = async (config) => {
  71803. return migrate(db, config);
  71804. };
  71805. await connection.connect();
  71806. const query = async (sql, params) => {
  71807. const res = await connection.execute(sql, params);
  71808. return res[0];
  71809. };
  71810. const proxy = async (params) => {
  71811. const result2 = await connection.query({
  71812. sql: params.sql,
  71813. values: params.params,
  71814. rowsAsArray: params.mode === "array"
  71815. });
  71816. return result2[0];
  71817. };
  71818. const transactionProxy = async (queries) => {
  71819. const results = [];
  71820. try {
  71821. await connection.beginTransaction();
  71822. for (const query2 of queries) {
  71823. const res = await connection.query(query2.sql);
  71824. results.push(res[0]);
  71825. }
  71826. await connection.commit();
  71827. } catch (error2) {
  71828. await connection.rollback();
  71829. results.push(error2);
  71830. }
  71831. return results;
  71832. };
  71833. return {
  71834. db: { query },
  71835. packageName: "mysql2",
  71836. proxy,
  71837. transactionProxy,
  71838. database: result.database,
  71839. migrate: migrateFn
  71840. };
  71841. }
  71842. console.error(
  71843. "To connect to SingleStore database - please install 'mysql2' driver"
  71844. );
  71845. process.exit(1);
  71846. };
  71847. parseMysqlCredentials = (credentials2) => {
  71848. if ("url" in credentials2) {
  71849. const url = credentials2.url;
  71850. const connectionUrl = new URL(url);
  71851. const pathname = connectionUrl.pathname;
  71852. const database = pathname.split("/")[pathname.split("/").length - 1];
  71853. if (!database) {
  71854. console.error(
  71855. "You should specify a database name in connection string (mysql://USER:PASSWORD@HOST:PORT/DATABASE)"
  71856. );
  71857. process.exit(1);
  71858. }
  71859. return { database, url };
  71860. } else {
  71861. return {
  71862. database: credentials2.database,
  71863. credentials: credentials2
  71864. };
  71865. }
  71866. };
  71867. connectToMySQL = async (it) => {
  71868. const result = parseMysqlCredentials(it);
  71869. if (await checkPackage("mysql2")) {
  71870. const { createConnection } = await import("mysql2/promise");
  71871. const { drizzle } = await import("drizzle-orm/mysql2");
  71872. const { migrate } = await import("drizzle-orm/mysql2/migrator");
  71873. const connection = result.url ? await createConnection(result.url) : await createConnection(result.credentials);
  71874. const db = drizzle(connection);
  71875. const migrateFn = async (config) => {
  71876. return migrate(db, config);
  71877. };
  71878. const typeCast = (field, next) => {
  71879. if (field.type === "TIMESTAMP" || field.type === "DATETIME" || field.type === "DATE") {
  71880. return field.string();
  71881. }
  71882. return next();
  71883. };
  71884. await connection.connect();
  71885. const query = async (sql, params) => {
  71886. const res = await connection.execute({
  71887. sql,
  71888. values: params,
  71889. typeCast
  71890. });
  71891. return res[0];
  71892. };
  71893. const proxy = async (params) => {
  71894. const result2 = await connection.query({
  71895. sql: params.sql,
  71896. values: params.params,
  71897. rowsAsArray: params.mode === "array",
  71898. typeCast
  71899. });
  71900. return result2[0];
  71901. };
  71902. const transactionProxy = async (queries) => {
  71903. const results = [];
  71904. try {
  71905. await connection.beginTransaction();
  71906. for (const query2 of queries) {
  71907. const res = await connection.query(query2.sql);
  71908. results.push(res[0]);
  71909. }
  71910. await connection.commit();
  71911. } catch (error2) {
  71912. await connection.rollback();
  71913. results.push(error2);
  71914. }
  71915. return results;
  71916. };
  71917. return {
  71918. db: { query },
  71919. packageName: "mysql2",
  71920. proxy,
  71921. transactionProxy,
  71922. database: result.database,
  71923. migrate: migrateFn
  71924. };
  71925. }
  71926. if (await checkPackage("@planetscale/database")) {
  71927. const { Client: Client2 } = await import("@planetscale/database");
  71928. const { drizzle } = await import("drizzle-orm/planetscale-serverless");
  71929. const { migrate } = await import("drizzle-orm/planetscale-serverless/migrator");
  71930. const connection = new Client2(result);
  71931. const db = drizzle(connection);
  71932. const migrateFn = async (config) => {
  71933. return migrate(db, config);
  71934. };
  71935. const query = async (sql, params) => {
  71936. const res = await connection.execute(sql, params);
  71937. return res.rows;
  71938. };
  71939. const proxy = async (params) => {
  71940. const result2 = await connection.execute(
  71941. params.sql,
  71942. params.params,
  71943. params.mode === "array" ? { as: "array" } : void 0
  71944. );
  71945. return result2.rows;
  71946. };
  71947. const transactionProxy = async (queries) => {
  71948. const results = [];
  71949. try {
  71950. await connection.transaction(async (tx) => {
  71951. for (const query2 of queries) {
  71952. const res = await tx.execute(query2.sql);
  71953. results.push(res.rows);
  71954. }
  71955. });
  71956. } catch (error2) {
  71957. results.push(error2);
  71958. }
  71959. return results;
  71960. };
  71961. return {
  71962. db: { query },
  71963. packageName: "@planetscale/database",
  71964. proxy,
  71965. transactionProxy,
  71966. database: result.database,
  71967. migrate: migrateFn
  71968. };
  71969. }
  71970. console.error(
  71971. "To connect to MySQL database - please install either of 'mysql2' or '@planetscale/database' drivers"
  71972. );
  71973. process.exit(1);
  71974. };
  71975. prepareSqliteParams = (params, driver2) => {
  71976. return params.map((param) => {
  71977. if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
  71978. const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
  71979. if (driver2 === "d1-http" || driver2 === "d1") {
  71980. return value;
  71981. }
  71982. return Buffer.from(value);
  71983. }
  71984. return param;
  71985. });
  71986. };
  71987. preparePGliteParams = (params) => {
  71988. return params.map((param) => {
  71989. if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
  71990. const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
  71991. return value;
  71992. }
  71993. return param;
  71994. });
  71995. };
  71996. connectToD1 = async (d1) => {
  71997. const db = {
  71998. query: async (sql, params) => {
  71999. const stmt = d1.prepare(sql);
  72000. const boundStmt = params && params.length > 0 ? stmt.bind(...params) : stmt;
  72001. const result = await boundStmt.all();
  72002. return result.results ?? [];
  72003. },
  72004. run: async (query) => {
  72005. const stmt = d1.prepare(query);
  72006. await stmt.run();
  72007. }
  72008. };
  72009. const proxy = async (params) => {
  72010. const preparedParams = prepareSqliteParams(params.params || [], "d1");
  72011. const stmt = d1.prepare(params.sql);
  72012. const boundStmt = preparedParams.length > 0 ? stmt.bind(...preparedParams) : stmt;
  72013. try {
  72014. if (params.mode === "array") {
  72015. return await boundStmt.raw();
  72016. }
  72017. const result = await boundStmt.all();
  72018. return result.results ?? [];
  72019. } catch (error2) {
  72020. if (error2?.message?.includes("SQLITE_AUTH") || error2?.message?.includes("not authorized")) {
  72021. return [];
  72022. }
  72023. throw error2;
  72024. }
  72025. };
  72026. const transactionProxy = async (queries) => {
  72027. const results = [];
  72028. try {
  72029. const statements = queries.map((q5) => d1.prepare(q5.sql));
  72030. const batchResults = await d1.batch(statements);
  72031. for (const result of batchResults) {
  72032. results.push(result.results ?? []);
  72033. }
  72034. } catch (error2) {
  72035. results.push(error2);
  72036. }
  72037. return results;
  72038. };
  72039. const { drizzle } = await import("drizzle-orm/d1");
  72040. const { migrate } = await import("drizzle-orm/d1/migrator");
  72041. const drzl = drizzle(d1);
  72042. const migrateFn = async (config) => {
  72043. return migrate(drzl, config);
  72044. };
  72045. return { ...db, packageName: "d1", proxy, transactionProxy, migrate: migrateFn };
  72046. };
  72047. connectToSQLite = async (credentials2) => {
  72048. if ("driver" in credentials2) {
  72049. const { driver: driver2 } = credentials2;
  72050. if (driver2 === "d1-http") {
  72051. const { drizzle } = await import("drizzle-orm/sqlite-proxy");
  72052. const { migrate } = await import("drizzle-orm/sqlite-proxy/migrator");
  72053. const remoteCallback = async (sql, params, method) => {
  72054. const res = await fetch2(
  72055. `https://api.cloudflare.com/client/v4/accounts/${credentials2.accountId}/d1/database/${credentials2.databaseId}/${method === "values" ? "raw" : "query"}`,
  72056. {
  72057. method: "POST",
  72058. body: JSON.stringify({ sql, params }),
  72059. headers: {
  72060. "Content-Type": "application/json",
  72061. Authorization: `Bearer ${credentials2.token}`
  72062. }
  72063. }
  72064. );
  72065. const data = await res.json();
  72066. if (!data.success) {
  72067. throw new Error(
  72068. data.errors.map((it) => `${it.code}: ${it.message}`).join("\n")
  72069. );
  72070. }
  72071. const result = data.result[0].results;
  72072. const rows = Array.isArray(result) ? result : result.rows;
  72073. return {
  72074. rows
  72075. };
  72076. };
  72077. const remoteBatchCallback = async (queries) => {
  72078. const sql = queries.map((q5) => q5.sql).join("; ");
  72079. const res = await fetch2(
  72080. `https://api.cloudflare.com/client/v4/accounts/${credentials2.accountId}/d1/database/${credentials2.databaseId}/query`,
  72081. {
  72082. method: "POST",
  72083. body: JSON.stringify({ sql }),
  72084. headers: {
  72085. "Content-Type": "application/json",
  72086. Authorization: `Bearer ${credentials2.token}`
  72087. }
  72088. }
  72089. );
  72090. const data = await res.json();
  72091. if (!data.success) {
  72092. throw new Error(
  72093. data.errors.map((it) => `${it.code}: ${it.message}`).join("\n")
  72094. );
  72095. }
  72096. const rows = data.result.map((result) => {
  72097. const res2 = result.results;
  72098. return Array.isArray(res2) ? res2 : res2.rows;
  72099. });
  72100. return {
  72101. rows
  72102. };
  72103. };
  72104. const drzl = drizzle(remoteCallback);
  72105. const migrateFn = async (config) => {
  72106. return migrate(
  72107. drzl,
  72108. async (queries) => {
  72109. for (const query of queries) {
  72110. await remoteCallback(query, [], "run");
  72111. }
  72112. },
  72113. config
  72114. );
  72115. };
  72116. const db = {
  72117. query: async (sql, params) => {
  72118. const res = await remoteCallback(sql, params || [], "all");
  72119. return res.rows;
  72120. },
  72121. run: async (query) => {
  72122. await remoteCallback(query, [], "run");
  72123. }
  72124. };
  72125. const proxy = async (params) => {
  72126. const preparedParams = prepareSqliteParams(params.params || [], "d1-http");
  72127. const result = await remoteCallback(
  72128. params.sql,
  72129. preparedParams,
  72130. params.mode === "array" ? "values" : "all"
  72131. );
  72132. return result.rows;
  72133. };
  72134. const transactionProxy = async (queries) => {
  72135. const result = await remoteBatchCallback(queries);
  72136. return result.rows;
  72137. };
  72138. return { ...db, packageName: "d1-http", proxy, transactionProxy, migrate: migrateFn };
  72139. } else {
  72140. assertUnreachable(driver2);
  72141. }
  72142. }
  72143. if (await checkPackage("@libsql/client")) {
  72144. const { createClient } = await import("@libsql/client");
  72145. const { drizzle } = await import("drizzle-orm/libsql");
  72146. const { migrate } = await import("drizzle-orm/libsql/migrator");
  72147. const client = createClient({
  72148. url: normaliseSQLiteUrl(credentials2.url, "libsql")
  72149. });
  72150. const drzl = drizzle(client);
  72151. const migrateFn = async (config) => {
  72152. return migrate(drzl, config);
  72153. };
  72154. const db = {
  72155. query: async (sql, params) => {
  72156. const res = await client.execute({ sql, args: params || [] });
  72157. return res.rows;
  72158. },
  72159. run: async (query) => {
  72160. await client.execute(query);
  72161. }
  72162. };
  72163. const proxy = async (params) => {
  72164. const preparedParams = prepareSqliteParams(params.params || []);
  72165. const result = await client.execute({
  72166. sql: params.sql,
  72167. args: preparedParams
  72168. });
  72169. if (params.mode === "array") {
  72170. return result.rows.map((row) => Object.values(row));
  72171. } else {
  72172. return result.rows;
  72173. }
  72174. };
  72175. const transactionProxy = async (queries) => {
  72176. const results = [];
  72177. let transaction = null;
  72178. try {
  72179. transaction = await client.transaction();
  72180. for (const query of queries) {
  72181. const result = await transaction.execute(query.sql);
  72182. results.push(result.rows);
  72183. }
  72184. await transaction.commit();
  72185. } catch (error2) {
  72186. results.push(error2);
  72187. await transaction?.rollback();
  72188. } finally {
  72189. transaction?.close();
  72190. }
  72191. return results;
  72192. };
  72193. return { ...db, packageName: "@libsql/client", proxy, transactionProxy, migrate: migrateFn };
  72194. }
  72195. if (await checkPackage("better-sqlite3")) {
  72196. const { default: Database } = await import("better-sqlite3");
  72197. const { drizzle } = await import("drizzle-orm/better-sqlite3");
  72198. const { migrate } = await import("drizzle-orm/better-sqlite3/migrator");
  72199. const sqlite = new Database(
  72200. normaliseSQLiteUrl(credentials2.url, "better-sqlite")
  72201. );
  72202. const drzl = drizzle(sqlite);
  72203. const migrateFn = async (config) => {
  72204. return migrate(drzl, config);
  72205. };
  72206. const db = {
  72207. query: async (sql, params = []) => {
  72208. return sqlite.prepare(sql).bind(params).all();
  72209. },
  72210. run: async (query) => {
  72211. sqlite.prepare(query).run();
  72212. }
  72213. };
  72214. const proxy = async (params) => {
  72215. const preparedParams = prepareSqliteParams(params.params || []);
  72216. if (params.method === "values" || params.method === "get" || params.method === "all") {
  72217. return sqlite.prepare(params.sql).raw(params.mode === "array").all(preparedParams);
  72218. }
  72219. sqlite.prepare(params.sql).run(preparedParams);
  72220. return [];
  72221. };
  72222. const transactionProxy = async (queries) => {
  72223. const results = [];
  72224. const tx = sqlite.transaction((queries2) => {
  72225. for (const query of queries2) {
  72226. let result = [];
  72227. if (query.method === "values" || query.method === "get" || query.method === "all") {
  72228. result = sqlite.prepare(query.sql).all();
  72229. } else {
  72230. sqlite.prepare(query.sql).run();
  72231. }
  72232. results.push(result);
  72233. }
  72234. });
  72235. try {
  72236. tx(queries);
  72237. } catch (error2) {
  72238. results.push(error2);
  72239. }
  72240. return results;
  72241. };
  72242. return { ...db, packageName: "better-sqlite3", proxy, transactionProxy, migrate: migrateFn };
  72243. }
  72244. console.log(
  72245. "Please install either 'better-sqlite3' or '@libsql/client' for Drizzle Kit to connect to SQLite databases"
  72246. );
  72247. process.exit(1);
  72248. };
  72249. connectToLibSQL = async (credentials2) => {
  72250. if (await checkPackage("@libsql/client")) {
  72251. const { createClient } = await import("@libsql/client");
  72252. const { drizzle } = await import("drizzle-orm/libsql");
  72253. const { migrate } = await import("drizzle-orm/libsql/migrator");
  72254. const client = createClient({
  72255. url: normaliseSQLiteUrl(credentials2.url, "libsql"),
  72256. authToken: credentials2.authToken
  72257. });
  72258. const drzl = drizzle(client);
  72259. const migrateFn = async (config) => {
  72260. return migrate(drzl, config);
  72261. };
  72262. const db = {
  72263. query: async (sql, params) => {
  72264. const res = await client.execute({ sql, args: params || [] });
  72265. return res.rows;
  72266. },
  72267. run: async (query) => {
  72268. await client.execute(query);
  72269. },
  72270. batchWithPragma: async (queries) => {
  72271. await client.migrate(queries);
  72272. }
  72273. };
  72274. const proxy = async (params) => {
  72275. const preparedParams = prepareSqliteParams(params.params || []);
  72276. const result = await client.execute({
  72277. sql: params.sql,
  72278. args: preparedParams
  72279. });
  72280. if (params.mode === "array") {
  72281. return result.rows.map((row) => Object.values(row));
  72282. } else {
  72283. return result.rows;
  72284. }
  72285. };
  72286. const transactionProxy = async (queries) => {
  72287. const results = [];
  72288. let transaction = null;
  72289. try {
  72290. transaction = await client.transaction();
  72291. for (const query of queries) {
  72292. const result = await transaction.execute(query.sql);
  72293. results.push(result.rows);
  72294. }
  72295. await transaction.commit();
  72296. } catch (error2) {
  72297. results.push(error2);
  72298. await transaction?.rollback();
  72299. } finally {
  72300. transaction?.close();
  72301. }
  72302. return results;
  72303. };
  72304. return { ...db, packageName: "@libsql/client", proxy, transactionProxy, migrate: migrateFn };
  72305. }
  72306. console.log(
  72307. "Please install '@libsql/client' for Drizzle Kit to connect to LibSQL databases"
  72308. );
  72309. process.exit(1);
  72310. };
  72311. }
  72312. });
  72313. // src/serializer/studio.ts
  72314. var studio_exports = {};
  72315. __export(studio_exports, {
  72316. drizzleForLibSQL: () => drizzleForLibSQL,
  72317. drizzleForMySQL: () => drizzleForMySQL,
  72318. drizzleForPostgres: () => drizzleForPostgres,
  72319. drizzleForSQLite: () => drizzleForSQLite,
  72320. drizzleForSingleStore: () => drizzleForSingleStore,
  72321. extractRelations: () => extractRelations,
  72322. prepareMySqlSchema: () => prepareMySqlSchema,
  72323. preparePgSchema: () => preparePgSchema,
  72324. prepareSQLiteSchema: () => prepareSQLiteSchema,
  72325. prepareServer: () => prepareServer,
  72326. prepareSingleStoreSchema: () => prepareSingleStoreSchema
  72327. });
  72328. import { createHash as createHash3 } from "crypto";
  72329. import { is as is6 } from "drizzle-orm";
  72330. import { getTableConfig as mysqlTableConfig, MySqlTable } from "drizzle-orm/mysql-core";
  72331. import { getTableConfig as pgTableConfig, PgTable as PgTable2 } from "drizzle-orm/pg-core";
  72332. import {
  72333. createTableRelationsHelpers,
  72334. extractTablesRelationalConfig,
  72335. Many,
  72336. normalizeRelation,
  72337. One,
  72338. Relations as Relations2
  72339. } from "drizzle-orm/relations";
  72340. import { getTableConfig as singlestoreTableConfig, SingleStoreTable } from "drizzle-orm/singlestore-core";
  72341. import { getTableConfig as sqliteTableConfig, SQLiteTable } from "drizzle-orm/sqlite-core";
  72342. import fs4 from "fs";
  72343. import { createServer } from "https";
  72344. var preparePgSchema, prepareMySqlSchema, prepareSQLiteSchema, prepareSingleStoreSchema, getCustomDefaults, drizzleForPostgres, drizzleForMySQL, drizzleForSQLite, drizzleForLibSQL, drizzleForSingleStore, extractRelations, init, proxySchema, transactionProxySchema, defaultsSchema, schema5, jsonStringify, prepareServer;
  72345. var init_studio2 = __esm({
  72346. "src/serializer/studio.ts"() {
  72347. "use strict";
  72348. init_dist();
  72349. init_esm2();
  72350. init_dist2();
  72351. init_compress2();
  72352. init_cors();
  72353. init_global();
  72354. init_esm();
  72355. init_utils3();
  72356. init_serializer();
  72357. init_utils2();
  72358. preparePgSchema = async (path3) => {
  72359. const imports = prepareFilenames(path3);
  72360. const pgSchema2 = {};
  72361. const relations = {};
  72362. const files = imports.map((it, index6) => ({
  72363. // get the file name from the path
  72364. name: it.split("/").pop() || `schema${index6}.ts`,
  72365. content: fs4.readFileSync(it, "utf-8")
  72366. }));
  72367. await safeRegister(async () => {
  72368. for (let i6 = 0; i6 < imports.length; i6++) {
  72369. const it = imports[i6];
  72370. const i0 = __require(`${it}`);
  72371. const i0values = Object.entries(i0);
  72372. i0values.forEach(([k5, t6]) => {
  72373. if (is6(t6, PgTable2)) {
  72374. const schema6 = pgTableConfig(t6).schema || "public";
  72375. pgSchema2[schema6] = pgSchema2[schema6] || {};
  72376. pgSchema2[schema6][k5] = t6;
  72377. }
  72378. if (is6(t6, Relations2)) {
  72379. relations[k5] = t6;
  72380. }
  72381. });
  72382. }
  72383. });
  72384. return { schema: pgSchema2, relations, files };
  72385. };
  72386. prepareMySqlSchema = async (path3) => {
  72387. const imports = prepareFilenames(path3);
  72388. const mysqlSchema3 = {
  72389. public: {}
  72390. };
  72391. const relations = {};
  72392. const files = imports.map((it, index6) => ({
  72393. // get the file name from the path
  72394. name: it.split("/").pop() || `schema${index6}.ts`,
  72395. content: fs4.readFileSync(it, "utf-8")
  72396. }));
  72397. await safeRegister(async () => {
  72398. for (let i6 = 0; i6 < imports.length; i6++) {
  72399. const it = imports[i6];
  72400. const i0 = __require(`${it}`);
  72401. const i0values = Object.entries(i0);
  72402. i0values.forEach(([k5, t6]) => {
  72403. if (is6(t6, MySqlTable)) {
  72404. const schema6 = mysqlTableConfig(t6).schema || "public";
  72405. mysqlSchema3[schema6][k5] = t6;
  72406. }
  72407. if (is6(t6, Relations2)) {
  72408. relations[k5] = t6;
  72409. }
  72410. });
  72411. }
  72412. });
  72413. return { schema: mysqlSchema3, relations, files };
  72414. };
  72415. prepareSQLiteSchema = async (path3) => {
  72416. const imports = prepareFilenames(path3);
  72417. const sqliteSchema2 = {
  72418. public: {}
  72419. };
  72420. const relations = {};
  72421. const files = imports.map((it, index6) => ({
  72422. // get the file name from the path
  72423. name: it.split("/").pop() || `schema${index6}.ts`,
  72424. content: fs4.readFileSync(it, "utf-8")
  72425. }));
  72426. await safeRegister(async () => {
  72427. for (let i6 = 0; i6 < imports.length; i6++) {
  72428. const it = imports[i6];
  72429. const i0 = __require(`${it}`);
  72430. const i0values = Object.entries(i0);
  72431. i0values.forEach(([k5, t6]) => {
  72432. if (is6(t6, SQLiteTable)) {
  72433. const schema6 = "public";
  72434. sqliteSchema2[schema6][k5] = t6;
  72435. }
  72436. if (is6(t6, Relations2)) {
  72437. relations[k5] = t6;
  72438. }
  72439. });
  72440. }
  72441. });
  72442. return { schema: sqliteSchema2, relations, files };
  72443. };
  72444. prepareSingleStoreSchema = async (path3) => {
  72445. const imports = prepareFilenames(path3);
  72446. const singlestoreSchema2 = {
  72447. public: {}
  72448. };
  72449. const relations = {};
  72450. const files = imports.map((it, index6) => ({
  72451. // get the file name from the path
  72452. name: it.split("/").pop() || `schema${index6}.ts`,
  72453. content: fs4.readFileSync(it, "utf-8")
  72454. }));
  72455. await safeRegister(async () => {
  72456. for (let i6 = 0; i6 < imports.length; i6++) {
  72457. const it = imports[i6];
  72458. const i0 = __require(`${it}`);
  72459. const i0values = Object.entries(i0);
  72460. i0values.forEach(([k5, t6]) => {
  72461. if (is6(t6, SingleStoreTable)) {
  72462. const schema6 = singlestoreTableConfig(t6).schema || "public";
  72463. singlestoreSchema2[schema6][k5] = t6;
  72464. }
  72465. if (is6(t6, Relations2)) {
  72466. relations[k5] = t6;
  72467. }
  72468. });
  72469. }
  72470. });
  72471. return { schema: singlestoreSchema2, relations, files };
  72472. };
  72473. getCustomDefaults = (schema6, casing2) => {
  72474. const customDefaults = [];
  72475. Object.entries(schema6).map(([schema7, tables]) => {
  72476. Object.entries(tables).map(([, table6]) => {
  72477. let tableConfig;
  72478. if (is6(table6, PgTable2)) {
  72479. tableConfig = pgTableConfig(table6);
  72480. } else if (is6(table6, MySqlTable)) {
  72481. tableConfig = mysqlTableConfig(table6);
  72482. } else if (is6(table6, SQLiteTable)) {
  72483. tableConfig = sqliteTableConfig(table6);
  72484. } else {
  72485. tableConfig = singlestoreTableConfig(table6);
  72486. }
  72487. tableConfig.columns.map((column6) => {
  72488. if (column6.defaultFn) {
  72489. customDefaults.push({
  72490. schema: schema7,
  72491. table: tableConfig.name,
  72492. column: getColumnCasing(column6, casing2),
  72493. func: column6.defaultFn
  72494. });
  72495. }
  72496. });
  72497. });
  72498. });
  72499. return customDefaults;
  72500. };
  72501. drizzleForPostgres = async (credentials2, pgSchema2, relations, schemaFiles, casing2) => {
  72502. const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  72503. const db = await preparePostgresDB2(credentials2);
  72504. const customDefaults = getCustomDefaults(pgSchema2, casing2);
  72505. let dbUrl;
  72506. if ("driver" in credentials2) {
  72507. const { driver: driver2 } = credentials2;
  72508. if (driver2 === "aws-data-api") {
  72509. dbUrl = `aws-data-api://${credentials2.database}/${credentials2.secretArn}/${credentials2.resourceArn}`;
  72510. } else if (driver2 === "pglite") {
  72511. dbUrl = "client" in credentials2 ? credentials2.client.dataDir || "pglite://custom-client" : credentials2.url;
  72512. } else {
  72513. assertUnreachable(driver2);
  72514. }
  72515. } else if ("url" in credentials2) {
  72516. dbUrl = credentials2.url;
  72517. } else {
  72518. dbUrl = `postgresql://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
  72519. }
  72520. const dbHash = createHash3("sha256").update(dbUrl).digest("hex");
  72521. return {
  72522. dbHash,
  72523. dialect: "postgresql",
  72524. driver: "driver" in credentials2 ? credentials2.driver : void 0,
  72525. packageName: db.packageName,
  72526. proxy: db.proxy,
  72527. transactionProxy: db.transactionProxy,
  72528. customDefaults,
  72529. schema: pgSchema2,
  72530. relations,
  72531. schemaFiles,
  72532. casing: casing2
  72533. };
  72534. };
  72535. drizzleForMySQL = async (credentials2, mysqlSchema3, relations, schemaFiles, casing2) => {
  72536. const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  72537. const { proxy, transactionProxy, database, packageName } = await connectToMySQL2(credentials2);
  72538. const customDefaults = getCustomDefaults(mysqlSchema3, casing2);
  72539. let dbUrl;
  72540. if ("url" in credentials2) {
  72541. dbUrl = credentials2.url;
  72542. } else {
  72543. dbUrl = `mysql://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
  72544. }
  72545. const dbHash = createHash3("sha256").update(dbUrl).digest("hex");
  72546. return {
  72547. dbHash,
  72548. dialect: "mysql",
  72549. packageName,
  72550. databaseName: database,
  72551. proxy,
  72552. transactionProxy,
  72553. customDefaults,
  72554. schema: mysqlSchema3,
  72555. relations,
  72556. schemaFiles,
  72557. casing: casing2
  72558. };
  72559. };
  72560. drizzleForSQLite = async (credentials2, sqliteSchema2, relations, schemaFiles, casing2) => {
  72561. const customDefaults = getCustomDefaults(sqliteSchema2, casing2);
  72562. if ("driver" in credentials2 && credentials2.driver === "d1") {
  72563. const { connectToD1: connectToD12 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  72564. const sqliteDB2 = await connectToD12(credentials2.binding);
  72565. const dbUrl2 = "d1://binding";
  72566. const dbHash2 = createHash3("sha256").update(dbUrl2).digest("hex");
  72567. return {
  72568. dbHash: dbHash2,
  72569. dialect: "sqlite",
  72570. driver: "d1",
  72571. packageName: "d1",
  72572. proxy: sqliteDB2.proxy,
  72573. transactionProxy: sqliteDB2.transactionProxy,
  72574. customDefaults,
  72575. schema: sqliteSchema2,
  72576. relations,
  72577. schemaFiles,
  72578. casing: casing2
  72579. };
  72580. }
  72581. const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  72582. const sqliteDB = await connectToSQLite2(credentials2);
  72583. let dbUrl;
  72584. if ("driver" in credentials2) {
  72585. const { driver: driver2 } = credentials2;
  72586. if (driver2 === "d1-http") {
  72587. dbUrl = `d1-http://${credentials2.accountId}/${credentials2.databaseId}/${credentials2.token}`;
  72588. } else {
  72589. assertUnreachable(driver2);
  72590. }
  72591. } else {
  72592. dbUrl = credentials2.url;
  72593. }
  72594. const dbHash = createHash3("sha256").update(dbUrl).digest("hex");
  72595. return {
  72596. dbHash,
  72597. dialect: "sqlite",
  72598. driver: "driver" in credentials2 ? credentials2.driver : void 0,
  72599. packageName: sqliteDB.packageName,
  72600. proxy: sqliteDB.proxy,
  72601. transactionProxy: sqliteDB.transactionProxy,
  72602. customDefaults,
  72603. schema: sqliteSchema2,
  72604. relations,
  72605. schemaFiles,
  72606. casing: casing2
  72607. };
  72608. };
  72609. drizzleForLibSQL = async (credentials2, sqliteSchema2, relations, schemaFiles, casing2) => {
  72610. const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  72611. const sqliteDB = await connectToLibSQL2(credentials2);
  72612. const customDefaults = getCustomDefaults(sqliteSchema2, casing2);
  72613. let dbUrl = `turso://${credentials2.url}/${credentials2.authToken}`;
  72614. const dbHash = createHash3("sha256").update(dbUrl).digest("hex");
  72615. return {
  72616. dbHash,
  72617. dialect: "sqlite",
  72618. driver: void 0,
  72619. packageName: sqliteDB.packageName,
  72620. proxy: sqliteDB.proxy,
  72621. transactionProxy: sqliteDB.transactionProxy,
  72622. customDefaults,
  72623. schema: sqliteSchema2,
  72624. relations,
  72625. schemaFiles,
  72626. casing: casing2
  72627. };
  72628. };
  72629. drizzleForSingleStore = async (credentials2, singlestoreSchema2, relations, schemaFiles, casing2) => {
  72630. const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  72631. const { proxy, transactionProxy, database, packageName } = await connectToSingleStore2(credentials2);
  72632. const customDefaults = getCustomDefaults(singlestoreSchema2, casing2);
  72633. let dbUrl;
  72634. if ("url" in credentials2) {
  72635. dbUrl = credentials2.url;
  72636. } else {
  72637. dbUrl = `singlestore://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
  72638. }
  72639. const dbHash = createHash3("sha256").update(dbUrl).digest("hex");
  72640. return {
  72641. dbHash,
  72642. dialect: "singlestore",
  72643. databaseName: database,
  72644. packageName,
  72645. proxy,
  72646. transactionProxy,
  72647. customDefaults,
  72648. schema: singlestoreSchema2,
  72649. relations,
  72650. schemaFiles,
  72651. casing: casing2
  72652. };
  72653. };
  72654. extractRelations = (tablesConfig, casing2) => {
  72655. const relations = Object.values(tablesConfig.tables).map(
  72656. (it) => Object.entries(it.relations).map(([name, relation]) => {
  72657. try {
  72658. const normalized = normalizeRelation(
  72659. tablesConfig.tables,
  72660. tablesConfig.tableNamesMap,
  72661. relation
  72662. );
  72663. const rel = relation;
  72664. const refTableName = rel.referencedTableName;
  72665. const refTable = rel.referencedTable;
  72666. const fields = normalized.fields.map((it2) => getColumnCasing(it2, casing2)).flat();
  72667. const refColumns = normalized.references.map((it2) => getColumnCasing(it2, casing2)).flat();
  72668. let refSchema;
  72669. if (is6(refTable, PgTable2)) {
  72670. refSchema = pgTableConfig(refTable).schema;
  72671. } else if (is6(refTable, MySqlTable)) {
  72672. refSchema = mysqlTableConfig(refTable).schema;
  72673. } else if (is6(refTable, SQLiteTable)) {
  72674. refSchema = void 0;
  72675. } else if (is6(refTable, SingleStoreTable)) {
  72676. refSchema = singlestoreTableConfig(refTable).schema;
  72677. } else {
  72678. throw new Error("unsupported dialect");
  72679. }
  72680. let type;
  72681. if (is6(rel, One)) {
  72682. type = "one";
  72683. } else if (is6(rel, Many)) {
  72684. type = "many";
  72685. } else {
  72686. throw new Error("unsupported relation type");
  72687. }
  72688. return {
  72689. name,
  72690. type,
  72691. table: it.dbName,
  72692. schema: it.schema || "public",
  72693. columns: fields,
  72694. refTable: refTableName,
  72695. refSchema: refSchema || "public",
  72696. refColumns
  72697. };
  72698. } catch {
  72699. throw new Error(
  72700. `Invalid relation "${relation.fieldName}" for table "${it.schema ? `${it.schema}.${it.dbName}` : it.dbName}"`
  72701. );
  72702. }
  72703. })
  72704. ).flat();
  72705. return relations;
  72706. };
  72707. init = external_exports.object({
  72708. type: external_exports.literal("init")
  72709. });
  72710. proxySchema = external_exports.object({
  72711. type: external_exports.literal("proxy"),
  72712. data: external_exports.object({
  72713. sql: external_exports.string(),
  72714. params: external_exports.array(external_exports.any()).optional(),
  72715. typings: external_exports.string().array().optional(),
  72716. mode: external_exports.enum(["array", "object"]).default("object"),
  72717. method: external_exports.union([
  72718. external_exports.literal("values"),
  72719. external_exports.literal("get"),
  72720. external_exports.literal("all"),
  72721. external_exports.literal("run"),
  72722. external_exports.literal("execute")
  72723. ])
  72724. })
  72725. });
  72726. transactionProxySchema = external_exports.object({
  72727. type: external_exports.literal("tproxy"),
  72728. data: external_exports.object({
  72729. sql: external_exports.string(),
  72730. method: external_exports.union([
  72731. external_exports.literal("values"),
  72732. external_exports.literal("get"),
  72733. external_exports.literal("all"),
  72734. external_exports.literal("run"),
  72735. external_exports.literal("execute")
  72736. ]).optional()
  72737. }).array()
  72738. });
  72739. defaultsSchema = external_exports.object({
  72740. type: external_exports.literal("defaults"),
  72741. data: external_exports.array(
  72742. external_exports.object({
  72743. schema: external_exports.string(),
  72744. table: external_exports.string(),
  72745. column: external_exports.string()
  72746. })
  72747. ).min(1)
  72748. });
  72749. schema5 = external_exports.union([
  72750. init,
  72751. proxySchema,
  72752. transactionProxySchema,
  72753. defaultsSchema
  72754. ]);
  72755. jsonStringify = (data) => {
  72756. return JSON.stringify(data, (_key, value) => {
  72757. if (value instanceof Error) {
  72758. return {
  72759. error: value.message
  72760. };
  72761. }
  72762. if (typeof value === "bigint") {
  72763. return value.toString();
  72764. }
  72765. if (value && typeof value === "object" && "type" in value && "data" in value && value.type === "Buffer" || value instanceof ArrayBuffer || value instanceof Buffer) {
  72766. return Buffer.from(value).toString("base64");
  72767. }
  72768. return value;
  72769. });
  72770. };
  72771. prepareServer = async ({
  72772. dialect: dialect6,
  72773. driver: driver2,
  72774. packageName,
  72775. databaseName,
  72776. proxy,
  72777. transactionProxy,
  72778. customDefaults,
  72779. schema: drizzleSchema,
  72780. relations,
  72781. dbHash,
  72782. casing: casing2,
  72783. schemaFiles
  72784. }, app) => {
  72785. app = app !== void 0 ? app : new Hono2();
  72786. app.use(compress());
  72787. app.use(async (ctx, next) => {
  72788. await next();
  72789. ctx.header("Access-Control-Allow-Private-Network", "true");
  72790. });
  72791. app.use(cors());
  72792. app.onError((err2, ctx) => {
  72793. console.error(err2);
  72794. return ctx.json({
  72795. status: "error",
  72796. error: err2.message
  72797. });
  72798. });
  72799. const relationalSchema = {
  72800. ...Object.fromEntries(
  72801. Object.entries(drizzleSchema).map(([schemaName, schema6]) => {
  72802. const mappedTableEntries = Object.entries(schema6).map(
  72803. ([tableName, table6]) => {
  72804. return [`__${schemaName}__.${tableName}`, table6];
  72805. }
  72806. );
  72807. return mappedTableEntries;
  72808. }).flat()
  72809. ),
  72810. ...relations
  72811. };
  72812. const relationsConfig = extractTablesRelationalConfig(
  72813. relationalSchema,
  72814. createTableRelationsHelpers
  72815. );
  72816. app.post("/", zValidator("json", schema5), async (c5) => {
  72817. const body = c5.req.valid("json");
  72818. const { type } = body;
  72819. if (type === "init") {
  72820. const preparedDefaults = customDefaults.map((d5) => ({
  72821. schema: d5.schema,
  72822. table: d5.table,
  72823. column: d5.column
  72824. }));
  72825. let relations2 = [];
  72826. try {
  72827. relations2 = extractRelations(relationsConfig, casing2);
  72828. } catch (error2) {
  72829. console.warn(
  72830. "Failed to extract relations. This is likely due to ambiguous or misconfigured relations."
  72831. );
  72832. console.warn(
  72833. "Please check your schema and ensure that all relations are correctly defined."
  72834. );
  72835. console.warn(
  72836. "See: https://orm.drizzle.team/docs/relations#disambiguating-relations"
  72837. );
  72838. console.warn("Error message:", error2.message);
  72839. }
  72840. return c5.json({
  72841. version: "6.2",
  72842. dialect: dialect6,
  72843. driver: driver2,
  72844. packageName,
  72845. schemaFiles,
  72846. customDefaults: preparedDefaults,
  72847. relations: relations2,
  72848. dbHash,
  72849. databaseName
  72850. });
  72851. }
  72852. if (type === "proxy") {
  72853. const result = await proxy({
  72854. ...body.data,
  72855. params: body.data.params || []
  72856. });
  72857. return c5.json(JSON.parse(jsonStringify(result)));
  72858. }
  72859. if (type === "tproxy") {
  72860. const result = await transactionProxy(body.data);
  72861. return c5.json(JSON.parse(jsonStringify(result)));
  72862. }
  72863. if (type === "defaults") {
  72864. const columns = body.data;
  72865. const result = columns.map((column6) => {
  72866. const found = customDefaults.find((d5) => {
  72867. return d5.schema === column6.schema && d5.table === column6.table && d5.column === column6.column;
  72868. });
  72869. if (!found) {
  72870. throw new Error(
  72871. `Custom default not found for ${column6.schema}.${column6.table}.${column6.column}`
  72872. );
  72873. }
  72874. const value = found.func();
  72875. return {
  72876. ...column6,
  72877. value
  72878. };
  72879. });
  72880. return c5.json(JSON.parse(jsonStringify(result)));
  72881. }
  72882. throw new Error(`Unknown type: ${type}`);
  72883. });
  72884. return {
  72885. start: (params) => {
  72886. serve(
  72887. {
  72888. fetch: app.fetch,
  72889. createServer: params.key ? createServer : void 0,
  72890. hostname: params.host,
  72891. port: params.port,
  72892. serverOptions: {
  72893. key: params.key,
  72894. cert: params.cert
  72895. }
  72896. },
  72897. () => params.cb(null, `${params.host}:${params.port}`)
  72898. );
  72899. }
  72900. };
  72901. };
  72902. }
  72903. });
  72904. // src/serializer/sqliteImports.ts
  72905. var sqliteImports_exports = {};
  72906. __export(sqliteImports_exports, {
  72907. prepareFromExports: () => prepareFromExports2,
  72908. prepareFromSqliteImports: () => prepareFromSqliteImports
  72909. });
  72910. import { is as is7 } from "drizzle-orm";
  72911. import { SQLiteTable as SQLiteTable2, SQLiteView as SQLiteView3 } from "drizzle-orm/sqlite-core";
  72912. var prepareFromExports2, prepareFromSqliteImports;
  72913. var init_sqliteImports = __esm({
  72914. "src/serializer/sqliteImports.ts"() {
  72915. "use strict";
  72916. init_utils3();
  72917. prepareFromExports2 = (exports) => {
  72918. const tables = [];
  72919. const views = [];
  72920. const i0values = Object.values(exports);
  72921. i0values.forEach((t6) => {
  72922. if (is7(t6, SQLiteTable2)) {
  72923. tables.push(t6);
  72924. }
  72925. if (is7(t6, SQLiteView3)) {
  72926. views.push(t6);
  72927. }
  72928. });
  72929. return { tables, views };
  72930. };
  72931. prepareFromSqliteImports = async (imports) => {
  72932. const tables = [];
  72933. const views = [];
  72934. await safeRegister(async () => {
  72935. for (let i6 = 0; i6 < imports.length; i6++) {
  72936. const it = imports[i6];
  72937. const i0 = __require(`${it}`);
  72938. const prepared = prepareFromExports2(i0);
  72939. tables.push(...prepared.tables);
  72940. views.push(...prepared.views);
  72941. }
  72942. });
  72943. return { tables: Array.from(new Set(tables)), views };
  72944. };
  72945. }
  72946. });
  72947. // src/serializer/mysqlImports.ts
  72948. var mysqlImports_exports = {};
  72949. __export(mysqlImports_exports, {
  72950. prepareFromExports: () => prepareFromExports3,
  72951. prepareFromMySqlImports: () => prepareFromMySqlImports
  72952. });
  72953. import { is as is8 } from "drizzle-orm";
  72954. import { MySqlTable as MySqlTable2, MySqlView as MySqlView3 } from "drizzle-orm/mysql-core";
  72955. var prepareFromExports3, prepareFromMySqlImports;
  72956. var init_mysqlImports = __esm({
  72957. "src/serializer/mysqlImports.ts"() {
  72958. "use strict";
  72959. init_utils3();
  72960. prepareFromExports3 = (exports) => {
  72961. const tables = [];
  72962. const views = [];
  72963. const i0values = Object.values(exports);
  72964. i0values.forEach((t6) => {
  72965. if (is8(t6, MySqlTable2)) {
  72966. tables.push(t6);
  72967. }
  72968. if (is8(t6, MySqlView3)) {
  72969. views.push(t6);
  72970. }
  72971. });
  72972. return { tables, views };
  72973. };
  72974. prepareFromMySqlImports = async (imports) => {
  72975. const tables = [];
  72976. const views = [];
  72977. await safeRegister(async () => {
  72978. for (let i6 = 0; i6 < imports.length; i6++) {
  72979. const it = imports[i6];
  72980. const i0 = __require(`${it}`);
  72981. const prepared = prepareFromExports3(i0);
  72982. tables.push(...prepared.tables);
  72983. views.push(...prepared.views);
  72984. }
  72985. });
  72986. return { tables: Array.from(new Set(tables)), views };
  72987. };
  72988. }
  72989. });
  72990. // src/cli/commands/mysqlPushUtils.ts
  72991. var mysqlPushUtils_exports = {};
  72992. __export(mysqlPushUtils_exports, {
  72993. filterStatements: () => filterStatements,
  72994. logSuggestionsAndReturn: () => logSuggestionsAndReturn2
  72995. });
  72996. var import_hanji8, filterStatements, logSuggestionsAndReturn2;
  72997. var init_mysqlPushUtils = __esm({
  72998. "src/cli/commands/mysqlPushUtils.ts"() {
  72999. "use strict";
  73000. init_source();
  73001. import_hanji8 = __toESM(require_hanji());
  73002. init_mysqlSchema();
  73003. init_selector_ui();
  73004. init_outputs();
  73005. filterStatements = (statements, currentSchema, prevSchema) => {
  73006. return statements.filter((statement) => {
  73007. if (statement.type === "alter_table_alter_column_set_type") {
  73008. if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
  73009. return false;
  73010. }
  73011. if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
  73012. return false;
  73013. }
  73014. if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
  73015. return false;
  73016. }
  73017. } else if (statement.type === "alter_table_alter_column_set_default") {
  73018. if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
  73019. return false;
  73020. }
  73021. if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
  73022. return false;
  73023. }
  73024. } else if (statement.type === "delete_unique_constraint") {
  73025. const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
  73026. if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
  73027. return false;
  73028. }
  73029. } else if (statement.type === "alter_table_alter_column_drop_notnull") {
  73030. const serialStatement = statements.find(
  73031. (it) => it.type === "alter_table_alter_column_set_type"
  73032. );
  73033. if (serialStatement?.oldDataType.startsWith("bigint unsigned") && serialStatement?.newDataType.startsWith("serial") && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
  73034. return false;
  73035. }
  73036. if (statement.newDataType === "serial" && !statement.columnNotNull) {
  73037. return false;
  73038. }
  73039. if (statement.columnAutoIncrement) {
  73040. return false;
  73041. }
  73042. }
  73043. return true;
  73044. });
  73045. };
  73046. logSuggestionsAndReturn2 = async (db, statements, json2) => {
  73047. let shouldAskForApprove = false;
  73048. const statementsToExecute = [];
  73049. const infoToPrint = [];
  73050. const tablesToRemove = [];
  73051. const columnsToRemove = [];
  73052. const schemasToRemove = [];
  73053. const tablesToTruncate = [];
  73054. for (const statement of statements) {
  73055. if (statement.type === "drop_table") {
  73056. const res = await db.query(
  73057. `select count(*) as count from \`${statement.tableName}\``
  73058. );
  73059. const count = Number(res[0].count);
  73060. if (count > 0) {
  73061. infoToPrint.push(
  73062. `\xB7 You're about to delete ${source_default.underline(
  73063. statement.tableName
  73064. )} table with ${count} items`
  73065. );
  73066. tablesToRemove.push(statement.tableName);
  73067. shouldAskForApprove = true;
  73068. }
  73069. } else if (statement.type === "alter_table_drop_column") {
  73070. const res = await db.query(
  73071. `select count(*) as count from \`${statement.tableName}\``
  73072. );
  73073. const count = Number(res[0].count);
  73074. if (count > 0) {
  73075. infoToPrint.push(
  73076. `\xB7 You're about to delete ${source_default.underline(
  73077. statement.columnName
  73078. )} column in ${statement.tableName} table with ${count} items`
  73079. );
  73080. columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
  73081. shouldAskForApprove = true;
  73082. }
  73083. } else if (statement.type === "drop_schema") {
  73084. const res = await db.query(
  73085. `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
  73086. );
  73087. const count = Number(res[0].count);
  73088. if (count > 0) {
  73089. infoToPrint.push(
  73090. `\xB7 You're about to delete ${source_default.underline(
  73091. statement.name
  73092. )} schema with ${count} tables`
  73093. );
  73094. schemasToRemove.push(statement.name);
  73095. shouldAskForApprove = true;
  73096. }
  73097. } else if (statement.type === "alter_table_alter_column_set_type") {
  73098. const res = await db.query(
  73099. `select count(*) as count from \`${statement.tableName}\``
  73100. );
  73101. const count = Number(res[0].count);
  73102. if (count > 0) {
  73103. infoToPrint.push(
  73104. `\xB7 You're about to change ${source_default.underline(
  73105. statement.columnName
  73106. )} column type from ${source_default.underline(
  73107. statement.oldDataType
  73108. )} to ${source_default.underline(statement.newDataType)} with ${count} items`
  73109. );
  73110. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73111. tablesToTruncate.push(statement.tableName);
  73112. shouldAskForApprove = true;
  73113. }
  73114. } else if (statement.type === "alter_table_alter_column_drop_default") {
  73115. if (statement.columnNotNull) {
  73116. const res = await db.query(
  73117. `select count(*) as count from \`${statement.tableName}\``
  73118. );
  73119. const count = Number(res[0].count);
  73120. if (count > 0) {
  73121. infoToPrint.push(
  73122. `\xB7 You're about to remove default value from ${source_default.underline(
  73123. statement.columnName
  73124. )} not-null column with ${count} items`
  73125. );
  73126. tablesToTruncate.push(statement.tableName);
  73127. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73128. shouldAskForApprove = true;
  73129. }
  73130. }
  73131. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  73132. if (typeof statement.columnDefault === "undefined") {
  73133. const res = await db.query(
  73134. `select count(*) as count from \`${statement.tableName}\``
  73135. );
  73136. const count = Number(res[0].count);
  73137. if (count > 0) {
  73138. infoToPrint.push(
  73139. `\xB7 You're about to set not-null constraint to ${source_default.underline(
  73140. statement.columnName
  73141. )} column without default, which contains ${count} items`
  73142. );
  73143. tablesToTruncate.push(statement.tableName);
  73144. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73145. shouldAskForApprove = true;
  73146. }
  73147. }
  73148. } else if (statement.type === "alter_table_alter_column_drop_pk") {
  73149. const res = await db.query(
  73150. `select count(*) as count from \`${statement.tableName}\``
  73151. );
  73152. if (Object.values(json2.tables[statement.tableName].columns).filter(
  73153. (column6) => column6.autoincrement
  73154. ).length > 0) {
  73155. console.log(
  73156. `${withStyle.errorWarning(
  73157. `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
  73158. )}`
  73159. );
  73160. process.exit(1);
  73161. }
  73162. const count = Number(res[0].count);
  73163. if (count > 0) {
  73164. infoToPrint.push(
  73165. `\xB7 You're about to change ${source_default.underline(
  73166. statement.tableName
  73167. )} primary key. This statements may fail and you table may left without primary key`
  73168. );
  73169. tablesToTruncate.push(statement.tableName);
  73170. shouldAskForApprove = true;
  73171. }
  73172. } else if (statement.type === "delete_composite_pk") {
  73173. if (Object.values(json2.tables[statement.tableName].columns).filter(
  73174. (column6) => column6.autoincrement
  73175. ).length > 0) {
  73176. console.log(
  73177. `${withStyle.errorWarning(
  73178. `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
  73179. )}`
  73180. );
  73181. process.exit(1);
  73182. }
  73183. } else if (statement.type === "alter_table_add_column") {
  73184. if (statement.column.notNull && typeof statement.column.default === "undefined") {
  73185. const res = await db.query(
  73186. `select count(*) as count from \`${statement.tableName}\``
  73187. );
  73188. const count = Number(res[0].count);
  73189. if (count > 0) {
  73190. infoToPrint.push(
  73191. `\xB7 You're about to add not-null ${source_default.underline(
  73192. statement.column.name
  73193. )} column without default value, which contains ${count} items`
  73194. );
  73195. tablesToTruncate.push(statement.tableName);
  73196. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73197. shouldAskForApprove = true;
  73198. }
  73199. }
  73200. } else if (statement.type === "create_unique_constraint") {
  73201. const res = await db.query(
  73202. `select count(*) as count from \`${statement.tableName}\``
  73203. );
  73204. const count = Number(res[0].count);
  73205. if (count > 0) {
  73206. const unsquashedUnique = MySqlSquasher.unsquashUnique(statement.data);
  73207. console.log(
  73208. `\xB7 You're about to add ${source_default.underline(
  73209. unsquashedUnique.name
  73210. )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
  73211. statement.tableName
  73212. )} table?
  73213. `
  73214. );
  73215. const { status, data } = await (0, import_hanji8.render)(
  73216. new Select([
  73217. "No, add the constraint without truncating the table",
  73218. `Yes, truncate the table`
  73219. ])
  73220. );
  73221. if (data?.index === 1) {
  73222. tablesToTruncate.push(statement.tableName);
  73223. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73224. shouldAskForApprove = true;
  73225. }
  73226. }
  73227. }
  73228. }
  73229. return {
  73230. statementsToExecute,
  73231. shouldAskForApprove,
  73232. infoToPrint,
  73233. columnsToRemove: [...new Set(columnsToRemove)],
  73234. schemasToRemove: [...new Set(schemasToRemove)],
  73235. tablesToTruncate: [...new Set(tablesToTruncate)],
  73236. tablesToRemove: [...new Set(tablesToRemove)]
  73237. };
  73238. };
  73239. }
  73240. });
  73241. // src/cli/commands/mysqlIntrospect.ts
  73242. var mysqlIntrospect_exports = {};
  73243. __export(mysqlIntrospect_exports, {
  73244. mysqlPushIntrospect: () => mysqlPushIntrospect
  73245. });
  73246. var import_hanji9, mysqlPushIntrospect;
  73247. var init_mysqlIntrospect = __esm({
  73248. "src/cli/commands/mysqlIntrospect.ts"() {
  73249. "use strict";
  73250. import_hanji9 = __toESM(require_hanji());
  73251. init_mjs();
  73252. init_global();
  73253. init_mysqlSerializer();
  73254. init_views();
  73255. mysqlPushIntrospect = async (db, databaseName, filters) => {
  73256. const matchers = filters.map((it) => {
  73257. return new Minimatch(it);
  73258. });
  73259. const filter2 = (tableName) => {
  73260. if (matchers.length === 0) return true;
  73261. let flags = [];
  73262. for (let matcher of matchers) {
  73263. if (matcher.negate) {
  73264. if (!matcher.match(tableName)) {
  73265. flags.push(false);
  73266. }
  73267. }
  73268. if (matcher.match(tableName)) {
  73269. flags.push(true);
  73270. }
  73271. }
  73272. if (flags.length > 0) {
  73273. return flags.every(Boolean);
  73274. }
  73275. return false;
  73276. };
  73277. const progress = new ProgressView(
  73278. "Pulling schema from database...",
  73279. "Pulling schema from database..."
  73280. );
  73281. const res = await (0, import_hanji9.renderWithTask)(
  73282. progress,
  73283. fromDatabase3(db, databaseName, filter2)
  73284. );
  73285. const schema6 = { id: originUUID, prevId: "", ...res };
  73286. const { internal, ...schemaWithoutInternals } = schema6;
  73287. return { schema: schemaWithoutInternals };
  73288. };
  73289. }
  73290. });
  73291. // src/serializer/singlestoreImports.ts
  73292. var singlestoreImports_exports = {};
  73293. __export(singlestoreImports_exports, {
  73294. prepareFromExports: () => prepareFromExports4,
  73295. prepareFromSingleStoreImports: () => prepareFromSingleStoreImports
  73296. });
  73297. import { is as is9 } from "drizzle-orm";
  73298. import { SingleStoreTable as SingleStoreTable2 } from "drizzle-orm/singlestore-core";
  73299. var prepareFromExports4, prepareFromSingleStoreImports;
  73300. var init_singlestoreImports = __esm({
  73301. "src/serializer/singlestoreImports.ts"() {
  73302. "use strict";
  73303. init_utils3();
  73304. prepareFromExports4 = (exports) => {
  73305. const tables = [];
  73306. const i0values = Object.values(exports);
  73307. i0values.forEach((t6) => {
  73308. if (is9(t6, SingleStoreTable2)) {
  73309. tables.push(t6);
  73310. }
  73311. });
  73312. return {
  73313. tables
  73314. /* views */
  73315. };
  73316. };
  73317. prepareFromSingleStoreImports = async (imports) => {
  73318. const tables = [];
  73319. await safeRegister(async () => {
  73320. for (let i6 = 0; i6 < imports.length; i6++) {
  73321. const it = imports[i6];
  73322. const i0 = __require(`${it}`);
  73323. const prepared = prepareFromExports4(i0);
  73324. tables.push(...prepared.tables);
  73325. }
  73326. });
  73327. return {
  73328. tables: Array.from(new Set(tables))
  73329. /* , views */
  73330. };
  73331. };
  73332. }
  73333. });
  73334. // src/cli/commands/singlestorePushUtils.ts
  73335. var singlestorePushUtils_exports = {};
  73336. __export(singlestorePushUtils_exports, {
  73337. filterStatements: () => filterStatements2,
  73338. findColumnTypeAlternations: () => findColumnTypeAlternations,
  73339. logSuggestionsAndReturn: () => logSuggestionsAndReturn3
  73340. });
  73341. function findColumnTypeAlternations(columns1, columns2) {
  73342. const changes = [];
  73343. for (const key in columns1) {
  73344. if (columns1.hasOwnProperty(key) && columns2.hasOwnProperty(key)) {
  73345. const col1 = columns1[key];
  73346. const col2 = columns2[key];
  73347. if (col1.type !== col2.type) {
  73348. changes.push(col2.name);
  73349. }
  73350. }
  73351. }
  73352. return changes;
  73353. }
  73354. var import_hanji10, filterStatements2, logSuggestionsAndReturn3;
  73355. var init_singlestorePushUtils = __esm({
  73356. "src/cli/commands/singlestorePushUtils.ts"() {
  73357. "use strict";
  73358. init_source();
  73359. import_hanji10 = __toESM(require_hanji());
  73360. init_sqlgenerator();
  73361. init_singlestoreSchema();
  73362. init_utils();
  73363. init_selector_ui();
  73364. init_outputs();
  73365. filterStatements2 = (statements, currentSchema, prevSchema) => {
  73366. return statements.filter((statement) => {
  73367. if (statement.type === "alter_table_alter_column_set_type") {
  73368. if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
  73369. return false;
  73370. }
  73371. if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
  73372. return false;
  73373. }
  73374. if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
  73375. return false;
  73376. }
  73377. } else if (statement.type === "alter_table_alter_column_set_default") {
  73378. if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
  73379. return false;
  73380. }
  73381. if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
  73382. return false;
  73383. }
  73384. } else if (statement.type === "delete_unique_constraint") {
  73385. const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
  73386. if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
  73387. return false;
  73388. }
  73389. } else if (statement.type === "alter_table_alter_column_drop_notnull") {
  73390. const serialStatement = statements.find(
  73391. (it) => it.type === "alter_table_alter_column_set_type"
  73392. );
  73393. if (serialStatement?.oldDataType.startsWith("bigint unsigned") && serialStatement?.newDataType.startsWith("serial") && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
  73394. return false;
  73395. }
  73396. if (statement.newDataType === "serial" && !statement.columnNotNull) {
  73397. return false;
  73398. }
  73399. if (statement.columnAutoIncrement) {
  73400. return false;
  73401. }
  73402. }
  73403. return true;
  73404. });
  73405. };
  73406. logSuggestionsAndReturn3 = async (db, statements, json2, json1) => {
  73407. let shouldAskForApprove = false;
  73408. const statementsToExecute = [];
  73409. const infoToPrint = [];
  73410. const tablesToRemove = [];
  73411. const columnsToRemove = [];
  73412. const schemasToRemove = [];
  73413. const tablesToTruncate = [];
  73414. for (const statement of statements) {
  73415. if (statement.type === "drop_table") {
  73416. const res = await db.query(
  73417. `select count(*) as count from \`${statement.tableName}\``
  73418. );
  73419. const count = Number(res[0].count);
  73420. if (count > 0) {
  73421. infoToPrint.push(
  73422. `\xB7 You're about to delete ${source_default.underline(
  73423. statement.tableName
  73424. )} table with ${count} items`
  73425. );
  73426. tablesToRemove.push(statement.tableName);
  73427. shouldAskForApprove = true;
  73428. }
  73429. } else if (statement.type === "alter_table_drop_column") {
  73430. const res = await db.query(
  73431. `select count(*) as count from \`${statement.tableName}\``
  73432. );
  73433. const count = Number(res[0].count);
  73434. if (count > 0) {
  73435. infoToPrint.push(
  73436. `\xB7 You're about to delete ${source_default.underline(
  73437. statement.columnName
  73438. )} column in ${statement.tableName} table with ${count} items`
  73439. );
  73440. columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
  73441. shouldAskForApprove = true;
  73442. }
  73443. } else if (statement.type === "drop_schema") {
  73444. const res = await db.query(
  73445. `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
  73446. );
  73447. const count = Number(res[0].count);
  73448. if (count > 0) {
  73449. infoToPrint.push(
  73450. `\xB7 You're about to delete ${source_default.underline(
  73451. statement.name
  73452. )} schema with ${count} tables`
  73453. );
  73454. schemasToRemove.push(statement.name);
  73455. shouldAskForApprove = true;
  73456. }
  73457. } else if (statement.type === "alter_table_alter_column_set_type") {
  73458. const res = await db.query(
  73459. `select count(*) as count from \`${statement.tableName}\``
  73460. );
  73461. const count = Number(res[0].count);
  73462. if (count > 0) {
  73463. infoToPrint.push(
  73464. `\xB7 You're about to change ${source_default.underline(
  73465. statement.columnName
  73466. )} column type from ${source_default.underline(
  73467. statement.oldDataType
  73468. )} to ${source_default.underline(statement.newDataType)} with ${count} items`
  73469. );
  73470. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73471. tablesToTruncate.push(statement.tableName);
  73472. shouldAskForApprove = true;
  73473. }
  73474. } else if (statement.type === "alter_table_alter_column_drop_default") {
  73475. if (statement.columnNotNull) {
  73476. const res = await db.query(
  73477. `select count(*) as count from \`${statement.tableName}\``
  73478. );
  73479. const count = Number(res[0].count);
  73480. if (count > 0) {
  73481. infoToPrint.push(
  73482. `\xB7 You're about to remove default value from ${source_default.underline(
  73483. statement.columnName
  73484. )} not-null column with ${count} items`
  73485. );
  73486. tablesToTruncate.push(statement.tableName);
  73487. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73488. shouldAskForApprove = true;
  73489. }
  73490. }
  73491. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  73492. if (typeof statement.columnDefault === "undefined") {
  73493. const res = await db.query(
  73494. `select count(*) as count from \`${statement.tableName}\``
  73495. );
  73496. const count = Number(res[0].count);
  73497. if (count > 0) {
  73498. infoToPrint.push(
  73499. `\xB7 You're about to set not-null constraint to ${source_default.underline(
  73500. statement.columnName
  73501. )} column without default, which contains ${count} items`
  73502. );
  73503. tablesToTruncate.push(statement.tableName);
  73504. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73505. shouldAskForApprove = true;
  73506. }
  73507. }
  73508. } else if (statement.type === "alter_table_alter_column_drop_pk") {
  73509. const res = await db.query(
  73510. `select count(*) as count from \`${statement.tableName}\``
  73511. );
  73512. if (Object.values(json2.tables[statement.tableName].columns).filter(
  73513. (column6) => column6.autoincrement
  73514. ).length > 0) {
  73515. console.log(
  73516. `${withStyle.errorWarning(
  73517. `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
  73518. )}`
  73519. );
  73520. process.exit(1);
  73521. }
  73522. const count = Number(res[0].count);
  73523. if (count > 0) {
  73524. infoToPrint.push(
  73525. `\xB7 You're about to change ${source_default.underline(
  73526. statement.tableName
  73527. )} primary key. This statements may fail and you table may left without primary key`
  73528. );
  73529. tablesToTruncate.push(statement.tableName);
  73530. shouldAskForApprove = true;
  73531. }
  73532. } else if (statement.type === "delete_composite_pk") {
  73533. if (Object.values(json2.tables[statement.tableName].columns).filter(
  73534. (column6) => column6.autoincrement
  73535. ).length > 0) {
  73536. console.log(
  73537. `${withStyle.errorWarning(
  73538. `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
  73539. )}`
  73540. );
  73541. process.exit(1);
  73542. }
  73543. } else if (statement.type === "alter_table_add_column") {
  73544. if (statement.column.notNull && typeof statement.column.default === "undefined") {
  73545. const res = await db.query(
  73546. `select count(*) as count from \`${statement.tableName}\``
  73547. );
  73548. const count = Number(res[0].count);
  73549. if (count > 0) {
  73550. infoToPrint.push(
  73551. `\xB7 You're about to add not-null ${source_default.underline(
  73552. statement.column.name
  73553. )} column without default value, which contains ${count} items`
  73554. );
  73555. tablesToTruncate.push(statement.tableName);
  73556. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73557. shouldAskForApprove = true;
  73558. }
  73559. }
  73560. } else if (statement.type === "create_unique_constraint") {
  73561. const res = await db.query(
  73562. `select count(*) as count from \`${statement.tableName}\``
  73563. );
  73564. const count = Number(res[0].count);
  73565. if (count > 0) {
  73566. const unsquashedUnique = SingleStoreSquasher.unsquashUnique(statement.data);
  73567. console.log(
  73568. `\xB7 You're about to add ${source_default.underline(
  73569. unsquashedUnique.name
  73570. )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
  73571. statement.tableName
  73572. )} table?
  73573. `
  73574. );
  73575. const { status, data } = await (0, import_hanji10.render)(
  73576. new Select([
  73577. "No, add the constraint without truncating the table",
  73578. `Yes, truncate the table`
  73579. ])
  73580. );
  73581. if (data?.index === 1) {
  73582. tablesToTruncate.push(statement.tableName);
  73583. statementsToExecute.push(`truncate table ${statement.tableName};`);
  73584. shouldAskForApprove = true;
  73585. }
  73586. }
  73587. } else if (statement.type === "singlestore_recreate_table") {
  73588. const tableName = statement.tableName;
  73589. const prevColumns = json1.tables[tableName].columns;
  73590. const currentColumns = json2.tables[tableName].columns;
  73591. const { removedColumns, addedColumns } = findAddedAndRemoved(
  73592. Object.keys(prevColumns),
  73593. Object.keys(currentColumns)
  73594. );
  73595. if (removedColumns.length) {
  73596. for (const removedColumn of removedColumns) {
  73597. const res = await db.query(
  73598. `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
  73599. );
  73600. const count = Number(res[0].count);
  73601. if (count > 0) {
  73602. infoToPrint.push(
  73603. `\xB7 You're about to delete ${source_default.underline(
  73604. removedColumn
  73605. )} column in ${tableName} table with ${count} items`
  73606. );
  73607. columnsToRemove.push(removedColumn);
  73608. shouldAskForApprove = true;
  73609. }
  73610. }
  73611. }
  73612. if (addedColumns.length) {
  73613. for (const addedColumn of addedColumns) {
  73614. const [res] = await db.query(
  73615. `select count(*) as count from \`${tableName}\``
  73616. );
  73617. const columnConf = json2.tables[tableName].columns[addedColumn];
  73618. const count = Number(res.count);
  73619. if (count > 0 && columnConf.notNull && !columnConf.default) {
  73620. infoToPrint.push(
  73621. `\xB7 You're about to add not-null ${source_default.underline(
  73622. addedColumn
  73623. )} column without default value to table, which contains ${count} items`
  73624. );
  73625. shouldAskForApprove = true;
  73626. tablesToTruncate.push(tableName);
  73627. statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
  73628. }
  73629. }
  73630. }
  73631. const columnWithChangedType = findColumnTypeAlternations(prevColumns, currentColumns);
  73632. for (const column6 of columnWithChangedType) {
  73633. const [res] = await db.query(
  73634. `select count(*) as count from \`${tableName}\` WHERE \`${tableName}\`.\`${column6}\` IS NOT NULL;`
  73635. );
  73636. const count = Number(res.count);
  73637. if (count > 0) {
  73638. infoToPrint.push(
  73639. `\xB7 You're about recreate ${source_default.underline(tableName)} table with data type changing for ${source_default.underline(
  73640. column6
  73641. )} column, which contains ${count} items`
  73642. );
  73643. shouldAskForApprove = true;
  73644. tablesToTruncate.push(tableName);
  73645. statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
  73646. }
  73647. }
  73648. }
  73649. const stmnt = fromJson([statement], "singlestore", "push");
  73650. if (typeof stmnt !== "undefined") {
  73651. statementsToExecute.push(...stmnt);
  73652. }
  73653. }
  73654. return {
  73655. statementsToExecute,
  73656. shouldAskForApprove,
  73657. infoToPrint,
  73658. columnsToRemove: [...new Set(columnsToRemove)],
  73659. schemasToRemove: [...new Set(schemasToRemove)],
  73660. tablesToTruncate: [...new Set(tablesToTruncate)],
  73661. tablesToRemove: [...new Set(tablesToRemove)]
  73662. };
  73663. };
  73664. }
  73665. });
  73666. // src/cli/commands/singlestoreIntrospect.ts
  73667. var singlestoreIntrospect_exports = {};
  73668. __export(singlestoreIntrospect_exports, {
  73669. singlestorePushIntrospect: () => singlestorePushIntrospect
  73670. });
  73671. var import_hanji11, singlestorePushIntrospect;
  73672. var init_singlestoreIntrospect = __esm({
  73673. "src/cli/commands/singlestoreIntrospect.ts"() {
  73674. "use strict";
  73675. import_hanji11 = __toESM(require_hanji());
  73676. init_mjs();
  73677. init_global();
  73678. init_singlestoreSerializer();
  73679. init_views();
  73680. singlestorePushIntrospect = async (db, databaseName, filters) => {
  73681. const matchers = filters.map((it) => {
  73682. return new Minimatch(it);
  73683. });
  73684. const filter2 = (tableName) => {
  73685. if (matchers.length === 0) return true;
  73686. let flags = [];
  73687. for (let matcher of matchers) {
  73688. if (matcher.negate) {
  73689. if (!matcher.match(tableName)) {
  73690. flags.push(false);
  73691. }
  73692. }
  73693. if (matcher.match(tableName)) {
  73694. flags.push(true);
  73695. }
  73696. }
  73697. if (flags.length > 0) {
  73698. return flags.every(Boolean);
  73699. }
  73700. return false;
  73701. };
  73702. const progress = new ProgressView(
  73703. "Pulling schema from database...",
  73704. "Pulling schema from database..."
  73705. );
  73706. const res = await (0, import_hanji11.renderWithTask)(
  73707. progress,
  73708. fromDatabase4(db, databaseName, filter2)
  73709. );
  73710. const schema6 = { id: originUUID, prevId: "", ...res };
  73711. const { internal, ...schemaWithoutInternals } = schema6;
  73712. return { schema: schemaWithoutInternals };
  73713. };
  73714. }
  73715. });
  73716. // src/api.ts
  73717. init_migrate();
  73718. import { randomUUID } from "crypto";
  73719. import { is as is10 } from "drizzle-orm";
  73720. import { getTableConfig as mysqlTableConfig2, MySqlTable as MySqlTable3 } from "drizzle-orm/mysql-core";
  73721. import { getTableConfig as pgTableConfig2, PgTable as PgTable3 } from "drizzle-orm/pg-core";
  73722. import { Relations as Relations3 } from "drizzle-orm/relations";
  73723. import {
  73724. getTableConfig as singlestoreTableConfig2,
  73725. SingleStoreTable as SingleStoreTable3
  73726. } from "drizzle-orm/singlestore-core";
  73727. import { SQLiteTable as SQLiteTable3 } from "drizzle-orm/sqlite-core";
  73728. // src/cli/commands/pgIntrospect.ts
  73729. var import_hanji3 = __toESM(require_hanji());
  73730. init_mjs();
  73731. init_global();
  73732. init_pgSerializer();
  73733. init_views();
  73734. var pgPushIntrospect = async (db, filters, schemaFilters, entities, tsSchema) => {
  73735. const matchers = filters.map((it) => {
  73736. return new Minimatch(it);
  73737. });
  73738. const filter2 = (tableName) => {
  73739. if (matchers.length === 0) return true;
  73740. let flags = [];
  73741. for (let matcher of matchers) {
  73742. if (matcher.negate) {
  73743. if (!matcher.match(tableName)) {
  73744. flags.push(false);
  73745. }
  73746. }
  73747. if (matcher.match(tableName)) {
  73748. flags.push(true);
  73749. }
  73750. }
  73751. if (flags.length > 0) {
  73752. return flags.every(Boolean);
  73753. }
  73754. return false;
  73755. };
  73756. const progress = new ProgressView(
  73757. "Pulling schema from database...",
  73758. "Pulling schema from database..."
  73759. );
  73760. const res = await (0, import_hanji3.renderWithTask)(
  73761. progress,
  73762. fromDatabase(db, filter2, schemaFilters, entities, void 0, tsSchema)
  73763. );
  73764. const schema6 = { id: originUUID, prevId: "", ...res };
  73765. const { internal, ...schemaWithoutInternals } = schema6;
  73766. return { schema: schemaWithoutInternals };
  73767. };
  73768. // src/cli/commands/pgPushUtils.ts
  73769. init_source();
  73770. var import_hanji5 = __toESM(require_hanji());
  73771. init_pgSchema();
  73772. init_sqlgenerator();
  73773. init_selector_ui();
  73774. function concatSchemaAndTableName(schema6, table6) {
  73775. return schema6 ? `"${schema6}"."${table6}"` : `"${table6}"`;
  73776. }
  73777. function tableNameWithSchemaFrom(schema6, tableName, renamedSchemas, renamedTables) {
  73778. const newSchemaName = schema6 ? renamedSchemas[schema6] ? renamedSchemas[schema6] : schema6 : void 0;
  73779. const newTableName = renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] ? renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] : tableName;
  73780. return concatSchemaAndTableName(newSchemaName, newTableName);
  73781. }
  73782. var pgSuggestions = async (db, statements) => {
  73783. let shouldAskForApprove = false;
  73784. const statementsToExecute = [];
  73785. const infoToPrint = [];
  73786. const tablesToRemove = [];
  73787. const columnsToRemove = [];
  73788. const schemasToRemove = [];
  73789. const tablesToTruncate = [];
  73790. const matViewsToRemove = [];
  73791. let renamedSchemas = {};
  73792. let renamedTables = {};
  73793. for (const statement of statements) {
  73794. if (statement.type === "rename_schema") {
  73795. renamedSchemas[statement.to] = statement.from;
  73796. } else if (statement.type === "rename_table") {
  73797. renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
  73798. } else if (statement.type === "drop_table") {
  73799. const res = await db.query(
  73800. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  73801. );
  73802. const count = Number(res[0].count);
  73803. if (count > 0) {
  73804. infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count} items`);
  73805. tablesToRemove.push(statement.tableName);
  73806. shouldAskForApprove = true;
  73807. }
  73808. } else if (statement.type === "drop_view" && statement.materialized) {
  73809. const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
  73810. const count = Number(res[0].count);
  73811. if (count > 0) {
  73812. infoToPrint.push(
  73813. `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count} items`
  73814. );
  73815. matViewsToRemove.push(statement.name);
  73816. shouldAskForApprove = true;
  73817. }
  73818. } else if (statement.type === "alter_table_drop_column") {
  73819. const res = await db.query(
  73820. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  73821. );
  73822. const count = Number(res[0].count);
  73823. if (count > 0) {
  73824. infoToPrint.push(
  73825. `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count} items`
  73826. );
  73827. columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
  73828. shouldAskForApprove = true;
  73829. }
  73830. } else if (statement.type === "drop_schema") {
  73831. const res = await db.query(
  73832. `select count(*) as count from information_schema.tables where table_schema = '${statement.name}';`
  73833. );
  73834. const count = Number(res[0].count);
  73835. if (count > 0) {
  73836. infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count} tables`);
  73837. schemasToRemove.push(statement.name);
  73838. shouldAskForApprove = true;
  73839. }
  73840. } else if (statement.type === "alter_table_alter_column_set_type") {
  73841. const res = await db.query(
  73842. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  73843. );
  73844. const count = Number(res[0].count);
  73845. if (count > 0) {
  73846. infoToPrint.push(
  73847. `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
  73848. statement.newDataType
  73849. )} with ${count} items`
  73850. );
  73851. statementsToExecute.push(
  73852. `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
  73853. );
  73854. tablesToTruncate.push(statement.tableName);
  73855. shouldAskForApprove = true;
  73856. }
  73857. } else if (statement.type === "alter_table_alter_column_drop_pk") {
  73858. const res = await db.query(
  73859. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  73860. );
  73861. const count = Number(res[0].count);
  73862. if (count > 0) {
  73863. infoToPrint.push(
  73864. `\xB7 You're about to change ${source_default.underline(statement.tableName)} primary key. This statements may fail and you table may left without primary key`
  73865. );
  73866. tablesToTruncate.push(statement.tableName);
  73867. shouldAskForApprove = true;
  73868. }
  73869. const tableNameWithSchema = tableNameWithSchemaFrom(
  73870. statement.schema,
  73871. statement.tableName,
  73872. renamedSchemas,
  73873. renamedTables
  73874. );
  73875. const pkNameResponse = await db.query(
  73876. `SELECT constraint_name FROM information_schema.table_constraints
  73877. WHERE table_schema = '${typeof statement.schema === "undefined" || statement.schema === "" ? "public" : statement.schema}'
  73878. AND table_name = '${statement.tableName}'
  73879. AND constraint_type = 'PRIMARY KEY';`
  73880. );
  73881. statementsToExecute.push(
  73882. `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${pkNameResponse[0].constraint_name}"`
  73883. );
  73884. continue;
  73885. } else if (statement.type === "alter_table_add_column") {
  73886. if (statement.column.notNull && typeof statement.column.default === "undefined") {
  73887. const res = await db.query(
  73888. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  73889. );
  73890. const count = Number(res[0].count);
  73891. if (count > 0) {
  73892. infoToPrint.push(
  73893. `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count} items`
  73894. );
  73895. tablesToTruncate.push(statement.tableName);
  73896. statementsToExecute.push(
  73897. `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
  73898. );
  73899. shouldAskForApprove = true;
  73900. }
  73901. }
  73902. } else if (statement.type === "create_unique_constraint") {
  73903. const res = await db.query(
  73904. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  73905. );
  73906. const count = Number(res[0].count);
  73907. if (count > 0) {
  73908. const unsquashedUnique = PgSquasher.unsquashUnique(statement.data);
  73909. console.log(
  73910. `\xB7 You're about to add ${source_default.underline(
  73911. unsquashedUnique.name
  73912. )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
  73913. statement.tableName
  73914. )} table?
  73915. `
  73916. );
  73917. const { status, data } = await (0, import_hanji5.render)(
  73918. new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
  73919. );
  73920. if (data?.index === 1) {
  73921. tablesToTruncate.push(statement.tableName);
  73922. statementsToExecute.push(
  73923. `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
  73924. );
  73925. shouldAskForApprove = true;
  73926. }
  73927. }
  73928. }
  73929. const stmnt = fromJson([statement], "postgresql", "push");
  73930. if (typeof stmnt !== "undefined") {
  73931. statementsToExecute.push(...stmnt);
  73932. }
  73933. }
  73934. return {
  73935. statementsToExecute: [...new Set(statementsToExecute)],
  73936. shouldAskForApprove,
  73937. infoToPrint,
  73938. matViewsToRemove: [...new Set(matViewsToRemove)],
  73939. columnsToRemove: [...new Set(columnsToRemove)],
  73940. schemasToRemove: [...new Set(schemasToRemove)],
  73941. tablesToTruncate: [...new Set(tablesToTruncate)],
  73942. tablesToRemove: [...new Set(tablesToRemove)]
  73943. };
  73944. };
  73945. // src/cli/commands/pgUp.ts
  73946. init_pgSchema();
  73947. init_utils();
  73948. var updateUpToV6 = (json) => {
  73949. const schema6 = pgSchemaV5.parse(json);
  73950. const tables = Object.fromEntries(
  73951. Object.entries(schema6.tables).map((it) => {
  73952. const table6 = it[1];
  73953. const schema7 = table6.schema || "public";
  73954. return [`${schema7}.${table6.name}`, table6];
  73955. })
  73956. );
  73957. const enums = Object.fromEntries(
  73958. Object.entries(schema6.enums).map((it) => {
  73959. const en = it[1];
  73960. return [
  73961. `public.${en.name}`,
  73962. {
  73963. name: en.name,
  73964. schema: "public",
  73965. values: Object.values(en.values)
  73966. }
  73967. ];
  73968. })
  73969. );
  73970. return {
  73971. ...schema6,
  73972. version: "6",
  73973. dialect: "postgresql",
  73974. tables,
  73975. enums
  73976. };
  73977. };
  73978. var updateUpToV7 = (json) => {
  73979. const schema6 = pgSchemaV6.parse(json);
  73980. const tables = Object.fromEntries(
  73981. Object.entries(schema6.tables).map((it) => {
  73982. const table6 = it[1];
  73983. const mappedIndexes = Object.fromEntries(
  73984. Object.entries(table6.indexes).map((idx) => {
  73985. const { columns, ...rest } = idx[1];
  73986. const mappedColumns = columns.map((it2) => {
  73987. return {
  73988. expression: it2,
  73989. isExpression: false,
  73990. asc: true,
  73991. nulls: "last",
  73992. opClass: void 0
  73993. };
  73994. });
  73995. return [idx[0], { columns: mappedColumns, with: {}, ...rest }];
  73996. })
  73997. );
  73998. return [it[0], { ...table6, indexes: mappedIndexes, policies: {}, isRLSEnabled: false, checkConstraints: {} }];
  73999. })
  74000. );
  74001. return {
  74002. ...schema6,
  74003. version: "7",
  74004. dialect: "postgresql",
  74005. sequences: {},
  74006. tables,
  74007. policies: {},
  74008. views: {},
  74009. roles: {}
  74010. };
  74011. };
  74012. // src/cli/commands/sqliteIntrospect.ts
  74013. var import_hanji6 = __toESM(require_hanji());
  74014. init_mjs();
  74015. init_global();
  74016. // src/introspect-sqlite.ts
  74017. import { toCamelCase as toCamelCase2 } from "drizzle-orm/casing";
  74018. // ../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js
  74019. var UPPERCASE = /[\p{Lu}]/u;
  74020. var LOWERCASE = /[\p{Ll}]/u;
  74021. var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
  74022. var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
  74023. var SEPARATORS = /[_.\- ]+/;
  74024. var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
  74025. var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
  74026. var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
  74027. var preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
  74028. let isLastCharLower = false;
  74029. let isLastCharUpper = false;
  74030. let isLastLastCharUpper = false;
  74031. let isLastLastCharPreserved = false;
  74032. for (let index6 = 0; index6 < string.length; index6++) {
  74033. const character = string[index6];
  74034. isLastLastCharPreserved = index6 > 2 ? string[index6 - 3] === "-" : true;
  74035. if (isLastCharLower && UPPERCASE.test(character)) {
  74036. string = string.slice(0, index6) + "-" + string.slice(index6);
  74037. isLastCharLower = false;
  74038. isLastLastCharUpper = isLastCharUpper;
  74039. isLastCharUpper = true;
  74040. index6++;
  74041. } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
  74042. string = string.slice(0, index6 - 1) + "-" + string.slice(index6 - 1);
  74043. isLastLastCharUpper = isLastCharUpper;
  74044. isLastCharUpper = false;
  74045. isLastCharLower = true;
  74046. } else {
  74047. isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
  74048. isLastLastCharUpper = isLastCharUpper;
  74049. isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
  74050. }
  74051. }
  74052. return string;
  74053. };
  74054. var preserveConsecutiveUppercase = (input, toLowerCase) => {
  74055. LEADING_CAPITAL.lastIndex = 0;
  74056. return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
  74057. };
  74058. var postProcess = (input, toUpperCase) => {
  74059. SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
  74060. NUMBERS_AND_IDENTIFIER.lastIndex = 0;
  74061. return input.replace(SEPARATORS_AND_IDENTIFIER, (_3, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m6) => toUpperCase(m6));
  74062. };
  74063. function camelCase(input, options) {
  74064. if (!(typeof input === "string" || Array.isArray(input))) {
  74065. throw new TypeError("Expected the input to be `string | string[]`");
  74066. }
  74067. options = {
  74068. pascalCase: false,
  74069. preserveConsecutiveUppercase: false,
  74070. ...options
  74071. };
  74072. if (Array.isArray(input)) {
  74073. input = input.map((x5) => x5.trim()).filter((x5) => x5.length).join("-");
  74074. } else {
  74075. input = input.trim();
  74076. }
  74077. if (input.length === 0) {
  74078. return "";
  74079. }
  74080. const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
  74081. const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
  74082. if (input.length === 1) {
  74083. if (SEPARATORS.test(input)) {
  74084. return "";
  74085. }
  74086. return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
  74087. }
  74088. const hasUpperCase = input !== toLowerCase(input);
  74089. if (hasUpperCase) {
  74090. input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
  74091. }
  74092. input = input.replace(LEADING_SEPARATORS, "");
  74093. input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
  74094. if (options.pascalCase) {
  74095. input = toUpperCase(input.charAt(0)) + input.slice(1);
  74096. }
  74097. return postProcess(input, toUpperCase);
  74098. }
  74099. // src/@types/utils.ts
  74100. String.prototype.trimChar = function(char) {
  74101. let start = 0;
  74102. let end = this.length;
  74103. while (start < end && this[start] === char) ++start;
  74104. while (end > start && this[end - 1] === char) --end;
  74105. return start > 0 || end < this.length ? this.substring(start, end) : this.toString();
  74106. };
  74107. String.prototype.squashSpaces = function() {
  74108. return this.replace(/ +/g, " ").trim();
  74109. };
  74110. String.prototype.camelCase = function() {
  74111. return camelCase(String(this));
  74112. };
  74113. String.prototype.capitalise = function() {
  74114. return this && this.length > 0 ? `${this[0].toUpperCase()}${this.slice(1)}` : String(this);
  74115. };
  74116. String.prototype.concatIf = function(it, condition) {
  74117. return condition ? `${this}${it}` : String(this);
  74118. };
  74119. String.prototype.snake_case = function() {
  74120. return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
  74121. };
  74122. Array.prototype.random = function() {
  74123. return this[~~(Math.random() * this.length)];
  74124. };
  74125. // src/introspect-sqlite.ts
  74126. init_global();
  74127. // src/cli/commands/sqliteIntrospect.ts
  74128. init_sqliteSerializer();
  74129. init_views();
  74130. var sqlitePushIntrospect = async (db, filters) => {
  74131. const matchers = filters.map((it) => {
  74132. return new Minimatch(it);
  74133. });
  74134. const filter2 = (tableName) => {
  74135. if (matchers.length === 0) return true;
  74136. let flags = [];
  74137. for (let matcher of matchers) {
  74138. if (matcher.negate) {
  74139. if (!matcher.match(tableName)) {
  74140. flags.push(false);
  74141. }
  74142. }
  74143. if (matcher.match(tableName)) {
  74144. flags.push(true);
  74145. }
  74146. }
  74147. if (flags.length > 0) {
  74148. return flags.every(Boolean);
  74149. }
  74150. return false;
  74151. };
  74152. const progress = new ProgressView(
  74153. "Pulling schema from database...",
  74154. "Pulling schema from database..."
  74155. );
  74156. const res = await (0, import_hanji6.renderWithTask)(progress, fromDatabase2(db, filter2));
  74157. const schema6 = { id: originUUID, prevId: "", ...res };
  74158. return { schema: schema6 };
  74159. };
  74160. // src/api.ts
  74161. init_sqlitePushUtils();
  74162. init_getTablesFilterByExtensions();
  74163. init_global();
  74164. init_mysqlSchema();
  74165. init_mysqlSerializer();
  74166. init_pgImports();
  74167. init_pgSchema();
  74168. init_pgSerializer();
  74169. init_singlestoreSchema();
  74170. init_singlestoreSerializer();
  74171. init_sqliteSchema();
  74172. init_sqliteSerializer();
  74173. // ../node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
  74174. import path2 from "path";
  74175. import os2 from "os";
  74176. import process3 from "process";
  74177. var homedir = os2.homedir();
  74178. var tmpdir = os2.tmpdir();
  74179. var { env: env2 } = process3;
  74180. var macos = (name) => {
  74181. const library = path2.join(homedir, "Library");
  74182. return {
  74183. data: path2.join(library, "Application Support", name),
  74184. config: path2.join(library, "Preferences", name),
  74185. cache: path2.join(library, "Caches", name),
  74186. log: path2.join(library, "Logs", name),
  74187. temp: path2.join(tmpdir, name)
  74188. };
  74189. };
  74190. var windows = (name) => {
  74191. const appData = env2.APPDATA || path2.join(homedir, "AppData", "Roaming");
  74192. const localAppData = env2.LOCALAPPDATA || path2.join(homedir, "AppData", "Local");
  74193. return {
  74194. // Data/config/cache/log are invented by me as Windows isn't opinionated about this
  74195. data: path2.join(localAppData, name, "Data"),
  74196. config: path2.join(appData, name, "Config"),
  74197. cache: path2.join(localAppData, name, "Cache"),
  74198. log: path2.join(localAppData, name, "Log"),
  74199. temp: path2.join(tmpdir, name)
  74200. };
  74201. };
  74202. var linux = (name) => {
  74203. const username = path2.basename(homedir);
  74204. return {
  74205. data: path2.join(env2.XDG_DATA_HOME || path2.join(homedir, ".local", "share"), name),
  74206. config: path2.join(env2.XDG_CONFIG_HOME || path2.join(homedir, ".config"), name),
  74207. cache: path2.join(env2.XDG_CACHE_HOME || path2.join(homedir, ".cache"), name),
  74208. // https://wiki.debian.org/XDGBaseDirectorySpecification#state
  74209. log: path2.join(env2.XDG_STATE_HOME || path2.join(homedir, ".local", "state"), name),
  74210. temp: path2.join(tmpdir, username, name)
  74211. };
  74212. };
  74213. function envPaths(name, { suffix = "nodejs" } = {}) {
  74214. if (typeof name !== "string") {
  74215. throw new TypeError(`Expected a string, got ${typeof name}`);
  74216. }
  74217. if (suffix) {
  74218. name += `-${suffix}`;
  74219. }
  74220. if (process3.platform === "darwin") {
  74221. return macos(name);
  74222. }
  74223. if (process3.platform === "win32") {
  74224. return windows(name);
  74225. }
  74226. return linux(name);
  74227. }
  74228. // src/utils/certs.ts
  74229. import { mkdirSync } from "fs";
  74230. import { access, readFile } from "fs/promises";
  74231. import { exec } from "child_process";
  74232. import { join } from "path";
  74233. function runCommand(command, options = {}) {
  74234. return new Promise((resolve) => {
  74235. exec(command, options, (error2) => {
  74236. return resolve({ exitCode: error2?.code ?? 0 });
  74237. });
  74238. });
  74239. }
  74240. var certs = async () => {
  74241. const res = await runCommand("mkcert --help");
  74242. if (res.exitCode === 0) {
  74243. const p5 = envPaths("drizzle-studio", {
  74244. suffix: ""
  74245. });
  74246. mkdirSync(p5.data, { recursive: true });
  74247. const keyPath = join(p5.data, "localhost-key.pem");
  74248. const certPath = join(p5.data, "localhost.pem");
  74249. try {
  74250. await Promise.all([access(keyPath), access(certPath)]);
  74251. } catch (e6) {
  74252. await runCommand(`mkcert localhost`, { cwd: p5.data });
  74253. }
  74254. const [key, cert] = await Promise.all([
  74255. readFile(keyPath, { encoding: "utf-8" }),
  74256. readFile(certPath, { encoding: "utf-8" })
  74257. ]);
  74258. return key && cert ? { key, cert } : null;
  74259. }
  74260. return null;
  74261. };
  74262. // src/api.ts
  74263. var generateDrizzleJson = (imports, prevId, schemaFilters, casing2) => {
  74264. const prepared = prepareFromExports(imports);
  74265. const id = randomUUID();
  74266. const snapshot = generatePgSnapshot(
  74267. prepared.tables,
  74268. prepared.enums,
  74269. prepared.schemas,
  74270. prepared.sequences,
  74271. prepared.roles,
  74272. prepared.policies,
  74273. prepared.views,
  74274. prepared.matViews,
  74275. casing2,
  74276. schemaFilters
  74277. );
  74278. return {
  74279. ...snapshot,
  74280. id,
  74281. prevId: prevId ?? originUUID
  74282. };
  74283. };
  74284. var generateMigration = async (prev, cur) => {
  74285. const { applyPgSnapshotsDiff: applyPgSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  74286. const validatedPrev = pgSchema.parse(prev);
  74287. const validatedCur = pgSchema.parse(cur);
  74288. const squashedPrev = squashPgScheme(validatedPrev);
  74289. const squashedCur = squashPgScheme(validatedCur);
  74290. const { sqlStatements, _meta } = await applyPgSnapshotsDiff2(
  74291. squashedPrev,
  74292. squashedCur,
  74293. schemasResolver,
  74294. enumsResolver,
  74295. sequencesResolver,
  74296. policyResolver,
  74297. indPolicyResolver,
  74298. roleResolver,
  74299. tablesResolver,
  74300. columnsResolver,
  74301. viewsResolver,
  74302. validatedPrev,
  74303. validatedCur
  74304. );
  74305. return sqlStatements;
  74306. };
  74307. var pushSchema = async (imports, drizzleInstance, schemaFilters, tablesFilter, extensionsFilters) => {
  74308. const { applyPgSnapshotsDiff: applyPgSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  74309. const { sql } = await import("drizzle-orm");
  74310. const filters = (tablesFilter ?? []).concat(
  74311. getTablesFilterByExtensions({ extensionsFilters, dialect: "postgresql" })
  74312. );
  74313. const db = {
  74314. query: async (query, params) => {
  74315. const res = await drizzleInstance.execute(sql.raw(query));
  74316. return res.rows;
  74317. }
  74318. };
  74319. const cur = generateDrizzleJson(imports);
  74320. const { schema: prev } = await pgPushIntrospect(
  74321. db,
  74322. filters,
  74323. schemaFilters ?? ["public"],
  74324. void 0
  74325. );
  74326. const validatedPrev = pgSchema.parse(prev);
  74327. const validatedCur = pgSchema.parse(cur);
  74328. const squashedPrev = squashPgScheme(validatedPrev, "push");
  74329. const squashedCur = squashPgScheme(validatedCur, "push");
  74330. const { statements } = await applyPgSnapshotsDiff2(
  74331. squashedPrev,
  74332. squashedCur,
  74333. schemasResolver,
  74334. enumsResolver,
  74335. sequencesResolver,
  74336. policyResolver,
  74337. indPolicyResolver,
  74338. roleResolver,
  74339. tablesResolver,
  74340. columnsResolver,
  74341. viewsResolver,
  74342. validatedPrev,
  74343. validatedCur,
  74344. "push"
  74345. );
  74346. const { shouldAskForApprove, statementsToExecute, infoToPrint } = await pgSuggestions(db, statements);
  74347. return {
  74348. hasDataLoss: shouldAskForApprove,
  74349. warnings: infoToPrint,
  74350. statementsToExecute,
  74351. apply: async () => {
  74352. for (const dStmnt of statementsToExecute) {
  74353. await db.query(dStmnt);
  74354. }
  74355. }
  74356. };
  74357. };
  74358. var startStudioPostgresServer = async (imports, credentials2, options) => {
  74359. const { drizzleForPostgres: drizzleForPostgres2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  74360. const pgSchema2 = {};
  74361. const relations = {};
  74362. Object.entries(imports).forEach(([k5, t6]) => {
  74363. if (is10(t6, PgTable3)) {
  74364. const schema6 = pgTableConfig2(t6).schema || "public";
  74365. pgSchema2[schema6] = pgSchema2[schema6] || {};
  74366. pgSchema2[schema6][k5] = t6;
  74367. }
  74368. if (is10(t6, Relations3)) {
  74369. relations[k5] = t6;
  74370. }
  74371. });
  74372. const setup = await drizzleForPostgres2(credentials2, pgSchema2, relations, [], options?.casing);
  74373. await startServerFromSetup(setup, options);
  74374. };
  74375. var generateSQLiteDrizzleJson = async (imports, prevId, casing2) => {
  74376. const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
  74377. const prepared = prepareFromExports5(imports);
  74378. const id = randomUUID();
  74379. const snapshot = generateSqliteSnapshot(prepared.tables, prepared.views, casing2);
  74380. return {
  74381. ...snapshot,
  74382. id,
  74383. prevId: prevId ?? originUUID
  74384. };
  74385. };
  74386. var generateSQLiteMigration = async (prev, cur) => {
  74387. const { applySqliteSnapshotsDiff: applySqliteSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  74388. const validatedPrev = sqliteSchema.parse(prev);
  74389. const validatedCur = sqliteSchema.parse(cur);
  74390. const squashedPrev = squashSqliteScheme(validatedPrev);
  74391. const squashedCur = squashSqliteScheme(validatedCur);
  74392. const { sqlStatements } = await applySqliteSnapshotsDiff2(
  74393. squashedPrev,
  74394. squashedCur,
  74395. tablesResolver,
  74396. columnsResolver,
  74397. sqliteViewsResolver,
  74398. validatedPrev,
  74399. validatedCur
  74400. );
  74401. return sqlStatements;
  74402. };
  74403. var pushSQLiteSchema = async (imports, drizzleInstance) => {
  74404. const { applySqliteSnapshotsDiff: applySqliteSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  74405. const { sql } = await import("drizzle-orm");
  74406. const db = {
  74407. query: async (query, params) => {
  74408. const res = drizzleInstance.all(sql.raw(query));
  74409. return res;
  74410. },
  74411. run: async (query) => {
  74412. return Promise.resolve(drizzleInstance.run(sql.raw(query))).then(
  74413. () => {
  74414. }
  74415. );
  74416. }
  74417. };
  74418. const cur = await generateSQLiteDrizzleJson(imports);
  74419. const { schema: prev } = await sqlitePushIntrospect(db, []);
  74420. const validatedPrev = sqliteSchema.parse(prev);
  74421. const validatedCur = sqliteSchema.parse(cur);
  74422. const squashedPrev = squashSqliteScheme(validatedPrev, "push");
  74423. const squashedCur = squashSqliteScheme(validatedCur, "push");
  74424. const { statements, _meta } = await applySqliteSnapshotsDiff2(
  74425. squashedPrev,
  74426. squashedCur,
  74427. tablesResolver,
  74428. columnsResolver,
  74429. sqliteViewsResolver,
  74430. validatedPrev,
  74431. validatedCur,
  74432. "push"
  74433. );
  74434. const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn(
  74435. db,
  74436. statements,
  74437. squashedPrev,
  74438. squashedCur,
  74439. _meta
  74440. );
  74441. return {
  74442. hasDataLoss: shouldAskForApprove,
  74443. warnings: infoToPrint,
  74444. statementsToExecute,
  74445. apply: async () => {
  74446. for (const dStmnt of statementsToExecute) {
  74447. await db.query(dStmnt);
  74448. }
  74449. }
  74450. };
  74451. };
  74452. var startStudioSQLiteServer = async (imports, credentials2, options) => {
  74453. const { drizzleForSQLite: drizzleForSQLite2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  74454. const sqliteSchema2 = {};
  74455. const relations = {};
  74456. Object.entries(imports).forEach(([k5, t6]) => {
  74457. if (is10(t6, SQLiteTable3)) {
  74458. const schema6 = "public";
  74459. sqliteSchema2[schema6] = sqliteSchema2[schema6] || {};
  74460. sqliteSchema2[schema6][k5] = t6;
  74461. }
  74462. if (is10(t6, Relations3)) {
  74463. relations[k5] = t6;
  74464. }
  74465. });
  74466. const setup = await drizzleForSQLite2(credentials2, sqliteSchema2, relations, [], options?.casing);
  74467. await startServerFromSetup(setup, options);
  74468. };
  74469. var generateMySQLDrizzleJson = async (imports, prevId, casing2) => {
  74470. const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
  74471. const prepared = prepareFromExports5(imports);
  74472. const id = randomUUID();
  74473. const snapshot = generateMySqlSnapshot(prepared.tables, prepared.views, casing2);
  74474. return {
  74475. ...snapshot,
  74476. id,
  74477. prevId: prevId ?? originUUID
  74478. };
  74479. };
  74480. var generateMySQLMigration = async (prev, cur) => {
  74481. const { applyMysqlSnapshotsDiff: applyMysqlSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  74482. const validatedPrev = mysqlSchema.parse(prev);
  74483. const validatedCur = mysqlSchema.parse(cur);
  74484. const squashedPrev = squashMysqlScheme(validatedPrev);
  74485. const squashedCur = squashMysqlScheme(validatedCur);
  74486. const { sqlStatements } = await applyMysqlSnapshotsDiff2(
  74487. squashedPrev,
  74488. squashedCur,
  74489. tablesResolver,
  74490. columnsResolver,
  74491. mySqlViewsResolver,
  74492. validatedPrev,
  74493. validatedCur
  74494. );
  74495. return sqlStatements;
  74496. };
  74497. var pushMySQLSchema = async (imports, drizzleInstance, databaseName) => {
  74498. const { applyMysqlSnapshotsDiff: applyMysqlSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  74499. const { logSuggestionsAndReturn: logSuggestionsAndReturn4 } = await Promise.resolve().then(() => (init_mysqlPushUtils(), mysqlPushUtils_exports));
  74500. const { mysqlPushIntrospect: mysqlPushIntrospect2 } = await Promise.resolve().then(() => (init_mysqlIntrospect(), mysqlIntrospect_exports));
  74501. const { sql } = await import("drizzle-orm");
  74502. const db = {
  74503. query: async (query, params) => {
  74504. const res = await drizzleInstance.execute(sql.raw(query));
  74505. return res[0];
  74506. }
  74507. };
  74508. const cur = await generateMySQLDrizzleJson(imports);
  74509. const { schema: prev } = await mysqlPushIntrospect2(db, databaseName, []);
  74510. const validatedPrev = mysqlSchema.parse(prev);
  74511. const validatedCur = mysqlSchema.parse(cur);
  74512. const squashedPrev = squashMysqlScheme(validatedPrev);
  74513. const squashedCur = squashMysqlScheme(validatedCur);
  74514. const { statements } = await applyMysqlSnapshotsDiff2(
  74515. squashedPrev,
  74516. squashedCur,
  74517. tablesResolver,
  74518. columnsResolver,
  74519. mySqlViewsResolver,
  74520. validatedPrev,
  74521. validatedCur,
  74522. "push"
  74523. );
  74524. const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn4(
  74525. db,
  74526. statements,
  74527. validatedCur
  74528. );
  74529. return {
  74530. hasDataLoss: shouldAskForApprove,
  74531. warnings: infoToPrint,
  74532. statementsToExecute,
  74533. apply: async () => {
  74534. for (const dStmnt of statementsToExecute) {
  74535. await db.query(dStmnt);
  74536. }
  74537. }
  74538. };
  74539. };
  74540. var startStudioMySQLServer = async (imports, credentials2, options) => {
  74541. const { drizzleForMySQL: drizzleForMySQL2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  74542. const mysqlSchema3 = {};
  74543. const relations = {};
  74544. Object.entries(imports).forEach(([k5, t6]) => {
  74545. if (is10(t6, MySqlTable3)) {
  74546. const schema6 = mysqlTableConfig2(t6).schema || "public";
  74547. mysqlSchema3[schema6] = mysqlSchema3[schema6] || {};
  74548. mysqlSchema3[schema6][k5] = t6;
  74549. }
  74550. if (is10(t6, Relations3)) {
  74551. relations[k5] = t6;
  74552. }
  74553. });
  74554. const setup = await drizzleForMySQL2(credentials2, mysqlSchema3, relations, [], options?.casing);
  74555. await startServerFromSetup(setup, options);
  74556. };
  74557. var generateSingleStoreDrizzleJson = async (imports, prevId, casing2) => {
  74558. const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_singlestoreImports(), singlestoreImports_exports));
  74559. const prepared = prepareFromExports5(imports);
  74560. const id = randomUUID();
  74561. const snapshot = generateSingleStoreSnapshot(
  74562. prepared.tables,
  74563. /* prepared.views, */
  74564. casing2
  74565. );
  74566. return {
  74567. ...snapshot,
  74568. id,
  74569. prevId: prevId ?? originUUID
  74570. };
  74571. };
  74572. var generateSingleStoreMigration = async (prev, cur) => {
  74573. const { applySingleStoreSnapshotsDiff: applySingleStoreSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  74574. const validatedPrev = singlestoreSchema.parse(prev);
  74575. const validatedCur = singlestoreSchema.parse(cur);
  74576. const squashedPrev = squashSingleStoreScheme(validatedPrev);
  74577. const squashedCur = squashSingleStoreScheme(validatedCur);
  74578. const { sqlStatements } = await applySingleStoreSnapshotsDiff2(
  74579. squashedPrev,
  74580. squashedCur,
  74581. tablesResolver,
  74582. columnsResolver,
  74583. /* singleStoreViewsResolver, */
  74584. validatedPrev,
  74585. validatedCur,
  74586. "push"
  74587. );
  74588. return sqlStatements;
  74589. };
  74590. var pushSingleStoreSchema = async (imports, drizzleInstance, databaseName) => {
  74591. const { applySingleStoreSnapshotsDiff: applySingleStoreSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  74592. const { logSuggestionsAndReturn: logSuggestionsAndReturn4 } = await Promise.resolve().then(() => (init_singlestorePushUtils(), singlestorePushUtils_exports));
  74593. const { singlestorePushIntrospect: singlestorePushIntrospect2 } = await Promise.resolve().then(() => (init_singlestoreIntrospect(), singlestoreIntrospect_exports));
  74594. const { sql } = await import("drizzle-orm");
  74595. const db = {
  74596. query: async (query) => {
  74597. const res = await drizzleInstance.execute(sql.raw(query));
  74598. return res[0];
  74599. }
  74600. };
  74601. const cur = await generateSingleStoreDrizzleJson(imports);
  74602. const { schema: prev } = await singlestorePushIntrospect2(db, databaseName, []);
  74603. const validatedPrev = singlestoreSchema.parse(prev);
  74604. const validatedCur = singlestoreSchema.parse(cur);
  74605. const squashedPrev = squashSingleStoreScheme(validatedPrev);
  74606. const squashedCur = squashSingleStoreScheme(validatedCur);
  74607. const { statements } = await applySingleStoreSnapshotsDiff2(
  74608. squashedPrev,
  74609. squashedCur,
  74610. tablesResolver,
  74611. columnsResolver,
  74612. /* singleStoreViewsResolver, */
  74613. validatedPrev,
  74614. validatedCur,
  74615. "push"
  74616. );
  74617. const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn4(
  74618. db,
  74619. statements,
  74620. validatedCur,
  74621. validatedPrev
  74622. );
  74623. return {
  74624. hasDataLoss: shouldAskForApprove,
  74625. warnings: infoToPrint,
  74626. statementsToExecute,
  74627. apply: async () => {
  74628. for (const dStmnt of statementsToExecute) {
  74629. await db.query(dStmnt);
  74630. }
  74631. }
  74632. };
  74633. };
  74634. var startStudioSingleStoreServer = async (imports, credentials2, options) => {
  74635. const { drizzleForSingleStore: drizzleForSingleStore2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  74636. const singleStoreSchema = {};
  74637. const relations = {};
  74638. Object.entries(imports).forEach(([k5, t6]) => {
  74639. if (is10(t6, SingleStoreTable3)) {
  74640. const schema6 = singlestoreTableConfig2(t6).schema || "public";
  74641. singleStoreSchema[schema6] = singleStoreSchema[schema6] || {};
  74642. singleStoreSchema[schema6][k5] = t6;
  74643. }
  74644. if (is10(t6, Relations3)) {
  74645. relations[k5] = t6;
  74646. }
  74647. });
  74648. const setup = await drizzleForSingleStore2(credentials2, singleStoreSchema, relations, [], options?.casing);
  74649. await startServerFromSetup(setup, options);
  74650. };
  74651. var startServerFromSetup = async (setup, options) => {
  74652. const { prepareServer: prepareServer2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  74653. const server = await prepareServer2(setup);
  74654. const host = options?.host || "127.0.0.1";
  74655. const port = options?.port || 4983;
  74656. const { key, cert } = await certs() || {};
  74657. server.start({
  74658. host,
  74659. port,
  74660. key,
  74661. cert,
  74662. cb: (err2) => {
  74663. if (err2) {
  74664. console.error(err2);
  74665. } else {
  74666. console.log(`Studio is running at ${key ? "https" : "http"}://${host}:${port}`);
  74667. }
  74668. }
  74669. });
  74670. };
  74671. var upPgSnapshot = (snapshot) => {
  74672. if (snapshot.version === "5") {
  74673. return updateUpToV7(updateUpToV6(snapshot));
  74674. }
  74675. if (snapshot.version === "6") {
  74676. return updateUpToV7(snapshot);
  74677. }
  74678. return snapshot;
  74679. };
  74680. export {
  74681. generateDrizzleJson,
  74682. generateMigration,
  74683. generateMySQLDrizzleJson,
  74684. generateMySQLMigration,
  74685. generateSQLiteDrizzleJson,
  74686. generateSQLiteMigration,
  74687. generateSingleStoreDrizzleJson,
  74688. generateSingleStoreMigration,
  74689. pushMySQLSchema,
  74690. pushSQLiteSchema,
  74691. pushSchema,
  74692. pushSingleStoreSchema,
  74693. startStudioMySQLServer,
  74694. startStudioPostgresServer,
  74695. startStudioSQLiteServer,
  74696. startStudioSingleStoreServer,
  74697. upPgSnapshot
  74698. };
  74699. /*! Bundled license information:
  74700. web-streams-polyfill/dist/ponyfill.es2018.js:
  74701. (**
  74702. * @license
  74703. * web-streams-polyfill v3.3.3
  74704. * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
  74705. * This code is released under the MIT license.
  74706. * SPDX-License-Identifier: MIT
  74707. *)
  74708. fetch-blob/index.js:
  74709. (*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
  74710. formdata-polyfill/esm.min.js:
  74711. (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
  74712. node-domexception/index.js:
  74713. (*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
  74714. gel/dist/primitives/chars.js:
  74715. gel/dist/primitives/buffer.js:
  74716. gel/dist/errors/index.js:
  74717. gel/dist/primitives/lru.js:
  74718. gel/dist/codecs/consts.js:
  74719. gel/dist/codecs/ifaces.js:
  74720. gel/dist/codecs/boolean.js:
  74721. gel/dist/codecs/numbers.js:
  74722. gel/dist/codecs/numerics.js:
  74723. gel/dist/codecs/text.js:
  74724. gel/dist/codecs/uuid.js:
  74725. gel/dist/codecs/bytes.js:
  74726. gel/dist/codecs/json.js:
  74727. gel/dist/datatypes/datetime.js:
  74728. gel/dist/codecs/datetime.js:
  74729. gel/dist/datatypes/memory.js:
  74730. gel/dist/codecs/memory.js:
  74731. gel/dist/codecs/pgvector.js:
  74732. gel/dist/codecs/codecs.js:
  74733. gel/dist/codecs/tuple.js:
  74734. gel/dist/datatypes/range.js:
  74735. gel/dist/codecs/range.js:
  74736. gel/dist/codecs/namedtuple.js:
  74737. gel/dist/codecs/array.js:
  74738. gel/dist/codecs/enum.js:
  74739. gel/dist/codecs/object.js:
  74740. gel/dist/codecs/set.js:
  74741. gel/dist/codecs/record.js:
  74742. gel/dist/codecs/sparseObject.js:
  74743. gel/dist/codecs/registry.js:
  74744. gel/dist/retry.js:
  74745. gel/dist/conUtils.js:
  74746. gel/dist/errors/map.js:
  74747. gel/dist/errors/resolve.js:
  74748. gel/dist/baseConn.js:
  74749. gel/dist/scram.js:
  74750. gel/dist/rawConn.js:
  74751. gel/dist/index.shared.js:
  74752. gel/dist/index.node.js:
  74753. (*!
  74754. * This source file is part of the Gel open source project.
  74755. *
  74756. * Copyright 2019-present MagicStack Inc. and the Gel authors.
  74757. *
  74758. * Licensed under the Apache License, Version 2.0 (the "License");
  74759. * you may not use this file except in compliance with the License.
  74760. * You may obtain a copy of the License at
  74761. *
  74762. * http://www.apache.org/licenses/LICENSE-2.0
  74763. *
  74764. * Unless required by applicable law or agreed to in writing, software
  74765. * distributed under the License is distributed on an "AS IS" BASIS,
  74766. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  74767. * See the License for the specific language governing permissions and
  74768. * limitations under the License.
  74769. *)
  74770. gel/dist/datatypes/dateutil.js:
  74771. (*!
  74772. * Portions Copyright (c) 2019 MagicStack Inc. and the Gel authors.
  74773. * Portions Copyright (c) 2001-2019 Python Software Foundation.
  74774. * All rights reserved.
  74775. * Licence: PSFL https://docs.python.org/3/license.html
  74776. *)
  74777. gel/dist/utils.js:
  74778. gel/dist/ifaces.js:
  74779. gel/dist/primitives/queues.js:
  74780. gel/dist/baseClient.js:
  74781. gel/dist/reflection/strictMap.js:
  74782. gel/dist/reflection/index.js:
  74783. (*!
  74784. * This source file is part of the Gel open source project.
  74785. *
  74786. * Copyright 2020-present MagicStack Inc. and the Gel authors.
  74787. *
  74788. * Licensed under the Apache License, Version 2.0 (the "License");
  74789. * you may not use this file except in compliance with the License.
  74790. * You may obtain a copy of the License at
  74791. *
  74792. * http://www.apache.org/licenses/LICENSE-2.0
  74793. *
  74794. * Unless required by applicable law or agreed to in writing, software
  74795. * distributed under the License is distributed on an "AS IS" BASIS,
  74796. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  74797. * See the License for the specific language governing permissions and
  74798. * limitations under the License.
  74799. *)
  74800. gel/dist/primitives/event.js:
  74801. (*!
  74802. * This source file is part of the Gel open source project.
  74803. *
  74804. * Copyright 2021-present MagicStack Inc. and the Gel authors.
  74805. *
  74806. * Licensed under the Apache License, Version 2.0 (the "License");
  74807. * you may not use this file except in compliance with the License.
  74808. * You may obtain a copy of the License at
  74809. *
  74810. * http://www.apache.org/licenses/LICENSE-2.0
  74811. *
  74812. * Unless required by applicable law or agreed to in writing, software
  74813. * distributed under the License is distributed on an "AS IS" BASIS,
  74814. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  74815. * See the License for the specific language governing permissions and
  74816. * limitations under the License.
  74817. *)
  74818. gel/dist/fetchConn.js:
  74819. (*!
  74820. * This source file is part of the Gel open source project.
  74821. *
  74822. * Copyright 2022-present MagicStack Inc. and the Gel authors.
  74823. *
  74824. * Licensed under the Apache License, Version 2.0 (the "License");
  74825. * you may not use this file except in compliance with the License.
  74826. * You may obtain a copy of the License at
  74827. *
  74828. * http://www.apache.org/licenses/LICENSE-2.0
  74829. *
  74830. * Unless required by applicable law or agreed to in writing, software
  74831. * distributed under the License is distributed on an "AS IS" BASIS,
  74832. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  74833. * See the License for the specific language governing permissions and
  74834. * limitations under the License.
  74835. *)
  74836. */