123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Zod = {}));
- })(this, (function (exports) { 'use strict';
- exports.util = void 0;
- (function (util) {
- util.assertEqual = (val) => val;
- function assertIs(_arg) { }
- util.assertIs = assertIs;
- function assertNever(_x) {
- throw new Error();
- }
- util.assertNever = assertNever;
- util.arrayToEnum = (items) => {
- const obj = {};
- for (const item of items) {
- obj[item] = item;
- }
- return obj;
- };
- util.getValidEnumValues = (obj) => {
- const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
- const filtered = {};
- for (const k of validKeys) {
- filtered[k] = obj[k];
- }
- return util.objectValues(filtered);
- };
- util.objectValues = (obj) => {
- return util.objectKeys(obj).map(function (e) {
- return obj[e];
- });
- };
- util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
- ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
- : (object) => {
- const keys = [];
- for (const key in object) {
- if (Object.prototype.hasOwnProperty.call(object, key)) {
- keys.push(key);
- }
- }
- return keys;
- };
- util.find = (arr, checker) => {
- for (const item of arr) {
- if (checker(item))
- return item;
- }
- return undefined;
- };
- util.isInteger = typeof Number.isInteger === "function"
- ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
- : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
- function joinValues(array, separator = " | ") {
- return array
- .map((val) => (typeof val === "string" ? `'${val}'` : val))
- .join(separator);
- }
- util.joinValues = joinValues;
- util.jsonStringifyReplacer = (_, value) => {
- if (typeof value === "bigint") {
- return value.toString();
- }
- return value;
- };
- })(exports.util || (exports.util = {}));
- exports.objectUtil = void 0;
- (function (objectUtil) {
- objectUtil.mergeShapes = (first, second) => {
- return {
- ...first,
- ...second, // second overwrites first
- };
- };
- })(exports.objectUtil || (exports.objectUtil = {}));
- const ZodParsedType = exports.util.arrayToEnum([
- "string",
- "nan",
- "number",
- "integer",
- "float",
- "boolean",
- "date",
- "bigint",
- "symbol",
- "function",
- "undefined",
- "null",
- "array",
- "object",
- "unknown",
- "promise",
- "void",
- "never",
- "map",
- "set",
- ]);
- const getParsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "undefined":
- return ZodParsedType.undefined;
- case "string":
- return ZodParsedType.string;
- case "number":
- return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
- case "boolean":
- return ZodParsedType.boolean;
- case "function":
- return ZodParsedType.function;
- case "bigint":
- return ZodParsedType.bigint;
- case "symbol":
- return ZodParsedType.symbol;
- case "object":
- if (Array.isArray(data)) {
- return ZodParsedType.array;
- }
- if (data === null) {
- return ZodParsedType.null;
- }
- if (data.then &&
- typeof data.then === "function" &&
- data.catch &&
- typeof data.catch === "function") {
- return ZodParsedType.promise;
- }
- if (typeof Map !== "undefined" && data instanceof Map) {
- return ZodParsedType.map;
- }
- if (typeof Set !== "undefined" && data instanceof Set) {
- return ZodParsedType.set;
- }
- if (typeof Date !== "undefined" && data instanceof Date) {
- return ZodParsedType.date;
- }
- return ZodParsedType.object;
- default:
- return ZodParsedType.unknown;
- }
- };
- const ZodIssueCode = exports.util.arrayToEnum([
- "invalid_type",
- "invalid_literal",
- "custom",
- "invalid_union",
- "invalid_union_discriminator",
- "invalid_enum_value",
- "unrecognized_keys",
- "invalid_arguments",
- "invalid_return_type",
- "invalid_date",
- "invalid_string",
- "too_small",
- "too_big",
- "invalid_intersection_types",
- "not_multiple_of",
- "not_finite",
- ]);
- const quotelessJson = (obj) => {
- const json = JSON.stringify(obj, null, 2);
- return json.replace(/"([^"]+)":/g, "$1:");
- };
- class ZodError extends Error {
- constructor(issues) {
- super();
- this.issues = [];
- this.addIssue = (sub) => {
- this.issues = [...this.issues, sub];
- };
- this.addIssues = (subs = []) => {
- this.issues = [...this.issues, ...subs];
- };
- const actualProto = new.target.prototype;
- if (Object.setPrototypeOf) {
- // eslint-disable-next-line ban/ban
- Object.setPrototypeOf(this, actualProto);
- }
- else {
- this.__proto__ = actualProto;
- }
- this.name = "ZodError";
- this.issues = issues;
- }
- get errors() {
- return this.issues;
- }
- format(_mapper) {
- const mapper = _mapper ||
- function (issue) {
- return issue.message;
- };
- const fieldErrors = { _errors: [] };
- const processError = (error) => {
- for (const issue of error.issues) {
- if (issue.code === "invalid_union") {
- issue.unionErrors.map(processError);
- }
- else if (issue.code === "invalid_return_type") {
- processError(issue.returnTypeError);
- }
- else if (issue.code === "invalid_arguments") {
- processError(issue.argumentsError);
- }
- else if (issue.path.length === 0) {
- fieldErrors._errors.push(mapper(issue));
- }
- else {
- let curr = fieldErrors;
- let i = 0;
- while (i < issue.path.length) {
- const el = issue.path[i];
- const terminal = i === issue.path.length - 1;
- if (!terminal) {
- curr[el] = curr[el] || { _errors: [] };
- // if (typeof el === "string") {
- // curr[el] = curr[el] || { _errors: [] };
- // } else if (typeof el === "number") {
- // const errorArray: any = [];
- // errorArray._errors = [];
- // curr[el] = curr[el] || errorArray;
- // }
- }
- else {
- curr[el] = curr[el] || { _errors: [] };
- curr[el]._errors.push(mapper(issue));
- }
- curr = curr[el];
- i++;
- }
- }
- }
- };
- processError(this);
- return fieldErrors;
- }
- toString() {
- return this.message;
- }
- get message() {
- return JSON.stringify(this.issues, exports.util.jsonStringifyReplacer, 2);
- }
- get isEmpty() {
- return this.issues.length === 0;
- }
- flatten(mapper = (issue) => issue.message) {
- const fieldErrors = {};
- const formErrors = [];
- for (const sub of this.issues) {
- if (sub.path.length > 0) {
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
- fieldErrors[sub.path[0]].push(mapper(sub));
- }
- else {
- formErrors.push(mapper(sub));
- }
- }
- return { formErrors, fieldErrors };
- }
- get formErrors() {
- return this.flatten();
- }
- }
- ZodError.create = (issues) => {
- const error = new ZodError(issues);
- return error;
- };
- const errorMap = (issue, _ctx) => {
- let message;
- switch (issue.code) {
- case ZodIssueCode.invalid_type:
- if (issue.received === ZodParsedType.undefined) {
- message = "Required";
- }
- else {
- message = `Expected ${issue.expected}, received ${issue.received}`;
- }
- break;
- case ZodIssueCode.invalid_literal:
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, exports.util.jsonStringifyReplacer)}`;
- break;
- case ZodIssueCode.unrecognized_keys:
- message = `Unrecognized key(s) in object: ${exports.util.joinValues(issue.keys, ", ")}`;
- break;
- case ZodIssueCode.invalid_union:
- message = `Invalid input`;
- break;
- case ZodIssueCode.invalid_union_discriminator:
- message = `Invalid discriminator value. Expected ${exports.util.joinValues(issue.options)}`;
- break;
- case ZodIssueCode.invalid_enum_value:
- message = `Invalid enum value. Expected ${exports.util.joinValues(issue.options)}, received '${issue.received}'`;
- break;
- case ZodIssueCode.invalid_arguments:
- message = `Invalid function arguments`;
- break;
- case ZodIssueCode.invalid_return_type:
- message = `Invalid function return type`;
- break;
- case ZodIssueCode.invalid_date:
- message = `Invalid date`;
- break;
- case ZodIssueCode.invalid_string:
- if (typeof issue.validation === "object") {
- if ("includes" in issue.validation) {
- message = `Invalid input: must include "${issue.validation.includes}"`;
- if (typeof issue.validation.position === "number") {
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
- }
- }
- else if ("startsWith" in issue.validation) {
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
- }
- else if ("endsWith" in issue.validation) {
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
- }
- else {
- exports.util.assertNever(issue.validation);
- }
- }
- else if (issue.validation !== "regex") {
- message = `Invalid ${issue.validation}`;
- }
- else {
- message = "Invalid";
- }
- break;
- case ZodIssueCode.too_small:
- if (issue.type === "array")
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
- else if (issue.type === "string")
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
- else if (issue.type === "number")
- message = `Number must be ${issue.exact
- ? `exactly equal to `
- : issue.inclusive
- ? `greater than or equal to `
- : `greater than `}${issue.minimum}`;
- else if (issue.type === "date")
- message = `Date must be ${issue.exact
- ? `exactly equal to `
- : issue.inclusive
- ? `greater than or equal to `
- : `greater than `}${new Date(Number(issue.minimum))}`;
- else
- message = "Invalid input";
- break;
- case ZodIssueCode.too_big:
- if (issue.type === "array")
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
- else if (issue.type === "string")
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
- else if (issue.type === "number")
- message = `Number must be ${issue.exact
- ? `exactly`
- : issue.inclusive
- ? `less than or equal to`
- : `less than`} ${issue.maximum}`;
- else if (issue.type === "bigint")
- message = `BigInt must be ${issue.exact
- ? `exactly`
- : issue.inclusive
- ? `less than or equal to`
- : `less than`} ${issue.maximum}`;
- else if (issue.type === "date")
- message = `Date must be ${issue.exact
- ? `exactly`
- : issue.inclusive
- ? `smaller than or equal to`
- : `smaller than`} ${new Date(Number(issue.maximum))}`;
- else
- message = "Invalid input";
- break;
- case ZodIssueCode.custom:
- message = `Invalid input`;
- break;
- case ZodIssueCode.invalid_intersection_types:
- message = `Intersection results could not be merged`;
- break;
- case ZodIssueCode.not_multiple_of:
- message = `Number must be a multiple of ${issue.multipleOf}`;
- break;
- case ZodIssueCode.not_finite:
- message = "Number must be finite";
- break;
- default:
- message = _ctx.defaultError;
- exports.util.assertNever(issue);
- }
- return { message };
- };
- let overrideErrorMap = errorMap;
- function setErrorMap(map) {
- overrideErrorMap = map;
- }
- function getErrorMap() {
- return overrideErrorMap;
- }
- const makeIssue = (params) => {
- const { data, path, errorMaps, issueData } = params;
- const fullPath = [...path, ...(issueData.path || [])];
- const fullIssue = {
- ...issueData,
- path: fullPath,
- };
- let errorMessage = "";
- const maps = errorMaps
- .filter((m) => !!m)
- .slice()
- .reverse();
- for (const map of maps) {
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
- }
- return {
- ...issueData,
- path: fullPath,
- message: issueData.message || errorMessage,
- };
- };
- const EMPTY_PATH = [];
- function addIssueToContext(ctx, issueData) {
- const issue = makeIssue({
- issueData: issueData,
- data: ctx.data,
- path: ctx.path,
- errorMaps: [
- ctx.common.contextualErrorMap,
- ctx.schemaErrorMap,
- getErrorMap(),
- errorMap, // then global default map
- ].filter((x) => !!x),
- });
- ctx.common.issues.push(issue);
- }
- class ParseStatus {
- constructor() {
- this.value = "valid";
- }
- dirty() {
- if (this.value === "valid")
- this.value = "dirty";
- }
- abort() {
- if (this.value !== "aborted")
- this.value = "aborted";
- }
- static mergeArray(status, results) {
- const arrayValue = [];
- for (const s of results) {
- if (s.status === "aborted")
- return INVALID;
- if (s.status === "dirty")
- status.dirty();
- arrayValue.push(s.value);
- }
- return { status: status.value, value: arrayValue };
- }
- static async mergeObjectAsync(status, pairs) {
- const syncPairs = [];
- for (const pair of pairs) {
- syncPairs.push({
- key: await pair.key,
- value: await pair.value,
- });
- }
- return ParseStatus.mergeObjectSync(status, syncPairs);
- }
- static mergeObjectSync(status, pairs) {
- const finalObject = {};
- for (const pair of pairs) {
- const { key, value } = pair;
- if (key.status === "aborted")
- return INVALID;
- if (value.status === "aborted")
- return INVALID;
- if (key.status === "dirty")
- status.dirty();
- if (value.status === "dirty")
- status.dirty();
- if (key.value !== "__proto__" &&
- (typeof value.value !== "undefined" || pair.alwaysSet)) {
- finalObject[key.value] = value.value;
- }
- }
- return { status: status.value, value: finalObject };
- }
- }
- const INVALID = Object.freeze({
- status: "aborted",
- });
- const DIRTY = (value) => ({ status: "dirty", value });
- const OK = (value) => ({ status: "valid", value });
- const isAborted = (x) => x.status === "aborted";
- const isDirty = (x) => x.status === "dirty";
- const isValid = (x) => x.status === "valid";
- const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
- var errorUtil;
- (function (errorUtil) {
- errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
- errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
- })(errorUtil || (errorUtil = {}));
- class ParseInputLazyPath {
- constructor(parent, value, path, key) {
- this._cachedPath = [];
- this.parent = parent;
- this.data = value;
- this._path = path;
- this._key = key;
- }
- get path() {
- if (!this._cachedPath.length) {
- if (this._key instanceof Array) {
- this._cachedPath.push(...this._path, ...this._key);
- }
- else {
- this._cachedPath.push(...this._path, this._key);
- }
- }
- return this._cachedPath;
- }
- }
- const handleResult = (ctx, result) => {
- if (isValid(result)) {
- return { success: true, data: result.value };
- }
- else {
- if (!ctx.common.issues.length) {
- throw new Error("Validation failed but no issues detected.");
- }
- return {
- success: false,
- get error() {
- if (this._error)
- return this._error;
- const error = new ZodError(ctx.common.issues);
- this._error = error;
- return this._error;
- },
- };
- }
- };
- function processCreateParams(params) {
- if (!params)
- return {};
- const { errorMap, invalid_type_error, required_error, description } = params;
- if (errorMap && (invalid_type_error || required_error)) {
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
- }
- if (errorMap)
- return { errorMap: errorMap, description };
- const customMap = (iss, ctx) => {
- if (iss.code !== "invalid_type")
- return { message: ctx.defaultError };
- if (typeof ctx.data === "undefined") {
- return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
- }
- return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
- };
- return { errorMap: customMap, description };
- }
- class ZodType {
- constructor(def) {
- /** Alias of safeParseAsync */
- this.spa = this.safeParseAsync;
- this._def = def;
- this.parse = this.parse.bind(this);
- this.safeParse = this.safeParse.bind(this);
- this.parseAsync = this.parseAsync.bind(this);
- this.safeParseAsync = this.safeParseAsync.bind(this);
- this.spa = this.spa.bind(this);
- this.refine = this.refine.bind(this);
- this.refinement = this.refinement.bind(this);
- this.superRefine = this.superRefine.bind(this);
- this.optional = this.optional.bind(this);
- this.nullable = this.nullable.bind(this);
- this.nullish = this.nullish.bind(this);
- this.array = this.array.bind(this);
- this.promise = this.promise.bind(this);
- this.or = this.or.bind(this);
- this.and = this.and.bind(this);
- this.transform = this.transform.bind(this);
- this.brand = this.brand.bind(this);
- this.default = this.default.bind(this);
- this.catch = this.catch.bind(this);
- this.describe = this.describe.bind(this);
- this.pipe = this.pipe.bind(this);
- this.readonly = this.readonly.bind(this);
- this.isNullable = this.isNullable.bind(this);
- this.isOptional = this.isOptional.bind(this);
- }
- get description() {
- return this._def.description;
- }
- _getType(input) {
- return getParsedType(input.data);
- }
- _getOrReturnCtx(input, ctx) {
- return (ctx || {
- common: input.parent.common,
- data: input.data,
- parsedType: getParsedType(input.data),
- schemaErrorMap: this._def.errorMap,
- path: input.path,
- parent: input.parent,
- });
- }
- _processInputParams(input) {
- return {
- status: new ParseStatus(),
- ctx: {
- common: input.parent.common,
- data: input.data,
- parsedType: getParsedType(input.data),
- schemaErrorMap: this._def.errorMap,
- path: input.path,
- parent: input.parent,
- },
- };
- }
- _parseSync(input) {
- const result = this._parse(input);
- if (isAsync(result)) {
- throw new Error("Synchronous parse encountered promise.");
- }
- return result;
- }
- _parseAsync(input) {
- const result = this._parse(input);
- return Promise.resolve(result);
- }
- parse(data, params) {
- const result = this.safeParse(data, params);
- if (result.success)
- return result.data;
- throw result.error;
- }
- safeParse(data, params) {
- var _a;
- const ctx = {
- common: {
- issues: [],
- async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
- },
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
- schemaErrorMap: this._def.errorMap,
- parent: null,
- data,
- parsedType: getParsedType(data),
- };
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
- return handleResult(ctx, result);
- }
- async parseAsync(data, params) {
- const result = await this.safeParseAsync(data, params);
- if (result.success)
- return result.data;
- throw result.error;
- }
- async safeParseAsync(data, params) {
- const ctx = {
- common: {
- issues: [],
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
- async: true,
- },
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
- schemaErrorMap: this._def.errorMap,
- parent: null,
- data,
- parsedType: getParsedType(data),
- };
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
- const result = await (isAsync(maybeAsyncResult)
- ? maybeAsyncResult
- : Promise.resolve(maybeAsyncResult));
- return handleResult(ctx, result);
- }
- refine(check, message) {
- const getIssueProperties = (val) => {
- if (typeof message === "string" || typeof message === "undefined") {
- return { message };
- }
- else if (typeof message === "function") {
- return message(val);
- }
- else {
- return message;
- }
- };
- return this._refinement((val, ctx) => {
- const result = check(val);
- const setError = () => ctx.addIssue({
- code: ZodIssueCode.custom,
- ...getIssueProperties(val),
- });
- if (typeof Promise !== "undefined" && result instanceof Promise) {
- return result.then((data) => {
- if (!data) {
- setError();
- return false;
- }
- else {
- return true;
- }
- });
- }
- if (!result) {
- setError();
- return false;
- }
- else {
- return true;
- }
- });
- }
- refinement(check, refinementData) {
- return this._refinement((val, ctx) => {
- if (!check(val)) {
- ctx.addIssue(typeof refinementData === "function"
- ? refinementData(val, ctx)
- : refinementData);
- return false;
- }
- else {
- return true;
- }
- });
- }
- _refinement(refinement) {
- return new ZodEffects({
- schema: this,
- typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
- effect: { type: "refinement", refinement },
- });
- }
- superRefine(refinement) {
- return this._refinement(refinement);
- }
- optional() {
- return ZodOptional.create(this, this._def);
- }
- nullable() {
- return ZodNullable.create(this, this._def);
- }
- nullish() {
- return this.nullable().optional();
- }
- array() {
- return ZodArray.create(this, this._def);
- }
- promise() {
- return ZodPromise.create(this, this._def);
- }
- or(option) {
- return ZodUnion.create([this, option], this._def);
- }
- and(incoming) {
- return ZodIntersection.create(this, incoming, this._def);
- }
- transform(transform) {
- return new ZodEffects({
- ...processCreateParams(this._def),
- schema: this,
- typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
- effect: { type: "transform", transform },
- });
- }
- default(def) {
- const defaultValueFunc = typeof def === "function" ? def : () => def;
- return new ZodDefault({
- ...processCreateParams(this._def),
- innerType: this,
- defaultValue: defaultValueFunc,
- typeName: exports.ZodFirstPartyTypeKind.ZodDefault,
- });
- }
- brand() {
- return new ZodBranded({
- typeName: exports.ZodFirstPartyTypeKind.ZodBranded,
- type: this,
- ...processCreateParams(this._def),
- });
- }
- catch(def) {
- const catchValueFunc = typeof def === "function" ? def : () => def;
- return new ZodCatch({
- ...processCreateParams(this._def),
- innerType: this,
- catchValue: catchValueFunc,
- typeName: exports.ZodFirstPartyTypeKind.ZodCatch,
- });
- }
- describe(description) {
- const This = this.constructor;
- return new This({
- ...this._def,
- description,
- });
- }
- pipe(target) {
- return ZodPipeline.create(this, target);
- }
- readonly() {
- return ZodReadonly.create(this);
- }
- isOptional() {
- return this.safeParse(undefined).success;
- }
- isNullable() {
- return this.safeParse(null).success;
- }
- }
- const cuidRegex = /^c[^\s-]{8,}$/i;
- const cuid2Regex = /^[a-z][a-z0-9]*$/;
- const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
- // const uuidRegex =
- // /^([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;
- 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;
- // from https://stackoverflow.com/a/46181/1550155
- // old version: too slow, didn't support unicode
- // 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;
- //old email regex
- // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
- // eslint-disable-next-line
- // const emailRegex =
- // /^(([^<>()[\]\\.,;:\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,})+))$/;
- // const emailRegex =
- // /^[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])?)*$/;
- // const emailRegex =
- // /^(?:[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;
- const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
- // const emailRegex =
- // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
- // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
- const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
- let emojiRegex;
- 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}))$/;
- 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})))$/;
- // Adapted from https://stackoverflow.com/a/3143231
- const datetimeRegex = (args) => {
- if (args.precision) {
- if (args.offset) {
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
- }
- else {
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
- }
- }
- else if (args.precision === 0) {
- if (args.offset) {
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
- }
- else {
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
- }
- }
- else {
- if (args.offset) {
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
- }
- else {
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
- }
- }
- };
- function isValidIP(ip, version) {
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
- return true;
- }
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
- return true;
- }
- return false;
- }
- class ZodString extends ZodType {
- _parse(input) {
- if (this._def.coerce) {
- input.data = String(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.string) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.string,
- received: ctx.parsedType,
- }
- //
- );
- return INVALID;
- }
- const status = new ParseStatus();
- let ctx = undefined;
- for (const check of this._def.checks) {
- if (check.kind === "min") {
- if (input.data.length < check.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: check.value,
- type: "string",
- inclusive: true,
- exact: false,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "max") {
- if (input.data.length > check.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: check.value,
- type: "string",
- inclusive: true,
- exact: false,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "length") {
- const tooBig = input.data.length > check.value;
- const tooSmall = input.data.length < check.value;
- if (tooBig || tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- if (tooBig) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: check.value,
- type: "string",
- inclusive: true,
- exact: true,
- message: check.message,
- });
- }
- else if (tooSmall) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: check.value,
- type: "string",
- inclusive: true,
- exact: true,
- message: check.message,
- });
- }
- status.dirty();
- }
- }
- else if (check.kind === "email") {
- if (!emailRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "email",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "emoji") {
- if (!emojiRegex) {
- emojiRegex = new RegExp(_emojiRegex, "u");
- }
- if (!emojiRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "emoji",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "uuid") {
- if (!uuidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "uuid",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "cuid") {
- if (!cuidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "cuid",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "cuid2") {
- if (!cuid2Regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "cuid2",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "ulid") {
- if (!ulidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "ulid",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "url") {
- try {
- new URL(input.data);
- }
- catch (_a) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "url",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "regex") {
- check.regex.lastIndex = 0;
- const testResult = check.regex.test(input.data);
- if (!testResult) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "regex",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "trim") {
- input.data = input.data.trim();
- }
- else if (check.kind === "includes") {
- if (!input.data.includes(check.value, check.position)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: { includes: check.value, position: check.position },
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "toLowerCase") {
- input.data = input.data.toLowerCase();
- }
- else if (check.kind === "toUpperCase") {
- input.data = input.data.toUpperCase();
- }
- else if (check.kind === "startsWith") {
- if (!input.data.startsWith(check.value)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: { startsWith: check.value },
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "endsWith") {
- if (!input.data.endsWith(check.value)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: { endsWith: check.value },
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "datetime") {
- const regex = datetimeRegex(check);
- if (!regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: "datetime",
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "ip") {
- if (!isValidIP(input.data, check.version)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "ip",
- code: ZodIssueCode.invalid_string,
- message: check.message,
- });
- status.dirty();
- }
- }
- else {
- exports.util.assertNever(check);
- }
- }
- return { status: status.value, value: input.data };
- }
- _regex(regex, validation, message) {
- return this.refinement((data) => regex.test(data), {
- validation,
- code: ZodIssueCode.invalid_string,
- ...errorUtil.errToObj(message),
- });
- }
- _addCheck(check) {
- return new ZodString({
- ...this._def,
- checks: [...this._def.checks, check],
- });
- }
- email(message) {
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
- }
- url(message) {
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
- }
- emoji(message) {
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
- }
- uuid(message) {
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
- }
- cuid(message) {
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
- }
- cuid2(message) {
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
- }
- ulid(message) {
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
- }
- ip(options) {
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
- }
- datetime(options) {
- var _a;
- if (typeof options === "string") {
- return this._addCheck({
- kind: "datetime",
- precision: null,
- offset: false,
- message: options,
- });
- }
- return this._addCheck({
- kind: "datetime",
- precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
- offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
- ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
- });
- }
- regex(regex, message) {
- return this._addCheck({
- kind: "regex",
- regex: regex,
- ...errorUtil.errToObj(message),
- });
- }
- includes(value, options) {
- return this._addCheck({
- kind: "includes",
- value: value,
- position: options === null || options === void 0 ? void 0 : options.position,
- ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
- });
- }
- startsWith(value, message) {
- return this._addCheck({
- kind: "startsWith",
- value: value,
- ...errorUtil.errToObj(message),
- });
- }
- endsWith(value, message) {
- return this._addCheck({
- kind: "endsWith",
- value: value,
- ...errorUtil.errToObj(message),
- });
- }
- min(minLength, message) {
- return this._addCheck({
- kind: "min",
- value: minLength,
- ...errorUtil.errToObj(message),
- });
- }
- max(maxLength, message) {
- return this._addCheck({
- kind: "max",
- value: maxLength,
- ...errorUtil.errToObj(message),
- });
- }
- length(len, message) {
- return this._addCheck({
- kind: "length",
- value: len,
- ...errorUtil.errToObj(message),
- });
- }
- /**
- * @deprecated Use z.string().min(1) instead.
- * @see {@link ZodString.min}
- */
- nonempty(message) {
- return this.min(1, errorUtil.errToObj(message));
- }
- trim() {
- return new ZodString({
- ...this._def,
- checks: [...this._def.checks, { kind: "trim" }],
- });
- }
- toLowerCase() {
- return new ZodString({
- ...this._def,
- checks: [...this._def.checks, { kind: "toLowerCase" }],
- });
- }
- toUpperCase() {
- return new ZodString({
- ...this._def,
- checks: [...this._def.checks, { kind: "toUpperCase" }],
- });
- }
- get isDatetime() {
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
- }
- get isEmail() {
- return !!this._def.checks.find((ch) => ch.kind === "email");
- }
- get isURL() {
- return !!this._def.checks.find((ch) => ch.kind === "url");
- }
- get isEmoji() {
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
- }
- get isUUID() {
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
- }
- get isCUID() {
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
- }
- get isCUID2() {
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
- }
- get isULID() {
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
- }
- get isIP() {
- return !!this._def.checks.find((ch) => ch.kind === "ip");
- }
- get minLength() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxLength() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- }
- ZodString.create = (params) => {
- var _a;
- return new ZodString({
- checks: [],
- typeName: exports.ZodFirstPartyTypeKind.ZodString,
- coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
- ...processCreateParams(params),
- });
- };
- // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
- function floatSafeRemainder(val, step) {
- const valDecCount = (val.toString().split(".")[1] || "").length;
- const stepDecCount = (step.toString().split(".")[1] || "").length;
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
- const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
- const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
- return (valInt % stepInt) / Math.pow(10, decCount);
- }
- class ZodNumber extends ZodType {
- constructor() {
- super(...arguments);
- this.min = this.gte;
- this.max = this.lte;
- this.step = this.multipleOf;
- }
- _parse(input) {
- if (this._def.coerce) {
- input.data = Number(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.number) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.number,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- let ctx = undefined;
- const status = new ParseStatus();
- for (const check of this._def.checks) {
- if (check.kind === "int") {
- if (!exports.util.isInteger(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: "integer",
- received: "float",
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "min") {
- const tooSmall = check.inclusive
- ? input.data < check.value
- : input.data <= check.value;
- if (tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: check.value,
- type: "number",
- inclusive: check.inclusive,
- exact: false,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "max") {
- const tooBig = check.inclusive
- ? input.data > check.value
- : input.data >= check.value;
- if (tooBig) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: check.value,
- type: "number",
- inclusive: check.inclusive,
- exact: false,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "multipleOf") {
- if (floatSafeRemainder(input.data, check.value) !== 0) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.not_multiple_of,
- multipleOf: check.value,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "finite") {
- if (!Number.isFinite(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.not_finite,
- message: check.message,
- });
- status.dirty();
- }
- }
- else {
- exports.util.assertNever(check);
- }
- }
- return { status: status.value, value: input.data };
- }
- gte(value, message) {
- return this.setLimit("min", value, true, errorUtil.toString(message));
- }
- gt(value, message) {
- return this.setLimit("min", value, false, errorUtil.toString(message));
- }
- lte(value, message) {
- return this.setLimit("max", value, true, errorUtil.toString(message));
- }
- lt(value, message) {
- return this.setLimit("max", value, false, errorUtil.toString(message));
- }
- setLimit(kind, value, inclusive, message) {
- return new ZodNumber({
- ...this._def,
- checks: [
- ...this._def.checks,
- {
- kind,
- value,
- inclusive,
- message: errorUtil.toString(message),
- },
- ],
- });
- }
- _addCheck(check) {
- return new ZodNumber({
- ...this._def,
- checks: [...this._def.checks, check],
- });
- }
- int(message) {
- return this._addCheck({
- kind: "int",
- message: errorUtil.toString(message),
- });
- }
- positive(message) {
- return this._addCheck({
- kind: "min",
- value: 0,
- inclusive: false,
- message: errorUtil.toString(message),
- });
- }
- negative(message) {
- return this._addCheck({
- kind: "max",
- value: 0,
- inclusive: false,
- message: errorUtil.toString(message),
- });
- }
- nonpositive(message) {
- return this._addCheck({
- kind: "max",
- value: 0,
- inclusive: true,
- message: errorUtil.toString(message),
- });
- }
- nonnegative(message) {
- return this._addCheck({
- kind: "min",
- value: 0,
- inclusive: true,
- message: errorUtil.toString(message),
- });
- }
- multipleOf(value, message) {
- return this._addCheck({
- kind: "multipleOf",
- value: value,
- message: errorUtil.toString(message),
- });
- }
- finite(message) {
- return this._addCheck({
- kind: "finite",
- message: errorUtil.toString(message),
- });
- }
- safe(message) {
- return this._addCheck({
- kind: "min",
- inclusive: true,
- value: Number.MIN_SAFE_INTEGER,
- message: errorUtil.toString(message),
- })._addCheck({
- kind: "max",
- inclusive: true,
- value: Number.MAX_SAFE_INTEGER,
- message: errorUtil.toString(message),
- });
- }
- get minValue() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxValue() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- get isInt() {
- return !!this._def.checks.find((ch) => ch.kind === "int" ||
- (ch.kind === "multipleOf" && exports.util.isInteger(ch.value)));
- }
- get isFinite() {
- let max = null, min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "finite" ||
- ch.kind === "int" ||
- ch.kind === "multipleOf") {
- return true;
- }
- else if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- else if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return Number.isFinite(min) && Number.isFinite(max);
- }
- }
- ZodNumber.create = (params) => {
- return new ZodNumber({
- checks: [],
- typeName: exports.ZodFirstPartyTypeKind.ZodNumber,
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
- ...processCreateParams(params),
- });
- };
- class ZodBigInt extends ZodType {
- constructor() {
- super(...arguments);
- this.min = this.gte;
- this.max = this.lte;
- }
- _parse(input) {
- if (this._def.coerce) {
- input.data = BigInt(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.bigint) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.bigint,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- let ctx = undefined;
- const status = new ParseStatus();
- for (const check of this._def.checks) {
- if (check.kind === "min") {
- const tooSmall = check.inclusive
- ? input.data < check.value
- : input.data <= check.value;
- if (tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- type: "bigint",
- minimum: check.value,
- inclusive: check.inclusive,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "max") {
- const tooBig = check.inclusive
- ? input.data > check.value
- : input.data >= check.value;
- if (tooBig) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- type: "bigint",
- maximum: check.value,
- inclusive: check.inclusive,
- message: check.message,
- });
- status.dirty();
- }
- }
- else if (check.kind === "multipleOf") {
- if (input.data % check.value !== BigInt(0)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.not_multiple_of,
- multipleOf: check.value,
- message: check.message,
- });
- status.dirty();
- }
- }
- else {
- exports.util.assertNever(check);
- }
- }
- return { status: status.value, value: input.data };
- }
- gte(value, message) {
- return this.setLimit("min", value, true, errorUtil.toString(message));
- }
- gt(value, message) {
- return this.setLimit("min", value, false, errorUtil.toString(message));
- }
- lte(value, message) {
- return this.setLimit("max", value, true, errorUtil.toString(message));
- }
- lt(value, message) {
- return this.setLimit("max", value, false, errorUtil.toString(message));
- }
- setLimit(kind, value, inclusive, message) {
- return new ZodBigInt({
- ...this._def,
- checks: [
- ...this._def.checks,
- {
- kind,
- value,
- inclusive,
- message: errorUtil.toString(message),
- },
- ],
- });
- }
- _addCheck(check) {
- return new ZodBigInt({
- ...this._def,
- checks: [...this._def.checks, check],
- });
- }
- positive(message) {
- return this._addCheck({
- kind: "min",
- value: BigInt(0),
- inclusive: false,
- message: errorUtil.toString(message),
- });
- }
- negative(message) {
- return this._addCheck({
- kind: "max",
- value: BigInt(0),
- inclusive: false,
- message: errorUtil.toString(message),
- });
- }
- nonpositive(message) {
- return this._addCheck({
- kind: "max",
- value: BigInt(0),
- inclusive: true,
- message: errorUtil.toString(message),
- });
- }
- nonnegative(message) {
- return this._addCheck({
- kind: "min",
- value: BigInt(0),
- inclusive: true,
- message: errorUtil.toString(message),
- });
- }
- multipleOf(value, message) {
- return this._addCheck({
- kind: "multipleOf",
- value,
- message: errorUtil.toString(message),
- });
- }
- get minValue() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxValue() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- }
- ZodBigInt.create = (params) => {
- var _a;
- return new ZodBigInt({
- checks: [],
- typeName: exports.ZodFirstPartyTypeKind.ZodBigInt,
- coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
- ...processCreateParams(params),
- });
- };
- class ZodBoolean extends ZodType {
- _parse(input) {
- if (this._def.coerce) {
- input.data = Boolean(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.boolean) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.boolean,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- return OK(input.data);
- }
- }
- ZodBoolean.create = (params) => {
- return new ZodBoolean({
- typeName: exports.ZodFirstPartyTypeKind.ZodBoolean,
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
- ...processCreateParams(params),
- });
- };
- class ZodDate extends ZodType {
- _parse(input) {
- if (this._def.coerce) {
- input.data = new Date(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.date) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.date,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- if (isNaN(input.data.getTime())) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_date,
- });
- return INVALID;
- }
- const status = new ParseStatus();
- let ctx = undefined;
- for (const check of this._def.checks) {
- if (check.kind === "min") {
- if (input.data.getTime() < check.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- message: check.message,
- inclusive: true,
- exact: false,
- minimum: check.value,
- type: "date",
- });
- status.dirty();
- }
- }
- else if (check.kind === "max") {
- if (input.data.getTime() > check.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- message: check.message,
- inclusive: true,
- exact: false,
- maximum: check.value,
- type: "date",
- });
- status.dirty();
- }
- }
- else {
- exports.util.assertNever(check);
- }
- }
- return {
- status: status.value,
- value: new Date(input.data.getTime()),
- };
- }
- _addCheck(check) {
- return new ZodDate({
- ...this._def,
- checks: [...this._def.checks, check],
- });
- }
- min(minDate, message) {
- return this._addCheck({
- kind: "min",
- value: minDate.getTime(),
- message: errorUtil.toString(message),
- });
- }
- max(maxDate, message) {
- return this._addCheck({
- kind: "max",
- value: maxDate.getTime(),
- message: errorUtil.toString(message),
- });
- }
- get minDate() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min != null ? new Date(min) : null;
- }
- get maxDate() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max != null ? new Date(max) : null;
- }
- }
- ZodDate.create = (params) => {
- return new ZodDate({
- checks: [],
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
- typeName: exports.ZodFirstPartyTypeKind.ZodDate,
- ...processCreateParams(params),
- });
- };
- class ZodSymbol extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.symbol) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.symbol,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- return OK(input.data);
- }
- }
- ZodSymbol.create = (params) => {
- return new ZodSymbol({
- typeName: exports.ZodFirstPartyTypeKind.ZodSymbol,
- ...processCreateParams(params),
- });
- };
- class ZodUndefined extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.undefined) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.undefined,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- return OK(input.data);
- }
- }
- ZodUndefined.create = (params) => {
- return new ZodUndefined({
- typeName: exports.ZodFirstPartyTypeKind.ZodUndefined,
- ...processCreateParams(params),
- });
- };
- class ZodNull extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.null) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.null,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- return OK(input.data);
- }
- }
- ZodNull.create = (params) => {
- return new ZodNull({
- typeName: exports.ZodFirstPartyTypeKind.ZodNull,
- ...processCreateParams(params),
- });
- };
- class ZodAny extends ZodType {
- constructor() {
- super(...arguments);
- // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
- this._any = true;
- }
- _parse(input) {
- return OK(input.data);
- }
- }
- ZodAny.create = (params) => {
- return new ZodAny({
- typeName: exports.ZodFirstPartyTypeKind.ZodAny,
- ...processCreateParams(params),
- });
- };
- class ZodUnknown extends ZodType {
- constructor() {
- super(...arguments);
- // required
- this._unknown = true;
- }
- _parse(input) {
- return OK(input.data);
- }
- }
- ZodUnknown.create = (params) => {
- return new ZodUnknown({
- typeName: exports.ZodFirstPartyTypeKind.ZodUnknown,
- ...processCreateParams(params),
- });
- };
- class ZodNever extends ZodType {
- _parse(input) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.never,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- }
- ZodNever.create = (params) => {
- return new ZodNever({
- typeName: exports.ZodFirstPartyTypeKind.ZodNever,
- ...processCreateParams(params),
- });
- };
- class ZodVoid extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.undefined) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.void,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- return OK(input.data);
- }
- }
- ZodVoid.create = (params) => {
- return new ZodVoid({
- typeName: exports.ZodFirstPartyTypeKind.ZodVoid,
- ...processCreateParams(params),
- });
- };
- class ZodArray extends ZodType {
- _parse(input) {
- const { ctx, status } = this._processInputParams(input);
- const def = this._def;
- if (ctx.parsedType !== ZodParsedType.array) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.array,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- if (def.exactLength !== null) {
- const tooBig = ctx.data.length > def.exactLength.value;
- const tooSmall = ctx.data.length < def.exactLength.value;
- if (tooBig || tooSmall) {
- addIssueToContext(ctx, {
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
- minimum: (tooSmall ? def.exactLength.value : undefined),
- maximum: (tooBig ? def.exactLength.value : undefined),
- type: "array",
- inclusive: true,
- exact: true,
- message: def.exactLength.message,
- });
- status.dirty();
- }
- }
- if (def.minLength !== null) {
- if (ctx.data.length < def.minLength.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: def.minLength.value,
- type: "array",
- inclusive: true,
- exact: false,
- message: def.minLength.message,
- });
- status.dirty();
- }
- }
- if (def.maxLength !== null) {
- if (ctx.data.length > def.maxLength.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: def.maxLength.value,
- type: "array",
- inclusive: true,
- exact: false,
- message: def.maxLength.message,
- });
- status.dirty();
- }
- }
- if (ctx.common.async) {
- return Promise.all([...ctx.data].map((item, i) => {
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
- })).then((result) => {
- return ParseStatus.mergeArray(status, result);
- });
- }
- const result = [...ctx.data].map((item, i) => {
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
- });
- return ParseStatus.mergeArray(status, result);
- }
- get element() {
- return this._def.type;
- }
- min(minLength, message) {
- return new ZodArray({
- ...this._def,
- minLength: { value: minLength, message: errorUtil.toString(message) },
- });
- }
- max(maxLength, message) {
- return new ZodArray({
- ...this._def,
- maxLength: { value: maxLength, message: errorUtil.toString(message) },
- });
- }
- length(len, message) {
- return new ZodArray({
- ...this._def,
- exactLength: { value: len, message: errorUtil.toString(message) },
- });
- }
- nonempty(message) {
- return this.min(1, message);
- }
- }
- ZodArray.create = (schema, params) => {
- return new ZodArray({
- type: schema,
- minLength: null,
- maxLength: null,
- exactLength: null,
- typeName: exports.ZodFirstPartyTypeKind.ZodArray,
- ...processCreateParams(params),
- });
- };
- function deepPartialify(schema) {
- if (schema instanceof ZodObject) {
- const newShape = {};
- for (const key in schema.shape) {
- const fieldSchema = schema.shape[key];
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
- }
- return new ZodObject({
- ...schema._def,
- shape: () => newShape,
- });
- }
- else if (schema instanceof ZodArray) {
- return new ZodArray({
- ...schema._def,
- type: deepPartialify(schema.element),
- });
- }
- else if (schema instanceof ZodOptional) {
- return ZodOptional.create(deepPartialify(schema.unwrap()));
- }
- else if (schema instanceof ZodNullable) {
- return ZodNullable.create(deepPartialify(schema.unwrap()));
- }
- else if (schema instanceof ZodTuple) {
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
- }
- else {
- return schema;
- }
- }
- class ZodObject extends ZodType {
- constructor() {
- super(...arguments);
- this._cached = null;
- /**
- * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
- * If you want to pass through unknown properties, use `.passthrough()` instead.
- */
- this.nonstrict = this.passthrough;
- // extend<
- // Augmentation extends ZodRawShape,
- // NewOutput extends util.flatten<{
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
- // ? Augmentation[k]["_output"]
- // : k extends keyof Output
- // ? Output[k]
- // : never;
- // }>,
- // NewInput extends util.flatten<{
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
- // ? Augmentation[k]["_input"]
- // : k extends keyof Input
- // ? Input[k]
- // : never;
- // }>
- // >(
- // augmentation: Augmentation
- // ): ZodObject<
- // extendShape<T, Augmentation>,
- // UnknownKeys,
- // Catchall,
- // NewOutput,
- // NewInput
- // > {
- // return new ZodObject({
- // ...this._def,
- // shape: () => ({
- // ...this._def.shape(),
- // ...augmentation,
- // }),
- // }) as any;
- // }
- /**
- * @deprecated Use `.extend` instead
- * */
- this.augment = this.extend;
- }
- _getCached() {
- if (this._cached !== null)
- return this._cached;
- const shape = this._def.shape();
- const keys = exports.util.objectKeys(shape);
- return (this._cached = { shape, keys });
- }
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.object) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.object,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- const { status, ctx } = this._processInputParams(input);
- const { shape, keys: shapeKeys } = this._getCached();
- const extraKeys = [];
- if (!(this._def.catchall instanceof ZodNever &&
- this._def.unknownKeys === "strip")) {
- for (const key in ctx.data) {
- if (!shapeKeys.includes(key)) {
- extraKeys.push(key);
- }
- }
- }
- const pairs = [];
- for (const key of shapeKeys) {
- const keyValidator = shape[key];
- const value = ctx.data[key];
- pairs.push({
- key: { status: "valid", value: key },
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
- alwaysSet: key in ctx.data,
- });
- }
- if (this._def.catchall instanceof ZodNever) {
- const unknownKeys = this._def.unknownKeys;
- if (unknownKeys === "passthrough") {
- for (const key of extraKeys) {
- pairs.push({
- key: { status: "valid", value: key },
- value: { status: "valid", value: ctx.data[key] },
- });
- }
- }
- else if (unknownKeys === "strict") {
- if (extraKeys.length > 0) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.unrecognized_keys,
- keys: extraKeys,
- });
- status.dirty();
- }
- }
- else if (unknownKeys === "strip") ;
- else {
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
- }
- }
- else {
- // run catchall validation
- const catchall = this._def.catchall;
- for (const key of extraKeys) {
- const value = ctx.data[key];
- pairs.push({
- key: { status: "valid", value: key },
- value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
- ),
- alwaysSet: key in ctx.data,
- });
- }
- }
- if (ctx.common.async) {
- return Promise.resolve()
- .then(async () => {
- const syncPairs = [];
- for (const pair of pairs) {
- const key = await pair.key;
- syncPairs.push({
- key,
- value: await pair.value,
- alwaysSet: pair.alwaysSet,
- });
- }
- return syncPairs;
- })
- .then((syncPairs) => {
- return ParseStatus.mergeObjectSync(status, syncPairs);
- });
- }
- else {
- return ParseStatus.mergeObjectSync(status, pairs);
- }
- }
- get shape() {
- return this._def.shape();
- }
- strict(message) {
- errorUtil.errToObj;
- return new ZodObject({
- ...this._def,
- unknownKeys: "strict",
- ...(message !== undefined
- ? {
- errorMap: (issue, ctx) => {
- var _a, _b, _c, _d;
- 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;
- if (issue.code === "unrecognized_keys")
- return {
- message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
- };
- return {
- message: defaultError,
- };
- },
- }
- : {}),
- });
- }
- strip() {
- return new ZodObject({
- ...this._def,
- unknownKeys: "strip",
- });
- }
- passthrough() {
- return new ZodObject({
- ...this._def,
- unknownKeys: "passthrough",
- });
- }
- // const AugmentFactory =
- // <Def extends ZodObjectDef>(def: Def) =>
- // <Augmentation extends ZodRawShape>(
- // augmentation: Augmentation
- // ): ZodObject<
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
- // Def["unknownKeys"],
- // Def["catchall"]
- // > => {
- // return new ZodObject({
- // ...def,
- // shape: () => ({
- // ...def.shape(),
- // ...augmentation,
- // }),
- // }) as any;
- // };
- extend(augmentation) {
- return new ZodObject({
- ...this._def,
- shape: () => ({
- ...this._def.shape(),
- ...augmentation,
- }),
- });
- }
- /**
- * Prior to zod@1.0.12 there was a bug in the
- * inferred type of merged objects. Please
- * upgrade if you are experiencing issues.
- */
- merge(merging) {
- const merged = new ZodObject({
- unknownKeys: merging._def.unknownKeys,
- catchall: merging._def.catchall,
- shape: () => ({
- ...this._def.shape(),
- ...merging._def.shape(),
- }),
- typeName: exports.ZodFirstPartyTypeKind.ZodObject,
- });
- return merged;
- }
- // merge<
- // Incoming extends AnyZodObject,
- // Augmentation extends Incoming["shape"],
- // NewOutput extends {
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
- // ? Augmentation[k]["_output"]
- // : k extends keyof Output
- // ? Output[k]
- // : never;
- // },
- // NewInput extends {
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
- // ? Augmentation[k]["_input"]
- // : k extends keyof Input
- // ? Input[k]
- // : never;
- // }
- // >(
- // merging: Incoming
- // ): ZodObject<
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
- // Incoming["_def"]["unknownKeys"],
- // Incoming["_def"]["catchall"],
- // NewOutput,
- // NewInput
- // > {
- // const merged: any = new ZodObject({
- // unknownKeys: merging._def.unknownKeys,
- // catchall: merging._def.catchall,
- // shape: () =>
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
- // typeName: ZodFirstPartyTypeKind.ZodObject,
- // }) as any;
- // return merged;
- // }
- setKey(key, schema) {
- return this.augment({ [key]: schema });
- }
- // merge<Incoming extends AnyZodObject>(
- // merging: Incoming
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
- // ZodObject<
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
- // Incoming["_def"]["unknownKeys"],
- // Incoming["_def"]["catchall"]
- // > {
- // // const mergedShape = objectUtil.mergeShapes(
- // // this._def.shape(),
- // // merging._def.shape()
- // // );
- // const merged: any = new ZodObject({
- // unknownKeys: merging._def.unknownKeys,
- // catchall: merging._def.catchall,
- // shape: () =>
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
- // typeName: ZodFirstPartyTypeKind.ZodObject,
- // }) as any;
- // return merged;
- // }
- catchall(index) {
- return new ZodObject({
- ...this._def,
- catchall: index,
- });
- }
- pick(mask) {
- const shape = {};
- exports.util.objectKeys(mask).forEach((key) => {
- if (mask[key] && this.shape[key]) {
- shape[key] = this.shape[key];
- }
- });
- return new ZodObject({
- ...this._def,
- shape: () => shape,
- });
- }
- omit(mask) {
- const shape = {};
- exports.util.objectKeys(this.shape).forEach((key) => {
- if (!mask[key]) {
- shape[key] = this.shape[key];
- }
- });
- return new ZodObject({
- ...this._def,
- shape: () => shape,
- });
- }
- /**
- * @deprecated
- */
- deepPartial() {
- return deepPartialify(this);
- }
- partial(mask) {
- const newShape = {};
- exports.util.objectKeys(this.shape).forEach((key) => {
- const fieldSchema = this.shape[key];
- if (mask && !mask[key]) {
- newShape[key] = fieldSchema;
- }
- else {
- newShape[key] = fieldSchema.optional();
- }
- });
- return new ZodObject({
- ...this._def,
- shape: () => newShape,
- });
- }
- required(mask) {
- const newShape = {};
- exports.util.objectKeys(this.shape).forEach((key) => {
- if (mask && !mask[key]) {
- newShape[key] = this.shape[key];
- }
- else {
- const fieldSchema = this.shape[key];
- let newField = fieldSchema;
- while (newField instanceof ZodOptional) {
- newField = newField._def.innerType;
- }
- newShape[key] = newField;
- }
- });
- return new ZodObject({
- ...this._def,
- shape: () => newShape,
- });
- }
- keyof() {
- return createZodEnum(exports.util.objectKeys(this.shape));
- }
- }
- ZodObject.create = (shape, params) => {
- return new ZodObject({
- shape: () => shape,
- unknownKeys: "strip",
- catchall: ZodNever.create(),
- typeName: exports.ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params),
- });
- };
- ZodObject.strictCreate = (shape, params) => {
- return new ZodObject({
- shape: () => shape,
- unknownKeys: "strict",
- catchall: ZodNever.create(),
- typeName: exports.ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params),
- });
- };
- ZodObject.lazycreate = (shape, params) => {
- return new ZodObject({
- shape,
- unknownKeys: "strip",
- catchall: ZodNever.create(),
- typeName: exports.ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params),
- });
- };
- class ZodUnion extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const options = this._def.options;
- function handleResults(results) {
- // return first issue-free validation if it exists
- for (const result of results) {
- if (result.result.status === "valid") {
- return result.result;
- }
- }
- for (const result of results) {
- if (result.result.status === "dirty") {
- // add issues from dirty option
- ctx.common.issues.push(...result.ctx.common.issues);
- return result.result;
- }
- }
- // return invalid
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_union,
- unionErrors,
- });
- return INVALID;
- }
- if (ctx.common.async) {
- return Promise.all(options.map(async (option) => {
- const childCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: [],
- },
- parent: null,
- };
- return {
- result: await option._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: childCtx,
- }),
- ctx: childCtx,
- };
- })).then(handleResults);
- }
- else {
- let dirty = undefined;
- const issues = [];
- for (const option of options) {
- const childCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: [],
- },
- parent: null,
- };
- const result = option._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: childCtx,
- });
- if (result.status === "valid") {
- return result;
- }
- else if (result.status === "dirty" && !dirty) {
- dirty = { result, ctx: childCtx };
- }
- if (childCtx.common.issues.length) {
- issues.push(childCtx.common.issues);
- }
- }
- if (dirty) {
- ctx.common.issues.push(...dirty.ctx.common.issues);
- return dirty.result;
- }
- const unionErrors = issues.map((issues) => new ZodError(issues));
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_union,
- unionErrors,
- });
- return INVALID;
- }
- }
- get options() {
- return this._def.options;
- }
- }
- ZodUnion.create = (types, params) => {
- return new ZodUnion({
- options: types,
- typeName: exports.ZodFirstPartyTypeKind.ZodUnion,
- ...processCreateParams(params),
- });
- };
- /////////////////////////////////////////////////////
- /////////////////////////////////////////////////////
- ////////// //////////
- ////////// ZodDiscriminatedUnion //////////
- ////////// //////////
- /////////////////////////////////////////////////////
- /////////////////////////////////////////////////////
- const getDiscriminator = (type) => {
- if (type instanceof ZodLazy) {
- return getDiscriminator(type.schema);
- }
- else if (type instanceof ZodEffects) {
- return getDiscriminator(type.innerType());
- }
- else if (type instanceof ZodLiteral) {
- return [type.value];
- }
- else if (type instanceof ZodEnum) {
- return type.options;
- }
- else if (type instanceof ZodNativeEnum) {
- // eslint-disable-next-line ban/ban
- return Object.keys(type.enum);
- }
- else if (type instanceof ZodDefault) {
- return getDiscriminator(type._def.innerType);
- }
- else if (type instanceof ZodUndefined) {
- return [undefined];
- }
- else if (type instanceof ZodNull) {
- return [null];
- }
- else {
- return null;
- }
- };
- class ZodDiscriminatedUnion extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.object) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.object,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- const discriminator = this.discriminator;
- const discriminatorValue = ctx.data[discriminator];
- const option = this.optionsMap.get(discriminatorValue);
- if (!option) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_union_discriminator,
- options: Array.from(this.optionsMap.keys()),
- path: [discriminator],
- });
- return INVALID;
- }
- if (ctx.common.async) {
- return option._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- });
- }
- else {
- return option._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- });
- }
- }
- get discriminator() {
- return this._def.discriminator;
- }
- get options() {
- return this._def.options;
- }
- get optionsMap() {
- return this._def.optionsMap;
- }
- /**
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
- * have a different value for each object in the union.
- * @param discriminator the name of the discriminator property
- * @param types an array of object schemas
- * @param params
- */
- static create(discriminator, options, params) {
- // Get all the valid discriminator values
- const optionsMap = new Map();
- // try {
- for (const type of options) {
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
- if (!discriminatorValues) {
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
- }
- for (const value of discriminatorValues) {
- if (optionsMap.has(value)) {
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
- }
- optionsMap.set(value, type);
- }
- }
- return new ZodDiscriminatedUnion({
- typeName: exports.ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
- discriminator,
- options,
- optionsMap,
- ...processCreateParams(params),
- });
- }
- }
- function mergeValues(a, b) {
- const aType = getParsedType(a);
- const bType = getParsedType(b);
- if (a === b) {
- return { valid: true, data: a };
- }
- else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
- const bKeys = exports.util.objectKeys(b);
- const sharedKeys = exports.util
- .objectKeys(a)
- .filter((key) => bKeys.indexOf(key) !== -1);
- const newObj = { ...a, ...b };
- for (const key of sharedKeys) {
- const sharedValue = mergeValues(a[key], b[key]);
- if (!sharedValue.valid) {
- return { valid: false };
- }
- newObj[key] = sharedValue.data;
- }
- return { valid: true, data: newObj };
- }
- else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
- if (a.length !== b.length) {
- return { valid: false };
- }
- const newArray = [];
- for (let index = 0; index < a.length; index++) {
- const itemA = a[index];
- const itemB = b[index];
- const sharedValue = mergeValues(itemA, itemB);
- if (!sharedValue.valid) {
- return { valid: false };
- }
- newArray.push(sharedValue.data);
- }
- return { valid: true, data: newArray };
- }
- else if (aType === ZodParsedType.date &&
- bType === ZodParsedType.date &&
- +a === +b) {
- return { valid: true, data: a };
- }
- else {
- return { valid: false };
- }
- }
- class ZodIntersection extends ZodType {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- const handleParsed = (parsedLeft, parsedRight) => {
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
- return INVALID;
- }
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
- if (!merged.valid) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_intersection_types,
- });
- return INVALID;
- }
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
- status.dirty();
- }
- return { status: status.value, value: merged.data };
- };
- if (ctx.common.async) {
- return Promise.all([
- this._def.left._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- }),
- this._def.right._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- }),
- ]).then(([left, right]) => handleParsed(left, right));
- }
- else {
- return handleParsed(this._def.left._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- }), this._def.right._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- }));
- }
- }
- }
- ZodIntersection.create = (left, right, params) => {
- return new ZodIntersection({
- left: left,
- right: right,
- typeName: exports.ZodFirstPartyTypeKind.ZodIntersection,
- ...processCreateParams(params),
- });
- };
- class ZodTuple extends ZodType {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.array) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.array,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- if (ctx.data.length < this._def.items.length) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: this._def.items.length,
- inclusive: true,
- exact: false,
- type: "array",
- });
- return INVALID;
- }
- const rest = this._def.rest;
- if (!rest && ctx.data.length > this._def.items.length) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: this._def.items.length,
- inclusive: true,
- exact: false,
- type: "array",
- });
- status.dirty();
- }
- const items = [...ctx.data]
- .map((item, itemIndex) => {
- const schema = this._def.items[itemIndex] || this._def.rest;
- if (!schema)
- return null;
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
- })
- .filter((x) => !!x); // filter nulls
- if (ctx.common.async) {
- return Promise.all(items).then((results) => {
- return ParseStatus.mergeArray(status, results);
- });
- }
- else {
- return ParseStatus.mergeArray(status, items);
- }
- }
- get items() {
- return this._def.items;
- }
- rest(rest) {
- return new ZodTuple({
- ...this._def,
- rest,
- });
- }
- }
- ZodTuple.create = (schemas, params) => {
- if (!Array.isArray(schemas)) {
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
- }
- return new ZodTuple({
- items: schemas,
- typeName: exports.ZodFirstPartyTypeKind.ZodTuple,
- rest: null,
- ...processCreateParams(params),
- });
- };
- class ZodRecord extends ZodType {
- get keySchema() {
- return this._def.keyType;
- }
- get valueSchema() {
- return this._def.valueType;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.object) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.object,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- const pairs = [];
- const keyType = this._def.keyType;
- const valueType = this._def.valueType;
- for (const key in ctx.data) {
- pairs.push({
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
- });
- }
- if (ctx.common.async) {
- return ParseStatus.mergeObjectAsync(status, pairs);
- }
- else {
- return ParseStatus.mergeObjectSync(status, pairs);
- }
- }
- get element() {
- return this._def.valueType;
- }
- static create(first, second, third) {
- if (second instanceof ZodType) {
- return new ZodRecord({
- keyType: first,
- valueType: second,
- typeName: exports.ZodFirstPartyTypeKind.ZodRecord,
- ...processCreateParams(third),
- });
- }
- return new ZodRecord({
- keyType: ZodString.create(),
- valueType: first,
- typeName: exports.ZodFirstPartyTypeKind.ZodRecord,
- ...processCreateParams(second),
- });
- }
- }
- class ZodMap extends ZodType {
- get keySchema() {
- return this._def.keyType;
- }
- get valueSchema() {
- return this._def.valueType;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.map) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.map,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- const keyType = this._def.keyType;
- const valueType = this._def.valueType;
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
- return {
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
- };
- });
- if (ctx.common.async) {
- const finalMap = new Map();
- return Promise.resolve().then(async () => {
- for (const pair of pairs) {
- const key = await pair.key;
- const value = await pair.value;
- if (key.status === "aborted" || value.status === "aborted") {
- return INVALID;
- }
- if (key.status === "dirty" || value.status === "dirty") {
- status.dirty();
- }
- finalMap.set(key.value, value.value);
- }
- return { status: status.value, value: finalMap };
- });
- }
- else {
- const finalMap = new Map();
- for (const pair of pairs) {
- const key = pair.key;
- const value = pair.value;
- if (key.status === "aborted" || value.status === "aborted") {
- return INVALID;
- }
- if (key.status === "dirty" || value.status === "dirty") {
- status.dirty();
- }
- finalMap.set(key.value, value.value);
- }
- return { status: status.value, value: finalMap };
- }
- }
- }
- ZodMap.create = (keyType, valueType, params) => {
- return new ZodMap({
- valueType,
- keyType,
- typeName: exports.ZodFirstPartyTypeKind.ZodMap,
- ...processCreateParams(params),
- });
- };
- class ZodSet extends ZodType {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.set) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.set,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- const def = this._def;
- if (def.minSize !== null) {
- if (ctx.data.size < def.minSize.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: def.minSize.value,
- type: "set",
- inclusive: true,
- exact: false,
- message: def.minSize.message,
- });
- status.dirty();
- }
- }
- if (def.maxSize !== null) {
- if (ctx.data.size > def.maxSize.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: def.maxSize.value,
- type: "set",
- inclusive: true,
- exact: false,
- message: def.maxSize.message,
- });
- status.dirty();
- }
- }
- const valueType = this._def.valueType;
- function finalizeSet(elements) {
- const parsedSet = new Set();
- for (const element of elements) {
- if (element.status === "aborted")
- return INVALID;
- if (element.status === "dirty")
- status.dirty();
- parsedSet.add(element.value);
- }
- return { status: status.value, value: parsedSet };
- }
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
- if (ctx.common.async) {
- return Promise.all(elements).then((elements) => finalizeSet(elements));
- }
- else {
- return finalizeSet(elements);
- }
- }
- min(minSize, message) {
- return new ZodSet({
- ...this._def,
- minSize: { value: minSize, message: errorUtil.toString(message) },
- });
- }
- max(maxSize, message) {
- return new ZodSet({
- ...this._def,
- maxSize: { value: maxSize, message: errorUtil.toString(message) },
- });
- }
- size(size, message) {
- return this.min(size, message).max(size, message);
- }
- nonempty(message) {
- return this.min(1, message);
- }
- }
- ZodSet.create = (valueType, params) => {
- return new ZodSet({
- valueType,
- minSize: null,
- maxSize: null,
- typeName: exports.ZodFirstPartyTypeKind.ZodSet,
- ...processCreateParams(params),
- });
- };
- class ZodFunction extends ZodType {
- constructor() {
- super(...arguments);
- this.validate = this.implement;
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.function) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.function,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- function makeArgsIssue(args, error) {
- return makeIssue({
- data: args,
- path: ctx.path,
- errorMaps: [
- ctx.common.contextualErrorMap,
- ctx.schemaErrorMap,
- getErrorMap(),
- errorMap,
- ].filter((x) => !!x),
- issueData: {
- code: ZodIssueCode.invalid_arguments,
- argumentsError: error,
- },
- });
- }
- function makeReturnsIssue(returns, error) {
- return makeIssue({
- data: returns,
- path: ctx.path,
- errorMaps: [
- ctx.common.contextualErrorMap,
- ctx.schemaErrorMap,
- getErrorMap(),
- errorMap,
- ].filter((x) => !!x),
- issueData: {
- code: ZodIssueCode.invalid_return_type,
- returnTypeError: error,
- },
- });
- }
- const params = { errorMap: ctx.common.contextualErrorMap };
- const fn = ctx.data;
- if (this._def.returns instanceof ZodPromise) {
- // Would love a way to avoid disabling this rule, but we need
- // an alias (using an arrow function was what caused 2651).
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- const me = this;
- return OK(async function (...args) {
- const error = new ZodError([]);
- const parsedArgs = await me._def.args
- .parseAsync(args, params)
- .catch((e) => {
- error.addIssue(makeArgsIssue(args, e));
- throw error;
- });
- const result = await Reflect.apply(fn, this, parsedArgs);
- const parsedReturns = await me._def.returns._def.type
- .parseAsync(result, params)
- .catch((e) => {
- error.addIssue(makeReturnsIssue(result, e));
- throw error;
- });
- return parsedReturns;
- });
- }
- else {
- // Would love a way to avoid disabling this rule, but we need
- // an alias (using an arrow function was what caused 2651).
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- const me = this;
- return OK(function (...args) {
- const parsedArgs = me._def.args.safeParse(args, params);
- if (!parsedArgs.success) {
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
- }
- const result = Reflect.apply(fn, this, parsedArgs.data);
- const parsedReturns = me._def.returns.safeParse(result, params);
- if (!parsedReturns.success) {
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
- }
- return parsedReturns.data;
- });
- }
- }
- parameters() {
- return this._def.args;
- }
- returnType() {
- return this._def.returns;
- }
- args(...items) {
- return new ZodFunction({
- ...this._def,
- args: ZodTuple.create(items).rest(ZodUnknown.create()),
- });
- }
- returns(returnType) {
- return new ZodFunction({
- ...this._def,
- returns: returnType,
- });
- }
- implement(func) {
- const validatedFunc = this.parse(func);
- return validatedFunc;
- }
- strictImplement(func) {
- const validatedFunc = this.parse(func);
- return validatedFunc;
- }
- static create(args, returns, params) {
- return new ZodFunction({
- args: (args
- ? args
- : ZodTuple.create([]).rest(ZodUnknown.create())),
- returns: returns || ZodUnknown.create(),
- typeName: exports.ZodFirstPartyTypeKind.ZodFunction,
- ...processCreateParams(params),
- });
- }
- }
- class ZodLazy extends ZodType {
- get schema() {
- return this._def.getter();
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const lazySchema = this._def.getter();
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
- }
- }
- ZodLazy.create = (getter, params) => {
- return new ZodLazy({
- getter: getter,
- typeName: exports.ZodFirstPartyTypeKind.ZodLazy,
- ...processCreateParams(params),
- });
- };
- class ZodLiteral extends ZodType {
- _parse(input) {
- if (input.data !== this._def.value) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode.invalid_literal,
- expected: this._def.value,
- });
- return INVALID;
- }
- return { status: "valid", value: input.data };
- }
- get value() {
- return this._def.value;
- }
- }
- ZodLiteral.create = (value, params) => {
- return new ZodLiteral({
- value: value,
- typeName: exports.ZodFirstPartyTypeKind.ZodLiteral,
- ...processCreateParams(params),
- });
- };
- function createZodEnum(values, params) {
- return new ZodEnum({
- values,
- typeName: exports.ZodFirstPartyTypeKind.ZodEnum,
- ...processCreateParams(params),
- });
- }
- class ZodEnum extends ZodType {
- _parse(input) {
- if (typeof input.data !== "string") {
- const ctx = this._getOrReturnCtx(input);
- const expectedValues = this._def.values;
- addIssueToContext(ctx, {
- expected: exports.util.joinValues(expectedValues),
- received: ctx.parsedType,
- code: ZodIssueCode.invalid_type,
- });
- return INVALID;
- }
- if (this._def.values.indexOf(input.data) === -1) {
- const ctx = this._getOrReturnCtx(input);
- const expectedValues = this._def.values;
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode.invalid_enum_value,
- options: expectedValues,
- });
- return INVALID;
- }
- return OK(input.data);
- }
- get options() {
- return this._def.values;
- }
- get enum() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- get Values() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- get Enum() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- extract(values) {
- return ZodEnum.create(values);
- }
- exclude(values) {
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
- }
- }
- ZodEnum.create = createZodEnum;
- class ZodNativeEnum extends ZodType {
- _parse(input) {
- const nativeEnumValues = exports.util.getValidEnumValues(this._def.values);
- const ctx = this._getOrReturnCtx(input);
- if (ctx.parsedType !== ZodParsedType.string &&
- ctx.parsedType !== ZodParsedType.number) {
- const expectedValues = exports.util.objectValues(nativeEnumValues);
- addIssueToContext(ctx, {
- expected: exports.util.joinValues(expectedValues),
- received: ctx.parsedType,
- code: ZodIssueCode.invalid_type,
- });
- return INVALID;
- }
- if (nativeEnumValues.indexOf(input.data) === -1) {
- const expectedValues = exports.util.objectValues(nativeEnumValues);
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode.invalid_enum_value,
- options: expectedValues,
- });
- return INVALID;
- }
- return OK(input.data);
- }
- get enum() {
- return this._def.values;
- }
- }
- ZodNativeEnum.create = (values, params) => {
- return new ZodNativeEnum({
- values: values,
- typeName: exports.ZodFirstPartyTypeKind.ZodNativeEnum,
- ...processCreateParams(params),
- });
- };
- class ZodPromise extends ZodType {
- unwrap() {
- return this._def.type;
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.promise &&
- ctx.common.async === false) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.promise,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- const promisified = ctx.parsedType === ZodParsedType.promise
- ? ctx.data
- : Promise.resolve(ctx.data);
- return OK(promisified.then((data) => {
- return this._def.type.parseAsync(data, {
- path: ctx.path,
- errorMap: ctx.common.contextualErrorMap,
- });
- }));
- }
- }
- ZodPromise.create = (schema, params) => {
- return new ZodPromise({
- type: schema,
- typeName: exports.ZodFirstPartyTypeKind.ZodPromise,
- ...processCreateParams(params),
- });
- };
- class ZodEffects extends ZodType {
- innerType() {
- return this._def.schema;
- }
- sourceType() {
- return this._def.schema._def.typeName === exports.ZodFirstPartyTypeKind.ZodEffects
- ? this._def.schema.sourceType()
- : this._def.schema;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- const effect = this._def.effect || null;
- const checkCtx = {
- addIssue: (arg) => {
- addIssueToContext(ctx, arg);
- if (arg.fatal) {
- status.abort();
- }
- else {
- status.dirty();
- }
- },
- get path() {
- return ctx.path;
- },
- };
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
- if (effect.type === "preprocess") {
- const processed = effect.transform(ctx.data, checkCtx);
- if (ctx.common.issues.length) {
- return {
- status: "dirty",
- value: ctx.data,
- };
- }
- if (ctx.common.async) {
- return Promise.resolve(processed).then((processed) => {
- return this._def.schema._parseAsync({
- data: processed,
- path: ctx.path,
- parent: ctx,
- });
- });
- }
- else {
- return this._def.schema._parseSync({
- data: processed,
- path: ctx.path,
- parent: ctx,
- });
- }
- }
- if (effect.type === "refinement") {
- const executeRefinement = (acc
- // effect: RefinementEffect<any>
- ) => {
- const result = effect.refinement(acc, checkCtx);
- if (ctx.common.async) {
- return Promise.resolve(result);
- }
- if (result instanceof Promise) {
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
- }
- return acc;
- };
- if (ctx.common.async === false) {
- const inner = this._def.schema._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- });
- if (inner.status === "aborted")
- return INVALID;
- if (inner.status === "dirty")
- status.dirty();
- // return value is ignored
- executeRefinement(inner.value);
- return { status: status.value, value: inner.value };
- }
- else {
- return this._def.schema
- ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
- .then((inner) => {
- if (inner.status === "aborted")
- return INVALID;
- if (inner.status === "dirty")
- status.dirty();
- return executeRefinement(inner.value).then(() => {
- return { status: status.value, value: inner.value };
- });
- });
- }
- }
- if (effect.type === "transform") {
- if (ctx.common.async === false) {
- const base = this._def.schema._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- });
- if (!isValid(base))
- return base;
- const result = effect.transform(base.value, checkCtx);
- if (result instanceof Promise) {
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
- }
- return { status: status.value, value: result };
- }
- else {
- return this._def.schema
- ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
- .then((base) => {
- if (!isValid(base))
- return base;
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
- });
- }
- }
- exports.util.assertNever(effect);
- }
- }
- ZodEffects.create = (schema, effect, params) => {
- return new ZodEffects({
- schema,
- typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
- effect,
- ...processCreateParams(params),
- });
- };
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
- return new ZodEffects({
- schema,
- effect: { type: "preprocess", transform: preprocess },
- typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
- ...processCreateParams(params),
- });
- };
- class ZodOptional extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType === ZodParsedType.undefined) {
- return OK(undefined);
- }
- return this._def.innerType._parse(input);
- }
- unwrap() {
- return this._def.innerType;
- }
- }
- ZodOptional.create = (type, params) => {
- return new ZodOptional({
- innerType: type,
- typeName: exports.ZodFirstPartyTypeKind.ZodOptional,
- ...processCreateParams(params),
- });
- };
- class ZodNullable extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType === ZodParsedType.null) {
- return OK(null);
- }
- return this._def.innerType._parse(input);
- }
- unwrap() {
- return this._def.innerType;
- }
- }
- ZodNullable.create = (type, params) => {
- return new ZodNullable({
- innerType: type,
- typeName: exports.ZodFirstPartyTypeKind.ZodNullable,
- ...processCreateParams(params),
- });
- };
- class ZodDefault extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- let data = ctx.data;
- if (ctx.parsedType === ZodParsedType.undefined) {
- data = this._def.defaultValue();
- }
- return this._def.innerType._parse({
- data,
- path: ctx.path,
- parent: ctx,
- });
- }
- removeDefault() {
- return this._def.innerType;
- }
- }
- ZodDefault.create = (type, params) => {
- return new ZodDefault({
- innerType: type,
- typeName: exports.ZodFirstPartyTypeKind.ZodDefault,
- defaultValue: typeof params.default === "function"
- ? params.default
- : () => params.default,
- ...processCreateParams(params),
- });
- };
- class ZodCatch extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- // newCtx is used to not collect issues from inner types in ctx
- const newCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: [],
- },
- };
- const result = this._def.innerType._parse({
- data: newCtx.data,
- path: newCtx.path,
- parent: {
- ...newCtx,
- },
- });
- if (isAsync(result)) {
- return result.then((result) => {
- return {
- status: "valid",
- value: result.status === "valid"
- ? result.value
- : this._def.catchValue({
- get error() {
- return new ZodError(newCtx.common.issues);
- },
- input: newCtx.data,
- }),
- };
- });
- }
- else {
- return {
- status: "valid",
- value: result.status === "valid"
- ? result.value
- : this._def.catchValue({
- get error() {
- return new ZodError(newCtx.common.issues);
- },
- input: newCtx.data,
- }),
- };
- }
- }
- removeCatch() {
- return this._def.innerType;
- }
- }
- ZodCatch.create = (type, params) => {
- return new ZodCatch({
- innerType: type,
- typeName: exports.ZodFirstPartyTypeKind.ZodCatch,
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
- ...processCreateParams(params),
- });
- };
- class ZodNaN extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.nan) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.nan,
- received: ctx.parsedType,
- });
- return INVALID;
- }
- return { status: "valid", value: input.data };
- }
- }
- ZodNaN.create = (params) => {
- return new ZodNaN({
- typeName: exports.ZodFirstPartyTypeKind.ZodNaN,
- ...processCreateParams(params),
- });
- };
- const BRAND = Symbol("zod_brand");
- class ZodBranded extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const data = ctx.data;
- return this._def.type._parse({
- data,
- path: ctx.path,
- parent: ctx,
- });
- }
- unwrap() {
- return this._def.type;
- }
- }
- class ZodPipeline extends ZodType {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.common.async) {
- const handleAsync = async () => {
- const inResult = await this._def.in._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- });
- if (inResult.status === "aborted")
- return INVALID;
- if (inResult.status === "dirty") {
- status.dirty();
- return DIRTY(inResult.value);
- }
- else {
- return this._def.out._parseAsync({
- data: inResult.value,
- path: ctx.path,
- parent: ctx,
- });
- }
- };
- return handleAsync();
- }
- else {
- const inResult = this._def.in._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx,
- });
- if (inResult.status === "aborted")
- return INVALID;
- if (inResult.status === "dirty") {
- status.dirty();
- return {
- status: "dirty",
- value: inResult.value,
- };
- }
- else {
- return this._def.out._parseSync({
- data: inResult.value,
- path: ctx.path,
- parent: ctx,
- });
- }
- }
- }
- static create(a, b) {
- return new ZodPipeline({
- in: a,
- out: b,
- typeName: exports.ZodFirstPartyTypeKind.ZodPipeline,
- });
- }
- }
- class ZodReadonly extends ZodType {
- _parse(input) {
- const result = this._def.innerType._parse(input);
- if (isValid(result)) {
- result.value = Object.freeze(result.value);
- }
- return result;
- }
- }
- ZodReadonly.create = (type, params) => {
- return new ZodReadonly({
- innerType: type,
- typeName: exports.ZodFirstPartyTypeKind.ZodReadonly,
- ...processCreateParams(params),
- });
- };
- const custom = (check, params = {},
- /**
- * @deprecated
- *
- * Pass `fatal` into the params object instead:
- *
- * ```ts
- * z.string().custom((val) => val.length > 5, { fatal: false })
- * ```
- *
- */
- fatal) => {
- if (check)
- return ZodAny.create().superRefine((data, ctx) => {
- var _a, _b;
- if (!check(data)) {
- const p = typeof params === "function"
- ? params(data)
- : typeof params === "string"
- ? { message: params }
- : params;
- const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
- const p2 = typeof p === "string" ? { message: p } : p;
- ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
- }
- });
- return ZodAny.create();
- };
- const late = {
- object: ZodObject.lazycreate,
- };
- exports.ZodFirstPartyTypeKind = void 0;
- (function (ZodFirstPartyTypeKind) {
- ZodFirstPartyTypeKind["ZodString"] = "ZodString";
- ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
- ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
- ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
- ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
- ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
- ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
- ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
- ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
- ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
- ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
- ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
- ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
- ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
- ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
- ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
- ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
- ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
- ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
- ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
- ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
- ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
- ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
- ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
- ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
- ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
- ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
- ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
- ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
- ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
- ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
- ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
- ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
- ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
- ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
- ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
- })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
- const instanceOfType = (
- // const instanceOfType = <T extends new (...args: any[]) => any>(
- cls, params = {
- message: `Input not instance of ${cls.name}`,
- }) => custom((data) => data instanceof cls, params);
- const stringType = ZodString.create;
- const numberType = ZodNumber.create;
- const nanType = ZodNaN.create;
- const bigIntType = ZodBigInt.create;
- const booleanType = ZodBoolean.create;
- const dateType = ZodDate.create;
- const symbolType = ZodSymbol.create;
- const undefinedType = ZodUndefined.create;
- const nullType = ZodNull.create;
- const anyType = ZodAny.create;
- const unknownType = ZodUnknown.create;
- const neverType = ZodNever.create;
- const voidType = ZodVoid.create;
- const arrayType = ZodArray.create;
- const objectType = ZodObject.create;
- const strictObjectType = ZodObject.strictCreate;
- const unionType = ZodUnion.create;
- const discriminatedUnionType = ZodDiscriminatedUnion.create;
- const intersectionType = ZodIntersection.create;
- const tupleType = ZodTuple.create;
- const recordType = ZodRecord.create;
- const mapType = ZodMap.create;
- const setType = ZodSet.create;
- const functionType = ZodFunction.create;
- const lazyType = ZodLazy.create;
- const literalType = ZodLiteral.create;
- const enumType = ZodEnum.create;
- const nativeEnumType = ZodNativeEnum.create;
- const promiseType = ZodPromise.create;
- const effectsType = ZodEffects.create;
- const optionalType = ZodOptional.create;
- const nullableType = ZodNullable.create;
- const preprocessType = ZodEffects.createWithPreprocess;
- const pipelineType = ZodPipeline.create;
- const ostring = () => stringType().optional();
- const onumber = () => numberType().optional();
- const oboolean = () => booleanType().optional();
- const coerce = {
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
- boolean: ((arg) => ZodBoolean.create({
- ...arg,
- coerce: true,
- })),
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
- date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
- };
- const NEVER = INVALID;
- var z = /*#__PURE__*/Object.freeze({
- __proto__: null,
- defaultErrorMap: errorMap,
- setErrorMap: setErrorMap,
- getErrorMap: getErrorMap,
- makeIssue: makeIssue,
- EMPTY_PATH: EMPTY_PATH,
- addIssueToContext: addIssueToContext,
- ParseStatus: ParseStatus,
- INVALID: INVALID,
- DIRTY: DIRTY,
- OK: OK,
- isAborted: isAborted,
- isDirty: isDirty,
- isValid: isValid,
- isAsync: isAsync,
- get util () { return exports.util; },
- get objectUtil () { return exports.objectUtil; },
- ZodParsedType: ZodParsedType,
- getParsedType: getParsedType,
- ZodType: ZodType,
- ZodString: ZodString,
- ZodNumber: ZodNumber,
- ZodBigInt: ZodBigInt,
- ZodBoolean: ZodBoolean,
- ZodDate: ZodDate,
- ZodSymbol: ZodSymbol,
- ZodUndefined: ZodUndefined,
- ZodNull: ZodNull,
- ZodAny: ZodAny,
- ZodUnknown: ZodUnknown,
- ZodNever: ZodNever,
- ZodVoid: ZodVoid,
- ZodArray: ZodArray,
- ZodObject: ZodObject,
- ZodUnion: ZodUnion,
- ZodDiscriminatedUnion: ZodDiscriminatedUnion,
- ZodIntersection: ZodIntersection,
- ZodTuple: ZodTuple,
- ZodRecord: ZodRecord,
- ZodMap: ZodMap,
- ZodSet: ZodSet,
- ZodFunction: ZodFunction,
- ZodLazy: ZodLazy,
- ZodLiteral: ZodLiteral,
- ZodEnum: ZodEnum,
- ZodNativeEnum: ZodNativeEnum,
- ZodPromise: ZodPromise,
- ZodEffects: ZodEffects,
- ZodTransformer: ZodEffects,
- ZodOptional: ZodOptional,
- ZodNullable: ZodNullable,
- ZodDefault: ZodDefault,
- ZodCatch: ZodCatch,
- ZodNaN: ZodNaN,
- BRAND: BRAND,
- ZodBranded: ZodBranded,
- ZodPipeline: ZodPipeline,
- ZodReadonly: ZodReadonly,
- custom: custom,
- Schema: ZodType,
- ZodSchema: ZodType,
- late: late,
- get ZodFirstPartyTypeKind () { return exports.ZodFirstPartyTypeKind; },
- coerce: coerce,
- any: anyType,
- array: arrayType,
- bigint: bigIntType,
- boolean: booleanType,
- date: dateType,
- discriminatedUnion: discriminatedUnionType,
- effect: effectsType,
- 'enum': enumType,
- 'function': functionType,
- 'instanceof': instanceOfType,
- intersection: intersectionType,
- lazy: lazyType,
- literal: literalType,
- map: mapType,
- nan: nanType,
- nativeEnum: nativeEnumType,
- never: neverType,
- 'null': nullType,
- nullable: nullableType,
- number: numberType,
- object: objectType,
- oboolean: oboolean,
- onumber: onumber,
- optional: optionalType,
- ostring: ostring,
- pipeline: pipelineType,
- preprocess: preprocessType,
- promise: promiseType,
- record: recordType,
- set: setType,
- strictObject: strictObjectType,
- string: stringType,
- symbol: symbolType,
- transformer: effectsType,
- tuple: tupleType,
- 'undefined': undefinedType,
- union: unionType,
- unknown: unknownType,
- 'void': voidType,
- NEVER: NEVER,
- ZodIssueCode: ZodIssueCode,
- quotelessJson: quotelessJson,
- ZodError: ZodError
- });
- exports.BRAND = BRAND;
- exports.DIRTY = DIRTY;
- exports.EMPTY_PATH = EMPTY_PATH;
- exports.INVALID = INVALID;
- exports.NEVER = NEVER;
- exports.OK = OK;
- exports.ParseStatus = ParseStatus;
- exports.Schema = ZodType;
- exports.ZodAny = ZodAny;
- exports.ZodArray = ZodArray;
- exports.ZodBigInt = ZodBigInt;
- exports.ZodBoolean = ZodBoolean;
- exports.ZodBranded = ZodBranded;
- exports.ZodCatch = ZodCatch;
- exports.ZodDate = ZodDate;
- exports.ZodDefault = ZodDefault;
- exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion;
- exports.ZodEffects = ZodEffects;
- exports.ZodEnum = ZodEnum;
- exports.ZodError = ZodError;
- exports.ZodFunction = ZodFunction;
- exports.ZodIntersection = ZodIntersection;
- exports.ZodIssueCode = ZodIssueCode;
- exports.ZodLazy = ZodLazy;
- exports.ZodLiteral = ZodLiteral;
- exports.ZodMap = ZodMap;
- exports.ZodNaN = ZodNaN;
- exports.ZodNativeEnum = ZodNativeEnum;
- exports.ZodNever = ZodNever;
- exports.ZodNull = ZodNull;
- exports.ZodNullable = ZodNullable;
- exports.ZodNumber = ZodNumber;
- exports.ZodObject = ZodObject;
- exports.ZodOptional = ZodOptional;
- exports.ZodParsedType = ZodParsedType;
- exports.ZodPipeline = ZodPipeline;
- exports.ZodPromise = ZodPromise;
- exports.ZodReadonly = ZodReadonly;
- exports.ZodRecord = ZodRecord;
- exports.ZodSchema = ZodType;
- exports.ZodSet = ZodSet;
- exports.ZodString = ZodString;
- exports.ZodSymbol = ZodSymbol;
- exports.ZodTransformer = ZodEffects;
- exports.ZodTuple = ZodTuple;
- exports.ZodType = ZodType;
- exports.ZodUndefined = ZodUndefined;
- exports.ZodUnion = ZodUnion;
- exports.ZodUnknown = ZodUnknown;
- exports.ZodVoid = ZodVoid;
- exports.addIssueToContext = addIssueToContext;
- exports.any = anyType;
- exports.array = arrayType;
- exports.bigint = bigIntType;
- exports.boolean = booleanType;
- exports.coerce = coerce;
- exports.custom = custom;
- exports.date = dateType;
- exports["default"] = z;
- exports.defaultErrorMap = errorMap;
- exports.discriminatedUnion = discriminatedUnionType;
- exports.effect = effectsType;
- exports["enum"] = enumType;
- exports["function"] = functionType;
- exports.getErrorMap = getErrorMap;
- exports.getParsedType = getParsedType;
- exports["instanceof"] = instanceOfType;
- exports.intersection = intersectionType;
- exports.isAborted = isAborted;
- exports.isAsync = isAsync;
- exports.isDirty = isDirty;
- exports.isValid = isValid;
- exports.late = late;
- exports.lazy = lazyType;
- exports.literal = literalType;
- exports.makeIssue = makeIssue;
- exports.map = mapType;
- exports.nan = nanType;
- exports.nativeEnum = nativeEnumType;
- exports.never = neverType;
- exports["null"] = nullType;
- exports.nullable = nullableType;
- exports.number = numberType;
- exports.object = objectType;
- exports.oboolean = oboolean;
- exports.onumber = onumber;
- exports.optional = optionalType;
- exports.ostring = ostring;
- exports.pipeline = pipelineType;
- exports.preprocess = preprocessType;
- exports.promise = promiseType;
- exports.quotelessJson = quotelessJson;
- exports.record = recordType;
- exports.set = setType;
- exports.setErrorMap = setErrorMap;
- exports.strictObject = strictObjectType;
- exports.string = stringType;
- exports.symbol = symbolType;
- exports.transformer = effectsType;
- exports.tuple = tupleType;
- exports["undefined"] = undefinedType;
- exports.union = unionType;
- exports.unknown = unknownType;
- exports["void"] = voidType;
- exports.z = z;
- Object.defineProperty(exports, '__esModule', { value: true });
- }));
|