utils.mjs 193 KB

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