index.umd.js 155 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Zod = {}));
  5. })(this, (function (exports) { 'use strict';
  6. exports.util = void 0;
  7. (function (util) {
  8. util.assertEqual = (val) => val;
  9. function assertIs(_arg) { }
  10. util.assertIs = assertIs;
  11. function assertNever(_x) {
  12. throw new Error();
  13. }
  14. util.assertNever = assertNever;
  15. util.arrayToEnum = (items) => {
  16. const obj = {};
  17. for (const item of items) {
  18. obj[item] = item;
  19. }
  20. return obj;
  21. };
  22. util.getValidEnumValues = (obj) => {
  23. const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
  24. const filtered = {};
  25. for (const k of validKeys) {
  26. filtered[k] = obj[k];
  27. }
  28. return util.objectValues(filtered);
  29. };
  30. util.objectValues = (obj) => {
  31. return util.objectKeys(obj).map(function (e) {
  32. return obj[e];
  33. });
  34. };
  35. util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
  36. ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
  37. : (object) => {
  38. const keys = [];
  39. for (const key in object) {
  40. if (Object.prototype.hasOwnProperty.call(object, key)) {
  41. keys.push(key);
  42. }
  43. }
  44. return keys;
  45. };
  46. util.find = (arr, checker) => {
  47. for (const item of arr) {
  48. if (checker(item))
  49. return item;
  50. }
  51. return undefined;
  52. };
  53. util.isInteger = typeof Number.isInteger === "function"
  54. ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
  55. : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
  56. function joinValues(array, separator = " | ") {
  57. return array
  58. .map((val) => (typeof val === "string" ? `'${val}'` : val))
  59. .join(separator);
  60. }
  61. util.joinValues = joinValues;
  62. util.jsonStringifyReplacer = (_, value) => {
  63. if (typeof value === "bigint") {
  64. return value.toString();
  65. }
  66. return value;
  67. };
  68. })(exports.util || (exports.util = {}));
  69. exports.objectUtil = void 0;
  70. (function (objectUtil) {
  71. objectUtil.mergeShapes = (first, second) => {
  72. return {
  73. ...first,
  74. ...second, // second overwrites first
  75. };
  76. };
  77. })(exports.objectUtil || (exports.objectUtil = {}));
  78. const ZodParsedType = exports.util.arrayToEnum([
  79. "string",
  80. "nan",
  81. "number",
  82. "integer",
  83. "float",
  84. "boolean",
  85. "date",
  86. "bigint",
  87. "symbol",
  88. "function",
  89. "undefined",
  90. "null",
  91. "array",
  92. "object",
  93. "unknown",
  94. "promise",
  95. "void",
  96. "never",
  97. "map",
  98. "set",
  99. ]);
  100. const getParsedType = (data) => {
  101. const t = typeof data;
  102. switch (t) {
  103. case "undefined":
  104. return ZodParsedType.undefined;
  105. case "string":
  106. return ZodParsedType.string;
  107. case "number":
  108. return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
  109. case "boolean":
  110. return ZodParsedType.boolean;
  111. case "function":
  112. return ZodParsedType.function;
  113. case "bigint":
  114. return ZodParsedType.bigint;
  115. case "symbol":
  116. return ZodParsedType.symbol;
  117. case "object":
  118. if (Array.isArray(data)) {
  119. return ZodParsedType.array;
  120. }
  121. if (data === null) {
  122. return ZodParsedType.null;
  123. }
  124. if (data.then &&
  125. typeof data.then === "function" &&
  126. data.catch &&
  127. typeof data.catch === "function") {
  128. return ZodParsedType.promise;
  129. }
  130. if (typeof Map !== "undefined" && data instanceof Map) {
  131. return ZodParsedType.map;
  132. }
  133. if (typeof Set !== "undefined" && data instanceof Set) {
  134. return ZodParsedType.set;
  135. }
  136. if (typeof Date !== "undefined" && data instanceof Date) {
  137. return ZodParsedType.date;
  138. }
  139. return ZodParsedType.object;
  140. default:
  141. return ZodParsedType.unknown;
  142. }
  143. };
  144. const ZodIssueCode = exports.util.arrayToEnum([
  145. "invalid_type",
  146. "invalid_literal",
  147. "custom",
  148. "invalid_union",
  149. "invalid_union_discriminator",
  150. "invalid_enum_value",
  151. "unrecognized_keys",
  152. "invalid_arguments",
  153. "invalid_return_type",
  154. "invalid_date",
  155. "invalid_string",
  156. "too_small",
  157. "too_big",
  158. "invalid_intersection_types",
  159. "not_multiple_of",
  160. "not_finite",
  161. ]);
  162. const quotelessJson = (obj) => {
  163. const json = JSON.stringify(obj, null, 2);
  164. return json.replace(/"([^"]+)":/g, "$1:");
  165. };
  166. class ZodError extends Error {
  167. constructor(issues) {
  168. super();
  169. this.issues = [];
  170. this.addIssue = (sub) => {
  171. this.issues = [...this.issues, sub];
  172. };
  173. this.addIssues = (subs = []) => {
  174. this.issues = [...this.issues, ...subs];
  175. };
  176. const actualProto = new.target.prototype;
  177. if (Object.setPrototypeOf) {
  178. // eslint-disable-next-line ban/ban
  179. Object.setPrototypeOf(this, actualProto);
  180. }
  181. else {
  182. this.__proto__ = actualProto;
  183. }
  184. this.name = "ZodError";
  185. this.issues = issues;
  186. }
  187. get errors() {
  188. return this.issues;
  189. }
  190. format(_mapper) {
  191. const mapper = _mapper ||
  192. function (issue) {
  193. return issue.message;
  194. };
  195. const fieldErrors = { _errors: [] };
  196. const processError = (error) => {
  197. for (const issue of error.issues) {
  198. if (issue.code === "invalid_union") {
  199. issue.unionErrors.map(processError);
  200. }
  201. else if (issue.code === "invalid_return_type") {
  202. processError(issue.returnTypeError);
  203. }
  204. else if (issue.code === "invalid_arguments") {
  205. processError(issue.argumentsError);
  206. }
  207. else if (issue.path.length === 0) {
  208. fieldErrors._errors.push(mapper(issue));
  209. }
  210. else {
  211. let curr = fieldErrors;
  212. let i = 0;
  213. while (i < issue.path.length) {
  214. const el = issue.path[i];
  215. const terminal = i === issue.path.length - 1;
  216. if (!terminal) {
  217. curr[el] = curr[el] || { _errors: [] };
  218. // if (typeof el === "string") {
  219. // curr[el] = curr[el] || { _errors: [] };
  220. // } else if (typeof el === "number") {
  221. // const errorArray: any = [];
  222. // errorArray._errors = [];
  223. // curr[el] = curr[el] || errorArray;
  224. // }
  225. }
  226. else {
  227. curr[el] = curr[el] || { _errors: [] };
  228. curr[el]._errors.push(mapper(issue));
  229. }
  230. curr = curr[el];
  231. i++;
  232. }
  233. }
  234. }
  235. };
  236. processError(this);
  237. return fieldErrors;
  238. }
  239. toString() {
  240. return this.message;
  241. }
  242. get message() {
  243. return JSON.stringify(this.issues, exports.util.jsonStringifyReplacer, 2);
  244. }
  245. get isEmpty() {
  246. return this.issues.length === 0;
  247. }
  248. flatten(mapper = (issue) => issue.message) {
  249. const fieldErrors = {};
  250. const formErrors = [];
  251. for (const sub of this.issues) {
  252. if (sub.path.length > 0) {
  253. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
  254. fieldErrors[sub.path[0]].push(mapper(sub));
  255. }
  256. else {
  257. formErrors.push(mapper(sub));
  258. }
  259. }
  260. return { formErrors, fieldErrors };
  261. }
  262. get formErrors() {
  263. return this.flatten();
  264. }
  265. }
  266. ZodError.create = (issues) => {
  267. const error = new ZodError(issues);
  268. return error;
  269. };
  270. const errorMap = (issue, _ctx) => {
  271. let message;
  272. switch (issue.code) {
  273. case ZodIssueCode.invalid_type:
  274. if (issue.received === ZodParsedType.undefined) {
  275. message = "Required";
  276. }
  277. else {
  278. message = `Expected ${issue.expected}, received ${issue.received}`;
  279. }
  280. break;
  281. case ZodIssueCode.invalid_literal:
  282. message = `Invalid literal value, expected ${JSON.stringify(issue.expected, exports.util.jsonStringifyReplacer)}`;
  283. break;
  284. case ZodIssueCode.unrecognized_keys:
  285. message = `Unrecognized key(s) in object: ${exports.util.joinValues(issue.keys, ", ")}`;
  286. break;
  287. case ZodIssueCode.invalid_union:
  288. message = `Invalid input`;
  289. break;
  290. case ZodIssueCode.invalid_union_discriminator:
  291. message = `Invalid discriminator value. Expected ${exports.util.joinValues(issue.options)}`;
  292. break;
  293. case ZodIssueCode.invalid_enum_value:
  294. message = `Invalid enum value. Expected ${exports.util.joinValues(issue.options)}, received '${issue.received}'`;
  295. break;
  296. case ZodIssueCode.invalid_arguments:
  297. message = `Invalid function arguments`;
  298. break;
  299. case ZodIssueCode.invalid_return_type:
  300. message = `Invalid function return type`;
  301. break;
  302. case ZodIssueCode.invalid_date:
  303. message = `Invalid date`;
  304. break;
  305. case ZodIssueCode.invalid_string:
  306. if (typeof issue.validation === "object") {
  307. if ("includes" in issue.validation) {
  308. message = `Invalid input: must include "${issue.validation.includes}"`;
  309. if (typeof issue.validation.position === "number") {
  310. message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
  311. }
  312. }
  313. else if ("startsWith" in issue.validation) {
  314. message = `Invalid input: must start with "${issue.validation.startsWith}"`;
  315. }
  316. else if ("endsWith" in issue.validation) {
  317. message = `Invalid input: must end with "${issue.validation.endsWith}"`;
  318. }
  319. else {
  320. exports.util.assertNever(issue.validation);
  321. }
  322. }
  323. else if (issue.validation !== "regex") {
  324. message = `Invalid ${issue.validation}`;
  325. }
  326. else {
  327. message = "Invalid";
  328. }
  329. break;
  330. case ZodIssueCode.too_small:
  331. if (issue.type === "array")
  332. message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
  333. else if (issue.type === "string")
  334. message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
  335. else if (issue.type === "number")
  336. message = `Number must be ${issue.exact
  337. ? `exactly equal to `
  338. : issue.inclusive
  339. ? `greater than or equal to `
  340. : `greater than `}${issue.minimum}`;
  341. else if (issue.type === "date")
  342. message = `Date must be ${issue.exact
  343. ? `exactly equal to `
  344. : issue.inclusive
  345. ? `greater than or equal to `
  346. : `greater than `}${new Date(Number(issue.minimum))}`;
  347. else
  348. message = "Invalid input";
  349. break;
  350. case ZodIssueCode.too_big:
  351. if (issue.type === "array")
  352. message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
  353. else if (issue.type === "string")
  354. message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
  355. else if (issue.type === "number")
  356. message = `Number must be ${issue.exact
  357. ? `exactly`
  358. : issue.inclusive
  359. ? `less than or equal to`
  360. : `less than`} ${issue.maximum}`;
  361. else if (issue.type === "bigint")
  362. message = `BigInt must be ${issue.exact
  363. ? `exactly`
  364. : issue.inclusive
  365. ? `less than or equal to`
  366. : `less than`} ${issue.maximum}`;
  367. else if (issue.type === "date")
  368. message = `Date must be ${issue.exact
  369. ? `exactly`
  370. : issue.inclusive
  371. ? `smaller than or equal to`
  372. : `smaller than`} ${new Date(Number(issue.maximum))}`;
  373. else
  374. message = "Invalid input";
  375. break;
  376. case ZodIssueCode.custom:
  377. message = `Invalid input`;
  378. break;
  379. case ZodIssueCode.invalid_intersection_types:
  380. message = `Intersection results could not be merged`;
  381. break;
  382. case ZodIssueCode.not_multiple_of:
  383. message = `Number must be a multiple of ${issue.multipleOf}`;
  384. break;
  385. case ZodIssueCode.not_finite:
  386. message = "Number must be finite";
  387. break;
  388. default:
  389. message = _ctx.defaultError;
  390. exports.util.assertNever(issue);
  391. }
  392. return { message };
  393. };
  394. let overrideErrorMap = errorMap;
  395. function setErrorMap(map) {
  396. overrideErrorMap = map;
  397. }
  398. function getErrorMap() {
  399. return overrideErrorMap;
  400. }
  401. const makeIssue = (params) => {
  402. const { data, path, errorMaps, issueData } = params;
  403. const fullPath = [...path, ...(issueData.path || [])];
  404. const fullIssue = {
  405. ...issueData,
  406. path: fullPath,
  407. };
  408. let errorMessage = "";
  409. const maps = errorMaps
  410. .filter((m) => !!m)
  411. .slice()
  412. .reverse();
  413. for (const map of maps) {
  414. errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  415. }
  416. return {
  417. ...issueData,
  418. path: fullPath,
  419. message: issueData.message || errorMessage,
  420. };
  421. };
  422. const EMPTY_PATH = [];
  423. function addIssueToContext(ctx, issueData) {
  424. const issue = makeIssue({
  425. issueData: issueData,
  426. data: ctx.data,
  427. path: ctx.path,
  428. errorMaps: [
  429. ctx.common.contextualErrorMap,
  430. ctx.schemaErrorMap,
  431. getErrorMap(),
  432. errorMap, // then global default map
  433. ].filter((x) => !!x),
  434. });
  435. ctx.common.issues.push(issue);
  436. }
  437. class ParseStatus {
  438. constructor() {
  439. this.value = "valid";
  440. }
  441. dirty() {
  442. if (this.value === "valid")
  443. this.value = "dirty";
  444. }
  445. abort() {
  446. if (this.value !== "aborted")
  447. this.value = "aborted";
  448. }
  449. static mergeArray(status, results) {
  450. const arrayValue = [];
  451. for (const s of results) {
  452. if (s.status === "aborted")
  453. return INVALID;
  454. if (s.status === "dirty")
  455. status.dirty();
  456. arrayValue.push(s.value);
  457. }
  458. return { status: status.value, value: arrayValue };
  459. }
  460. static async mergeObjectAsync(status, pairs) {
  461. const syncPairs = [];
  462. for (const pair of pairs) {
  463. syncPairs.push({
  464. key: await pair.key,
  465. value: await pair.value,
  466. });
  467. }
  468. return ParseStatus.mergeObjectSync(status, syncPairs);
  469. }
  470. static mergeObjectSync(status, pairs) {
  471. const finalObject = {};
  472. for (const pair of pairs) {
  473. const { key, value } = pair;
  474. if (key.status === "aborted")
  475. return INVALID;
  476. if (value.status === "aborted")
  477. return INVALID;
  478. if (key.status === "dirty")
  479. status.dirty();
  480. if (value.status === "dirty")
  481. status.dirty();
  482. if (key.value !== "__proto__" &&
  483. (typeof value.value !== "undefined" || pair.alwaysSet)) {
  484. finalObject[key.value] = value.value;
  485. }
  486. }
  487. return { status: status.value, value: finalObject };
  488. }
  489. }
  490. const INVALID = Object.freeze({
  491. status: "aborted",
  492. });
  493. const DIRTY = (value) => ({ status: "dirty", value });
  494. const OK = (value) => ({ status: "valid", value });
  495. const isAborted = (x) => x.status === "aborted";
  496. const isDirty = (x) => x.status === "dirty";
  497. const isValid = (x) => x.status === "valid";
  498. const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
  499. var errorUtil;
  500. (function (errorUtil) {
  501. errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  502. errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
  503. })(errorUtil || (errorUtil = {}));
  504. class ParseInputLazyPath {
  505. constructor(parent, value, path, key) {
  506. this._cachedPath = [];
  507. this.parent = parent;
  508. this.data = value;
  509. this._path = path;
  510. this._key = key;
  511. }
  512. get path() {
  513. if (!this._cachedPath.length) {
  514. if (this._key instanceof Array) {
  515. this._cachedPath.push(...this._path, ...this._key);
  516. }
  517. else {
  518. this._cachedPath.push(...this._path, this._key);
  519. }
  520. }
  521. return this._cachedPath;
  522. }
  523. }
  524. const handleResult = (ctx, result) => {
  525. if (isValid(result)) {
  526. return { success: true, data: result.value };
  527. }
  528. else {
  529. if (!ctx.common.issues.length) {
  530. throw new Error("Validation failed but no issues detected.");
  531. }
  532. return {
  533. success: false,
  534. get error() {
  535. if (this._error)
  536. return this._error;
  537. const error = new ZodError(ctx.common.issues);
  538. this._error = error;
  539. return this._error;
  540. },
  541. };
  542. }
  543. };
  544. function processCreateParams(params) {
  545. if (!params)
  546. return {};
  547. const { errorMap, invalid_type_error, required_error, description } = params;
  548. if (errorMap && (invalid_type_error || required_error)) {
  549. throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  550. }
  551. if (errorMap)
  552. return { errorMap: errorMap, description };
  553. const customMap = (iss, ctx) => {
  554. if (iss.code !== "invalid_type")
  555. return { message: ctx.defaultError };
  556. if (typeof ctx.data === "undefined") {
  557. return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
  558. }
  559. return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
  560. };
  561. return { errorMap: customMap, description };
  562. }
  563. class ZodType {
  564. constructor(def) {
  565. /** Alias of safeParseAsync */
  566. this.spa = this.safeParseAsync;
  567. this._def = def;
  568. this.parse = this.parse.bind(this);
  569. this.safeParse = this.safeParse.bind(this);
  570. this.parseAsync = this.parseAsync.bind(this);
  571. this.safeParseAsync = this.safeParseAsync.bind(this);
  572. this.spa = this.spa.bind(this);
  573. this.refine = this.refine.bind(this);
  574. this.refinement = this.refinement.bind(this);
  575. this.superRefine = this.superRefine.bind(this);
  576. this.optional = this.optional.bind(this);
  577. this.nullable = this.nullable.bind(this);
  578. this.nullish = this.nullish.bind(this);
  579. this.array = this.array.bind(this);
  580. this.promise = this.promise.bind(this);
  581. this.or = this.or.bind(this);
  582. this.and = this.and.bind(this);
  583. this.transform = this.transform.bind(this);
  584. this.brand = this.brand.bind(this);
  585. this.default = this.default.bind(this);
  586. this.catch = this.catch.bind(this);
  587. this.describe = this.describe.bind(this);
  588. this.pipe = this.pipe.bind(this);
  589. this.readonly = this.readonly.bind(this);
  590. this.isNullable = this.isNullable.bind(this);
  591. this.isOptional = this.isOptional.bind(this);
  592. }
  593. get description() {
  594. return this._def.description;
  595. }
  596. _getType(input) {
  597. return getParsedType(input.data);
  598. }
  599. _getOrReturnCtx(input, ctx) {
  600. return (ctx || {
  601. common: input.parent.common,
  602. data: input.data,
  603. parsedType: getParsedType(input.data),
  604. schemaErrorMap: this._def.errorMap,
  605. path: input.path,
  606. parent: input.parent,
  607. });
  608. }
  609. _processInputParams(input) {
  610. return {
  611. status: new ParseStatus(),
  612. ctx: {
  613. common: input.parent.common,
  614. data: input.data,
  615. parsedType: getParsedType(input.data),
  616. schemaErrorMap: this._def.errorMap,
  617. path: input.path,
  618. parent: input.parent,
  619. },
  620. };
  621. }
  622. _parseSync(input) {
  623. const result = this._parse(input);
  624. if (isAsync(result)) {
  625. throw new Error("Synchronous parse encountered promise.");
  626. }
  627. return result;
  628. }
  629. _parseAsync(input) {
  630. const result = this._parse(input);
  631. return Promise.resolve(result);
  632. }
  633. parse(data, params) {
  634. const result = this.safeParse(data, params);
  635. if (result.success)
  636. return result.data;
  637. throw result.error;
  638. }
  639. safeParse(data, params) {
  640. var _a;
  641. const ctx = {
  642. common: {
  643. issues: [],
  644. async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
  645. contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
  646. },
  647. path: (params === null || params === void 0 ? void 0 : params.path) || [],
  648. schemaErrorMap: this._def.errorMap,
  649. parent: null,
  650. data,
  651. parsedType: getParsedType(data),
  652. };
  653. const result = this._parseSync({ data, path: ctx.path, parent: ctx });
  654. return handleResult(ctx, result);
  655. }
  656. async parseAsync(data, params) {
  657. const result = await this.safeParseAsync(data, params);
  658. if (result.success)
  659. return result.data;
  660. throw result.error;
  661. }
  662. async safeParseAsync(data, params) {
  663. const ctx = {
  664. common: {
  665. issues: [],
  666. contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
  667. async: true,
  668. },
  669. path: (params === null || params === void 0 ? void 0 : params.path) || [],
  670. schemaErrorMap: this._def.errorMap,
  671. parent: null,
  672. data,
  673. parsedType: getParsedType(data),
  674. };
  675. const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
  676. const result = await (isAsync(maybeAsyncResult)
  677. ? maybeAsyncResult
  678. : Promise.resolve(maybeAsyncResult));
  679. return handleResult(ctx, result);
  680. }
  681. refine(check, message) {
  682. const getIssueProperties = (val) => {
  683. if (typeof message === "string" || typeof message === "undefined") {
  684. return { message };
  685. }
  686. else if (typeof message === "function") {
  687. return message(val);
  688. }
  689. else {
  690. return message;
  691. }
  692. };
  693. return this._refinement((val, ctx) => {
  694. const result = check(val);
  695. const setError = () => ctx.addIssue({
  696. code: ZodIssueCode.custom,
  697. ...getIssueProperties(val),
  698. });
  699. if (typeof Promise !== "undefined" && result instanceof Promise) {
  700. return result.then((data) => {
  701. if (!data) {
  702. setError();
  703. return false;
  704. }
  705. else {
  706. return true;
  707. }
  708. });
  709. }
  710. if (!result) {
  711. setError();
  712. return false;
  713. }
  714. else {
  715. return true;
  716. }
  717. });
  718. }
  719. refinement(check, refinementData) {
  720. return this._refinement((val, ctx) => {
  721. if (!check(val)) {
  722. ctx.addIssue(typeof refinementData === "function"
  723. ? refinementData(val, ctx)
  724. : refinementData);
  725. return false;
  726. }
  727. else {
  728. return true;
  729. }
  730. });
  731. }
  732. _refinement(refinement) {
  733. return new ZodEffects({
  734. schema: this,
  735. typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
  736. effect: { type: "refinement", refinement },
  737. });
  738. }
  739. superRefine(refinement) {
  740. return this._refinement(refinement);
  741. }
  742. optional() {
  743. return ZodOptional.create(this, this._def);
  744. }
  745. nullable() {
  746. return ZodNullable.create(this, this._def);
  747. }
  748. nullish() {
  749. return this.nullable().optional();
  750. }
  751. array() {
  752. return ZodArray.create(this, this._def);
  753. }
  754. promise() {
  755. return ZodPromise.create(this, this._def);
  756. }
  757. or(option) {
  758. return ZodUnion.create([this, option], this._def);
  759. }
  760. and(incoming) {
  761. return ZodIntersection.create(this, incoming, this._def);
  762. }
  763. transform(transform) {
  764. return new ZodEffects({
  765. ...processCreateParams(this._def),
  766. schema: this,
  767. typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
  768. effect: { type: "transform", transform },
  769. });
  770. }
  771. default(def) {
  772. const defaultValueFunc = typeof def === "function" ? def : () => def;
  773. return new ZodDefault({
  774. ...processCreateParams(this._def),
  775. innerType: this,
  776. defaultValue: defaultValueFunc,
  777. typeName: exports.ZodFirstPartyTypeKind.ZodDefault,
  778. });
  779. }
  780. brand() {
  781. return new ZodBranded({
  782. typeName: exports.ZodFirstPartyTypeKind.ZodBranded,
  783. type: this,
  784. ...processCreateParams(this._def),
  785. });
  786. }
  787. catch(def) {
  788. const catchValueFunc = typeof def === "function" ? def : () => def;
  789. return new ZodCatch({
  790. ...processCreateParams(this._def),
  791. innerType: this,
  792. catchValue: catchValueFunc,
  793. typeName: exports.ZodFirstPartyTypeKind.ZodCatch,
  794. });
  795. }
  796. describe(description) {
  797. const This = this.constructor;
  798. return new This({
  799. ...this._def,
  800. description,
  801. });
  802. }
  803. pipe(target) {
  804. return ZodPipeline.create(this, target);
  805. }
  806. readonly() {
  807. return ZodReadonly.create(this);
  808. }
  809. isOptional() {
  810. return this.safeParse(undefined).success;
  811. }
  812. isNullable() {
  813. return this.safeParse(null).success;
  814. }
  815. }
  816. const cuidRegex = /^c[^\s-]{8,}$/i;
  817. const cuid2Regex = /^[a-z][a-z0-9]*$/;
  818. const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
  819. // const uuidRegex =
  820. // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
  821. const 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;
  822. // from https://stackoverflow.com/a/46181/1550155
  823. // old version: too slow, didn't support unicode
  824. // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
  825. //old email regex
  826. // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
  827. // eslint-disable-next-line
  828. // const emailRegex =
  829. // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
  830. // const emailRegex =
  831. // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  832. // const emailRegex =
  833. // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
  834. const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
  835. // const emailRegex =
  836. // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
  837. // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
  838. const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
  839. let emojiRegex;
  840. const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
  841. const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
  842. // Adapted from https://stackoverflow.com/a/3143231
  843. const datetimeRegex = (args) => {
  844. if (args.precision) {
  845. if (args.offset) {
  846. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  847. }
  848. else {
  849. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
  850. }
  851. }
  852. else if (args.precision === 0) {
  853. if (args.offset) {
  854. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  855. }
  856. else {
  857. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
  858. }
  859. }
  860. else {
  861. if (args.offset) {
  862. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  863. }
  864. else {
  865. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
  866. }
  867. }
  868. };
  869. function isValidIP(ip, version) {
  870. if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
  871. return true;
  872. }
  873. if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
  874. return true;
  875. }
  876. return false;
  877. }
  878. class ZodString extends ZodType {
  879. _parse(input) {
  880. if (this._def.coerce) {
  881. input.data = String(input.data);
  882. }
  883. const parsedType = this._getType(input);
  884. if (parsedType !== ZodParsedType.string) {
  885. const ctx = this._getOrReturnCtx(input);
  886. addIssueToContext(ctx, {
  887. code: ZodIssueCode.invalid_type,
  888. expected: ZodParsedType.string,
  889. received: ctx.parsedType,
  890. }
  891. //
  892. );
  893. return INVALID;
  894. }
  895. const status = new ParseStatus();
  896. let ctx = undefined;
  897. for (const check of this._def.checks) {
  898. if (check.kind === "min") {
  899. if (input.data.length < check.value) {
  900. ctx = this._getOrReturnCtx(input, ctx);
  901. addIssueToContext(ctx, {
  902. code: ZodIssueCode.too_small,
  903. minimum: check.value,
  904. type: "string",
  905. inclusive: true,
  906. exact: false,
  907. message: check.message,
  908. });
  909. status.dirty();
  910. }
  911. }
  912. else if (check.kind === "max") {
  913. if (input.data.length > check.value) {
  914. ctx = this._getOrReturnCtx(input, ctx);
  915. addIssueToContext(ctx, {
  916. code: ZodIssueCode.too_big,
  917. maximum: check.value,
  918. type: "string",
  919. inclusive: true,
  920. exact: false,
  921. message: check.message,
  922. });
  923. status.dirty();
  924. }
  925. }
  926. else if (check.kind === "length") {
  927. const tooBig = input.data.length > check.value;
  928. const tooSmall = input.data.length < check.value;
  929. if (tooBig || tooSmall) {
  930. ctx = this._getOrReturnCtx(input, ctx);
  931. if (tooBig) {
  932. addIssueToContext(ctx, {
  933. code: ZodIssueCode.too_big,
  934. maximum: check.value,
  935. type: "string",
  936. inclusive: true,
  937. exact: true,
  938. message: check.message,
  939. });
  940. }
  941. else if (tooSmall) {
  942. addIssueToContext(ctx, {
  943. code: ZodIssueCode.too_small,
  944. minimum: check.value,
  945. type: "string",
  946. inclusive: true,
  947. exact: true,
  948. message: check.message,
  949. });
  950. }
  951. status.dirty();
  952. }
  953. }
  954. else if (check.kind === "email") {
  955. if (!emailRegex.test(input.data)) {
  956. ctx = this._getOrReturnCtx(input, ctx);
  957. addIssueToContext(ctx, {
  958. validation: "email",
  959. code: ZodIssueCode.invalid_string,
  960. message: check.message,
  961. });
  962. status.dirty();
  963. }
  964. }
  965. else if (check.kind === "emoji") {
  966. if (!emojiRegex) {
  967. emojiRegex = new RegExp(_emojiRegex, "u");
  968. }
  969. if (!emojiRegex.test(input.data)) {
  970. ctx = this._getOrReturnCtx(input, ctx);
  971. addIssueToContext(ctx, {
  972. validation: "emoji",
  973. code: ZodIssueCode.invalid_string,
  974. message: check.message,
  975. });
  976. status.dirty();
  977. }
  978. }
  979. else if (check.kind === "uuid") {
  980. if (!uuidRegex.test(input.data)) {
  981. ctx = this._getOrReturnCtx(input, ctx);
  982. addIssueToContext(ctx, {
  983. validation: "uuid",
  984. code: ZodIssueCode.invalid_string,
  985. message: check.message,
  986. });
  987. status.dirty();
  988. }
  989. }
  990. else if (check.kind === "cuid") {
  991. if (!cuidRegex.test(input.data)) {
  992. ctx = this._getOrReturnCtx(input, ctx);
  993. addIssueToContext(ctx, {
  994. validation: "cuid",
  995. code: ZodIssueCode.invalid_string,
  996. message: check.message,
  997. });
  998. status.dirty();
  999. }
  1000. }
  1001. else if (check.kind === "cuid2") {
  1002. if (!cuid2Regex.test(input.data)) {
  1003. ctx = this._getOrReturnCtx(input, ctx);
  1004. addIssueToContext(ctx, {
  1005. validation: "cuid2",
  1006. code: ZodIssueCode.invalid_string,
  1007. message: check.message,
  1008. });
  1009. status.dirty();
  1010. }
  1011. }
  1012. else if (check.kind === "ulid") {
  1013. if (!ulidRegex.test(input.data)) {
  1014. ctx = this._getOrReturnCtx(input, ctx);
  1015. addIssueToContext(ctx, {
  1016. validation: "ulid",
  1017. code: ZodIssueCode.invalid_string,
  1018. message: check.message,
  1019. });
  1020. status.dirty();
  1021. }
  1022. }
  1023. else if (check.kind === "url") {
  1024. try {
  1025. new URL(input.data);
  1026. }
  1027. catch (_a) {
  1028. ctx = this._getOrReturnCtx(input, ctx);
  1029. addIssueToContext(ctx, {
  1030. validation: "url",
  1031. code: ZodIssueCode.invalid_string,
  1032. message: check.message,
  1033. });
  1034. status.dirty();
  1035. }
  1036. }
  1037. else if (check.kind === "regex") {
  1038. check.regex.lastIndex = 0;
  1039. const testResult = check.regex.test(input.data);
  1040. if (!testResult) {
  1041. ctx = this._getOrReturnCtx(input, ctx);
  1042. addIssueToContext(ctx, {
  1043. validation: "regex",
  1044. code: ZodIssueCode.invalid_string,
  1045. message: check.message,
  1046. });
  1047. status.dirty();
  1048. }
  1049. }
  1050. else if (check.kind === "trim") {
  1051. input.data = input.data.trim();
  1052. }
  1053. else if (check.kind === "includes") {
  1054. if (!input.data.includes(check.value, check.position)) {
  1055. ctx = this._getOrReturnCtx(input, ctx);
  1056. addIssueToContext(ctx, {
  1057. code: ZodIssueCode.invalid_string,
  1058. validation: { includes: check.value, position: check.position },
  1059. message: check.message,
  1060. });
  1061. status.dirty();
  1062. }
  1063. }
  1064. else if (check.kind === "toLowerCase") {
  1065. input.data = input.data.toLowerCase();
  1066. }
  1067. else if (check.kind === "toUpperCase") {
  1068. input.data = input.data.toUpperCase();
  1069. }
  1070. else if (check.kind === "startsWith") {
  1071. if (!input.data.startsWith(check.value)) {
  1072. ctx = this._getOrReturnCtx(input, ctx);
  1073. addIssueToContext(ctx, {
  1074. code: ZodIssueCode.invalid_string,
  1075. validation: { startsWith: check.value },
  1076. message: check.message,
  1077. });
  1078. status.dirty();
  1079. }
  1080. }
  1081. else if (check.kind === "endsWith") {
  1082. if (!input.data.endsWith(check.value)) {
  1083. ctx = this._getOrReturnCtx(input, ctx);
  1084. addIssueToContext(ctx, {
  1085. code: ZodIssueCode.invalid_string,
  1086. validation: { endsWith: check.value },
  1087. message: check.message,
  1088. });
  1089. status.dirty();
  1090. }
  1091. }
  1092. else if (check.kind === "datetime") {
  1093. const regex = datetimeRegex(check);
  1094. if (!regex.test(input.data)) {
  1095. ctx = this._getOrReturnCtx(input, ctx);
  1096. addIssueToContext(ctx, {
  1097. code: ZodIssueCode.invalid_string,
  1098. validation: "datetime",
  1099. message: check.message,
  1100. });
  1101. status.dirty();
  1102. }
  1103. }
  1104. else if (check.kind === "ip") {
  1105. if (!isValidIP(input.data, check.version)) {
  1106. ctx = this._getOrReturnCtx(input, ctx);
  1107. addIssueToContext(ctx, {
  1108. validation: "ip",
  1109. code: ZodIssueCode.invalid_string,
  1110. message: check.message,
  1111. });
  1112. status.dirty();
  1113. }
  1114. }
  1115. else {
  1116. exports.util.assertNever(check);
  1117. }
  1118. }
  1119. return { status: status.value, value: input.data };
  1120. }
  1121. _regex(regex, validation, message) {
  1122. return this.refinement((data) => regex.test(data), {
  1123. validation,
  1124. code: ZodIssueCode.invalid_string,
  1125. ...errorUtil.errToObj(message),
  1126. });
  1127. }
  1128. _addCheck(check) {
  1129. return new ZodString({
  1130. ...this._def,
  1131. checks: [...this._def.checks, check],
  1132. });
  1133. }
  1134. email(message) {
  1135. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  1136. }
  1137. url(message) {
  1138. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  1139. }
  1140. emoji(message) {
  1141. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  1142. }
  1143. uuid(message) {
  1144. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  1145. }
  1146. cuid(message) {
  1147. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  1148. }
  1149. cuid2(message) {
  1150. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  1151. }
  1152. ulid(message) {
  1153. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  1154. }
  1155. ip(options) {
  1156. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  1157. }
  1158. datetime(options) {
  1159. var _a;
  1160. if (typeof options === "string") {
  1161. return this._addCheck({
  1162. kind: "datetime",
  1163. precision: null,
  1164. offset: false,
  1165. message: options,
  1166. });
  1167. }
  1168. return this._addCheck({
  1169. kind: "datetime",
  1170. precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
  1171. offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
  1172. ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
  1173. });
  1174. }
  1175. regex(regex, message) {
  1176. return this._addCheck({
  1177. kind: "regex",
  1178. regex: regex,
  1179. ...errorUtil.errToObj(message),
  1180. });
  1181. }
  1182. includes(value, options) {
  1183. return this._addCheck({
  1184. kind: "includes",
  1185. value: value,
  1186. position: options === null || options === void 0 ? void 0 : options.position,
  1187. ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
  1188. });
  1189. }
  1190. startsWith(value, message) {
  1191. return this._addCheck({
  1192. kind: "startsWith",
  1193. value: value,
  1194. ...errorUtil.errToObj(message),
  1195. });
  1196. }
  1197. endsWith(value, message) {
  1198. return this._addCheck({
  1199. kind: "endsWith",
  1200. value: value,
  1201. ...errorUtil.errToObj(message),
  1202. });
  1203. }
  1204. min(minLength, message) {
  1205. return this._addCheck({
  1206. kind: "min",
  1207. value: minLength,
  1208. ...errorUtil.errToObj(message),
  1209. });
  1210. }
  1211. max(maxLength, message) {
  1212. return this._addCheck({
  1213. kind: "max",
  1214. value: maxLength,
  1215. ...errorUtil.errToObj(message),
  1216. });
  1217. }
  1218. length(len, message) {
  1219. return this._addCheck({
  1220. kind: "length",
  1221. value: len,
  1222. ...errorUtil.errToObj(message),
  1223. });
  1224. }
  1225. /**
  1226. * @deprecated Use z.string().min(1) instead.
  1227. * @see {@link ZodString.min}
  1228. */
  1229. nonempty(message) {
  1230. return this.min(1, errorUtil.errToObj(message));
  1231. }
  1232. trim() {
  1233. return new ZodString({
  1234. ...this._def,
  1235. checks: [...this._def.checks, { kind: "trim" }],
  1236. });
  1237. }
  1238. toLowerCase() {
  1239. return new ZodString({
  1240. ...this._def,
  1241. checks: [...this._def.checks, { kind: "toLowerCase" }],
  1242. });
  1243. }
  1244. toUpperCase() {
  1245. return new ZodString({
  1246. ...this._def,
  1247. checks: [...this._def.checks, { kind: "toUpperCase" }],
  1248. });
  1249. }
  1250. get isDatetime() {
  1251. return !!this._def.checks.find((ch) => ch.kind === "datetime");
  1252. }
  1253. get isEmail() {
  1254. return !!this._def.checks.find((ch) => ch.kind === "email");
  1255. }
  1256. get isURL() {
  1257. return !!this._def.checks.find((ch) => ch.kind === "url");
  1258. }
  1259. get isEmoji() {
  1260. return !!this._def.checks.find((ch) => ch.kind === "emoji");
  1261. }
  1262. get isUUID() {
  1263. return !!this._def.checks.find((ch) => ch.kind === "uuid");
  1264. }
  1265. get isCUID() {
  1266. return !!this._def.checks.find((ch) => ch.kind === "cuid");
  1267. }
  1268. get isCUID2() {
  1269. return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  1270. }
  1271. get isULID() {
  1272. return !!this._def.checks.find((ch) => ch.kind === "ulid");
  1273. }
  1274. get isIP() {
  1275. return !!this._def.checks.find((ch) => ch.kind === "ip");
  1276. }
  1277. get minLength() {
  1278. let min = null;
  1279. for (const ch of this._def.checks) {
  1280. if (ch.kind === "min") {
  1281. if (min === null || ch.value > min)
  1282. min = ch.value;
  1283. }
  1284. }
  1285. return min;
  1286. }
  1287. get maxLength() {
  1288. let max = null;
  1289. for (const ch of this._def.checks) {
  1290. if (ch.kind === "max") {
  1291. if (max === null || ch.value < max)
  1292. max = ch.value;
  1293. }
  1294. }
  1295. return max;
  1296. }
  1297. }
  1298. ZodString.create = (params) => {
  1299. var _a;
  1300. return new ZodString({
  1301. checks: [],
  1302. typeName: exports.ZodFirstPartyTypeKind.ZodString,
  1303. coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
  1304. ...processCreateParams(params),
  1305. });
  1306. };
  1307. // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
  1308. function floatSafeRemainder(val, step) {
  1309. const valDecCount = (val.toString().split(".")[1] || "").length;
  1310. const stepDecCount = (step.toString().split(".")[1] || "").length;
  1311. const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  1312. const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  1313. const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  1314. return (valInt % stepInt) / Math.pow(10, decCount);
  1315. }
  1316. class ZodNumber extends ZodType {
  1317. constructor() {
  1318. super(...arguments);
  1319. this.min = this.gte;
  1320. this.max = this.lte;
  1321. this.step = this.multipleOf;
  1322. }
  1323. _parse(input) {
  1324. if (this._def.coerce) {
  1325. input.data = Number(input.data);
  1326. }
  1327. const parsedType = this._getType(input);
  1328. if (parsedType !== ZodParsedType.number) {
  1329. const ctx = this._getOrReturnCtx(input);
  1330. addIssueToContext(ctx, {
  1331. code: ZodIssueCode.invalid_type,
  1332. expected: ZodParsedType.number,
  1333. received: ctx.parsedType,
  1334. });
  1335. return INVALID;
  1336. }
  1337. let ctx = undefined;
  1338. const status = new ParseStatus();
  1339. for (const check of this._def.checks) {
  1340. if (check.kind === "int") {
  1341. if (!exports.util.isInteger(input.data)) {
  1342. ctx = this._getOrReturnCtx(input, ctx);
  1343. addIssueToContext(ctx, {
  1344. code: ZodIssueCode.invalid_type,
  1345. expected: "integer",
  1346. received: "float",
  1347. message: check.message,
  1348. });
  1349. status.dirty();
  1350. }
  1351. }
  1352. else if (check.kind === "min") {
  1353. const tooSmall = check.inclusive
  1354. ? input.data < check.value
  1355. : input.data <= check.value;
  1356. if (tooSmall) {
  1357. ctx = this._getOrReturnCtx(input, ctx);
  1358. addIssueToContext(ctx, {
  1359. code: ZodIssueCode.too_small,
  1360. minimum: check.value,
  1361. type: "number",
  1362. inclusive: check.inclusive,
  1363. exact: false,
  1364. message: check.message,
  1365. });
  1366. status.dirty();
  1367. }
  1368. }
  1369. else if (check.kind === "max") {
  1370. const tooBig = check.inclusive
  1371. ? input.data > check.value
  1372. : input.data >= check.value;
  1373. if (tooBig) {
  1374. ctx = this._getOrReturnCtx(input, ctx);
  1375. addIssueToContext(ctx, {
  1376. code: ZodIssueCode.too_big,
  1377. maximum: check.value,
  1378. type: "number",
  1379. inclusive: check.inclusive,
  1380. exact: false,
  1381. message: check.message,
  1382. });
  1383. status.dirty();
  1384. }
  1385. }
  1386. else if (check.kind === "multipleOf") {
  1387. if (floatSafeRemainder(input.data, check.value) !== 0) {
  1388. ctx = this._getOrReturnCtx(input, ctx);
  1389. addIssueToContext(ctx, {
  1390. code: ZodIssueCode.not_multiple_of,
  1391. multipleOf: check.value,
  1392. message: check.message,
  1393. });
  1394. status.dirty();
  1395. }
  1396. }
  1397. else if (check.kind === "finite") {
  1398. if (!Number.isFinite(input.data)) {
  1399. ctx = this._getOrReturnCtx(input, ctx);
  1400. addIssueToContext(ctx, {
  1401. code: ZodIssueCode.not_finite,
  1402. message: check.message,
  1403. });
  1404. status.dirty();
  1405. }
  1406. }
  1407. else {
  1408. exports.util.assertNever(check);
  1409. }
  1410. }
  1411. return { status: status.value, value: input.data };
  1412. }
  1413. gte(value, message) {
  1414. return this.setLimit("min", value, true, errorUtil.toString(message));
  1415. }
  1416. gt(value, message) {
  1417. return this.setLimit("min", value, false, errorUtil.toString(message));
  1418. }
  1419. lte(value, message) {
  1420. return this.setLimit("max", value, true, errorUtil.toString(message));
  1421. }
  1422. lt(value, message) {
  1423. return this.setLimit("max", value, false, errorUtil.toString(message));
  1424. }
  1425. setLimit(kind, value, inclusive, message) {
  1426. return new ZodNumber({
  1427. ...this._def,
  1428. checks: [
  1429. ...this._def.checks,
  1430. {
  1431. kind,
  1432. value,
  1433. inclusive,
  1434. message: errorUtil.toString(message),
  1435. },
  1436. ],
  1437. });
  1438. }
  1439. _addCheck(check) {
  1440. return new ZodNumber({
  1441. ...this._def,
  1442. checks: [...this._def.checks, check],
  1443. });
  1444. }
  1445. int(message) {
  1446. return this._addCheck({
  1447. kind: "int",
  1448. message: errorUtil.toString(message),
  1449. });
  1450. }
  1451. positive(message) {
  1452. return this._addCheck({
  1453. kind: "min",
  1454. value: 0,
  1455. inclusive: false,
  1456. message: errorUtil.toString(message),
  1457. });
  1458. }
  1459. negative(message) {
  1460. return this._addCheck({
  1461. kind: "max",
  1462. value: 0,
  1463. inclusive: false,
  1464. message: errorUtil.toString(message),
  1465. });
  1466. }
  1467. nonpositive(message) {
  1468. return this._addCheck({
  1469. kind: "max",
  1470. value: 0,
  1471. inclusive: true,
  1472. message: errorUtil.toString(message),
  1473. });
  1474. }
  1475. nonnegative(message) {
  1476. return this._addCheck({
  1477. kind: "min",
  1478. value: 0,
  1479. inclusive: true,
  1480. message: errorUtil.toString(message),
  1481. });
  1482. }
  1483. multipleOf(value, message) {
  1484. return this._addCheck({
  1485. kind: "multipleOf",
  1486. value: value,
  1487. message: errorUtil.toString(message),
  1488. });
  1489. }
  1490. finite(message) {
  1491. return this._addCheck({
  1492. kind: "finite",
  1493. message: errorUtil.toString(message),
  1494. });
  1495. }
  1496. safe(message) {
  1497. return this._addCheck({
  1498. kind: "min",
  1499. inclusive: true,
  1500. value: Number.MIN_SAFE_INTEGER,
  1501. message: errorUtil.toString(message),
  1502. })._addCheck({
  1503. kind: "max",
  1504. inclusive: true,
  1505. value: Number.MAX_SAFE_INTEGER,
  1506. message: errorUtil.toString(message),
  1507. });
  1508. }
  1509. get minValue() {
  1510. let min = null;
  1511. for (const ch of this._def.checks) {
  1512. if (ch.kind === "min") {
  1513. if (min === null || ch.value > min)
  1514. min = ch.value;
  1515. }
  1516. }
  1517. return min;
  1518. }
  1519. get maxValue() {
  1520. let max = null;
  1521. for (const ch of this._def.checks) {
  1522. if (ch.kind === "max") {
  1523. if (max === null || ch.value < max)
  1524. max = ch.value;
  1525. }
  1526. }
  1527. return max;
  1528. }
  1529. get isInt() {
  1530. return !!this._def.checks.find((ch) => ch.kind === "int" ||
  1531. (ch.kind === "multipleOf" && exports.util.isInteger(ch.value)));
  1532. }
  1533. get isFinite() {
  1534. let max = null, min = null;
  1535. for (const ch of this._def.checks) {
  1536. if (ch.kind === "finite" ||
  1537. ch.kind === "int" ||
  1538. ch.kind === "multipleOf") {
  1539. return true;
  1540. }
  1541. else if (ch.kind === "min") {
  1542. if (min === null || ch.value > min)
  1543. min = ch.value;
  1544. }
  1545. else if (ch.kind === "max") {
  1546. if (max === null || ch.value < max)
  1547. max = ch.value;
  1548. }
  1549. }
  1550. return Number.isFinite(min) && Number.isFinite(max);
  1551. }
  1552. }
  1553. ZodNumber.create = (params) => {
  1554. return new ZodNumber({
  1555. checks: [],
  1556. typeName: exports.ZodFirstPartyTypeKind.ZodNumber,
  1557. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  1558. ...processCreateParams(params),
  1559. });
  1560. };
  1561. class ZodBigInt extends ZodType {
  1562. constructor() {
  1563. super(...arguments);
  1564. this.min = this.gte;
  1565. this.max = this.lte;
  1566. }
  1567. _parse(input) {
  1568. if (this._def.coerce) {
  1569. input.data = BigInt(input.data);
  1570. }
  1571. const parsedType = this._getType(input);
  1572. if (parsedType !== ZodParsedType.bigint) {
  1573. const ctx = this._getOrReturnCtx(input);
  1574. addIssueToContext(ctx, {
  1575. code: ZodIssueCode.invalid_type,
  1576. expected: ZodParsedType.bigint,
  1577. received: ctx.parsedType,
  1578. });
  1579. return INVALID;
  1580. }
  1581. let ctx = undefined;
  1582. const status = new ParseStatus();
  1583. for (const check of this._def.checks) {
  1584. if (check.kind === "min") {
  1585. const tooSmall = check.inclusive
  1586. ? input.data < check.value
  1587. : input.data <= check.value;
  1588. if (tooSmall) {
  1589. ctx = this._getOrReturnCtx(input, ctx);
  1590. addIssueToContext(ctx, {
  1591. code: ZodIssueCode.too_small,
  1592. type: "bigint",
  1593. minimum: check.value,
  1594. inclusive: check.inclusive,
  1595. message: check.message,
  1596. });
  1597. status.dirty();
  1598. }
  1599. }
  1600. else if (check.kind === "max") {
  1601. const tooBig = check.inclusive
  1602. ? input.data > check.value
  1603. : input.data >= check.value;
  1604. if (tooBig) {
  1605. ctx = this._getOrReturnCtx(input, ctx);
  1606. addIssueToContext(ctx, {
  1607. code: ZodIssueCode.too_big,
  1608. type: "bigint",
  1609. maximum: check.value,
  1610. inclusive: check.inclusive,
  1611. message: check.message,
  1612. });
  1613. status.dirty();
  1614. }
  1615. }
  1616. else if (check.kind === "multipleOf") {
  1617. if (input.data % check.value !== BigInt(0)) {
  1618. ctx = this._getOrReturnCtx(input, ctx);
  1619. addIssueToContext(ctx, {
  1620. code: ZodIssueCode.not_multiple_of,
  1621. multipleOf: check.value,
  1622. message: check.message,
  1623. });
  1624. status.dirty();
  1625. }
  1626. }
  1627. else {
  1628. exports.util.assertNever(check);
  1629. }
  1630. }
  1631. return { status: status.value, value: input.data };
  1632. }
  1633. gte(value, message) {
  1634. return this.setLimit("min", value, true, errorUtil.toString(message));
  1635. }
  1636. gt(value, message) {
  1637. return this.setLimit("min", value, false, errorUtil.toString(message));
  1638. }
  1639. lte(value, message) {
  1640. return this.setLimit("max", value, true, errorUtil.toString(message));
  1641. }
  1642. lt(value, message) {
  1643. return this.setLimit("max", value, false, errorUtil.toString(message));
  1644. }
  1645. setLimit(kind, value, inclusive, message) {
  1646. return new ZodBigInt({
  1647. ...this._def,
  1648. checks: [
  1649. ...this._def.checks,
  1650. {
  1651. kind,
  1652. value,
  1653. inclusive,
  1654. message: errorUtil.toString(message),
  1655. },
  1656. ],
  1657. });
  1658. }
  1659. _addCheck(check) {
  1660. return new ZodBigInt({
  1661. ...this._def,
  1662. checks: [...this._def.checks, check],
  1663. });
  1664. }
  1665. positive(message) {
  1666. return this._addCheck({
  1667. kind: "min",
  1668. value: BigInt(0),
  1669. inclusive: false,
  1670. message: errorUtil.toString(message),
  1671. });
  1672. }
  1673. negative(message) {
  1674. return this._addCheck({
  1675. kind: "max",
  1676. value: BigInt(0),
  1677. inclusive: false,
  1678. message: errorUtil.toString(message),
  1679. });
  1680. }
  1681. nonpositive(message) {
  1682. return this._addCheck({
  1683. kind: "max",
  1684. value: BigInt(0),
  1685. inclusive: true,
  1686. message: errorUtil.toString(message),
  1687. });
  1688. }
  1689. nonnegative(message) {
  1690. return this._addCheck({
  1691. kind: "min",
  1692. value: BigInt(0),
  1693. inclusive: true,
  1694. message: errorUtil.toString(message),
  1695. });
  1696. }
  1697. multipleOf(value, message) {
  1698. return this._addCheck({
  1699. kind: "multipleOf",
  1700. value,
  1701. message: errorUtil.toString(message),
  1702. });
  1703. }
  1704. get minValue() {
  1705. let min = null;
  1706. for (const ch of this._def.checks) {
  1707. if (ch.kind === "min") {
  1708. if (min === null || ch.value > min)
  1709. min = ch.value;
  1710. }
  1711. }
  1712. return min;
  1713. }
  1714. get maxValue() {
  1715. let max = null;
  1716. for (const ch of this._def.checks) {
  1717. if (ch.kind === "max") {
  1718. if (max === null || ch.value < max)
  1719. max = ch.value;
  1720. }
  1721. }
  1722. return max;
  1723. }
  1724. }
  1725. ZodBigInt.create = (params) => {
  1726. var _a;
  1727. return new ZodBigInt({
  1728. checks: [],
  1729. typeName: exports.ZodFirstPartyTypeKind.ZodBigInt,
  1730. coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
  1731. ...processCreateParams(params),
  1732. });
  1733. };
  1734. class ZodBoolean extends ZodType {
  1735. _parse(input) {
  1736. if (this._def.coerce) {
  1737. input.data = Boolean(input.data);
  1738. }
  1739. const parsedType = this._getType(input);
  1740. if (parsedType !== ZodParsedType.boolean) {
  1741. const ctx = this._getOrReturnCtx(input);
  1742. addIssueToContext(ctx, {
  1743. code: ZodIssueCode.invalid_type,
  1744. expected: ZodParsedType.boolean,
  1745. received: ctx.parsedType,
  1746. });
  1747. return INVALID;
  1748. }
  1749. return OK(input.data);
  1750. }
  1751. }
  1752. ZodBoolean.create = (params) => {
  1753. return new ZodBoolean({
  1754. typeName: exports.ZodFirstPartyTypeKind.ZodBoolean,
  1755. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  1756. ...processCreateParams(params),
  1757. });
  1758. };
  1759. class ZodDate extends ZodType {
  1760. _parse(input) {
  1761. if (this._def.coerce) {
  1762. input.data = new Date(input.data);
  1763. }
  1764. const parsedType = this._getType(input);
  1765. if (parsedType !== ZodParsedType.date) {
  1766. const ctx = this._getOrReturnCtx(input);
  1767. addIssueToContext(ctx, {
  1768. code: ZodIssueCode.invalid_type,
  1769. expected: ZodParsedType.date,
  1770. received: ctx.parsedType,
  1771. });
  1772. return INVALID;
  1773. }
  1774. if (isNaN(input.data.getTime())) {
  1775. const ctx = this._getOrReturnCtx(input);
  1776. addIssueToContext(ctx, {
  1777. code: ZodIssueCode.invalid_date,
  1778. });
  1779. return INVALID;
  1780. }
  1781. const status = new ParseStatus();
  1782. let ctx = undefined;
  1783. for (const check of this._def.checks) {
  1784. if (check.kind === "min") {
  1785. if (input.data.getTime() < check.value) {
  1786. ctx = this._getOrReturnCtx(input, ctx);
  1787. addIssueToContext(ctx, {
  1788. code: ZodIssueCode.too_small,
  1789. message: check.message,
  1790. inclusive: true,
  1791. exact: false,
  1792. minimum: check.value,
  1793. type: "date",
  1794. });
  1795. status.dirty();
  1796. }
  1797. }
  1798. else if (check.kind === "max") {
  1799. if (input.data.getTime() > check.value) {
  1800. ctx = this._getOrReturnCtx(input, ctx);
  1801. addIssueToContext(ctx, {
  1802. code: ZodIssueCode.too_big,
  1803. message: check.message,
  1804. inclusive: true,
  1805. exact: false,
  1806. maximum: check.value,
  1807. type: "date",
  1808. });
  1809. status.dirty();
  1810. }
  1811. }
  1812. else {
  1813. exports.util.assertNever(check);
  1814. }
  1815. }
  1816. return {
  1817. status: status.value,
  1818. value: new Date(input.data.getTime()),
  1819. };
  1820. }
  1821. _addCheck(check) {
  1822. return new ZodDate({
  1823. ...this._def,
  1824. checks: [...this._def.checks, check],
  1825. });
  1826. }
  1827. min(minDate, message) {
  1828. return this._addCheck({
  1829. kind: "min",
  1830. value: minDate.getTime(),
  1831. message: errorUtil.toString(message),
  1832. });
  1833. }
  1834. max(maxDate, message) {
  1835. return this._addCheck({
  1836. kind: "max",
  1837. value: maxDate.getTime(),
  1838. message: errorUtil.toString(message),
  1839. });
  1840. }
  1841. get minDate() {
  1842. let min = null;
  1843. for (const ch of this._def.checks) {
  1844. if (ch.kind === "min") {
  1845. if (min === null || ch.value > min)
  1846. min = ch.value;
  1847. }
  1848. }
  1849. return min != null ? new Date(min) : null;
  1850. }
  1851. get maxDate() {
  1852. let max = null;
  1853. for (const ch of this._def.checks) {
  1854. if (ch.kind === "max") {
  1855. if (max === null || ch.value < max)
  1856. max = ch.value;
  1857. }
  1858. }
  1859. return max != null ? new Date(max) : null;
  1860. }
  1861. }
  1862. ZodDate.create = (params) => {
  1863. return new ZodDate({
  1864. checks: [],
  1865. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  1866. typeName: exports.ZodFirstPartyTypeKind.ZodDate,
  1867. ...processCreateParams(params),
  1868. });
  1869. };
  1870. class ZodSymbol extends ZodType {
  1871. _parse(input) {
  1872. const parsedType = this._getType(input);
  1873. if (parsedType !== ZodParsedType.symbol) {
  1874. const ctx = this._getOrReturnCtx(input);
  1875. addIssueToContext(ctx, {
  1876. code: ZodIssueCode.invalid_type,
  1877. expected: ZodParsedType.symbol,
  1878. received: ctx.parsedType,
  1879. });
  1880. return INVALID;
  1881. }
  1882. return OK(input.data);
  1883. }
  1884. }
  1885. ZodSymbol.create = (params) => {
  1886. return new ZodSymbol({
  1887. typeName: exports.ZodFirstPartyTypeKind.ZodSymbol,
  1888. ...processCreateParams(params),
  1889. });
  1890. };
  1891. class ZodUndefined extends ZodType {
  1892. _parse(input) {
  1893. const parsedType = this._getType(input);
  1894. if (parsedType !== ZodParsedType.undefined) {
  1895. const ctx = this._getOrReturnCtx(input);
  1896. addIssueToContext(ctx, {
  1897. code: ZodIssueCode.invalid_type,
  1898. expected: ZodParsedType.undefined,
  1899. received: ctx.parsedType,
  1900. });
  1901. return INVALID;
  1902. }
  1903. return OK(input.data);
  1904. }
  1905. }
  1906. ZodUndefined.create = (params) => {
  1907. return new ZodUndefined({
  1908. typeName: exports.ZodFirstPartyTypeKind.ZodUndefined,
  1909. ...processCreateParams(params),
  1910. });
  1911. };
  1912. class ZodNull extends ZodType {
  1913. _parse(input) {
  1914. const parsedType = this._getType(input);
  1915. if (parsedType !== ZodParsedType.null) {
  1916. const ctx = this._getOrReturnCtx(input);
  1917. addIssueToContext(ctx, {
  1918. code: ZodIssueCode.invalid_type,
  1919. expected: ZodParsedType.null,
  1920. received: ctx.parsedType,
  1921. });
  1922. return INVALID;
  1923. }
  1924. return OK(input.data);
  1925. }
  1926. }
  1927. ZodNull.create = (params) => {
  1928. return new ZodNull({
  1929. typeName: exports.ZodFirstPartyTypeKind.ZodNull,
  1930. ...processCreateParams(params),
  1931. });
  1932. };
  1933. class ZodAny extends ZodType {
  1934. constructor() {
  1935. super(...arguments);
  1936. // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
  1937. this._any = true;
  1938. }
  1939. _parse(input) {
  1940. return OK(input.data);
  1941. }
  1942. }
  1943. ZodAny.create = (params) => {
  1944. return new ZodAny({
  1945. typeName: exports.ZodFirstPartyTypeKind.ZodAny,
  1946. ...processCreateParams(params),
  1947. });
  1948. };
  1949. class ZodUnknown extends ZodType {
  1950. constructor() {
  1951. super(...arguments);
  1952. // required
  1953. this._unknown = true;
  1954. }
  1955. _parse(input) {
  1956. return OK(input.data);
  1957. }
  1958. }
  1959. ZodUnknown.create = (params) => {
  1960. return new ZodUnknown({
  1961. typeName: exports.ZodFirstPartyTypeKind.ZodUnknown,
  1962. ...processCreateParams(params),
  1963. });
  1964. };
  1965. class ZodNever extends ZodType {
  1966. _parse(input) {
  1967. const ctx = this._getOrReturnCtx(input);
  1968. addIssueToContext(ctx, {
  1969. code: ZodIssueCode.invalid_type,
  1970. expected: ZodParsedType.never,
  1971. received: ctx.parsedType,
  1972. });
  1973. return INVALID;
  1974. }
  1975. }
  1976. ZodNever.create = (params) => {
  1977. return new ZodNever({
  1978. typeName: exports.ZodFirstPartyTypeKind.ZodNever,
  1979. ...processCreateParams(params),
  1980. });
  1981. };
  1982. class ZodVoid extends ZodType {
  1983. _parse(input) {
  1984. const parsedType = this._getType(input);
  1985. if (parsedType !== ZodParsedType.undefined) {
  1986. const ctx = this._getOrReturnCtx(input);
  1987. addIssueToContext(ctx, {
  1988. code: ZodIssueCode.invalid_type,
  1989. expected: ZodParsedType.void,
  1990. received: ctx.parsedType,
  1991. });
  1992. return INVALID;
  1993. }
  1994. return OK(input.data);
  1995. }
  1996. }
  1997. ZodVoid.create = (params) => {
  1998. return new ZodVoid({
  1999. typeName: exports.ZodFirstPartyTypeKind.ZodVoid,
  2000. ...processCreateParams(params),
  2001. });
  2002. };
  2003. class ZodArray extends ZodType {
  2004. _parse(input) {
  2005. const { ctx, status } = this._processInputParams(input);
  2006. const def = this._def;
  2007. if (ctx.parsedType !== ZodParsedType.array) {
  2008. addIssueToContext(ctx, {
  2009. code: ZodIssueCode.invalid_type,
  2010. expected: ZodParsedType.array,
  2011. received: ctx.parsedType,
  2012. });
  2013. return INVALID;
  2014. }
  2015. if (def.exactLength !== null) {
  2016. const tooBig = ctx.data.length > def.exactLength.value;
  2017. const tooSmall = ctx.data.length < def.exactLength.value;
  2018. if (tooBig || tooSmall) {
  2019. addIssueToContext(ctx, {
  2020. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  2021. minimum: (tooSmall ? def.exactLength.value : undefined),
  2022. maximum: (tooBig ? def.exactLength.value : undefined),
  2023. type: "array",
  2024. inclusive: true,
  2025. exact: true,
  2026. message: def.exactLength.message,
  2027. });
  2028. status.dirty();
  2029. }
  2030. }
  2031. if (def.minLength !== null) {
  2032. if (ctx.data.length < def.minLength.value) {
  2033. addIssueToContext(ctx, {
  2034. code: ZodIssueCode.too_small,
  2035. minimum: def.minLength.value,
  2036. type: "array",
  2037. inclusive: true,
  2038. exact: false,
  2039. message: def.minLength.message,
  2040. });
  2041. status.dirty();
  2042. }
  2043. }
  2044. if (def.maxLength !== null) {
  2045. if (ctx.data.length > def.maxLength.value) {
  2046. addIssueToContext(ctx, {
  2047. code: ZodIssueCode.too_big,
  2048. maximum: def.maxLength.value,
  2049. type: "array",
  2050. inclusive: true,
  2051. exact: false,
  2052. message: def.maxLength.message,
  2053. });
  2054. status.dirty();
  2055. }
  2056. }
  2057. if (ctx.common.async) {
  2058. return Promise.all([...ctx.data].map((item, i) => {
  2059. return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  2060. })).then((result) => {
  2061. return ParseStatus.mergeArray(status, result);
  2062. });
  2063. }
  2064. const result = [...ctx.data].map((item, i) => {
  2065. return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  2066. });
  2067. return ParseStatus.mergeArray(status, result);
  2068. }
  2069. get element() {
  2070. return this._def.type;
  2071. }
  2072. min(minLength, message) {
  2073. return new ZodArray({
  2074. ...this._def,
  2075. minLength: { value: minLength, message: errorUtil.toString(message) },
  2076. });
  2077. }
  2078. max(maxLength, message) {
  2079. return new ZodArray({
  2080. ...this._def,
  2081. maxLength: { value: maxLength, message: errorUtil.toString(message) },
  2082. });
  2083. }
  2084. length(len, message) {
  2085. return new ZodArray({
  2086. ...this._def,
  2087. exactLength: { value: len, message: errorUtil.toString(message) },
  2088. });
  2089. }
  2090. nonempty(message) {
  2091. return this.min(1, message);
  2092. }
  2093. }
  2094. ZodArray.create = (schema, params) => {
  2095. return new ZodArray({
  2096. type: schema,
  2097. minLength: null,
  2098. maxLength: null,
  2099. exactLength: null,
  2100. typeName: exports.ZodFirstPartyTypeKind.ZodArray,
  2101. ...processCreateParams(params),
  2102. });
  2103. };
  2104. function deepPartialify(schema) {
  2105. if (schema instanceof ZodObject) {
  2106. const newShape = {};
  2107. for (const key in schema.shape) {
  2108. const fieldSchema = schema.shape[key];
  2109. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
  2110. }
  2111. return new ZodObject({
  2112. ...schema._def,
  2113. shape: () => newShape,
  2114. });
  2115. }
  2116. else if (schema instanceof ZodArray) {
  2117. return new ZodArray({
  2118. ...schema._def,
  2119. type: deepPartialify(schema.element),
  2120. });
  2121. }
  2122. else if (schema instanceof ZodOptional) {
  2123. return ZodOptional.create(deepPartialify(schema.unwrap()));
  2124. }
  2125. else if (schema instanceof ZodNullable) {
  2126. return ZodNullable.create(deepPartialify(schema.unwrap()));
  2127. }
  2128. else if (schema instanceof ZodTuple) {
  2129. return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  2130. }
  2131. else {
  2132. return schema;
  2133. }
  2134. }
  2135. class ZodObject extends ZodType {
  2136. constructor() {
  2137. super(...arguments);
  2138. this._cached = null;
  2139. /**
  2140. * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
  2141. * If you want to pass through unknown properties, use `.passthrough()` instead.
  2142. */
  2143. this.nonstrict = this.passthrough;
  2144. // extend<
  2145. // Augmentation extends ZodRawShape,
  2146. // NewOutput extends util.flatten<{
  2147. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  2148. // ? Augmentation[k]["_output"]
  2149. // : k extends keyof Output
  2150. // ? Output[k]
  2151. // : never;
  2152. // }>,
  2153. // NewInput extends util.flatten<{
  2154. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  2155. // ? Augmentation[k]["_input"]
  2156. // : k extends keyof Input
  2157. // ? Input[k]
  2158. // : never;
  2159. // }>
  2160. // >(
  2161. // augmentation: Augmentation
  2162. // ): ZodObject<
  2163. // extendShape<T, Augmentation>,
  2164. // UnknownKeys,
  2165. // Catchall,
  2166. // NewOutput,
  2167. // NewInput
  2168. // > {
  2169. // return new ZodObject({
  2170. // ...this._def,
  2171. // shape: () => ({
  2172. // ...this._def.shape(),
  2173. // ...augmentation,
  2174. // }),
  2175. // }) as any;
  2176. // }
  2177. /**
  2178. * @deprecated Use `.extend` instead
  2179. * */
  2180. this.augment = this.extend;
  2181. }
  2182. _getCached() {
  2183. if (this._cached !== null)
  2184. return this._cached;
  2185. const shape = this._def.shape();
  2186. const keys = exports.util.objectKeys(shape);
  2187. return (this._cached = { shape, keys });
  2188. }
  2189. _parse(input) {
  2190. const parsedType = this._getType(input);
  2191. if (parsedType !== ZodParsedType.object) {
  2192. const ctx = this._getOrReturnCtx(input);
  2193. addIssueToContext(ctx, {
  2194. code: ZodIssueCode.invalid_type,
  2195. expected: ZodParsedType.object,
  2196. received: ctx.parsedType,
  2197. });
  2198. return INVALID;
  2199. }
  2200. const { status, ctx } = this._processInputParams(input);
  2201. const { shape, keys: shapeKeys } = this._getCached();
  2202. const extraKeys = [];
  2203. if (!(this._def.catchall instanceof ZodNever &&
  2204. this._def.unknownKeys === "strip")) {
  2205. for (const key in ctx.data) {
  2206. if (!shapeKeys.includes(key)) {
  2207. extraKeys.push(key);
  2208. }
  2209. }
  2210. }
  2211. const pairs = [];
  2212. for (const key of shapeKeys) {
  2213. const keyValidator = shape[key];
  2214. const value = ctx.data[key];
  2215. pairs.push({
  2216. key: { status: "valid", value: key },
  2217. value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
  2218. alwaysSet: key in ctx.data,
  2219. });
  2220. }
  2221. if (this._def.catchall instanceof ZodNever) {
  2222. const unknownKeys = this._def.unknownKeys;
  2223. if (unknownKeys === "passthrough") {
  2224. for (const key of extraKeys) {
  2225. pairs.push({
  2226. key: { status: "valid", value: key },
  2227. value: { status: "valid", value: ctx.data[key] },
  2228. });
  2229. }
  2230. }
  2231. else if (unknownKeys === "strict") {
  2232. if (extraKeys.length > 0) {
  2233. addIssueToContext(ctx, {
  2234. code: ZodIssueCode.unrecognized_keys,
  2235. keys: extraKeys,
  2236. });
  2237. status.dirty();
  2238. }
  2239. }
  2240. else if (unknownKeys === "strip") ;
  2241. else {
  2242. throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
  2243. }
  2244. }
  2245. else {
  2246. // run catchall validation
  2247. const catchall = this._def.catchall;
  2248. for (const key of extraKeys) {
  2249. const value = ctx.data[key];
  2250. pairs.push({
  2251. key: { status: "valid", value: key },
  2252. value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
  2253. ),
  2254. alwaysSet: key in ctx.data,
  2255. });
  2256. }
  2257. }
  2258. if (ctx.common.async) {
  2259. return Promise.resolve()
  2260. .then(async () => {
  2261. const syncPairs = [];
  2262. for (const pair of pairs) {
  2263. const key = await pair.key;
  2264. syncPairs.push({
  2265. key,
  2266. value: await pair.value,
  2267. alwaysSet: pair.alwaysSet,
  2268. });
  2269. }
  2270. return syncPairs;
  2271. })
  2272. .then((syncPairs) => {
  2273. return ParseStatus.mergeObjectSync(status, syncPairs);
  2274. });
  2275. }
  2276. else {
  2277. return ParseStatus.mergeObjectSync(status, pairs);
  2278. }
  2279. }
  2280. get shape() {
  2281. return this._def.shape();
  2282. }
  2283. strict(message) {
  2284. errorUtil.errToObj;
  2285. return new ZodObject({
  2286. ...this._def,
  2287. unknownKeys: "strict",
  2288. ...(message !== undefined
  2289. ? {
  2290. errorMap: (issue, ctx) => {
  2291. var _a, _b, _c, _d;
  2292. const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
  2293. if (issue.code === "unrecognized_keys")
  2294. return {
  2295. message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
  2296. };
  2297. return {
  2298. message: defaultError,
  2299. };
  2300. },
  2301. }
  2302. : {}),
  2303. });
  2304. }
  2305. strip() {
  2306. return new ZodObject({
  2307. ...this._def,
  2308. unknownKeys: "strip",
  2309. });
  2310. }
  2311. passthrough() {
  2312. return new ZodObject({
  2313. ...this._def,
  2314. unknownKeys: "passthrough",
  2315. });
  2316. }
  2317. // const AugmentFactory =
  2318. // <Def extends ZodObjectDef>(def: Def) =>
  2319. // <Augmentation extends ZodRawShape>(
  2320. // augmentation: Augmentation
  2321. // ): ZodObject<
  2322. // extendShape<ReturnType<Def["shape"]>, Augmentation>,
  2323. // Def["unknownKeys"],
  2324. // Def["catchall"]
  2325. // > => {
  2326. // return new ZodObject({
  2327. // ...def,
  2328. // shape: () => ({
  2329. // ...def.shape(),
  2330. // ...augmentation,
  2331. // }),
  2332. // }) as any;
  2333. // };
  2334. extend(augmentation) {
  2335. return new ZodObject({
  2336. ...this._def,
  2337. shape: () => ({
  2338. ...this._def.shape(),
  2339. ...augmentation,
  2340. }),
  2341. });
  2342. }
  2343. /**
  2344. * Prior to zod@1.0.12 there was a bug in the
  2345. * inferred type of merged objects. Please
  2346. * upgrade if you are experiencing issues.
  2347. */
  2348. merge(merging) {
  2349. const merged = new ZodObject({
  2350. unknownKeys: merging._def.unknownKeys,
  2351. catchall: merging._def.catchall,
  2352. shape: () => ({
  2353. ...this._def.shape(),
  2354. ...merging._def.shape(),
  2355. }),
  2356. typeName: exports.ZodFirstPartyTypeKind.ZodObject,
  2357. });
  2358. return merged;
  2359. }
  2360. // merge<
  2361. // Incoming extends AnyZodObject,
  2362. // Augmentation extends Incoming["shape"],
  2363. // NewOutput extends {
  2364. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  2365. // ? Augmentation[k]["_output"]
  2366. // : k extends keyof Output
  2367. // ? Output[k]
  2368. // : never;
  2369. // },
  2370. // NewInput extends {
  2371. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  2372. // ? Augmentation[k]["_input"]
  2373. // : k extends keyof Input
  2374. // ? Input[k]
  2375. // : never;
  2376. // }
  2377. // >(
  2378. // merging: Incoming
  2379. // ): ZodObject<
  2380. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  2381. // Incoming["_def"]["unknownKeys"],
  2382. // Incoming["_def"]["catchall"],
  2383. // NewOutput,
  2384. // NewInput
  2385. // > {
  2386. // const merged: any = new ZodObject({
  2387. // unknownKeys: merging._def.unknownKeys,
  2388. // catchall: merging._def.catchall,
  2389. // shape: () =>
  2390. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  2391. // typeName: ZodFirstPartyTypeKind.ZodObject,
  2392. // }) as any;
  2393. // return merged;
  2394. // }
  2395. setKey(key, schema) {
  2396. return this.augment({ [key]: schema });
  2397. }
  2398. // merge<Incoming extends AnyZodObject>(
  2399. // merging: Incoming
  2400. // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  2401. // ZodObject<
  2402. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  2403. // Incoming["_def"]["unknownKeys"],
  2404. // Incoming["_def"]["catchall"]
  2405. // > {
  2406. // // const mergedShape = objectUtil.mergeShapes(
  2407. // // this._def.shape(),
  2408. // // merging._def.shape()
  2409. // // );
  2410. // const merged: any = new ZodObject({
  2411. // unknownKeys: merging._def.unknownKeys,
  2412. // catchall: merging._def.catchall,
  2413. // shape: () =>
  2414. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  2415. // typeName: ZodFirstPartyTypeKind.ZodObject,
  2416. // }) as any;
  2417. // return merged;
  2418. // }
  2419. catchall(index) {
  2420. return new ZodObject({
  2421. ...this._def,
  2422. catchall: index,
  2423. });
  2424. }
  2425. pick(mask) {
  2426. const shape = {};
  2427. exports.util.objectKeys(mask).forEach((key) => {
  2428. if (mask[key] && this.shape[key]) {
  2429. shape[key] = this.shape[key];
  2430. }
  2431. });
  2432. return new ZodObject({
  2433. ...this._def,
  2434. shape: () => shape,
  2435. });
  2436. }
  2437. omit(mask) {
  2438. const shape = {};
  2439. exports.util.objectKeys(this.shape).forEach((key) => {
  2440. if (!mask[key]) {
  2441. shape[key] = this.shape[key];
  2442. }
  2443. });
  2444. return new ZodObject({
  2445. ...this._def,
  2446. shape: () => shape,
  2447. });
  2448. }
  2449. /**
  2450. * @deprecated
  2451. */
  2452. deepPartial() {
  2453. return deepPartialify(this);
  2454. }
  2455. partial(mask) {
  2456. const newShape = {};
  2457. exports.util.objectKeys(this.shape).forEach((key) => {
  2458. const fieldSchema = this.shape[key];
  2459. if (mask && !mask[key]) {
  2460. newShape[key] = fieldSchema;
  2461. }
  2462. else {
  2463. newShape[key] = fieldSchema.optional();
  2464. }
  2465. });
  2466. return new ZodObject({
  2467. ...this._def,
  2468. shape: () => newShape,
  2469. });
  2470. }
  2471. required(mask) {
  2472. const newShape = {};
  2473. exports.util.objectKeys(this.shape).forEach((key) => {
  2474. if (mask && !mask[key]) {
  2475. newShape[key] = this.shape[key];
  2476. }
  2477. else {
  2478. const fieldSchema = this.shape[key];
  2479. let newField = fieldSchema;
  2480. while (newField instanceof ZodOptional) {
  2481. newField = newField._def.innerType;
  2482. }
  2483. newShape[key] = newField;
  2484. }
  2485. });
  2486. return new ZodObject({
  2487. ...this._def,
  2488. shape: () => newShape,
  2489. });
  2490. }
  2491. keyof() {
  2492. return createZodEnum(exports.util.objectKeys(this.shape));
  2493. }
  2494. }
  2495. ZodObject.create = (shape, params) => {
  2496. return new ZodObject({
  2497. shape: () => shape,
  2498. unknownKeys: "strip",
  2499. catchall: ZodNever.create(),
  2500. typeName: exports.ZodFirstPartyTypeKind.ZodObject,
  2501. ...processCreateParams(params),
  2502. });
  2503. };
  2504. ZodObject.strictCreate = (shape, params) => {
  2505. return new ZodObject({
  2506. shape: () => shape,
  2507. unknownKeys: "strict",
  2508. catchall: ZodNever.create(),
  2509. typeName: exports.ZodFirstPartyTypeKind.ZodObject,
  2510. ...processCreateParams(params),
  2511. });
  2512. };
  2513. ZodObject.lazycreate = (shape, params) => {
  2514. return new ZodObject({
  2515. shape,
  2516. unknownKeys: "strip",
  2517. catchall: ZodNever.create(),
  2518. typeName: exports.ZodFirstPartyTypeKind.ZodObject,
  2519. ...processCreateParams(params),
  2520. });
  2521. };
  2522. class ZodUnion extends ZodType {
  2523. _parse(input) {
  2524. const { ctx } = this._processInputParams(input);
  2525. const options = this._def.options;
  2526. function handleResults(results) {
  2527. // return first issue-free validation if it exists
  2528. for (const result of results) {
  2529. if (result.result.status === "valid") {
  2530. return result.result;
  2531. }
  2532. }
  2533. for (const result of results) {
  2534. if (result.result.status === "dirty") {
  2535. // add issues from dirty option
  2536. ctx.common.issues.push(...result.ctx.common.issues);
  2537. return result.result;
  2538. }
  2539. }
  2540. // return invalid
  2541. const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
  2542. addIssueToContext(ctx, {
  2543. code: ZodIssueCode.invalid_union,
  2544. unionErrors,
  2545. });
  2546. return INVALID;
  2547. }
  2548. if (ctx.common.async) {
  2549. return Promise.all(options.map(async (option) => {
  2550. const childCtx = {
  2551. ...ctx,
  2552. common: {
  2553. ...ctx.common,
  2554. issues: [],
  2555. },
  2556. parent: null,
  2557. };
  2558. return {
  2559. result: await option._parseAsync({
  2560. data: ctx.data,
  2561. path: ctx.path,
  2562. parent: childCtx,
  2563. }),
  2564. ctx: childCtx,
  2565. };
  2566. })).then(handleResults);
  2567. }
  2568. else {
  2569. let dirty = undefined;
  2570. const issues = [];
  2571. for (const option of options) {
  2572. const childCtx = {
  2573. ...ctx,
  2574. common: {
  2575. ...ctx.common,
  2576. issues: [],
  2577. },
  2578. parent: null,
  2579. };
  2580. const result = option._parseSync({
  2581. data: ctx.data,
  2582. path: ctx.path,
  2583. parent: childCtx,
  2584. });
  2585. if (result.status === "valid") {
  2586. return result;
  2587. }
  2588. else if (result.status === "dirty" && !dirty) {
  2589. dirty = { result, ctx: childCtx };
  2590. }
  2591. if (childCtx.common.issues.length) {
  2592. issues.push(childCtx.common.issues);
  2593. }
  2594. }
  2595. if (dirty) {
  2596. ctx.common.issues.push(...dirty.ctx.common.issues);
  2597. return dirty.result;
  2598. }
  2599. const unionErrors = issues.map((issues) => new ZodError(issues));
  2600. addIssueToContext(ctx, {
  2601. code: ZodIssueCode.invalid_union,
  2602. unionErrors,
  2603. });
  2604. return INVALID;
  2605. }
  2606. }
  2607. get options() {
  2608. return this._def.options;
  2609. }
  2610. }
  2611. ZodUnion.create = (types, params) => {
  2612. return new ZodUnion({
  2613. options: types,
  2614. typeName: exports.ZodFirstPartyTypeKind.ZodUnion,
  2615. ...processCreateParams(params),
  2616. });
  2617. };
  2618. /////////////////////////////////////////////////////
  2619. /////////////////////////////////////////////////////
  2620. ////////// //////////
  2621. ////////// ZodDiscriminatedUnion //////////
  2622. ////////// //////////
  2623. /////////////////////////////////////////////////////
  2624. /////////////////////////////////////////////////////
  2625. const getDiscriminator = (type) => {
  2626. if (type instanceof ZodLazy) {
  2627. return getDiscriminator(type.schema);
  2628. }
  2629. else if (type instanceof ZodEffects) {
  2630. return getDiscriminator(type.innerType());
  2631. }
  2632. else if (type instanceof ZodLiteral) {
  2633. return [type.value];
  2634. }
  2635. else if (type instanceof ZodEnum) {
  2636. return type.options;
  2637. }
  2638. else if (type instanceof ZodNativeEnum) {
  2639. // eslint-disable-next-line ban/ban
  2640. return Object.keys(type.enum);
  2641. }
  2642. else if (type instanceof ZodDefault) {
  2643. return getDiscriminator(type._def.innerType);
  2644. }
  2645. else if (type instanceof ZodUndefined) {
  2646. return [undefined];
  2647. }
  2648. else if (type instanceof ZodNull) {
  2649. return [null];
  2650. }
  2651. else {
  2652. return null;
  2653. }
  2654. };
  2655. class ZodDiscriminatedUnion extends ZodType {
  2656. _parse(input) {
  2657. const { ctx } = this._processInputParams(input);
  2658. if (ctx.parsedType !== ZodParsedType.object) {
  2659. addIssueToContext(ctx, {
  2660. code: ZodIssueCode.invalid_type,
  2661. expected: ZodParsedType.object,
  2662. received: ctx.parsedType,
  2663. });
  2664. return INVALID;
  2665. }
  2666. const discriminator = this.discriminator;
  2667. const discriminatorValue = ctx.data[discriminator];
  2668. const option = this.optionsMap.get(discriminatorValue);
  2669. if (!option) {
  2670. addIssueToContext(ctx, {
  2671. code: ZodIssueCode.invalid_union_discriminator,
  2672. options: Array.from(this.optionsMap.keys()),
  2673. path: [discriminator],
  2674. });
  2675. return INVALID;
  2676. }
  2677. if (ctx.common.async) {
  2678. return option._parseAsync({
  2679. data: ctx.data,
  2680. path: ctx.path,
  2681. parent: ctx,
  2682. });
  2683. }
  2684. else {
  2685. return option._parseSync({
  2686. data: ctx.data,
  2687. path: ctx.path,
  2688. parent: ctx,
  2689. });
  2690. }
  2691. }
  2692. get discriminator() {
  2693. return this._def.discriminator;
  2694. }
  2695. get options() {
  2696. return this._def.options;
  2697. }
  2698. get optionsMap() {
  2699. return this._def.optionsMap;
  2700. }
  2701. /**
  2702. * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
  2703. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
  2704. * have a different value for each object in the union.
  2705. * @param discriminator the name of the discriminator property
  2706. * @param types an array of object schemas
  2707. * @param params
  2708. */
  2709. static create(discriminator, options, params) {
  2710. // Get all the valid discriminator values
  2711. const optionsMap = new Map();
  2712. // try {
  2713. for (const type of options) {
  2714. const discriminatorValues = getDiscriminator(type.shape[discriminator]);
  2715. if (!discriminatorValues) {
  2716. throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
  2717. }
  2718. for (const value of discriminatorValues) {
  2719. if (optionsMap.has(value)) {
  2720. throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
  2721. }
  2722. optionsMap.set(value, type);
  2723. }
  2724. }
  2725. return new ZodDiscriminatedUnion({
  2726. typeName: exports.ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  2727. discriminator,
  2728. options,
  2729. optionsMap,
  2730. ...processCreateParams(params),
  2731. });
  2732. }
  2733. }
  2734. function mergeValues(a, b) {
  2735. const aType = getParsedType(a);
  2736. const bType = getParsedType(b);
  2737. if (a === b) {
  2738. return { valid: true, data: a };
  2739. }
  2740. else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  2741. const bKeys = exports.util.objectKeys(b);
  2742. const sharedKeys = exports.util
  2743. .objectKeys(a)
  2744. .filter((key) => bKeys.indexOf(key) !== -1);
  2745. const newObj = { ...a, ...b };
  2746. for (const key of sharedKeys) {
  2747. const sharedValue = mergeValues(a[key], b[key]);
  2748. if (!sharedValue.valid) {
  2749. return { valid: false };
  2750. }
  2751. newObj[key] = sharedValue.data;
  2752. }
  2753. return { valid: true, data: newObj };
  2754. }
  2755. else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  2756. if (a.length !== b.length) {
  2757. return { valid: false };
  2758. }
  2759. const newArray = [];
  2760. for (let index = 0; index < a.length; index++) {
  2761. const itemA = a[index];
  2762. const itemB = b[index];
  2763. const sharedValue = mergeValues(itemA, itemB);
  2764. if (!sharedValue.valid) {
  2765. return { valid: false };
  2766. }
  2767. newArray.push(sharedValue.data);
  2768. }
  2769. return { valid: true, data: newArray };
  2770. }
  2771. else if (aType === ZodParsedType.date &&
  2772. bType === ZodParsedType.date &&
  2773. +a === +b) {
  2774. return { valid: true, data: a };
  2775. }
  2776. else {
  2777. return { valid: false };
  2778. }
  2779. }
  2780. class ZodIntersection extends ZodType {
  2781. _parse(input) {
  2782. const { status, ctx } = this._processInputParams(input);
  2783. const handleParsed = (parsedLeft, parsedRight) => {
  2784. if (isAborted(parsedLeft) || isAborted(parsedRight)) {
  2785. return INVALID;
  2786. }
  2787. const merged = mergeValues(parsedLeft.value, parsedRight.value);
  2788. if (!merged.valid) {
  2789. addIssueToContext(ctx, {
  2790. code: ZodIssueCode.invalid_intersection_types,
  2791. });
  2792. return INVALID;
  2793. }
  2794. if (isDirty(parsedLeft) || isDirty(parsedRight)) {
  2795. status.dirty();
  2796. }
  2797. return { status: status.value, value: merged.data };
  2798. };
  2799. if (ctx.common.async) {
  2800. return Promise.all([
  2801. this._def.left._parseAsync({
  2802. data: ctx.data,
  2803. path: ctx.path,
  2804. parent: ctx,
  2805. }),
  2806. this._def.right._parseAsync({
  2807. data: ctx.data,
  2808. path: ctx.path,
  2809. parent: ctx,
  2810. }),
  2811. ]).then(([left, right]) => handleParsed(left, right));
  2812. }
  2813. else {
  2814. return handleParsed(this._def.left._parseSync({
  2815. data: ctx.data,
  2816. path: ctx.path,
  2817. parent: ctx,
  2818. }), this._def.right._parseSync({
  2819. data: ctx.data,
  2820. path: ctx.path,
  2821. parent: ctx,
  2822. }));
  2823. }
  2824. }
  2825. }
  2826. ZodIntersection.create = (left, right, params) => {
  2827. return new ZodIntersection({
  2828. left: left,
  2829. right: right,
  2830. typeName: exports.ZodFirstPartyTypeKind.ZodIntersection,
  2831. ...processCreateParams(params),
  2832. });
  2833. };
  2834. class ZodTuple extends ZodType {
  2835. _parse(input) {
  2836. const { status, ctx } = this._processInputParams(input);
  2837. if (ctx.parsedType !== ZodParsedType.array) {
  2838. addIssueToContext(ctx, {
  2839. code: ZodIssueCode.invalid_type,
  2840. expected: ZodParsedType.array,
  2841. received: ctx.parsedType,
  2842. });
  2843. return INVALID;
  2844. }
  2845. if (ctx.data.length < this._def.items.length) {
  2846. addIssueToContext(ctx, {
  2847. code: ZodIssueCode.too_small,
  2848. minimum: this._def.items.length,
  2849. inclusive: true,
  2850. exact: false,
  2851. type: "array",
  2852. });
  2853. return INVALID;
  2854. }
  2855. const rest = this._def.rest;
  2856. if (!rest && ctx.data.length > this._def.items.length) {
  2857. addIssueToContext(ctx, {
  2858. code: ZodIssueCode.too_big,
  2859. maximum: this._def.items.length,
  2860. inclusive: true,
  2861. exact: false,
  2862. type: "array",
  2863. });
  2864. status.dirty();
  2865. }
  2866. const items = [...ctx.data]
  2867. .map((item, itemIndex) => {
  2868. const schema = this._def.items[itemIndex] || this._def.rest;
  2869. if (!schema)
  2870. return null;
  2871. return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
  2872. })
  2873. .filter((x) => !!x); // filter nulls
  2874. if (ctx.common.async) {
  2875. return Promise.all(items).then((results) => {
  2876. return ParseStatus.mergeArray(status, results);
  2877. });
  2878. }
  2879. else {
  2880. return ParseStatus.mergeArray(status, items);
  2881. }
  2882. }
  2883. get items() {
  2884. return this._def.items;
  2885. }
  2886. rest(rest) {
  2887. return new ZodTuple({
  2888. ...this._def,
  2889. rest,
  2890. });
  2891. }
  2892. }
  2893. ZodTuple.create = (schemas, params) => {
  2894. if (!Array.isArray(schemas)) {
  2895. throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  2896. }
  2897. return new ZodTuple({
  2898. items: schemas,
  2899. typeName: exports.ZodFirstPartyTypeKind.ZodTuple,
  2900. rest: null,
  2901. ...processCreateParams(params),
  2902. });
  2903. };
  2904. class ZodRecord extends ZodType {
  2905. get keySchema() {
  2906. return this._def.keyType;
  2907. }
  2908. get valueSchema() {
  2909. return this._def.valueType;
  2910. }
  2911. _parse(input) {
  2912. const { status, ctx } = this._processInputParams(input);
  2913. if (ctx.parsedType !== ZodParsedType.object) {
  2914. addIssueToContext(ctx, {
  2915. code: ZodIssueCode.invalid_type,
  2916. expected: ZodParsedType.object,
  2917. received: ctx.parsedType,
  2918. });
  2919. return INVALID;
  2920. }
  2921. const pairs = [];
  2922. const keyType = this._def.keyType;
  2923. const valueType = this._def.valueType;
  2924. for (const key in ctx.data) {
  2925. pairs.push({
  2926. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
  2927. value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
  2928. });
  2929. }
  2930. if (ctx.common.async) {
  2931. return ParseStatus.mergeObjectAsync(status, pairs);
  2932. }
  2933. else {
  2934. return ParseStatus.mergeObjectSync(status, pairs);
  2935. }
  2936. }
  2937. get element() {
  2938. return this._def.valueType;
  2939. }
  2940. static create(first, second, third) {
  2941. if (second instanceof ZodType) {
  2942. return new ZodRecord({
  2943. keyType: first,
  2944. valueType: second,
  2945. typeName: exports.ZodFirstPartyTypeKind.ZodRecord,
  2946. ...processCreateParams(third),
  2947. });
  2948. }
  2949. return new ZodRecord({
  2950. keyType: ZodString.create(),
  2951. valueType: first,
  2952. typeName: exports.ZodFirstPartyTypeKind.ZodRecord,
  2953. ...processCreateParams(second),
  2954. });
  2955. }
  2956. }
  2957. class ZodMap extends ZodType {
  2958. get keySchema() {
  2959. return this._def.keyType;
  2960. }
  2961. get valueSchema() {
  2962. return this._def.valueType;
  2963. }
  2964. _parse(input) {
  2965. const { status, ctx } = this._processInputParams(input);
  2966. if (ctx.parsedType !== ZodParsedType.map) {
  2967. addIssueToContext(ctx, {
  2968. code: ZodIssueCode.invalid_type,
  2969. expected: ZodParsedType.map,
  2970. received: ctx.parsedType,
  2971. });
  2972. return INVALID;
  2973. }
  2974. const keyType = this._def.keyType;
  2975. const valueType = this._def.valueType;
  2976. const pairs = [...ctx.data.entries()].map(([key, value], index) => {
  2977. return {
  2978. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
  2979. value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
  2980. };
  2981. });
  2982. if (ctx.common.async) {
  2983. const finalMap = new Map();
  2984. return Promise.resolve().then(async () => {
  2985. for (const pair of pairs) {
  2986. const key = await pair.key;
  2987. const value = await pair.value;
  2988. if (key.status === "aborted" || value.status === "aborted") {
  2989. return INVALID;
  2990. }
  2991. if (key.status === "dirty" || value.status === "dirty") {
  2992. status.dirty();
  2993. }
  2994. finalMap.set(key.value, value.value);
  2995. }
  2996. return { status: status.value, value: finalMap };
  2997. });
  2998. }
  2999. else {
  3000. const finalMap = new Map();
  3001. for (const pair of pairs) {
  3002. const key = pair.key;
  3003. const value = pair.value;
  3004. if (key.status === "aborted" || value.status === "aborted") {
  3005. return INVALID;
  3006. }
  3007. if (key.status === "dirty" || value.status === "dirty") {
  3008. status.dirty();
  3009. }
  3010. finalMap.set(key.value, value.value);
  3011. }
  3012. return { status: status.value, value: finalMap };
  3013. }
  3014. }
  3015. }
  3016. ZodMap.create = (keyType, valueType, params) => {
  3017. return new ZodMap({
  3018. valueType,
  3019. keyType,
  3020. typeName: exports.ZodFirstPartyTypeKind.ZodMap,
  3021. ...processCreateParams(params),
  3022. });
  3023. };
  3024. class ZodSet extends ZodType {
  3025. _parse(input) {
  3026. const { status, ctx } = this._processInputParams(input);
  3027. if (ctx.parsedType !== ZodParsedType.set) {
  3028. addIssueToContext(ctx, {
  3029. code: ZodIssueCode.invalid_type,
  3030. expected: ZodParsedType.set,
  3031. received: ctx.parsedType,
  3032. });
  3033. return INVALID;
  3034. }
  3035. const def = this._def;
  3036. if (def.minSize !== null) {
  3037. if (ctx.data.size < def.minSize.value) {
  3038. addIssueToContext(ctx, {
  3039. code: ZodIssueCode.too_small,
  3040. minimum: def.minSize.value,
  3041. type: "set",
  3042. inclusive: true,
  3043. exact: false,
  3044. message: def.minSize.message,
  3045. });
  3046. status.dirty();
  3047. }
  3048. }
  3049. if (def.maxSize !== null) {
  3050. if (ctx.data.size > def.maxSize.value) {
  3051. addIssueToContext(ctx, {
  3052. code: ZodIssueCode.too_big,
  3053. maximum: def.maxSize.value,
  3054. type: "set",
  3055. inclusive: true,
  3056. exact: false,
  3057. message: def.maxSize.message,
  3058. });
  3059. status.dirty();
  3060. }
  3061. }
  3062. const valueType = this._def.valueType;
  3063. function finalizeSet(elements) {
  3064. const parsedSet = new Set();
  3065. for (const element of elements) {
  3066. if (element.status === "aborted")
  3067. return INVALID;
  3068. if (element.status === "dirty")
  3069. status.dirty();
  3070. parsedSet.add(element.value);
  3071. }
  3072. return { status: status.value, value: parsedSet };
  3073. }
  3074. const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
  3075. if (ctx.common.async) {
  3076. return Promise.all(elements).then((elements) => finalizeSet(elements));
  3077. }
  3078. else {
  3079. return finalizeSet(elements);
  3080. }
  3081. }
  3082. min(minSize, message) {
  3083. return new ZodSet({
  3084. ...this._def,
  3085. minSize: { value: minSize, message: errorUtil.toString(message) },
  3086. });
  3087. }
  3088. max(maxSize, message) {
  3089. return new ZodSet({
  3090. ...this._def,
  3091. maxSize: { value: maxSize, message: errorUtil.toString(message) },
  3092. });
  3093. }
  3094. size(size, message) {
  3095. return this.min(size, message).max(size, message);
  3096. }
  3097. nonempty(message) {
  3098. return this.min(1, message);
  3099. }
  3100. }
  3101. ZodSet.create = (valueType, params) => {
  3102. return new ZodSet({
  3103. valueType,
  3104. minSize: null,
  3105. maxSize: null,
  3106. typeName: exports.ZodFirstPartyTypeKind.ZodSet,
  3107. ...processCreateParams(params),
  3108. });
  3109. };
  3110. class ZodFunction extends ZodType {
  3111. constructor() {
  3112. super(...arguments);
  3113. this.validate = this.implement;
  3114. }
  3115. _parse(input) {
  3116. const { ctx } = this._processInputParams(input);
  3117. if (ctx.parsedType !== ZodParsedType.function) {
  3118. addIssueToContext(ctx, {
  3119. code: ZodIssueCode.invalid_type,
  3120. expected: ZodParsedType.function,
  3121. received: ctx.parsedType,
  3122. });
  3123. return INVALID;
  3124. }
  3125. function makeArgsIssue(args, error) {
  3126. return makeIssue({
  3127. data: args,
  3128. path: ctx.path,
  3129. errorMaps: [
  3130. ctx.common.contextualErrorMap,
  3131. ctx.schemaErrorMap,
  3132. getErrorMap(),
  3133. errorMap,
  3134. ].filter((x) => !!x),
  3135. issueData: {
  3136. code: ZodIssueCode.invalid_arguments,
  3137. argumentsError: error,
  3138. },
  3139. });
  3140. }
  3141. function makeReturnsIssue(returns, error) {
  3142. return makeIssue({
  3143. data: returns,
  3144. path: ctx.path,
  3145. errorMaps: [
  3146. ctx.common.contextualErrorMap,
  3147. ctx.schemaErrorMap,
  3148. getErrorMap(),
  3149. errorMap,
  3150. ].filter((x) => !!x),
  3151. issueData: {
  3152. code: ZodIssueCode.invalid_return_type,
  3153. returnTypeError: error,
  3154. },
  3155. });
  3156. }
  3157. const params = { errorMap: ctx.common.contextualErrorMap };
  3158. const fn = ctx.data;
  3159. if (this._def.returns instanceof ZodPromise) {
  3160. // Would love a way to avoid disabling this rule, but we need
  3161. // an alias (using an arrow function was what caused 2651).
  3162. // eslint-disable-next-line @typescript-eslint/no-this-alias
  3163. const me = this;
  3164. return OK(async function (...args) {
  3165. const error = new ZodError([]);
  3166. const parsedArgs = await me._def.args
  3167. .parseAsync(args, params)
  3168. .catch((e) => {
  3169. error.addIssue(makeArgsIssue(args, e));
  3170. throw error;
  3171. });
  3172. const result = await Reflect.apply(fn, this, parsedArgs);
  3173. const parsedReturns = await me._def.returns._def.type
  3174. .parseAsync(result, params)
  3175. .catch((e) => {
  3176. error.addIssue(makeReturnsIssue(result, e));
  3177. throw error;
  3178. });
  3179. return parsedReturns;
  3180. });
  3181. }
  3182. else {
  3183. // Would love a way to avoid disabling this rule, but we need
  3184. // an alias (using an arrow function was what caused 2651).
  3185. // eslint-disable-next-line @typescript-eslint/no-this-alias
  3186. const me = this;
  3187. return OK(function (...args) {
  3188. const parsedArgs = me._def.args.safeParse(args, params);
  3189. if (!parsedArgs.success) {
  3190. throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
  3191. }
  3192. const result = Reflect.apply(fn, this, parsedArgs.data);
  3193. const parsedReturns = me._def.returns.safeParse(result, params);
  3194. if (!parsedReturns.success) {
  3195. throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
  3196. }
  3197. return parsedReturns.data;
  3198. });
  3199. }
  3200. }
  3201. parameters() {
  3202. return this._def.args;
  3203. }
  3204. returnType() {
  3205. return this._def.returns;
  3206. }
  3207. args(...items) {
  3208. return new ZodFunction({
  3209. ...this._def,
  3210. args: ZodTuple.create(items).rest(ZodUnknown.create()),
  3211. });
  3212. }
  3213. returns(returnType) {
  3214. return new ZodFunction({
  3215. ...this._def,
  3216. returns: returnType,
  3217. });
  3218. }
  3219. implement(func) {
  3220. const validatedFunc = this.parse(func);
  3221. return validatedFunc;
  3222. }
  3223. strictImplement(func) {
  3224. const validatedFunc = this.parse(func);
  3225. return validatedFunc;
  3226. }
  3227. static create(args, returns, params) {
  3228. return new ZodFunction({
  3229. args: (args
  3230. ? args
  3231. : ZodTuple.create([]).rest(ZodUnknown.create())),
  3232. returns: returns || ZodUnknown.create(),
  3233. typeName: exports.ZodFirstPartyTypeKind.ZodFunction,
  3234. ...processCreateParams(params),
  3235. });
  3236. }
  3237. }
  3238. class ZodLazy extends ZodType {
  3239. get schema() {
  3240. return this._def.getter();
  3241. }
  3242. _parse(input) {
  3243. const { ctx } = this._processInputParams(input);
  3244. const lazySchema = this._def.getter();
  3245. return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  3246. }
  3247. }
  3248. ZodLazy.create = (getter, params) => {
  3249. return new ZodLazy({
  3250. getter: getter,
  3251. typeName: exports.ZodFirstPartyTypeKind.ZodLazy,
  3252. ...processCreateParams(params),
  3253. });
  3254. };
  3255. class ZodLiteral extends ZodType {
  3256. _parse(input) {
  3257. if (input.data !== this._def.value) {
  3258. const ctx = this._getOrReturnCtx(input);
  3259. addIssueToContext(ctx, {
  3260. received: ctx.data,
  3261. code: ZodIssueCode.invalid_literal,
  3262. expected: this._def.value,
  3263. });
  3264. return INVALID;
  3265. }
  3266. return { status: "valid", value: input.data };
  3267. }
  3268. get value() {
  3269. return this._def.value;
  3270. }
  3271. }
  3272. ZodLiteral.create = (value, params) => {
  3273. return new ZodLiteral({
  3274. value: value,
  3275. typeName: exports.ZodFirstPartyTypeKind.ZodLiteral,
  3276. ...processCreateParams(params),
  3277. });
  3278. };
  3279. function createZodEnum(values, params) {
  3280. return new ZodEnum({
  3281. values,
  3282. typeName: exports.ZodFirstPartyTypeKind.ZodEnum,
  3283. ...processCreateParams(params),
  3284. });
  3285. }
  3286. class ZodEnum extends ZodType {
  3287. _parse(input) {
  3288. if (typeof input.data !== "string") {
  3289. const ctx = this._getOrReturnCtx(input);
  3290. const expectedValues = this._def.values;
  3291. addIssueToContext(ctx, {
  3292. expected: exports.util.joinValues(expectedValues),
  3293. received: ctx.parsedType,
  3294. code: ZodIssueCode.invalid_type,
  3295. });
  3296. return INVALID;
  3297. }
  3298. if (this._def.values.indexOf(input.data) === -1) {
  3299. const ctx = this._getOrReturnCtx(input);
  3300. const expectedValues = this._def.values;
  3301. addIssueToContext(ctx, {
  3302. received: ctx.data,
  3303. code: ZodIssueCode.invalid_enum_value,
  3304. options: expectedValues,
  3305. });
  3306. return INVALID;
  3307. }
  3308. return OK(input.data);
  3309. }
  3310. get options() {
  3311. return this._def.values;
  3312. }
  3313. get enum() {
  3314. const enumValues = {};
  3315. for (const val of this._def.values) {
  3316. enumValues[val] = val;
  3317. }
  3318. return enumValues;
  3319. }
  3320. get Values() {
  3321. const enumValues = {};
  3322. for (const val of this._def.values) {
  3323. enumValues[val] = val;
  3324. }
  3325. return enumValues;
  3326. }
  3327. get Enum() {
  3328. const enumValues = {};
  3329. for (const val of this._def.values) {
  3330. enumValues[val] = val;
  3331. }
  3332. return enumValues;
  3333. }
  3334. extract(values) {
  3335. return ZodEnum.create(values);
  3336. }
  3337. exclude(values) {
  3338. return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
  3339. }
  3340. }
  3341. ZodEnum.create = createZodEnum;
  3342. class ZodNativeEnum extends ZodType {
  3343. _parse(input) {
  3344. const nativeEnumValues = exports.util.getValidEnumValues(this._def.values);
  3345. const ctx = this._getOrReturnCtx(input);
  3346. if (ctx.parsedType !== ZodParsedType.string &&
  3347. ctx.parsedType !== ZodParsedType.number) {
  3348. const expectedValues = exports.util.objectValues(nativeEnumValues);
  3349. addIssueToContext(ctx, {
  3350. expected: exports.util.joinValues(expectedValues),
  3351. received: ctx.parsedType,
  3352. code: ZodIssueCode.invalid_type,
  3353. });
  3354. return INVALID;
  3355. }
  3356. if (nativeEnumValues.indexOf(input.data) === -1) {
  3357. const expectedValues = exports.util.objectValues(nativeEnumValues);
  3358. addIssueToContext(ctx, {
  3359. received: ctx.data,
  3360. code: ZodIssueCode.invalid_enum_value,
  3361. options: expectedValues,
  3362. });
  3363. return INVALID;
  3364. }
  3365. return OK(input.data);
  3366. }
  3367. get enum() {
  3368. return this._def.values;
  3369. }
  3370. }
  3371. ZodNativeEnum.create = (values, params) => {
  3372. return new ZodNativeEnum({
  3373. values: values,
  3374. typeName: exports.ZodFirstPartyTypeKind.ZodNativeEnum,
  3375. ...processCreateParams(params),
  3376. });
  3377. };
  3378. class ZodPromise extends ZodType {
  3379. unwrap() {
  3380. return this._def.type;
  3381. }
  3382. _parse(input) {
  3383. const { ctx } = this._processInputParams(input);
  3384. if (ctx.parsedType !== ZodParsedType.promise &&
  3385. ctx.common.async === false) {
  3386. addIssueToContext(ctx, {
  3387. code: ZodIssueCode.invalid_type,
  3388. expected: ZodParsedType.promise,
  3389. received: ctx.parsedType,
  3390. });
  3391. return INVALID;
  3392. }
  3393. const promisified = ctx.parsedType === ZodParsedType.promise
  3394. ? ctx.data
  3395. : Promise.resolve(ctx.data);
  3396. return OK(promisified.then((data) => {
  3397. return this._def.type.parseAsync(data, {
  3398. path: ctx.path,
  3399. errorMap: ctx.common.contextualErrorMap,
  3400. });
  3401. }));
  3402. }
  3403. }
  3404. ZodPromise.create = (schema, params) => {
  3405. return new ZodPromise({
  3406. type: schema,
  3407. typeName: exports.ZodFirstPartyTypeKind.ZodPromise,
  3408. ...processCreateParams(params),
  3409. });
  3410. };
  3411. class ZodEffects extends ZodType {
  3412. innerType() {
  3413. return this._def.schema;
  3414. }
  3415. sourceType() {
  3416. return this._def.schema._def.typeName === exports.ZodFirstPartyTypeKind.ZodEffects
  3417. ? this._def.schema.sourceType()
  3418. : this._def.schema;
  3419. }
  3420. _parse(input) {
  3421. const { status, ctx } = this._processInputParams(input);
  3422. const effect = this._def.effect || null;
  3423. const checkCtx = {
  3424. addIssue: (arg) => {
  3425. addIssueToContext(ctx, arg);
  3426. if (arg.fatal) {
  3427. status.abort();
  3428. }
  3429. else {
  3430. status.dirty();
  3431. }
  3432. },
  3433. get path() {
  3434. return ctx.path;
  3435. },
  3436. };
  3437. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
  3438. if (effect.type === "preprocess") {
  3439. const processed = effect.transform(ctx.data, checkCtx);
  3440. if (ctx.common.issues.length) {
  3441. return {
  3442. status: "dirty",
  3443. value: ctx.data,
  3444. };
  3445. }
  3446. if (ctx.common.async) {
  3447. return Promise.resolve(processed).then((processed) => {
  3448. return this._def.schema._parseAsync({
  3449. data: processed,
  3450. path: ctx.path,
  3451. parent: ctx,
  3452. });
  3453. });
  3454. }
  3455. else {
  3456. return this._def.schema._parseSync({
  3457. data: processed,
  3458. path: ctx.path,
  3459. parent: ctx,
  3460. });
  3461. }
  3462. }
  3463. if (effect.type === "refinement") {
  3464. const executeRefinement = (acc
  3465. // effect: RefinementEffect<any>
  3466. ) => {
  3467. const result = effect.refinement(acc, checkCtx);
  3468. if (ctx.common.async) {
  3469. return Promise.resolve(result);
  3470. }
  3471. if (result instanceof Promise) {
  3472. throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
  3473. }
  3474. return acc;
  3475. };
  3476. if (ctx.common.async === false) {
  3477. const inner = this._def.schema._parseSync({
  3478. data: ctx.data,
  3479. path: ctx.path,
  3480. parent: ctx,
  3481. });
  3482. if (inner.status === "aborted")
  3483. return INVALID;
  3484. if (inner.status === "dirty")
  3485. status.dirty();
  3486. // return value is ignored
  3487. executeRefinement(inner.value);
  3488. return { status: status.value, value: inner.value };
  3489. }
  3490. else {
  3491. return this._def.schema
  3492. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  3493. .then((inner) => {
  3494. if (inner.status === "aborted")
  3495. return INVALID;
  3496. if (inner.status === "dirty")
  3497. status.dirty();
  3498. return executeRefinement(inner.value).then(() => {
  3499. return { status: status.value, value: inner.value };
  3500. });
  3501. });
  3502. }
  3503. }
  3504. if (effect.type === "transform") {
  3505. if (ctx.common.async === false) {
  3506. const base = this._def.schema._parseSync({
  3507. data: ctx.data,
  3508. path: ctx.path,
  3509. parent: ctx,
  3510. });
  3511. if (!isValid(base))
  3512. return base;
  3513. const result = effect.transform(base.value, checkCtx);
  3514. if (result instanceof Promise) {
  3515. throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
  3516. }
  3517. return { status: status.value, value: result };
  3518. }
  3519. else {
  3520. return this._def.schema
  3521. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  3522. .then((base) => {
  3523. if (!isValid(base))
  3524. return base;
  3525. return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
  3526. });
  3527. }
  3528. }
  3529. exports.util.assertNever(effect);
  3530. }
  3531. }
  3532. ZodEffects.create = (schema, effect, params) => {
  3533. return new ZodEffects({
  3534. schema,
  3535. typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
  3536. effect,
  3537. ...processCreateParams(params),
  3538. });
  3539. };
  3540. ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  3541. return new ZodEffects({
  3542. schema,
  3543. effect: { type: "preprocess", transform: preprocess },
  3544. typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
  3545. ...processCreateParams(params),
  3546. });
  3547. };
  3548. class ZodOptional extends ZodType {
  3549. _parse(input) {
  3550. const parsedType = this._getType(input);
  3551. if (parsedType === ZodParsedType.undefined) {
  3552. return OK(undefined);
  3553. }
  3554. return this._def.innerType._parse(input);
  3555. }
  3556. unwrap() {
  3557. return this._def.innerType;
  3558. }
  3559. }
  3560. ZodOptional.create = (type, params) => {
  3561. return new ZodOptional({
  3562. innerType: type,
  3563. typeName: exports.ZodFirstPartyTypeKind.ZodOptional,
  3564. ...processCreateParams(params),
  3565. });
  3566. };
  3567. class ZodNullable extends ZodType {
  3568. _parse(input) {
  3569. const parsedType = this._getType(input);
  3570. if (parsedType === ZodParsedType.null) {
  3571. return OK(null);
  3572. }
  3573. return this._def.innerType._parse(input);
  3574. }
  3575. unwrap() {
  3576. return this._def.innerType;
  3577. }
  3578. }
  3579. ZodNullable.create = (type, params) => {
  3580. return new ZodNullable({
  3581. innerType: type,
  3582. typeName: exports.ZodFirstPartyTypeKind.ZodNullable,
  3583. ...processCreateParams(params),
  3584. });
  3585. };
  3586. class ZodDefault extends ZodType {
  3587. _parse(input) {
  3588. const { ctx } = this._processInputParams(input);
  3589. let data = ctx.data;
  3590. if (ctx.parsedType === ZodParsedType.undefined) {
  3591. data = this._def.defaultValue();
  3592. }
  3593. return this._def.innerType._parse({
  3594. data,
  3595. path: ctx.path,
  3596. parent: ctx,
  3597. });
  3598. }
  3599. removeDefault() {
  3600. return this._def.innerType;
  3601. }
  3602. }
  3603. ZodDefault.create = (type, params) => {
  3604. return new ZodDefault({
  3605. innerType: type,
  3606. typeName: exports.ZodFirstPartyTypeKind.ZodDefault,
  3607. defaultValue: typeof params.default === "function"
  3608. ? params.default
  3609. : () => params.default,
  3610. ...processCreateParams(params),
  3611. });
  3612. };
  3613. class ZodCatch extends ZodType {
  3614. _parse(input) {
  3615. const { ctx } = this._processInputParams(input);
  3616. // newCtx is used to not collect issues from inner types in ctx
  3617. const newCtx = {
  3618. ...ctx,
  3619. common: {
  3620. ...ctx.common,
  3621. issues: [],
  3622. },
  3623. };
  3624. const result = this._def.innerType._parse({
  3625. data: newCtx.data,
  3626. path: newCtx.path,
  3627. parent: {
  3628. ...newCtx,
  3629. },
  3630. });
  3631. if (isAsync(result)) {
  3632. return result.then((result) => {
  3633. return {
  3634. status: "valid",
  3635. value: result.status === "valid"
  3636. ? result.value
  3637. : this._def.catchValue({
  3638. get error() {
  3639. return new ZodError(newCtx.common.issues);
  3640. },
  3641. input: newCtx.data,
  3642. }),
  3643. };
  3644. });
  3645. }
  3646. else {
  3647. return {
  3648. status: "valid",
  3649. value: result.status === "valid"
  3650. ? result.value
  3651. : this._def.catchValue({
  3652. get error() {
  3653. return new ZodError(newCtx.common.issues);
  3654. },
  3655. input: newCtx.data,
  3656. }),
  3657. };
  3658. }
  3659. }
  3660. removeCatch() {
  3661. return this._def.innerType;
  3662. }
  3663. }
  3664. ZodCatch.create = (type, params) => {
  3665. return new ZodCatch({
  3666. innerType: type,
  3667. typeName: exports.ZodFirstPartyTypeKind.ZodCatch,
  3668. catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
  3669. ...processCreateParams(params),
  3670. });
  3671. };
  3672. class ZodNaN extends ZodType {
  3673. _parse(input) {
  3674. const parsedType = this._getType(input);
  3675. if (parsedType !== ZodParsedType.nan) {
  3676. const ctx = this._getOrReturnCtx(input);
  3677. addIssueToContext(ctx, {
  3678. code: ZodIssueCode.invalid_type,
  3679. expected: ZodParsedType.nan,
  3680. received: ctx.parsedType,
  3681. });
  3682. return INVALID;
  3683. }
  3684. return { status: "valid", value: input.data };
  3685. }
  3686. }
  3687. ZodNaN.create = (params) => {
  3688. return new ZodNaN({
  3689. typeName: exports.ZodFirstPartyTypeKind.ZodNaN,
  3690. ...processCreateParams(params),
  3691. });
  3692. };
  3693. const BRAND = Symbol("zod_brand");
  3694. class ZodBranded extends ZodType {
  3695. _parse(input) {
  3696. const { ctx } = this._processInputParams(input);
  3697. const data = ctx.data;
  3698. return this._def.type._parse({
  3699. data,
  3700. path: ctx.path,
  3701. parent: ctx,
  3702. });
  3703. }
  3704. unwrap() {
  3705. return this._def.type;
  3706. }
  3707. }
  3708. class ZodPipeline extends ZodType {
  3709. _parse(input) {
  3710. const { status, ctx } = this._processInputParams(input);
  3711. if (ctx.common.async) {
  3712. const handleAsync = async () => {
  3713. const inResult = await this._def.in._parseAsync({
  3714. data: ctx.data,
  3715. path: ctx.path,
  3716. parent: ctx,
  3717. });
  3718. if (inResult.status === "aborted")
  3719. return INVALID;
  3720. if (inResult.status === "dirty") {
  3721. status.dirty();
  3722. return DIRTY(inResult.value);
  3723. }
  3724. else {
  3725. return this._def.out._parseAsync({
  3726. data: inResult.value,
  3727. path: ctx.path,
  3728. parent: ctx,
  3729. });
  3730. }
  3731. };
  3732. return handleAsync();
  3733. }
  3734. else {
  3735. const inResult = this._def.in._parseSync({
  3736. data: ctx.data,
  3737. path: ctx.path,
  3738. parent: ctx,
  3739. });
  3740. if (inResult.status === "aborted")
  3741. return INVALID;
  3742. if (inResult.status === "dirty") {
  3743. status.dirty();
  3744. return {
  3745. status: "dirty",
  3746. value: inResult.value,
  3747. };
  3748. }
  3749. else {
  3750. return this._def.out._parseSync({
  3751. data: inResult.value,
  3752. path: ctx.path,
  3753. parent: ctx,
  3754. });
  3755. }
  3756. }
  3757. }
  3758. static create(a, b) {
  3759. return new ZodPipeline({
  3760. in: a,
  3761. out: b,
  3762. typeName: exports.ZodFirstPartyTypeKind.ZodPipeline,
  3763. });
  3764. }
  3765. }
  3766. class ZodReadonly extends ZodType {
  3767. _parse(input) {
  3768. const result = this._def.innerType._parse(input);
  3769. if (isValid(result)) {
  3770. result.value = Object.freeze(result.value);
  3771. }
  3772. return result;
  3773. }
  3774. }
  3775. ZodReadonly.create = (type, params) => {
  3776. return new ZodReadonly({
  3777. innerType: type,
  3778. typeName: exports.ZodFirstPartyTypeKind.ZodReadonly,
  3779. ...processCreateParams(params),
  3780. });
  3781. };
  3782. const custom = (check, params = {},
  3783. /**
  3784. * @deprecated
  3785. *
  3786. * Pass `fatal` into the params object instead:
  3787. *
  3788. * ```ts
  3789. * z.string().custom((val) => val.length > 5, { fatal: false })
  3790. * ```
  3791. *
  3792. */
  3793. fatal) => {
  3794. if (check)
  3795. return ZodAny.create().superRefine((data, ctx) => {
  3796. var _a, _b;
  3797. if (!check(data)) {
  3798. const p = typeof params === "function"
  3799. ? params(data)
  3800. : typeof params === "string"
  3801. ? { message: params }
  3802. : params;
  3803. const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
  3804. const p2 = typeof p === "string" ? { message: p } : p;
  3805. ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
  3806. }
  3807. });
  3808. return ZodAny.create();
  3809. };
  3810. const late = {
  3811. object: ZodObject.lazycreate,
  3812. };
  3813. exports.ZodFirstPartyTypeKind = void 0;
  3814. (function (ZodFirstPartyTypeKind) {
  3815. ZodFirstPartyTypeKind["ZodString"] = "ZodString";
  3816. ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
  3817. ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
  3818. ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
  3819. ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
  3820. ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
  3821. ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
  3822. ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
  3823. ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
  3824. ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
  3825. ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
  3826. ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
  3827. ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
  3828. ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
  3829. ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
  3830. ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
  3831. ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  3832. ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
  3833. ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
  3834. ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
  3835. ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
  3836. ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
  3837. ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
  3838. ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
  3839. ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
  3840. ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
  3841. ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
  3842. ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
  3843. ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
  3844. ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
  3845. ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
  3846. ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
  3847. ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
  3848. ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
  3849. ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
  3850. ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
  3851. })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
  3852. const instanceOfType = (
  3853. // const instanceOfType = <T extends new (...args: any[]) => any>(
  3854. cls, params = {
  3855. message: `Input not instance of ${cls.name}`,
  3856. }) => custom((data) => data instanceof cls, params);
  3857. const stringType = ZodString.create;
  3858. const numberType = ZodNumber.create;
  3859. const nanType = ZodNaN.create;
  3860. const bigIntType = ZodBigInt.create;
  3861. const booleanType = ZodBoolean.create;
  3862. const dateType = ZodDate.create;
  3863. const symbolType = ZodSymbol.create;
  3864. const undefinedType = ZodUndefined.create;
  3865. const nullType = ZodNull.create;
  3866. const anyType = ZodAny.create;
  3867. const unknownType = ZodUnknown.create;
  3868. const neverType = ZodNever.create;
  3869. const voidType = ZodVoid.create;
  3870. const arrayType = ZodArray.create;
  3871. const objectType = ZodObject.create;
  3872. const strictObjectType = ZodObject.strictCreate;
  3873. const unionType = ZodUnion.create;
  3874. const discriminatedUnionType = ZodDiscriminatedUnion.create;
  3875. const intersectionType = ZodIntersection.create;
  3876. const tupleType = ZodTuple.create;
  3877. const recordType = ZodRecord.create;
  3878. const mapType = ZodMap.create;
  3879. const setType = ZodSet.create;
  3880. const functionType = ZodFunction.create;
  3881. const lazyType = ZodLazy.create;
  3882. const literalType = ZodLiteral.create;
  3883. const enumType = ZodEnum.create;
  3884. const nativeEnumType = ZodNativeEnum.create;
  3885. const promiseType = ZodPromise.create;
  3886. const effectsType = ZodEffects.create;
  3887. const optionalType = ZodOptional.create;
  3888. const nullableType = ZodNullable.create;
  3889. const preprocessType = ZodEffects.createWithPreprocess;
  3890. const pipelineType = ZodPipeline.create;
  3891. const ostring = () => stringType().optional();
  3892. const onumber = () => numberType().optional();
  3893. const oboolean = () => booleanType().optional();
  3894. const coerce = {
  3895. string: ((arg) => ZodString.create({ ...arg, coerce: true })),
  3896. number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
  3897. boolean: ((arg) => ZodBoolean.create({
  3898. ...arg,
  3899. coerce: true,
  3900. })),
  3901. bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
  3902. date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
  3903. };
  3904. const NEVER = INVALID;
  3905. var z = /*#__PURE__*/Object.freeze({
  3906. __proto__: null,
  3907. defaultErrorMap: errorMap,
  3908. setErrorMap: setErrorMap,
  3909. getErrorMap: getErrorMap,
  3910. makeIssue: makeIssue,
  3911. EMPTY_PATH: EMPTY_PATH,
  3912. addIssueToContext: addIssueToContext,
  3913. ParseStatus: ParseStatus,
  3914. INVALID: INVALID,
  3915. DIRTY: DIRTY,
  3916. OK: OK,
  3917. isAborted: isAborted,
  3918. isDirty: isDirty,
  3919. isValid: isValid,
  3920. isAsync: isAsync,
  3921. get util () { return exports.util; },
  3922. get objectUtil () { return exports.objectUtil; },
  3923. ZodParsedType: ZodParsedType,
  3924. getParsedType: getParsedType,
  3925. ZodType: ZodType,
  3926. ZodString: ZodString,
  3927. ZodNumber: ZodNumber,
  3928. ZodBigInt: ZodBigInt,
  3929. ZodBoolean: ZodBoolean,
  3930. ZodDate: ZodDate,
  3931. ZodSymbol: ZodSymbol,
  3932. ZodUndefined: ZodUndefined,
  3933. ZodNull: ZodNull,
  3934. ZodAny: ZodAny,
  3935. ZodUnknown: ZodUnknown,
  3936. ZodNever: ZodNever,
  3937. ZodVoid: ZodVoid,
  3938. ZodArray: ZodArray,
  3939. ZodObject: ZodObject,
  3940. ZodUnion: ZodUnion,
  3941. ZodDiscriminatedUnion: ZodDiscriminatedUnion,
  3942. ZodIntersection: ZodIntersection,
  3943. ZodTuple: ZodTuple,
  3944. ZodRecord: ZodRecord,
  3945. ZodMap: ZodMap,
  3946. ZodSet: ZodSet,
  3947. ZodFunction: ZodFunction,
  3948. ZodLazy: ZodLazy,
  3949. ZodLiteral: ZodLiteral,
  3950. ZodEnum: ZodEnum,
  3951. ZodNativeEnum: ZodNativeEnum,
  3952. ZodPromise: ZodPromise,
  3953. ZodEffects: ZodEffects,
  3954. ZodTransformer: ZodEffects,
  3955. ZodOptional: ZodOptional,
  3956. ZodNullable: ZodNullable,
  3957. ZodDefault: ZodDefault,
  3958. ZodCatch: ZodCatch,
  3959. ZodNaN: ZodNaN,
  3960. BRAND: BRAND,
  3961. ZodBranded: ZodBranded,
  3962. ZodPipeline: ZodPipeline,
  3963. ZodReadonly: ZodReadonly,
  3964. custom: custom,
  3965. Schema: ZodType,
  3966. ZodSchema: ZodType,
  3967. late: late,
  3968. get ZodFirstPartyTypeKind () { return exports.ZodFirstPartyTypeKind; },
  3969. coerce: coerce,
  3970. any: anyType,
  3971. array: arrayType,
  3972. bigint: bigIntType,
  3973. boolean: booleanType,
  3974. date: dateType,
  3975. discriminatedUnion: discriminatedUnionType,
  3976. effect: effectsType,
  3977. 'enum': enumType,
  3978. 'function': functionType,
  3979. 'instanceof': instanceOfType,
  3980. intersection: intersectionType,
  3981. lazy: lazyType,
  3982. literal: literalType,
  3983. map: mapType,
  3984. nan: nanType,
  3985. nativeEnum: nativeEnumType,
  3986. never: neverType,
  3987. 'null': nullType,
  3988. nullable: nullableType,
  3989. number: numberType,
  3990. object: objectType,
  3991. oboolean: oboolean,
  3992. onumber: onumber,
  3993. optional: optionalType,
  3994. ostring: ostring,
  3995. pipeline: pipelineType,
  3996. preprocess: preprocessType,
  3997. promise: promiseType,
  3998. record: recordType,
  3999. set: setType,
  4000. strictObject: strictObjectType,
  4001. string: stringType,
  4002. symbol: symbolType,
  4003. transformer: effectsType,
  4004. tuple: tupleType,
  4005. 'undefined': undefinedType,
  4006. union: unionType,
  4007. unknown: unknownType,
  4008. 'void': voidType,
  4009. NEVER: NEVER,
  4010. ZodIssueCode: ZodIssueCode,
  4011. quotelessJson: quotelessJson,
  4012. ZodError: ZodError
  4013. });
  4014. exports.BRAND = BRAND;
  4015. exports.DIRTY = DIRTY;
  4016. exports.EMPTY_PATH = EMPTY_PATH;
  4017. exports.INVALID = INVALID;
  4018. exports.NEVER = NEVER;
  4019. exports.OK = OK;
  4020. exports.ParseStatus = ParseStatus;
  4021. exports.Schema = ZodType;
  4022. exports.ZodAny = ZodAny;
  4023. exports.ZodArray = ZodArray;
  4024. exports.ZodBigInt = ZodBigInt;
  4025. exports.ZodBoolean = ZodBoolean;
  4026. exports.ZodBranded = ZodBranded;
  4027. exports.ZodCatch = ZodCatch;
  4028. exports.ZodDate = ZodDate;
  4029. exports.ZodDefault = ZodDefault;
  4030. exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion;
  4031. exports.ZodEffects = ZodEffects;
  4032. exports.ZodEnum = ZodEnum;
  4033. exports.ZodError = ZodError;
  4034. exports.ZodFunction = ZodFunction;
  4035. exports.ZodIntersection = ZodIntersection;
  4036. exports.ZodIssueCode = ZodIssueCode;
  4037. exports.ZodLazy = ZodLazy;
  4038. exports.ZodLiteral = ZodLiteral;
  4039. exports.ZodMap = ZodMap;
  4040. exports.ZodNaN = ZodNaN;
  4041. exports.ZodNativeEnum = ZodNativeEnum;
  4042. exports.ZodNever = ZodNever;
  4043. exports.ZodNull = ZodNull;
  4044. exports.ZodNullable = ZodNullable;
  4045. exports.ZodNumber = ZodNumber;
  4046. exports.ZodObject = ZodObject;
  4047. exports.ZodOptional = ZodOptional;
  4048. exports.ZodParsedType = ZodParsedType;
  4049. exports.ZodPipeline = ZodPipeline;
  4050. exports.ZodPromise = ZodPromise;
  4051. exports.ZodReadonly = ZodReadonly;
  4052. exports.ZodRecord = ZodRecord;
  4053. exports.ZodSchema = ZodType;
  4054. exports.ZodSet = ZodSet;
  4055. exports.ZodString = ZodString;
  4056. exports.ZodSymbol = ZodSymbol;
  4057. exports.ZodTransformer = ZodEffects;
  4058. exports.ZodTuple = ZodTuple;
  4059. exports.ZodType = ZodType;
  4060. exports.ZodUndefined = ZodUndefined;
  4061. exports.ZodUnion = ZodUnion;
  4062. exports.ZodUnknown = ZodUnknown;
  4063. exports.ZodVoid = ZodVoid;
  4064. exports.addIssueToContext = addIssueToContext;
  4065. exports.any = anyType;
  4066. exports.array = arrayType;
  4067. exports.bigint = bigIntType;
  4068. exports.boolean = booleanType;
  4069. exports.coerce = coerce;
  4070. exports.custom = custom;
  4071. exports.date = dateType;
  4072. exports["default"] = z;
  4073. exports.defaultErrorMap = errorMap;
  4074. exports.discriminatedUnion = discriminatedUnionType;
  4075. exports.effect = effectsType;
  4076. exports["enum"] = enumType;
  4077. exports["function"] = functionType;
  4078. exports.getErrorMap = getErrorMap;
  4079. exports.getParsedType = getParsedType;
  4080. exports["instanceof"] = instanceOfType;
  4081. exports.intersection = intersectionType;
  4082. exports.isAborted = isAborted;
  4083. exports.isAsync = isAsync;
  4084. exports.isDirty = isDirty;
  4085. exports.isValid = isValid;
  4086. exports.late = late;
  4087. exports.lazy = lazyType;
  4088. exports.literal = literalType;
  4089. exports.makeIssue = makeIssue;
  4090. exports.map = mapType;
  4091. exports.nan = nanType;
  4092. exports.nativeEnum = nativeEnumType;
  4093. exports.never = neverType;
  4094. exports["null"] = nullType;
  4095. exports.nullable = nullableType;
  4096. exports.number = numberType;
  4097. exports.object = objectType;
  4098. exports.oboolean = oboolean;
  4099. exports.onumber = onumber;
  4100. exports.optional = optionalType;
  4101. exports.ostring = ostring;
  4102. exports.pipeline = pipelineType;
  4103. exports.preprocess = preprocessType;
  4104. exports.promise = promiseType;
  4105. exports.quotelessJson = quotelessJson;
  4106. exports.record = recordType;
  4107. exports.set = setType;
  4108. exports.setErrorMap = setErrorMap;
  4109. exports.strictObject = strictObjectType;
  4110. exports.string = stringType;
  4111. exports.symbol = symbolType;
  4112. exports.transformer = effectsType;
  4113. exports.tuple = tupleType;
  4114. exports["undefined"] = undefinedType;
  4115. exports.union = unionType;
  4116. exports.unknown = unknownType;
  4117. exports["void"] = voidType;
  4118. exports.z = z;
  4119. Object.defineProperty(exports, '__esModule', { value: true });
  4120. }));