utils.js 195 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414
  1. #!/usr/bin/env node
  2. "use strict";
  3. var __create = Object.create;
  4. var __defProp = Object.defineProperty;
  5. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  6. var __getOwnPropNames = Object.getOwnPropertyNames;
  7. var __getProtoOf = Object.getPrototypeOf;
  8. var __hasOwnProp = Object.prototype.hasOwnProperty;
  9. var __commonJS = (cb, mod) => function __require() {
  10. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  11. };
  12. var __export = (target, all) => {
  13. for (var name in all)
  14. __defProp(target, name, { get: all[name], enumerable: true });
  15. };
  16. var __copyProps = (to, from, except, desc) => {
  17. if (from && typeof from === "object" || typeof from === "function") {
  18. for (let key of __getOwnPropNames(from))
  19. if (!__hasOwnProp.call(to, key) && key !== except)
  20. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  21. }
  22. return to;
  23. };
  24. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  25. // If the importer is in node compatibility mode or this is not an ESM
  26. // file that has been converted to a CommonJS file using a Babel-
  27. // compatible transform (i.e. "__esModule" has not been set), then set
  28. // "default" to the CommonJS "module.exports" for node compatibility.
  29. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  30. mod
  31. ));
  32. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  33. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/readline.js
  34. var require_readline = __commonJS({
  35. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/readline.js"(exports2) {
  36. "use strict";
  37. var __importDefault = exports2 && exports2.__importDefault || function(mod) {
  38. return mod && mod.__esModule ? mod : { "default": mod };
  39. };
  40. Object.defineProperty(exports2, "__esModule", { value: true });
  41. exports2.createClosable = exports2.stdout = exports2.stdin = void 0;
  42. var readline_1 = __importDefault(require("readline"));
  43. exports2.stdin = process.stdin;
  44. exports2.stdout = process.stdout;
  45. readline_1.default.emitKeypressEvents(exports2.stdin);
  46. var createClosable = () => {
  47. return readline_1.default.createInterface({
  48. input: exports2.stdin,
  49. escapeCodeTimeout: 50
  50. });
  51. };
  52. exports2.createClosable = createClosable;
  53. }
  54. });
  55. // ../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
  56. var require_src = __commonJS({
  57. "../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2, module2) {
  58. "use strict";
  59. var ESC = "\x1B";
  60. var CSI = `${ESC}[`;
  61. var beep = "\x07";
  62. var cursor = {
  63. to(x, y) {
  64. if (!y) return `${CSI}${x + 1}G`;
  65. return `${CSI}${y + 1};${x + 1}H`;
  66. },
  67. move(x, y) {
  68. let ret = "";
  69. if (x < 0) ret += `${CSI}${-x}D`;
  70. else if (x > 0) ret += `${CSI}${x}C`;
  71. if (y < 0) ret += `${CSI}${-y}A`;
  72. else if (y > 0) ret += `${CSI}${y}B`;
  73. return ret;
  74. },
  75. up: (count = 1) => `${CSI}${count}A`,
  76. down: (count = 1) => `${CSI}${count}B`,
  77. forward: (count = 1) => `${CSI}${count}C`,
  78. backward: (count = 1) => `${CSI}${count}D`,
  79. nextLine: (count = 1) => `${CSI}E`.repeat(count),
  80. prevLine: (count = 1) => `${CSI}F`.repeat(count),
  81. left: `${CSI}G`,
  82. hide: `${CSI}?25l`,
  83. show: `${CSI}?25h`,
  84. save: `${ESC}7`,
  85. restore: `${ESC}8`
  86. };
  87. var scroll = {
  88. up: (count = 1) => `${CSI}S`.repeat(count),
  89. down: (count = 1) => `${CSI}T`.repeat(count)
  90. };
  91. var erase = {
  92. screen: `${CSI}2J`,
  93. up: (count = 1) => `${CSI}1J`.repeat(count),
  94. down: (count = 1) => `${CSI}J`.repeat(count),
  95. line: `${CSI}2K`,
  96. lineEnd: `${CSI}K`,
  97. lineStart: `${CSI}1K`,
  98. lines(count) {
  99. let clear = "";
  100. for (let i = 0; i < count; i++)
  101. clear += this.line + (i < count - 1 ? cursor.up() : "");
  102. if (count)
  103. clear += cursor.left;
  104. return clear;
  105. }
  106. };
  107. module2.exports = { cursor, scroll, erase, beep };
  108. }
  109. });
  110. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/utils.js
  111. var require_utils = __commonJS({
  112. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/utils.js"(exports2) {
  113. "use strict";
  114. Object.defineProperty(exports2, "__esModule", { value: true });
  115. exports2.clear = exports2.stringWidth = exports2.fallbackStringWidth = exports2.stripAnsi = exports2.strip = void 0;
  116. var sisteransi_1 = require_src();
  117. var strip = (str) => {
  118. const pattern = [
  119. "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
  120. "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
  121. ].join("|");
  122. const RGX = new RegExp(pattern, "g");
  123. return typeof str === "string" ? str.replace(RGX, "") : str;
  124. };
  125. exports2.strip = strip;
  126. var stripAnsi = (str) => {
  127. if (typeof Bun !== "undefined" && Bun.stripANSI) {
  128. return Bun.stripANSI(str);
  129. }
  130. return (0, exports2.strip)(str);
  131. };
  132. exports2.stripAnsi = stripAnsi;
  133. var fallbackStringWidth = (str) => {
  134. let len = 0;
  135. const stripped = (0, exports2.stripAnsi)(str);
  136. for (const _ of stripped)
  137. len++;
  138. return len;
  139. };
  140. exports2.fallbackStringWidth = fallbackStringWidth;
  141. var stringWidth = (str) => {
  142. if (typeof Bun !== "undefined" && Bun.stringWidth)
  143. return Bun.stringWidth(str);
  144. return (0, exports2.fallbackStringWidth)(str);
  145. };
  146. exports2.stringWidth = stringWidth;
  147. var clear = function(prompt, perLine) {
  148. if (!perLine)
  149. return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
  150. let rows = 0;
  151. const lines = prompt.split(/\r?\n/);
  152. for (let line of lines) {
  153. rows += 1 + Math.floor(Math.max((0, exports2.stringWidth)(line) - 1, 0) / perLine);
  154. }
  155. return sisteransi_1.erase.lines(rows);
  156. };
  157. exports2.clear = clear;
  158. }
  159. });
  160. // ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
  161. var require_lodash = __commonJS({
  162. "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports2, module2) {
  163. var FUNC_ERROR_TEXT = "Expected a function";
  164. var NAN = 0 / 0;
  165. var symbolTag = "[object Symbol]";
  166. var reTrim = /^\s+|\s+$/g;
  167. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  168. var reIsBinary = /^0b[01]+$/i;
  169. var reIsOctal = /^0o[0-7]+$/i;
  170. var freeParseInt = parseInt;
  171. var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
  172. var freeSelf = typeof self == "object" && self && self.Object === Object && self;
  173. var root = freeGlobal || freeSelf || Function("return this")();
  174. var objectProto = Object.prototype;
  175. var objectToString = objectProto.toString;
  176. var nativeMax = Math.max;
  177. var nativeMin = Math.min;
  178. var now = function() {
  179. return root.Date.now();
  180. };
  181. function debounce(func, wait, options) {
  182. var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
  183. if (typeof func != "function") {
  184. throw new TypeError(FUNC_ERROR_TEXT);
  185. }
  186. wait = toNumber(wait) || 0;
  187. if (isObject(options)) {
  188. leading = !!options.leading;
  189. maxing = "maxWait" in options;
  190. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  191. trailing = "trailing" in options ? !!options.trailing : trailing;
  192. }
  193. function invokeFunc(time) {
  194. var args = lastArgs, thisArg = lastThis;
  195. lastArgs = lastThis = void 0;
  196. lastInvokeTime = time;
  197. result = func.apply(thisArg, args);
  198. return result;
  199. }
  200. function leadingEdge(time) {
  201. lastInvokeTime = time;
  202. timerId = setTimeout(timerExpired, wait);
  203. return leading ? invokeFunc(time) : result;
  204. }
  205. function remainingWait(time) {
  206. var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
  207. return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
  208. }
  209. function shouldInvoke(time) {
  210. var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
  211. return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
  212. }
  213. function timerExpired() {
  214. var time = now();
  215. if (shouldInvoke(time)) {
  216. return trailingEdge(time);
  217. }
  218. timerId = setTimeout(timerExpired, remainingWait(time));
  219. }
  220. function trailingEdge(time) {
  221. timerId = void 0;
  222. if (trailing && lastArgs) {
  223. return invokeFunc(time);
  224. }
  225. lastArgs = lastThis = void 0;
  226. return result;
  227. }
  228. function cancel() {
  229. if (timerId !== void 0) {
  230. clearTimeout(timerId);
  231. }
  232. lastInvokeTime = 0;
  233. lastArgs = lastCallTime = lastThis = timerId = void 0;
  234. }
  235. function flush() {
  236. return timerId === void 0 ? result : trailingEdge(now());
  237. }
  238. function debounced() {
  239. var time = now(), isInvoking = shouldInvoke(time);
  240. lastArgs = arguments;
  241. lastThis = this;
  242. lastCallTime = time;
  243. if (isInvoking) {
  244. if (timerId === void 0) {
  245. return leadingEdge(lastCallTime);
  246. }
  247. if (maxing) {
  248. timerId = setTimeout(timerExpired, wait);
  249. return invokeFunc(lastCallTime);
  250. }
  251. }
  252. if (timerId === void 0) {
  253. timerId = setTimeout(timerExpired, wait);
  254. }
  255. return result;
  256. }
  257. debounced.cancel = cancel;
  258. debounced.flush = flush;
  259. return debounced;
  260. }
  261. function throttle(func, wait, options) {
  262. var leading = true, trailing = true;
  263. if (typeof func != "function") {
  264. throw new TypeError(FUNC_ERROR_TEXT);
  265. }
  266. if (isObject(options)) {
  267. leading = "leading" in options ? !!options.leading : leading;
  268. trailing = "trailing" in options ? !!options.trailing : trailing;
  269. }
  270. return debounce(func, wait, {
  271. "leading": leading,
  272. "maxWait": wait,
  273. "trailing": trailing
  274. });
  275. }
  276. function isObject(value) {
  277. var type = typeof value;
  278. return !!value && (type == "object" || type == "function");
  279. }
  280. function isObjectLike(value) {
  281. return !!value && typeof value == "object";
  282. }
  283. function isSymbol(value) {
  284. return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
  285. }
  286. function toNumber(value) {
  287. if (typeof value == "number") {
  288. return value;
  289. }
  290. if (isSymbol(value)) {
  291. return NAN;
  292. }
  293. if (isObject(value)) {
  294. var other = typeof value.valueOf == "function" ? value.valueOf() : value;
  295. value = isObject(other) ? other + "" : other;
  296. }
  297. if (typeof value != "string") {
  298. return value === 0 ? value : +value;
  299. }
  300. value = value.replace(reTrim, "");
  301. var isBinary = reIsBinary.test(value);
  302. return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
  303. }
  304. module2.exports = throttle;
  305. }
  306. });
  307. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/index.js
  308. var require_hanji = __commonJS({
  309. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/index.js"(exports2) {
  310. "use strict";
  311. var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
  312. function adopt(value) {
  313. return value instanceof P ? value : new P(function(resolve) {
  314. resolve(value);
  315. });
  316. }
  317. return new (P || (P = Promise))(function(resolve, reject) {
  318. function fulfilled(value) {
  319. try {
  320. step(generator.next(value));
  321. } catch (e) {
  322. reject(e);
  323. }
  324. }
  325. function rejected(value) {
  326. try {
  327. step(generator["throw"](value));
  328. } catch (e) {
  329. reject(e);
  330. }
  331. }
  332. function step(result) {
  333. result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
  334. }
  335. step((generator = generator.apply(thisArg, _arguments || [])).next());
  336. });
  337. };
  338. var __importDefault = exports2 && exports2.__importDefault || function(mod) {
  339. return mod && mod.__esModule ? mod : { "default": mod };
  340. };
  341. Object.defineProperty(exports2, "__esModule", { value: true });
  342. exports2.TaskTerminal = exports2.TaskView = exports2.Terminal = exports2.deferred = exports2.SelectState = exports2.Prompt = void 0;
  343. exports2.render = render2;
  344. exports2.renderWithTask = renderWithTask;
  345. exports2.onTerminate = onTerminate;
  346. var readline_1 = require_readline();
  347. var sisteransi_1 = require_src();
  348. var utils_1 = require_utils();
  349. var lodash_throttle_1 = __importDefault(require_lodash());
  350. var Prompt2 = class {
  351. constructor() {
  352. this.attachCallbacks = [];
  353. this.detachCallbacks = [];
  354. this.inputCallbacks = [];
  355. }
  356. requestLayout() {
  357. this.terminal.requestLayout();
  358. }
  359. on(type, callback) {
  360. if (type === "attach") {
  361. this.attachCallbacks.push(callback);
  362. } else if (type === "detach") {
  363. this.detachCallbacks.push(callback);
  364. } else if (type === "input") {
  365. this.inputCallbacks.push(callback);
  366. }
  367. }
  368. attach(terminal) {
  369. this.terminal = terminal;
  370. this.attachCallbacks.forEach((it) => it(terminal));
  371. }
  372. detach(terminal) {
  373. this.detachCallbacks.forEach((it) => it(terminal));
  374. this.terminal = void 0;
  375. }
  376. input(str, key) {
  377. this.inputCallbacks.forEach((it) => it(str, key));
  378. }
  379. };
  380. exports2.Prompt = Prompt2;
  381. var SelectState2 = class {
  382. constructor(items) {
  383. this.items = items;
  384. this.selectedIdx = 0;
  385. }
  386. bind(prompt) {
  387. prompt.on("input", (str, key) => {
  388. const invalidate = this.consume(str, key);
  389. if (invalidate)
  390. prompt.requestLayout();
  391. });
  392. }
  393. consume(str, key) {
  394. if (!key)
  395. return false;
  396. if (key.name === "down") {
  397. this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
  398. return true;
  399. }
  400. if (key.name === "up") {
  401. this.selectedIdx -= 1;
  402. this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
  403. return true;
  404. }
  405. return false;
  406. }
  407. };
  408. exports2.SelectState = SelectState2;
  409. var deferred = () => {
  410. let resolve;
  411. let reject;
  412. const promise = new Promise((res, rej) => {
  413. resolve = res;
  414. reject = rej;
  415. });
  416. return {
  417. resolve,
  418. reject,
  419. promise
  420. };
  421. };
  422. exports2.deferred = deferred;
  423. var Terminal = class {
  424. constructor(view5, stdin, stdout, closable) {
  425. this.view = view5;
  426. this.stdin = stdin;
  427. this.stdout = stdout;
  428. this.closable = closable;
  429. this.text = "";
  430. this.status = "idle";
  431. if (this.stdin.isTTY)
  432. this.stdin.setRawMode(true);
  433. const keypress = (str, key) => {
  434. if (key.name === "c" && key.ctrl === true) {
  435. this.requestLayout();
  436. this.view.detach(this);
  437. this.tearDown(keypress);
  438. if (terminateHandler) {
  439. terminateHandler(this.stdin, this.stdout);
  440. return;
  441. }
  442. this.stdout.write(`
  443. ^C
  444. `);
  445. process.exit(1);
  446. }
  447. if (key.name === "escape") {
  448. this.status = "aborted";
  449. this.requestLayout();
  450. this.view.detach(this);
  451. this.tearDown(keypress);
  452. this.resolve({ status: "aborted", data: void 0 });
  453. return;
  454. }
  455. if (key.name === "return") {
  456. this.status = "submitted";
  457. this.requestLayout();
  458. this.view.detach(this);
  459. this.tearDown(keypress);
  460. this.resolve({ status: "submitted", data: this.view.result() });
  461. return;
  462. }
  463. view5.input(str, key);
  464. };
  465. this.stdin.on("keypress", keypress);
  466. this.view.attach(this);
  467. const { resolve, promise } = (0, exports2.deferred)();
  468. this.resolve = resolve;
  469. this.promise = promise;
  470. this.renderFunc = (0, lodash_throttle_1.default)((str) => {
  471. this.stdout.write(str);
  472. });
  473. }
  474. tearDown(keypress) {
  475. this.stdout.write(sisteransi_1.cursor.show);
  476. this.stdin.removeListener("keypress", keypress);
  477. if (this.stdin.isTTY)
  478. this.stdin.setRawMode(false);
  479. this.closable.close();
  480. }
  481. result() {
  482. return this.promise;
  483. }
  484. toggleCursor(state) {
  485. if (state === "hide") {
  486. this.stdout.write(sisteransi_1.cursor.hide);
  487. } else {
  488. this.stdout.write(sisteransi_1.cursor.show);
  489. }
  490. }
  491. requestLayout() {
  492. const string = this.view.render(this.status);
  493. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  494. this.text = string;
  495. this.renderFunc(`${clearPrefix}${string}`);
  496. }
  497. };
  498. exports2.Terminal = Terminal;
  499. var TaskView2 = class {
  500. constructor() {
  501. this.attachCallbacks = [];
  502. this.detachCallbacks = [];
  503. }
  504. requestLayout() {
  505. this.terminal.requestLayout();
  506. }
  507. attach(terminal) {
  508. this.terminal = terminal;
  509. this.attachCallbacks.forEach((it) => it(terminal));
  510. }
  511. detach(terminal) {
  512. this.detachCallbacks.forEach((it) => it(terminal));
  513. this.terminal = void 0;
  514. }
  515. on(type, callback) {
  516. if (type === "attach") {
  517. this.attachCallbacks.push(callback);
  518. } else if (type === "detach") {
  519. this.detachCallbacks.push(callback);
  520. }
  521. }
  522. };
  523. exports2.TaskView = TaskView2;
  524. var TaskTerminal = class {
  525. constructor(view5, stdout) {
  526. this.view = view5;
  527. this.stdout = stdout;
  528. this.text = "";
  529. this.view.attach(this);
  530. }
  531. requestLayout() {
  532. const string = this.view.render("pending");
  533. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  534. this.text = string;
  535. this.stdout.write(`${clearPrefix}${string}`);
  536. }
  537. clear() {
  538. const string = this.view.render("done");
  539. this.view.detach(this);
  540. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  541. this.stdout.write(`${clearPrefix}${string}`);
  542. }
  543. reject(err) {
  544. const string = this.view.render("rejected", err);
  545. this.view.detach(this);
  546. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  547. this.stdout.write(`${clearPrefix}${string}`);
  548. }
  549. };
  550. exports2.TaskTerminal = TaskTerminal;
  551. function render2(view5) {
  552. if (typeof view5 === "string") {
  553. process.stdout.write(`${view5}
  554. `);
  555. return;
  556. }
  557. if (!process.stdin.isTTY || !process.stdout.isTTY) {
  558. 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."));
  559. }
  560. const closable = (0, readline_1.createClosable)();
  561. const terminal = new Terminal(view5, readline_1.stdin, readline_1.stdout, closable);
  562. terminal.requestLayout();
  563. return terminal.result();
  564. }
  565. function renderWithTask(view5, task) {
  566. return __awaiter(this, void 0, void 0, function* () {
  567. const terminal = new TaskTerminal(view5, process.stdout);
  568. terminal.requestLayout();
  569. try {
  570. const result = yield task;
  571. terminal.clear();
  572. return result;
  573. } catch (err) {
  574. terminal.reject(err);
  575. process.exit(1);
  576. }
  577. });
  578. }
  579. var terminateHandler;
  580. function onTerminate(callback) {
  581. terminateHandler = callback;
  582. }
  583. }
  584. });
  585. // src/utils.ts
  586. var utils_exports = {};
  587. __export(utils_exports, {
  588. assertV1OutFolder: () => assertV1OutFolder,
  589. columnRenameKey: () => columnRenameKey,
  590. copy: () => copy,
  591. dryJournal: () => dryJournal,
  592. escapeSingleQuotes: () => escapeSingleQuotes,
  593. findAddedAndRemoved: () => findAddedAndRemoved,
  594. isPgArrayType: () => isPgArrayType,
  595. kloudMeta: () => kloudMeta,
  596. normalisePGliteUrl: () => normalisePGliteUrl,
  597. normaliseSQLiteUrl: () => normaliseSQLiteUrl,
  598. objectValues: () => objectValues,
  599. prepareMigrationFolder: () => prepareMigrationFolder,
  600. prepareMigrationMeta: () => prepareMigrationMeta,
  601. prepareOutFolder: () => prepareOutFolder,
  602. schemaRenameKey: () => schemaRenameKey,
  603. tableRenameKey: () => tableRenameKey,
  604. unescapeSingleQuotes: () => unescapeSingleQuotes,
  605. validateWithReport: () => validateWithReport
  606. });
  607. module.exports = __toCommonJS(utils_exports);
  608. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js
  609. var ANSI_BACKGROUND_OFFSET = 10;
  610. var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
  611. var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
  612. var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
  613. var styles = {
  614. modifier: {
  615. reset: [0, 0],
  616. // 21 isn't widely supported and 22 does the same thing
  617. bold: [1, 22],
  618. dim: [2, 22],
  619. italic: [3, 23],
  620. underline: [4, 24],
  621. overline: [53, 55],
  622. inverse: [7, 27],
  623. hidden: [8, 28],
  624. strikethrough: [9, 29]
  625. },
  626. color: {
  627. black: [30, 39],
  628. red: [31, 39],
  629. green: [32, 39],
  630. yellow: [33, 39],
  631. blue: [34, 39],
  632. magenta: [35, 39],
  633. cyan: [36, 39],
  634. white: [37, 39],
  635. // Bright color
  636. blackBright: [90, 39],
  637. gray: [90, 39],
  638. // Alias of `blackBright`
  639. grey: [90, 39],
  640. // Alias of `blackBright`
  641. redBright: [91, 39],
  642. greenBright: [92, 39],
  643. yellowBright: [93, 39],
  644. blueBright: [94, 39],
  645. magentaBright: [95, 39],
  646. cyanBright: [96, 39],
  647. whiteBright: [97, 39]
  648. },
  649. bgColor: {
  650. bgBlack: [40, 49],
  651. bgRed: [41, 49],
  652. bgGreen: [42, 49],
  653. bgYellow: [43, 49],
  654. bgBlue: [44, 49],
  655. bgMagenta: [45, 49],
  656. bgCyan: [46, 49],
  657. bgWhite: [47, 49],
  658. // Bright color
  659. bgBlackBright: [100, 49],
  660. bgGray: [100, 49],
  661. // Alias of `bgBlackBright`
  662. bgGrey: [100, 49],
  663. // Alias of `bgBlackBright`
  664. bgRedBright: [101, 49],
  665. bgGreenBright: [102, 49],
  666. bgYellowBright: [103, 49],
  667. bgBlueBright: [104, 49],
  668. bgMagentaBright: [105, 49],
  669. bgCyanBright: [106, 49],
  670. bgWhiteBright: [107, 49]
  671. }
  672. };
  673. var modifierNames = Object.keys(styles.modifier);
  674. var foregroundColorNames = Object.keys(styles.color);
  675. var backgroundColorNames = Object.keys(styles.bgColor);
  676. var colorNames = [...foregroundColorNames, ...backgroundColorNames];
  677. function assembleStyles() {
  678. const codes = /* @__PURE__ */ new Map();
  679. for (const [groupName, group] of Object.entries(styles)) {
  680. for (const [styleName, style] of Object.entries(group)) {
  681. styles[styleName] = {
  682. open: `\x1B[${style[0]}m`,
  683. close: `\x1B[${style[1]}m`
  684. };
  685. group[styleName] = styles[styleName];
  686. codes.set(style[0], style[1]);
  687. }
  688. Object.defineProperty(styles, groupName, {
  689. value: group,
  690. enumerable: false
  691. });
  692. }
  693. Object.defineProperty(styles, "codes", {
  694. value: codes,
  695. enumerable: false
  696. });
  697. styles.color.close = "\x1B[39m";
  698. styles.bgColor.close = "\x1B[49m";
  699. styles.color.ansi = wrapAnsi16();
  700. styles.color.ansi256 = wrapAnsi256();
  701. styles.color.ansi16m = wrapAnsi16m();
  702. styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  703. styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  704. styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  705. Object.defineProperties(styles, {
  706. rgbToAnsi256: {
  707. value(red, green, blue) {
  708. if (red === green && green === blue) {
  709. if (red < 8) {
  710. return 16;
  711. }
  712. if (red > 248) {
  713. return 231;
  714. }
  715. return Math.round((red - 8) / 247 * 24) + 232;
  716. }
  717. return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
  718. },
  719. enumerable: false
  720. },
  721. hexToRgb: {
  722. value(hex) {
  723. const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
  724. if (!matches) {
  725. return [0, 0, 0];
  726. }
  727. let [colorString] = matches;
  728. if (colorString.length === 3) {
  729. colorString = [...colorString].map((character) => character + character).join("");
  730. }
  731. const integer = Number.parseInt(colorString, 16);
  732. return [
  733. /* eslint-disable no-bitwise */
  734. integer >> 16 & 255,
  735. integer >> 8 & 255,
  736. integer & 255
  737. /* eslint-enable no-bitwise */
  738. ];
  739. },
  740. enumerable: false
  741. },
  742. hexToAnsi256: {
  743. value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
  744. enumerable: false
  745. },
  746. ansi256ToAnsi: {
  747. value(code) {
  748. if (code < 8) {
  749. return 30 + code;
  750. }
  751. if (code < 16) {
  752. return 90 + (code - 8);
  753. }
  754. let red;
  755. let green;
  756. let blue;
  757. if (code >= 232) {
  758. red = ((code - 232) * 10 + 8) / 255;
  759. green = red;
  760. blue = red;
  761. } else {
  762. code -= 16;
  763. const remainder = code % 36;
  764. red = Math.floor(code / 36) / 5;
  765. green = Math.floor(remainder / 6) / 5;
  766. blue = remainder % 6 / 5;
  767. }
  768. const value = Math.max(red, green, blue) * 2;
  769. if (value === 0) {
  770. return 30;
  771. }
  772. let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
  773. if (value === 2) {
  774. result += 60;
  775. }
  776. return result;
  777. },
  778. enumerable: false
  779. },
  780. rgbToAnsi: {
  781. value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
  782. enumerable: false
  783. },
  784. hexToAnsi: {
  785. value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
  786. enumerable: false
  787. }
  788. });
  789. return styles;
  790. }
  791. var ansiStyles = assembleStyles();
  792. var ansi_styles_default = ansiStyles;
  793. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js
  794. var import_node_process = __toESM(require("node:process"), 1);
  795. var import_node_os = __toESM(require("node:os"), 1);
  796. var import_node_tty = __toESM(require("node:tty"), 1);
  797. function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
  798. const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  799. const position = argv.indexOf(prefix + flag);
  800. const terminatorPosition = argv.indexOf("--");
  801. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  802. }
  803. var { env } = import_node_process.default;
  804. var flagForceColor;
  805. if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
  806. flagForceColor = 0;
  807. } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
  808. flagForceColor = 1;
  809. }
  810. function envForceColor() {
  811. if ("FORCE_COLOR" in env) {
  812. if (env.FORCE_COLOR === "true") {
  813. return 1;
  814. }
  815. if (env.FORCE_COLOR === "false") {
  816. return 0;
  817. }
  818. return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  819. }
  820. }
  821. function translateLevel(level) {
  822. if (level === 0) {
  823. return false;
  824. }
  825. return {
  826. level,
  827. hasBasic: true,
  828. has256: level >= 2,
  829. has16m: level >= 3
  830. };
  831. }
  832. function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  833. const noFlagForceColor = envForceColor();
  834. if (noFlagForceColor !== void 0) {
  835. flagForceColor = noFlagForceColor;
  836. }
  837. const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  838. if (forceColor === 0) {
  839. return 0;
  840. }
  841. if (sniffFlags) {
  842. if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
  843. return 3;
  844. }
  845. if (hasFlag("color=256")) {
  846. return 2;
  847. }
  848. }
  849. if ("TF_BUILD" in env && "AGENT_NAME" in env) {
  850. return 1;
  851. }
  852. if (haveStream && !streamIsTTY && forceColor === void 0) {
  853. return 0;
  854. }
  855. const min = forceColor || 0;
  856. if (env.TERM === "dumb") {
  857. return min;
  858. }
  859. if (import_node_process.default.platform === "win32") {
  860. const osRelease = import_node_os.default.release().split(".");
  861. if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  862. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  863. }
  864. return 1;
  865. }
  866. if ("CI" in env) {
  867. if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
  868. return 3;
  869. }
  870. if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
  871. return 1;
  872. }
  873. return min;
  874. }
  875. if ("TEAMCITY_VERSION" in env) {
  876. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  877. }
  878. if (env.COLORTERM === "truecolor") {
  879. return 3;
  880. }
  881. if (env.TERM === "xterm-kitty") {
  882. return 3;
  883. }
  884. if ("TERM_PROGRAM" in env) {
  885. const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
  886. switch (env.TERM_PROGRAM) {
  887. case "iTerm.app": {
  888. return version >= 3 ? 3 : 2;
  889. }
  890. case "Apple_Terminal": {
  891. return 2;
  892. }
  893. }
  894. }
  895. if (/-256(color)?$/i.test(env.TERM)) {
  896. return 2;
  897. }
  898. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  899. return 1;
  900. }
  901. if ("COLORTERM" in env) {
  902. return 1;
  903. }
  904. return min;
  905. }
  906. function createSupportsColor(stream, options = {}) {
  907. const level = _supportsColor(stream, {
  908. streamIsTTY: stream && stream.isTTY,
  909. ...options
  910. });
  911. return translateLevel(level);
  912. }
  913. var supportsColor = {
  914. stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
  915. stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
  916. };
  917. var supports_color_default = supportsColor;
  918. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js
  919. function stringReplaceAll(string, substring, replacer) {
  920. let index6 = string.indexOf(substring);
  921. if (index6 === -1) {
  922. return string;
  923. }
  924. const substringLength = substring.length;
  925. let endIndex = 0;
  926. let returnValue = "";
  927. do {
  928. returnValue += string.slice(endIndex, index6) + substring + replacer;
  929. endIndex = index6 + substringLength;
  930. index6 = string.indexOf(substring, endIndex);
  931. } while (index6 !== -1);
  932. returnValue += string.slice(endIndex);
  933. return returnValue;
  934. }
  935. function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index6) {
  936. let endIndex = 0;
  937. let returnValue = "";
  938. do {
  939. const gotCR = string[index6 - 1] === "\r";
  940. returnValue += string.slice(endIndex, gotCR ? index6 - 1 : index6) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
  941. endIndex = index6 + 1;
  942. index6 = string.indexOf("\n", endIndex);
  943. } while (index6 !== -1);
  944. returnValue += string.slice(endIndex);
  945. return returnValue;
  946. }
  947. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js
  948. var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
  949. var GENERATOR = Symbol("GENERATOR");
  950. var STYLER = Symbol("STYLER");
  951. var IS_EMPTY = Symbol("IS_EMPTY");
  952. var levelMapping = [
  953. "ansi",
  954. "ansi",
  955. "ansi256",
  956. "ansi16m"
  957. ];
  958. var styles2 = /* @__PURE__ */ Object.create(null);
  959. var applyOptions = (object, options = {}) => {
  960. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  961. throw new Error("The `level` option should be an integer from 0 to 3");
  962. }
  963. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  964. object.level = options.level === void 0 ? colorLevel : options.level;
  965. };
  966. var chalkFactory = (options) => {
  967. const chalk2 = (...strings) => strings.join(" ");
  968. applyOptions(chalk2, options);
  969. Object.setPrototypeOf(chalk2, createChalk.prototype);
  970. return chalk2;
  971. };
  972. function createChalk(options) {
  973. return chalkFactory(options);
  974. }
  975. Object.setPrototypeOf(createChalk.prototype, Function.prototype);
  976. for (const [styleName, style] of Object.entries(ansi_styles_default)) {
  977. styles2[styleName] = {
  978. get() {
  979. const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
  980. Object.defineProperty(this, styleName, { value: builder });
  981. return builder;
  982. }
  983. };
  984. }
  985. styles2.visible = {
  986. get() {
  987. const builder = createBuilder(this, this[STYLER], true);
  988. Object.defineProperty(this, "visible", { value: builder });
  989. return builder;
  990. }
  991. };
  992. var getModelAnsi = (model, level, type, ...arguments_) => {
  993. if (model === "rgb") {
  994. if (level === "ansi16m") {
  995. return ansi_styles_default[type].ansi16m(...arguments_);
  996. }
  997. if (level === "ansi256") {
  998. return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
  999. }
  1000. return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
  1001. }
  1002. if (model === "hex") {
  1003. return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
  1004. }
  1005. return ansi_styles_default[type][model](...arguments_);
  1006. };
  1007. var usedModels = ["rgb", "hex", "ansi256"];
  1008. for (const model of usedModels) {
  1009. styles2[model] = {
  1010. get() {
  1011. const { level } = this;
  1012. return function(...arguments_) {
  1013. const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
  1014. return createBuilder(this, styler, this[IS_EMPTY]);
  1015. };
  1016. }
  1017. };
  1018. const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
  1019. styles2[bgModel] = {
  1020. get() {
  1021. const { level } = this;
  1022. return function(...arguments_) {
  1023. const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
  1024. return createBuilder(this, styler, this[IS_EMPTY]);
  1025. };
  1026. }
  1027. };
  1028. }
  1029. var proto = Object.defineProperties(() => {
  1030. }, {
  1031. ...styles2,
  1032. level: {
  1033. enumerable: true,
  1034. get() {
  1035. return this[GENERATOR].level;
  1036. },
  1037. set(level) {
  1038. this[GENERATOR].level = level;
  1039. }
  1040. }
  1041. });
  1042. var createStyler = (open, close, parent) => {
  1043. let openAll;
  1044. let closeAll;
  1045. if (parent === void 0) {
  1046. openAll = open;
  1047. closeAll = close;
  1048. } else {
  1049. openAll = parent.openAll + open;
  1050. closeAll = close + parent.closeAll;
  1051. }
  1052. return {
  1053. open,
  1054. close,
  1055. openAll,
  1056. closeAll,
  1057. parent
  1058. };
  1059. };
  1060. var createBuilder = (self2, _styler, _isEmpty) => {
  1061. const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
  1062. Object.setPrototypeOf(builder, proto);
  1063. builder[GENERATOR] = self2;
  1064. builder[STYLER] = _styler;
  1065. builder[IS_EMPTY] = _isEmpty;
  1066. return builder;
  1067. };
  1068. var applyStyle = (self2, string) => {
  1069. if (self2.level <= 0 || !string) {
  1070. return self2[IS_EMPTY] ? "" : string;
  1071. }
  1072. let styler = self2[STYLER];
  1073. if (styler === void 0) {
  1074. return string;
  1075. }
  1076. const { openAll, closeAll } = styler;
  1077. if (string.includes("\x1B")) {
  1078. while (styler !== void 0) {
  1079. string = stringReplaceAll(string, styler.close, styler.open);
  1080. styler = styler.parent;
  1081. }
  1082. }
  1083. const lfIndex = string.indexOf("\n");
  1084. if (lfIndex !== -1) {
  1085. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  1086. }
  1087. return openAll + string + closeAll;
  1088. };
  1089. Object.defineProperties(createChalk.prototype, styles2);
  1090. var chalk = createChalk();
  1091. var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
  1092. var source_default = chalk;
  1093. // src/utils.ts
  1094. var import_fs = require("fs");
  1095. var import_path = require("path");
  1096. var import_url = require("url");
  1097. // src/cli/views.ts
  1098. var import_hanji = __toESM(require_hanji());
  1099. var info = (msg, greyMsg = "") => {
  1100. return `${source_default.blue.bold("Info:")} ${msg} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
  1101. };
  1102. // src/global.ts
  1103. var originUUID = "00000000-0000-0000-0000-000000000000";
  1104. var snapshotVersion = "7";
  1105. function assertUnreachable(x) {
  1106. throw new Error("Didn't expect to get here");
  1107. }
  1108. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js
  1109. var util;
  1110. (function(util2) {
  1111. util2.assertEqual = (_) => {
  1112. };
  1113. function assertIs(_arg) {
  1114. }
  1115. util2.assertIs = assertIs;
  1116. function assertNever(_x) {
  1117. throw new Error();
  1118. }
  1119. util2.assertNever = assertNever;
  1120. util2.arrayToEnum = (items) => {
  1121. const obj = {};
  1122. for (const item of items) {
  1123. obj[item] = item;
  1124. }
  1125. return obj;
  1126. };
  1127. util2.getValidEnumValues = (obj) => {
  1128. const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
  1129. const filtered = {};
  1130. for (const k of validKeys) {
  1131. filtered[k] = obj[k];
  1132. }
  1133. return util2.objectValues(filtered);
  1134. };
  1135. util2.objectValues = (obj) => {
  1136. return util2.objectKeys(obj).map(function(e) {
  1137. return obj[e];
  1138. });
  1139. };
  1140. util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
  1141. const keys = [];
  1142. for (const key in object) {
  1143. if (Object.prototype.hasOwnProperty.call(object, key)) {
  1144. keys.push(key);
  1145. }
  1146. }
  1147. return keys;
  1148. };
  1149. util2.find = (arr, checker) => {
  1150. for (const item of arr) {
  1151. if (checker(item))
  1152. return item;
  1153. }
  1154. return void 0;
  1155. };
  1156. util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  1157. function joinValues(array, separator = " | ") {
  1158. return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  1159. }
  1160. util2.joinValues = joinValues;
  1161. util2.jsonStringifyReplacer = (_, value) => {
  1162. if (typeof value === "bigint") {
  1163. return value.toString();
  1164. }
  1165. return value;
  1166. };
  1167. })(util || (util = {}));
  1168. var objectUtil;
  1169. (function(objectUtil2) {
  1170. objectUtil2.mergeShapes = (first, second) => {
  1171. return {
  1172. ...first,
  1173. ...second
  1174. // second overwrites first
  1175. };
  1176. };
  1177. })(objectUtil || (objectUtil = {}));
  1178. var ZodParsedType = util.arrayToEnum([
  1179. "string",
  1180. "nan",
  1181. "number",
  1182. "integer",
  1183. "float",
  1184. "boolean",
  1185. "date",
  1186. "bigint",
  1187. "symbol",
  1188. "function",
  1189. "undefined",
  1190. "null",
  1191. "array",
  1192. "object",
  1193. "unknown",
  1194. "promise",
  1195. "void",
  1196. "never",
  1197. "map",
  1198. "set"
  1199. ]);
  1200. var getParsedType = (data) => {
  1201. const t = typeof data;
  1202. switch (t) {
  1203. case "undefined":
  1204. return ZodParsedType.undefined;
  1205. case "string":
  1206. return ZodParsedType.string;
  1207. case "number":
  1208. return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
  1209. case "boolean":
  1210. return ZodParsedType.boolean;
  1211. case "function":
  1212. return ZodParsedType.function;
  1213. case "bigint":
  1214. return ZodParsedType.bigint;
  1215. case "symbol":
  1216. return ZodParsedType.symbol;
  1217. case "object":
  1218. if (Array.isArray(data)) {
  1219. return ZodParsedType.array;
  1220. }
  1221. if (data === null) {
  1222. return ZodParsedType.null;
  1223. }
  1224. if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
  1225. return ZodParsedType.promise;
  1226. }
  1227. if (typeof Map !== "undefined" && data instanceof Map) {
  1228. return ZodParsedType.map;
  1229. }
  1230. if (typeof Set !== "undefined" && data instanceof Set) {
  1231. return ZodParsedType.set;
  1232. }
  1233. if (typeof Date !== "undefined" && data instanceof Date) {
  1234. return ZodParsedType.date;
  1235. }
  1236. return ZodParsedType.object;
  1237. default:
  1238. return ZodParsedType.unknown;
  1239. }
  1240. };
  1241. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js
  1242. var ZodIssueCode = util.arrayToEnum([
  1243. "invalid_type",
  1244. "invalid_literal",
  1245. "custom",
  1246. "invalid_union",
  1247. "invalid_union_discriminator",
  1248. "invalid_enum_value",
  1249. "unrecognized_keys",
  1250. "invalid_arguments",
  1251. "invalid_return_type",
  1252. "invalid_date",
  1253. "invalid_string",
  1254. "too_small",
  1255. "too_big",
  1256. "invalid_intersection_types",
  1257. "not_multiple_of",
  1258. "not_finite"
  1259. ]);
  1260. var ZodError = class _ZodError extends Error {
  1261. get errors() {
  1262. return this.issues;
  1263. }
  1264. constructor(issues) {
  1265. super();
  1266. this.issues = [];
  1267. this.addIssue = (sub) => {
  1268. this.issues = [...this.issues, sub];
  1269. };
  1270. this.addIssues = (subs = []) => {
  1271. this.issues = [...this.issues, ...subs];
  1272. };
  1273. const actualProto = new.target.prototype;
  1274. if (Object.setPrototypeOf) {
  1275. Object.setPrototypeOf(this, actualProto);
  1276. } else {
  1277. this.__proto__ = actualProto;
  1278. }
  1279. this.name = "ZodError";
  1280. this.issues = issues;
  1281. }
  1282. format(_mapper) {
  1283. const mapper = _mapper || function(issue) {
  1284. return issue.message;
  1285. };
  1286. const fieldErrors = { _errors: [] };
  1287. const processError = (error) => {
  1288. for (const issue of error.issues) {
  1289. if (issue.code === "invalid_union") {
  1290. issue.unionErrors.map(processError);
  1291. } else if (issue.code === "invalid_return_type") {
  1292. processError(issue.returnTypeError);
  1293. } else if (issue.code === "invalid_arguments") {
  1294. processError(issue.argumentsError);
  1295. } else if (issue.path.length === 0) {
  1296. fieldErrors._errors.push(mapper(issue));
  1297. } else {
  1298. let curr = fieldErrors;
  1299. let i = 0;
  1300. while (i < issue.path.length) {
  1301. const el = issue.path[i];
  1302. const terminal = i === issue.path.length - 1;
  1303. if (!terminal) {
  1304. curr[el] = curr[el] || { _errors: [] };
  1305. } else {
  1306. curr[el] = curr[el] || { _errors: [] };
  1307. curr[el]._errors.push(mapper(issue));
  1308. }
  1309. curr = curr[el];
  1310. i++;
  1311. }
  1312. }
  1313. }
  1314. };
  1315. processError(this);
  1316. return fieldErrors;
  1317. }
  1318. static assert(value) {
  1319. if (!(value instanceof _ZodError)) {
  1320. throw new Error(`Not a ZodError: ${value}`);
  1321. }
  1322. }
  1323. toString() {
  1324. return this.message;
  1325. }
  1326. get message() {
  1327. return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  1328. }
  1329. get isEmpty() {
  1330. return this.issues.length === 0;
  1331. }
  1332. flatten(mapper = (issue) => issue.message) {
  1333. const fieldErrors = {};
  1334. const formErrors = [];
  1335. for (const sub of this.issues) {
  1336. if (sub.path.length > 0) {
  1337. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
  1338. fieldErrors[sub.path[0]].push(mapper(sub));
  1339. } else {
  1340. formErrors.push(mapper(sub));
  1341. }
  1342. }
  1343. return { formErrors, fieldErrors };
  1344. }
  1345. get formErrors() {
  1346. return this.flatten();
  1347. }
  1348. };
  1349. ZodError.create = (issues) => {
  1350. const error = new ZodError(issues);
  1351. return error;
  1352. };
  1353. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js
  1354. var errorMap = (issue, _ctx) => {
  1355. let message;
  1356. switch (issue.code) {
  1357. case ZodIssueCode.invalid_type:
  1358. if (issue.received === ZodParsedType.undefined) {
  1359. message = "Required";
  1360. } else {
  1361. message = `Expected ${issue.expected}, received ${issue.received}`;
  1362. }
  1363. break;
  1364. case ZodIssueCode.invalid_literal:
  1365. message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
  1366. break;
  1367. case ZodIssueCode.unrecognized_keys:
  1368. message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
  1369. break;
  1370. case ZodIssueCode.invalid_union:
  1371. message = `Invalid input`;
  1372. break;
  1373. case ZodIssueCode.invalid_union_discriminator:
  1374. message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
  1375. break;
  1376. case ZodIssueCode.invalid_enum_value:
  1377. message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
  1378. break;
  1379. case ZodIssueCode.invalid_arguments:
  1380. message = `Invalid function arguments`;
  1381. break;
  1382. case ZodIssueCode.invalid_return_type:
  1383. message = `Invalid function return type`;
  1384. break;
  1385. case ZodIssueCode.invalid_date:
  1386. message = `Invalid date`;
  1387. break;
  1388. case ZodIssueCode.invalid_string:
  1389. if (typeof issue.validation === "object") {
  1390. if ("includes" in issue.validation) {
  1391. message = `Invalid input: must include "${issue.validation.includes}"`;
  1392. if (typeof issue.validation.position === "number") {
  1393. message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
  1394. }
  1395. } else if ("startsWith" in issue.validation) {
  1396. message = `Invalid input: must start with "${issue.validation.startsWith}"`;
  1397. } else if ("endsWith" in issue.validation) {
  1398. message = `Invalid input: must end with "${issue.validation.endsWith}"`;
  1399. } else {
  1400. util.assertNever(issue.validation);
  1401. }
  1402. } else if (issue.validation !== "regex") {
  1403. message = `Invalid ${issue.validation}`;
  1404. } else {
  1405. message = "Invalid";
  1406. }
  1407. break;
  1408. case ZodIssueCode.too_small:
  1409. if (issue.type === "array")
  1410. message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
  1411. else if (issue.type === "string")
  1412. message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
  1413. else if (issue.type === "number")
  1414. message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
  1415. else if (issue.type === "date")
  1416. message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
  1417. else
  1418. message = "Invalid input";
  1419. break;
  1420. case ZodIssueCode.too_big:
  1421. if (issue.type === "array")
  1422. message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
  1423. else if (issue.type === "string")
  1424. message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
  1425. else if (issue.type === "number")
  1426. message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
  1427. else if (issue.type === "bigint")
  1428. message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
  1429. else if (issue.type === "date")
  1430. message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
  1431. else
  1432. message = "Invalid input";
  1433. break;
  1434. case ZodIssueCode.custom:
  1435. message = `Invalid input`;
  1436. break;
  1437. case ZodIssueCode.invalid_intersection_types:
  1438. message = `Intersection results could not be merged`;
  1439. break;
  1440. case ZodIssueCode.not_multiple_of:
  1441. message = `Number must be a multiple of ${issue.multipleOf}`;
  1442. break;
  1443. case ZodIssueCode.not_finite:
  1444. message = "Number must be finite";
  1445. break;
  1446. default:
  1447. message = _ctx.defaultError;
  1448. util.assertNever(issue);
  1449. }
  1450. return { message };
  1451. };
  1452. var en_default = errorMap;
  1453. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js
  1454. var overrideErrorMap = en_default;
  1455. function getErrorMap() {
  1456. return overrideErrorMap;
  1457. }
  1458. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
  1459. var makeIssue = (params) => {
  1460. const { data, path, errorMaps, issueData } = params;
  1461. const fullPath = [...path, ...issueData.path || []];
  1462. const fullIssue = {
  1463. ...issueData,
  1464. path: fullPath
  1465. };
  1466. if (issueData.message !== void 0) {
  1467. return {
  1468. ...issueData,
  1469. path: fullPath,
  1470. message: issueData.message
  1471. };
  1472. }
  1473. let errorMessage = "";
  1474. const maps = errorMaps.filter((m) => !!m).slice().reverse();
  1475. for (const map of maps) {
  1476. errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  1477. }
  1478. return {
  1479. ...issueData,
  1480. path: fullPath,
  1481. message: errorMessage
  1482. };
  1483. };
  1484. function addIssueToContext(ctx, issueData) {
  1485. const overrideMap = getErrorMap();
  1486. const issue = makeIssue({
  1487. issueData,
  1488. data: ctx.data,
  1489. path: ctx.path,
  1490. errorMaps: [
  1491. ctx.common.contextualErrorMap,
  1492. // contextual error map is first priority
  1493. ctx.schemaErrorMap,
  1494. // then schema-bound map if available
  1495. overrideMap,
  1496. // then global override map
  1497. overrideMap === en_default ? void 0 : en_default
  1498. // then global default map
  1499. ].filter((x) => !!x)
  1500. });
  1501. ctx.common.issues.push(issue);
  1502. }
  1503. var ParseStatus = class _ParseStatus {
  1504. constructor() {
  1505. this.value = "valid";
  1506. }
  1507. dirty() {
  1508. if (this.value === "valid")
  1509. this.value = "dirty";
  1510. }
  1511. abort() {
  1512. if (this.value !== "aborted")
  1513. this.value = "aborted";
  1514. }
  1515. static mergeArray(status, results) {
  1516. const arrayValue = [];
  1517. for (const s of results) {
  1518. if (s.status === "aborted")
  1519. return INVALID;
  1520. if (s.status === "dirty")
  1521. status.dirty();
  1522. arrayValue.push(s.value);
  1523. }
  1524. return { status: status.value, value: arrayValue };
  1525. }
  1526. static async mergeObjectAsync(status, pairs) {
  1527. const syncPairs = [];
  1528. for (const pair of pairs) {
  1529. const key = await pair.key;
  1530. const value = await pair.value;
  1531. syncPairs.push({
  1532. key,
  1533. value
  1534. });
  1535. }
  1536. return _ParseStatus.mergeObjectSync(status, syncPairs);
  1537. }
  1538. static mergeObjectSync(status, pairs) {
  1539. const finalObject = {};
  1540. for (const pair of pairs) {
  1541. const { key, value } = pair;
  1542. if (key.status === "aborted")
  1543. return INVALID;
  1544. if (value.status === "aborted")
  1545. return INVALID;
  1546. if (key.status === "dirty")
  1547. status.dirty();
  1548. if (value.status === "dirty")
  1549. status.dirty();
  1550. if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
  1551. finalObject[key.value] = value.value;
  1552. }
  1553. }
  1554. return { status: status.value, value: finalObject };
  1555. }
  1556. };
  1557. var INVALID = Object.freeze({
  1558. status: "aborted"
  1559. });
  1560. var DIRTY = (value) => ({ status: "dirty", value });
  1561. var OK = (value) => ({ status: "valid", value });
  1562. var isAborted = (x) => x.status === "aborted";
  1563. var isDirty = (x) => x.status === "dirty";
  1564. var isValid = (x) => x.status === "valid";
  1565. var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
  1566. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js
  1567. var errorUtil;
  1568. (function(errorUtil2) {
  1569. errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  1570. errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
  1571. })(errorUtil || (errorUtil = {}));
  1572. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js
  1573. var ParseInputLazyPath = class {
  1574. constructor(parent, value, path, key) {
  1575. this._cachedPath = [];
  1576. this.parent = parent;
  1577. this.data = value;
  1578. this._path = path;
  1579. this._key = key;
  1580. }
  1581. get path() {
  1582. if (!this._cachedPath.length) {
  1583. if (Array.isArray(this._key)) {
  1584. this._cachedPath.push(...this._path, ...this._key);
  1585. } else {
  1586. this._cachedPath.push(...this._path, this._key);
  1587. }
  1588. }
  1589. return this._cachedPath;
  1590. }
  1591. };
  1592. var handleResult = (ctx, result) => {
  1593. if (isValid(result)) {
  1594. return { success: true, data: result.value };
  1595. } else {
  1596. if (!ctx.common.issues.length) {
  1597. throw new Error("Validation failed but no issues detected.");
  1598. }
  1599. return {
  1600. success: false,
  1601. get error() {
  1602. if (this._error)
  1603. return this._error;
  1604. const error = new ZodError(ctx.common.issues);
  1605. this._error = error;
  1606. return this._error;
  1607. }
  1608. };
  1609. }
  1610. };
  1611. function processCreateParams(params) {
  1612. if (!params)
  1613. return {};
  1614. const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  1615. if (errorMap2 && (invalid_type_error || required_error)) {
  1616. throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  1617. }
  1618. if (errorMap2)
  1619. return { errorMap: errorMap2, description };
  1620. const customMap = (iss, ctx) => {
  1621. const { message } = params;
  1622. if (iss.code === "invalid_enum_value") {
  1623. return { message: message ?? ctx.defaultError };
  1624. }
  1625. if (typeof ctx.data === "undefined") {
  1626. return { message: message ?? required_error ?? ctx.defaultError };
  1627. }
  1628. if (iss.code !== "invalid_type")
  1629. return { message: ctx.defaultError };
  1630. return { message: message ?? invalid_type_error ?? ctx.defaultError };
  1631. };
  1632. return { errorMap: customMap, description };
  1633. }
  1634. var ZodType = class {
  1635. get description() {
  1636. return this._def.description;
  1637. }
  1638. _getType(input) {
  1639. return getParsedType(input.data);
  1640. }
  1641. _getOrReturnCtx(input, ctx) {
  1642. return ctx || {
  1643. common: input.parent.common,
  1644. data: input.data,
  1645. parsedType: getParsedType(input.data),
  1646. schemaErrorMap: this._def.errorMap,
  1647. path: input.path,
  1648. parent: input.parent
  1649. };
  1650. }
  1651. _processInputParams(input) {
  1652. return {
  1653. status: new ParseStatus(),
  1654. ctx: {
  1655. common: input.parent.common,
  1656. data: input.data,
  1657. parsedType: getParsedType(input.data),
  1658. schemaErrorMap: this._def.errorMap,
  1659. path: input.path,
  1660. parent: input.parent
  1661. }
  1662. };
  1663. }
  1664. _parseSync(input) {
  1665. const result = this._parse(input);
  1666. if (isAsync(result)) {
  1667. throw new Error("Synchronous parse encountered promise.");
  1668. }
  1669. return result;
  1670. }
  1671. _parseAsync(input) {
  1672. const result = this._parse(input);
  1673. return Promise.resolve(result);
  1674. }
  1675. parse(data, params) {
  1676. const result = this.safeParse(data, params);
  1677. if (result.success)
  1678. return result.data;
  1679. throw result.error;
  1680. }
  1681. safeParse(data, params) {
  1682. const ctx = {
  1683. common: {
  1684. issues: [],
  1685. async: (params == null ? void 0 : params.async) ?? false,
  1686. contextualErrorMap: params == null ? void 0 : params.errorMap
  1687. },
  1688. path: (params == null ? void 0 : params.path) || [],
  1689. schemaErrorMap: this._def.errorMap,
  1690. parent: null,
  1691. data,
  1692. parsedType: getParsedType(data)
  1693. };
  1694. const result = this._parseSync({ data, path: ctx.path, parent: ctx });
  1695. return handleResult(ctx, result);
  1696. }
  1697. "~validate"(data) {
  1698. var _a, _b;
  1699. const ctx = {
  1700. common: {
  1701. issues: [],
  1702. async: !!this["~standard"].async
  1703. },
  1704. path: [],
  1705. schemaErrorMap: this._def.errorMap,
  1706. parent: null,
  1707. data,
  1708. parsedType: getParsedType(data)
  1709. };
  1710. if (!this["~standard"].async) {
  1711. try {
  1712. const result = this._parseSync({ data, path: [], parent: ctx });
  1713. return isValid(result) ? {
  1714. value: result.value
  1715. } : {
  1716. issues: ctx.common.issues
  1717. };
  1718. } catch (err) {
  1719. if ((_b = (_a = err == null ? void 0 : err.message) == null ? void 0 : _a.toLowerCase()) == null ? void 0 : _b.includes("encountered")) {
  1720. this["~standard"].async = true;
  1721. }
  1722. ctx.common = {
  1723. issues: [],
  1724. async: true
  1725. };
  1726. }
  1727. }
  1728. return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
  1729. value: result.value
  1730. } : {
  1731. issues: ctx.common.issues
  1732. });
  1733. }
  1734. async parseAsync(data, params) {
  1735. const result = await this.safeParseAsync(data, params);
  1736. if (result.success)
  1737. return result.data;
  1738. throw result.error;
  1739. }
  1740. async safeParseAsync(data, params) {
  1741. const ctx = {
  1742. common: {
  1743. issues: [],
  1744. contextualErrorMap: params == null ? void 0 : params.errorMap,
  1745. async: true
  1746. },
  1747. path: (params == null ? void 0 : params.path) || [],
  1748. schemaErrorMap: this._def.errorMap,
  1749. parent: null,
  1750. data,
  1751. parsedType: getParsedType(data)
  1752. };
  1753. const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
  1754. const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
  1755. return handleResult(ctx, result);
  1756. }
  1757. refine(check, message) {
  1758. const getIssueProperties = (val) => {
  1759. if (typeof message === "string" || typeof message === "undefined") {
  1760. return { message };
  1761. } else if (typeof message === "function") {
  1762. return message(val);
  1763. } else {
  1764. return message;
  1765. }
  1766. };
  1767. return this._refinement((val, ctx) => {
  1768. const result = check(val);
  1769. const setError = () => ctx.addIssue({
  1770. code: ZodIssueCode.custom,
  1771. ...getIssueProperties(val)
  1772. });
  1773. if (typeof Promise !== "undefined" && result instanceof Promise) {
  1774. return result.then((data) => {
  1775. if (!data) {
  1776. setError();
  1777. return false;
  1778. } else {
  1779. return true;
  1780. }
  1781. });
  1782. }
  1783. if (!result) {
  1784. setError();
  1785. return false;
  1786. } else {
  1787. return true;
  1788. }
  1789. });
  1790. }
  1791. refinement(check, refinementData) {
  1792. return this._refinement((val, ctx) => {
  1793. if (!check(val)) {
  1794. ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
  1795. return false;
  1796. } else {
  1797. return true;
  1798. }
  1799. });
  1800. }
  1801. _refinement(refinement) {
  1802. return new ZodEffects({
  1803. schema: this,
  1804. typeName: ZodFirstPartyTypeKind.ZodEffects,
  1805. effect: { type: "refinement", refinement }
  1806. });
  1807. }
  1808. superRefine(refinement) {
  1809. return this._refinement(refinement);
  1810. }
  1811. constructor(def) {
  1812. this.spa = this.safeParseAsync;
  1813. this._def = def;
  1814. this.parse = this.parse.bind(this);
  1815. this.safeParse = this.safeParse.bind(this);
  1816. this.parseAsync = this.parseAsync.bind(this);
  1817. this.safeParseAsync = this.safeParseAsync.bind(this);
  1818. this.spa = this.spa.bind(this);
  1819. this.refine = this.refine.bind(this);
  1820. this.refinement = this.refinement.bind(this);
  1821. this.superRefine = this.superRefine.bind(this);
  1822. this.optional = this.optional.bind(this);
  1823. this.nullable = this.nullable.bind(this);
  1824. this.nullish = this.nullish.bind(this);
  1825. this.array = this.array.bind(this);
  1826. this.promise = this.promise.bind(this);
  1827. this.or = this.or.bind(this);
  1828. this.and = this.and.bind(this);
  1829. this.transform = this.transform.bind(this);
  1830. this.brand = this.brand.bind(this);
  1831. this.default = this.default.bind(this);
  1832. this.catch = this.catch.bind(this);
  1833. this.describe = this.describe.bind(this);
  1834. this.pipe = this.pipe.bind(this);
  1835. this.readonly = this.readonly.bind(this);
  1836. this.isNullable = this.isNullable.bind(this);
  1837. this.isOptional = this.isOptional.bind(this);
  1838. this["~standard"] = {
  1839. version: 1,
  1840. vendor: "zod",
  1841. validate: (data) => this["~validate"](data)
  1842. };
  1843. }
  1844. optional() {
  1845. return ZodOptional.create(this, this._def);
  1846. }
  1847. nullable() {
  1848. return ZodNullable.create(this, this._def);
  1849. }
  1850. nullish() {
  1851. return this.nullable().optional();
  1852. }
  1853. array() {
  1854. return ZodArray.create(this);
  1855. }
  1856. promise() {
  1857. return ZodPromise.create(this, this._def);
  1858. }
  1859. or(option) {
  1860. return ZodUnion.create([this, option], this._def);
  1861. }
  1862. and(incoming) {
  1863. return ZodIntersection.create(this, incoming, this._def);
  1864. }
  1865. transform(transform) {
  1866. return new ZodEffects({
  1867. ...processCreateParams(this._def),
  1868. schema: this,
  1869. typeName: ZodFirstPartyTypeKind.ZodEffects,
  1870. effect: { type: "transform", transform }
  1871. });
  1872. }
  1873. default(def) {
  1874. const defaultValueFunc = typeof def === "function" ? def : () => def;
  1875. return new ZodDefault({
  1876. ...processCreateParams(this._def),
  1877. innerType: this,
  1878. defaultValue: defaultValueFunc,
  1879. typeName: ZodFirstPartyTypeKind.ZodDefault
  1880. });
  1881. }
  1882. brand() {
  1883. return new ZodBranded({
  1884. typeName: ZodFirstPartyTypeKind.ZodBranded,
  1885. type: this,
  1886. ...processCreateParams(this._def)
  1887. });
  1888. }
  1889. catch(def) {
  1890. const catchValueFunc = typeof def === "function" ? def : () => def;
  1891. return new ZodCatch({
  1892. ...processCreateParams(this._def),
  1893. innerType: this,
  1894. catchValue: catchValueFunc,
  1895. typeName: ZodFirstPartyTypeKind.ZodCatch
  1896. });
  1897. }
  1898. describe(description) {
  1899. const This = this.constructor;
  1900. return new This({
  1901. ...this._def,
  1902. description
  1903. });
  1904. }
  1905. pipe(target) {
  1906. return ZodPipeline.create(this, target);
  1907. }
  1908. readonly() {
  1909. return ZodReadonly.create(this);
  1910. }
  1911. isOptional() {
  1912. return this.safeParse(void 0).success;
  1913. }
  1914. isNullable() {
  1915. return this.safeParse(null).success;
  1916. }
  1917. };
  1918. var cuidRegex = /^c[^\s-]{8,}$/i;
  1919. var cuid2Regex = /^[0-9a-z]+$/;
  1920. var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
  1921. var 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;
  1922. var nanoidRegex = /^[a-z0-9_-]{21}$/i;
  1923. var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
  1924. var 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)?)??$/;
  1925. var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
  1926. var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
  1927. var emojiRegex;
  1928. var 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])$/;
  1929. var 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])$/;
  1930. var 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]))$/;
  1931. var 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])$/;
  1932. var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
  1933. var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
  1934. var 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])))`;
  1935. var dateRegex = new RegExp(`^${dateRegexSource}$`);
  1936. function timeRegexSource(args) {
  1937. let secondsRegexSource = `[0-5]\\d`;
  1938. if (args.precision) {
  1939. secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  1940. } else if (args.precision == null) {
  1941. secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  1942. }
  1943. const secondsQuantifier = args.precision ? "+" : "?";
  1944. return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
  1945. }
  1946. function timeRegex(args) {
  1947. return new RegExp(`^${timeRegexSource(args)}$`);
  1948. }
  1949. function datetimeRegex(args) {
  1950. let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  1951. const opts = [];
  1952. opts.push(args.local ? `Z?` : `Z`);
  1953. if (args.offset)
  1954. opts.push(`([+-]\\d{2}:?\\d{2})`);
  1955. regex = `${regex}(${opts.join("|")})`;
  1956. return new RegExp(`^${regex}$`);
  1957. }
  1958. function isValidIP(ip, version) {
  1959. if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
  1960. return true;
  1961. }
  1962. if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
  1963. return true;
  1964. }
  1965. return false;
  1966. }
  1967. function isValidJWT(jwt, alg) {
  1968. if (!jwtRegex.test(jwt))
  1969. return false;
  1970. try {
  1971. const [header] = jwt.split(".");
  1972. const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
  1973. const decoded = JSON.parse(atob(base64));
  1974. if (typeof decoded !== "object" || decoded === null)
  1975. return false;
  1976. if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
  1977. return false;
  1978. if (!decoded.alg)
  1979. return false;
  1980. if (alg && decoded.alg !== alg)
  1981. return false;
  1982. return true;
  1983. } catch {
  1984. return false;
  1985. }
  1986. }
  1987. function isValidCidr(ip, version) {
  1988. if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
  1989. return true;
  1990. }
  1991. if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
  1992. return true;
  1993. }
  1994. return false;
  1995. }
  1996. var ZodString = class _ZodString extends ZodType {
  1997. _parse(input) {
  1998. if (this._def.coerce) {
  1999. input.data = String(input.data);
  2000. }
  2001. const parsedType = this._getType(input);
  2002. if (parsedType !== ZodParsedType.string) {
  2003. const ctx2 = this._getOrReturnCtx(input);
  2004. addIssueToContext(ctx2, {
  2005. code: ZodIssueCode.invalid_type,
  2006. expected: ZodParsedType.string,
  2007. received: ctx2.parsedType
  2008. });
  2009. return INVALID;
  2010. }
  2011. const status = new ParseStatus();
  2012. let ctx = void 0;
  2013. for (const check of this._def.checks) {
  2014. if (check.kind === "min") {
  2015. if (input.data.length < check.value) {
  2016. ctx = this._getOrReturnCtx(input, ctx);
  2017. addIssueToContext(ctx, {
  2018. code: ZodIssueCode.too_small,
  2019. minimum: check.value,
  2020. type: "string",
  2021. inclusive: true,
  2022. exact: false,
  2023. message: check.message
  2024. });
  2025. status.dirty();
  2026. }
  2027. } else if (check.kind === "max") {
  2028. if (input.data.length > check.value) {
  2029. ctx = this._getOrReturnCtx(input, ctx);
  2030. addIssueToContext(ctx, {
  2031. code: ZodIssueCode.too_big,
  2032. maximum: check.value,
  2033. type: "string",
  2034. inclusive: true,
  2035. exact: false,
  2036. message: check.message
  2037. });
  2038. status.dirty();
  2039. }
  2040. } else if (check.kind === "length") {
  2041. const tooBig = input.data.length > check.value;
  2042. const tooSmall = input.data.length < check.value;
  2043. if (tooBig || tooSmall) {
  2044. ctx = this._getOrReturnCtx(input, ctx);
  2045. if (tooBig) {
  2046. addIssueToContext(ctx, {
  2047. code: ZodIssueCode.too_big,
  2048. maximum: check.value,
  2049. type: "string",
  2050. inclusive: true,
  2051. exact: true,
  2052. message: check.message
  2053. });
  2054. } else if (tooSmall) {
  2055. addIssueToContext(ctx, {
  2056. code: ZodIssueCode.too_small,
  2057. minimum: check.value,
  2058. type: "string",
  2059. inclusive: true,
  2060. exact: true,
  2061. message: check.message
  2062. });
  2063. }
  2064. status.dirty();
  2065. }
  2066. } else if (check.kind === "email") {
  2067. if (!emailRegex.test(input.data)) {
  2068. ctx = this._getOrReturnCtx(input, ctx);
  2069. addIssueToContext(ctx, {
  2070. validation: "email",
  2071. code: ZodIssueCode.invalid_string,
  2072. message: check.message
  2073. });
  2074. status.dirty();
  2075. }
  2076. } else if (check.kind === "emoji") {
  2077. if (!emojiRegex) {
  2078. emojiRegex = new RegExp(_emojiRegex, "u");
  2079. }
  2080. if (!emojiRegex.test(input.data)) {
  2081. ctx = this._getOrReturnCtx(input, ctx);
  2082. addIssueToContext(ctx, {
  2083. validation: "emoji",
  2084. code: ZodIssueCode.invalid_string,
  2085. message: check.message
  2086. });
  2087. status.dirty();
  2088. }
  2089. } else if (check.kind === "uuid") {
  2090. if (!uuidRegex.test(input.data)) {
  2091. ctx = this._getOrReturnCtx(input, ctx);
  2092. addIssueToContext(ctx, {
  2093. validation: "uuid",
  2094. code: ZodIssueCode.invalid_string,
  2095. message: check.message
  2096. });
  2097. status.dirty();
  2098. }
  2099. } else if (check.kind === "nanoid") {
  2100. if (!nanoidRegex.test(input.data)) {
  2101. ctx = this._getOrReturnCtx(input, ctx);
  2102. addIssueToContext(ctx, {
  2103. validation: "nanoid",
  2104. code: ZodIssueCode.invalid_string,
  2105. message: check.message
  2106. });
  2107. status.dirty();
  2108. }
  2109. } else if (check.kind === "cuid") {
  2110. if (!cuidRegex.test(input.data)) {
  2111. ctx = this._getOrReturnCtx(input, ctx);
  2112. addIssueToContext(ctx, {
  2113. validation: "cuid",
  2114. code: ZodIssueCode.invalid_string,
  2115. message: check.message
  2116. });
  2117. status.dirty();
  2118. }
  2119. } else if (check.kind === "cuid2") {
  2120. if (!cuid2Regex.test(input.data)) {
  2121. ctx = this._getOrReturnCtx(input, ctx);
  2122. addIssueToContext(ctx, {
  2123. validation: "cuid2",
  2124. code: ZodIssueCode.invalid_string,
  2125. message: check.message
  2126. });
  2127. status.dirty();
  2128. }
  2129. } else if (check.kind === "ulid") {
  2130. if (!ulidRegex.test(input.data)) {
  2131. ctx = this._getOrReturnCtx(input, ctx);
  2132. addIssueToContext(ctx, {
  2133. validation: "ulid",
  2134. code: ZodIssueCode.invalid_string,
  2135. message: check.message
  2136. });
  2137. status.dirty();
  2138. }
  2139. } else if (check.kind === "url") {
  2140. try {
  2141. new URL(input.data);
  2142. } catch {
  2143. ctx = this._getOrReturnCtx(input, ctx);
  2144. addIssueToContext(ctx, {
  2145. validation: "url",
  2146. code: ZodIssueCode.invalid_string,
  2147. message: check.message
  2148. });
  2149. status.dirty();
  2150. }
  2151. } else if (check.kind === "regex") {
  2152. check.regex.lastIndex = 0;
  2153. const testResult = check.regex.test(input.data);
  2154. if (!testResult) {
  2155. ctx = this._getOrReturnCtx(input, ctx);
  2156. addIssueToContext(ctx, {
  2157. validation: "regex",
  2158. code: ZodIssueCode.invalid_string,
  2159. message: check.message
  2160. });
  2161. status.dirty();
  2162. }
  2163. } else if (check.kind === "trim") {
  2164. input.data = input.data.trim();
  2165. } else if (check.kind === "includes") {
  2166. if (!input.data.includes(check.value, check.position)) {
  2167. ctx = this._getOrReturnCtx(input, ctx);
  2168. addIssueToContext(ctx, {
  2169. code: ZodIssueCode.invalid_string,
  2170. validation: { includes: check.value, position: check.position },
  2171. message: check.message
  2172. });
  2173. status.dirty();
  2174. }
  2175. } else if (check.kind === "toLowerCase") {
  2176. input.data = input.data.toLowerCase();
  2177. } else if (check.kind === "toUpperCase") {
  2178. input.data = input.data.toUpperCase();
  2179. } else if (check.kind === "startsWith") {
  2180. if (!input.data.startsWith(check.value)) {
  2181. ctx = this._getOrReturnCtx(input, ctx);
  2182. addIssueToContext(ctx, {
  2183. code: ZodIssueCode.invalid_string,
  2184. validation: { startsWith: check.value },
  2185. message: check.message
  2186. });
  2187. status.dirty();
  2188. }
  2189. } else if (check.kind === "endsWith") {
  2190. if (!input.data.endsWith(check.value)) {
  2191. ctx = this._getOrReturnCtx(input, ctx);
  2192. addIssueToContext(ctx, {
  2193. code: ZodIssueCode.invalid_string,
  2194. validation: { endsWith: check.value },
  2195. message: check.message
  2196. });
  2197. status.dirty();
  2198. }
  2199. } else if (check.kind === "datetime") {
  2200. const regex = datetimeRegex(check);
  2201. if (!regex.test(input.data)) {
  2202. ctx = this._getOrReturnCtx(input, ctx);
  2203. addIssueToContext(ctx, {
  2204. code: ZodIssueCode.invalid_string,
  2205. validation: "datetime",
  2206. message: check.message
  2207. });
  2208. status.dirty();
  2209. }
  2210. } else if (check.kind === "date") {
  2211. const regex = dateRegex;
  2212. if (!regex.test(input.data)) {
  2213. ctx = this._getOrReturnCtx(input, ctx);
  2214. addIssueToContext(ctx, {
  2215. code: ZodIssueCode.invalid_string,
  2216. validation: "date",
  2217. message: check.message
  2218. });
  2219. status.dirty();
  2220. }
  2221. } else if (check.kind === "time") {
  2222. const regex = timeRegex(check);
  2223. if (!regex.test(input.data)) {
  2224. ctx = this._getOrReturnCtx(input, ctx);
  2225. addIssueToContext(ctx, {
  2226. code: ZodIssueCode.invalid_string,
  2227. validation: "time",
  2228. message: check.message
  2229. });
  2230. status.dirty();
  2231. }
  2232. } else if (check.kind === "duration") {
  2233. if (!durationRegex.test(input.data)) {
  2234. ctx = this._getOrReturnCtx(input, ctx);
  2235. addIssueToContext(ctx, {
  2236. validation: "duration",
  2237. code: ZodIssueCode.invalid_string,
  2238. message: check.message
  2239. });
  2240. status.dirty();
  2241. }
  2242. } else if (check.kind === "ip") {
  2243. if (!isValidIP(input.data, check.version)) {
  2244. ctx = this._getOrReturnCtx(input, ctx);
  2245. addIssueToContext(ctx, {
  2246. validation: "ip",
  2247. code: ZodIssueCode.invalid_string,
  2248. message: check.message
  2249. });
  2250. status.dirty();
  2251. }
  2252. } else if (check.kind === "jwt") {
  2253. if (!isValidJWT(input.data, check.alg)) {
  2254. ctx = this._getOrReturnCtx(input, ctx);
  2255. addIssueToContext(ctx, {
  2256. validation: "jwt",
  2257. code: ZodIssueCode.invalid_string,
  2258. message: check.message
  2259. });
  2260. status.dirty();
  2261. }
  2262. } else if (check.kind === "cidr") {
  2263. if (!isValidCidr(input.data, check.version)) {
  2264. ctx = this._getOrReturnCtx(input, ctx);
  2265. addIssueToContext(ctx, {
  2266. validation: "cidr",
  2267. code: ZodIssueCode.invalid_string,
  2268. message: check.message
  2269. });
  2270. status.dirty();
  2271. }
  2272. } else if (check.kind === "base64") {
  2273. if (!base64Regex.test(input.data)) {
  2274. ctx = this._getOrReturnCtx(input, ctx);
  2275. addIssueToContext(ctx, {
  2276. validation: "base64",
  2277. code: ZodIssueCode.invalid_string,
  2278. message: check.message
  2279. });
  2280. status.dirty();
  2281. }
  2282. } else if (check.kind === "base64url") {
  2283. if (!base64urlRegex.test(input.data)) {
  2284. ctx = this._getOrReturnCtx(input, ctx);
  2285. addIssueToContext(ctx, {
  2286. validation: "base64url",
  2287. code: ZodIssueCode.invalid_string,
  2288. message: check.message
  2289. });
  2290. status.dirty();
  2291. }
  2292. } else {
  2293. util.assertNever(check);
  2294. }
  2295. }
  2296. return { status: status.value, value: input.data };
  2297. }
  2298. _regex(regex, validation, message) {
  2299. return this.refinement((data) => regex.test(data), {
  2300. validation,
  2301. code: ZodIssueCode.invalid_string,
  2302. ...errorUtil.errToObj(message)
  2303. });
  2304. }
  2305. _addCheck(check) {
  2306. return new _ZodString({
  2307. ...this._def,
  2308. checks: [...this._def.checks, check]
  2309. });
  2310. }
  2311. email(message) {
  2312. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  2313. }
  2314. url(message) {
  2315. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  2316. }
  2317. emoji(message) {
  2318. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  2319. }
  2320. uuid(message) {
  2321. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  2322. }
  2323. nanoid(message) {
  2324. return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  2325. }
  2326. cuid(message) {
  2327. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  2328. }
  2329. cuid2(message) {
  2330. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  2331. }
  2332. ulid(message) {
  2333. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  2334. }
  2335. base64(message) {
  2336. return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  2337. }
  2338. base64url(message) {
  2339. return this._addCheck({
  2340. kind: "base64url",
  2341. ...errorUtil.errToObj(message)
  2342. });
  2343. }
  2344. jwt(options) {
  2345. return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  2346. }
  2347. ip(options) {
  2348. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  2349. }
  2350. cidr(options) {
  2351. return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  2352. }
  2353. datetime(options) {
  2354. if (typeof options === "string") {
  2355. return this._addCheck({
  2356. kind: "datetime",
  2357. precision: null,
  2358. offset: false,
  2359. local: false,
  2360. message: options
  2361. });
  2362. }
  2363. return this._addCheck({
  2364. kind: "datetime",
  2365. precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
  2366. offset: (options == null ? void 0 : options.offset) ?? false,
  2367. local: (options == null ? void 0 : options.local) ?? false,
  2368. ...errorUtil.errToObj(options == null ? void 0 : options.message)
  2369. });
  2370. }
  2371. date(message) {
  2372. return this._addCheck({ kind: "date", message });
  2373. }
  2374. time(options) {
  2375. if (typeof options === "string") {
  2376. return this._addCheck({
  2377. kind: "time",
  2378. precision: null,
  2379. message: options
  2380. });
  2381. }
  2382. return this._addCheck({
  2383. kind: "time",
  2384. precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
  2385. ...errorUtil.errToObj(options == null ? void 0 : options.message)
  2386. });
  2387. }
  2388. duration(message) {
  2389. return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  2390. }
  2391. regex(regex, message) {
  2392. return this._addCheck({
  2393. kind: "regex",
  2394. regex,
  2395. ...errorUtil.errToObj(message)
  2396. });
  2397. }
  2398. includes(value, options) {
  2399. return this._addCheck({
  2400. kind: "includes",
  2401. value,
  2402. position: options == null ? void 0 : options.position,
  2403. ...errorUtil.errToObj(options == null ? void 0 : options.message)
  2404. });
  2405. }
  2406. startsWith(value, message) {
  2407. return this._addCheck({
  2408. kind: "startsWith",
  2409. value,
  2410. ...errorUtil.errToObj(message)
  2411. });
  2412. }
  2413. endsWith(value, message) {
  2414. return this._addCheck({
  2415. kind: "endsWith",
  2416. value,
  2417. ...errorUtil.errToObj(message)
  2418. });
  2419. }
  2420. min(minLength, message) {
  2421. return this._addCheck({
  2422. kind: "min",
  2423. value: minLength,
  2424. ...errorUtil.errToObj(message)
  2425. });
  2426. }
  2427. max(maxLength, message) {
  2428. return this._addCheck({
  2429. kind: "max",
  2430. value: maxLength,
  2431. ...errorUtil.errToObj(message)
  2432. });
  2433. }
  2434. length(len, message) {
  2435. return this._addCheck({
  2436. kind: "length",
  2437. value: len,
  2438. ...errorUtil.errToObj(message)
  2439. });
  2440. }
  2441. /**
  2442. * Equivalent to `.min(1)`
  2443. */
  2444. nonempty(message) {
  2445. return this.min(1, errorUtil.errToObj(message));
  2446. }
  2447. trim() {
  2448. return new _ZodString({
  2449. ...this._def,
  2450. checks: [...this._def.checks, { kind: "trim" }]
  2451. });
  2452. }
  2453. toLowerCase() {
  2454. return new _ZodString({
  2455. ...this._def,
  2456. checks: [...this._def.checks, { kind: "toLowerCase" }]
  2457. });
  2458. }
  2459. toUpperCase() {
  2460. return new _ZodString({
  2461. ...this._def,
  2462. checks: [...this._def.checks, { kind: "toUpperCase" }]
  2463. });
  2464. }
  2465. get isDatetime() {
  2466. return !!this._def.checks.find((ch) => ch.kind === "datetime");
  2467. }
  2468. get isDate() {
  2469. return !!this._def.checks.find((ch) => ch.kind === "date");
  2470. }
  2471. get isTime() {
  2472. return !!this._def.checks.find((ch) => ch.kind === "time");
  2473. }
  2474. get isDuration() {
  2475. return !!this._def.checks.find((ch) => ch.kind === "duration");
  2476. }
  2477. get isEmail() {
  2478. return !!this._def.checks.find((ch) => ch.kind === "email");
  2479. }
  2480. get isURL() {
  2481. return !!this._def.checks.find((ch) => ch.kind === "url");
  2482. }
  2483. get isEmoji() {
  2484. return !!this._def.checks.find((ch) => ch.kind === "emoji");
  2485. }
  2486. get isUUID() {
  2487. return !!this._def.checks.find((ch) => ch.kind === "uuid");
  2488. }
  2489. get isNANOID() {
  2490. return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  2491. }
  2492. get isCUID() {
  2493. return !!this._def.checks.find((ch) => ch.kind === "cuid");
  2494. }
  2495. get isCUID2() {
  2496. return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  2497. }
  2498. get isULID() {
  2499. return !!this._def.checks.find((ch) => ch.kind === "ulid");
  2500. }
  2501. get isIP() {
  2502. return !!this._def.checks.find((ch) => ch.kind === "ip");
  2503. }
  2504. get isCIDR() {
  2505. return !!this._def.checks.find((ch) => ch.kind === "cidr");
  2506. }
  2507. get isBase64() {
  2508. return !!this._def.checks.find((ch) => ch.kind === "base64");
  2509. }
  2510. get isBase64url() {
  2511. return !!this._def.checks.find((ch) => ch.kind === "base64url");
  2512. }
  2513. get minLength() {
  2514. let min = null;
  2515. for (const ch of this._def.checks) {
  2516. if (ch.kind === "min") {
  2517. if (min === null || ch.value > min)
  2518. min = ch.value;
  2519. }
  2520. }
  2521. return min;
  2522. }
  2523. get maxLength() {
  2524. let max = null;
  2525. for (const ch of this._def.checks) {
  2526. if (ch.kind === "max") {
  2527. if (max === null || ch.value < max)
  2528. max = ch.value;
  2529. }
  2530. }
  2531. return max;
  2532. }
  2533. };
  2534. ZodString.create = (params) => {
  2535. return new ZodString({
  2536. checks: [],
  2537. typeName: ZodFirstPartyTypeKind.ZodString,
  2538. coerce: (params == null ? void 0 : params.coerce) ?? false,
  2539. ...processCreateParams(params)
  2540. });
  2541. };
  2542. function floatSafeRemainder(val, step) {
  2543. const valDecCount = (val.toString().split(".")[1] || "").length;
  2544. const stepDecCount = (step.toString().split(".")[1] || "").length;
  2545. const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  2546. const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  2547. const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  2548. return valInt % stepInt / 10 ** decCount;
  2549. }
  2550. var ZodNumber = class _ZodNumber extends ZodType {
  2551. constructor() {
  2552. super(...arguments);
  2553. this.min = this.gte;
  2554. this.max = this.lte;
  2555. this.step = this.multipleOf;
  2556. }
  2557. _parse(input) {
  2558. if (this._def.coerce) {
  2559. input.data = Number(input.data);
  2560. }
  2561. const parsedType = this._getType(input);
  2562. if (parsedType !== ZodParsedType.number) {
  2563. const ctx2 = this._getOrReturnCtx(input);
  2564. addIssueToContext(ctx2, {
  2565. code: ZodIssueCode.invalid_type,
  2566. expected: ZodParsedType.number,
  2567. received: ctx2.parsedType
  2568. });
  2569. return INVALID;
  2570. }
  2571. let ctx = void 0;
  2572. const status = new ParseStatus();
  2573. for (const check of this._def.checks) {
  2574. if (check.kind === "int") {
  2575. if (!util.isInteger(input.data)) {
  2576. ctx = this._getOrReturnCtx(input, ctx);
  2577. addIssueToContext(ctx, {
  2578. code: ZodIssueCode.invalid_type,
  2579. expected: "integer",
  2580. received: "float",
  2581. message: check.message
  2582. });
  2583. status.dirty();
  2584. }
  2585. } else if (check.kind === "min") {
  2586. const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
  2587. if (tooSmall) {
  2588. ctx = this._getOrReturnCtx(input, ctx);
  2589. addIssueToContext(ctx, {
  2590. code: ZodIssueCode.too_small,
  2591. minimum: check.value,
  2592. type: "number",
  2593. inclusive: check.inclusive,
  2594. exact: false,
  2595. message: check.message
  2596. });
  2597. status.dirty();
  2598. }
  2599. } else if (check.kind === "max") {
  2600. const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
  2601. if (tooBig) {
  2602. ctx = this._getOrReturnCtx(input, ctx);
  2603. addIssueToContext(ctx, {
  2604. code: ZodIssueCode.too_big,
  2605. maximum: check.value,
  2606. type: "number",
  2607. inclusive: check.inclusive,
  2608. exact: false,
  2609. message: check.message
  2610. });
  2611. status.dirty();
  2612. }
  2613. } else if (check.kind === "multipleOf") {
  2614. if (floatSafeRemainder(input.data, check.value) !== 0) {
  2615. ctx = this._getOrReturnCtx(input, ctx);
  2616. addIssueToContext(ctx, {
  2617. code: ZodIssueCode.not_multiple_of,
  2618. multipleOf: check.value,
  2619. message: check.message
  2620. });
  2621. status.dirty();
  2622. }
  2623. } else if (check.kind === "finite") {
  2624. if (!Number.isFinite(input.data)) {
  2625. ctx = this._getOrReturnCtx(input, ctx);
  2626. addIssueToContext(ctx, {
  2627. code: ZodIssueCode.not_finite,
  2628. message: check.message
  2629. });
  2630. status.dirty();
  2631. }
  2632. } else {
  2633. util.assertNever(check);
  2634. }
  2635. }
  2636. return { status: status.value, value: input.data };
  2637. }
  2638. gte(value, message) {
  2639. return this.setLimit("min", value, true, errorUtil.toString(message));
  2640. }
  2641. gt(value, message) {
  2642. return this.setLimit("min", value, false, errorUtil.toString(message));
  2643. }
  2644. lte(value, message) {
  2645. return this.setLimit("max", value, true, errorUtil.toString(message));
  2646. }
  2647. lt(value, message) {
  2648. return this.setLimit("max", value, false, errorUtil.toString(message));
  2649. }
  2650. setLimit(kind, value, inclusive, message) {
  2651. return new _ZodNumber({
  2652. ...this._def,
  2653. checks: [
  2654. ...this._def.checks,
  2655. {
  2656. kind,
  2657. value,
  2658. inclusive,
  2659. message: errorUtil.toString(message)
  2660. }
  2661. ]
  2662. });
  2663. }
  2664. _addCheck(check) {
  2665. return new _ZodNumber({
  2666. ...this._def,
  2667. checks: [...this._def.checks, check]
  2668. });
  2669. }
  2670. int(message) {
  2671. return this._addCheck({
  2672. kind: "int",
  2673. message: errorUtil.toString(message)
  2674. });
  2675. }
  2676. positive(message) {
  2677. return this._addCheck({
  2678. kind: "min",
  2679. value: 0,
  2680. inclusive: false,
  2681. message: errorUtil.toString(message)
  2682. });
  2683. }
  2684. negative(message) {
  2685. return this._addCheck({
  2686. kind: "max",
  2687. value: 0,
  2688. inclusive: false,
  2689. message: errorUtil.toString(message)
  2690. });
  2691. }
  2692. nonpositive(message) {
  2693. return this._addCheck({
  2694. kind: "max",
  2695. value: 0,
  2696. inclusive: true,
  2697. message: errorUtil.toString(message)
  2698. });
  2699. }
  2700. nonnegative(message) {
  2701. return this._addCheck({
  2702. kind: "min",
  2703. value: 0,
  2704. inclusive: true,
  2705. message: errorUtil.toString(message)
  2706. });
  2707. }
  2708. multipleOf(value, message) {
  2709. return this._addCheck({
  2710. kind: "multipleOf",
  2711. value,
  2712. message: errorUtil.toString(message)
  2713. });
  2714. }
  2715. finite(message) {
  2716. return this._addCheck({
  2717. kind: "finite",
  2718. message: errorUtil.toString(message)
  2719. });
  2720. }
  2721. safe(message) {
  2722. return this._addCheck({
  2723. kind: "min",
  2724. inclusive: true,
  2725. value: Number.MIN_SAFE_INTEGER,
  2726. message: errorUtil.toString(message)
  2727. })._addCheck({
  2728. kind: "max",
  2729. inclusive: true,
  2730. value: Number.MAX_SAFE_INTEGER,
  2731. message: errorUtil.toString(message)
  2732. });
  2733. }
  2734. get minValue() {
  2735. let min = null;
  2736. for (const ch of this._def.checks) {
  2737. if (ch.kind === "min") {
  2738. if (min === null || ch.value > min)
  2739. min = ch.value;
  2740. }
  2741. }
  2742. return min;
  2743. }
  2744. get maxValue() {
  2745. let max = null;
  2746. for (const ch of this._def.checks) {
  2747. if (ch.kind === "max") {
  2748. if (max === null || ch.value < max)
  2749. max = ch.value;
  2750. }
  2751. }
  2752. return max;
  2753. }
  2754. get isInt() {
  2755. return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  2756. }
  2757. get isFinite() {
  2758. let max = null;
  2759. let min = null;
  2760. for (const ch of this._def.checks) {
  2761. if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
  2762. return true;
  2763. } else if (ch.kind === "min") {
  2764. if (min === null || ch.value > min)
  2765. min = ch.value;
  2766. } else if (ch.kind === "max") {
  2767. if (max === null || ch.value < max)
  2768. max = ch.value;
  2769. }
  2770. }
  2771. return Number.isFinite(min) && Number.isFinite(max);
  2772. }
  2773. };
  2774. ZodNumber.create = (params) => {
  2775. return new ZodNumber({
  2776. checks: [],
  2777. typeName: ZodFirstPartyTypeKind.ZodNumber,
  2778. coerce: (params == null ? void 0 : params.coerce) || false,
  2779. ...processCreateParams(params)
  2780. });
  2781. };
  2782. var ZodBigInt = class _ZodBigInt extends ZodType {
  2783. constructor() {
  2784. super(...arguments);
  2785. this.min = this.gte;
  2786. this.max = this.lte;
  2787. }
  2788. _parse(input) {
  2789. if (this._def.coerce) {
  2790. try {
  2791. input.data = BigInt(input.data);
  2792. } catch {
  2793. return this._getInvalidInput(input);
  2794. }
  2795. }
  2796. const parsedType = this._getType(input);
  2797. if (parsedType !== ZodParsedType.bigint) {
  2798. return this._getInvalidInput(input);
  2799. }
  2800. let ctx = void 0;
  2801. const status = new ParseStatus();
  2802. for (const check of this._def.checks) {
  2803. if (check.kind === "min") {
  2804. const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
  2805. if (tooSmall) {
  2806. ctx = this._getOrReturnCtx(input, ctx);
  2807. addIssueToContext(ctx, {
  2808. code: ZodIssueCode.too_small,
  2809. type: "bigint",
  2810. minimum: check.value,
  2811. inclusive: check.inclusive,
  2812. message: check.message
  2813. });
  2814. status.dirty();
  2815. }
  2816. } else if (check.kind === "max") {
  2817. const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
  2818. if (tooBig) {
  2819. ctx = this._getOrReturnCtx(input, ctx);
  2820. addIssueToContext(ctx, {
  2821. code: ZodIssueCode.too_big,
  2822. type: "bigint",
  2823. maximum: check.value,
  2824. inclusive: check.inclusive,
  2825. message: check.message
  2826. });
  2827. status.dirty();
  2828. }
  2829. } else if (check.kind === "multipleOf") {
  2830. if (input.data % check.value !== BigInt(0)) {
  2831. ctx = this._getOrReturnCtx(input, ctx);
  2832. addIssueToContext(ctx, {
  2833. code: ZodIssueCode.not_multiple_of,
  2834. multipleOf: check.value,
  2835. message: check.message
  2836. });
  2837. status.dirty();
  2838. }
  2839. } else {
  2840. util.assertNever(check);
  2841. }
  2842. }
  2843. return { status: status.value, value: input.data };
  2844. }
  2845. _getInvalidInput(input) {
  2846. const ctx = this._getOrReturnCtx(input);
  2847. addIssueToContext(ctx, {
  2848. code: ZodIssueCode.invalid_type,
  2849. expected: ZodParsedType.bigint,
  2850. received: ctx.parsedType
  2851. });
  2852. return INVALID;
  2853. }
  2854. gte(value, message) {
  2855. return this.setLimit("min", value, true, errorUtil.toString(message));
  2856. }
  2857. gt(value, message) {
  2858. return this.setLimit("min", value, false, errorUtil.toString(message));
  2859. }
  2860. lte(value, message) {
  2861. return this.setLimit("max", value, true, errorUtil.toString(message));
  2862. }
  2863. lt(value, message) {
  2864. return this.setLimit("max", value, false, errorUtil.toString(message));
  2865. }
  2866. setLimit(kind, value, inclusive, message) {
  2867. return new _ZodBigInt({
  2868. ...this._def,
  2869. checks: [
  2870. ...this._def.checks,
  2871. {
  2872. kind,
  2873. value,
  2874. inclusive,
  2875. message: errorUtil.toString(message)
  2876. }
  2877. ]
  2878. });
  2879. }
  2880. _addCheck(check) {
  2881. return new _ZodBigInt({
  2882. ...this._def,
  2883. checks: [...this._def.checks, check]
  2884. });
  2885. }
  2886. positive(message) {
  2887. return this._addCheck({
  2888. kind: "min",
  2889. value: BigInt(0),
  2890. inclusive: false,
  2891. message: errorUtil.toString(message)
  2892. });
  2893. }
  2894. negative(message) {
  2895. return this._addCheck({
  2896. kind: "max",
  2897. value: BigInt(0),
  2898. inclusive: false,
  2899. message: errorUtil.toString(message)
  2900. });
  2901. }
  2902. nonpositive(message) {
  2903. return this._addCheck({
  2904. kind: "max",
  2905. value: BigInt(0),
  2906. inclusive: true,
  2907. message: errorUtil.toString(message)
  2908. });
  2909. }
  2910. nonnegative(message) {
  2911. return this._addCheck({
  2912. kind: "min",
  2913. value: BigInt(0),
  2914. inclusive: true,
  2915. message: errorUtil.toString(message)
  2916. });
  2917. }
  2918. multipleOf(value, message) {
  2919. return this._addCheck({
  2920. kind: "multipleOf",
  2921. value,
  2922. message: errorUtil.toString(message)
  2923. });
  2924. }
  2925. get minValue() {
  2926. let min = null;
  2927. for (const ch of this._def.checks) {
  2928. if (ch.kind === "min") {
  2929. if (min === null || ch.value > min)
  2930. min = ch.value;
  2931. }
  2932. }
  2933. return min;
  2934. }
  2935. get maxValue() {
  2936. let max = null;
  2937. for (const ch of this._def.checks) {
  2938. if (ch.kind === "max") {
  2939. if (max === null || ch.value < max)
  2940. max = ch.value;
  2941. }
  2942. }
  2943. return max;
  2944. }
  2945. };
  2946. ZodBigInt.create = (params) => {
  2947. return new ZodBigInt({
  2948. checks: [],
  2949. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  2950. coerce: (params == null ? void 0 : params.coerce) ?? false,
  2951. ...processCreateParams(params)
  2952. });
  2953. };
  2954. var ZodBoolean = class extends ZodType {
  2955. _parse(input) {
  2956. if (this._def.coerce) {
  2957. input.data = Boolean(input.data);
  2958. }
  2959. const parsedType = this._getType(input);
  2960. if (parsedType !== ZodParsedType.boolean) {
  2961. const ctx = this._getOrReturnCtx(input);
  2962. addIssueToContext(ctx, {
  2963. code: ZodIssueCode.invalid_type,
  2964. expected: ZodParsedType.boolean,
  2965. received: ctx.parsedType
  2966. });
  2967. return INVALID;
  2968. }
  2969. return OK(input.data);
  2970. }
  2971. };
  2972. ZodBoolean.create = (params) => {
  2973. return new ZodBoolean({
  2974. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  2975. coerce: (params == null ? void 0 : params.coerce) || false,
  2976. ...processCreateParams(params)
  2977. });
  2978. };
  2979. var ZodDate = class _ZodDate extends ZodType {
  2980. _parse(input) {
  2981. if (this._def.coerce) {
  2982. input.data = new Date(input.data);
  2983. }
  2984. const parsedType = this._getType(input);
  2985. if (parsedType !== ZodParsedType.date) {
  2986. const ctx2 = this._getOrReturnCtx(input);
  2987. addIssueToContext(ctx2, {
  2988. code: ZodIssueCode.invalid_type,
  2989. expected: ZodParsedType.date,
  2990. received: ctx2.parsedType
  2991. });
  2992. return INVALID;
  2993. }
  2994. if (Number.isNaN(input.data.getTime())) {
  2995. const ctx2 = this._getOrReturnCtx(input);
  2996. addIssueToContext(ctx2, {
  2997. code: ZodIssueCode.invalid_date
  2998. });
  2999. return INVALID;
  3000. }
  3001. const status = new ParseStatus();
  3002. let ctx = void 0;
  3003. for (const check of this._def.checks) {
  3004. if (check.kind === "min") {
  3005. if (input.data.getTime() < check.value) {
  3006. ctx = this._getOrReturnCtx(input, ctx);
  3007. addIssueToContext(ctx, {
  3008. code: ZodIssueCode.too_small,
  3009. message: check.message,
  3010. inclusive: true,
  3011. exact: false,
  3012. minimum: check.value,
  3013. type: "date"
  3014. });
  3015. status.dirty();
  3016. }
  3017. } else if (check.kind === "max") {
  3018. if (input.data.getTime() > check.value) {
  3019. ctx = this._getOrReturnCtx(input, ctx);
  3020. addIssueToContext(ctx, {
  3021. code: ZodIssueCode.too_big,
  3022. message: check.message,
  3023. inclusive: true,
  3024. exact: false,
  3025. maximum: check.value,
  3026. type: "date"
  3027. });
  3028. status.dirty();
  3029. }
  3030. } else {
  3031. util.assertNever(check);
  3032. }
  3033. }
  3034. return {
  3035. status: status.value,
  3036. value: new Date(input.data.getTime())
  3037. };
  3038. }
  3039. _addCheck(check) {
  3040. return new _ZodDate({
  3041. ...this._def,
  3042. checks: [...this._def.checks, check]
  3043. });
  3044. }
  3045. min(minDate, message) {
  3046. return this._addCheck({
  3047. kind: "min",
  3048. value: minDate.getTime(),
  3049. message: errorUtil.toString(message)
  3050. });
  3051. }
  3052. max(maxDate, message) {
  3053. return this._addCheck({
  3054. kind: "max",
  3055. value: maxDate.getTime(),
  3056. message: errorUtil.toString(message)
  3057. });
  3058. }
  3059. get minDate() {
  3060. let min = null;
  3061. for (const ch of this._def.checks) {
  3062. if (ch.kind === "min") {
  3063. if (min === null || ch.value > min)
  3064. min = ch.value;
  3065. }
  3066. }
  3067. return min != null ? new Date(min) : null;
  3068. }
  3069. get maxDate() {
  3070. let max = null;
  3071. for (const ch of this._def.checks) {
  3072. if (ch.kind === "max") {
  3073. if (max === null || ch.value < max)
  3074. max = ch.value;
  3075. }
  3076. }
  3077. return max != null ? new Date(max) : null;
  3078. }
  3079. };
  3080. ZodDate.create = (params) => {
  3081. return new ZodDate({
  3082. checks: [],
  3083. coerce: (params == null ? void 0 : params.coerce) || false,
  3084. typeName: ZodFirstPartyTypeKind.ZodDate,
  3085. ...processCreateParams(params)
  3086. });
  3087. };
  3088. var ZodSymbol = class extends ZodType {
  3089. _parse(input) {
  3090. const parsedType = this._getType(input);
  3091. if (parsedType !== ZodParsedType.symbol) {
  3092. const ctx = this._getOrReturnCtx(input);
  3093. addIssueToContext(ctx, {
  3094. code: ZodIssueCode.invalid_type,
  3095. expected: ZodParsedType.symbol,
  3096. received: ctx.parsedType
  3097. });
  3098. return INVALID;
  3099. }
  3100. return OK(input.data);
  3101. }
  3102. };
  3103. ZodSymbol.create = (params) => {
  3104. return new ZodSymbol({
  3105. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  3106. ...processCreateParams(params)
  3107. });
  3108. };
  3109. var ZodUndefined = class extends ZodType {
  3110. _parse(input) {
  3111. const parsedType = this._getType(input);
  3112. if (parsedType !== ZodParsedType.undefined) {
  3113. const ctx = this._getOrReturnCtx(input);
  3114. addIssueToContext(ctx, {
  3115. code: ZodIssueCode.invalid_type,
  3116. expected: ZodParsedType.undefined,
  3117. received: ctx.parsedType
  3118. });
  3119. return INVALID;
  3120. }
  3121. return OK(input.data);
  3122. }
  3123. };
  3124. ZodUndefined.create = (params) => {
  3125. return new ZodUndefined({
  3126. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  3127. ...processCreateParams(params)
  3128. });
  3129. };
  3130. var ZodNull = class extends ZodType {
  3131. _parse(input) {
  3132. const parsedType = this._getType(input);
  3133. if (parsedType !== ZodParsedType.null) {
  3134. const ctx = this._getOrReturnCtx(input);
  3135. addIssueToContext(ctx, {
  3136. code: ZodIssueCode.invalid_type,
  3137. expected: ZodParsedType.null,
  3138. received: ctx.parsedType
  3139. });
  3140. return INVALID;
  3141. }
  3142. return OK(input.data);
  3143. }
  3144. };
  3145. ZodNull.create = (params) => {
  3146. return new ZodNull({
  3147. typeName: ZodFirstPartyTypeKind.ZodNull,
  3148. ...processCreateParams(params)
  3149. });
  3150. };
  3151. var ZodAny = class extends ZodType {
  3152. constructor() {
  3153. super(...arguments);
  3154. this._any = true;
  3155. }
  3156. _parse(input) {
  3157. return OK(input.data);
  3158. }
  3159. };
  3160. ZodAny.create = (params) => {
  3161. return new ZodAny({
  3162. typeName: ZodFirstPartyTypeKind.ZodAny,
  3163. ...processCreateParams(params)
  3164. });
  3165. };
  3166. var ZodUnknown = class extends ZodType {
  3167. constructor() {
  3168. super(...arguments);
  3169. this._unknown = true;
  3170. }
  3171. _parse(input) {
  3172. return OK(input.data);
  3173. }
  3174. };
  3175. ZodUnknown.create = (params) => {
  3176. return new ZodUnknown({
  3177. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  3178. ...processCreateParams(params)
  3179. });
  3180. };
  3181. var ZodNever = class extends ZodType {
  3182. _parse(input) {
  3183. const ctx = this._getOrReturnCtx(input);
  3184. addIssueToContext(ctx, {
  3185. code: ZodIssueCode.invalid_type,
  3186. expected: ZodParsedType.never,
  3187. received: ctx.parsedType
  3188. });
  3189. return INVALID;
  3190. }
  3191. };
  3192. ZodNever.create = (params) => {
  3193. return new ZodNever({
  3194. typeName: ZodFirstPartyTypeKind.ZodNever,
  3195. ...processCreateParams(params)
  3196. });
  3197. };
  3198. var ZodVoid = class extends ZodType {
  3199. _parse(input) {
  3200. const parsedType = this._getType(input);
  3201. if (parsedType !== ZodParsedType.undefined) {
  3202. const ctx = this._getOrReturnCtx(input);
  3203. addIssueToContext(ctx, {
  3204. code: ZodIssueCode.invalid_type,
  3205. expected: ZodParsedType.void,
  3206. received: ctx.parsedType
  3207. });
  3208. return INVALID;
  3209. }
  3210. return OK(input.data);
  3211. }
  3212. };
  3213. ZodVoid.create = (params) => {
  3214. return new ZodVoid({
  3215. typeName: ZodFirstPartyTypeKind.ZodVoid,
  3216. ...processCreateParams(params)
  3217. });
  3218. };
  3219. var ZodArray = class _ZodArray extends ZodType {
  3220. _parse(input) {
  3221. const { ctx, status } = this._processInputParams(input);
  3222. const def = this._def;
  3223. if (ctx.parsedType !== ZodParsedType.array) {
  3224. addIssueToContext(ctx, {
  3225. code: ZodIssueCode.invalid_type,
  3226. expected: ZodParsedType.array,
  3227. received: ctx.parsedType
  3228. });
  3229. return INVALID;
  3230. }
  3231. if (def.exactLength !== null) {
  3232. const tooBig = ctx.data.length > def.exactLength.value;
  3233. const tooSmall = ctx.data.length < def.exactLength.value;
  3234. if (tooBig || tooSmall) {
  3235. addIssueToContext(ctx, {
  3236. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  3237. minimum: tooSmall ? def.exactLength.value : void 0,
  3238. maximum: tooBig ? def.exactLength.value : void 0,
  3239. type: "array",
  3240. inclusive: true,
  3241. exact: true,
  3242. message: def.exactLength.message
  3243. });
  3244. status.dirty();
  3245. }
  3246. }
  3247. if (def.minLength !== null) {
  3248. if (ctx.data.length < def.minLength.value) {
  3249. addIssueToContext(ctx, {
  3250. code: ZodIssueCode.too_small,
  3251. minimum: def.minLength.value,
  3252. type: "array",
  3253. inclusive: true,
  3254. exact: false,
  3255. message: def.minLength.message
  3256. });
  3257. status.dirty();
  3258. }
  3259. }
  3260. if (def.maxLength !== null) {
  3261. if (ctx.data.length > def.maxLength.value) {
  3262. addIssueToContext(ctx, {
  3263. code: ZodIssueCode.too_big,
  3264. maximum: def.maxLength.value,
  3265. type: "array",
  3266. inclusive: true,
  3267. exact: false,
  3268. message: def.maxLength.message
  3269. });
  3270. status.dirty();
  3271. }
  3272. }
  3273. if (ctx.common.async) {
  3274. return Promise.all([...ctx.data].map((item, i) => {
  3275. return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  3276. })).then((result2) => {
  3277. return ParseStatus.mergeArray(status, result2);
  3278. });
  3279. }
  3280. const result = [...ctx.data].map((item, i) => {
  3281. return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  3282. });
  3283. return ParseStatus.mergeArray(status, result);
  3284. }
  3285. get element() {
  3286. return this._def.type;
  3287. }
  3288. min(minLength, message) {
  3289. return new _ZodArray({
  3290. ...this._def,
  3291. minLength: { value: minLength, message: errorUtil.toString(message) }
  3292. });
  3293. }
  3294. max(maxLength, message) {
  3295. return new _ZodArray({
  3296. ...this._def,
  3297. maxLength: { value: maxLength, message: errorUtil.toString(message) }
  3298. });
  3299. }
  3300. length(len, message) {
  3301. return new _ZodArray({
  3302. ...this._def,
  3303. exactLength: { value: len, message: errorUtil.toString(message) }
  3304. });
  3305. }
  3306. nonempty(message) {
  3307. return this.min(1, message);
  3308. }
  3309. };
  3310. ZodArray.create = (schema4, params) => {
  3311. return new ZodArray({
  3312. type: schema4,
  3313. minLength: null,
  3314. maxLength: null,
  3315. exactLength: null,
  3316. typeName: ZodFirstPartyTypeKind.ZodArray,
  3317. ...processCreateParams(params)
  3318. });
  3319. };
  3320. function deepPartialify(schema4) {
  3321. if (schema4 instanceof ZodObject) {
  3322. const newShape = {};
  3323. for (const key in schema4.shape) {
  3324. const fieldSchema = schema4.shape[key];
  3325. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
  3326. }
  3327. return new ZodObject({
  3328. ...schema4._def,
  3329. shape: () => newShape
  3330. });
  3331. } else if (schema4 instanceof ZodArray) {
  3332. return new ZodArray({
  3333. ...schema4._def,
  3334. type: deepPartialify(schema4.element)
  3335. });
  3336. } else if (schema4 instanceof ZodOptional) {
  3337. return ZodOptional.create(deepPartialify(schema4.unwrap()));
  3338. } else if (schema4 instanceof ZodNullable) {
  3339. return ZodNullable.create(deepPartialify(schema4.unwrap()));
  3340. } else if (schema4 instanceof ZodTuple) {
  3341. return ZodTuple.create(schema4.items.map((item) => deepPartialify(item)));
  3342. } else {
  3343. return schema4;
  3344. }
  3345. }
  3346. var ZodObject = class _ZodObject extends ZodType {
  3347. constructor() {
  3348. super(...arguments);
  3349. this._cached = null;
  3350. this.nonstrict = this.passthrough;
  3351. this.augment = this.extend;
  3352. }
  3353. _getCached() {
  3354. if (this._cached !== null)
  3355. return this._cached;
  3356. const shape = this._def.shape();
  3357. const keys = util.objectKeys(shape);
  3358. this._cached = { shape, keys };
  3359. return this._cached;
  3360. }
  3361. _parse(input) {
  3362. const parsedType = this._getType(input);
  3363. if (parsedType !== ZodParsedType.object) {
  3364. const ctx2 = this._getOrReturnCtx(input);
  3365. addIssueToContext(ctx2, {
  3366. code: ZodIssueCode.invalid_type,
  3367. expected: ZodParsedType.object,
  3368. received: ctx2.parsedType
  3369. });
  3370. return INVALID;
  3371. }
  3372. const { status, ctx } = this._processInputParams(input);
  3373. const { shape, keys: shapeKeys } = this._getCached();
  3374. const extraKeys = [];
  3375. if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
  3376. for (const key in ctx.data) {
  3377. if (!shapeKeys.includes(key)) {
  3378. extraKeys.push(key);
  3379. }
  3380. }
  3381. }
  3382. const pairs = [];
  3383. for (const key of shapeKeys) {
  3384. const keyValidator = shape[key];
  3385. const value = ctx.data[key];
  3386. pairs.push({
  3387. key: { status: "valid", value: key },
  3388. value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
  3389. alwaysSet: key in ctx.data
  3390. });
  3391. }
  3392. if (this._def.catchall instanceof ZodNever) {
  3393. const unknownKeys = this._def.unknownKeys;
  3394. if (unknownKeys === "passthrough") {
  3395. for (const key of extraKeys) {
  3396. pairs.push({
  3397. key: { status: "valid", value: key },
  3398. value: { status: "valid", value: ctx.data[key] }
  3399. });
  3400. }
  3401. } else if (unknownKeys === "strict") {
  3402. if (extraKeys.length > 0) {
  3403. addIssueToContext(ctx, {
  3404. code: ZodIssueCode.unrecognized_keys,
  3405. keys: extraKeys
  3406. });
  3407. status.dirty();
  3408. }
  3409. } else if (unknownKeys === "strip") {
  3410. } else {
  3411. throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
  3412. }
  3413. } else {
  3414. const catchall = this._def.catchall;
  3415. for (const key of extraKeys) {
  3416. const value = ctx.data[key];
  3417. pairs.push({
  3418. key: { status: "valid", value: key },
  3419. value: catchall._parse(
  3420. new ParseInputLazyPath(ctx, value, ctx.path, key)
  3421. //, ctx.child(key), value, getParsedType(value)
  3422. ),
  3423. alwaysSet: key in ctx.data
  3424. });
  3425. }
  3426. }
  3427. if (ctx.common.async) {
  3428. return Promise.resolve().then(async () => {
  3429. const syncPairs = [];
  3430. for (const pair of pairs) {
  3431. const key = await pair.key;
  3432. const value = await pair.value;
  3433. syncPairs.push({
  3434. key,
  3435. value,
  3436. alwaysSet: pair.alwaysSet
  3437. });
  3438. }
  3439. return syncPairs;
  3440. }).then((syncPairs) => {
  3441. return ParseStatus.mergeObjectSync(status, syncPairs);
  3442. });
  3443. } else {
  3444. return ParseStatus.mergeObjectSync(status, pairs);
  3445. }
  3446. }
  3447. get shape() {
  3448. return this._def.shape();
  3449. }
  3450. strict(message) {
  3451. errorUtil.errToObj;
  3452. return new _ZodObject({
  3453. ...this._def,
  3454. unknownKeys: "strict",
  3455. ...message !== void 0 ? {
  3456. errorMap: (issue, ctx) => {
  3457. var _a, _b;
  3458. const defaultError = ((_b = (_a = this._def).errorMap) == null ? void 0 : _b.call(_a, issue, ctx).message) ?? ctx.defaultError;
  3459. if (issue.code === "unrecognized_keys")
  3460. return {
  3461. message: errorUtil.errToObj(message).message ?? defaultError
  3462. };
  3463. return {
  3464. message: defaultError
  3465. };
  3466. }
  3467. } : {}
  3468. });
  3469. }
  3470. strip() {
  3471. return new _ZodObject({
  3472. ...this._def,
  3473. unknownKeys: "strip"
  3474. });
  3475. }
  3476. passthrough() {
  3477. return new _ZodObject({
  3478. ...this._def,
  3479. unknownKeys: "passthrough"
  3480. });
  3481. }
  3482. // const AugmentFactory =
  3483. // <Def extends ZodObjectDef>(def: Def) =>
  3484. // <Augmentation extends ZodRawShape>(
  3485. // augmentation: Augmentation
  3486. // ): ZodObject<
  3487. // extendShape<ReturnType<Def["shape"]>, Augmentation>,
  3488. // Def["unknownKeys"],
  3489. // Def["catchall"]
  3490. // > => {
  3491. // return new ZodObject({
  3492. // ...def,
  3493. // shape: () => ({
  3494. // ...def.shape(),
  3495. // ...augmentation,
  3496. // }),
  3497. // }) as any;
  3498. // };
  3499. extend(augmentation) {
  3500. return new _ZodObject({
  3501. ...this._def,
  3502. shape: () => ({
  3503. ...this._def.shape(),
  3504. ...augmentation
  3505. })
  3506. });
  3507. }
  3508. /**
  3509. * Prior to zod@1.0.12 there was a bug in the
  3510. * inferred type of merged objects. Please
  3511. * upgrade if you are experiencing issues.
  3512. */
  3513. merge(merging) {
  3514. const merged = new _ZodObject({
  3515. unknownKeys: merging._def.unknownKeys,
  3516. catchall: merging._def.catchall,
  3517. shape: () => ({
  3518. ...this._def.shape(),
  3519. ...merging._def.shape()
  3520. }),
  3521. typeName: ZodFirstPartyTypeKind.ZodObject
  3522. });
  3523. return merged;
  3524. }
  3525. // merge<
  3526. // Incoming extends AnyZodObject,
  3527. // Augmentation extends Incoming["shape"],
  3528. // NewOutput extends {
  3529. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  3530. // ? Augmentation[k]["_output"]
  3531. // : k extends keyof Output
  3532. // ? Output[k]
  3533. // : never;
  3534. // },
  3535. // NewInput extends {
  3536. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  3537. // ? Augmentation[k]["_input"]
  3538. // : k extends keyof Input
  3539. // ? Input[k]
  3540. // : never;
  3541. // }
  3542. // >(
  3543. // merging: Incoming
  3544. // ): ZodObject<
  3545. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  3546. // Incoming["_def"]["unknownKeys"],
  3547. // Incoming["_def"]["catchall"],
  3548. // NewOutput,
  3549. // NewInput
  3550. // > {
  3551. // const merged: any = new ZodObject({
  3552. // unknownKeys: merging._def.unknownKeys,
  3553. // catchall: merging._def.catchall,
  3554. // shape: () =>
  3555. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  3556. // typeName: ZodFirstPartyTypeKind.ZodObject,
  3557. // }) as any;
  3558. // return merged;
  3559. // }
  3560. setKey(key, schema4) {
  3561. return this.augment({ [key]: schema4 });
  3562. }
  3563. // merge<Incoming extends AnyZodObject>(
  3564. // merging: Incoming
  3565. // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  3566. // ZodObject<
  3567. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  3568. // Incoming["_def"]["unknownKeys"],
  3569. // Incoming["_def"]["catchall"]
  3570. // > {
  3571. // // const mergedShape = objectUtil.mergeShapes(
  3572. // // this._def.shape(),
  3573. // // merging._def.shape()
  3574. // // );
  3575. // const merged: any = new ZodObject({
  3576. // unknownKeys: merging._def.unknownKeys,
  3577. // catchall: merging._def.catchall,
  3578. // shape: () =>
  3579. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  3580. // typeName: ZodFirstPartyTypeKind.ZodObject,
  3581. // }) as any;
  3582. // return merged;
  3583. // }
  3584. catchall(index6) {
  3585. return new _ZodObject({
  3586. ...this._def,
  3587. catchall: index6
  3588. });
  3589. }
  3590. pick(mask) {
  3591. const shape = {};
  3592. for (const key of util.objectKeys(mask)) {
  3593. if (mask[key] && this.shape[key]) {
  3594. shape[key] = this.shape[key];
  3595. }
  3596. }
  3597. return new _ZodObject({
  3598. ...this._def,
  3599. shape: () => shape
  3600. });
  3601. }
  3602. omit(mask) {
  3603. const shape = {};
  3604. for (const key of util.objectKeys(this.shape)) {
  3605. if (!mask[key]) {
  3606. shape[key] = this.shape[key];
  3607. }
  3608. }
  3609. return new _ZodObject({
  3610. ...this._def,
  3611. shape: () => shape
  3612. });
  3613. }
  3614. /**
  3615. * @deprecated
  3616. */
  3617. deepPartial() {
  3618. return deepPartialify(this);
  3619. }
  3620. partial(mask) {
  3621. const newShape = {};
  3622. for (const key of util.objectKeys(this.shape)) {
  3623. const fieldSchema = this.shape[key];
  3624. if (mask && !mask[key]) {
  3625. newShape[key] = fieldSchema;
  3626. } else {
  3627. newShape[key] = fieldSchema.optional();
  3628. }
  3629. }
  3630. return new _ZodObject({
  3631. ...this._def,
  3632. shape: () => newShape
  3633. });
  3634. }
  3635. required(mask) {
  3636. const newShape = {};
  3637. for (const key of util.objectKeys(this.shape)) {
  3638. if (mask && !mask[key]) {
  3639. newShape[key] = this.shape[key];
  3640. } else {
  3641. const fieldSchema = this.shape[key];
  3642. let newField = fieldSchema;
  3643. while (newField instanceof ZodOptional) {
  3644. newField = newField._def.innerType;
  3645. }
  3646. newShape[key] = newField;
  3647. }
  3648. }
  3649. return new _ZodObject({
  3650. ...this._def,
  3651. shape: () => newShape
  3652. });
  3653. }
  3654. keyof() {
  3655. return createZodEnum(util.objectKeys(this.shape));
  3656. }
  3657. };
  3658. ZodObject.create = (shape, params) => {
  3659. return new ZodObject({
  3660. shape: () => shape,
  3661. unknownKeys: "strip",
  3662. catchall: ZodNever.create(),
  3663. typeName: ZodFirstPartyTypeKind.ZodObject,
  3664. ...processCreateParams(params)
  3665. });
  3666. };
  3667. ZodObject.strictCreate = (shape, params) => {
  3668. return new ZodObject({
  3669. shape: () => shape,
  3670. unknownKeys: "strict",
  3671. catchall: ZodNever.create(),
  3672. typeName: ZodFirstPartyTypeKind.ZodObject,
  3673. ...processCreateParams(params)
  3674. });
  3675. };
  3676. ZodObject.lazycreate = (shape, params) => {
  3677. return new ZodObject({
  3678. shape,
  3679. unknownKeys: "strip",
  3680. catchall: ZodNever.create(),
  3681. typeName: ZodFirstPartyTypeKind.ZodObject,
  3682. ...processCreateParams(params)
  3683. });
  3684. };
  3685. var ZodUnion = class extends ZodType {
  3686. _parse(input) {
  3687. const { ctx } = this._processInputParams(input);
  3688. const options = this._def.options;
  3689. function handleResults(results) {
  3690. for (const result of results) {
  3691. if (result.result.status === "valid") {
  3692. return result.result;
  3693. }
  3694. }
  3695. for (const result of results) {
  3696. if (result.result.status === "dirty") {
  3697. ctx.common.issues.push(...result.ctx.common.issues);
  3698. return result.result;
  3699. }
  3700. }
  3701. const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
  3702. addIssueToContext(ctx, {
  3703. code: ZodIssueCode.invalid_union,
  3704. unionErrors
  3705. });
  3706. return INVALID;
  3707. }
  3708. if (ctx.common.async) {
  3709. return Promise.all(options.map(async (option) => {
  3710. const childCtx = {
  3711. ...ctx,
  3712. common: {
  3713. ...ctx.common,
  3714. issues: []
  3715. },
  3716. parent: null
  3717. };
  3718. return {
  3719. result: await option._parseAsync({
  3720. data: ctx.data,
  3721. path: ctx.path,
  3722. parent: childCtx
  3723. }),
  3724. ctx: childCtx
  3725. };
  3726. })).then(handleResults);
  3727. } else {
  3728. let dirty = void 0;
  3729. const issues = [];
  3730. for (const option of options) {
  3731. const childCtx = {
  3732. ...ctx,
  3733. common: {
  3734. ...ctx.common,
  3735. issues: []
  3736. },
  3737. parent: null
  3738. };
  3739. const result = option._parseSync({
  3740. data: ctx.data,
  3741. path: ctx.path,
  3742. parent: childCtx
  3743. });
  3744. if (result.status === "valid") {
  3745. return result;
  3746. } else if (result.status === "dirty" && !dirty) {
  3747. dirty = { result, ctx: childCtx };
  3748. }
  3749. if (childCtx.common.issues.length) {
  3750. issues.push(childCtx.common.issues);
  3751. }
  3752. }
  3753. if (dirty) {
  3754. ctx.common.issues.push(...dirty.ctx.common.issues);
  3755. return dirty.result;
  3756. }
  3757. const unionErrors = issues.map((issues2) => new ZodError(issues2));
  3758. addIssueToContext(ctx, {
  3759. code: ZodIssueCode.invalid_union,
  3760. unionErrors
  3761. });
  3762. return INVALID;
  3763. }
  3764. }
  3765. get options() {
  3766. return this._def.options;
  3767. }
  3768. };
  3769. ZodUnion.create = (types, params) => {
  3770. return new ZodUnion({
  3771. options: types,
  3772. typeName: ZodFirstPartyTypeKind.ZodUnion,
  3773. ...processCreateParams(params)
  3774. });
  3775. };
  3776. var getDiscriminator = (type) => {
  3777. if (type instanceof ZodLazy) {
  3778. return getDiscriminator(type.schema);
  3779. } else if (type instanceof ZodEffects) {
  3780. return getDiscriminator(type.innerType());
  3781. } else if (type instanceof ZodLiteral) {
  3782. return [type.value];
  3783. } else if (type instanceof ZodEnum) {
  3784. return type.options;
  3785. } else if (type instanceof ZodNativeEnum) {
  3786. return util.objectValues(type.enum);
  3787. } else if (type instanceof ZodDefault) {
  3788. return getDiscriminator(type._def.innerType);
  3789. } else if (type instanceof ZodUndefined) {
  3790. return [void 0];
  3791. } else if (type instanceof ZodNull) {
  3792. return [null];
  3793. } else if (type instanceof ZodOptional) {
  3794. return [void 0, ...getDiscriminator(type.unwrap())];
  3795. } else if (type instanceof ZodNullable) {
  3796. return [null, ...getDiscriminator(type.unwrap())];
  3797. } else if (type instanceof ZodBranded) {
  3798. return getDiscriminator(type.unwrap());
  3799. } else if (type instanceof ZodReadonly) {
  3800. return getDiscriminator(type.unwrap());
  3801. } else if (type instanceof ZodCatch) {
  3802. return getDiscriminator(type._def.innerType);
  3803. } else {
  3804. return [];
  3805. }
  3806. };
  3807. var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
  3808. _parse(input) {
  3809. const { ctx } = this._processInputParams(input);
  3810. if (ctx.parsedType !== ZodParsedType.object) {
  3811. addIssueToContext(ctx, {
  3812. code: ZodIssueCode.invalid_type,
  3813. expected: ZodParsedType.object,
  3814. received: ctx.parsedType
  3815. });
  3816. return INVALID;
  3817. }
  3818. const discriminator = this.discriminator;
  3819. const discriminatorValue = ctx.data[discriminator];
  3820. const option = this.optionsMap.get(discriminatorValue);
  3821. if (!option) {
  3822. addIssueToContext(ctx, {
  3823. code: ZodIssueCode.invalid_union_discriminator,
  3824. options: Array.from(this.optionsMap.keys()),
  3825. path: [discriminator]
  3826. });
  3827. return INVALID;
  3828. }
  3829. if (ctx.common.async) {
  3830. return option._parseAsync({
  3831. data: ctx.data,
  3832. path: ctx.path,
  3833. parent: ctx
  3834. });
  3835. } else {
  3836. return option._parseSync({
  3837. data: ctx.data,
  3838. path: ctx.path,
  3839. parent: ctx
  3840. });
  3841. }
  3842. }
  3843. get discriminator() {
  3844. return this._def.discriminator;
  3845. }
  3846. get options() {
  3847. return this._def.options;
  3848. }
  3849. get optionsMap() {
  3850. return this._def.optionsMap;
  3851. }
  3852. /**
  3853. * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
  3854. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
  3855. * have a different value for each object in the union.
  3856. * @param discriminator the name of the discriminator property
  3857. * @param types an array of object schemas
  3858. * @param params
  3859. */
  3860. static create(discriminator, options, params) {
  3861. const optionsMap = /* @__PURE__ */ new Map();
  3862. for (const type of options) {
  3863. const discriminatorValues = getDiscriminator(type.shape[discriminator]);
  3864. if (!discriminatorValues.length) {
  3865. throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
  3866. }
  3867. for (const value of discriminatorValues) {
  3868. if (optionsMap.has(value)) {
  3869. throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
  3870. }
  3871. optionsMap.set(value, type);
  3872. }
  3873. }
  3874. return new _ZodDiscriminatedUnion({
  3875. typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  3876. discriminator,
  3877. options,
  3878. optionsMap,
  3879. ...processCreateParams(params)
  3880. });
  3881. }
  3882. };
  3883. function mergeValues(a, b) {
  3884. const aType = getParsedType(a);
  3885. const bType = getParsedType(b);
  3886. if (a === b) {
  3887. return { valid: true, data: a };
  3888. } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  3889. const bKeys = util.objectKeys(b);
  3890. const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
  3891. const newObj = { ...a, ...b };
  3892. for (const key of sharedKeys) {
  3893. const sharedValue = mergeValues(a[key], b[key]);
  3894. if (!sharedValue.valid) {
  3895. return { valid: false };
  3896. }
  3897. newObj[key] = sharedValue.data;
  3898. }
  3899. return { valid: true, data: newObj };
  3900. } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  3901. if (a.length !== b.length) {
  3902. return { valid: false };
  3903. }
  3904. const newArray = [];
  3905. for (let index6 = 0; index6 < a.length; index6++) {
  3906. const itemA = a[index6];
  3907. const itemB = b[index6];
  3908. const sharedValue = mergeValues(itemA, itemB);
  3909. if (!sharedValue.valid) {
  3910. return { valid: false };
  3911. }
  3912. newArray.push(sharedValue.data);
  3913. }
  3914. return { valid: true, data: newArray };
  3915. } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
  3916. return { valid: true, data: a };
  3917. } else {
  3918. return { valid: false };
  3919. }
  3920. }
  3921. var ZodIntersection = class extends ZodType {
  3922. _parse(input) {
  3923. const { status, ctx } = this._processInputParams(input);
  3924. const handleParsed = (parsedLeft, parsedRight) => {
  3925. if (isAborted(parsedLeft) || isAborted(parsedRight)) {
  3926. return INVALID;
  3927. }
  3928. const merged = mergeValues(parsedLeft.value, parsedRight.value);
  3929. if (!merged.valid) {
  3930. addIssueToContext(ctx, {
  3931. code: ZodIssueCode.invalid_intersection_types
  3932. });
  3933. return INVALID;
  3934. }
  3935. if (isDirty(parsedLeft) || isDirty(parsedRight)) {
  3936. status.dirty();
  3937. }
  3938. return { status: status.value, value: merged.data };
  3939. };
  3940. if (ctx.common.async) {
  3941. return Promise.all([
  3942. this._def.left._parseAsync({
  3943. data: ctx.data,
  3944. path: ctx.path,
  3945. parent: ctx
  3946. }),
  3947. this._def.right._parseAsync({
  3948. data: ctx.data,
  3949. path: ctx.path,
  3950. parent: ctx
  3951. })
  3952. ]).then(([left, right]) => handleParsed(left, right));
  3953. } else {
  3954. return handleParsed(this._def.left._parseSync({
  3955. data: ctx.data,
  3956. path: ctx.path,
  3957. parent: ctx
  3958. }), this._def.right._parseSync({
  3959. data: ctx.data,
  3960. path: ctx.path,
  3961. parent: ctx
  3962. }));
  3963. }
  3964. }
  3965. };
  3966. ZodIntersection.create = (left, right, params) => {
  3967. return new ZodIntersection({
  3968. left,
  3969. right,
  3970. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  3971. ...processCreateParams(params)
  3972. });
  3973. };
  3974. var ZodTuple = class _ZodTuple extends ZodType {
  3975. _parse(input) {
  3976. const { status, ctx } = this._processInputParams(input);
  3977. if (ctx.parsedType !== ZodParsedType.array) {
  3978. addIssueToContext(ctx, {
  3979. code: ZodIssueCode.invalid_type,
  3980. expected: ZodParsedType.array,
  3981. received: ctx.parsedType
  3982. });
  3983. return INVALID;
  3984. }
  3985. if (ctx.data.length < this._def.items.length) {
  3986. addIssueToContext(ctx, {
  3987. code: ZodIssueCode.too_small,
  3988. minimum: this._def.items.length,
  3989. inclusive: true,
  3990. exact: false,
  3991. type: "array"
  3992. });
  3993. return INVALID;
  3994. }
  3995. const rest = this._def.rest;
  3996. if (!rest && ctx.data.length > this._def.items.length) {
  3997. addIssueToContext(ctx, {
  3998. code: ZodIssueCode.too_big,
  3999. maximum: this._def.items.length,
  4000. inclusive: true,
  4001. exact: false,
  4002. type: "array"
  4003. });
  4004. status.dirty();
  4005. }
  4006. const items = [...ctx.data].map((item, itemIndex) => {
  4007. const schema4 = this._def.items[itemIndex] || this._def.rest;
  4008. if (!schema4)
  4009. return null;
  4010. return schema4._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
  4011. }).filter((x) => !!x);
  4012. if (ctx.common.async) {
  4013. return Promise.all(items).then((results) => {
  4014. return ParseStatus.mergeArray(status, results);
  4015. });
  4016. } else {
  4017. return ParseStatus.mergeArray(status, items);
  4018. }
  4019. }
  4020. get items() {
  4021. return this._def.items;
  4022. }
  4023. rest(rest) {
  4024. return new _ZodTuple({
  4025. ...this._def,
  4026. rest
  4027. });
  4028. }
  4029. };
  4030. ZodTuple.create = (schemas, params) => {
  4031. if (!Array.isArray(schemas)) {
  4032. throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  4033. }
  4034. return new ZodTuple({
  4035. items: schemas,
  4036. typeName: ZodFirstPartyTypeKind.ZodTuple,
  4037. rest: null,
  4038. ...processCreateParams(params)
  4039. });
  4040. };
  4041. var ZodRecord = class _ZodRecord extends ZodType {
  4042. get keySchema() {
  4043. return this._def.keyType;
  4044. }
  4045. get valueSchema() {
  4046. return this._def.valueType;
  4047. }
  4048. _parse(input) {
  4049. const { status, ctx } = this._processInputParams(input);
  4050. if (ctx.parsedType !== ZodParsedType.object) {
  4051. addIssueToContext(ctx, {
  4052. code: ZodIssueCode.invalid_type,
  4053. expected: ZodParsedType.object,
  4054. received: ctx.parsedType
  4055. });
  4056. return INVALID;
  4057. }
  4058. const pairs = [];
  4059. const keyType = this._def.keyType;
  4060. const valueType = this._def.valueType;
  4061. for (const key in ctx.data) {
  4062. pairs.push({
  4063. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
  4064. value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
  4065. alwaysSet: key in ctx.data
  4066. });
  4067. }
  4068. if (ctx.common.async) {
  4069. return ParseStatus.mergeObjectAsync(status, pairs);
  4070. } else {
  4071. return ParseStatus.mergeObjectSync(status, pairs);
  4072. }
  4073. }
  4074. get element() {
  4075. return this._def.valueType;
  4076. }
  4077. static create(first, second, third) {
  4078. if (second instanceof ZodType) {
  4079. return new _ZodRecord({
  4080. keyType: first,
  4081. valueType: second,
  4082. typeName: ZodFirstPartyTypeKind.ZodRecord,
  4083. ...processCreateParams(third)
  4084. });
  4085. }
  4086. return new _ZodRecord({
  4087. keyType: ZodString.create(),
  4088. valueType: first,
  4089. typeName: ZodFirstPartyTypeKind.ZodRecord,
  4090. ...processCreateParams(second)
  4091. });
  4092. }
  4093. };
  4094. var ZodMap = class extends ZodType {
  4095. get keySchema() {
  4096. return this._def.keyType;
  4097. }
  4098. get valueSchema() {
  4099. return this._def.valueType;
  4100. }
  4101. _parse(input) {
  4102. const { status, ctx } = this._processInputParams(input);
  4103. if (ctx.parsedType !== ZodParsedType.map) {
  4104. addIssueToContext(ctx, {
  4105. code: ZodIssueCode.invalid_type,
  4106. expected: ZodParsedType.map,
  4107. received: ctx.parsedType
  4108. });
  4109. return INVALID;
  4110. }
  4111. const keyType = this._def.keyType;
  4112. const valueType = this._def.valueType;
  4113. const pairs = [...ctx.data.entries()].map(([key, value], index6) => {
  4114. return {
  4115. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])),
  4116. value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"]))
  4117. };
  4118. });
  4119. if (ctx.common.async) {
  4120. const finalMap = /* @__PURE__ */ new Map();
  4121. return Promise.resolve().then(async () => {
  4122. for (const pair of pairs) {
  4123. const key = await pair.key;
  4124. const value = await pair.value;
  4125. if (key.status === "aborted" || value.status === "aborted") {
  4126. return INVALID;
  4127. }
  4128. if (key.status === "dirty" || value.status === "dirty") {
  4129. status.dirty();
  4130. }
  4131. finalMap.set(key.value, value.value);
  4132. }
  4133. return { status: status.value, value: finalMap };
  4134. });
  4135. } else {
  4136. const finalMap = /* @__PURE__ */ new Map();
  4137. for (const pair of pairs) {
  4138. const key = pair.key;
  4139. const value = pair.value;
  4140. if (key.status === "aborted" || value.status === "aborted") {
  4141. return INVALID;
  4142. }
  4143. if (key.status === "dirty" || value.status === "dirty") {
  4144. status.dirty();
  4145. }
  4146. finalMap.set(key.value, value.value);
  4147. }
  4148. return { status: status.value, value: finalMap };
  4149. }
  4150. }
  4151. };
  4152. ZodMap.create = (keyType, valueType, params) => {
  4153. return new ZodMap({
  4154. valueType,
  4155. keyType,
  4156. typeName: ZodFirstPartyTypeKind.ZodMap,
  4157. ...processCreateParams(params)
  4158. });
  4159. };
  4160. var ZodSet = class _ZodSet extends ZodType {
  4161. _parse(input) {
  4162. const { status, ctx } = this._processInputParams(input);
  4163. if (ctx.parsedType !== ZodParsedType.set) {
  4164. addIssueToContext(ctx, {
  4165. code: ZodIssueCode.invalid_type,
  4166. expected: ZodParsedType.set,
  4167. received: ctx.parsedType
  4168. });
  4169. return INVALID;
  4170. }
  4171. const def = this._def;
  4172. if (def.minSize !== null) {
  4173. if (ctx.data.size < def.minSize.value) {
  4174. addIssueToContext(ctx, {
  4175. code: ZodIssueCode.too_small,
  4176. minimum: def.minSize.value,
  4177. type: "set",
  4178. inclusive: true,
  4179. exact: false,
  4180. message: def.minSize.message
  4181. });
  4182. status.dirty();
  4183. }
  4184. }
  4185. if (def.maxSize !== null) {
  4186. if (ctx.data.size > def.maxSize.value) {
  4187. addIssueToContext(ctx, {
  4188. code: ZodIssueCode.too_big,
  4189. maximum: def.maxSize.value,
  4190. type: "set",
  4191. inclusive: true,
  4192. exact: false,
  4193. message: def.maxSize.message
  4194. });
  4195. status.dirty();
  4196. }
  4197. }
  4198. const valueType = this._def.valueType;
  4199. function finalizeSet(elements2) {
  4200. const parsedSet = /* @__PURE__ */ new Set();
  4201. for (const element of elements2) {
  4202. if (element.status === "aborted")
  4203. return INVALID;
  4204. if (element.status === "dirty")
  4205. status.dirty();
  4206. parsedSet.add(element.value);
  4207. }
  4208. return { status: status.value, value: parsedSet };
  4209. }
  4210. const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
  4211. if (ctx.common.async) {
  4212. return Promise.all(elements).then((elements2) => finalizeSet(elements2));
  4213. } else {
  4214. return finalizeSet(elements);
  4215. }
  4216. }
  4217. min(minSize, message) {
  4218. return new _ZodSet({
  4219. ...this._def,
  4220. minSize: { value: minSize, message: errorUtil.toString(message) }
  4221. });
  4222. }
  4223. max(maxSize, message) {
  4224. return new _ZodSet({
  4225. ...this._def,
  4226. maxSize: { value: maxSize, message: errorUtil.toString(message) }
  4227. });
  4228. }
  4229. size(size, message) {
  4230. return this.min(size, message).max(size, message);
  4231. }
  4232. nonempty(message) {
  4233. return this.min(1, message);
  4234. }
  4235. };
  4236. ZodSet.create = (valueType, params) => {
  4237. return new ZodSet({
  4238. valueType,
  4239. minSize: null,
  4240. maxSize: null,
  4241. typeName: ZodFirstPartyTypeKind.ZodSet,
  4242. ...processCreateParams(params)
  4243. });
  4244. };
  4245. var ZodFunction = class _ZodFunction extends ZodType {
  4246. constructor() {
  4247. super(...arguments);
  4248. this.validate = this.implement;
  4249. }
  4250. _parse(input) {
  4251. const { ctx } = this._processInputParams(input);
  4252. if (ctx.parsedType !== ZodParsedType.function) {
  4253. addIssueToContext(ctx, {
  4254. code: ZodIssueCode.invalid_type,
  4255. expected: ZodParsedType.function,
  4256. received: ctx.parsedType
  4257. });
  4258. return INVALID;
  4259. }
  4260. function makeArgsIssue(args, error) {
  4261. return makeIssue({
  4262. data: args,
  4263. path: ctx.path,
  4264. errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
  4265. issueData: {
  4266. code: ZodIssueCode.invalid_arguments,
  4267. argumentsError: error
  4268. }
  4269. });
  4270. }
  4271. function makeReturnsIssue(returns, error) {
  4272. return makeIssue({
  4273. data: returns,
  4274. path: ctx.path,
  4275. errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
  4276. issueData: {
  4277. code: ZodIssueCode.invalid_return_type,
  4278. returnTypeError: error
  4279. }
  4280. });
  4281. }
  4282. const params = { errorMap: ctx.common.contextualErrorMap };
  4283. const fn = ctx.data;
  4284. if (this._def.returns instanceof ZodPromise) {
  4285. const me = this;
  4286. return OK(async function(...args) {
  4287. const error = new ZodError([]);
  4288. const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
  4289. error.addIssue(makeArgsIssue(args, e));
  4290. throw error;
  4291. });
  4292. const result = await Reflect.apply(fn, this, parsedArgs);
  4293. const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
  4294. error.addIssue(makeReturnsIssue(result, e));
  4295. throw error;
  4296. });
  4297. return parsedReturns;
  4298. });
  4299. } else {
  4300. const me = this;
  4301. return OK(function(...args) {
  4302. const parsedArgs = me._def.args.safeParse(args, params);
  4303. if (!parsedArgs.success) {
  4304. throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
  4305. }
  4306. const result = Reflect.apply(fn, this, parsedArgs.data);
  4307. const parsedReturns = me._def.returns.safeParse(result, params);
  4308. if (!parsedReturns.success) {
  4309. throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
  4310. }
  4311. return parsedReturns.data;
  4312. });
  4313. }
  4314. }
  4315. parameters() {
  4316. return this._def.args;
  4317. }
  4318. returnType() {
  4319. return this._def.returns;
  4320. }
  4321. args(...items) {
  4322. return new _ZodFunction({
  4323. ...this._def,
  4324. args: ZodTuple.create(items).rest(ZodUnknown.create())
  4325. });
  4326. }
  4327. returns(returnType) {
  4328. return new _ZodFunction({
  4329. ...this._def,
  4330. returns: returnType
  4331. });
  4332. }
  4333. implement(func) {
  4334. const validatedFunc = this.parse(func);
  4335. return validatedFunc;
  4336. }
  4337. strictImplement(func) {
  4338. const validatedFunc = this.parse(func);
  4339. return validatedFunc;
  4340. }
  4341. static create(args, returns, params) {
  4342. return new _ZodFunction({
  4343. args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
  4344. returns: returns || ZodUnknown.create(),
  4345. typeName: ZodFirstPartyTypeKind.ZodFunction,
  4346. ...processCreateParams(params)
  4347. });
  4348. }
  4349. };
  4350. var ZodLazy = class extends ZodType {
  4351. get schema() {
  4352. return this._def.getter();
  4353. }
  4354. _parse(input) {
  4355. const { ctx } = this._processInputParams(input);
  4356. const lazySchema = this._def.getter();
  4357. return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  4358. }
  4359. };
  4360. ZodLazy.create = (getter, params) => {
  4361. return new ZodLazy({
  4362. getter,
  4363. typeName: ZodFirstPartyTypeKind.ZodLazy,
  4364. ...processCreateParams(params)
  4365. });
  4366. };
  4367. var ZodLiteral = class extends ZodType {
  4368. _parse(input) {
  4369. if (input.data !== this._def.value) {
  4370. const ctx = this._getOrReturnCtx(input);
  4371. addIssueToContext(ctx, {
  4372. received: ctx.data,
  4373. code: ZodIssueCode.invalid_literal,
  4374. expected: this._def.value
  4375. });
  4376. return INVALID;
  4377. }
  4378. return { status: "valid", value: input.data };
  4379. }
  4380. get value() {
  4381. return this._def.value;
  4382. }
  4383. };
  4384. ZodLiteral.create = (value, params) => {
  4385. return new ZodLiteral({
  4386. value,
  4387. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  4388. ...processCreateParams(params)
  4389. });
  4390. };
  4391. function createZodEnum(values, params) {
  4392. return new ZodEnum({
  4393. values,
  4394. typeName: ZodFirstPartyTypeKind.ZodEnum,
  4395. ...processCreateParams(params)
  4396. });
  4397. }
  4398. var ZodEnum = class _ZodEnum extends ZodType {
  4399. _parse(input) {
  4400. if (typeof input.data !== "string") {
  4401. const ctx = this._getOrReturnCtx(input);
  4402. const expectedValues = this._def.values;
  4403. addIssueToContext(ctx, {
  4404. expected: util.joinValues(expectedValues),
  4405. received: ctx.parsedType,
  4406. code: ZodIssueCode.invalid_type
  4407. });
  4408. return INVALID;
  4409. }
  4410. if (!this._cache) {
  4411. this._cache = new Set(this._def.values);
  4412. }
  4413. if (!this._cache.has(input.data)) {
  4414. const ctx = this._getOrReturnCtx(input);
  4415. const expectedValues = this._def.values;
  4416. addIssueToContext(ctx, {
  4417. received: ctx.data,
  4418. code: ZodIssueCode.invalid_enum_value,
  4419. options: expectedValues
  4420. });
  4421. return INVALID;
  4422. }
  4423. return OK(input.data);
  4424. }
  4425. get options() {
  4426. return this._def.values;
  4427. }
  4428. get enum() {
  4429. const enumValues = {};
  4430. for (const val of this._def.values) {
  4431. enumValues[val] = val;
  4432. }
  4433. return enumValues;
  4434. }
  4435. get Values() {
  4436. const enumValues = {};
  4437. for (const val of this._def.values) {
  4438. enumValues[val] = val;
  4439. }
  4440. return enumValues;
  4441. }
  4442. get Enum() {
  4443. const enumValues = {};
  4444. for (const val of this._def.values) {
  4445. enumValues[val] = val;
  4446. }
  4447. return enumValues;
  4448. }
  4449. extract(values, newDef = this._def) {
  4450. return _ZodEnum.create(values, {
  4451. ...this._def,
  4452. ...newDef
  4453. });
  4454. }
  4455. exclude(values, newDef = this._def) {
  4456. return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
  4457. ...this._def,
  4458. ...newDef
  4459. });
  4460. }
  4461. };
  4462. ZodEnum.create = createZodEnum;
  4463. var ZodNativeEnum = class extends ZodType {
  4464. _parse(input) {
  4465. const nativeEnumValues = util.getValidEnumValues(this._def.values);
  4466. const ctx = this._getOrReturnCtx(input);
  4467. if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
  4468. const expectedValues = util.objectValues(nativeEnumValues);
  4469. addIssueToContext(ctx, {
  4470. expected: util.joinValues(expectedValues),
  4471. received: ctx.parsedType,
  4472. code: ZodIssueCode.invalid_type
  4473. });
  4474. return INVALID;
  4475. }
  4476. if (!this._cache) {
  4477. this._cache = new Set(util.getValidEnumValues(this._def.values));
  4478. }
  4479. if (!this._cache.has(input.data)) {
  4480. const expectedValues = util.objectValues(nativeEnumValues);
  4481. addIssueToContext(ctx, {
  4482. received: ctx.data,
  4483. code: ZodIssueCode.invalid_enum_value,
  4484. options: expectedValues
  4485. });
  4486. return INVALID;
  4487. }
  4488. return OK(input.data);
  4489. }
  4490. get enum() {
  4491. return this._def.values;
  4492. }
  4493. };
  4494. ZodNativeEnum.create = (values, params) => {
  4495. return new ZodNativeEnum({
  4496. values,
  4497. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  4498. ...processCreateParams(params)
  4499. });
  4500. };
  4501. var ZodPromise = class extends ZodType {
  4502. unwrap() {
  4503. return this._def.type;
  4504. }
  4505. _parse(input) {
  4506. const { ctx } = this._processInputParams(input);
  4507. if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
  4508. addIssueToContext(ctx, {
  4509. code: ZodIssueCode.invalid_type,
  4510. expected: ZodParsedType.promise,
  4511. received: ctx.parsedType
  4512. });
  4513. return INVALID;
  4514. }
  4515. const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
  4516. return OK(promisified.then((data) => {
  4517. return this._def.type.parseAsync(data, {
  4518. path: ctx.path,
  4519. errorMap: ctx.common.contextualErrorMap
  4520. });
  4521. }));
  4522. }
  4523. };
  4524. ZodPromise.create = (schema4, params) => {
  4525. return new ZodPromise({
  4526. type: schema4,
  4527. typeName: ZodFirstPartyTypeKind.ZodPromise,
  4528. ...processCreateParams(params)
  4529. });
  4530. };
  4531. var ZodEffects = class extends ZodType {
  4532. innerType() {
  4533. return this._def.schema;
  4534. }
  4535. sourceType() {
  4536. return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  4537. }
  4538. _parse(input) {
  4539. const { status, ctx } = this._processInputParams(input);
  4540. const effect = this._def.effect || null;
  4541. const checkCtx = {
  4542. addIssue: (arg) => {
  4543. addIssueToContext(ctx, arg);
  4544. if (arg.fatal) {
  4545. status.abort();
  4546. } else {
  4547. status.dirty();
  4548. }
  4549. },
  4550. get path() {
  4551. return ctx.path;
  4552. }
  4553. };
  4554. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
  4555. if (effect.type === "preprocess") {
  4556. const processed = effect.transform(ctx.data, checkCtx);
  4557. if (ctx.common.async) {
  4558. return Promise.resolve(processed).then(async (processed2) => {
  4559. if (status.value === "aborted")
  4560. return INVALID;
  4561. const result = await this._def.schema._parseAsync({
  4562. data: processed2,
  4563. path: ctx.path,
  4564. parent: ctx
  4565. });
  4566. if (result.status === "aborted")
  4567. return INVALID;
  4568. if (result.status === "dirty")
  4569. return DIRTY(result.value);
  4570. if (status.value === "dirty")
  4571. return DIRTY(result.value);
  4572. return result;
  4573. });
  4574. } else {
  4575. if (status.value === "aborted")
  4576. return INVALID;
  4577. const result = this._def.schema._parseSync({
  4578. data: processed,
  4579. path: ctx.path,
  4580. parent: ctx
  4581. });
  4582. if (result.status === "aborted")
  4583. return INVALID;
  4584. if (result.status === "dirty")
  4585. return DIRTY(result.value);
  4586. if (status.value === "dirty")
  4587. return DIRTY(result.value);
  4588. return result;
  4589. }
  4590. }
  4591. if (effect.type === "refinement") {
  4592. const executeRefinement = (acc) => {
  4593. const result = effect.refinement(acc, checkCtx);
  4594. if (ctx.common.async) {
  4595. return Promise.resolve(result);
  4596. }
  4597. if (result instanceof Promise) {
  4598. throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
  4599. }
  4600. return acc;
  4601. };
  4602. if (ctx.common.async === false) {
  4603. const inner = this._def.schema._parseSync({
  4604. data: ctx.data,
  4605. path: ctx.path,
  4606. parent: ctx
  4607. });
  4608. if (inner.status === "aborted")
  4609. return INVALID;
  4610. if (inner.status === "dirty")
  4611. status.dirty();
  4612. executeRefinement(inner.value);
  4613. return { status: status.value, value: inner.value };
  4614. } else {
  4615. return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
  4616. if (inner.status === "aborted")
  4617. return INVALID;
  4618. if (inner.status === "dirty")
  4619. status.dirty();
  4620. return executeRefinement(inner.value).then(() => {
  4621. return { status: status.value, value: inner.value };
  4622. });
  4623. });
  4624. }
  4625. }
  4626. if (effect.type === "transform") {
  4627. if (ctx.common.async === false) {
  4628. const base = this._def.schema._parseSync({
  4629. data: ctx.data,
  4630. path: ctx.path,
  4631. parent: ctx
  4632. });
  4633. if (!isValid(base))
  4634. return INVALID;
  4635. const result = effect.transform(base.value, checkCtx);
  4636. if (result instanceof Promise) {
  4637. throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
  4638. }
  4639. return { status: status.value, value: result };
  4640. } else {
  4641. return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
  4642. if (!isValid(base))
  4643. return INVALID;
  4644. return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
  4645. status: status.value,
  4646. value: result
  4647. }));
  4648. });
  4649. }
  4650. }
  4651. util.assertNever(effect);
  4652. }
  4653. };
  4654. ZodEffects.create = (schema4, effect, params) => {
  4655. return new ZodEffects({
  4656. schema: schema4,
  4657. typeName: ZodFirstPartyTypeKind.ZodEffects,
  4658. effect,
  4659. ...processCreateParams(params)
  4660. });
  4661. };
  4662. ZodEffects.createWithPreprocess = (preprocess, schema4, params) => {
  4663. return new ZodEffects({
  4664. schema: schema4,
  4665. effect: { type: "preprocess", transform: preprocess },
  4666. typeName: ZodFirstPartyTypeKind.ZodEffects,
  4667. ...processCreateParams(params)
  4668. });
  4669. };
  4670. var ZodOptional = class extends ZodType {
  4671. _parse(input) {
  4672. const parsedType = this._getType(input);
  4673. if (parsedType === ZodParsedType.undefined) {
  4674. return OK(void 0);
  4675. }
  4676. return this._def.innerType._parse(input);
  4677. }
  4678. unwrap() {
  4679. return this._def.innerType;
  4680. }
  4681. };
  4682. ZodOptional.create = (type, params) => {
  4683. return new ZodOptional({
  4684. innerType: type,
  4685. typeName: ZodFirstPartyTypeKind.ZodOptional,
  4686. ...processCreateParams(params)
  4687. });
  4688. };
  4689. var ZodNullable = class extends ZodType {
  4690. _parse(input) {
  4691. const parsedType = this._getType(input);
  4692. if (parsedType === ZodParsedType.null) {
  4693. return OK(null);
  4694. }
  4695. return this._def.innerType._parse(input);
  4696. }
  4697. unwrap() {
  4698. return this._def.innerType;
  4699. }
  4700. };
  4701. ZodNullable.create = (type, params) => {
  4702. return new ZodNullable({
  4703. innerType: type,
  4704. typeName: ZodFirstPartyTypeKind.ZodNullable,
  4705. ...processCreateParams(params)
  4706. });
  4707. };
  4708. var ZodDefault = class extends ZodType {
  4709. _parse(input) {
  4710. const { ctx } = this._processInputParams(input);
  4711. let data = ctx.data;
  4712. if (ctx.parsedType === ZodParsedType.undefined) {
  4713. data = this._def.defaultValue();
  4714. }
  4715. return this._def.innerType._parse({
  4716. data,
  4717. path: ctx.path,
  4718. parent: ctx
  4719. });
  4720. }
  4721. removeDefault() {
  4722. return this._def.innerType;
  4723. }
  4724. };
  4725. ZodDefault.create = (type, params) => {
  4726. return new ZodDefault({
  4727. innerType: type,
  4728. typeName: ZodFirstPartyTypeKind.ZodDefault,
  4729. defaultValue: typeof params.default === "function" ? params.default : () => params.default,
  4730. ...processCreateParams(params)
  4731. });
  4732. };
  4733. var ZodCatch = class extends ZodType {
  4734. _parse(input) {
  4735. const { ctx } = this._processInputParams(input);
  4736. const newCtx = {
  4737. ...ctx,
  4738. common: {
  4739. ...ctx.common,
  4740. issues: []
  4741. }
  4742. };
  4743. const result = this._def.innerType._parse({
  4744. data: newCtx.data,
  4745. path: newCtx.path,
  4746. parent: {
  4747. ...newCtx
  4748. }
  4749. });
  4750. if (isAsync(result)) {
  4751. return result.then((result2) => {
  4752. return {
  4753. status: "valid",
  4754. value: result2.status === "valid" ? result2.value : this._def.catchValue({
  4755. get error() {
  4756. return new ZodError(newCtx.common.issues);
  4757. },
  4758. input: newCtx.data
  4759. })
  4760. };
  4761. });
  4762. } else {
  4763. return {
  4764. status: "valid",
  4765. value: result.status === "valid" ? result.value : this._def.catchValue({
  4766. get error() {
  4767. return new ZodError(newCtx.common.issues);
  4768. },
  4769. input: newCtx.data
  4770. })
  4771. };
  4772. }
  4773. }
  4774. removeCatch() {
  4775. return this._def.innerType;
  4776. }
  4777. };
  4778. ZodCatch.create = (type, params) => {
  4779. return new ZodCatch({
  4780. innerType: type,
  4781. typeName: ZodFirstPartyTypeKind.ZodCatch,
  4782. catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
  4783. ...processCreateParams(params)
  4784. });
  4785. };
  4786. var ZodNaN = class extends ZodType {
  4787. _parse(input) {
  4788. const parsedType = this._getType(input);
  4789. if (parsedType !== ZodParsedType.nan) {
  4790. const ctx = this._getOrReturnCtx(input);
  4791. addIssueToContext(ctx, {
  4792. code: ZodIssueCode.invalid_type,
  4793. expected: ZodParsedType.nan,
  4794. received: ctx.parsedType
  4795. });
  4796. return INVALID;
  4797. }
  4798. return { status: "valid", value: input.data };
  4799. }
  4800. };
  4801. ZodNaN.create = (params) => {
  4802. return new ZodNaN({
  4803. typeName: ZodFirstPartyTypeKind.ZodNaN,
  4804. ...processCreateParams(params)
  4805. });
  4806. };
  4807. var BRAND = Symbol("zod_brand");
  4808. var ZodBranded = class extends ZodType {
  4809. _parse(input) {
  4810. const { ctx } = this._processInputParams(input);
  4811. const data = ctx.data;
  4812. return this._def.type._parse({
  4813. data,
  4814. path: ctx.path,
  4815. parent: ctx
  4816. });
  4817. }
  4818. unwrap() {
  4819. return this._def.type;
  4820. }
  4821. };
  4822. var ZodPipeline = class _ZodPipeline extends ZodType {
  4823. _parse(input) {
  4824. const { status, ctx } = this._processInputParams(input);
  4825. if (ctx.common.async) {
  4826. const handleAsync = async () => {
  4827. const inResult = await this._def.in._parseAsync({
  4828. data: ctx.data,
  4829. path: ctx.path,
  4830. parent: ctx
  4831. });
  4832. if (inResult.status === "aborted")
  4833. return INVALID;
  4834. if (inResult.status === "dirty") {
  4835. status.dirty();
  4836. return DIRTY(inResult.value);
  4837. } else {
  4838. return this._def.out._parseAsync({
  4839. data: inResult.value,
  4840. path: ctx.path,
  4841. parent: ctx
  4842. });
  4843. }
  4844. };
  4845. return handleAsync();
  4846. } else {
  4847. const inResult = this._def.in._parseSync({
  4848. data: ctx.data,
  4849. path: ctx.path,
  4850. parent: ctx
  4851. });
  4852. if (inResult.status === "aborted")
  4853. return INVALID;
  4854. if (inResult.status === "dirty") {
  4855. status.dirty();
  4856. return {
  4857. status: "dirty",
  4858. value: inResult.value
  4859. };
  4860. } else {
  4861. return this._def.out._parseSync({
  4862. data: inResult.value,
  4863. path: ctx.path,
  4864. parent: ctx
  4865. });
  4866. }
  4867. }
  4868. }
  4869. static create(a, b) {
  4870. return new _ZodPipeline({
  4871. in: a,
  4872. out: b,
  4873. typeName: ZodFirstPartyTypeKind.ZodPipeline
  4874. });
  4875. }
  4876. };
  4877. var ZodReadonly = class extends ZodType {
  4878. _parse(input) {
  4879. const result = this._def.innerType._parse(input);
  4880. const freeze = (data) => {
  4881. if (isValid(data)) {
  4882. data.value = Object.freeze(data.value);
  4883. }
  4884. return data;
  4885. };
  4886. return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  4887. }
  4888. unwrap() {
  4889. return this._def.innerType;
  4890. }
  4891. };
  4892. ZodReadonly.create = (type, params) => {
  4893. return new ZodReadonly({
  4894. innerType: type,
  4895. typeName: ZodFirstPartyTypeKind.ZodReadonly,
  4896. ...processCreateParams(params)
  4897. });
  4898. };
  4899. var late = {
  4900. object: ZodObject.lazycreate
  4901. };
  4902. var ZodFirstPartyTypeKind;
  4903. (function(ZodFirstPartyTypeKind2) {
  4904. ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  4905. ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  4906. ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  4907. ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  4908. ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  4909. ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  4910. ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  4911. ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  4912. ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  4913. ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  4914. ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  4915. ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  4916. ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  4917. ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  4918. ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  4919. ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  4920. ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  4921. ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  4922. ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  4923. ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  4924. ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  4925. ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  4926. ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  4927. ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  4928. ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  4929. ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  4930. ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  4931. ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  4932. ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  4933. ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  4934. ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  4935. ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  4936. ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  4937. ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  4938. ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  4939. ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
  4940. })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
  4941. var stringType = ZodString.create;
  4942. var numberType = ZodNumber.create;
  4943. var nanType = ZodNaN.create;
  4944. var bigIntType = ZodBigInt.create;
  4945. var booleanType = ZodBoolean.create;
  4946. var dateType = ZodDate.create;
  4947. var symbolType = ZodSymbol.create;
  4948. var undefinedType = ZodUndefined.create;
  4949. var nullType = ZodNull.create;
  4950. var anyType = ZodAny.create;
  4951. var unknownType = ZodUnknown.create;
  4952. var neverType = ZodNever.create;
  4953. var voidType = ZodVoid.create;
  4954. var arrayType = ZodArray.create;
  4955. var objectType = ZodObject.create;
  4956. var strictObjectType = ZodObject.strictCreate;
  4957. var unionType = ZodUnion.create;
  4958. var discriminatedUnionType = ZodDiscriminatedUnion.create;
  4959. var intersectionType = ZodIntersection.create;
  4960. var tupleType = ZodTuple.create;
  4961. var recordType = ZodRecord.create;
  4962. var mapType = ZodMap.create;
  4963. var setType = ZodSet.create;
  4964. var functionType = ZodFunction.create;
  4965. var lazyType = ZodLazy.create;
  4966. var literalType = ZodLiteral.create;
  4967. var enumType = ZodEnum.create;
  4968. var nativeEnumType = ZodNativeEnum.create;
  4969. var promiseType = ZodPromise.create;
  4970. var effectsType = ZodEffects.create;
  4971. var optionalType = ZodOptional.create;
  4972. var nullableType = ZodNullable.create;
  4973. var preprocessType = ZodEffects.createWithPreprocess;
  4974. var pipelineType = ZodPipeline.create;
  4975. // src/serializer/gelSchema.ts
  4976. var enumSchema = objectType({
  4977. name: stringType(),
  4978. schema: stringType(),
  4979. values: stringType().array()
  4980. }).strict();
  4981. var enumSchemaV1 = objectType({
  4982. name: stringType(),
  4983. values: recordType(stringType(), stringType())
  4984. }).strict();
  4985. var indexColumn = objectType({
  4986. expression: stringType(),
  4987. isExpression: booleanType(),
  4988. asc: booleanType(),
  4989. nulls: stringType().optional(),
  4990. opclass: stringType().optional()
  4991. });
  4992. var index = objectType({
  4993. name: stringType(),
  4994. columns: indexColumn.array(),
  4995. isUnique: booleanType(),
  4996. with: recordType(stringType(), anyType()).optional(),
  4997. method: stringType().default("btree"),
  4998. where: stringType().optional(),
  4999. concurrently: booleanType().default(false)
  5000. }).strict();
  5001. var fk = objectType({
  5002. name: stringType(),
  5003. tableFrom: stringType(),
  5004. columnsFrom: stringType().array(),
  5005. tableTo: stringType(),
  5006. schemaTo: stringType().optional(),
  5007. columnsTo: stringType().array(),
  5008. onUpdate: stringType().optional(),
  5009. onDelete: stringType().optional()
  5010. }).strict();
  5011. var sequenceSchema = objectType({
  5012. name: stringType(),
  5013. increment: stringType().optional(),
  5014. minValue: stringType().optional(),
  5015. maxValue: stringType().optional(),
  5016. startWith: stringType().optional(),
  5017. cache: stringType().optional(),
  5018. cycle: booleanType().optional(),
  5019. schema: stringType()
  5020. }).strict();
  5021. var roleSchema = objectType({
  5022. name: stringType(),
  5023. createDb: booleanType().optional(),
  5024. createRole: booleanType().optional(),
  5025. inherit: booleanType().optional()
  5026. }).strict();
  5027. var sequenceSquashed = objectType({
  5028. name: stringType(),
  5029. schema: stringType(),
  5030. values: stringType()
  5031. }).strict();
  5032. var column = objectType({
  5033. name: stringType(),
  5034. type: stringType(),
  5035. typeSchema: stringType().optional(),
  5036. primaryKey: booleanType(),
  5037. notNull: booleanType(),
  5038. default: anyType().optional(),
  5039. isUnique: anyType().optional(),
  5040. uniqueName: stringType().optional(),
  5041. nullsNotDistinct: booleanType().optional(),
  5042. generated: objectType({
  5043. type: literalType("stored"),
  5044. as: stringType()
  5045. }).optional(),
  5046. identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
  5047. }).strict();
  5048. var checkConstraint = objectType({
  5049. name: stringType(),
  5050. value: stringType()
  5051. }).strict();
  5052. var columnSquashed = objectType({
  5053. name: stringType(),
  5054. type: stringType(),
  5055. typeSchema: stringType().optional(),
  5056. primaryKey: booleanType(),
  5057. notNull: booleanType(),
  5058. default: anyType().optional(),
  5059. isUnique: anyType().optional(),
  5060. uniqueName: stringType().optional(),
  5061. nullsNotDistinct: booleanType().optional(),
  5062. generated: objectType({
  5063. type: literalType("stored"),
  5064. as: stringType()
  5065. }).optional(),
  5066. identity: stringType().optional()
  5067. }).strict();
  5068. var compositePK = objectType({
  5069. name: stringType(),
  5070. columns: stringType().array()
  5071. }).strict();
  5072. var uniqueConstraint = objectType({
  5073. name: stringType(),
  5074. columns: stringType().array(),
  5075. nullsNotDistinct: booleanType()
  5076. }).strict();
  5077. var policy = objectType({
  5078. name: stringType(),
  5079. as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
  5080. for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
  5081. to: stringType().array().optional(),
  5082. using: stringType().optional(),
  5083. withCheck: stringType().optional(),
  5084. on: stringType().optional(),
  5085. schema: stringType().optional()
  5086. }).strict();
  5087. var policySquashed = objectType({
  5088. name: stringType(),
  5089. values: stringType()
  5090. }).strict();
  5091. var viewWithOption = objectType({
  5092. checkOption: enumType(["local", "cascaded"]).optional(),
  5093. securityBarrier: booleanType().optional(),
  5094. securityInvoker: booleanType().optional()
  5095. }).strict();
  5096. var matViewWithOption = objectType({
  5097. fillfactor: numberType().optional(),
  5098. toastTupleTarget: numberType().optional(),
  5099. parallelWorkers: numberType().optional(),
  5100. autovacuumEnabled: booleanType().optional(),
  5101. vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
  5102. vacuumTruncate: booleanType().optional(),
  5103. autovacuumVacuumThreshold: numberType().optional(),
  5104. autovacuumVacuumScaleFactor: numberType().optional(),
  5105. autovacuumVacuumCostDelay: numberType().optional(),
  5106. autovacuumVacuumCostLimit: numberType().optional(),
  5107. autovacuumFreezeMinAge: numberType().optional(),
  5108. autovacuumFreezeMaxAge: numberType().optional(),
  5109. autovacuumFreezeTableAge: numberType().optional(),
  5110. autovacuumMultixactFreezeMinAge: numberType().optional(),
  5111. autovacuumMultixactFreezeMaxAge: numberType().optional(),
  5112. autovacuumMultixactFreezeTableAge: numberType().optional(),
  5113. logAutovacuumMinDuration: numberType().optional(),
  5114. userCatalogTable: booleanType().optional()
  5115. }).strict();
  5116. var mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
  5117. var view = objectType({
  5118. name: stringType(),
  5119. schema: stringType(),
  5120. columns: recordType(stringType(), column),
  5121. definition: stringType().optional(),
  5122. materialized: booleanType(),
  5123. with: mergedViewWithOption.optional(),
  5124. isExisting: booleanType(),
  5125. withNoData: booleanType().optional(),
  5126. using: stringType().optional(),
  5127. tablespace: stringType().optional()
  5128. }).strict();
  5129. var table = objectType({
  5130. name: stringType(),
  5131. schema: stringType(),
  5132. columns: recordType(stringType(), column),
  5133. indexes: recordType(stringType(), index),
  5134. foreignKeys: recordType(stringType(), fk),
  5135. compositePrimaryKeys: recordType(stringType(), compositePK),
  5136. uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
  5137. policies: recordType(stringType(), policy).default({}),
  5138. checkConstraints: recordType(stringType(), checkConstraint).default({}),
  5139. isRLSEnabled: booleanType().default(false)
  5140. }).strict();
  5141. var schemaHash = objectType({
  5142. id: stringType(),
  5143. prevId: stringType()
  5144. });
  5145. var kitInternals = objectType({
  5146. tables: recordType(
  5147. stringType(),
  5148. objectType({
  5149. columns: recordType(
  5150. stringType(),
  5151. objectType({
  5152. isArray: booleanType().optional(),
  5153. dimensions: numberType().optional(),
  5154. rawType: stringType().optional(),
  5155. isDefaultAnExpression: booleanType().optional()
  5156. }).optional()
  5157. )
  5158. }).optional()
  5159. )
  5160. }).optional();
  5161. var gelSchemaExternal = objectType({
  5162. version: literalType("1"),
  5163. dialect: literalType("gel"),
  5164. tables: arrayType(table),
  5165. enums: arrayType(enumSchemaV1),
  5166. schemas: arrayType(objectType({ name: stringType() })),
  5167. _meta: objectType({
  5168. schemas: recordType(stringType(), stringType()),
  5169. tables: recordType(stringType(), stringType()),
  5170. columns: recordType(stringType(), stringType())
  5171. })
  5172. }).strict();
  5173. var gelSchemaInternal = objectType({
  5174. version: literalType("1"),
  5175. dialect: literalType("gel"),
  5176. tables: recordType(stringType(), table),
  5177. enums: recordType(stringType(), enumSchema),
  5178. schemas: recordType(stringType(), stringType()),
  5179. views: recordType(stringType(), view).default({}),
  5180. sequences: recordType(stringType(), sequenceSchema).default({}),
  5181. roles: recordType(stringType(), roleSchema).default({}),
  5182. policies: recordType(stringType(), policy).default({}),
  5183. _meta: objectType({
  5184. schemas: recordType(stringType(), stringType()),
  5185. tables: recordType(stringType(), stringType()),
  5186. columns: recordType(stringType(), stringType())
  5187. }),
  5188. internal: kitInternals
  5189. }).strict();
  5190. var tableSquashed = objectType({
  5191. name: stringType(),
  5192. schema: stringType(),
  5193. columns: recordType(stringType(), columnSquashed),
  5194. indexes: recordType(stringType(), stringType()),
  5195. foreignKeys: recordType(stringType(), stringType()),
  5196. compositePrimaryKeys: recordType(stringType(), stringType()),
  5197. uniqueConstraints: recordType(stringType(), stringType()),
  5198. policies: recordType(stringType(), stringType()),
  5199. checkConstraints: recordType(stringType(), stringType()),
  5200. isRLSEnabled: booleanType().default(false)
  5201. }).strict();
  5202. var gelSchemaSquashed = objectType({
  5203. version: literalType("1"),
  5204. dialect: literalType("gel"),
  5205. tables: recordType(stringType(), tableSquashed),
  5206. enums: recordType(stringType(), enumSchema),
  5207. schemas: recordType(stringType(), stringType()),
  5208. views: recordType(stringType(), view),
  5209. sequences: recordType(stringType(), sequenceSquashed),
  5210. roles: recordType(stringType(), roleSchema).default({}),
  5211. policies: recordType(stringType(), policySquashed).default({})
  5212. }).strict();
  5213. var gelSchema = gelSchemaInternal.merge(schemaHash);
  5214. var backwardCompatibleGelSchema = gelSchema;
  5215. var dryGel = gelSchema.parse({
  5216. version: "1",
  5217. dialect: "gel",
  5218. id: originUUID,
  5219. prevId: "",
  5220. tables: {},
  5221. enums: {},
  5222. schemas: {},
  5223. policies: {},
  5224. roles: {},
  5225. sequences: {},
  5226. _meta: {
  5227. schemas: {},
  5228. tables: {},
  5229. columns: {}
  5230. }
  5231. });
  5232. // src/serializer/mysqlSchema.ts
  5233. var index2 = objectType({
  5234. name: stringType(),
  5235. columns: stringType().array(),
  5236. isUnique: booleanType(),
  5237. using: enumType(["btree", "hash"]).optional(),
  5238. algorithm: enumType(["default", "inplace", "copy"]).optional(),
  5239. lock: enumType(["default", "none", "shared", "exclusive"]).optional()
  5240. }).strict();
  5241. var fk2 = objectType({
  5242. name: stringType(),
  5243. tableFrom: stringType(),
  5244. columnsFrom: stringType().array(),
  5245. tableTo: stringType(),
  5246. columnsTo: stringType().array(),
  5247. onUpdate: stringType().optional(),
  5248. onDelete: stringType().optional()
  5249. }).strict();
  5250. var column2 = objectType({
  5251. name: stringType(),
  5252. type: stringType(),
  5253. primaryKey: booleanType(),
  5254. notNull: booleanType(),
  5255. autoincrement: booleanType().optional(),
  5256. default: anyType().optional(),
  5257. onUpdate: anyType().optional(),
  5258. generated: objectType({
  5259. type: enumType(["stored", "virtual"]),
  5260. as: stringType()
  5261. }).optional()
  5262. }).strict();
  5263. var tableV3 = objectType({
  5264. name: stringType(),
  5265. columns: recordType(stringType(), column2),
  5266. indexes: recordType(stringType(), index2),
  5267. foreignKeys: recordType(stringType(), fk2)
  5268. }).strict();
  5269. var compositePK2 = objectType({
  5270. name: stringType(),
  5271. columns: stringType().array()
  5272. }).strict();
  5273. var uniqueConstraint2 = objectType({
  5274. name: stringType(),
  5275. columns: stringType().array()
  5276. }).strict();
  5277. var checkConstraint2 = objectType({
  5278. name: stringType(),
  5279. value: stringType()
  5280. }).strict();
  5281. var tableV4 = objectType({
  5282. name: stringType(),
  5283. schema: stringType().optional(),
  5284. columns: recordType(stringType(), column2),
  5285. indexes: recordType(stringType(), index2),
  5286. foreignKeys: recordType(stringType(), fk2)
  5287. }).strict();
  5288. var table2 = objectType({
  5289. name: stringType(),
  5290. columns: recordType(stringType(), column2),
  5291. indexes: recordType(stringType(), index2),
  5292. foreignKeys: recordType(stringType(), fk2),
  5293. compositePrimaryKeys: recordType(stringType(), compositePK2),
  5294. uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
  5295. checkConstraint: recordType(stringType(), checkConstraint2).default({})
  5296. }).strict();
  5297. var viewMeta = objectType({
  5298. algorithm: enumType(["undefined", "merge", "temptable"]),
  5299. sqlSecurity: enumType(["definer", "invoker"]),
  5300. withCheckOption: enumType(["local", "cascaded"]).optional()
  5301. }).strict();
  5302. var view2 = objectType({
  5303. name: stringType(),
  5304. columns: recordType(stringType(), column2),
  5305. definition: stringType().optional(),
  5306. isExisting: booleanType()
  5307. }).strict().merge(viewMeta);
  5308. var kitInternals2 = objectType({
  5309. tables: recordType(
  5310. stringType(),
  5311. objectType({
  5312. columns: recordType(
  5313. stringType(),
  5314. objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
  5315. )
  5316. }).optional()
  5317. ).optional(),
  5318. indexes: recordType(
  5319. stringType(),
  5320. objectType({
  5321. columns: recordType(
  5322. stringType(),
  5323. objectType({ isExpression: booleanType().optional() }).optional()
  5324. )
  5325. }).optional()
  5326. ).optional()
  5327. }).optional();
  5328. var dialect = literalType("mysql");
  5329. var schemaHash2 = objectType({
  5330. id: stringType(),
  5331. prevId: stringType()
  5332. });
  5333. var schemaInternalV3 = objectType({
  5334. version: literalType("3"),
  5335. dialect,
  5336. tables: recordType(stringType(), tableV3)
  5337. }).strict();
  5338. var schemaInternalV4 = objectType({
  5339. version: literalType("4"),
  5340. dialect,
  5341. tables: recordType(stringType(), tableV4),
  5342. schemas: recordType(stringType(), stringType())
  5343. }).strict();
  5344. var schemaInternalV5 = objectType({
  5345. version: literalType("5"),
  5346. dialect,
  5347. tables: recordType(stringType(), table2),
  5348. schemas: recordType(stringType(), stringType()),
  5349. _meta: objectType({
  5350. schemas: recordType(stringType(), stringType()),
  5351. tables: recordType(stringType(), stringType()),
  5352. columns: recordType(stringType(), stringType())
  5353. }),
  5354. internal: kitInternals2
  5355. }).strict();
  5356. var schemaInternal = objectType({
  5357. version: literalType("5"),
  5358. dialect,
  5359. tables: recordType(stringType(), table2),
  5360. views: recordType(stringType(), view2).default({}),
  5361. _meta: objectType({
  5362. tables: recordType(stringType(), stringType()),
  5363. columns: recordType(stringType(), stringType())
  5364. }),
  5365. internal: kitInternals2
  5366. }).strict();
  5367. var schemaV3 = schemaInternalV3.merge(schemaHash2);
  5368. var schemaV4 = schemaInternalV4.merge(schemaHash2);
  5369. var schemaV5 = schemaInternalV5.merge(schemaHash2);
  5370. var schema = schemaInternal.merge(schemaHash2);
  5371. var tableSquashedV4 = objectType({
  5372. name: stringType(),
  5373. schema: stringType().optional(),
  5374. columns: recordType(stringType(), column2),
  5375. indexes: recordType(stringType(), stringType()),
  5376. foreignKeys: recordType(stringType(), stringType())
  5377. }).strict();
  5378. var tableSquashed2 = objectType({
  5379. name: stringType(),
  5380. columns: recordType(stringType(), column2),
  5381. indexes: recordType(stringType(), stringType()),
  5382. foreignKeys: recordType(stringType(), stringType()),
  5383. compositePrimaryKeys: recordType(stringType(), stringType()),
  5384. uniqueConstraints: recordType(stringType(), stringType()).default({}),
  5385. checkConstraints: recordType(stringType(), stringType()).default({})
  5386. }).strict();
  5387. var viewSquashed = view2.omit({
  5388. algorithm: true,
  5389. sqlSecurity: true,
  5390. withCheckOption: true
  5391. }).extend({ meta: stringType() });
  5392. var schemaSquashed = objectType({
  5393. version: literalType("5"),
  5394. dialect,
  5395. tables: recordType(stringType(), tableSquashed2),
  5396. views: recordType(stringType(), viewSquashed)
  5397. }).strict();
  5398. var schemaSquashedV4 = objectType({
  5399. version: literalType("4"),
  5400. dialect,
  5401. tables: recordType(stringType(), tableSquashedV4),
  5402. schemas: recordType(stringType(), stringType())
  5403. }).strict();
  5404. var mysqlSchema = schema;
  5405. var mysqlSchemaV5 = schemaV5;
  5406. var backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]);
  5407. var dryMySql = mysqlSchema.parse({
  5408. version: "5",
  5409. dialect: "mysql",
  5410. id: originUUID,
  5411. prevId: "",
  5412. tables: {},
  5413. schemas: {},
  5414. views: {},
  5415. _meta: {
  5416. schemas: {},
  5417. tables: {},
  5418. columns: {}
  5419. }
  5420. });
  5421. // src/serializer/pgSchema.ts
  5422. var indexV2 = objectType({
  5423. name: stringType(),
  5424. columns: recordType(
  5425. stringType(),
  5426. objectType({
  5427. name: stringType()
  5428. })
  5429. ),
  5430. isUnique: booleanType()
  5431. }).strict();
  5432. var columnV2 = objectType({
  5433. name: stringType(),
  5434. type: stringType(),
  5435. primaryKey: booleanType(),
  5436. notNull: booleanType(),
  5437. default: anyType().optional(),
  5438. references: stringType().optional()
  5439. }).strict();
  5440. var tableV2 = objectType({
  5441. name: stringType(),
  5442. columns: recordType(stringType(), columnV2),
  5443. indexes: recordType(stringType(), indexV2)
  5444. }).strict();
  5445. var enumSchemaV12 = objectType({
  5446. name: stringType(),
  5447. values: recordType(stringType(), stringType())
  5448. }).strict();
  5449. var enumSchema2 = objectType({
  5450. name: stringType(),
  5451. schema: stringType(),
  5452. values: stringType().array()
  5453. }).strict();
  5454. var pgSchemaV2 = objectType({
  5455. version: literalType("2"),
  5456. tables: recordType(stringType(), tableV2),
  5457. enums: recordType(stringType(), enumSchemaV12)
  5458. }).strict();
  5459. var references = objectType({
  5460. foreignKeyName: stringType(),
  5461. table: stringType(),
  5462. column: stringType(),
  5463. onDelete: stringType().optional(),
  5464. onUpdate: stringType().optional()
  5465. }).strict();
  5466. var columnV1 = objectType({
  5467. name: stringType(),
  5468. type: stringType(),
  5469. primaryKey: booleanType(),
  5470. notNull: booleanType(),
  5471. default: anyType().optional(),
  5472. references: references.optional()
  5473. }).strict();
  5474. var tableV1 = objectType({
  5475. name: stringType(),
  5476. columns: recordType(stringType(), columnV1),
  5477. indexes: recordType(stringType(), indexV2)
  5478. }).strict();
  5479. var pgSchemaV1 = objectType({
  5480. version: literalType("1"),
  5481. tables: recordType(stringType(), tableV1),
  5482. enums: recordType(stringType(), enumSchemaV12)
  5483. }).strict();
  5484. var indexColumn2 = objectType({
  5485. expression: stringType(),
  5486. isExpression: booleanType(),
  5487. asc: booleanType(),
  5488. nulls: stringType().optional(),
  5489. opclass: stringType().optional()
  5490. });
  5491. var index3 = objectType({
  5492. name: stringType(),
  5493. columns: indexColumn2.array(),
  5494. isUnique: booleanType(),
  5495. with: recordType(stringType(), anyType()).optional(),
  5496. method: stringType().default("btree"),
  5497. where: stringType().optional(),
  5498. concurrently: booleanType().default(false)
  5499. }).strict();
  5500. var indexV4 = objectType({
  5501. name: stringType(),
  5502. columns: stringType().array(),
  5503. isUnique: booleanType(),
  5504. with: recordType(stringType(), stringType()).optional(),
  5505. method: stringType().default("btree"),
  5506. where: stringType().optional(),
  5507. concurrently: booleanType().default(false)
  5508. }).strict();
  5509. var indexV5 = objectType({
  5510. name: stringType(),
  5511. columns: stringType().array(),
  5512. isUnique: booleanType(),
  5513. with: recordType(stringType(), stringType()).optional(),
  5514. method: stringType().default("btree"),
  5515. where: stringType().optional(),
  5516. concurrently: booleanType().default(false)
  5517. }).strict();
  5518. var indexV6 = objectType({
  5519. name: stringType(),
  5520. columns: stringType().array(),
  5521. isUnique: booleanType(),
  5522. with: recordType(stringType(), stringType()).optional(),
  5523. method: stringType().default("btree"),
  5524. where: stringType().optional(),
  5525. concurrently: booleanType().default(false)
  5526. }).strict();
  5527. var fk3 = objectType({
  5528. name: stringType(),
  5529. tableFrom: stringType(),
  5530. columnsFrom: stringType().array(),
  5531. tableTo: stringType(),
  5532. schemaTo: stringType().optional(),
  5533. columnsTo: stringType().array(),
  5534. onUpdate: stringType().optional(),
  5535. onDelete: stringType().optional()
  5536. }).strict();
  5537. var sequenceSchema2 = objectType({
  5538. name: stringType(),
  5539. increment: stringType().optional(),
  5540. minValue: stringType().optional(),
  5541. maxValue: stringType().optional(),
  5542. startWith: stringType().optional(),
  5543. cache: stringType().optional(),
  5544. cycle: booleanType().optional(),
  5545. schema: stringType()
  5546. }).strict();
  5547. var roleSchema2 = objectType({
  5548. name: stringType(),
  5549. createDb: booleanType().optional(),
  5550. createRole: booleanType().optional(),
  5551. inherit: booleanType().optional()
  5552. }).strict();
  5553. var sequenceSquashed2 = objectType({
  5554. name: stringType(),
  5555. schema: stringType(),
  5556. values: stringType()
  5557. }).strict();
  5558. var columnV7 = objectType({
  5559. name: stringType(),
  5560. type: stringType(),
  5561. typeSchema: stringType().optional(),
  5562. primaryKey: booleanType(),
  5563. notNull: booleanType(),
  5564. default: anyType().optional(),
  5565. isUnique: anyType().optional(),
  5566. uniqueName: stringType().optional(),
  5567. nullsNotDistinct: booleanType().optional()
  5568. }).strict();
  5569. var column3 = objectType({
  5570. name: stringType(),
  5571. type: stringType(),
  5572. typeSchema: stringType().optional(),
  5573. primaryKey: booleanType(),
  5574. notNull: booleanType(),
  5575. default: anyType().optional(),
  5576. isUnique: anyType().optional(),
  5577. uniqueName: stringType().optional(),
  5578. nullsNotDistinct: booleanType().optional(),
  5579. generated: objectType({
  5580. type: literalType("stored"),
  5581. as: stringType()
  5582. }).optional(),
  5583. identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
  5584. }).strict();
  5585. var checkConstraint3 = objectType({
  5586. name: stringType(),
  5587. value: stringType()
  5588. }).strict();
  5589. var columnSquashed2 = objectType({
  5590. name: stringType(),
  5591. type: stringType(),
  5592. typeSchema: stringType().optional(),
  5593. primaryKey: booleanType(),
  5594. notNull: booleanType(),
  5595. default: anyType().optional(),
  5596. isUnique: anyType().optional(),
  5597. uniqueName: stringType().optional(),
  5598. nullsNotDistinct: booleanType().optional(),
  5599. generated: objectType({
  5600. type: literalType("stored"),
  5601. as: stringType()
  5602. }).optional(),
  5603. identity: stringType().optional()
  5604. }).strict();
  5605. var tableV32 = objectType({
  5606. name: stringType(),
  5607. columns: recordType(stringType(), column3),
  5608. indexes: recordType(stringType(), index3),
  5609. foreignKeys: recordType(stringType(), fk3)
  5610. }).strict();
  5611. var compositePK3 = objectType({
  5612. name: stringType(),
  5613. columns: stringType().array()
  5614. }).strict();
  5615. var uniqueConstraint3 = objectType({
  5616. name: stringType(),
  5617. columns: stringType().array(),
  5618. nullsNotDistinct: booleanType()
  5619. }).strict();
  5620. var policy2 = objectType({
  5621. name: stringType(),
  5622. as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
  5623. for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
  5624. to: stringType().array().optional(),
  5625. using: stringType().optional(),
  5626. withCheck: stringType().optional(),
  5627. on: stringType().optional(),
  5628. schema: stringType().optional()
  5629. }).strict();
  5630. var policySquashed2 = objectType({
  5631. name: stringType(),
  5632. values: stringType()
  5633. }).strict();
  5634. var viewWithOption2 = objectType({
  5635. checkOption: enumType(["local", "cascaded"]).optional(),
  5636. securityBarrier: booleanType().optional(),
  5637. securityInvoker: booleanType().optional()
  5638. }).strict();
  5639. var matViewWithOption2 = objectType({
  5640. fillfactor: numberType().optional(),
  5641. toastTupleTarget: numberType().optional(),
  5642. parallelWorkers: numberType().optional(),
  5643. autovacuumEnabled: booleanType().optional(),
  5644. vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
  5645. vacuumTruncate: booleanType().optional(),
  5646. autovacuumVacuumThreshold: numberType().optional(),
  5647. autovacuumVacuumScaleFactor: numberType().optional(),
  5648. autovacuumVacuumCostDelay: numberType().optional(),
  5649. autovacuumVacuumCostLimit: numberType().optional(),
  5650. autovacuumFreezeMinAge: numberType().optional(),
  5651. autovacuumFreezeMaxAge: numberType().optional(),
  5652. autovacuumFreezeTableAge: numberType().optional(),
  5653. autovacuumMultixactFreezeMinAge: numberType().optional(),
  5654. autovacuumMultixactFreezeMaxAge: numberType().optional(),
  5655. autovacuumMultixactFreezeTableAge: numberType().optional(),
  5656. logAutovacuumMinDuration: numberType().optional(),
  5657. userCatalogTable: booleanType().optional()
  5658. }).strict();
  5659. var mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict();
  5660. var view3 = objectType({
  5661. name: stringType(),
  5662. schema: stringType(),
  5663. columns: recordType(stringType(), column3),
  5664. definition: stringType().optional(),
  5665. materialized: booleanType(),
  5666. with: mergedViewWithOption2.optional(),
  5667. isExisting: booleanType(),
  5668. withNoData: booleanType().optional(),
  5669. using: stringType().optional(),
  5670. tablespace: stringType().optional()
  5671. }).strict();
  5672. var tableV42 = objectType({
  5673. name: stringType(),
  5674. schema: stringType(),
  5675. columns: recordType(stringType(), column3),
  5676. indexes: recordType(stringType(), indexV4),
  5677. foreignKeys: recordType(stringType(), fk3)
  5678. }).strict();
  5679. var tableV5 = objectType({
  5680. name: stringType(),
  5681. schema: stringType(),
  5682. columns: recordType(stringType(), column3),
  5683. indexes: recordType(stringType(), indexV5),
  5684. foreignKeys: recordType(stringType(), fk3),
  5685. compositePrimaryKeys: recordType(stringType(), compositePK3),
  5686. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
  5687. }).strict();
  5688. var tableV6 = objectType({
  5689. name: stringType(),
  5690. schema: stringType(),
  5691. columns: recordType(stringType(), column3),
  5692. indexes: recordType(stringType(), indexV6),
  5693. foreignKeys: recordType(stringType(), fk3),
  5694. compositePrimaryKeys: recordType(stringType(), compositePK3),
  5695. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
  5696. }).strict();
  5697. var tableV7 = objectType({
  5698. name: stringType(),
  5699. schema: stringType(),
  5700. columns: recordType(stringType(), columnV7),
  5701. indexes: recordType(stringType(), index3),
  5702. foreignKeys: recordType(stringType(), fk3),
  5703. compositePrimaryKeys: recordType(stringType(), compositePK3),
  5704. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
  5705. }).strict();
  5706. var table3 = objectType({
  5707. name: stringType(),
  5708. schema: stringType(),
  5709. columns: recordType(stringType(), column3),
  5710. indexes: recordType(stringType(), index3),
  5711. foreignKeys: recordType(stringType(), fk3),
  5712. compositePrimaryKeys: recordType(stringType(), compositePK3),
  5713. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}),
  5714. policies: recordType(stringType(), policy2).default({}),
  5715. checkConstraints: recordType(stringType(), checkConstraint3).default({}),
  5716. isRLSEnabled: booleanType().default(false)
  5717. }).strict();
  5718. var schemaHash3 = objectType({
  5719. id: stringType(),
  5720. prevId: stringType()
  5721. });
  5722. var kitInternals3 = objectType({
  5723. tables: recordType(
  5724. stringType(),
  5725. objectType({
  5726. columns: recordType(
  5727. stringType(),
  5728. objectType({
  5729. isArray: booleanType().optional(),
  5730. dimensions: numberType().optional(),
  5731. rawType: stringType().optional(),
  5732. isDefaultAnExpression: booleanType().optional()
  5733. }).optional()
  5734. )
  5735. }).optional()
  5736. )
  5737. }).optional();
  5738. var pgSchemaInternalV3 = objectType({
  5739. version: literalType("3"),
  5740. dialect: literalType("pg"),
  5741. tables: recordType(stringType(), tableV32),
  5742. enums: recordType(stringType(), enumSchemaV12)
  5743. }).strict();
  5744. var pgSchemaInternalV4 = objectType({
  5745. version: literalType("4"),
  5746. dialect: literalType("pg"),
  5747. tables: recordType(stringType(), tableV42),
  5748. enums: recordType(stringType(), enumSchemaV12),
  5749. schemas: recordType(stringType(), stringType())
  5750. }).strict();
  5751. var pgSchemaInternalV5 = objectType({
  5752. version: literalType("5"),
  5753. dialect: literalType("pg"),
  5754. tables: recordType(stringType(), tableV5),
  5755. enums: recordType(stringType(), enumSchemaV12),
  5756. schemas: recordType(stringType(), stringType()),
  5757. _meta: objectType({
  5758. schemas: recordType(stringType(), stringType()),
  5759. tables: recordType(stringType(), stringType()),
  5760. columns: recordType(stringType(), stringType())
  5761. }),
  5762. internal: kitInternals3
  5763. }).strict();
  5764. var pgSchemaInternalV6 = objectType({
  5765. version: literalType("6"),
  5766. dialect: literalType("postgresql"),
  5767. tables: recordType(stringType(), tableV6),
  5768. enums: recordType(stringType(), enumSchema2),
  5769. schemas: recordType(stringType(), stringType()),
  5770. _meta: objectType({
  5771. schemas: recordType(stringType(), stringType()),
  5772. tables: recordType(stringType(), stringType()),
  5773. columns: recordType(stringType(), stringType())
  5774. }),
  5775. internal: kitInternals3
  5776. }).strict();
  5777. var pgSchemaExternal = objectType({
  5778. version: literalType("5"),
  5779. dialect: literalType("pg"),
  5780. tables: arrayType(table3),
  5781. enums: arrayType(enumSchemaV12),
  5782. schemas: arrayType(objectType({ name: stringType() })),
  5783. _meta: objectType({
  5784. schemas: recordType(stringType(), stringType()),
  5785. tables: recordType(stringType(), stringType()),
  5786. columns: recordType(stringType(), stringType())
  5787. })
  5788. }).strict();
  5789. var pgSchemaInternalV7 = objectType({
  5790. version: literalType("7"),
  5791. dialect: literalType("postgresql"),
  5792. tables: recordType(stringType(), tableV7),
  5793. enums: recordType(stringType(), enumSchema2),
  5794. schemas: recordType(stringType(), stringType()),
  5795. sequences: recordType(stringType(), sequenceSchema2),
  5796. _meta: objectType({
  5797. schemas: recordType(stringType(), stringType()),
  5798. tables: recordType(stringType(), stringType()),
  5799. columns: recordType(stringType(), stringType())
  5800. }),
  5801. internal: kitInternals3
  5802. }).strict();
  5803. var pgSchemaInternal = objectType({
  5804. version: literalType("7"),
  5805. dialect: literalType("postgresql"),
  5806. tables: recordType(stringType(), table3),
  5807. enums: recordType(stringType(), enumSchema2),
  5808. schemas: recordType(stringType(), stringType()),
  5809. views: recordType(stringType(), view3).default({}),
  5810. sequences: recordType(stringType(), sequenceSchema2).default({}),
  5811. roles: recordType(stringType(), roleSchema2).default({}),
  5812. policies: recordType(stringType(), policy2).default({}),
  5813. _meta: objectType({
  5814. schemas: recordType(stringType(), stringType()),
  5815. tables: recordType(stringType(), stringType()),
  5816. columns: recordType(stringType(), stringType())
  5817. }),
  5818. internal: kitInternals3
  5819. }).strict();
  5820. var tableSquashed3 = objectType({
  5821. name: stringType(),
  5822. schema: stringType(),
  5823. columns: recordType(stringType(), columnSquashed2),
  5824. indexes: recordType(stringType(), stringType()),
  5825. foreignKeys: recordType(stringType(), stringType()),
  5826. compositePrimaryKeys: recordType(stringType(), stringType()),
  5827. uniqueConstraints: recordType(stringType(), stringType()),
  5828. policies: recordType(stringType(), stringType()),
  5829. checkConstraints: recordType(stringType(), stringType()),
  5830. isRLSEnabled: booleanType().default(false)
  5831. }).strict();
  5832. var tableSquashedV42 = objectType({
  5833. name: stringType(),
  5834. schema: stringType(),
  5835. columns: recordType(stringType(), column3),
  5836. indexes: recordType(stringType(), stringType()),
  5837. foreignKeys: recordType(stringType(), stringType())
  5838. }).strict();
  5839. var pgSchemaSquashedV4 = objectType({
  5840. version: literalType("4"),
  5841. dialect: literalType("pg"),
  5842. tables: recordType(stringType(), tableSquashedV42),
  5843. enums: recordType(stringType(), enumSchemaV12),
  5844. schemas: recordType(stringType(), stringType())
  5845. }).strict();
  5846. var pgSchemaSquashedV6 = objectType({
  5847. version: literalType("6"),
  5848. dialect: literalType("postgresql"),
  5849. tables: recordType(stringType(), tableSquashed3),
  5850. enums: recordType(stringType(), enumSchema2),
  5851. schemas: recordType(stringType(), stringType())
  5852. }).strict();
  5853. var pgSchemaSquashed = objectType({
  5854. version: literalType("7"),
  5855. dialect: literalType("postgresql"),
  5856. tables: recordType(stringType(), tableSquashed3),
  5857. enums: recordType(stringType(), enumSchema2),
  5858. schemas: recordType(stringType(), stringType()),
  5859. views: recordType(stringType(), view3),
  5860. sequences: recordType(stringType(), sequenceSquashed2),
  5861. roles: recordType(stringType(), roleSchema2).default({}),
  5862. policies: recordType(stringType(), policySquashed2).default({})
  5863. }).strict();
  5864. var pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash3);
  5865. var pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash3);
  5866. var pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash3);
  5867. var pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash3);
  5868. var pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash3);
  5869. var pgSchema = pgSchemaInternal.merge(schemaHash3);
  5870. var backwardCompatiblePgSchema = unionType([
  5871. pgSchemaV5,
  5872. pgSchemaV6,
  5873. pgSchema
  5874. ]);
  5875. var dryPg = pgSchema.parse({
  5876. version: snapshotVersion,
  5877. dialect: "postgresql",
  5878. id: originUUID,
  5879. prevId: "",
  5880. tables: {},
  5881. enums: {},
  5882. schemas: {},
  5883. policies: {},
  5884. roles: {},
  5885. sequences: {},
  5886. _meta: {
  5887. schemas: {},
  5888. tables: {},
  5889. columns: {}
  5890. }
  5891. });
  5892. // src/serializer/singlestoreSchema.ts
  5893. var index4 = objectType({
  5894. name: stringType(),
  5895. columns: stringType().array(),
  5896. isUnique: booleanType(),
  5897. using: enumType(["btree", "hash"]).optional(),
  5898. algorithm: enumType(["default", "inplace", "copy"]).optional(),
  5899. lock: enumType(["default", "none", "shared", "exclusive"]).optional()
  5900. }).strict();
  5901. var column4 = objectType({
  5902. name: stringType(),
  5903. type: stringType(),
  5904. primaryKey: booleanType(),
  5905. notNull: booleanType(),
  5906. autoincrement: booleanType().optional(),
  5907. default: anyType().optional(),
  5908. onUpdate: anyType().optional(),
  5909. generated: objectType({
  5910. type: enumType(["stored", "virtual"]),
  5911. as: stringType()
  5912. }).optional()
  5913. }).strict();
  5914. var compositePK4 = objectType({
  5915. name: stringType(),
  5916. columns: stringType().array()
  5917. }).strict();
  5918. var uniqueConstraint4 = objectType({
  5919. name: stringType(),
  5920. columns: stringType().array()
  5921. }).strict();
  5922. var table4 = objectType({
  5923. name: stringType(),
  5924. columns: recordType(stringType(), column4),
  5925. indexes: recordType(stringType(), index4),
  5926. compositePrimaryKeys: recordType(stringType(), compositePK4),
  5927. uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({})
  5928. }).strict();
  5929. var viewMeta2 = objectType({
  5930. algorithm: enumType(["undefined", "merge", "temptable"]),
  5931. sqlSecurity: enumType(["definer", "invoker"]),
  5932. withCheckOption: enumType(["local", "cascaded"]).optional()
  5933. }).strict();
  5934. var kitInternals4 = objectType({
  5935. tables: recordType(
  5936. stringType(),
  5937. objectType({
  5938. columns: recordType(
  5939. stringType(),
  5940. objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
  5941. )
  5942. }).optional()
  5943. ).optional(),
  5944. indexes: recordType(
  5945. stringType(),
  5946. objectType({
  5947. columns: recordType(
  5948. stringType(),
  5949. objectType({ isExpression: booleanType().optional() }).optional()
  5950. )
  5951. }).optional()
  5952. ).optional()
  5953. }).optional();
  5954. var dialect2 = literalType("singlestore");
  5955. var schemaHash4 = objectType({
  5956. id: stringType(),
  5957. prevId: stringType()
  5958. });
  5959. var schemaInternal2 = objectType({
  5960. version: literalType("1"),
  5961. dialect: dialect2,
  5962. tables: recordType(stringType(), table4),
  5963. /* views: record(string(), view).default({}), */
  5964. _meta: objectType({
  5965. tables: recordType(stringType(), stringType()),
  5966. columns: recordType(stringType(), stringType())
  5967. }),
  5968. internal: kitInternals4
  5969. }).strict();
  5970. var schema2 = schemaInternal2.merge(schemaHash4);
  5971. var tableSquashed4 = objectType({
  5972. name: stringType(),
  5973. columns: recordType(stringType(), column4),
  5974. indexes: recordType(stringType(), stringType()),
  5975. compositePrimaryKeys: recordType(stringType(), stringType()),
  5976. uniqueConstraints: recordType(stringType(), stringType()).default({})
  5977. }).strict();
  5978. var schemaSquashed2 = objectType({
  5979. version: literalType("1"),
  5980. dialect: dialect2,
  5981. tables: recordType(stringType(), tableSquashed4)
  5982. /* views: record(string(), viewSquashed), */
  5983. }).strict();
  5984. var singlestoreSchema = schema2;
  5985. var backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]);
  5986. var drySingleStore = singlestoreSchema.parse({
  5987. version: "1",
  5988. dialect: "singlestore",
  5989. id: originUUID,
  5990. prevId: "",
  5991. tables: {},
  5992. schemas: {},
  5993. /* views: {}, */
  5994. _meta: {
  5995. schemas: {},
  5996. tables: {},
  5997. columns: {}
  5998. }
  5999. });
  6000. // src/serializer/sqliteSchema.ts
  6001. var index5 = objectType({
  6002. name: stringType(),
  6003. columns: stringType().array(),
  6004. where: stringType().optional(),
  6005. isUnique: booleanType()
  6006. }).strict();
  6007. var fk4 = objectType({
  6008. name: stringType(),
  6009. tableFrom: stringType(),
  6010. columnsFrom: stringType().array(),
  6011. tableTo: stringType(),
  6012. columnsTo: stringType().array(),
  6013. onUpdate: stringType().optional(),
  6014. onDelete: stringType().optional()
  6015. }).strict();
  6016. var compositePK5 = objectType({
  6017. columns: stringType().array(),
  6018. name: stringType().optional()
  6019. }).strict();
  6020. var column5 = objectType({
  6021. name: stringType(),
  6022. type: stringType(),
  6023. primaryKey: booleanType(),
  6024. notNull: booleanType(),
  6025. autoincrement: booleanType().optional(),
  6026. default: anyType().optional(),
  6027. generated: objectType({
  6028. type: enumType(["stored", "virtual"]),
  6029. as: stringType()
  6030. }).optional()
  6031. }).strict();
  6032. var tableV33 = objectType({
  6033. name: stringType(),
  6034. columns: recordType(stringType(), column5),
  6035. indexes: recordType(stringType(), index5),
  6036. foreignKeys: recordType(stringType(), fk4)
  6037. }).strict();
  6038. var uniqueConstraint5 = objectType({
  6039. name: stringType(),
  6040. columns: stringType().array()
  6041. }).strict();
  6042. var checkConstraint4 = objectType({
  6043. name: stringType(),
  6044. value: stringType()
  6045. }).strict();
  6046. var table5 = objectType({
  6047. name: stringType(),
  6048. columns: recordType(stringType(), column5),
  6049. indexes: recordType(stringType(), index5),
  6050. foreignKeys: recordType(stringType(), fk4),
  6051. compositePrimaryKeys: recordType(stringType(), compositePK5),
  6052. uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}),
  6053. checkConstraints: recordType(stringType(), checkConstraint4).default({})
  6054. }).strict();
  6055. var view4 = objectType({
  6056. name: stringType(),
  6057. columns: recordType(stringType(), column5),
  6058. definition: stringType().optional(),
  6059. isExisting: booleanType()
  6060. }).strict();
  6061. var dialect3 = enumType(["sqlite"]);
  6062. var schemaHash5 = objectType({
  6063. id: stringType(),
  6064. prevId: stringType()
  6065. }).strict();
  6066. var schemaInternalV32 = objectType({
  6067. version: literalType("3"),
  6068. dialect: dialect3,
  6069. tables: recordType(stringType(), tableV33),
  6070. enums: objectType({})
  6071. }).strict();
  6072. var schemaInternalV42 = objectType({
  6073. version: literalType("4"),
  6074. dialect: dialect3,
  6075. tables: recordType(stringType(), table5),
  6076. views: recordType(stringType(), view4).default({}),
  6077. enums: objectType({})
  6078. }).strict();
  6079. var schemaInternalV52 = objectType({
  6080. version: literalType("5"),
  6081. dialect: dialect3,
  6082. tables: recordType(stringType(), table5),
  6083. enums: objectType({}),
  6084. _meta: objectType({
  6085. tables: recordType(stringType(), stringType()),
  6086. columns: recordType(stringType(), stringType())
  6087. })
  6088. }).strict();
  6089. var kitInternals5 = objectType({
  6090. indexes: recordType(
  6091. stringType(),
  6092. objectType({
  6093. columns: recordType(
  6094. stringType(),
  6095. objectType({ isExpression: booleanType().optional() }).optional()
  6096. )
  6097. }).optional()
  6098. ).optional()
  6099. }).optional();
  6100. var latestVersion = literalType("6");
  6101. var schemaInternal3 = objectType({
  6102. version: latestVersion,
  6103. dialect: dialect3,
  6104. tables: recordType(stringType(), table5),
  6105. views: recordType(stringType(), view4).default({}),
  6106. enums: objectType({}),
  6107. _meta: objectType({
  6108. tables: recordType(stringType(), stringType()),
  6109. columns: recordType(stringType(), stringType())
  6110. }),
  6111. internal: kitInternals5
  6112. }).strict();
  6113. var schemaV32 = schemaInternalV32.merge(schemaHash5).strict();
  6114. var schemaV42 = schemaInternalV42.merge(schemaHash5).strict();
  6115. var schemaV52 = schemaInternalV52.merge(schemaHash5).strict();
  6116. var schema3 = schemaInternal3.merge(schemaHash5).strict();
  6117. var tableSquashed5 = objectType({
  6118. name: stringType(),
  6119. columns: recordType(stringType(), column5),
  6120. indexes: recordType(stringType(), stringType()),
  6121. foreignKeys: recordType(stringType(), stringType()),
  6122. compositePrimaryKeys: recordType(stringType(), stringType()),
  6123. uniqueConstraints: recordType(stringType(), stringType()).default({}),
  6124. checkConstraints: recordType(stringType(), stringType()).default({})
  6125. }).strict();
  6126. var schemaSquashed3 = objectType({
  6127. version: latestVersion,
  6128. dialect: dialect3,
  6129. tables: recordType(stringType(), tableSquashed5),
  6130. views: recordType(stringType(), view4),
  6131. enums: anyType()
  6132. }).strict();
  6133. var drySQLite = schema3.parse({
  6134. version: "6",
  6135. dialect: "sqlite",
  6136. id: originUUID,
  6137. prevId: "",
  6138. tables: {},
  6139. views: {},
  6140. enums: {},
  6141. _meta: {
  6142. tables: {},
  6143. columns: {}
  6144. }
  6145. });
  6146. var sqliteSchemaV5 = schemaV52;
  6147. var backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]);
  6148. // src/utils.ts
  6149. var copy = (it) => {
  6150. return JSON.parse(JSON.stringify(it));
  6151. };
  6152. var objectValues = (obj) => {
  6153. return Object.values(obj);
  6154. };
  6155. var assertV1OutFolder = (out) => {
  6156. if (!(0, import_fs.existsSync)(out)) return;
  6157. const oldMigrationFolders = (0, import_fs.readdirSync)(out).filter(
  6158. (it) => it.length === 14 && /^\d+$/.test(it)
  6159. );
  6160. if (oldMigrationFolders.length > 0) {
  6161. console.log(
  6162. `Your migrations folder format is outdated, please run ${source_default.green.bold(
  6163. `drizzle-kit up`
  6164. )}`
  6165. );
  6166. process.exit(1);
  6167. }
  6168. };
  6169. var dryJournal = (dialect4) => {
  6170. return {
  6171. version: snapshotVersion,
  6172. dialect: dialect4,
  6173. entries: []
  6174. };
  6175. };
  6176. var prepareOutFolder = (out, dialect4) => {
  6177. const meta = (0, import_path.join)(out, "meta");
  6178. const journalPath = (0, import_path.join)(meta, "_journal.json");
  6179. if (!(0, import_fs.existsSync)((0, import_path.join)(out, "meta"))) {
  6180. (0, import_fs.mkdirSync)(meta, { recursive: true });
  6181. (0, import_fs.writeFileSync)(journalPath, JSON.stringify(dryJournal(dialect4)));
  6182. }
  6183. const journal = JSON.parse((0, import_fs.readFileSync)(journalPath).toString());
  6184. const snapshots = (0, import_fs.readdirSync)(meta).filter((it) => !it.startsWith("_")).map((it) => (0, import_path.join)(meta, it));
  6185. snapshots.sort();
  6186. return { meta, snapshots, journal };
  6187. };
  6188. var validatorForDialect = (dialect4) => {
  6189. switch (dialect4) {
  6190. case "postgresql":
  6191. return { validator: backwardCompatiblePgSchema, version: 7 };
  6192. case "sqlite":
  6193. return { validator: backwardCompatibleSqliteSchema, version: 6 };
  6194. case "turso":
  6195. return { validator: backwardCompatibleSqliteSchema, version: 6 };
  6196. case "mysql":
  6197. return { validator: backwardCompatibleMysqlSchema, version: 5 };
  6198. case "singlestore":
  6199. return { validator: backwardCompatibleSingleStoreSchema, version: 1 };
  6200. case "gel":
  6201. return { validator: backwardCompatibleGelSchema, version: 1 };
  6202. }
  6203. };
  6204. var validateWithReport = (snapshots, dialect4) => {
  6205. const { validator, version } = validatorForDialect(dialect4);
  6206. const result = snapshots.reduce(
  6207. (accum, it) => {
  6208. const raw = JSON.parse((0, import_fs.readFileSync)(`./${it}`).toString());
  6209. accum.rawMap[it] = raw;
  6210. if (raw["version"] && Number(raw["version"]) > version) {
  6211. console.log(
  6212. info(
  6213. `${it} snapshot is of unsupported version, please update drizzle-kit`
  6214. )
  6215. );
  6216. process.exit(0);
  6217. }
  6218. const result2 = validator.safeParse(raw);
  6219. if (!result2.success) {
  6220. accum.malformed.push(it);
  6221. return accum;
  6222. }
  6223. const snapshot = result2.data;
  6224. if (snapshot.version !== String(version)) {
  6225. accum.nonLatest.push(it);
  6226. return accum;
  6227. }
  6228. const idEntry = accum.idsMap[snapshot["prevId"]] ?? {
  6229. parent: it,
  6230. snapshots: []
  6231. };
  6232. idEntry.snapshots.push(it);
  6233. accum.idsMap[snapshot["prevId"]] = idEntry;
  6234. return accum;
  6235. },
  6236. {
  6237. malformed: [],
  6238. nonLatest: [],
  6239. idToNameMap: {},
  6240. idsMap: {},
  6241. rawMap: {}
  6242. }
  6243. );
  6244. return result;
  6245. };
  6246. var prepareMigrationFolder = (outFolder = "drizzle", dialect4) => {
  6247. const { snapshots, journal } = prepareOutFolder(outFolder, dialect4);
  6248. const report = validateWithReport(snapshots, dialect4);
  6249. if (report.nonLatest.length > 0) {
  6250. console.log(
  6251. report.nonLatest.map((it) => {
  6252. return `${it}/snapshot.json is not of the latest version`;
  6253. }).concat(`Run ${source_default.green.bold(`drizzle-kit up`)}`).join("\n")
  6254. );
  6255. process.exit(0);
  6256. }
  6257. if (report.malformed.length) {
  6258. const message2 = report.malformed.map((it) => {
  6259. return `${it} data is malformed`;
  6260. }).join("\n");
  6261. console.log(message2);
  6262. }
  6263. const collisionEntries = Object.entries(report.idsMap).filter(
  6264. (it) => it[1].snapshots.length > 1
  6265. );
  6266. const message = collisionEntries.map((it) => {
  6267. const data = it[1];
  6268. return `[${data.snapshots.join(
  6269. ", "
  6270. )}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
  6271. }).join("\n").trim();
  6272. if (message) {
  6273. console.log(source_default.red.bold("Error:"), message);
  6274. }
  6275. const abort = report.malformed.length || collisionEntries.length > 0;
  6276. if (abort) {
  6277. process.exit(0);
  6278. }
  6279. return { snapshots, journal };
  6280. };
  6281. var prepareMigrationMeta = (schemas, tables, columns) => {
  6282. const _meta = {
  6283. schemas: {},
  6284. tables: {},
  6285. columns: {}
  6286. };
  6287. schemas.forEach((it) => {
  6288. const from = schemaRenameKey(it.from);
  6289. const to = schemaRenameKey(it.to);
  6290. _meta.schemas[from] = to;
  6291. });
  6292. tables.forEach((it) => {
  6293. const from = tableRenameKey(it.from);
  6294. const to = tableRenameKey(it.to);
  6295. _meta.tables[from] = to;
  6296. });
  6297. columns.forEach((it) => {
  6298. const from = columnRenameKey(it.from.table, it.from.schema, it.from.column);
  6299. const to = columnRenameKey(it.to.table, it.to.schema, it.to.column);
  6300. _meta.columns[from] = to;
  6301. });
  6302. return _meta;
  6303. };
  6304. var schemaRenameKey = (it) => {
  6305. return it;
  6306. };
  6307. var tableRenameKey = (it) => {
  6308. const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`;
  6309. return out;
  6310. };
  6311. var columnRenameKey = (table6, schema4, column6) => {
  6312. const out = schema4 ? `"${schema4}"."${table6}"."${column6}"` : `"${table6}"."${column6}"`;
  6313. return out;
  6314. };
  6315. var kloudMeta = () => {
  6316. return {
  6317. pg: [5],
  6318. mysql: [],
  6319. sqlite: []
  6320. };
  6321. };
  6322. var normaliseSQLiteUrl = (it, type) => {
  6323. if (type === "libsql") {
  6324. if (it.startsWith("file:")) {
  6325. return it;
  6326. }
  6327. try {
  6328. const url = (0, import_url.parse)(it);
  6329. if (url.protocol === null) {
  6330. return `file:${it}`;
  6331. }
  6332. return it;
  6333. } catch (e) {
  6334. return `file:${it}`;
  6335. }
  6336. }
  6337. if (type === "better-sqlite") {
  6338. if (it.startsWith("file:")) {
  6339. return it.substring(5);
  6340. }
  6341. return it;
  6342. }
  6343. assertUnreachable(type);
  6344. };
  6345. var normalisePGliteUrl = (it) => {
  6346. if (it.startsWith("file:")) {
  6347. return it.substring(5);
  6348. }
  6349. return it;
  6350. };
  6351. function isPgArrayType(sqlType) {
  6352. return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
  6353. }
  6354. function findAddedAndRemoved(columnNames1, columnNames2) {
  6355. const set1 = new Set(columnNames1);
  6356. const set2 = new Set(columnNames2);
  6357. const addedColumns = columnNames2.filter((it) => !set1.has(it));
  6358. const removedColumns = columnNames1.filter((it) => !set2.has(it));
  6359. return { addedColumns, removedColumns };
  6360. }
  6361. function escapeSingleQuotes(str) {
  6362. return str.replace(/'/g, "''");
  6363. }
  6364. function unescapeSingleQuotes(str, ignoreFirstAndLastChar) {
  6365. const regex = ignoreFirstAndLastChar ? /(?<!^)'(?!$)/g : /'/g;
  6366. return str.replace(/''/g, "'").replace(regex, "\\'");
  6367. }
  6368. // Annotate the CommonJS export names for ESM import in node:
  6369. 0 && (module.exports = {
  6370. assertV1OutFolder,
  6371. columnRenameKey,
  6372. copy,
  6373. dryJournal,
  6374. escapeSingleQuotes,
  6375. findAddedAndRemoved,
  6376. isPgArrayType,
  6377. kloudMeta,
  6378. normalisePGliteUrl,
  6379. normaliseSQLiteUrl,
  6380. objectValues,
  6381. prepareMigrationFolder,
  6382. prepareMigrationMeta,
  6383. prepareOutFolder,
  6384. schemaRenameKey,
  6385. tableRenameKey,
  6386. unescapeSingleQuotes,
  6387. validateWithReport
  6388. });