express-zod-api 17.1.2 → 17.2.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/CHANGELOG.md CHANGED
@@ -2,6 +2,33 @@
2
2
 
3
3
  ## Version 17
4
4
 
5
+ ### v17.2.0
6
+
7
+ - Introducing `beforeUpload` option for the `upload` option in config:
8
+ - A code to execute before connecting the upload middleware;
9
+ - It can be used to connect a middleware that restricts the ability to upload;
10
+ - It accepts a function similar to `beforeRouting`, having `app` and `logger` in its argument.
11
+
12
+ ```typescript
13
+ import createHttpError from "http-errors";
14
+ import { createConfig } from "express-zod-api";
15
+
16
+ const config = createConfig({
17
+ server: {
18
+ upload: {
19
+ beforeUpload: ({ app, logger }) => {
20
+ app.use((req, res, next) => {
21
+ if (req.is("multipart/form-data") && !canUpload(req)) {
22
+ return next(createHttpError(403, "Not authorized"));
23
+ }
24
+ next();
25
+ });
26
+ },
27
+ },
28
+ },
29
+ });
30
+ ```
31
+
5
32
  ### v17.1.2
6
33
 
7
34
  - Fixed Uncaught Exception when using `limitError` feature.
package/README.md CHANGED
@@ -791,7 +791,9 @@ Some options are forced in order to ensure the correct workflow:
791
791
  { abortOnLimit: false, parseNested: true }
792
792
  ```
793
793
 
794
- The `limitHandler` option is replaced by the `limitError` one, so you can set the limits this way:
794
+ The `limitHandler` option is replaced by the `limitError` one. You can also connect an additional middleware for
795
+ restricting the ability to upload using the `beforeUpload` option. So the configuration for the limited and restricted
796
+ upload might look this way:
795
797
 
796
798
  ```typescript
797
799
  import createHttpError from "http-errors";
