express-zod-api 17.7.0-beta1 → 17.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -15,7 +15,7 @@ Original error: ${e.originalError.message}.`:""))};var hr=require("ramda");var r
15
15
  \x1B[38;5;117m 888\x1B[3m Proudly supports transgender community.\x1B[23m\x1B[39m
16
16
  \x1B[38;5;117m\x1B[3mfor Tonya \x1B[23m888\x1B[3m Start your API server with I/O schema validation and custom middlewares in minutes.\x1B[23m\x1B[39m
17
17
  \x1B[90m\x1B[3m Thank you for choosing Express Zod API for your project.\x1B[23m\x1B[39m
18
- `;var It=({app:e,rootLogger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log(Cr()),t.debug("Running","v17.7.0-beta1 (CJS)"),ie({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,m)=>{let u=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;u.info(`${d.method}: ${s}`),await i.execute({request:d,response:m,logger:u,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}})};var Ze=R(require("http-errors"),1);var Ir=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:(0,Ze.isHttpError)(o)?o:(0,Ze.default)(400,le(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},Er=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=(0,Ze.default)(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Ge({response:i,logger:a,error:new Q(le(p).message,s)})}},wr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()};var Mr=async e=>{let t=Ar(e.logger)?tt({...e.logger,winston:await ne("winston")}):e.logger,r=e.errorHandler||ye,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=Er(i),a=Ir(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Nr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o}=await Mr(e);return It({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},vr=async(e,t)=>{let r=(0,Et.default)().disable("x-powered-by");if(e.server.compression){let d=await ne("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||Et.default.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=await Mr(e);if(e.server.upload){let d=await ne("express-fileupload"),{limitError:m,beforeUpload:u,...l}={...typeof e.server.upload=="object"&&e.server.upload};u&&u({app:r,logger:o}),r.use(d({...l,abortOnLimit:!1,parseNested:!0,logger:{log:o.debug.bind(o)}})),m&&r.use(wr(m))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},m)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),m()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),It({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,m)=>d.listen(m,()=>{o.info("Listening",m)}),p={httpServer:a(zr.default.createServer(r),e.server.listen),httpsServer:e.https?a(Zr.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};var eo=R(require("assert/strict"),1),to=require("openapi3-ts/oas31");var F=R(require("assert/strict"),1),G=require("openapi3-ts/oas31"),c=require("ramda"),O=require("zod");var wt=require("zod");var rt=e=>!isNaN(e.getTime()),ot=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Me="DateIn",Dr=()=>E(Me,wt.z.string().regex(ot).transform(e=>new Date(e)).pipe(wt.z.date().refine(rt)));var kr=require("zod");var Ne="DateOut",Lr=()=>E(Ne,kr.z.date().refine(rt).transform(e=>e.toISOString()));var se=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Ee(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,m=a?a({schema:e,...p,next:l=>se({schema:l,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),u=t&&t({schema:e,prev:m,...p});return u?{...m,...u}:m};var jr=50,Ur="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",jo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Kr=/:([A-Za-z0-9_]+)/g,Fr=e=>e.match(Kr)?.map(t=>t.slice(1))||[],Br=e=>e.replace(Kr,t=>`{${t.slice(1)}}`),Ho=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),Uo=({schema:{_def:{innerType:e}},next:t})=>t(e),Ko=()=>({format:"any"}),Fo=e=>((0,F.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Bo=({schema:e})=>({type:"string",format:e instanceof O.z.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),qo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Vo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),$o=e=>{let[t,r]=e.filter(i=>!(0,G.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,F.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,c.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,c.concat)(i,s):i===s?s:F.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,c.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([i,s])=>(0,c.mergeDeepRight)(i,s))),o},_o=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return $o(o)}catch{}return{allOf:o}},Go=({schema:e,next:t})=>t(e.unwrap()),Wo=({schema:e,next:t})=>t(e._def.innerType),Yo=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,G.isReferenceObject)(r)||(r.type=Vr(r)),r},qr=e=>{let t=(0,c.toLower)((0,c.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Hr=({schema:e})=>({type:qr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Jo=({schema:{value:e}})=>({type:qr(e),const:e}),Qo=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ie(p)?p instanceof O.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=nt({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},Xo=()=>({type:"null"}),en=e=>((0,F.default)(!e.isResponse,new I({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:ot.source,externalDocs:{url:Ur}}),tn=e=>((0,F.default)(e.isResponse,new I({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ur}}),rn=e=>F.default.fail(new I({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),on=()=>({type:"boolean"}),nn=()=>({type:"integer",format:"bigint"}),sn=e=>e.every(t=>t instanceof O.z.ZodLiteral),an=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof O.z.ZodEnum||e instanceof O.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=nt({schema:O.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof O.z.ZodLiteral)return{type:"object",properties:nt({schema:O.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof O.z.ZodUnion&&sn(e.options)){let o=(0,c.map)(s=>`${s.value}`,e.options),i=(0,c.fromPairs)((0,c.xprod)(o,[t]));return{type:"object",properties:nt({schema:O.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},pn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},dn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),cn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:m,isDatetime:u,_def:{checks:l}}})=>{let y=l.find(b=>b.kind==="regex"),T=l.find(b=>b.kind==="datetime"),S=y?y.regex:T?T.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,A={type:"string"},h={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:m};for(let b in h)if(h[b]){A.format=b;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),S&&(A.pattern=S.source),A},mn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},nt=({schema:{shape:e},next:t})=>(0,c.map)(t,e),ln=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return jo?.[t]},Vr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},un=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,G.isReferenceObject)(o)){let s=Be(e,ln(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(O.z.any())}if(!t&&i.type==="preprocess"&&!(0,G.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},fn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),yn=({schema:e,next:t})=>t(e.unwrap()),gn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},hn=({next:e,schema:t})=>e(t.shape.raw),$r=e=>e.length?(0,c.zipObj)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e)):void 0,_r=(e,t,r=[])=>(0,c.pipe)(K,(0,c.map)((0,c.when)((0,c.both)(Z,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),$r)({schema:e,variant:t?"parsed":"original",validate:!0}),xn=(e,t)=>(0,c.pipe)(K,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),$r)({schema:e,variant:"original",validate:!0}),ve=(e,t)=>e instanceof O.z.ZodObject?e:e instanceof O.z.ZodUnion||e instanceof O.z.ZodDiscriminatedUnion?Array.from(e.options.values()).map(r=>ve(r,t)).reduce((r,o)=>r.merge(o.partial()),O.z.object({})):e instanceof O.z.ZodEffects?((0,F.default)(e._def.effect.type==="refinement",t),ve(e._def.schema,t)):ve(e._def.left,t).merge(ve(e._def.right,t)),Gr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=ve(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=Fr(e),l=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=h=>y&&u.includes(h),A=h=>T&&ht(h);return Object.keys(m).filter(h=>l||S(h)).map(h=>{let b=se({schema:m[h],isResponse:!1,rules:Zt,onEach:Mt,onMissing:Nt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),q=p==="components"?a(z(d,h),b):b;return{name:h,in:S(h)?"path":A(h)?"header":"query",required:!m[h].isOptional(),description:b.description||d,schema:q,examples:xn(r,h)}})},Zt={ZodString:cn,ZodNumber:mn,ZodBigInt:nn,ZodBoolean:on,ZodNull:Xo,ZodArray:pn,ZodTuple:dn,ZodRecord:an,ZodObject:Qo,ZodLiteral:Jo,ZodIntersection:_o,ZodUnion:qo,ZodAny:Ko,ZodDefault:Ho,ZodEnum:Hr,ZodNativeEnum:Hr,ZodEffects:un,ZodOptional:Go,ZodNullable:Yo,ZodDiscriminatedUnion:Vo,ZodBranded:yn,ZodDate:rn,ZodCatch:Uo,ZodPipeline:fn,ZodLazy:gn,ZodReadonly:Wo,[_]:Bo,[ze]:Fo,[Ne]:tn,[Me]:en,[te]:hn},Mt=({schema:e,isResponse:t,prev:r})=>{if((0,G.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof O.z.ZodLazy,s=r.type!==void 0,a=t&&Ie(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),m={};return o&&(m.description=o),p&&(m.type=Vr(r)),d.length&&(m.examples=Array.from(d)),m},Nt=({schema:e,...t})=>F.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),zt=(e,t)=>{if((0,G.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,c.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,c.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>zt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>zt(o,t))),r},Wr=e=>(0,G.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),Yr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:m,statusCode:u,description:l=`${e.toUpperCase()} ${t} ${Tt(i)} response ${m?u:""}`.trim()})=>{let y=Wr(se({schema:r,isResponse:!0,rules:Zt,onEach:Mt,onMissing:Nt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(z(l),y):y,examples:_r(r,!0)};return{description:l,content:(0,c.fromPairs)((0,c.xprod)(o,[T]))}},Tn=()=>({type:"http",scheme:"basic"}),bn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Sn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},On=({name:e})=>({type:"apiKey",in:"header",name:e}),An=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Rn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Pn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),Jr=(e,t)=>{let r={basic:Tn,bearer:bn,input:Sn,header:On,cookie:An,openid:Rn,oauth2:Pn};return We(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?(0,c.mergeAll)((0,c.map)(({name:r,scopes:o})=>(0,c.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(At(e)):it({or:[e]}),Qr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let m=Fr(t),u=Wr(zt(se({schema:r,isResponse:!1,rules:Zt,onEach:Mt,onMissing:Nt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),m)),l={schema:p==="components"?a(z(d),u):u,examples:_r(r,!1,m)};return{description:d,content:(0,c.fromPairs)((0,c.xprod)(o,[l]))}},Xr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),vt=e=>e.length<=jr?e:e.slice(0,jr-1)+"\u2026";var st=class extends to.OpenApiBuilder{lastSecuritySchemaIds={};lastOperationIdSuffixes={};makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){if(o)return(0,eo.default)(!(o in this.lastOperationIdSuffixes),new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),this.lastOperationIdSuffixes[o]=1,o;let i=z(r,t);return i in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[i]++,`${i}${this.lastOperationIdSuffixes[i]}`):(this.lastOperationIdSuffixes[i]=1,i)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let o in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:m=Fe}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});ie({routing:t,onEndpoint:(l,y,T)=>{let S=T,A={path:y,method:S,endpoint:l,composition:d,serializer:m,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,b]=["short","long"].map(l.getDescription.bind(l)),q=h?vt(h):p&&b?vt(b):void 0,ke=l.getTags(),Ae=r.inputSources?.[S]||yt[S],pe=this.ensureUniqOperationId(y,S,l.getOperationId(S)),Le=Gr({...A,inputSources:Ae,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),je={};for(let L of["positive","negative"]){let x=l.getResponses(L);for(let{mimeTypes:P,schema:C,statusCodes:N}of x)for(let de of N)je[de]=Yr({...A,variant:L,schema:C,mimeTypes:P,statusCode:de,hasMultipleStatusCodes:x.length>1||N.length>1,description:a?.[`${L}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:de})})}let ut=Ae.includes("body")?Qr({...A,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,He=it(We(Jr(l.getSecurity(),Ae),L=>{let x=this.ensureUniqSecuritySchemaName(L),P=["oauth2","openIdConnect"].includes(L.type)?l.getScopes():[];return this.addSecurityScheme(x,L),{name:x,scopes:P}}));this.addPath(Br(y),{[S]:{operationId:pe,summary:q,description:b,tags:ke.length>0?ke:void 0,parameters:Le.length>0?Le:void 0,requestBody:ut,security:He.length>0?He:void 0,responses:je}})}}),this.rootDoc.tags=r.tags?Xr(r.tags):[]}};var Dt=R(require("http"),1);var Cn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>U),...t}),In=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Dt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Dt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},En=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),ro=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Pr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Cn({fnMethod:a,requestProps:t}),d=In({fnMethod:a,responseProps:r}),m=En({fnMethod:a,loggerProps:i}),u={cors:!1,logger:m,...o};return await e.execute({request:p,response:d,config:u,logger:m}),{requestMock:p,responseMock:d,loggerMock:m}};var w=R(require("typescript"),1);var k=R(require("typescript"),1),be=require("ramda"),n=k.default.factory,W=[n.createModifier(k.default.SyntaxKind.ExportKeyword)],wn=[n.createModifier(k.default.SyntaxKind.AsyncKeyword)],zn=[n.createModifier(k.default.SyntaxKind.PublicKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],oo=[n.createModifier(k.default.SyntaxKind.ProtectedKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],kt=n.createTemplateHead(""),Se=n.createTemplateTail(""),Lt=n.createTemplateMiddle(" "),jt=e=>n.createTemplateLiteralType(kt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Se:Lt))),Ht=jt(["M","P"]),at=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),pt=(e,t)=>(0,be.chain)(([r,o])=>[at(n.createIdentifier(r),o,t)],(0,be.toPairs)(e)),Ut=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),no=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),io=(e,t)=>n.createPropertySignature(void 0,`"${e}"`,void 0,n.createTypeReferenceNode(t)),Y=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.default.NodeFlags.Const),Kt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),dt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,t),so=(e,t,r)=>n.createPropertyDeclaration(zn,e,void 0,t,r),ao=(e,t,r)=>n.createClassDeclaration(W,e,void 0,void 0,[t,...r]),po=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),co=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.default.SyntaxKind.AnyKeyword)]),mo=(e,t,r)=>n.createInterfaceDeclaration(W,e,void 0,t,r),lo=e=>(0,be.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,be.toPairs)(e)),Ft=(e,t,r)=>n.createArrowFunction(r?wn:void 0,void 0,e.map(o=>at(o)),void 0,void 0,t),Bt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,pt({acc:void 0,key:void 0}),void 0,void 0,t),r]);var uo=["get","post","put","delete","patch"];var g=R(require("typescript"),1),mt=require("zod");var B=R(require("typescript"),1),{factory:ct}=B.default,qt=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Oe=(e,t,r)=>{let o=ct.createTypeAliasDeclaration(void 0,ct.createIdentifier(t),void 0,e);return r&&qt(o,r),o},Vt=(e,t)=>{let r=B.default.createSourceFile("print.ts","",B.default.ScriptTarget.Latest,!1,B.default.ScriptKind.TS);return B.default.createPrinter(t).printNode(B.default.EmitHint.Unspecified,e,r)},Zn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fo=e=>Zn.test(e)?ct.createIdentifier(e):ct.createStringLiteral(e);var{factory:f}=g.default,Mn={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},Nn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),vn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ie(a)?a instanceof mt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,fo(s),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&qt(d,a.description),d});return f.createTypeLiteralNode(i)},Dn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),kn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),yo=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),Ln=e=>Mn?.[e.kind],jn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Be(e,Ln(o)),a={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||g.default.SyntaxKind.AnyKeyword)}return o},Hn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Un=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Kn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Fn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Bn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),qn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Vn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),$n=({next:e,schema:t})=>e(t.unwrap()),_n=({next:e,schema:t})=>e(t._def.innerType),Gn=({next:e,schema:t})=>e(t._def.innerType),Wn=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),Yn=()=>f.createLiteralTypeNode(f.createNull()),Jn=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,f.createLiteralTypeNode(f.createNull())),t(s,r(i.schema)))},Qn=({schema:e})=>{let t=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),r=f.createTypeReferenceNode("Buffer"),o=f.createUnionTypeNode([t,r]);return e instanceof mt.z.ZodString?t:e instanceof mt.z.ZodUnion?o:r},Xn=({next:e,schema:t})=>e(t.shape.raw),ei={ZodString:ae(g.default.SyntaxKind.StringKeyword),ZodNumber:ae(g.default.SyntaxKind.NumberKeyword),ZodBigInt:ae(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:ae(g.default.SyntaxKind.BooleanKeyword),ZodAny:ae(g.default.SyntaxKind.AnyKeyword),[Me]:ae(g.default.SyntaxKind.StringKeyword),[Ne]:ae(g.default.SyntaxKind.StringKeyword),ZodNull:Yn,ZodArray:Dn,ZodTuple:Fn,ZodRecord:Bn,ZodObject:vn,ZodLiteral:Nn,ZodIntersection:qn,ZodUnion:yo,ZodDefault:Vn,ZodEnum:kn,ZodNativeEnum:Hn,ZodEffects:jn,ZodOptional:Un,ZodNullable:Kn,ZodDiscriminatedUnion:yo,ZodBranded:$n,ZodCatch:Gn,ZodPipeline:Wn,ZodLazy:Jn,ZodReadonly:_n,[_]:Qn,[te]:Xn},De=({schema:e,...t})=>se({schema:e,rules:ei,onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),...t});var lt=class{program=[];usage=[];registry={};paths=[];aliases={};ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return t in this.aliases?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=Oe(r,t),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=Fe,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){ie({routing:t,onEndpoint:(x,P,C)=>{let N={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},de=z(C,P,"input"),ho=De({...N,schema:x.getSchema("input"),isResponse:!1}),Re=i?z(C,P,"positive.response"):void 0,$t=x.getSchema("positive"),_t=i?De({...N,isResponse:!0,schema:$t}):void 0,Pe=i?z(C,P,"negative.response"):void 0,Gt=x.getSchema("negative"),Wt=i?De({...N,isResponse:!0,schema:Gt}):void 0,Yt=z(C,P,"response"),xo=Re&&Pe?n.createUnionTypeNode([n.createTypeReferenceNode(Re),n.createTypeReferenceNode(Pe)]):De({...N,isResponse:!0,schema:$t.or(Gt)});this.program.push(Oe(ho,de)),_t&&Re&&this.program.push(Oe(_t,Re)),Wt&&Pe&&this.program.push(Oe(Wt,Pe)),this.program.push(Oe(xo,Yt)),C!=="options"&&(this.paths.push(P),this.registry[`${C} ${P}`]={input:de,positive:Re,negative:Pe,response:Yt,isJson:x.getMimeTypes("positive").includes(U),tags:x.getTags()})}}),this.program.unshift(...Object.values(this.aliases)),this.program.push(Kt(this.ids.pathType,this.paths)),this.program.push(Kt(this.ids.methodType,uo)),this.program.push(dt(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.default.SyntaxKind.ExtendsKeyword,[Ut(this.ids.methodPathType,w.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input"}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive"},{id:this.ids.negResponseInterface,kind:"negative"}),this.interfaces.push({id:this.ids.responseInterface,kind:"response"});for(let{id:x,kind:P}of this.interfaces)this.program.push(mo(x,a,Object.keys(this.registry).map(C=>{let N=this.registry[C][P];return N?io(C,N):void 0}).filter(C=>C!==void 0)));if(r==="types")return;let p=n.createVariableStatement(W,Y(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(Object.keys(this.registry).filter(x=>this.registry[x].isJson).map(x=>n.createPropertyAssignment(`"${x}"`,n.createTrue()))))),d=n.createVariableStatement(W,Y(this.ids.endpointTagsConst,n.createObjectLiteralExpression(Object.keys(this.registry).map(x=>n.createPropertyAssignment(`"${x}"`,n.createArrayLiteralExpression(this.registry[x].tags.map(P=>n.createStringLiteral(P)))))))),m=dt(this.ids.providerType,n.createFunctionTypeNode(lo({M:this.ids.methodType,P:this.ids.pathType}),pt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Ht)}),po(this.ids.responseInterface,Ht))),u=dt(this.ids.implementationType,n.createFunctionTypeNode(void 0,pt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.default.SyntaxKind.StringKeyword),params:Ut(w.default.SyntaxKind.StringKeyword,w.default.SyntaxKind.AnyKeyword)}),co())),l=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Se)]),y=Bt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[l,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),T=Bt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[l]),w.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),S=ao(this.ids.clientClass,no([at(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),oo)]),[so(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Ft([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,y,T]),!0))]);this.program.push(p,d,m,u,S);let A=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),h=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(U))]),void 0,this.ids.undefinedValue)),b=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),q=n.createVariableStatement(void 0,Y(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Se)]),n.createObjectLiteralExpression([A,h,b])])))),ke=n.createVariableStatement(void 0,Y(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ae=n.createVariableStatement(void 0,Y(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Se)])))),[pe,Le]=["json","text"].map(x=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,x),void 0,void 0))),je=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(kt,[n.createTemplateSpan(this.ids.methodParameter,Lt),n.createTemplateSpan(this.ids.pathParameter,Se)]),w.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([pe])),ut=n.createVariableStatement(W,Y(this.ids.exampleImplementationConst,Ft([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([ke,Ae,q,je,Le]),!0),n.createTypeReferenceNode(this.ids.implementationType))),He=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),L=n.createVariableStatement(void 0,Y(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(ut,L,He)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Vt(r,t)).join(`
18
+ `;var It=({app:e,rootLogger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log(Cr()),t.debug("Running","v17.7.0 (CJS)"),ie({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,m)=>{let u=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;u.info(`${d.method}: ${s}`),await i.execute({request:d,response:m,logger:u,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}})};var Ze=R(require("http-errors"),1);var Ir=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:(0,Ze.isHttpError)(o)?o:(0,Ze.default)(400,le(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},Er=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=(0,Ze.default)(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Ge({response:i,logger:a,error:new Q(le(p).message,s)})}},wr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()};var Mr=async e=>{let t=Ar(e.logger)?tt({...e.logger,winston:await ne("winston")}):e.logger,r=e.errorHandler||ye,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=Er(i),a=Ir(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},Nr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o}=await Mr(e);return It({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},vr=async(e,t)=>{let r=(0,Et.default)().disable("x-powered-by");if(e.server.compression){let d=await ne("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||Et.default.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=await Mr(e);if(e.server.upload){let d=await ne("express-fileupload"),{limitError:m,beforeUpload:u,...l}={...typeof e.server.upload=="object"&&e.server.upload};u&&u({app:r,logger:o}),r.use(d({...l,abortOnLimit:!1,parseNested:!0,logger:{log:o.debug.bind(o)}})),m&&r.use(wr(m))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},m)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),m()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),It({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,m)=>d.listen(m,()=>{o.info("Listening",m)}),p={httpServer:a(zr.default.createServer(r),e.server.listen),httpsServer:e.https?a(Zr.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};var eo=R(require("assert/strict"),1),to=require("openapi3-ts/oas31");var F=R(require("assert/strict"),1),G=require("openapi3-ts/oas31"),c=require("ramda"),O=require("zod");var wt=require("zod");var rt=e=>!isNaN(e.getTime()),ot=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Me="DateIn",Dr=()=>E(Me,wt.z.string().regex(ot).transform(e=>new Date(e)).pipe(wt.z.date().refine(rt)));var kr=require("zod");var Ne="DateOut",Lr=()=>E(Ne,kr.z.date().refine(rt).transform(e=>e.toISOString()));var se=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Ee(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,m=a?a({schema:e,...p,next:l=>se({schema:l,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),u=t&&t({schema:e,prev:m,...p});return u?{...m,...u}:m};var jr=50,Ur="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",jo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Kr=/:([A-Za-z0-9_]+)/g,Fr=e=>e.match(Kr)?.map(t=>t.slice(1))||[],Br=e=>e.replace(Kr,t=>`{${t.slice(1)}}`),Ho=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),Uo=({schema:{_def:{innerType:e}},next:t})=>t(e),Ko=()=>({format:"any"}),Fo=e=>((0,F.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Bo=({schema:e})=>({type:"string",format:e instanceof O.z.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),qo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Vo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),$o=e=>{let[t,r]=e.filter(i=>!(0,G.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,F.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,c.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,c.concat)(i,s):i===s?s:F.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,c.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([i,s])=>(0,c.mergeDeepRight)(i,s))),o},_o=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return $o(o)}catch{}return{allOf:o}},Go=({schema:e,next:t})=>t(e.unwrap()),Wo=({schema:e,next:t})=>t(e._def.innerType),Yo=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,G.isReferenceObject)(r)||(r.type=Vr(r)),r},qr=e=>{let t=(0,c.toLower)((0,c.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Hr=({schema:e})=>({type:qr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Jo=({schema:{value:e}})=>({type:qr(e),const:e}),Qo=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ie(p)?p instanceof O.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=nt({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},Xo=()=>({type:"null"}),en=e=>((0,F.default)(!e.isResponse,new I({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:ot.source,externalDocs:{url:Ur}}),tn=e=>((0,F.default)(e.isResponse,new I({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ur}}),rn=e=>F.default.fail(new I({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),on=()=>({type:"boolean"}),nn=()=>({type:"integer",format:"bigint"}),sn=e=>e.every(t=>t instanceof O.z.ZodLiteral),an=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof O.z.ZodEnum||e instanceof O.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=nt({schema:O.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof O.z.ZodLiteral)return{type:"object",properties:nt({schema:O.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof O.z.ZodUnion&&sn(e.options)){let o=(0,c.map)(s=>`${s.value}`,e.options),i=(0,c.fromPairs)((0,c.xprod)(o,[t]));return{type:"object",properties:nt({schema:O.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},pn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},dn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),cn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:m,isDatetime:u,_def:{checks:l}}})=>{let y=l.find(b=>b.kind==="regex"),T=l.find(b=>b.kind==="datetime"),S=y?y.regex:T?T.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,A={type:"string"},h={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:m};for(let b in h)if(h[b]){A.format=b;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),S&&(A.pattern=S.source),A},mn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},nt=({schema:{shape:e},next:t})=>(0,c.map)(t,e),ln=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return jo?.[t]},Vr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},un=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,G.isReferenceObject)(o)){let s=Be(e,ln(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(O.z.any())}if(!t&&i.type==="preprocess"&&!(0,G.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},fn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),yn=({schema:e,next:t})=>t(e.unwrap()),gn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},hn=({next:e,schema:t})=>e(t.shape.raw),$r=e=>e.length?(0,c.zipObj)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e)):void 0,_r=(e,t,r=[])=>(0,c.pipe)(K,(0,c.map)((0,c.when)((0,c.both)(Z,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),$r)({schema:e,variant:t?"parsed":"original",validate:!0}),xn=(e,t)=>(0,c.pipe)(K,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),$r)({schema:e,variant:"original",validate:!0}),ve=(e,t)=>e instanceof O.z.ZodObject?e:e instanceof O.z.ZodUnion||e instanceof O.z.ZodDiscriminatedUnion?Array.from(e.options.values()).map(r=>ve(r,t)).reduce((r,o)=>r.merge(o.partial()),O.z.object({})):e instanceof O.z.ZodEffects?((0,F.default)(e._def.effect.type==="refinement",t),ve(e._def.schema,t)):ve(e._def.left,t).merge(ve(e._def.right,t)),Gr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=ve(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=Fr(e),l=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=h=>y&&u.includes(h),A=h=>T&&ht(h);return Object.keys(m).filter(h=>l||S(h)).map(h=>{let b=se({schema:m[h],isResponse:!1,rules:Zt,onEach:Mt,onMissing:Nt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),q=p==="components"?a(z(d,h),b):b;return{name:h,in:S(h)?"path":A(h)?"header":"query",required:!m[h].isOptional(),description:b.description||d,schema:q,examples:xn(r,h)}})},Zt={ZodString:cn,ZodNumber:mn,ZodBigInt:nn,ZodBoolean:on,ZodNull:Xo,ZodArray:pn,ZodTuple:dn,ZodRecord:an,ZodObject:Qo,ZodLiteral:Jo,ZodIntersection:_o,ZodUnion:qo,ZodAny:Ko,ZodDefault:Ho,ZodEnum:Hr,ZodNativeEnum:Hr,ZodEffects:un,ZodOptional:Go,ZodNullable:Yo,ZodDiscriminatedUnion:Vo,ZodBranded:yn,ZodDate:rn,ZodCatch:Uo,ZodPipeline:fn,ZodLazy:gn,ZodReadonly:Wo,[_]:Bo,[ze]:Fo,[Ne]:tn,[Me]:en,[te]:hn},Mt=({schema:e,isResponse:t,prev:r})=>{if((0,G.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof O.z.ZodLazy,s=r.type!==void 0,a=t&&Ie(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),m={};return o&&(m.description=o),p&&(m.type=Vr(r)),d.length&&(m.examples=Array.from(d)),m},Nt=({schema:e,...t})=>F.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),zt=(e,t)=>{if((0,G.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,c.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,c.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>zt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>zt(o,t))),r},Wr=e=>(0,G.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),Yr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:m,statusCode:u,description:l=`${e.toUpperCase()} ${t} ${Tt(i)} response ${m?u:""}`.trim()})=>{let y=Wr(se({schema:r,isResponse:!0,rules:Zt,onEach:Mt,onMissing:Nt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(z(l),y):y,examples:_r(r,!0)};return{description:l,content:(0,c.fromPairs)((0,c.xprod)(o,[T]))}},Tn=()=>({type:"http",scheme:"basic"}),bn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Sn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},On=({name:e})=>({type:"apiKey",in:"header",name:e}),An=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Rn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Pn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),Jr=(e,t)=>{let r={basic:Tn,bearer:bn,input:Sn,header:On,cookie:An,openid:Rn,oauth2:Pn};return We(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?(0,c.mergeAll)((0,c.map)(({name:r,scopes:o})=>(0,c.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(At(e)):it({or:[e]}),Qr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let m=Fr(t),u=Wr(zt(se({schema:r,isResponse:!1,rules:Zt,onEach:Mt,onMissing:Nt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),m)),l={schema:p==="components"?a(z(d),u):u,examples:_r(r,!1,m)};return{description:d,content:(0,c.fromPairs)((0,c.xprod)(o,[l]))}},Xr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),vt=e=>e.length<=jr?e:e.slice(0,jr-1)+"\u2026";var st=class extends to.OpenApiBuilder{lastSecuritySchemaIds={};lastOperationIdSuffixes={};makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){if(o)return(0,eo.default)(!(o in this.lastOperationIdSuffixes),new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),this.lastOperationIdSuffixes[o]=1,o;let i=z(r,t);return i in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[i]++,`${i}${this.lastOperationIdSuffixes[i]}`):(this.lastOperationIdSuffixes[i]=1,i)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let o in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:m=Fe}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});ie({routing:t,onEndpoint:(l,y,T)=>{let S=T,A={path:y,method:S,endpoint:l,composition:d,serializer:m,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,b]=["short","long"].map(l.getDescription.bind(l)),q=h?vt(h):p&&b?vt(b):void 0,ke=l.getTags(),Ae=r.inputSources?.[S]||yt[S],pe=this.ensureUniqOperationId(y,S,l.getOperationId(S)),Le=Gr({...A,inputSources:Ae,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),je={};for(let L of["positive","negative"]){let x=l.getResponses(L);for(let{mimeTypes:P,schema:C,statusCodes:N}of x)for(let de of N)je[de]=Yr({...A,variant:L,schema:C,mimeTypes:P,statusCode:de,hasMultipleStatusCodes:x.length>1||N.length>1,description:a?.[`${L}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:de})})}let ut=Ae.includes("body")?Qr({...A,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,He=it(We(Jr(l.getSecurity(),Ae),L=>{let x=this.ensureUniqSecuritySchemaName(L),P=["oauth2","openIdConnect"].includes(L.type)?l.getScopes():[];return this.addSecurityScheme(x,L),{name:x,scopes:P}}));this.addPath(Br(y),{[S]:{operationId:pe,summary:q,description:b,tags:ke.length>0?ke:void 0,parameters:Le.length>0?Le:void 0,requestBody:ut,security:He.length>0?He:void 0,responses:je}})}}),this.rootDoc.tags=r.tags?Xr(r.tags):[]}};var Dt=R(require("http"),1);var Cn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>U),...t}),In=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Dt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Dt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},En=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),ro=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Pr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Cn({fnMethod:a,requestProps:t}),d=In({fnMethod:a,responseProps:r}),m=En({fnMethod:a,loggerProps:i}),u={cors:!1,logger:m,...o};return await e.execute({request:p,response:d,config:u,logger:m}),{requestMock:p,responseMock:d,loggerMock:m}};var w=R(require("typescript"),1);var k=R(require("typescript"),1),be=require("ramda"),n=k.default.factory,W=[n.createModifier(k.default.SyntaxKind.ExportKeyword)],wn=[n.createModifier(k.default.SyntaxKind.AsyncKeyword)],zn=[n.createModifier(k.default.SyntaxKind.PublicKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],oo=[n.createModifier(k.default.SyntaxKind.ProtectedKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],kt=n.createTemplateHead(""),Se=n.createTemplateTail(""),Lt=n.createTemplateMiddle(" "),jt=e=>n.createTemplateLiteralType(kt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Se:Lt))),Ht=jt(["M","P"]),at=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),pt=(e,t)=>(0,be.chain)(([r,o])=>[at(n.createIdentifier(r),o,t)],(0,be.toPairs)(e)),Ut=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),no=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),io=(e,t)=>n.createPropertySignature(void 0,`"${e}"`,void 0,n.createTypeReferenceNode(t)),Y=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.default.NodeFlags.Const),Kt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),dt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,t),so=(e,t,r)=>n.createPropertyDeclaration(zn,e,void 0,t,r),ao=(e,t,r)=>n.createClassDeclaration(W,e,void 0,void 0,[t,...r]),po=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),co=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.default.SyntaxKind.AnyKeyword)]),mo=(e,t,r)=>n.createInterfaceDeclaration(W,e,void 0,t,r),lo=e=>(0,be.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,be.toPairs)(e)),Ft=(e,t,r)=>n.createArrowFunction(r?wn:void 0,void 0,e.map(o=>at(o)),void 0,void 0,t),Bt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,pt({acc:void 0,key:void 0}),void 0,void 0,t),r]);var uo=["get","post","put","delete","patch"];var g=R(require("typescript"),1),mt=require("zod");var B=R(require("typescript"),1),{factory:ct}=B.default,qt=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Oe=(e,t,r)=>{let o=ct.createTypeAliasDeclaration(void 0,ct.createIdentifier(t),void 0,e);return r&&qt(o,r),o},Vt=(e,t)=>{let r=B.default.createSourceFile("print.ts","",B.default.ScriptTarget.Latest,!1,B.default.ScriptKind.TS);return B.default.createPrinter(t).printNode(B.default.EmitHint.Unspecified,e,r)},Zn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fo=e=>Zn.test(e)?ct.createIdentifier(e):ct.createStringLiteral(e);var{factory:f}=g.default,Mn={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},Nn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),vn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ie(a)?a instanceof mt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,fo(s),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&qt(d,a.description),d});return f.createTypeLiteralNode(i)},Dn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),kn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),yo=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),Ln=e=>Mn?.[e.kind],jn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Be(e,Ln(o)),a={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||g.default.SyntaxKind.AnyKeyword)}return o},Hn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Un=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Kn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Fn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Bn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),qn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Vn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),$n=({next:e,schema:t})=>e(t.unwrap()),_n=({next:e,schema:t})=>e(t._def.innerType),Gn=({next:e,schema:t})=>e(t._def.innerType),Wn=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),Yn=()=>f.createLiteralTypeNode(f.createNull()),Jn=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,f.createLiteralTypeNode(f.createNull())),t(s,r(i.schema)))},Qn=({schema:e})=>{let t=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),r=f.createTypeReferenceNode("Buffer"),o=f.createUnionTypeNode([t,r]);return e instanceof mt.z.ZodString?t:e instanceof mt.z.ZodUnion?o:r},Xn=({next:e,schema:t})=>e(t.shape.raw),ei={ZodString:ae(g.default.SyntaxKind.StringKeyword),ZodNumber:ae(g.default.SyntaxKind.NumberKeyword),ZodBigInt:ae(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:ae(g.default.SyntaxKind.BooleanKeyword),ZodAny:ae(g.default.SyntaxKind.AnyKeyword),[Me]:ae(g.default.SyntaxKind.StringKeyword),[Ne]:ae(g.default.SyntaxKind.StringKeyword),ZodNull:Yn,ZodArray:Dn,ZodTuple:Fn,ZodRecord:Bn,ZodObject:vn,ZodLiteral:Nn,ZodIntersection:qn,ZodUnion:yo,ZodDefault:Vn,ZodEnum:kn,ZodNativeEnum:Hn,ZodEffects:jn,ZodOptional:Un,ZodNullable:Kn,ZodDiscriminatedUnion:yo,ZodBranded:$n,ZodCatch:Gn,ZodPipeline:Wn,ZodLazy:Jn,ZodReadonly:_n,[_]:Qn,[te]:Xn},De=({schema:e,...t})=>se({schema:e,rules:ei,onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),...t});var lt=class{program=[];usage=[];registry={};paths=[];aliases={};ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return t in this.aliases?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=Oe(r,t),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=Fe,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){ie({routing:t,onEndpoint:(x,P,C)=>{let N={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},de=z(C,P,"input"),ho=De({...N,schema:x.getSchema("input"),isResponse:!1}),Re=i?z(C,P,"positive.response"):void 0,$t=x.getSchema("positive"),_t=i?De({...N,isResponse:!0,schema:$t}):void 0,Pe=i?z(C,P,"negative.response"):void 0,Gt=x.getSchema("negative"),Wt=i?De({...N,isResponse:!0,schema:Gt}):void 0,Yt=z(C,P,"response"),xo=Re&&Pe?n.createUnionTypeNode([n.createTypeReferenceNode(Re),n.createTypeReferenceNode(Pe)]):De({...N,isResponse:!0,schema:$t.or(Gt)});this.program.push(Oe(ho,de)),_t&&Re&&this.program.push(Oe(_t,Re)),Wt&&Pe&&this.program.push(Oe(Wt,Pe)),this.program.push(Oe(xo,Yt)),C!=="options"&&(this.paths.push(P),this.registry[`${C} ${P}`]={input:de,positive:Re,negative:Pe,response:Yt,isJson:x.getMimeTypes("positive").includes(U),tags:x.getTags()})}}),this.program.unshift(...Object.values(this.aliases)),this.program.push(Kt(this.ids.pathType,this.paths)),this.program.push(Kt(this.ids.methodType,uo)),this.program.push(dt(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.default.SyntaxKind.ExtendsKeyword,[Ut(this.ids.methodPathType,w.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input"}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive"},{id:this.ids.negResponseInterface,kind:"negative"}),this.interfaces.push({id:this.ids.responseInterface,kind:"response"});for(let{id:x,kind:P}of this.interfaces)this.program.push(mo(x,a,Object.keys(this.registry).map(C=>{let N=this.registry[C][P];return N?io(C,N):void 0}).filter(C=>C!==void 0)));if(r==="types")return;let p=n.createVariableStatement(W,Y(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(Object.keys(this.registry).filter(x=>this.registry[x].isJson).map(x=>n.createPropertyAssignment(`"${x}"`,n.createTrue()))))),d=n.createVariableStatement(W,Y(this.ids.endpointTagsConst,n.createObjectLiteralExpression(Object.keys(this.registry).map(x=>n.createPropertyAssignment(`"${x}"`,n.createArrayLiteralExpression(this.registry[x].tags.map(P=>n.createStringLiteral(P)))))))),m=dt(this.ids.providerType,n.createFunctionTypeNode(lo({M:this.ids.methodType,P:this.ids.pathType}),pt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Ht)}),po(this.ids.responseInterface,Ht))),u=dt(this.ids.implementationType,n.createFunctionTypeNode(void 0,pt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.default.SyntaxKind.StringKeyword),params:Ut(w.default.SyntaxKind.StringKeyword,w.default.SyntaxKind.AnyKeyword)}),co())),l=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Se)]),y=Bt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[l,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),T=Bt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[l]),w.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),S=ao(this.ids.clientClass,no([at(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),oo)]),[so(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Ft([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,y,T]),!0))]);this.program.push(p,d,m,u,S);let A=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),h=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(U))]),void 0,this.ids.undefinedValue)),b=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),q=n.createVariableStatement(void 0,Y(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Se)]),n.createObjectLiteralExpression([A,h,b])])))),ke=n.createVariableStatement(void 0,Y(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ae=n.createVariableStatement(void 0,Y(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Se)])))),[pe,Le]=["json","text"].map(x=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,x),void 0,void 0))),je=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(kt,[n.createTemplateSpan(this.ids.methodParameter,Lt),n.createTemplateSpan(this.ids.pathParameter,Se)]),w.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([pe])),ut=n.createVariableStatement(W,Y(this.ids.exampleImplementationConst,Ft([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([ke,Ae,q,je,Le]),!0),n.createTypeReferenceNode(this.ids.implementationType))),He=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),L=n.createVariableStatement(void 0,Y(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(ut,L,He)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Vt(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.printUsage(t),o=r&&w.default.addSyntheticLeadingComment(w.default.addSyntheticLeadingComment(n.createEmptyStatement(),w.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),w.default.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.program.concat(o||[]).map((i,s)=>Vt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ Original error: ${e.originalError.message}.`:""))};import{chain as Oo}from"ramda
15
15
  \x1B[38;5;117m 888\x1B[3m Proudly supports transgender community.\x1B[23m\x1B[39m
16
16
  \x1B[38;5;117m\x1B[3mfor Tonya \x1B[23m888\x1B[3m Start your API server with I/O schema validation and custom middlewares in minutes.\x1B[23m\x1B[39m
17
17
  \x1B[90m\x1B[3m Thank you for choosing Express Zod API for your project.\x1B[23m\x1B[39m
18
- `;var ht=({app:e,rootLogger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log(ir()),t.debug("Running","v17.7.0-beta1 (ESM)"),X({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let l=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;l.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:l,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}})};import sr,{isHttpError as Zo}from"http-errors";var ar=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:Zo(o)?o:sr(400,pe(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},pr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=sr(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Ke({response:i,logger:a,error:new G(pe(p).message,s)})}},dr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()};var mr=async e=>{let t=rr(e.logger)?gt({...e.logger,winston:await Q("winston")}):e.logger,r=e.errorHandler||Se,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=pr(i),a=ar(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},vo=async(e,t)=>{let{rootLogger:r,notFoundHandler:o}=await mr(e);return ht({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Do=async(e,t)=>{let r=cr().disable("x-powered-by");if(e.server.compression){let d=await Q("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||cr.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=await mr(e);if(e.server.upload){let d=await Q("express-fileupload"),{limitError:c,beforeUpload:l,...m}={...typeof e.server.upload=="object"&&e.server.upload};l&&l({app:r,logger:o}),r.use(d({...m,abortOnLimit:!1,parseNested:!0,logger:{log:o.debug.bind(o)}})),c&&r.use(dr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),ht({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(Mo.createServer(r),e.server.listen),httpsServer:e.https?a(No.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};import Fn from"assert/strict";import{OpenApiBuilder as Bn}from"openapi3-ts/oas31";import B from"assert/strict";import{isReferenceObject as te}from"openapi3-ts/oas31";import{both as Lo,complement as jo,concat as Ho,type as Uo,filter as Ko,fromPairs as _e,has as Fo,isNil as Bo,map as le,mergeAll as qo,mergeDeepRight as Vo,mergeDeepWith as $o,objOf as hr,omit as Ge,pipe as xr,pluck as _o,range as Go,reject as Wo,toLower as Yo,union as Jo,when as Qo,xprod as We,zipObj as Xo}from"ramda";import{z as S}from"zod";import{z as lr}from"zod";var qe=e=>!isNaN(e.getTime()),Ve=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Pe="DateIn",ur=()=>P(Pe,lr.string().regex(Ve).transform(e=>new Date(e)).pipe(lr.date().refine(qe)));import{z as ko}from"zod";var Ce="DateOut",fr=()=>P(Ce,ko.date().refine(qe).transform(e=>e.toISOString()));var ee=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Te(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:m=>ee({schema:m,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),l=t&&t({schema:e,prev:c,...p});return l?{...c,...l}:c};var yr=50,Tr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",en={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},br=/:([A-Za-z0-9_]+)/g,Sr=e=>e.match(br)?.map(t=>t.slice(1))||[],Or=e=>e.replace(br,t=>`{${t.slice(1)}}`),tn=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),rn=({schema:{_def:{innerType:e}},next:t})=>t(e),on=()=>({format:"any"}),nn=e=>(B(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),sn=({schema:e})=>({type:"string",format:e instanceof S.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),an=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),pn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),dn=e=>{let[t,r]=e.filter(i=>!te(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));B(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=$o((i,s)=>Array.isArray(i)&&Array.isArray(s)?Ho(i,s):i===s?s:B.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Jo(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=W(t.examples||[],r.examples||[],([i,s])=>Vo(i,s))),o},cn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return dn(o)}catch{}return{allOf:o}},mn=({schema:e,next:t})=>t(e.unwrap()),ln=({schema:e,next:t})=>t(e._def.innerType),un=({schema:e,next:t})=>{let r=t(e.unwrap());return te(r)||(r.type=Rr(r)),r},Ar=e=>{let t=Yo(Uo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},gr=({schema:e})=>({type:Ar(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),fn=({schema:{value:e}})=>({type:Ar(e),const:e}),yn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&xe(p)?p instanceof S.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=$e({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},gn=()=>({type:"null"}),hn=e=>(B(!e.isResponse,new C({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:Ve.source,externalDocs:{url:Tr}}),xn=e=>(B(e.isResponse,new C({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Tr}}),Tn=e=>B.fail(new C({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),bn=()=>({type:"boolean"}),Sn=()=>({type:"integer",format:"bigint"}),On=e=>e.every(t=>t instanceof S.ZodLiteral),An=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=$e({schema:S.object(_e(We(o,[t]))),...r}),i.required=o),i}if(e instanceof S.ZodLiteral)return{type:"object",properties:$e({schema:S.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof S.ZodUnion&&On(e.options)){let o=le(s=>`${s.value}`,e.options),i=_e(We(o,[t]));return{type:"object",properties:$e({schema:S.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},Rn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},Pn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Cn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:m}}})=>{let f=m.find(T=>T.kind==="regex"),x=m.find(T=>T.kind==="datetime"),b=f?f.regex:x?x.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,O={type:"string"},g={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let T in g)if(g[T]){O.format=T;break}return r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),b&&(O.pattern=b.source),O},In=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},$e=({schema:{shape:e},next:t})=>le(t,e),En=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return en?.[t]},Rr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},wn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!te(o)){let s=ke(e,En(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.any())}if(!t&&i.type==="preprocess"&&!te(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},zn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Zn=({schema:e,next:t})=>t(e.unwrap()),Mn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},Nn=({next:e,schema:t})=>e(t.shape.raw),Pr=e=>e.length?Xo(Go(1,e.length+1).map(t=>`example${t}`),le(hr("value"),e)):void 0,Cr=(e,t,r=[])=>xr(K,le(Qo(Lo(E,jo(Array.isArray)),Ge(r))),Pr)({schema:e,variant:t?"parsed":"original",validate:!0}),vn=(e,t)=>xr(K,Ko(Fo(t)),_o(t),Pr)({schema:e,variant:"original",validate:!0}),Ie=(e,t)=>e instanceof S.ZodObject?e:e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?Array.from(e.options.values()).map(r=>Ie(r,t)).reduce((r,o)=>r.merge(o.partial()),S.object({})):e instanceof S.ZodEffects?(B(e._def.effect.type==="refinement",t),Ie(e._def.schema,t)):Ie(e._def.left,t).merge(Ie(e._def.right,t)),Ir=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=Ie(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=Sr(e),m=o.includes("query"),f=o.includes("params"),x=o.includes("headers"),b=g=>f&&l.includes(g),O=g=>x&&it(g);return Object.keys(c).filter(g=>m||b(g)).map(g=>{let T=ee({schema:c[g],isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:a,path:e,method:t}),L=p==="components"?a(I(d,g),T):T;return{name:g,in:b(g)?"path":O(g)?"header":"query",required:!c[g].isOptional(),description:T.description||d,schema:L,examples:vn(r,g)}})},Tt={ZodString:Cn,ZodNumber:In,ZodBigInt:Sn,ZodBoolean:bn,ZodNull:gn,ZodArray:Rn,ZodTuple:Pn,ZodRecord:An,ZodObject:yn,ZodLiteral:fn,ZodIntersection:cn,ZodUnion:an,ZodAny:on,ZodDefault:tn,ZodEnum:gr,ZodNativeEnum:gr,ZodEffects:wn,ZodOptional:mn,ZodNullable:un,ZodDiscriminatedUnion:pn,ZodBranded:Zn,ZodDate:Tn,ZodCatch:rn,ZodPipeline:zn,ZodLazy:Mn,ZodReadonly:ln,[F]:sn,[be]:nn,[Ce]:xn,[Pe]:hn,[Y]:Nn},bt=({schema:e,isResponse:t,prev:r})=>{if(te(r))return{};let{description:o}=e,i=e instanceof S.ZodLazy,s=r.type!==void 0,a=t&&xe(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Rr(r)),d.length&&(c.examples=Array.from(d)),c},St=({schema:e,...t})=>B.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),xt=(e,t)=>{if(te(e))return e;let r={...e};return r.properties&&(r.properties=Ge(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Ge(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>xt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>xt(o,t))),r},Er=e=>te(e)?e:Ge(["examples"],e),wr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,description:m=`${e.toUpperCase()} ${t} ${at(i)} response ${c?l:""}`.trim()})=>{let f=Er(ee({schema:r,isResponse:!0,rules:Tt,onEach:bt,onMissing:St,serializer:s,getRef:a,makeRef:p,path:t,method:e})),x={schema:d==="components"?p(I(m),f):f,examples:Cr(r,!0)};return{description:m,content:_e(We(o,[x]))}},Dn=()=>({type:"http",scheme:"basic"}),kn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ln=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},jn=({name:e})=>({type:"apiKey",in:"header",name:e}),Hn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Un=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Kn=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),Wo(Bo,e))}),zr=(e,t)=>{let r={basic:Dn,bearer:kn,input:Ln,header:jn,cookie:Hn,openid:Un,oauth2:Kn};return Fe(e,o=>r[o.type](o,t))},Ye=e=>"or"in e?e.or.map(t=>"and"in t?qo(le(({name:r,scopes:o})=>hr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?Ye(mt(e)):Ye({or:[e]}),Zr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Sr(t),l=Er(xt(ee({schema:r,isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),m={schema:p==="components"?a(I(d),l):l,examples:Cr(r,!1,c)};return{description:d,content:_e(We(o,[m]))}},Mr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Ot=e=>e.length<=yr?e:e.slice(0,yr-1)+"\u2026";var At=class extends Bn{lastSecuritySchemaIds={};lastOperationIdSuffixes={};makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){if(o)return Fn(!(o in this.lastOperationIdSuffixes),new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),this.lastOperationIdSuffixes[o]=1,o;let i=I(r,t);return i in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[i]++,`${i}${this.lastOperationIdSuffixes[i]}`):(this.lastOperationIdSuffixes[i]=1,i)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let o in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=De}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});X({routing:t,onEndpoint:(m,f,x)=>{let b=x,O={path:f,method:b,endpoint:m,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[g,T]=["short","long"].map(m.getDescription.bind(m)),L=g?Ot(g):p&&T?Ot(T):void 0,we=m.getTags(),ye=r.inputSources?.[b]||ot[b],oe=this.ensureUniqOperationId(f,b,m.getOperationId(b)),ze=Ir({...O,inputSources:ye,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:f,operationId:oe})}),Ze={};for(let N of["positive","negative"]){let h=m.getResponses(N);for(let{mimeTypes:A,schema:R,statusCodes:z}of h)for(let ne of z)Ze[ne]=wr({...O,variant:N,schema:R,mimeTypes:A,statusCode:ne,hasMultipleStatusCodes:h.length>1||z.length>1,description:a?.[`${N}Response`]?.call(null,{method:b,path:f,operationId:oe,statusCode:ne})})}let tt=ye.includes("body")?Zr({...O,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:f,operationId:oe})}):void 0,Me=Ye(Fe(zr(m.getSecurity(),ye),N=>{let h=this.ensureUniqSecuritySchemaName(N),A=["oauth2","openIdConnect"].includes(N.type)?m.getScopes():[];return this.addSecurityScheme(h,N),{name:h,scopes:A}}));this.addPath(Or(f),{[b]:{operationId:oe,summary:L,description:T,tags:we.length>0?we:void 0,parameters:ze.length>0?ze:void 0,requestBody:tt,security:Me.length>0?Me:void 0,responses:Ze}})}}),this.rootDoc.tags=r.tags?Mr(r.tags):[]}};import Nr from"http";var qn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>v),...t}),Vn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Nr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Nr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},$n=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),_n=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await or([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=qn({fnMethod:a,requestProps:t}),d=Vn({fnMethod:a,responseProps:r}),c=$n({fnMethod:a,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:l,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import w from"typescript";import k from"typescript";import{chain as vr,toPairs as Dr}from"ramda";var n=k.factory,q=[n.createModifier(k.SyntaxKind.ExportKeyword)],Gn=[n.createModifier(k.SyntaxKind.AsyncKeyword)],Wn=[n.createModifier(k.SyntaxKind.PublicKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],kr=[n.createModifier(k.SyntaxKind.ProtectedKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Rt=n.createTemplateHead(""),ue=n.createTemplateTail(""),Pt=n.createTemplateMiddle(" "),Ct=e=>n.createTemplateLiteralType(Rt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?ue:Pt))),It=Ct(["M","P"]),Je=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),Qe=(e,t)=>vr(([r,o])=>[Je(n.createIdentifier(r),o,t)],Dr(e)),Et=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Lr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),jr=(e,t)=>n.createPropertySignature(void 0,`"${e}"`,void 0,n.createTypeReferenceNode(t)),V=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.NodeFlags.Const),wt=(e,t)=>n.createTypeAliasDeclaration(q,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),Xe=(e,t)=>n.createTypeAliasDeclaration(q,e,void 0,t),Hr=(e,t,r)=>n.createPropertyDeclaration(Wn,e,void 0,t,r),Ur=(e,t,r)=>n.createClassDeclaration(q,e,void 0,void 0,[t,...r]),Kr=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Fr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.SyntaxKind.AnyKeyword)]),Br=(e,t,r)=>n.createInterfaceDeclaration(q,e,void 0,t,r),qr=e=>vr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Dr(e)),zt=(e,t,r)=>n.createArrowFunction(r?Gn:void 0,void 0,e.map(o=>Je(o)),void 0,void 0,t),Zt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,Qe({acc:void 0,key:void 0}),void 0,void 0,t),r]);var Vr=["get","post","put","delete","patch"];import y from"typescript";import{z as vt}from"zod";import $ from"typescript";var{factory:et}=$,Mt=(e,t)=>{$.addSyntheticLeadingComment(e,$.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},fe=(e,t,r)=>{let o=et.createTypeAliasDeclaration(void 0,et.createIdentifier(t),void 0,e);return r&&Mt(o,r),o},Nt=(e,t)=>{let r=$.createSourceFile("print.ts","",$.ScriptTarget.Latest,!1,$.ScriptKind.TS);return $.createPrinter(t).printNode($.EmitHint.Unspecified,e,r)},Yn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,$r=e=>Yn.test(e)?et.createIdentifier(e):et.createStringLiteral(e);var{factory:u}=y,Jn={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Qn=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Xn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&xe(a)?a instanceof vt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,$r(s),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Mt(d,a.description),d});return u.createTypeLiteralNode(i)},ei=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),ti=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),_r=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),ri=e=>Jn?.[e.kind],oi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,ri(o)),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||y.SyntaxKind.AnyKeyword)}return o},ni=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),ii=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},si=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),ai=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),pi=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),di=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),ci=({next:e,schema:t})=>e(t._def.innerType),re=e=>()=>u.createKeywordTypeNode(e),mi=({next:e,schema:t})=>e(t.unwrap()),li=({next:e,schema:t})=>e(t._def.innerType),ui=({next:e,schema:t})=>e(t._def.innerType),fi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),yi=()=>u.createLiteralTypeNode(u.createNull()),gi=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,u.createLiteralTypeNode(u.createNull())),t(s,r(i.schema)))},hi=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof vt.ZodString?t:e instanceof vt.ZodUnion?o:r},xi=({next:e,schema:t})=>e(t.shape.raw),Ti={ZodString:re(y.SyntaxKind.StringKeyword),ZodNumber:re(y.SyntaxKind.NumberKeyword),ZodBigInt:re(y.SyntaxKind.BigIntKeyword),ZodBoolean:re(y.SyntaxKind.BooleanKeyword),ZodAny:re(y.SyntaxKind.AnyKeyword),[Pe]:re(y.SyntaxKind.StringKeyword),[Ce]:re(y.SyntaxKind.StringKeyword),ZodNull:yi,ZodArray:ei,ZodTuple:ai,ZodRecord:pi,ZodObject:Xn,ZodLiteral:Qn,ZodIntersection:di,ZodUnion:_r,ZodDefault:ci,ZodEnum:ti,ZodNativeEnum:ni,ZodEffects:oi,ZodOptional:ii,ZodNullable:si,ZodDiscriminatedUnion:_r,ZodBranded:mi,ZodCatch:ui,ZodPipeline:fi,ZodLazy:gi,ZodReadonly:li,[F]:hi,[Y]:xi},Ee=({schema:e,...t})=>ee({schema:e,rules:Ti,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var Dt=class{program=[];usage=[];registry={};paths=[];aliases={};ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return t in this.aliases?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=fe(r,t),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=De,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){X({routing:t,onEndpoint:(h,A,R)=>{let z={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},ne=I(R,A,"input"),Gr=Ee({...z,schema:h.getSchema("input"),isResponse:!1}),ge=i?I(R,A,"positive.response"):void 0,kt=h.getSchema("positive"),Lt=i?Ee({...z,isResponse:!0,schema:kt}):void 0,he=i?I(R,A,"negative.response"):void 0,jt=h.getSchema("negative"),Ht=i?Ee({...z,isResponse:!0,schema:jt}):void 0,Ut=I(R,A,"response"),Wr=ge&&he?n.createUnionTypeNode([n.createTypeReferenceNode(ge),n.createTypeReferenceNode(he)]):Ee({...z,isResponse:!0,schema:kt.or(jt)});this.program.push(fe(Gr,ne)),Lt&&ge&&this.program.push(fe(Lt,ge)),Ht&&he&&this.program.push(fe(Ht,he)),this.program.push(fe(Wr,Ut)),R!=="options"&&(this.paths.push(A),this.registry[`${R} ${A}`]={input:ne,positive:ge,negative:he,response:Ut,isJson:h.getMimeTypes("positive").includes(v),tags:h.getTags()})}}),this.program.unshift(...Object.values(this.aliases)),this.program.push(wt(this.ids.pathType,this.paths)),this.program.push(wt(this.ids.methodType,Vr)),this.program.push(Xe(this.ids.methodPathType,Ct([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.SyntaxKind.ExtendsKeyword,[Et(this.ids.methodPathType,w.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input"}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive"},{id:this.ids.negResponseInterface,kind:"negative"}),this.interfaces.push({id:this.ids.responseInterface,kind:"response"});for(let{id:h,kind:A}of this.interfaces)this.program.push(Br(h,a,Object.keys(this.registry).map(R=>{let z=this.registry[R][A];return z?jr(R,z):void 0}).filter(R=>R!==void 0)));if(r==="types")return;let p=n.createVariableStatement(q,V(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(Object.keys(this.registry).filter(h=>this.registry[h].isJson).map(h=>n.createPropertyAssignment(`"${h}"`,n.createTrue()))))),d=n.createVariableStatement(q,V(this.ids.endpointTagsConst,n.createObjectLiteralExpression(Object.keys(this.registry).map(h=>n.createPropertyAssignment(`"${h}"`,n.createArrayLiteralExpression(this.registry[h].tags.map(A=>n.createStringLiteral(A)))))))),c=Xe(this.ids.providerType,n.createFunctionTypeNode(qr({M:this.ids.methodType,P:this.ids.pathType}),Qe({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),It)}),Kr(this.ids.responseInterface,It))),l=Xe(this.ids.implementationType,n.createFunctionTypeNode(void 0,Qe({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.SyntaxKind.StringKeyword),params:Et(w.SyntaxKind.StringKeyword,w.SyntaxKind.AnyKeyword)}),Fr())),m=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,ue)]),f=Zt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[m,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),x=Zt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[m]),w.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),b=Ur(this.ids.clientClass,Lr([Je(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),kr)]),[Hr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),zt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,f,x]),!0))]);this.program.push(p,d,c,l,b);let O=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),g=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(v))]),void 0,this.ids.undefinedValue)),T=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),L=n.createVariableStatement(void 0,V(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,ue)]),n.createObjectLiteralExpression([O,g,T])])))),we=n.createVariableStatement(void 0,V(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ye=n.createVariableStatement(void 0,V(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),ue)])))),[oe,ze]=["json","text"].map(h=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,h),void 0,void 0))),Ze=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Rt,[n.createTemplateSpan(this.ids.methodParameter,Pt),n.createTemplateSpan(this.ids.pathParameter,ue)]),w.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([oe])),tt=n.createVariableStatement(q,V(this.ids.exampleImplementationConst,zt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([we,ye,L,Ze,ze]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Me=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),N=n.createVariableStatement(void 0,V(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(tt,N,Me)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Nt(r,t)).join(`
18
+ `;var ht=({app:e,rootLogger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log(ir()),t.debug("Running","v17.7.0 (ESM)"),X({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,a,p)=>{e[a](s,async(d,c)=>{let l=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;l.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:l,config:r,siblingMethods:p})})},onStatic:(i,s)=>{e.use(i,s)}})};import sr,{isHttpError as Zo}from"http-errors";var ar=({errorHandler:e,rootLogger:t,getChildLogger:r})=>async(o,i,s,a)=>{if(!o)return a();e.handler({error:Zo(o)?o:sr(400,pe(o).message),request:i,response:s,input:null,output:null,options:{},logger:r?await r({request:i,parent:t}):t})},pr=({errorHandler:e,getChildLogger:t,rootLogger:r})=>async(o,i)=>{let s=sr(404,`Can not ${o.method} ${o.path}`),a=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:a,error:s,input:null,output:null,options:{}})}catch(p){Ke({response:i,logger:a,error:new G(pe(p).message,s)})}},dr=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()};var mr=async e=>{let t=rr(e.logger)?gt({...e.logger,winston:await Q("winston")}):e.logger,r=e.errorHandler||Se,{childLoggerProvider:o}=e,i={errorHandler:r,rootLogger:t,getChildLogger:o},s=pr(i),a=ar(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:a}},vo=async(e,t)=>{let{rootLogger:r,notFoundHandler:o}=await mr(e);return ht({app:e.app,routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Do=async(e,t)=>{let r=cr().disable("x-powered-by");if(e.server.compression){let d=await Q("compression");r.use(d(typeof e.server.compression=="object"?e.server.compression:void 0))}r.use(e.server.jsonParser||cr.json());let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=await mr(e);if(e.server.upload){let d=await Q("express-fileupload"),{limitError:c,beforeUpload:l,...m}={...typeof e.server.upload=="object"&&e.server.upload};l&&l({app:r,logger:o}),r.use(d({...m,abortOnLimit:!1,parseNested:!0,logger:{log:o.debug.bind(o)}})),c&&r.use(dr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()})),r.use(s),e.server.beforeRouting&&await e.server.beforeRouting({app:r,logger:o}),ht({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let a=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),p={httpServer:a(Mo.createServer(r),e.server.listen),httpsServer:e.https?a(No.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...p,logger:o}};import Fn from"assert/strict";import{OpenApiBuilder as Bn}from"openapi3-ts/oas31";import B from"assert/strict";import{isReferenceObject as te}from"openapi3-ts/oas31";import{both as Lo,complement as jo,concat as Ho,type as Uo,filter as Ko,fromPairs as _e,has as Fo,isNil as Bo,map as le,mergeAll as qo,mergeDeepRight as Vo,mergeDeepWith as $o,objOf as hr,omit as Ge,pipe as xr,pluck as _o,range as Go,reject as Wo,toLower as Yo,union as Jo,when as Qo,xprod as We,zipObj as Xo}from"ramda";import{z as S}from"zod";import{z as lr}from"zod";var qe=e=>!isNaN(e.getTime()),Ve=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Pe="DateIn",ur=()=>P(Pe,lr.string().regex(Ve).transform(e=>new Date(e)).pipe(lr.date().refine(qe)));import{z as ko}from"zod";var Ce="DateOut",fr=()=>P(Ce,ko.date().refine(qe).transform(e=>e.toISOString()));var ee=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Te(e,"kind")||e._def.typeName,a=s?r[s]:void 0,p=i,c=a?a({schema:e,...p,next:m=>ee({schema:m,...p,onEach:t,rules:r,onMissing:o})}):o({schema:e,...p}),l=t&&t({schema:e,prev:c,...p});return l?{...c,...l}:c};var yr=50,Tr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",en={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},br=/:([A-Za-z0-9_]+)/g,Sr=e=>e.match(br)?.map(t=>t.slice(1))||[],Or=e=>e.replace(br,t=>`{${t.slice(1)}}`),tn=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),rn=({schema:{_def:{innerType:e}},next:t})=>t(e),on=()=>({format:"any"}),nn=e=>(B(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),sn=({schema:e})=>({type:"string",format:e instanceof S.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),an=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),pn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),dn=e=>{let[t,r]=e.filter(i=>!te(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));B(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=$o((i,s)=>Array.isArray(i)&&Array.isArray(s)?Ho(i,s):i===s?s:B.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Jo(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=W(t.examples||[],r.examples||[],([i,s])=>Vo(i,s))),o},cn=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return dn(o)}catch{}return{allOf:o}},mn=({schema:e,next:t})=>t(e.unwrap()),ln=({schema:e,next:t})=>t(e._def.innerType),un=({schema:e,next:t})=>{let r=t(e.unwrap());return te(r)||(r.type=Rr(r)),r},Ar=e=>{let t=Yo(Uo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},gr=({schema:e})=>({type:Ar(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),fn=({schema:{value:e}})=>({type:Ar(e),const:e}),yn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&xe(p)?p instanceof S.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=$e({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},gn=()=>({type:"null"}),hn=e=>(B(!e.isResponse,new C({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:Ve.source,externalDocs:{url:Tr}}),xn=e=>(B(e.isResponse,new C({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Tr}}),Tn=e=>B.fail(new C({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),bn=()=>({type:"boolean"}),Sn=()=>({type:"integer",format:"bigint"}),On=e=>e.every(t=>t instanceof S.ZodLiteral),An=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=$e({schema:S.object(_e(We(o,[t]))),...r}),i.required=o),i}if(e instanceof S.ZodLiteral)return{type:"object",properties:$e({schema:S.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof S.ZodUnion&&On(e.options)){let o=le(s=>`${s.value}`,e.options),i=_e(We(o,[t]));return{type:"object",properties:$e({schema:S.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},Rn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},Pn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Cn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:m}}})=>{let f=m.find(T=>T.kind==="regex"),x=m.find(T=>T.kind==="datetime"),b=f?f.regex:x?x.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,O={type:"string"},g={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let T in g)if(g[T]){O.format=T;break}return r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),b&&(O.pattern=b.source),O},In=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},$e=({schema:{shape:e},next:t})=>le(t,e),En=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return en?.[t]},Rr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},wn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!te(o)){let s=ke(e,En(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.any())}if(!t&&i.type==="preprocess"&&!te(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},zn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Zn=({schema:e,next:t})=>t(e.unwrap()),Mn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},Nn=({next:e,schema:t})=>e(t.shape.raw),Pr=e=>e.length?Xo(Go(1,e.length+1).map(t=>`example${t}`),le(hr("value"),e)):void 0,Cr=(e,t,r=[])=>xr(K,le(Qo(Lo(E,jo(Array.isArray)),Ge(r))),Pr)({schema:e,variant:t?"parsed":"original",validate:!0}),vn=(e,t)=>xr(K,Ko(Fo(t)),_o(t),Pr)({schema:e,variant:"original",validate:!0}),Ie=(e,t)=>e instanceof S.ZodObject?e:e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?Array.from(e.options.values()).map(r=>Ie(r,t)).reduce((r,o)=>r.merge(o.partial()),S.object({})):e instanceof S.ZodEffects?(B(e._def.effect.type==="refinement",t),Ie(e._def.schema,t)):Ie(e._def.left,t).merge(Ie(e._def.right,t)),Ir=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=Ie(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=Sr(e),m=o.includes("query"),f=o.includes("params"),x=o.includes("headers"),b=g=>f&&l.includes(g),O=g=>x&&it(g);return Object.keys(c).filter(g=>m||b(g)).map(g=>{let T=ee({schema:c[g],isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:a,path:e,method:t}),L=p==="components"?a(I(d,g),T):T;return{name:g,in:b(g)?"path":O(g)?"header":"query",required:!c[g].isOptional(),description:T.description||d,schema:L,examples:vn(r,g)}})},Tt={ZodString:Cn,ZodNumber:In,ZodBigInt:Sn,ZodBoolean:bn,ZodNull:gn,ZodArray:Rn,ZodTuple:Pn,ZodRecord:An,ZodObject:yn,ZodLiteral:fn,ZodIntersection:cn,ZodUnion:an,ZodAny:on,ZodDefault:tn,ZodEnum:gr,ZodNativeEnum:gr,ZodEffects:wn,ZodOptional:mn,ZodNullable:un,ZodDiscriminatedUnion:pn,ZodBranded:Zn,ZodDate:Tn,ZodCatch:rn,ZodPipeline:zn,ZodLazy:Mn,ZodReadonly:ln,[F]:sn,[be]:nn,[Ce]:xn,[Pe]:hn,[Y]:Nn},bt=({schema:e,isResponse:t,prev:r})=>{if(te(r))return{};let{description:o}=e,i=e instanceof S.ZodLazy,s=r.type!==void 0,a=t&&xe(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Rr(r)),d.length&&(c.examples=Array.from(d)),c},St=({schema:e,...t})=>B.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),xt=(e,t)=>{if(te(e))return e;let r={...e};return r.properties&&(r.properties=Ge(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Ge(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>xt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>xt(o,t))),r},Er=e=>te(e)?e:Ge(["examples"],e),wr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,description:m=`${e.toUpperCase()} ${t} ${at(i)} response ${c?l:""}`.trim()})=>{let f=Er(ee({schema:r,isResponse:!0,rules:Tt,onEach:bt,onMissing:St,serializer:s,getRef:a,makeRef:p,path:t,method:e})),x={schema:d==="components"?p(I(m),f):f,examples:Cr(r,!0)};return{description:m,content:_e(We(o,[x]))}},Dn=()=>({type:"http",scheme:"basic"}),kn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ln=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},jn=({name:e})=>({type:"apiKey",in:"header",name:e}),Hn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Un=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Kn=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),Wo(Bo,e))}),zr=(e,t)=>{let r={basic:Dn,bearer:kn,input:Ln,header:jn,cookie:Hn,openid:Un,oauth2:Kn};return Fe(e,o=>r[o.type](o,t))},Ye=e=>"or"in e?e.or.map(t=>"and"in t?qo(le(({name:r,scopes:o})=>hr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?Ye(mt(e)):Ye({or:[e]}),Zr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Sr(t),l=Er(xt(ee({schema:r,isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),m={schema:p==="components"?a(I(d),l):l,examples:Cr(r,!1,c)};return{description:d,content:_e(We(o,[m]))}},Mr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Ot=e=>e.length<=yr?e:e.slice(0,yr-1)+"\u2026";var At=class extends Bn{lastSecuritySchemaIds={};lastOperationIdSuffixes={};makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){if(o)return Fn(!(o in this.lastOperationIdSuffixes),new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),this.lastOperationIdSuffixes[o]=1,o;let i=I(r,t);return i in this.lastOperationIdSuffixes?(this.lastOperationIdSuffixes[i]++,`${i}${this.lastOperationIdSuffixes[i]}`):(this.lastOperationIdSuffixes[i]=1,i)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let o in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[o]))return o;return this.lastSecuritySchemaIds[t.type]=(this.lastSecuritySchemaIds?.[t.type]||0)+1,`${t.type.toUpperCase()}_${this.lastSecuritySchemaIds[t.type]}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=De}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});X({routing:t,onEndpoint:(m,f,x)=>{let b=x,O={path:f,method:b,endpoint:m,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[g,T]=["short","long"].map(m.getDescription.bind(m)),L=g?Ot(g):p&&T?Ot(T):void 0,we=m.getTags(),ye=r.inputSources?.[b]||ot[b],oe=this.ensureUniqOperationId(f,b,m.getOperationId(b)),ze=Ir({...O,inputSources:ye,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:f,operationId:oe})}),Ze={};for(let N of["positive","negative"]){let h=m.getResponses(N);for(let{mimeTypes:A,schema:R,statusCodes:z}of h)for(let ne of z)Ze[ne]=wr({...O,variant:N,schema:R,mimeTypes:A,statusCode:ne,hasMultipleStatusCodes:h.length>1||z.length>1,description:a?.[`${N}Response`]?.call(null,{method:b,path:f,operationId:oe,statusCode:ne})})}let tt=ye.includes("body")?Zr({...O,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:f,operationId:oe})}):void 0,Me=Ye(Fe(zr(m.getSecurity(),ye),N=>{let h=this.ensureUniqSecuritySchemaName(N),A=["oauth2","openIdConnect"].includes(N.type)?m.getScopes():[];return this.addSecurityScheme(h,N),{name:h,scopes:A}}));this.addPath(Or(f),{[b]:{operationId:oe,summary:L,description:T,tags:we.length>0?we:void 0,parameters:ze.length>0?ze:void 0,requestBody:tt,security:Me.length>0?Me:void 0,responses:Ze}})}}),this.rootDoc.tags=r.tags?Mr(r.tags):[]}};import Nr from"http";var qn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>v),...t}),Vn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Nr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Nr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},$n=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),_n=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await or([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=qn({fnMethod:a,requestProps:t}),d=Vn({fnMethod:a,responseProps:r}),c=$n({fnMethod:a,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:l,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import w from"typescript";import k from"typescript";import{chain as vr,toPairs as Dr}from"ramda";var n=k.factory,q=[n.createModifier(k.SyntaxKind.ExportKeyword)],Gn=[n.createModifier(k.SyntaxKind.AsyncKeyword)],Wn=[n.createModifier(k.SyntaxKind.PublicKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],kr=[n.createModifier(k.SyntaxKind.ProtectedKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Rt=n.createTemplateHead(""),ue=n.createTemplateTail(""),Pt=n.createTemplateMiddle(" "),Ct=e=>n.createTemplateLiteralType(Rt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?ue:Pt))),It=Ct(["M","P"]),Je=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),Qe=(e,t)=>vr(([r,o])=>[Je(n.createIdentifier(r),o,t)],Dr(e)),Et=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Lr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),jr=(e,t)=>n.createPropertySignature(void 0,`"${e}"`,void 0,n.createTypeReferenceNode(t)),V=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],k.NodeFlags.Const),wt=(e,t)=>n.createTypeAliasDeclaration(q,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),Xe=(e,t)=>n.createTypeAliasDeclaration(q,e,void 0,t),Hr=(e,t,r)=>n.createPropertyDeclaration(Wn,e,void 0,t,r),Ur=(e,t,r)=>n.createClassDeclaration(q,e,void 0,void 0,[t,...r]),Kr=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Fr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.SyntaxKind.AnyKeyword)]),Br=(e,t,r)=>n.createInterfaceDeclaration(q,e,void 0,t,r),qr=e=>vr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Dr(e)),zt=(e,t,r)=>n.createArrowFunction(r?Gn:void 0,void 0,e.map(o=>Je(o)),void 0,void 0,t),Zt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,Qe({acc:void 0,key:void 0}),void 0,void 0,t),r]);var Vr=["get","post","put","delete","patch"];import y from"typescript";import{z as vt}from"zod";import $ from"typescript";var{factory:et}=$,Mt=(e,t)=>{$.addSyntheticLeadingComment(e,$.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},fe=(e,t,r)=>{let o=et.createTypeAliasDeclaration(void 0,et.createIdentifier(t),void 0,e);return r&&Mt(o,r),o},Nt=(e,t)=>{let r=$.createSourceFile("print.ts","",$.ScriptTarget.Latest,!1,$.ScriptKind.TS);return $.createPrinter(t).printNode($.EmitHint.Unspecified,e,r)},Yn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,$r=e=>Yn.test(e)?et.createIdentifier(e):et.createStringLiteral(e);var{factory:u}=y,Jn={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Qn=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Xn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&xe(a)?a instanceof vt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,$r(s),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Mt(d,a.description),d});return u.createTypeLiteralNode(i)},ei=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),ti=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),_r=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),ri=e=>Jn?.[e.kind],oi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,ri(o)),a={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||y.SyntaxKind.AnyKeyword)}return o},ni=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),ii=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},si=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),ai=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),pi=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),di=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),ci=({next:e,schema:t})=>e(t._def.innerType),re=e=>()=>u.createKeywordTypeNode(e),mi=({next:e,schema:t})=>e(t.unwrap()),li=({next:e,schema:t})=>e(t._def.innerType),ui=({next:e,schema:t})=>e(t._def.innerType),fi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),yi=()=>u.createLiteralTypeNode(u.createNull()),gi=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,u.createLiteralTypeNode(u.createNull())),t(s,r(i.schema)))},hi=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof vt.ZodString?t:e instanceof vt.ZodUnion?o:r},xi=({next:e,schema:t})=>e(t.shape.raw),Ti={ZodString:re(y.SyntaxKind.StringKeyword),ZodNumber:re(y.SyntaxKind.NumberKeyword),ZodBigInt:re(y.SyntaxKind.BigIntKeyword),ZodBoolean:re(y.SyntaxKind.BooleanKeyword),ZodAny:re(y.SyntaxKind.AnyKeyword),[Pe]:re(y.SyntaxKind.StringKeyword),[Ce]:re(y.SyntaxKind.StringKeyword),ZodNull:yi,ZodArray:ei,ZodTuple:ai,ZodRecord:pi,ZodObject:Xn,ZodLiteral:Qn,ZodIntersection:di,ZodUnion:_r,ZodDefault:ci,ZodEnum:ti,ZodNativeEnum:ni,ZodEffects:oi,ZodOptional:ii,ZodNullable:si,ZodDiscriminatedUnion:_r,ZodBranded:mi,ZodCatch:ui,ZodPipeline:fi,ZodLazy:gi,ZodReadonly:li,[F]:hi,[Y]:xi},Ee=({schema:e,...t})=>ee({schema:e,rules:Ti,onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),...t});var Dt=class{program=[];usage=[];registry={};paths=[];aliases={};ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return t in this.aliases?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases[t]=fe(r,t),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=De,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){X({routing:t,onEndpoint:(h,A,R)=>{let z={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},ne=I(R,A,"input"),Gr=Ee({...z,schema:h.getSchema("input"),isResponse:!1}),ge=i?I(R,A,"positive.response"):void 0,kt=h.getSchema("positive"),Lt=i?Ee({...z,isResponse:!0,schema:kt}):void 0,he=i?I(R,A,"negative.response"):void 0,jt=h.getSchema("negative"),Ht=i?Ee({...z,isResponse:!0,schema:jt}):void 0,Ut=I(R,A,"response"),Wr=ge&&he?n.createUnionTypeNode([n.createTypeReferenceNode(ge),n.createTypeReferenceNode(he)]):Ee({...z,isResponse:!0,schema:kt.or(jt)});this.program.push(fe(Gr,ne)),Lt&&ge&&this.program.push(fe(Lt,ge)),Ht&&he&&this.program.push(fe(Ht,he)),this.program.push(fe(Wr,Ut)),R!=="options"&&(this.paths.push(A),this.registry[`${R} ${A}`]={input:ne,positive:ge,negative:he,response:Ut,isJson:h.getMimeTypes("positive").includes(v),tags:h.getTags()})}}),this.program.unshift(...Object.values(this.aliases)),this.program.push(wt(this.ids.pathType,this.paths)),this.program.push(wt(this.ids.methodType,Vr)),this.program.push(Xe(this.ids.methodPathType,Ct([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(w.SyntaxKind.ExtendsKeyword,[Et(this.ids.methodPathType,w.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input"}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive"},{id:this.ids.negResponseInterface,kind:"negative"}),this.interfaces.push({id:this.ids.responseInterface,kind:"response"});for(let{id:h,kind:A}of this.interfaces)this.program.push(Br(h,a,Object.keys(this.registry).map(R=>{let z=this.registry[R][A];return z?jr(R,z):void 0}).filter(R=>R!==void 0)));if(r==="types")return;let p=n.createVariableStatement(q,V(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(Object.keys(this.registry).filter(h=>this.registry[h].isJson).map(h=>n.createPropertyAssignment(`"${h}"`,n.createTrue()))))),d=n.createVariableStatement(q,V(this.ids.endpointTagsConst,n.createObjectLiteralExpression(Object.keys(this.registry).map(h=>n.createPropertyAssignment(`"${h}"`,n.createArrayLiteralExpression(this.registry[h].tags.map(A=>n.createStringLiteral(A)))))))),c=Xe(this.ids.providerType,n.createFunctionTypeNode(qr({M:this.ids.methodType,P:this.ids.pathType}),Qe({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),It)}),Kr(this.ids.responseInterface,It))),l=Xe(this.ids.implementationType,n.createFunctionTypeNode(void 0,Qe({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.SyntaxKind.StringKeyword),params:Et(w.SyntaxKind.StringKeyword,w.SyntaxKind.AnyKeyword)}),Fr())),m=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,ue)]),f=Zt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[m,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),x=Zt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[m]),w.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),b=Ur(this.ids.clientClass,Lr([Je(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),kr)]),[Hr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),zt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,f,x]),!0))]);this.program.push(p,d,c,l,b);let O=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),g=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(v))]),void 0,this.ids.undefinedValue)),T=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),L=n.createVariableStatement(void 0,V(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,ue)]),n.createObjectLiteralExpression([O,g,T])])))),we=n.createVariableStatement(void 0,V(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ye=n.createVariableStatement(void 0,V(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),ue)])))),[oe,ze]=["json","text"].map(h=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,h),void 0,void 0))),Ze=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Rt,[n.createTemplateSpan(this.ids.methodParameter,Pt),n.createTemplateSpan(this.ids.pathParameter,ue)]),w.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([oe])),tt=n.createVariableStatement(q,V(this.ids.exampleImplementationConst,zt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([we,ye,L,Ze,ze]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Me=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),N=n.createVariableStatement(void 0,V(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(tt,N,Me)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Nt(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.printUsage(t),o=r&&w.addSyntheticLeadingComment(w.addSyntheticLeadingComment(n.createEmptyStatement(),w.SyntaxKind.SingleLineCommentTrivia," Usage example:"),w.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.program.concat(o||[]).map((i,s)=>Nt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "17.7.0-beta1",
3
+ "version": "17.7.0",
4
4
  "description": "A Typescript library to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {