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