@@ -801,6 +803,14 @@ const config = createConfig({
801
803
  upload: {
802
804
  limits: { fileSize: 51200 }, // 50 KB
803
805
  limitError: createHttpError(413, "The file is too large"), // handled by errorHandler in config
806
+ beforeUpload: ({ app, logger }) => {
807
+ app.use((req, res, next) => {
808
+ if (req.is("multipart/form-data") && !canUpload(req)) {
809
+ return next(createHttpError(403, "Not authorized"));
810
+ }
811
+ next();
812
+ });
813
+ },
804
814
  },
805
815
  },
806
816
  });
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.1.2 (CJS)"),ie({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,p,a)=>{e[p](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:a})})},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,p)=>{if(!o)return p();e.handler({error:(0,Ze.isHttpError)(o)?o:(0,Ze.default)(400,le(o).message),request:i,response:s,input:null,output:null,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}`),p=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:p,error:s,input:null,output:null})}catch(a){_e({response:i,logger:p,error:new Q(le(a).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),p=Ir(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:p}},vr=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}},Nr=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))}if(r.use(e.server.jsonParser||Et.default.json()),e.server.upload){let d=await ne("express-fileupload"),{limitError:c,...l}={...typeof e.server.upload=="object"&&e.server.upload};r.use(d({...l,abortOnLimit:!1,parseNested:!0})),c&&r.use(wr(c))}e.server.rawParser&&(r.use(e.server.rawParser),r.use((d,{},c)=>{Buffer.isBuffer(d.body)&&(d.body={raw:d.body}),c()}));let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=await Mr(e);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 p=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),a={httpServer:p(zr.default.createServer(r),e.server.listen),httpsServer:e.https?p(Zr.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...a,logger:o}};var Xr=R(require("assert/strict"),1),eo=require("openapi3-ts/oas31");var F=R(require("assert/strict"),1),_=require("openapi3-ts/oas31"),m=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 ve="DateOut",Lr=()=>E(ve,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,p=s?r[s]:void 0,a=i,c=p?p({schema:e,...a,next:u=>se({schema:u,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),l=t&&t({schema:e,prev:c,...a});return l?{...c,...l}:c};var jr=50,Ur="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Lo={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)}}`),jo=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),Ho=({schema:{_def:{innerType:e}},next:t})=>t(e),Uo=()=>({format:"any"}),Ko=e=>((0,F.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Fo=({schema:e})=>({type:"string",format:e instanceof O.z.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),Bo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),qo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),Vo=e=>{let[t,r]=e.filter(i=>!(0,_.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,m.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,m.concat)(i,s):i===s?s:F.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([i,s])=>(0,m.mergeDeepRight)(i,s))),o},$o=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Vo(o)}catch{}return{allOf:o}},Go=({schema:e,next:t})=>t(e.unwrap()),_o=({schema:e,next:t})=>t(e._def.innerType),Wo=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,_.isReferenceObject)(r)||(r.type=qr(r)),r},Hr=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),Yo=({schema:{value:e}})=>({type:typeof e,enum:[e]}),Jo=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=a=>t&&Ie(a)?a instanceof O.z.ZodOptional:a.isOptional(),s=o.filter(a=>!i(e.shape[a])),p={type:"object"};return o.length&&(p.properties=nt({schema:e,isResponse:t,...r})),s.length&&(p.required=s),p},Qo=()=>({type:"null"}),Xo=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}}),en=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}}),tn=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})),rn=()=>({type:"boolean"}),on=()=>({type:"integer",format:"bigint"}),nn=e=>e.every(t=>t instanceof O.z.ZodLiteral),sn=({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,m.fromPairs)((0,m.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&&nn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),i=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:nt({schema:O.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},an=({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},next:t})=>({type:"array",prefixItems:e.map(t)}),dn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:p,isULID:a,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:u}}})=>{let y=u.find(b=>b.kind==="regex"),T=u.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":l,email:e,url:t,uuid:i,cuid:s,cuid2:p,ulid:a,ip:d,emoji:c};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},cn=({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,p=i?i.inclusive:!0,a={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?a.minimum=r:a.exclusiveMinimum=r,p?a.maximum=s:a.exclusiveMaximum=s,a},nt=({schema:{shape:e},next:t})=>(0,m.map)(t,e),mn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Lo?.[t]},qr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},ln=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,_.isReferenceObject)(o)){let s=Be(e,mn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(O.z.any())}if(!t&&i.type==="preprocess"&&!(0,_.isReferenceObject)(o)){let{type:s,...p}=o;return{...p,format:`${p.format||s} (preprocessed)`}}return o},un=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),fn=({schema:e,next:t})=>t(e.unwrap()),yn=({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)))},gn=({next:e,schema:t})=>e(t.shape.raw),Vr=e=>e.length?(0,m.zipObj)((0,m.range)(1,e.length+1).map(t=>`example${t}`),(0,m.map)((0,m.objOf)("value"),e)):void 0,$r=(e,t,r=[])=>(0,m.pipe)(K,(0,m.map)((0,m.when)((0,m.both)(Z,(0,m.complement)(Array.isArray)),(0,m.omit)(r))),Vr)({schema:e,variant:t?"parsed":"original",validate:!0}),hn=(e,t)=>(0,m.pipe)(K,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),Vr)({schema:e,variant:"original",validate:!0}),Ne=(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=>Ne(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),Ne(e._def.schema,t)):Ne(e._def.left,t).merge(Ne(e._def.right,t)),Gr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:p,composition:a,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=Ne(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=Fr(e),u=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=h=>y&&l.includes(h),A=h=>T&&ht(h);return Object.keys(c).filter(h=>u||S(h)).map(h=>{let b=se({schema:c[h],isResponse:!1,rules:Zt,onEach:Mt,onMissing:vt,serializer:i,getRef:s,makeRef:p,path:e,method:t}),q=a==="components"?p(z(d,h),b):b;return{name:h,in:S(h)?"path":A(h)?"header":"query",required:!c[h].isOptional(),description:b.description||d,schema:q,examples:hn(r,h)}})},Zt={ZodString:dn,ZodNumber:cn,ZodBigInt:on,ZodBoolean:rn,ZodNull:Qo,ZodArray:an,ZodTuple:pn,ZodRecord:sn,ZodObject:Jo,ZodLiteral:Yo,ZodIntersection:$o,ZodUnion:Bo,ZodAny:Uo,ZodDefault:jo,ZodEnum:Hr,ZodNativeEnum:Hr,ZodEffects:ln,ZodOptional:Go,ZodNullable:Wo,ZodDiscriminatedUnion:qo,ZodBranded:fn,ZodDate:tn,ZodCatch:Ho,ZodPipeline:un,ZodLazy:yn,ZodReadonly:_o,[G]:Fo,[ze]:Ko,[ve]:en,[Me]:Xo,[te]:gn},Mt=({schema:e,isResponse:t,prev:r})=>{if((0,_.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof O.z.ZodLazy,s=r.type!==void 0,p=t&&Ie(e),a=!i&&s&&!p&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),a&&(c.type=qr(r)),d.length&&(c.examples=Array.from(d)),c},vt=({schema:e,...t})=>F.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),zt=(e,t)=>{if((0,_.isReferenceObject)(e))return e;let r=e.properties?(0,m.omit)(t,e.properties):void 0,o=e.examples?e.examples.map(a=>(0,m.omit)(t,a)):void 0,i=e.required?e.required.filter(a=>!t.includes(a)):void 0,s=e.allOf?e.allOf.map(a=>zt(a,t)):void 0,p=e.oneOf?e.oneOf.map(a=>zt(a,t)):void 0;return(0,m.omit)(Object.entries({properties:r,required:i,examples:o,allOf:s,oneOf:p}).filter(([{},a])=>a===void 0).map(([a])=>a),{...e,properties:r,required:i,examples:o,allOf:s,oneOf:p})},_r=e=>(0,_.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),Wr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:p,makeRef:a,composition:d,hasMultipleStatusCodes:c,statusCode:l,description:u=`${e.toUpperCase()} ${t} ${Tt(i)} response ${c?l:""}`.trim()})=>{let y=_r(se({schema:r,isResponse:!0,rules:Zt,onEach:Mt,onMissing:vt,serializer:s,getRef:p,makeRef:a,path:t,method:e})),T={schema:d==="components"?a(z(u),y):y,examples:$r(r,!0)};return{description:u,content:(0,m.fromPairs)((0,m.xprod)(o,[T]))}},xn=()=>({type:"http",scheme:"basic"}),Tn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},bn=({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},Sn=({name:e})=>({type:"apiKey",in:"header",name:e}),On=({name:e})=>({type:"apiKey",in:"cookie",name:e}),An=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Rn=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Yr=(e,t)=>{let r={basic:xn,bearer:Tn,input:bn,header:Sn,cookie:On,openid:An,oauth2:Rn};return We(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(At(e)):it({or:[e]}),Jr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:p,composition:a,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Fr(t),l=_r(zt(se({schema:r,isResponse:!1,rules:Zt,onEach:Mt,onMissing:vt,serializer:i,getRef:s,makeRef:p,path:t,method:e}),c)),u={schema:a==="components"?p(z(d),l):l,examples:$r(r,!1,c)};return{description:d,content:(0,m.fromPairs)((0,m.xprod)(o,[u]))}},Qr=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}),Nt=e=>e.length<=jr?e:e.slice(0,jr-1)+"\u2026";var st=class extends eo.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,Xr.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:p,hasSummaryFromDescription:a=!0,composition:d="inline",serializer:c=Fe}){super(),this.addInfo({title:o,version:i});for(let u of typeof s=="string"?[s]:s)this.addServer({url:u});ie({routing:t,onEndpoint:(u,y,T)=>{let S=T,A={path:y,method:S,endpoint:u,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,b]=["short","long"].map(u.getDescription.bind(u)),q=h?Nt(h):a&&b?Nt(b):void 0,ke=u.getTags(),Ae=r.inputSources?.[S]||yt[S],pe=this.ensureUniqOperationId(y,S,u.getOperationId(S)),Le=Gr({...A,inputSources:Ae,schema:u.getSchema("input"),description:p?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),je={};for(let L of["positive","negative"]){let x=u.getResponses(L);for(let{mimeTypes:P,schema:C,statusCodes:v}of x)for(let de of v)je[de]=Wr({...A,variant:L,schema:C,mimeTypes:P,statusCode:de,hasMultipleStatusCodes:x.length>1||v.length>1,description:p?.[`${L}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:de})})}let ut=Ae.includes("body")?Jr({...A,schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:p?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,He=it(We(Yr(u.getSecurity(),Ae),L=>{let x=this.ensureUniqSecuritySchemaName(L),P=["oauth2","openIdConnect"].includes(L.type)?u.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?Qr(r.tags):[]}};var Dt=R(require("http"),1);var Pn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>U),...t}),Cn=({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},In=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),to=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let p=s||(await Pr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,a=Pn({fnMethod:p,requestProps:t}),d=Cn({fnMethod:p,responseProps:r}),c=In({fnMethod:p,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:a,response:d,config:l,logger:c}),{requestMock:a,responseMock:d,loggerMock:c}};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)],En=[n.createModifier(k.default.SyntaxKind.AsyncKeyword)],wn=[n.createModifier(k.default.SyntaxKind.PublicKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],ro=[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)]),oo=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),no=(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),io=(e,t,r)=>n.createPropertyDeclaration(wn,e,void 0,t,r),so=(e,t,r)=>n.createClassDeclaration(W,e,void 0,void 0,[t,...r]),ao=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),po=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.default.SyntaxKind.AnyKeyword)]),co=(e,t,r)=>n.createInterfaceDeclaration(W,e,void 0,t,r),mo=e=>(0,be.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,be.toPairs)(e)),Ft=(e,t,r)=>n.createArrowFunction(r?En: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 lo=["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_$]*$/,uo=e=>zn.test(e)?ct.createIdentifier(e):ct.createStringLiteral(e);var{factory:f}=g.default,Zn={[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},Mn=({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,p])=>{let a=t&&Ie(p)?p instanceof mt.z.ZodOptional:p.isOptional(),d=f.createPropertySignature(void 0,uo(s),a&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(p));return p.description&&qt(d,p.description),d});return f.createTypeLiteralNode(i)},Nn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Dn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),fo=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),kn=e=>Zn?.[e.kind],Ln=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Be(e,kn(o)),p={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&&p[s]||g.default.SyntaxKind.AnyKeyword)}return o},jn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Hn=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Un=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Kn=({next:e,schema:{items:t}})=>f.createTupleTypeNode(t.map(e)),Fn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Bn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),qn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),Vn=({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),_n=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),Wn=()=>f.createLiteralTypeNode(f.createNull()),Yn=({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)))},Jn=({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},Qn=({next:e,schema:t})=>e(t.shape.raw),Xn={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),[ve]:ae(g.default.SyntaxKind.StringKeyword),ZodNull:Wn,ZodArray:Nn,ZodTuple:Kn,ZodRecord:Fn,ZodObject:vn,ZodLiteral:Mn,ZodIntersection:Bn,ZodUnion:fo,ZodDefault:qn,ZodEnum:Dn,ZodNativeEnum:jn,ZodEffects:Ln,ZodOptional:Hn,ZodNullable:Un,ZodDiscriminatedUnion:fo,ZodBranded:Vn,ZodCatch:Gn,ZodPipeline:_n,ZodLazy:Yn,ZodReadonly:$n,[G]:Jn,[te]:Qn},De=({schema:e,...t})=>se({schema:e,rules:Xn,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 v={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},de=z(C,P,"input"),go=De({...v,schema:x.getSchema("input"),isResponse:!1}),Re=i?z(C,P,"positive.response"):void 0,$t=x.getSchema("positive"),Gt=i?De({...v,isResponse:!0,schema:$t}):void 0,Pe=i?z(C,P,"negative.response"):void 0,_t=x.getSchema("negative"),Wt=i?De({...v,isResponse:!0,schema:_t}):void 0,Yt=z(C,P,"response"),ho=Re&&Pe?n.createUnionTypeNode([n.createTypeReferenceNode(Re),n.createTypeReferenceNode(Pe)]):De({...v,isResponse:!0,schema:$t.or(_t)});this.program.push(Oe(go,de)),Gt&&Re&&this.program.push(Oe(Gt,Re)),Wt&&Pe&&this.program.push(Oe(Wt,Pe)),this.program.push(Oe(ho,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,lo)),this.program.push(dt(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[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(co(x,p,Object.keys(this.registry).map(C=>{let v=this.registry[C][P];return v?no(C,v):void 0}).filter(C=>C!==void 0)));if(r==="types")return;let a=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)))))))),c=dt(this.ids.providerType,n.createFunctionTypeNode(mo({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)}),ao(this.ids.responseInterface,Ht))),l=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)}),po())),u=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,[u,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,[u]),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=so(this.ids.clientClass,oo([at(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),ro)]),[io(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(a,d,c,l,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.2.0 (CJS)"),ie({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,p,a)=>{e[p](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:a})})},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,p)=>{if(!o)return p();e.handler({error:(0,Ze.isHttpError)(o)?o:(0,Ze.default)(400,le(o).message),request:i,response:s,input:null,output:null,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}`),p=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:p,error:s,input:null,output:null})}catch(a){_e({response:i,logger:p,error:new Q(le(a).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),p=Ir(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:p}},vr=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}},Nr=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:c,beforeUpload:l,...u}={...typeof e.server.upload=="object"&&e.server.upload};l&&l({app:r,logger:o}),r.use(d({...u,abortOnLimit:!1,parseNested:!0})),c&&r.use(wr(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}),It({app:r,routing:t,rootLogger:o,config:e}),r.use(i);let p=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),a={httpServer:p(zr.default.createServer(r),e.server.listen),httpsServer:e.https?p(Zr.default.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...a,logger:o}};var Xr=R(require("assert/strict"),1),eo=require("openapi3-ts/oas31");var F=R(require("assert/strict"),1),_=require("openapi3-ts/oas31"),m=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 ve="DateOut",Lr=()=>E(ve,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,p=s?r[s]:void 0,a=i,c=p?p({schema:e,...a,next:u=>se({schema:u,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),l=t&&t({schema:e,prev:c,...a});return l?{...c,...l}:c};var jr=50,Ur="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Lo={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)}}`),jo=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),Ho=({schema:{_def:{innerType:e}},next:t})=>t(e),Uo=()=>({format:"any"}),Ko=e=>((0,F.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Fo=({schema:e})=>({type:"string",format:e instanceof O.z.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),Bo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),qo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),Vo=e=>{let[t,r]=e.filter(i=>!(0,_.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,m.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,m.concat)(i,s):i===s?s:F.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([i,s])=>(0,m.mergeDeepRight)(i,s))),o},$o=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Vo(o)}catch{}return{allOf:o}},Go=({schema:e,next:t})=>t(e.unwrap()),_o=({schema:e,next:t})=>t(e._def.innerType),Wo=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,_.isReferenceObject)(r)||(r.type=qr(r)),r},Hr=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),Yo=({schema:{value:e}})=>({type:typeof e,enum:[e]}),Jo=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=a=>t&&Ie(a)?a instanceof O.z.ZodOptional:a.isOptional(),s=o.filter(a=>!i(e.shape[a])),p={type:"object"};return o.length&&(p.properties=nt({schema:e,isResponse:t,...r})),s.length&&(p.required=s),p},Qo=()=>({type:"null"}),Xo=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}}),en=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}}),tn=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})),rn=()=>({type:"boolean"}),on=()=>({type:"integer",format:"bigint"}),nn=e=>e.every(t=>t instanceof O.z.ZodLiteral),sn=({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,m.fromPairs)((0,m.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&&nn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),i=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:nt({schema:O.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},an=({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},next:t})=>({type:"array",prefixItems:e.map(t)}),dn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:p,isULID:a,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:u}}})=>{let y=u.find(b=>b.kind==="regex"),T=u.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":l,email:e,url:t,uuid:i,cuid:s,cuid2:p,ulid:a,ip:d,emoji:c};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},cn=({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,p=i?i.inclusive:!0,a={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?a.minimum=r:a.exclusiveMinimum=r,p?a.maximum=s:a.exclusiveMaximum=s,a},nt=({schema:{shape:e},next:t})=>(0,m.map)(t,e),mn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Lo?.[t]},qr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},ln=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,_.isReferenceObject)(o)){let s=Be(e,mn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(O.z.any())}if(!t&&i.type==="preprocess"&&!(0,_.isReferenceObject)(o)){let{type:s,...p}=o;return{...p,format:`${p.format||s} (preprocessed)`}}return o},un=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),fn=({schema:e,next:t})=>t(e.unwrap()),yn=({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)))},gn=({next:e,schema:t})=>e(t.shape.raw),Vr=e=>e.length?(0,m.zipObj)((0,m.range)(1,e.length+1).map(t=>`example${t}`),(0,m.map)((0,m.objOf)("value"),e)):void 0,$r=(e,t,r=[])=>(0,m.pipe)(K,(0,m.map)((0,m.when)((0,m.both)(Z,(0,m.complement)(Array.isArray)),(0,m.omit)(r))),Vr)({schema:e,variant:t?"parsed":"original",validate:!0}),hn=(e,t)=>(0,m.pipe)(K,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),Vr)({schema:e,variant:"original",validate:!0}),Ne=(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=>Ne(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),Ne(e._def.schema,t)):Ne(e._def.left,t).merge(Ne(e._def.right,t)),Gr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:p,composition:a,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=Ne(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),l=Fr(e),u=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=h=>y&&l.includes(h),A=h=>T&&ht(h);return Object.keys(c).filter(h=>u||S(h)).map(h=>{let b=se({schema:c[h],isResponse:!1,rules:Zt,onEach:Mt,onMissing:vt,serializer:i,getRef:s,makeRef:p,path:e,method:t}),q=a==="components"?p(z(d,h),b):b;return{name:h,in:S(h)?"path":A(h)?"header":"query",required:!c[h].isOptional(),description:b.description||d,schema:q,examples:hn(r,h)}})},Zt={ZodString:dn,ZodNumber:cn,ZodBigInt:on,ZodBoolean:rn,ZodNull:Qo,ZodArray:an,ZodTuple:pn,ZodRecord:sn,ZodObject:Jo,ZodLiteral:Yo,ZodIntersection:$o,ZodUnion:Bo,ZodAny:Uo,ZodDefault:jo,ZodEnum:Hr,ZodNativeEnum:Hr,ZodEffects:ln,ZodOptional:Go,ZodNullable:Wo,ZodDiscriminatedUnion:qo,ZodBranded:fn,ZodDate:tn,ZodCatch:Ho,ZodPipeline:un,ZodLazy:yn,ZodReadonly:_o,[G]:Fo,[ze]:Ko,[ve]:en,[Me]:Xo,[te]:gn},Mt=({schema:e,isResponse:t,prev:r})=>{if((0,_.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof O.z.ZodLazy,s=r.type!==void 0,p=t&&Ie(e),a=!i&&s&&!p&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),a&&(c.type=qr(r)),d.length&&(c.examples=Array.from(d)),c},vt=({schema:e,...t})=>F.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),zt=(e,t)=>{if((0,_.isReferenceObject)(e))return e;let r=e.properties?(0,m.omit)(t,e.properties):void 0,o=e.examples?e.examples.map(a=>(0,m.omit)(t,a)):void 0,i=e.required?e.required.filter(a=>!t.includes(a)):void 0,s=e.allOf?e.allOf.map(a=>zt(a,t)):void 0,p=e.oneOf?e.oneOf.map(a=>zt(a,t)):void 0;return(0,m.omit)(Object.entries({properties:r,required:i,examples:o,allOf:s,oneOf:p}).filter(([{},a])=>a===void 0).map(([a])=>a),{...e,properties:r,required:i,examples:o,allOf:s,oneOf:p})},_r=e=>(0,_.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),Wr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:p,makeRef:a,composition:d,hasMultipleStatusCodes:c,statusCode:l,description:u=`${e.toUpperCase()} ${t} ${Tt(i)} response ${c?l:""}`.trim()})=>{let y=_r(se({schema:r,isResponse:!0,rules:Zt,onEach:Mt,onMissing:vt,serializer:s,getRef:p,makeRef:a,path:t,method:e})),T={schema:d==="components"?a(z(u),y):y,examples:$r(r,!0)};return{description:u,content:(0,m.fromPairs)((0,m.xprod)(o,[T]))}},xn=()=>({type:"http",scheme:"basic"}),Tn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},bn=({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},Sn=({name:e})=>({type:"apiKey",in:"header",name:e}),On=({name:e})=>({type:"apiKey",in:"cookie",name:e}),An=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Rn=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Yr=(e,t)=>{let r={basic:xn,bearer:Tn,input:bn,header:Sn,cookie:On,openid:An,oauth2:Rn};return We(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?(0,m.mergeAll)((0,m.map)(({name:r,scopes:o})=>(0,m.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(At(e)):it({or:[e]}),Jr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:p,composition:a,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Fr(t),l=_r(zt(se({schema:r,isResponse:!1,rules:Zt,onEach:Mt,onMissing:vt,serializer:i,getRef:s,makeRef:p,path:t,method:e}),c)),u={schema:a==="components"?p(z(d),l):l,examples:$r(r,!1,c)};return{description:d,content:(0,m.fromPairs)((0,m.xprod)(o,[u]))}},Qr=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}),Nt=e=>e.length<=jr?e:e.slice(0,jr-1)+"\u2026";var st=class extends eo.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,Xr.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:p,hasSummaryFromDescription:a=!0,composition:d="inline",serializer:c=Fe}){super(),this.addInfo({title:o,version:i});for(let u of typeof s=="string"?[s]:s)this.addServer({url:u});ie({routing:t,onEndpoint:(u,y,T)=>{let S=T,A={path:y,method:S,endpoint:u,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,b]=["short","long"].map(u.getDescription.bind(u)),q=h?Nt(h):a&&b?Nt(b):void 0,ke=u.getTags(),Ae=r.inputSources?.[S]||yt[S],pe=this.ensureUniqOperationId(y,S,u.getOperationId(S)),Le=Gr({...A,inputSources:Ae,schema:u.getSchema("input"),description:p?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),je={};for(let L of["positive","negative"]){let x=u.getResponses(L);for(let{mimeTypes:P,schema:C,statusCodes:v}of x)for(let de of v)je[de]=Wr({...A,variant:L,schema:C,mimeTypes:P,statusCode:de,hasMultipleStatusCodes:x.length>1||v.length>1,description:p?.[`${L}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:de})})}let ut=Ae.includes("body")?Jr({...A,schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:p?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,He=it(We(Yr(u.getSecurity(),Ae),L=>{let x=this.ensureUniqSecuritySchemaName(L),P=["oauth2","openIdConnect"].includes(L.type)?u.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?Qr(r.tags):[]}};var Dt=R(require("http"),1);var Pn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>U),...t}),Cn=({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},In=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),to=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let p=s||(await Pr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,a=Pn({fnMethod:p,requestProps:t}),d=Cn({fnMethod:p,responseProps:r}),c=In({fnMethod:p,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:a,response:d,config:l,logger:c}),{requestMock:a,responseMock:d,loggerMock:c}};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)],En=[n.createModifier(k.default.SyntaxKind.AsyncKeyword)],wn=[n.createModifier(k.default.SyntaxKind.PublicKeyword),n.createModifier(k.default.SyntaxKind.ReadonlyKeyword)],ro=[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)]),oo=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),no=(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),io=(e,t,r)=>n.createPropertyDeclaration(wn,e,void 0,t,r),so=(e,t,r)=>n.createClassDeclaration(W,e,void 0,void 0,[t,...r]),ao=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),po=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.default.SyntaxKind.AnyKeyword)]),co=(e,t,r)=>n.createInterfaceDeclaration(W,e,void 0,t,r),mo=e=>(0,be.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,be.toPairs)(e)),Ft=(e,t,r)=>n.createArrowFunction(r?En: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 lo=["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_$]*$/,uo=e=>zn.test(e)?ct.createIdentifier(e):ct.createStringLiteral(e);var{factory:f}=g.default,Zn={[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},Mn=({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,p])=>{let a=t&&Ie(p)?p instanceof mt.z.ZodOptional:p.isOptional(),d=f.createPropertySignature(void 0,uo(s),a&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(p));return p.description&&qt(d,p.description),d});return f.createTypeLiteralNode(i)},Nn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Dn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),fo=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),kn=e=>Zn?.[e.kind],Ln=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Be(e,kn(o)),p={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&&p[s]||g.default.SyntaxKind.AnyKeyword)}return o},jn=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Hn=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},Un=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Kn=({next:e,schema:{items:t}})=>f.createTupleTypeNode(t.map(e)),Fn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Bn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),qn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),Vn=({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),_n=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),Wn=()=>f.createLiteralTypeNode(f.createNull()),Yn=({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)))},Jn=({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},Qn=({next:e,schema:t})=>e(t.shape.raw),Xn={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),[ve]:ae(g.default.SyntaxKind.StringKeyword),ZodNull:Wn,ZodArray:Nn,ZodTuple:Kn,ZodRecord:Fn,ZodObject:vn,ZodLiteral:Mn,ZodIntersection:Bn,ZodUnion:fo,ZodDefault:qn,ZodEnum:Dn,ZodNativeEnum:jn,ZodEffects:Ln,ZodOptional:Hn,ZodNullable:Un,ZodDiscriminatedUnion:fo,ZodBranded:Vn,ZodCatch:Gn,ZodPipeline:_n,ZodLazy:Yn,ZodReadonly:$n,[G]:Jn,[te]:Qn},De=({schema:e,...t})=>se({schema:e,rules:Xn,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 v={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},de=z(C,P,"input"),go=De({...v,schema:x.getSchema("input"),isResponse:!1}),Re=i?z(C,P,"positive.response"):void 0,$t=x.getSchema("positive"),Gt=i?De({...v,isResponse:!0,schema:$t}):void 0,Pe=i?z(C,P,"negative.response"):void 0,_t=x.getSchema("negative"),Wt=i?De({...v,isResponse:!0,schema:_t}):void 0,Yt=z(C,P,"response"),ho=Re&&Pe?n.createUnionTypeNode([n.createTypeReferenceNode(Re),n.createTypeReferenceNode(Pe)]):De({...v,isResponse:!0,schema:$t.or(_t)});this.program.push(Oe(go,de)),Gt&&Re&&this.program.push(Oe(Gt,Re)),Wt&&Pe&&this.program.push(Oe(Wt,Pe)),this.program.push(Oe(ho,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,lo)),this.program.push(dt(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[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(co(x,p,Object.keys(this.registry).map(C=>{let v=this.registry[C][P];return v?no(C,v):void 0}).filter(C=>C!==void 0)));if(r==="types")return;let a=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)))))))),c=dt(this.ids.providerType,n.createFunctionTypeNode(mo({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)}),ao(this.ids.responseInterface,Ht))),l=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)}),po())),u=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,[u,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,[u]),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=so(this.ids.clientClass,oo([at(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),ro)]),[io(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(a,d,c,l,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.d.cts CHANGED
@@ -585,6 +585,13 @@ type UploadOptions = Pick<express_fileupload__default.Options, "createParentPath
585
585
  * @example createHttpError(413, "The file is too large")
586
586
  * */
587
587
  limitError?: Error;
588
+ /**
589
+ * @desc A code to execute before connecting the upload middleware.
590
+ * @desc It can be used to connect a middleware that restricts the ability to upload.
591
+ * @default undefined
592
+ * @example ({ app }) => { app.use( ... ); }
593
+ * */
594
+ beforeUpload?: AppExtension;
588
595
  };
589
596
  type CompressionOptions = Pick<compression.CompressionOptions, "threshold" | "level" | "strategy" | "chunkSize" | "memLevel">;
590
597
  type AppExtension = (params: {
package/dist/index.d.ts CHANGED
@@ -585,6 +585,13 @@ type UploadOptions = Pick<express_fileupload__default.Options, "createParentPath
585
585
  * @example createHttpError(413, "The file is too large")
586
586
  * */
587
587
  limitError?: Error;
588
+ /**
589
+ * @desc A code to execute before connecting the upload middleware.
590
+ * @desc It can be used to connect a middleware that restricts the ability to upload.
591
+ * @default undefined
592
+ * @example ({ app }) => { app.use( ... ); }
593
+ * */
594
+ beforeUpload?: AppExtension;
588
595
  };
589
596
  type CompressionOptions = Pick<compression.CompressionOptions, "threshold" | "level" | "strategy" | "chunkSize" | "memLevel">;
590
597
  type AppExtension = (params: {
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ Original error: ${e.originalError.message}.`:""))};import{chain as So}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.1.2 (ESM)"),X({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,p,a)=>{e[p](s,async(d,c)=>{let m=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;m.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:m,config:r,siblingMethods:a})})},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,p)=>{if(!o)return p();e.handler({error:zo(o)?o:sr(400,pe(o).message),request:i,response:s,input:null,output:null,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}`),p=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:p,error:s,input:null,output:null})}catch(a){Fe({response:i,logger:p,error:new _(pe(a).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),p=ar(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:p}},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}},No=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))}if(r.use(e.server.jsonParser||cr.json()),e.server.upload){let d=await Q("express-fileupload"),{limitError:c,...m}={...typeof e.server.upload=="object"&&e.server.upload};r.use(d({...m,abortOnLimit:!1,parseNested:!0})),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()}));let{rootLogger:o,notFoundHandler:i,parserFailureHandler:s}=await mr(e);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 p=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),a={httpServer:p(Zo.createServer(r),e.server.listen),httpsServer:e.https?p(Mo.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...a,logger:o}};import Hn from"assert/strict";import{OpenApiBuilder as Un}from"openapi3-ts/oas31";import B from"assert/strict";import{isReferenceObject as te}from"openapi3-ts/oas31";import{both as ko,complement as Lo,concat as jo,filter as Ho,fromPairs as _e,has as Uo,isNil as Ko,map as le,mergeAll as Fo,mergeDeepRight as Bo,mergeDeepWith as qo,objOf as hr,omit as Ee,pipe as xr,pluck as Vo,range as $o,reject as Go,union as _o,when as Wo,xprod as We,zipObj as Yo}from"ramda";import{z as S}from"zod";import{z as lr}from"zod";var Ve=e=>!isNaN(e.getTime()),$e=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Pe="DateIn",ur=()=>P(Pe,lr.string().regex($e).transform(e=>new Date(e)).pipe(lr.date().refine(Ve)));import{z as Do}from"zod";var Ce="DateOut",fr=()=>P(Ce,Do.date().refine(Ve).transform(e=>e.toISOString()));var ee=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Te(e,"kind")||e._def.typeName,p=s?r[s]:void 0,a=i,c=p?p({schema:e,...a,next:l=>ee({schema:l,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),m=t&&t({schema:e,prev:c,...a});return m?{...c,...m}:c};var yr=50,Tr="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:[]},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)}}`),Qo=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),Xo=({schema:{_def:{innerType:e}},next:t})=>t(e),en=()=>({format:"any"}),tn=e=>(B(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),rn=({schema:e})=>({type:"string",format:e instanceof S.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),on=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),nn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),sn=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=qo((i,s)=>Array.isArray(i)&&Array.isArray(s)?jo(i,s):i===s?s:B.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=_o(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=W(t.examples||[],r.examples||[],([i,s])=>Bo(i,s))),o},an=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return sn(o)}catch{}return{allOf:o}},pn=({schema:e,next:t})=>t(e.unwrap()),dn=({schema:e,next:t})=>t(e._def.innerType),cn=({schema:e,next:t})=>{let r=t(e.unwrap());return te(r)||(r.type=Ar(r)),r},gr=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),mn=({schema:{value:e}})=>({type:typeof e,enum:[e]}),ln=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=a=>t&&xe(a)?a instanceof S.ZodOptional:a.isOptional(),s=o.filter(a=>!i(e.shape[a])),p={type:"object"};return o.length&&(p.properties=Ge({schema:e,isResponse:t,...r})),s.length&&(p.required=s),p},un=()=>({type:"null"}),fn=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:$e.source,externalDocs:{url:Tr}}),yn=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}}),gn=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})),hn=()=>({type:"boolean"}),xn=()=>({type:"integer",format:"bigint"}),Tn=e=>e.every(t=>t instanceof S.ZodLiteral),bn=({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=Ge({schema:S.object(_e(We(o,[t]))),...r}),i.required=o),i}if(e instanceof S.ZodLiteral)return{type:"object",properties:Ge({schema:S.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof S.ZodUnion&&Tn(e.options)){let o=le(s=>`${s.value}`,e.options),i=_e(We(o,[t]));return{type:"object",properties:Ge({schema:S.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},Sn=({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},On=({schema:{items:e},next:t})=>({type:"array",prefixItems:e.map(t)}),An=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:p,isULID:a,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:l}}})=>{let f=l.find(T=>T.kind==="regex"),x=l.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":m,email:e,url:t,uuid:i,cuid:s,cuid2:p,ulid:a,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},Rn=({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,p=i?i.inclusive:!0,a={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?a.minimum=r:a.exclusiveMinimum=r,p?a.maximum=s:a.exclusiveMaximum=s,a},Ge=({schema:{shape:e},next:t})=>le(t,e),Pn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Jo?.[t]},Ar=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Cn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!te(o)){let s=Le(e,Pn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.any())}if(!t&&i.type==="preprocess"&&!te(o)){let{type:s,...p}=o;return{...p,format:`${p.format||s} (preprocessed)`}}return o},In=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),En=({schema:e,next:t})=>t(e.unwrap()),wn=({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)))},zn=({next:e,schema:t})=>e(t.shape.raw),Rr=e=>e.length?Yo($o(1,e.length+1).map(t=>`example${t}`),le(hr("value"),e)):void 0,Pr=(e,t,r=[])=>xr(K,le(Wo(ko(E,Lo(Array.isArray)),Ee(r))),Rr)({schema:e,variant:t?"parsed":"original",validate:!0}),Zn=(e,t)=>xr(K,Ho(Uo(t)),Vo(t),Rr)({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)),Cr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:p,composition:a,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})),m=Sr(e),l=o.includes("query"),f=o.includes("params"),x=o.includes("headers"),b=g=>f&&m.includes(g),O=g=>x&&it(g);return Object.keys(c).filter(g=>l||b(g)).map(g=>{let T=ee({schema:c[g],isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:p,path:e,method:t}),L=a==="components"?p(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:Zn(r,g)}})},Tt={ZodString:An,ZodNumber:Rn,ZodBigInt:xn,ZodBoolean:hn,ZodNull:un,ZodArray:Sn,ZodTuple:On,ZodRecord:bn,ZodObject:ln,ZodLiteral:mn,ZodIntersection:an,ZodUnion:on,ZodAny:en,ZodDefault:Qo,ZodEnum:gr,ZodNativeEnum:gr,ZodEffects:Cn,ZodOptional:pn,ZodNullable:cn,ZodDiscriminatedUnion:nn,ZodBranded:En,ZodDate:gn,ZodCatch:Xo,ZodPipeline:In,ZodLazy:wn,ZodReadonly:dn,[F]:rn,[be]:tn,[Ce]:yn,[Pe]:fn,[Y]:zn},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,p=t&&xe(e),a=!i&&s&&!p&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),a&&(c.type=Ar(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.properties?Ee(t,e.properties):void 0,o=e.examples?e.examples.map(a=>Ee(t,a)):void 0,i=e.required?e.required.filter(a=>!t.includes(a)):void 0,s=e.allOf?e.allOf.map(a=>xt(a,t)):void 0,p=e.oneOf?e.oneOf.map(a=>xt(a,t)):void 0;return Ee(Object.entries({properties:r,required:i,examples:o,allOf:s,oneOf:p}).filter(([{},a])=>a===void 0).map(([a])=>a),{...e,properties:r,required:i,examples:o,allOf:s,oneOf:p})},Ir=e=>te(e)?e:Ee(["examples"],e),Er=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:p,makeRef:a,composition:d,hasMultipleStatusCodes:c,statusCode:m,description:l=`${e.toUpperCase()} ${t} ${at(i)} response ${c?m:""}`.trim()})=>{let f=Ir(ee({schema:r,isResponse:!0,rules:Tt,onEach:bt,onMissing:St,serializer:s,getRef:p,makeRef:a,path:t,method:e})),x={schema:d==="components"?a(I(l),f):f,examples:Pr(r,!0)};return{description:l,content:_e(We(o,[x]))}},Mn=()=>({type:"http",scheme:"basic"}),vn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Nn=({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},Dn=({name:e})=>({type:"apiKey",in:"header",name:e}),kn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ln=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),jn=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),Go(Ko,e))}),wr=(e,t)=>{let r={basic:Mn,bearer:vn,input:Nn,header:Dn,cookie:kn,openid:Ln,oauth2:jn};return Be(e,o=>r[o.type](o,t))},Ye=e=>"or"in e?e.or.map(t=>"and"in t?Fo(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:p,composition:a,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Sr(t),m=Ir(xt(ee({schema:r,isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:p,path:t,method:e}),c)),l={schema:a==="components"?p(I(d),m):m,examples:Pr(r,!1,c)};return{description:d,content:_e(We(o,[l]))}},Zr=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 Un{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 Hn(!(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:p,hasSummaryFromDescription:a=!0,composition:d="inline",serializer:c=ke}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});X({routing:t,onEndpoint:(l,f,x)=>{let b=x,O={path:f,method:b,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[g,T]=["short","long"].map(l.getDescription.bind(l)),L=g?Ot(g):a&&T?Ot(T):void 0,ze=l.getTags(),ye=r.inputSources?.[b]||ot[b],oe=this.ensureUniqOperationId(f,b,l.getOperationId(b)),Ze=Cr({...O,inputSources:ye,schema:l.getSchema("input"),description:p?.requestParameter?.call(null,{method:b,path:f,operationId:oe})}),Me={};for(let v of["positive","negative"]){let h=l.getResponses(v);for(let{mimeTypes:A,schema:R,statusCodes:z}of h)for(let ne of z)Me[ne]=Er({...O,variant:v,schema:R,mimeTypes:A,statusCode:ne,hasMultipleStatusCodes:h.length>1||z.length>1,description:p?.[`${v}Response`]?.call(null,{method:b,path:f,operationId:oe,statusCode:ne})})}let tt=ye.includes("body")?zr({...O,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:p?.requestBody?.call(null,{method:b,path:f,operationId:oe})}):void 0,ve=Ye(Be(wr(l.getSecurity(),ye),v=>{let h=this.ensureUniqSecuritySchemaName(v),A=["oauth2","openIdConnect"].includes(v.type)?l.getScopes():[];return this.addSecurityScheme(h,v),{name:h,scopes:A}}));this.addPath(Or(f),{[b]:{operationId:oe,summary:L,description:T,tags:ze.length>0?ze:void 0,parameters:Ze.length>0?Ze:void 0,requestBody:tt,security:ve.length>0?ve:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Zr(r.tags):[]}};import Mr from"http";var Kn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N),...t}),Fn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Mr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Mr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},Bn=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),qn=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let p=s||(await or([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,a=Kn({fnMethod:p,requestProps:t}),d=Fn({fnMethod:p,responseProps:r}),c=Bn({fnMethod:p,loggerProps:i}),m={cors:!1,logger:c,...o};return await e.execute({request:a,response:d,config:m,logger:c}),{requestMock:a,responseMock:d,loggerMock:c}};import w from"typescript";import k from"typescript";import{chain as vr,toPairs as Nr}from"ramda";var n=k.factory,q=[n.createModifier(k.SyntaxKind.ExportKeyword)],Vn=[n.createModifier(k.SyntaxKind.AsyncKeyword)],$n=[n.createModifier(k.SyntaxKind.PublicKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Dr=[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)],Nr(e)),Et=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),kr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Lr=(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),jr=(e,t,r)=>n.createPropertyDeclaration($n,e,void 0,t,r),Hr=(e,t,r)=>n.createClassDeclaration(q,e,void 0,void 0,[t,...r]),Ur=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Kr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.SyntaxKind.AnyKeyword)]),Fr=(e,t,r)=>n.createInterfaceDeclaration(q,e,void 0,t,r),Br=e=>vr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Nr(e)),zt=(e,t,r)=>n.createArrowFunction(r?Vn: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 qr=["get","post","put","delete","patch"];import y from"typescript";import{z as Nt}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},vt=(e,t)=>{let r=$.createSourceFile("print.ts","",$.ScriptTarget.Latest,!1,$.ScriptKind.TS);return $.createPrinter(t).printNode($.EmitHint.Unspecified,e,r)},Gn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Vr=e=>Gn.test(e)?et.createIdentifier(e):et.createStringLiteral(e);var{factory:u}=y,_n={[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},Wn=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Yn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,p])=>{let a=t&&xe(p)?p instanceof Nt.ZodOptional:p.isOptional(),d=u.createPropertySignature(void 0,Vr(s),a&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(p));return p.description&&Mt(d,p.description),d});return u.createTypeLiteralNode(i)},Jn=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),Qn=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),$r=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),Xn=e=>_n?.[e.kind],ei=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Le(e,Xn(o)),p={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&&p[s]||y.SyntaxKind.AnyKeyword)}return o},ti=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),ri=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},oi=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),ni=({next:e,schema:{items:t}})=>u.createTupleTypeNode(t.map(e)),ii=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),si=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),ai=({next:e,schema:t})=>e(t._def.innerType),re=e=>()=>u.createKeywordTypeNode(e),pi=({next:e,schema:t})=>e(t.unwrap()),di=({next:e,schema:t})=>e(t._def.innerType),ci=({next:e,schema:t})=>e(t._def.innerType),mi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),li=()=>u.createLiteralTypeNode(u.createNull()),ui=({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)))},fi=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof Nt.ZodString?t:e instanceof Nt.ZodUnion?o:r},yi=({next:e,schema:t})=>e(t.shape.raw),gi={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:li,ZodArray:Jn,ZodTuple:ni,ZodRecord:ii,ZodObject:Yn,ZodLiteral:Wn,ZodIntersection:si,ZodUnion:$r,ZodDefault:ai,ZodEnum:Qn,ZodNativeEnum:ti,ZodEffects:ei,ZodOptional:ri,ZodNullable:oi,ZodDiscriminatedUnion:$r,ZodBranded:pi,ZodCatch:ci,ZodPipeline:mi,ZodLazy:ui,ZodReadonly:di,[F]:fi,[Y]:yi},we=({schema:e,...t})=>ee({schema:e,rules:gi,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=ke,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=we({...z,schema:h.getSchema("input"),isResponse:!1}),ge=i?I(R,A,"positive.response"):void 0,kt=h.getSchema("positive"),Lt=i?we({...z,isResponse:!0,schema:kt}):void 0,he=i?I(R,A,"negative.response"):void 0,jt=h.getSchema("negative"),Ht=i?we({...z,isResponse:!0,schema:jt}):void 0,Ut=I(R,A,"response"),_r=ge&&he?n.createUnionTypeNode([n.createTypeReferenceNode(ge),n.createTypeReferenceNode(he)]):we({...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(_r,Ut)),R!=="options"&&(this.paths.push(A),this.registry[`${R} ${A}`]={input:ne,positive:ge,negative:he,response:Ut,isJson:h.getMimeTypes("positive").includes(N),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,qr)),this.program.push(Xe(this.ids.methodPathType,Ct([this.ids.methodType,this.ids.pathType])));let p=[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(Fr(h,p,Object.keys(this.registry).map(R=>{let z=this.registry[R][A];return z?Lr(R,z):void 0}).filter(R=>R!==void 0)));if(r==="types")return;let a=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(Br({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)}),Ur(this.ids.responseInterface,It))),m=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)}),Kr())),l=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,[l,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,[l]),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=Hr(this.ids.clientClass,kr([Je(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Dr)]),[jr(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(a,d,c,m,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(N))]),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])])))),ze=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))),Me=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([ze,ye,L,Me,Ze]),!0),n.createTypeReferenceNode(this.ids.implementationType))),ve=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"))])])),v=n.createVariableStatement(void 0,V(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(tt,v,ve)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:vt(r,t)).join(`
18
+ `;var ht=({app:e,rootLogger:t,config:r,routing:o})=>{r.startupLogo!==!1&&console.log(ir()),t.debug("Running","v17.2.0 (ESM)"),X({routing:o,hasCors:!!r.cors,onEndpoint:(i,s,p,a)=>{e[p](s,async(d,c)=>{let m=r.childLoggerProvider?await r.childLoggerProvider({request:d,parent:t}):t;m.info(`${d.method}: ${s}`),await i.execute({request:d,response:c,logger:m,config:r,siblingMethods:a})})},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,p)=>{if(!o)return p();e.handler({error:zo(o)?o:sr(400,pe(o).message),request:i,response:s,input:null,output:null,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}`),p=t?await t({request:o,parent:r}):r;try{e.handler({request:o,response:i,logger:p,error:s,input:null,output:null})}catch(a){Fe({response:i,logger:p,error:new _(pe(a).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),p=ar(i);return{rootLogger:t,errorHandler:r,notFoundHandler:s,parserFailureHandler:p}},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}},No=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:m,...l}={...typeof e.server.upload=="object"&&e.server.upload};m&&m({app:r,logger:o}),r.use(d({...l,abortOnLimit:!1,parseNested:!0})),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 p=(d,c)=>d.listen(c,()=>{o.info("Listening",c)}),a={httpServer:p(Zo.createServer(r),e.server.listen),httpsServer:e.https?p(Mo.createServer(e.https.options,r),e.https.listen):void 0};return{app:r,...a,logger:o}};import Hn from"assert/strict";import{OpenApiBuilder as Un}from"openapi3-ts/oas31";import B from"assert/strict";import{isReferenceObject as te}from"openapi3-ts/oas31";import{both as ko,complement as Lo,concat as jo,filter as Ho,fromPairs as _e,has as Uo,isNil as Ko,map as le,mergeAll as Fo,mergeDeepRight as Bo,mergeDeepWith as qo,objOf as hr,omit as Ee,pipe as xr,pluck as Vo,range as $o,reject as Go,union as _o,when as Wo,xprod as We,zipObj as Yo}from"ramda";import{z as S}from"zod";import{z as lr}from"zod";var Ve=e=>!isNaN(e.getTime()),$e=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;var Pe="DateIn",ur=()=>P(Pe,lr.string().regex($e).transform(e=>new Date(e)).pipe(lr.date().refine(Ve)));import{z as Do}from"zod";var Ce="DateOut",fr=()=>P(Ce,Do.date().refine(Ve).transform(e=>e.toISOString()));var ee=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=Te(e,"kind")||e._def.typeName,p=s?r[s]:void 0,a=i,c=p?p({schema:e,...a,next:l=>ee({schema:l,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),m=t&&t({schema:e,prev:c,...a});return m?{...c,...m}:c};var yr=50,Tr="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:[]},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)}}`),Qo=({schema:{_def:{innerType:e,defaultValue:t}},next:r})=>({...r(e),default:t()}),Xo=({schema:{_def:{innerType:e}},next:t})=>t(e),en=()=>({format:"any"}),tn=e=>(B(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),rn=({schema:e})=>({type:"string",format:e instanceof S.ZodString?e._def.checks.find(t=>t.kind==="regex")?"byte":"file":"binary"}),on=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),nn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:Array.from(e.values()).map(r)}),sn=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=qo((i,s)=>Array.isArray(i)&&Array.isArray(s)?jo(i,s):i===s?s:B.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=_o(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=W(t.examples||[],r.examples||[],([i,s])=>Bo(i,s))),o},an=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return sn(o)}catch{}return{allOf:o}},pn=({schema:e,next:t})=>t(e.unwrap()),dn=({schema:e,next:t})=>t(e._def.innerType),cn=({schema:e,next:t})=>{let r=t(e.unwrap());return te(r)||(r.type=Ar(r)),r},gr=({schema:e})=>({type:typeof Object.values(e.enum)[0],enum:Object.values(e.enum)}),mn=({schema:{value:e}})=>({type:typeof e,enum:[e]}),ln=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=a=>t&&xe(a)?a instanceof S.ZodOptional:a.isOptional(),s=o.filter(a=>!i(e.shape[a])),p={type:"object"};return o.length&&(p.properties=Ge({schema:e,isResponse:t,...r})),s.length&&(p.required=s),p},un=()=>({type:"null"}),fn=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:$e.source,externalDocs:{url:Tr}}),yn=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}}),gn=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})),hn=()=>({type:"boolean"}),xn=()=>({type:"integer",format:"bigint"}),Tn=e=>e.every(t=>t instanceof S.ZodLiteral),bn=({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=Ge({schema:S.object(_e(We(o,[t]))),...r}),i.required=o),i}if(e instanceof S.ZodLiteral)return{type:"object",properties:Ge({schema:S.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof S.ZodUnion&&Tn(e.options)){let o=le(s=>`${s.value}`,e.options),i=_e(We(o,[t]));return{type:"object",properties:Ge({schema:S.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},Sn=({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},On=({schema:{items:e},next:t})=>({type:"array",prefixItems:e.map(t)}),An=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:p,isULID:a,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:l}}})=>{let f=l.find(T=>T.kind==="regex"),x=l.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":m,email:e,url:t,uuid:i,cuid:s,cuid2:p,ulid:a,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},Rn=({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,p=i?i.inclusive:!0,a={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?a.minimum=r:a.exclusiveMinimum=r,p?a.maximum=s:a.exclusiveMaximum=s,a},Ge=({schema:{shape:e},next:t})=>le(t,e),Pn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Jo?.[t]},Ar=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Cn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!te(o)){let s=Le(e,Pn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.any())}if(!t&&i.type==="preprocess"&&!te(o)){let{type:s,...p}=o;return{...p,format:`${p.format||s} (preprocessed)`}}return o},In=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),En=({schema:e,next:t})=>t(e.unwrap()),wn=({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)))},zn=({next:e,schema:t})=>e(t.shape.raw),Rr=e=>e.length?Yo($o(1,e.length+1).map(t=>`example${t}`),le(hr("value"),e)):void 0,Pr=(e,t,r=[])=>xr(K,le(Wo(ko(E,Lo(Array.isArray)),Ee(r))),Rr)({schema:e,variant:t?"parsed":"original",validate:!0}),Zn=(e,t)=>xr(K,Ho(Uo(t)),Vo(t),Rr)({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)),Cr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:p,composition:a,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})),m=Sr(e),l=o.includes("query"),f=o.includes("params"),x=o.includes("headers"),b=g=>f&&m.includes(g),O=g=>x&&it(g);return Object.keys(c).filter(g=>l||b(g)).map(g=>{let T=ee({schema:c[g],isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:p,path:e,method:t}),L=a==="components"?p(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:Zn(r,g)}})},Tt={ZodString:An,ZodNumber:Rn,ZodBigInt:xn,ZodBoolean:hn,ZodNull:un,ZodArray:Sn,ZodTuple:On,ZodRecord:bn,ZodObject:ln,ZodLiteral:mn,ZodIntersection:an,ZodUnion:on,ZodAny:en,ZodDefault:Qo,ZodEnum:gr,ZodNativeEnum:gr,ZodEffects:Cn,ZodOptional:pn,ZodNullable:cn,ZodDiscriminatedUnion:nn,ZodBranded:En,ZodDate:gn,ZodCatch:Xo,ZodPipeline:In,ZodLazy:wn,ZodReadonly:dn,[F]:rn,[be]:tn,[Ce]:yn,[Pe]:fn,[Y]:zn},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,p=t&&xe(e),a=!i&&s&&!p&&e.isNullable(),d=i?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),a&&(c.type=Ar(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.properties?Ee(t,e.properties):void 0,o=e.examples?e.examples.map(a=>Ee(t,a)):void 0,i=e.required?e.required.filter(a=>!t.includes(a)):void 0,s=e.allOf?e.allOf.map(a=>xt(a,t)):void 0,p=e.oneOf?e.oneOf.map(a=>xt(a,t)):void 0;return Ee(Object.entries({properties:r,required:i,examples:o,allOf:s,oneOf:p}).filter(([{},a])=>a===void 0).map(([a])=>a),{...e,properties:r,required:i,examples:o,allOf:s,oneOf:p})},Ir=e=>te(e)?e:Ee(["examples"],e),Er=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:p,makeRef:a,composition:d,hasMultipleStatusCodes:c,statusCode:m,description:l=`${e.toUpperCase()} ${t} ${at(i)} response ${c?m:""}`.trim()})=>{let f=Ir(ee({schema:r,isResponse:!0,rules:Tt,onEach:bt,onMissing:St,serializer:s,getRef:p,makeRef:a,path:t,method:e})),x={schema:d==="components"?a(I(l),f):f,examples:Pr(r,!0)};return{description:l,content:_e(We(o,[x]))}},Mn=()=>({type:"http",scheme:"basic"}),vn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Nn=({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},Dn=({name:e})=>({type:"apiKey",in:"header",name:e}),kn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ln=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),jn=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),Go(Ko,e))}),wr=(e,t)=>{let r={basic:Mn,bearer:vn,input:Nn,header:Dn,cookie:kn,openid:Ln,oauth2:jn};return Be(e,o=>r[o.type](o,t))},Ye=e=>"or"in e?e.or.map(t=>"and"in t?Fo(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:p,composition:a,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Sr(t),m=Ir(xt(ee({schema:r,isResponse:!1,rules:Tt,onEach:bt,onMissing:St,serializer:i,getRef:s,makeRef:p,path:t,method:e}),c)),l={schema:a==="components"?p(I(d),m):m,examples:Pr(r,!1,c)};return{description:d,content:_e(We(o,[l]))}},Zr=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 Un{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 Hn(!(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:p,hasSummaryFromDescription:a=!0,composition:d="inline",serializer:c=ke}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});X({routing:t,onEndpoint:(l,f,x)=>{let b=x,O={path:f,method:b,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[g,T]=["short","long"].map(l.getDescription.bind(l)),L=g?Ot(g):a&&T?Ot(T):void 0,ze=l.getTags(),ye=r.inputSources?.[b]||ot[b],oe=this.ensureUniqOperationId(f,b,l.getOperationId(b)),Ze=Cr({...O,inputSources:ye,schema:l.getSchema("input"),description:p?.requestParameter?.call(null,{method:b,path:f,operationId:oe})}),Me={};for(let v of["positive","negative"]){let h=l.getResponses(v);for(let{mimeTypes:A,schema:R,statusCodes:z}of h)for(let ne of z)Me[ne]=Er({...O,variant:v,schema:R,mimeTypes:A,statusCode:ne,hasMultipleStatusCodes:h.length>1||z.length>1,description:p?.[`${v}Response`]?.call(null,{method:b,path:f,operationId:oe,statusCode:ne})})}let tt=ye.includes("body")?zr({...O,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:p?.requestBody?.call(null,{method:b,path:f,operationId:oe})}):void 0,ve=Ye(Be(wr(l.getSecurity(),ye),v=>{let h=this.ensureUniqSecuritySchemaName(v),A=["oauth2","openIdConnect"].includes(v.type)?l.getScopes():[];return this.addSecurityScheme(h,v),{name:h,scopes:A}}));this.addPath(Or(f),{[b]:{operationId:oe,summary:L,description:T,tags:ze.length>0?ze:void 0,parameters:Ze.length>0?Ze:void 0,requestBody:tt,security:ve.length>0?ve:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Zr(r.tags):[]}};import Mr from"http";var Kn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N),...t}),Fn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Mr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Mr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),...t};return r},Bn=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),qn=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let p=s||(await or([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,a=Kn({fnMethod:p,requestProps:t}),d=Fn({fnMethod:p,responseProps:r}),c=Bn({fnMethod:p,loggerProps:i}),m={cors:!1,logger:c,...o};return await e.execute({request:a,response:d,config:m,logger:c}),{requestMock:a,responseMock:d,loggerMock:c}};import w from"typescript";import k from"typescript";import{chain as vr,toPairs as Nr}from"ramda";var n=k.factory,q=[n.createModifier(k.SyntaxKind.ExportKeyword)],Vn=[n.createModifier(k.SyntaxKind.AsyncKeyword)],$n=[n.createModifier(k.SyntaxKind.PublicKeyword),n.createModifier(k.SyntaxKind.ReadonlyKeyword)],Dr=[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)],Nr(e)),Et=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),kr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Lr=(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),jr=(e,t,r)=>n.createPropertyDeclaration($n,e,void 0,t,r),Hr=(e,t,r)=>n.createClassDeclaration(q,e,void 0,void 0,[t,...r]),Ur=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Kr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(k.SyntaxKind.AnyKeyword)]),Fr=(e,t,r)=>n.createInterfaceDeclaration(q,e,void 0,t,r),Br=e=>vr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Nr(e)),zt=(e,t,r)=>n.createArrowFunction(r?Vn: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 qr=["get","post","put","delete","patch"];import y from"typescript";import{z as Nt}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},vt=(e,t)=>{let r=$.createSourceFile("print.ts","",$.ScriptTarget.Latest,!1,$.ScriptKind.TS);return $.createPrinter(t).printNode($.EmitHint.Unspecified,e,r)},Gn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Vr=e=>Gn.test(e)?et.createIdentifier(e):et.createStringLiteral(e);var{factory:u}=y,_n={[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},Wn=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Yn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,p])=>{let a=t&&xe(p)?p instanceof Nt.ZodOptional:p.isOptional(),d=u.createPropertySignature(void 0,Vr(s),a&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(p));return p.description&&Mt(d,p.description),d});return u.createTypeLiteralNode(i)},Jn=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),Qn=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),$r=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),Xn=e=>_n?.[e.kind],ei=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Le(e,Xn(o)),p={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&&p[s]||y.SyntaxKind.AnyKeyword)}return o},ti=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),ri=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},oi=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),ni=({next:e,schema:{items:t}})=>u.createTupleTypeNode(t.map(e)),ii=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),si=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),ai=({next:e,schema:t})=>e(t._def.innerType),re=e=>()=>u.createKeywordTypeNode(e),pi=({next:e,schema:t})=>e(t.unwrap()),di=({next:e,schema:t})=>e(t._def.innerType),ci=({next:e,schema:t})=>e(t._def.innerType),mi=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),li=()=>u.createLiteralTypeNode(u.createNull()),ui=({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)))},fi=({schema:e})=>{let t=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),r=u.createTypeReferenceNode("Buffer"),o=u.createUnionTypeNode([t,r]);return e instanceof Nt.ZodString?t:e instanceof Nt.ZodUnion?o:r},yi=({next:e,schema:t})=>e(t.shape.raw),gi={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:li,ZodArray:Jn,ZodTuple:ni,ZodRecord:ii,ZodObject:Yn,ZodLiteral:Wn,ZodIntersection:si,ZodUnion:$r,ZodDefault:ai,ZodEnum:Qn,ZodNativeEnum:ti,ZodEffects:ei,ZodOptional:ri,ZodNullable:oi,ZodDiscriminatedUnion:$r,ZodBranded:pi,ZodCatch:ci,ZodPipeline:mi,ZodLazy:ui,ZodReadonly:di,[F]:fi,[Y]:yi},we=({schema:e,...t})=>ee({schema:e,rules:gi,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=ke,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=we({...z,schema:h.getSchema("input"),isResponse:!1}),ge=i?I(R,A,"positive.response"):void 0,kt=h.getSchema("positive"),Lt=i?we({...z,isResponse:!0,schema:kt}):void 0,he=i?I(R,A,"negative.response"):void 0,jt=h.getSchema("negative"),Ht=i?we({...z,isResponse:!0,schema:jt}):void 0,Ut=I(R,A,"response"),_r=ge&&he?n.createUnionTypeNode([n.createTypeReferenceNode(ge),n.createTypeReferenceNode(he)]):we({...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(_r,Ut)),R!=="options"&&(this.paths.push(A),this.registry[`${R} ${A}`]={input:ne,positive:ge,negative:he,response:Ut,isJson:h.getMimeTypes("positive").includes(N),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,qr)),this.program.push(Xe(this.ids.methodPathType,Ct([this.ids.methodType,this.ids.pathType])));let p=[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(Fr(h,p,Object.keys(this.registry).map(R=>{let z=this.registry[R][A];return z?Lr(R,z):void 0}).filter(R=>R!==void 0)));if(r==="types")return;let a=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(Br({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)}),Ur(this.ids.responseInterface,It))),m=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)}),Kr())),l=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,[l,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,[l]),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=Hr(this.ids.clientClass,kr([Je(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),Dr)]),[jr(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(a,d,c,m,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(N))]),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])])))),ze=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))),Me=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([ze,ye,L,Me,Ze]),!0),n.createTypeReferenceNode(this.ids.implementationType))),ve=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"))])])),v=n.createVariableStatement(void 0,V(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(tt,v,ve)}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.addSyntheticLeadingComment(w.addSyntheticLeadingComment(n.createEmptyStatement(),w.SyntaxKind.SingleLineCommentTrivia," Usage example:"),w.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "17.1.2",
3
+ "version": "17.2.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": {