express-zod-api
Advanced tools
Comparing version 20.21.2 to 20.22.0
@@ -272,2 +272,17 @@ import * as zod from 'zod'; | ||
declare class DependsOnMethod extends Nesting { | ||
readonly pairs: ReadonlyArray<[Method, AbstractEndpoint]>; | ||
readonly firstEndpoint: AbstractEndpoint | undefined; | ||
readonly siblingMethods: ReadonlyArray<Method>; | ||
constructor(endpoints: Partial<Record<Method, AbstractEndpoint>>); | ||
} | ||
type OriginalStatic = typeof express__default.static; | ||
type StaticHandler = ReturnType<OriginalStatic>; | ||
declare class ServeStatic { | ||
params: Parameters<OriginalStatic>; | ||
constructor(...params: Parameters<OriginalStatic>); | ||
apply(path: string, cb: (path: string, handler: StaticHandler) => void): void; | ||
} | ||
type ResultSchema<R extends Result> = R extends Result<infer S> ? S : never; | ||
@@ -356,2 +371,13 @@ /** | ||
type ChildLoggerExtractor = (request: Request) => ActualLogger; | ||
interface Routing { | ||
[SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic; | ||
} | ||
declare abstract class Nesting { | ||
/** @desc Enables nested routes within the path assigned to the subject */ | ||
nest(routing: Routing): Routing; | ||
} | ||
type Handler<IN, OUT, OPT> = (params: { | ||
@@ -365,3 +391,3 @@ input: IN; | ||
type MimeVariant = Extract<IOVariant, "input"> | ResponseVariant; | ||
declare abstract class AbstractEndpoint { | ||
declare abstract class AbstractEndpoint extends Nesting { | ||
abstract execute(params: { | ||
@@ -422,4 +448,2 @@ request: Request; | ||
type ChildLoggerExtractor = (request: Request) => ActualLogger; | ||
type InputSource = keyof Pick<Request, "query" | "body" | "files" | "params" | "headers">; | ||
@@ -700,21 +724,2 @@ type InputSources = Record<Method, InputSource[]>; | ||
declare class DependsOnMethod { | ||
readonly pairs: ReadonlyArray<[Method, AbstractEndpoint]>; | ||
readonly firstEndpoint: AbstractEndpoint | undefined; | ||
readonly siblingMethods: ReadonlyArray<Method>; | ||
constructor(endpoints: Partial<Record<Method, AbstractEndpoint>>); | ||
} | ||
type OriginalStatic = typeof express__default.static; | ||
type StaticHandler = ReturnType<OriginalStatic>; | ||
declare class ServeStatic { | ||
params: Parameters<OriginalStatic>; | ||
constructor(...params: Parameters<OriginalStatic>); | ||
apply(path: string, cb: (path: string, handler: StaticHandler) => void): void; | ||
} | ||
interface Routing { | ||
[SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic; | ||
} | ||
declare const attachRouting: (config: AppConfig, routing: Routing) => { | ||
@@ -721,0 +726,0 @@ notFoundHandler: express__default.RequestHandler<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>>; |
@@ -1,4 +0,4 @@ | ||
import{clone as Yt,fromPairs as wo,map as Co,pipe as zo,toPairs as Io,pair as Eo}from"ramda";import{z as de}from"zod";import{memoizeWith as ho,pickBy as xo,xprod as bo}from"ramda";import{z as So}from"zod";var O={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var ce=class extends Error{name="RoutingError"},E=class extends Error{name="DocumentationError";cause;constructor({message:t,method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},He=class extends Error{name="IOSchemaError"},G=class extends He{constructor(r){super(Y(r),{cause:r});this.cause=r}name="OutputValidationError";get originalError(){return this.cause}},U=class extends He{constructor(r){super(Y(r),{cause:r});this.cause=r}name="InputValidationError";get originalError(){return this.cause}},D=class extends Error{constructor(r,o){super(Y(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Oe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var To=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(O.upload);return"files"in e&&r},mt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Oo=["body","query","params"],ut=e=>e.method.toLowerCase(),ft=e=>e.startsWith("x-"),Ro=e=>xo((t,r)=>ft(r),e),De=(e,t={})=>{let r=ut(e);return r==="options"?{}:(t[r]||mt[r]||Oo).filter(o=>o==="files"?To(e):!0).map(o=>o==="headers"?Ro(e[o]):e[o]).reduce((o,n)=>Object.assign(o,n),{})},K=e=>e instanceof Error?e:new Error(String(e)),Y=e=>e instanceof So.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof G?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},Q=(e,t,r)=>e.length&&t.length?bo(e,t).map(r):e.concat(t),Re=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,yt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),Z=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(yt).join(""),Ke=(e,t)=>{try{return typeof e.parse(t)}catch{return}},J=e=>typeof e=="object"&&e!==null,Fe=ho(()=>"static",()=>process.env.NODE_ENV==="production");import{clone as Ao,mergeDeepRight as Po}from"ramda";var g=Symbol.for("express-zod-api"),Be=e=>{let t=e.describe(e.description);return t._def[g]=Ao(t._def[g])||{examples:[]},t},Gt=(e,t)=>{if(!(g in e._def))return t;let r=Be(t);return r._def[g].examples=Q(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Po({...o},{...n}):n),r};var Zo=function(e){let t=Be(this);return t._def[g].examples.push(e),t},vo=function(e){let t=Be(this);return t._def[g].defaultLabel=e,t},jo=function(e){return new de.ZodBranded({typeName:de.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...Yt(this._def[g]),brand:e}})},Lo=function(e){let t=typeof e=="function"?e:zo(Io,Co(([n,i])=>Eo(e[String(n)]||n,i)),wo),r=t(Yt(this.shape)),o=de.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(de.ZodType.prototype,{example:{get(){return Zo.bind(this)}},brand:{set(){},get(){return jo.bind(this)}}}),Object.defineProperty(de.ZodDefault.prototype,"label",{get(){return vo.bind(this)}}),Object.defineProperty(de.ZodObject.prototype,"remap",{get(){return Lo.bind(this)}}));function No(e){return e}import{z as _o}from"zod";import{z as ir}from"zod";import{fail as A}from"node:assert/strict";import{z as Ae}from"zod";var qe=e=>!isNaN(e.getTime());var W=Symbol("DateIn"),Qt=()=>Ae.union([Ae.string().date(),Ae.string().datetime(),Ae.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ae.date().refine(qe)).brand(W);import{z as ko}from"zod";var X=Symbol("DateOut"),Jt=()=>ko.date().refine(qe).transform(e=>e.toISOString()).brand(X);import{z as Ve}from"zod";var N=Symbol("File"),Wt=Ve.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Mo={buffer:()=>Wt.brand(N),string:()=>Ve.string().brand(N),binary:()=>Wt.or(Ve.string()).brand(N),base64:()=>Ve.string().base64().brand(N)};function $e(e){return Mo[e||"string"]()}import{z as Uo}from"zod";var B=Symbol("Raw"),Xt=(e={})=>Uo.object({raw:$e("buffer")}).extend(e).brand(B);import{z as Ho}from"zod";var le=Symbol("Upload"),er=()=>Ho.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(le);var tr=(e,{next:t})=>e.options.some(t),Do=({_def:e},{next:t})=>[e.left,e.right].some(t),_e=(e,{next:t})=>t(e.unwrap()),gt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:tr,ZodDiscriminatedUnion:tr,ZodIntersection:Do,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:_e,ZodNullable:_e,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Ge=(e,{condition:t,rules:r=gt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let i=o<n?r[e._def[g]?.brand]||r[e._def.typeName]:void 0;return i?i(e,{next:a=>Ge(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},rr=e=>Ge(e,{condition:t=>t._def[g]?.brand===le}),or=e=>Ge(e,{condition:t=>t._def[g]?.brand===B,maxDepth:3}),ht=(e,t)=>{let r=new WeakSet;return Ge(e,{maxDepth:300,rules:{...gt,ZodBranded:_e,ZodReadonly:_e,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:i})=>[...o].concat(n??[]).some(i),ZodEffects:{out:void 0,in:gt.ZodEffects}[t],ZodNaN:()=>A("z.nan()"),ZodSymbol:()=>A("z.symbol()"),ZodFunction:()=>A("z.function()"),ZodMap:()=>A("z.map()"),ZodSet:()=>A("z.set()"),ZodBigInt:()=>A("z.bigint()"),ZodVoid:()=>A("z.void()"),ZodPromise:()=>A("z.promise()"),ZodNever:()=>A("z.never()"),ZodDate:()=>t==="in"&&A("z.date()"),[X]:()=>t==="in"&&A("ez.dateOut()"),[W]:()=>t==="out"&&A("ez.dateIn()"),[B]:()=>t==="out"&&A("ez.raw()"),[le]:()=>t==="out"&&A("ez.upload()"),[N]:()=>!1}})};import qo,{isHttpError as Vo}from"http-errors";import nr,{isHttpError as Ko}from"http-errors";import{z as Fo}from"zod";var Ye=(e,t)=>{if(typeof e=="function")return Ye(e(...t.arguments),t);if(e instanceof Fo.ZodType)return[{...t,schema:e}];if(Array.isArray(e)&&!e.length)throw new D(new Error(`At least one ${t.variant} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes}))},xt=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Bo=e=>Pe(e).statusCode,Pe=e=>Ko(e)?e:nr(e instanceof U?400:500,Y(e),{cause:e.cause||e}),we=e=>Fe()&&!e.expose?nr(e.statusCode).message:e.message;var Qe=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=we(qo(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?` | ||
Original error: ${e.handled.message}.`:""),{expose:Vo(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{chain as $o}from"ramda";var ee=e=>J(e)&&"or"in e,ue=e=>J(e)&&"and"in e,bt=e=>({and:$o(t=>ue(t)?t.and:[t],e)}),Je=(e,t)=>ue(e)?{and:e.and.map(r=>ee(r)?{or:r.or.map(t)}:t(r))}:ee(e)?{or:e.or.map(r=>ue(r)?{and:r.and.map(t)}:t(r))}:t(e),St=e=>e.and.reduce((t,r)=>({or:Q(t.or,ee(r)?r.or:[r],bt)}),{or:[]}),me=(e,t)=>ue(e)?ee(t)?me(St(e),t):bt([e,t]):ee(e)?ue(t)?me(t,e):ee(t)?{or:Q(e.or,t.or,bt)}:me(e,{and:[t]}):ue(t)||ee(t)?me(t,e):{and:[e,t]};import{z as sr}from"zod";var Tt=class{},q=class extends Tt{#e;#t;#r;constructor({input:t=sr.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof sr.ZodError?new U(o):o}}},fe=class extends q{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:i})=>new Promise((a,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,d)?.catch(d)})})}};var Ce=class{},We=class extends Ce{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:m,shortDescription:l}){super(),this.#a=n,this.#p=i,this.#r=d,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:m,short:l},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=rr(r)?"upload":or(r)?"raw":"json",this.#i={input:Object.freeze([O[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?me(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof ir.ZodError?new G(r):r}}async#f({method:t,logger:r,options:o,response:n,...i}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof fe))&&(Object.assign(o,await a.execute({...i,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#y({input:t,...r}){let o;try{o=await this.#n.input.parseAsync(t)}catch(n){throw n instanceof ir.ZodError?new U(n):n}return this.#a({...r,input:o})}async#g({error:t,...r}){try{await this.#p.execute({...r,error:t})}catch(o){Qe({...r,error:new D(K(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=ut(t),p={},d=null,c=null;if(n.cors){let l=this.#m(i);typeof n.cors=="function"&&(l=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:l}));for(let u in l)r.set(u,l[u])}let m=De(t,n.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options")return void r.status(200).end();d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(l){c=K(l)}await this.#g({input:m,output:d,request:t,response:r,error:c,logger:o,options:p})}};var ar=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>Gt(i,n),o)};import{z as k}from"zod";var te={positive:200,negative:400};var Ot=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ze=class extends Ot{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Ye(this.#e,{variant:"positive",arguments:[t],statusCodes:[te.positive],mimeTypes:[O.json]})}getNegativeResponse(){return Ye(this.#t,{variant:"negative",arguments:[],statusCodes:[te.negative],mimeTypes:[O.json]})}},Ie=new ze({positive:e=>{let t=F({schema:e}),r=k.object({status:k.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:k.object({status:k.literal("error"),error:k.object({message:k.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(e){let a=Pe(e);return xt(a,i,o,t),void n.status(a.statusCode).json({status:"error",error:{message:we(a)}})}n.status(te.positive).json({status:"success",data:r})}}),Rt=new ze({positive:e=>{let t=F({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof k.ZodArray?e.shape.items:k.array(k.any());return t.reduce((o,n)=>J(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:k.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=Pe(r);return xt(a,o,n,i),void e.status(a.statusCode).type("text/plain").send(we(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(te.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Ee=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof q?t:new q(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new fe(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new q({handler:t})),this.resultHandler)}build({input:t=_o.object({}),handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],l=typeof a=="function"?a:()=>a,u="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],S="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new We({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:u,tags:S,methods:m,getOperationId:l,description:n,shortDescription:i,inputSchema:ar(d,t)})}},Go=new Ee(Ie),Yo=new Ee(Rt);import{Ansis as Jo,blue as Wo,cyanBright as Xo,green as en,hex as tn,red as rn}from"ansis";import{inspect as on}from"node:util";import{performance as fr}from"node:perf_hooks";var et={debug:10,info:20,warn:30,error:40},cr=e=>J(e)&&Object.keys(et).some(t=>t in e),dr=e=>e in et,lr=(e,t)=>et[e]<et[t],mr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),Xe=mr(),pr=mr(2),Qo=e=>e<1e-6?["picosecond",e/1e-9,Xe]:e<.001?["nanosecond",e/1e-6,Xe]:e<1?["microsecond",e/.001,Xe]:e<1e3?["millisecond",e,Xe]:e<6e4?["second",e/1e3,pr]:["minute",e/6e4,pr],ur=e=>{let[t,r,o]=Qo(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var Ze=class e{config;styles={debug:Wo,info:en,warn:tn("#FFA500"),error:rn};constructor(t={}){let{color:r=new Jo().isSupported(),level:o=Fe()?"warn":"debug",depth:n=2,ctx:i={}}=t;this.config={color:r,level:o,depth:n,ctx:i}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return on(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:i,...a},color:p}=this.config;if(n==="silent"||lr(t,n))return;let d=[new Date().toISOString()];i&&d.push(p?Xo(i):i),d.push(p?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=fr.now();return()=>{let o=fr.now()-r,{message:n,severity:i="debug",formatter:a=ur}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};import{head as nn,tail as sn,toPairs as an}from"ramda";var ve=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(an(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=nn(this.pairs)?.[1],this.siblingMethods=Object.freeze(sn(this.pairs).map(([r])=>r))}};import pn from"express";var je=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,pn.static(...this.params))}};import Pt from"express";import yn from"node:http";import gn from"node:https";var ye=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Oe(e)};var re=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){if(a.includes("/"))throw new ce(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`);let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof Ce){let c=p.getMethods().slice();n&&c.push("options");for(let m of c)t(p,d,m)}else if(p instanceof je)r&&p.apply(d,r);else if(p instanceof ve){for(let[c,m]of p.pairs){if(!m.getMethods().includes(c))throw new ce(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`);t(m,d,c)}n&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else re({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:d})}};var At=({app:e,rootLogger:t,getChildLogger:r,config:o,routing:n,parsers:i})=>{let a=new WeakSet;re({routing:n,hasCors:!!o.cors,onEndpoint:(p,d,c,m)=>{let l=p.getRequestType();if(!a.has(p)){if(l==="json")try{ht(p.getSchema("input"),"in")}catch(u){t.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",{path:d,method:c,reason:u})}for(let u of["positive","negative"])if(p.getMimeTypes(u).includes(O.json))try{ht(p.getSchema(u),"out")}catch(S){t.warn(`The final ${u} response schema of the endpoint contains an unsupported JSON payload type.`,{path:d,method:c,reason:S})}a.add(p)}e[c](d,...i?.[l]||[],async(u,S)=>p.execute({request:u,response:S,logger:r(u),config:o,siblingMethods:m}))},onStatic:(p,d)=>{e.use(p,d)}})};import Tr,{isHttpError as dn}from"http-errors";import{setInterval as cn}from"node:timers/promises";var yr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",gr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",hr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,xr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),br=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Sr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(yr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",xr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(hr(c)||gr(c))&&a(c);for await(let c of cn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(br))};return{sockets:n,shutdown:()=>o??=d()}};var Or=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:dn(r)?r:Tr(400,K(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Rr=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=Tr(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){Qe({response:o,logger:i,error:new D(K(a),n)})}},ln=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},mn=e=>({log:e.debug.bind(e)}),Ar=async({getChildLogger:e,config:t})=>{let r=await ye("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let m=e(p);try{await n?.({request:p,logger:m})}catch(l){return c(l)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:mn(m)})(p,d,c)}),o&&a.push(ln(o)),a},Pr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},wr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:i}),n()},Cr=e=>t=>t.res?.locals[g]?.logger||e,zr=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(` | ||
`).slice(1))),Ir=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Sr(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};import{gray as un,hex as Er,italic as tt,whiteBright as fn}from"ansis";var Zr=()=>{let e=tt("Proudly supports transgender community.".padStart(109)),t=tt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=tt("Thank you for choosing Express Zod API for your project.".padStart(132)),o=tt("for Zoey".padEnd(20)),n=Er("#F5A9B8"),i=Er("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(fn,5,7).fill(n,7,9).fill(i,9,12).fill(un,12,13);return` | ||
import{clone as Qt,fromPairs as Co,map as zo,pipe as Io,toPairs as Eo,pair as Zo}from"ramda";import{z as de}from"zod";import{memoizeWith as xo,pickBy as bo,xprod as So}from"ramda";import{z as To}from"zod";var O={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var ce=class extends Error{name="RoutingError"},E=class extends Error{name="DocumentationError";cause;constructor({message:t,method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},De=class extends Error{name="IOSchemaError"},G=class extends De{constructor(r){super(Y(r),{cause:r});this.cause=r}name="OutputValidationError";get originalError(){return this.cause}},U=class extends De{constructor(r){super(Y(r),{cause:r});this.cause=r}name="InputValidationError";get originalError(){return this.cause}},D=class extends Error{constructor(r,o){super(Y(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Re=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Oo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(O.upload);return"files"in e&&r},ut={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Ro=["body","query","params"],ft=e=>e.method.toLowerCase(),yt=e=>e.startsWith("x-"),Ao=e=>bo((t,r)=>yt(r),e),Ke=(e,t={})=>{let r=ft(e);return r==="options"?{}:(t[r]||ut[r]||Ro).filter(o=>o==="files"?Oo(e):!0).map(o=>o==="headers"?Ao(e[o]):e[o]).reduce((o,n)=>Object.assign(o,n),{})},K=e=>e instanceof Error?e:new Error(String(e)),Y=e=>e instanceof To.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof G?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},Q=(e,t,r)=>e.length&&t.length?So(e,t).map(r):e.concat(t),Ae=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,gt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),Z=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(gt).join(""),Fe=(e,t)=>{try{return typeof e.parse(t)}catch{return}},J=e=>typeof e=="object"&&e!==null,Be=xo(()=>"static",()=>process.env.NODE_ENV==="production");import{clone as Po,mergeDeepRight as wo}from"ramda";var g=Symbol.for("express-zod-api"),qe=e=>{let t=e.describe(e.description);return t._def[g]=Po(t._def[g])||{examples:[]},t},Yt=(e,t)=>{if(!(g in e._def))return t;let r=qe(t);return r._def[g].examples=Q(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?wo({...o},{...n}):n),r};var vo=function(e){let t=qe(this);return t._def[g].examples.push(e),t},jo=function(e){let t=qe(this);return t._def[g].defaultLabel=e,t},Lo=function(e){return new de.ZodBranded({typeName:de.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...Qt(this._def[g]),brand:e}})},No=function(e){let t=typeof e=="function"?e:Io(Eo,zo(([n,i])=>Zo(e[String(n)]||n,i)),Co),r=t(Qt(this.shape)),o=de.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(de.ZodType.prototype,{example:{get(){return vo.bind(this)}},brand:{set(){},get(){return Lo.bind(this)}}}),Object.defineProperty(de.ZodDefault.prototype,"label",{get(){return jo.bind(this)}}),Object.defineProperty(de.ZodObject.prototype,"remap",{get(){return No.bind(this)}}));function ko(e){return e}import{z as Go}from"zod";import{z as ar}from"zod";import{fail as A}from"node:assert/strict";import{z as Pe}from"zod";var Ve=e=>!isNaN(e.getTime());var W=Symbol("DateIn"),Jt=()=>Pe.union([Pe.string().date(),Pe.string().datetime(),Pe.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Pe.date().refine(Ve)).brand(W);import{z as Mo}from"zod";var X=Symbol("DateOut"),Wt=()=>Mo.date().refine(Ve).transform(e=>e.toISOString()).brand(X);import{z as $e}from"zod";var N=Symbol("File"),Xt=$e.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Uo={buffer:()=>Xt.brand(N),string:()=>$e.string().brand(N),binary:()=>Xt.or($e.string()).brand(N),base64:()=>$e.string().base64().brand(N)};function _e(e){return Uo[e||"string"]()}import{z as Ho}from"zod";var B=Symbol("Raw"),er=(e={})=>Ho.object({raw:_e("buffer")}).extend(e).brand(B);import{z as Do}from"zod";var le=Symbol("Upload"),tr=()=>Do.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(le);var rr=(e,{next:t})=>e.options.some(t),Ko=({_def:e},{next:t})=>[e.left,e.right].some(t),Ge=(e,{next:t})=>t(e.unwrap()),ht={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:rr,ZodDiscriminatedUnion:rr,ZodIntersection:Ko,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:Ge,ZodNullable:Ge,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Ye=(e,{condition:t,rules:r=ht,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let i=o<n?r[e._def[g]?.brand]||r[e._def.typeName]:void 0;return i?i(e,{next:a=>Ye(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},or=e=>Ye(e,{condition:t=>t._def[g]?.brand===le}),nr=e=>Ye(e,{condition:t=>t._def[g]?.brand===B,maxDepth:3}),xt=(e,t)=>{let r=new WeakSet;return Ye(e,{maxDepth:300,rules:{...ht,ZodBranded:Ge,ZodReadonly:Ge,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:i})=>[...o].concat(n??[]).some(i),ZodEffects:{out:void 0,in:ht.ZodEffects}[t],ZodNaN:()=>A("z.nan()"),ZodSymbol:()=>A("z.symbol()"),ZodFunction:()=>A("z.function()"),ZodMap:()=>A("z.map()"),ZodSet:()=>A("z.set()"),ZodBigInt:()=>A("z.bigint()"),ZodVoid:()=>A("z.void()"),ZodPromise:()=>A("z.promise()"),ZodNever:()=>A("z.never()"),ZodDate:()=>t==="in"&&A("z.date()"),[X]:()=>t==="in"&&A("ez.dateOut()"),[W]:()=>t==="out"&&A("ez.dateIn()"),[B]:()=>t==="out"&&A("ez.raw()"),[le]:()=>t==="out"&&A("ez.upload()"),[N]:()=>!1}})};import Vo,{isHttpError as $o}from"http-errors";import sr,{isHttpError as Fo}from"http-errors";import{z as Bo}from"zod";var Qe=(e,t)=>{if(typeof e=="function")return Qe(e(...t.arguments),t);if(e instanceof Bo.ZodType)return[{...t,schema:e}];if(Array.isArray(e)&&!e.length)throw new D(new Error(`At least one ${t.variant} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes}))},bt=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),qo=e=>we(e).statusCode,we=e=>Fo(e)?e:sr(e instanceof U?400:500,Y(e),{cause:e.cause||e}),Ce=e=>Be()&&!e.expose?sr(e.statusCode).message:e.message;var Je=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ce(Vo(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?` | ||
Original error: ${e.handled.message}.`:""),{expose:$o(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{chain as _o}from"ramda";var ee=e=>J(e)&&"or"in e,ue=e=>J(e)&&"and"in e,St=e=>({and:_o(t=>ue(t)?t.and:[t],e)}),We=(e,t)=>ue(e)?{and:e.and.map(r=>ee(r)?{or:r.or.map(t)}:t(r))}:ee(e)?{or:e.or.map(r=>ue(r)?{and:r.and.map(t)}:t(r))}:t(e),Tt=e=>e.and.reduce((t,r)=>({or:Q(t.or,ee(r)?r.or:[r],St)}),{or:[]}),me=(e,t)=>ue(e)?ee(t)?me(Tt(e),t):St([e,t]):ee(e)?ue(t)?me(t,e):ee(t)?{or:Q(e.or,t.or,St)}:me(e,{and:[t]}):ue(t)||ee(t)?me(t,e):{and:[e,t]};import{z as ir}from"zod";var Ot=class{},q=class extends Ot{#e;#t;#r;constructor({input:t=ir.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof ir.ZodError?new U(o):o}}},fe=class extends q{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:i})=>new Promise((a,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,d)?.catch(d)})})}};var ye=class{nest(t){return Object.assign(t,{"":this})}};var ze=class extends ye{},Xe=class extends ze{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:m,shortDescription:l}){super(),this.#a=n,this.#p=i,this.#r=d,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:m,short:l},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=or(r)?"upload":nr(r)?"raw":"json",this.#i={input:Object.freeze([O[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?me(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof ar.ZodError?new G(r):r}}async#f({method:t,logger:r,options:o,response:n,...i}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof fe))&&(Object.assign(o,await a.execute({...i,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#y({input:t,...r}){let o;try{o=await this.#n.input.parseAsync(t)}catch(n){throw n instanceof ar.ZodError?new U(n):n}return this.#a({...r,input:o})}async#g({error:t,...r}){try{await this.#p.execute({...r,error:t})}catch(o){Je({...r,error:new D(K(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=ft(t),p={},d=null,c=null;if(n.cors){let l=this.#m(i);typeof n.cors=="function"&&(l=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:l}));for(let u in l)r.set(u,l[u])}let m=Ke(t,n.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options")return void r.status(200).end();d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(l){c=K(l)}await this.#g({input:m,output:d,request:t,response:r,error:c,logger:o,options:p})}};var pr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>Yt(i,n),o)};import{z as k}from"zod";var te={positive:200,negative:400};var Rt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Ie=class extends Rt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Qe(this.#e,{variant:"positive",arguments:[t],statusCodes:[te.positive],mimeTypes:[O.json]})}getNegativeResponse(){return Qe(this.#t,{variant:"negative",arguments:[],statusCodes:[te.negative],mimeTypes:[O.json]})}},Ee=new Ie({positive:e=>{let t=F({schema:e}),r=k.object({status:k.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:k.object({status:k.literal("error"),error:k.object({message:k.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(e){let a=we(e);return bt(a,i,o,t),void n.status(a.statusCode).json({status:"error",error:{message:Ce(a)}})}n.status(te.positive).json({status:"success",data:r})}}),At=new Ie({positive:e=>{let t=F({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof k.ZodArray?e.shape.items:k.array(k.any());return t.reduce((o,n)=>J(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:k.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=we(r);return bt(a,o,n,i),void e.status(a.statusCode).type("text/plain").send(Ce(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(te.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Ze=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof q?t:new q(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new fe(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new q({handler:t})),this.resultHandler)}build({input:t=Go.object({}),handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],l=typeof a=="function"?a:()=>a,u="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],S="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new Xe({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:u,tags:S,methods:m,getOperationId:l,description:n,shortDescription:i,inputSchema:pr(d,t)})}},Yo=new Ze(Ee),Qo=new Ze(At);import{Ansis as Wo,blue as Xo,cyanBright as en,green as tn,hex as rn,red as on}from"ansis";import{inspect as nn}from"node:util";import{performance as yr}from"node:perf_hooks";var tt={debug:10,info:20,warn:30,error:40},dr=e=>J(e)&&Object.keys(tt).some(t=>t in e),lr=e=>e in tt,mr=(e,t)=>tt[e]<tt[t],ur=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),et=ur(),cr=ur(2),Jo=e=>e<1e-6?["picosecond",e/1e-9,et]:e<.001?["nanosecond",e/1e-6,et]:e<1?["microsecond",e/.001,et]:e<1e3?["millisecond",e,et]:e<6e4?["second",e/1e3,cr]:["minute",e/6e4,cr],fr=e=>{let[t,r,o]=Jo(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var ve=class e{config;styles={debug:Xo,info:tn,warn:rn("#FFA500"),error:on};constructor(t={}){let{color:r=new Wo().isSupported(),level:o=Be()?"warn":"debug",depth:n=2,ctx:i={}}=t;this.config={color:r,level:o,depth:n,ctx:i}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return nn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:i,...a},color:p}=this.config;if(n==="silent"||mr(t,n))return;let d=[new Date().toISOString()];i&&d.push(p?en(i):i),d.push(p?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.prettyPrint(o)),Object.keys(a).length>0&&d.push(this.prettyPrint(a)),console.log(d.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=yr.now();return()=>{let o=yr.now()-r,{message:n,severity:i="debug",formatter:a=fr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};import{head as sn,tail as an,toPairs as pn}from"ramda";var je=class extends ye{pairs;firstEndpoint;siblingMethods;constructor(t){super(),this.pairs=Object.freeze(pn(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=sn(this.pairs)?.[1],this.siblingMethods=Object.freeze(an(this.pairs).map(([r])=>r))}};import cn from"express";var Le=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,cn.static(...this.params))}};import wt from"express";import gn from"node:http";import hn from"node:https";var ge=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Re(e)};var re=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){if(a.includes("/"))throw new ce(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`);let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof ze){let c=p.getMethods().slice();n&&c.push("options");for(let m of c)t(p,d,m)}else if(p instanceof Le)r&&p.apply(d,r);else if(p instanceof je){for(let[c,m]of p.pairs){if(!m.getMethods().includes(c))throw new ce(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`);t(m,d,c)}n&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else re({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:d})}};var Pt=({app:e,rootLogger:t,getChildLogger:r,config:o,routing:n,parsers:i})=>{let a=new WeakSet;re({routing:n,hasCors:!!o.cors,onEndpoint:(p,d,c,m)=>{let l=p.getRequestType();if(!a.has(p)){if(l==="json")try{xt(p.getSchema("input"),"in")}catch(u){t.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",{path:d,method:c,reason:u})}for(let u of["positive","negative"])if(p.getMimeTypes(u).includes(O.json))try{xt(p.getSchema(u),"out")}catch(S){t.warn(`The final ${u} response schema of the endpoint contains an unsupported JSON payload type.`,{path:d,method:c,reason:S})}a.add(p)}e[c](d,...i?.[l]||[],async(u,S)=>p.execute({request:u,response:S,logger:r(u),config:o,siblingMethods:m}))},onStatic:(p,d)=>{e.use(p,d)}})};import Or,{isHttpError as ln}from"http-errors";import{setInterval as dn}from"node:timers/promises";var gr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",hr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",xr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,br=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Sr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Tr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(gr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",br);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(xr(c)||hr(c))&&a(c);for await(let c of dn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(Sr))};return{sockets:n,shutdown:()=>o??=d()}};var Rr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:ln(r)?r:Or(400,K(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Ar=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=Or(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){Je({response:o,logger:i,error:new D(K(a),n)})}},mn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},un=e=>({log:e.debug.bind(e)}),Pr=async({getChildLogger:e,config:t})=>{let r=await ge("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let m=e(p);try{await n?.({request:p,logger:m})}catch(l){return c(l)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:un(m)})(p,d,c)}),o&&a.push(mn(o)),a},wr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Cr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:i}),n()},zr=e=>t=>t.res?.locals[g]?.logger||e,Ir=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(` | ||
`).slice(1))),Er=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Tr(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};import{gray as fn,hex as Zr,italic as rt,whiteBright as yn}from"ansis";var vr=()=>{let e=rt("Proudly supports transgender community.".padStart(109)),t=rt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=rt("Thank you for choosing Express Zod API for your project.".padStart(132)),o=rt("for Zoey".padEnd(20)),n=Zr("#F5A9B8"),i=Zr("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(yn,5,7).fill(n,7,9).fill(i,9,12).fill(fn,12,13);return` | ||
8888888888 8888888888P 888 d8888 8888888b. 8888888 | ||
@@ -18,6 +18,6 @@ 888 d88P 888 d88888 888 Y88b 888 | ||
`).map((d,c)=>a[c]?a[c](d):d).join(` | ||
`)};var vr=e=>{e.startupLogo!==!1&&console.log(Zr());let t=e.errorHandler||Ie,r=cr(e.logger)?e.logger:new Ze(e.logger);r.debug("Running",{build:"v20.21.2 (ESM)",env:process.env.NODE_ENV||"development"}),zr(r);let o=wr({rootLogger:r,config:e}),i={getChildLogger:Cr(r),errorHandler:t},a=Rr(i),p=Or(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},hn=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=vr(e);return At({app:e.app.use(i),rootLogger:r,routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},xn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=vr(e),p=Pt().disable("x-powered-by").use(a);if(e.server.compression){let u=await ye("compression");p.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Pt.json()],raw:[e.server.rawParser||Pt.raw(),Pr],upload:e.server.upload?await Ar({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),At({app:p,routing:t,rootLogger:r,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(u,S)=>u.listen(S,()=>r.info("Listening",S)),m=yn.createServer(p),l=e.https&&gn.createServer(e.https.options,p);return e.gracefulShutdown&&Ir({servers:[m].concat(l||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(m,e.server.listen),httpsServer:l&&c(l,e.https?.listen)}};import{OpenApiBuilder as Os}from"openapi3-ts/oas31";import{keys as Rs,pluck as As}from"ramda";import{isReferenceObject as Ct,isSchemaObject as ot}from"openapi3-ts/oas31";import{concat as bn,type as Nr,filter as Sn,fromPairs as Le,has as Tn,isNil as On,map as ge,mergeAll as Rn,mergeDeepRight as An,mergeDeepWith as Pn,objOf as kr,omit as nt,pipe as Mr,pluck as wn,range as Cn,reject as zn,toLower as In,union as En,when as Zn,xprod as st,zip as vn}from"ramda";import{z as x}from"zod";var oe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[g]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>oe(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:p,...n});return d?{...p,...d}:p};var jr=50,Ur="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",jn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Hr=/:([A-Za-z0-9_]+)/g,Ln=e=>e.match(Hr)?.map(t=>t.slice(1))||[],Dr=e=>e.replace(Hr,t=>`{${t.slice(1)}}`),Nn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),kn=({_def:{innerType:e}},{next:t})=>t(e),Mn=()=>({format:"any"}),Un=({},e)=>{if(e.isResponse)throw new E({message:"Please use ez.upload() only for input.",...e});return{type:"string",format:"binary"}},Hn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof x.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Dn=({options:e},{next:t})=>({oneOf:e.map(t)}),Kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Fn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return bn(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Bn=e=>{let[t,r]=e.filter(ot).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Pn(Fn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=En(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=Q(t.examples||[],r.examples||[],([n,i])=>An(n,i))),o},qn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Bn(o)}catch{}return{allOf:o}},Vn=(e,{next:t})=>t(e.unwrap()),$n=(e,{next:t})=>t(e.unwrap()),_n=(e,{next:t})=>{let r=t(e.unwrap());return ot(r)&&(r.type=Fr(r)),r},Kr=e=>{let t=In(Nr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Lr=e=>({type:Kr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Gn=({value:e})=>({type:Kr(e),const:e}),Yn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof x.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=rt(e,r)),i.length&&(a.required=i),a},Qn=()=>({type:"null"}),Jn=({},e)=>{if(e.isResponse)throw new E({message:"Please use ez.dateOut() for output.",...e});return{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:Ur}}},Wn=({},e)=>{if(!e.isResponse)throw new E({message:"Please use ez.dateIn() for input.",...e});return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ur}}},Xn=({},e)=>{throw new E({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})},es=()=>({type:"boolean"}),ts=()=>({type:"integer",format:"bigint"}),rs=e=>e.every(t=>t instanceof x.ZodLiteral),os=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=rt(x.object(Le(st(o,[t]))),r),n.required=o),n}if(e instanceof x.ZodLiteral)return{type:"object",properties:rt(x.object({[e.value]:t}),r),required:[e.value]};if(e instanceof x.ZodUnion&&rs(e.options)){let o=ge(i=>`${i.value}`,e.options),n=Le(st(o,[t]));return{type:"object",properties:rt(x.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ns=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},ss=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),is=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:l}})=>{let u=l.find(R=>R.kind==="regex"),S=l.find(R=>R.kind==="datetime"),T=u?u.regex:S?S.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,w={type:"string"},h={"date-time":m,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in h)if(h[R]){w.format=R;break}return r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),T&&(w.pattern=T.source),w},as=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(l=>l.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(l=>l.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,c?m.maximum=d:m.exclusiveMaximum=d,m},rt=({shape:e},t)=>ge(t,e),ps=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return jn?.[t]},Fr=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",cs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&ot(o)){let i=Ke(e,ps(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(x.any())}if(!t&&n.type==="preprocess"&&ot(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},ds=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ls=(e,{next:t})=>t(e.unwrap()),ms=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),us=(e,{next:t})=>t(e.unwrap().shape.raw),Br=e=>e.length?Le(vn(Cn(1,e.length+1).map(t=>`example${t}`),ge(kr("value"),e))):void 0,qr=(e,t,r=[])=>Mr(F,ge(Zn(o=>Nr(o)==="Object",nt(r))),Br)({schema:e,variant:t?"parsed":"original",validate:!0}),fs=(e,t)=>Mr(F,Sn(Tn(t)),wn(t),Br)({schema:e,variant:"original",validate:!0}),ne=e=>e instanceof x.ZodObject?e:e instanceof x.ZodBranded?ne(e.unwrap()):e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion?e.options.map(t=>ne(t)).reduce((t,r)=>t.merge(r.partial()),x.object({})):e instanceof x.ZodEffects?ne(e._def.schema):e instanceof x.ZodPipeline?ne(e._def.in):ne(e._def.left).merge(ne(e._def.right)),Vr=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:d}=ne(r),c=Ln(e),m=o.includes("query"),l=o.includes("params"),u=o.includes("headers"),S=h=>l&&c.includes(h),T=h=>u&&ft(h);return Object.keys(d).map(h=>({name:h,location:S(h)?"path":T(h)?"header":m?"query":void 0})).filter(h=>h.location!==void 0).map(({name:h,location:R})=>{let $=oe(d[h],{rules:{...a,...zt},onEach:It,onMissing:Et,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),ae=i==="components"?n(d[h],$,Z(p,h)):$;return{name:h,in:R,required:!d[h].isOptional(),description:$.description||p,schema:ae,examples:fs(r,h)}})},zt={ZodString:is,ZodNumber:as,ZodBigInt:ts,ZodBoolean:es,ZodNull:Qn,ZodArray:ns,ZodTuple:ss,ZodRecord:os,ZodObject:Yn,ZodLiteral:Gn,ZodIntersection:qn,ZodUnion:Dn,ZodAny:Mn,ZodDefault:Nn,ZodEnum:Lr,ZodNativeEnum:Lr,ZodEffects:cs,ZodOptional:Vn,ZodNullable:_n,ZodDiscriminatedUnion:Kn,ZodBranded:ls,ZodDate:Xn,ZodCatch:kn,ZodPipeline:ds,ZodLazy:ms,ZodReadonly:$n,[N]:Hn,[le]:Un,[X]:Wn,[W]:Jn,[B]:us},It=(e,{isResponse:t,prev:r})=>{if(Ct(r))return{};let{description:o}=e,n=e instanceof x.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),p&&(d.type=Fr(r)),!n){let c=F({schema:e,variant:t?"parsed":"original",validate:!0});c.length&&(d.examples=c.slice())}return d},Et=(e,t)=>{throw new E({message:`Zod type ${e.constructor.name} is unsupported.`,...t})},wt=(e,t)=>{if(Ct(e))return e;let r={...e};return r.properties&&(r.properties=nt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>nt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>wt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>wt(o,t))),r},$r=e=>Ct(e)?e:nt(["examples"],e),_r=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${p?d:""}`.trim()})=>{let l=$r(oe(r,{rules:{...c,...zt},onEach:It,onMissing:Et,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),u={schema:a==="components"?i(r,l,Z(m)):l,examples:qr(r,!0)};return{description:m,content:Le(st(o,[u]))}},ys=()=>({type:"http",scheme:"basic"}),gs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},hs=({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},xs=({name:e})=>({type:"apiKey",in:"header",name:e}),bs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ss=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ts=({flows:e={}})=>({type:"oauth2",flows:ge(t=>({...t,scopes:t.scopes||{}}),zn(On,e))}),Gr=(e,t)=>{let r={basic:ys,bearer:gs,input:hs,header:xs,cookie:bs,openid:Ss,oauth2:Ts};return Je(e,o=>r[o.type](o,t))},it=e=>"or"in e?e.or.map(t=>"and"in t?Rn(ge(({name:r,scopes:o})=>kr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?it(St(e)):it({or:[e]}),Yr=({method:e,path:t,schema:r,mimeTypes:o,makeRef:n,composition:i,brandHandling:a,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=$r(wt(oe(r,{rules:{...a,...zt},onEach:It,onMissing:Et,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),p)),m={schema:i==="components"?n(r,c,Z(d)):c,examples:qr(r,!1,p)};return{description:d,content:Le(st(o,[m]))}},Qr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Zt=e=>e.length<=jr?e:e.slice(0,jr-1)+"\u2026";var vt=class extends Os{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=Rs(te);references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||Z(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new E({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;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:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline"}){super(),this.addInfo({title:o,version:n});for(let l of typeof i=="string"?[i]:i)this.addServer({url:l});re({routing:t,onEndpoint:(l,u,S)=>{let T=S,w={path:u,method:T,endpoint:l,composition:c,brandHandling:p,makeRef:this.makeRef.bind(this)},[h,R]=["short","long"].map(l.getDescription.bind(l)),$=h?Zt(h):d&&R?Zt(R):void 0,ae=l.getTags(),he=r.inputSources?.[T]||mt[T],pe=this.ensureUniqOperationId(u,T,l.getOperationId(T)),xe=Vr({...w,inputSources:he,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:u,operationId:pe})}),Me={};for(let M of this.responseVariants){let _=l.getResponses(M);for(let{mimeTypes:P,schema:C,statusCodes:z}of _)for(let L of z)Me[L]=_r({...w,variant:M,schema:C,mimeTypes:P,statusCode:L,hasMultipleStatusCodes:_.length>1||z.length>1,description:a?.[`${M}Response`]?.call(null,{method:T,path:u,operationId:pe,statusCode:L})})}let lt=he.includes("body")?Yr({...w,paramNames:As("name",xe),schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:u,operationId:pe})}):void 0,Ue=it(Je(Gr(l.getSecurity(),he),M=>{let _=this.ensureUniqSecuritySchemaName(M),P=["oauth2","openIdConnect"].includes(M.type)?l.getScopes().slice():[];return this.addSecurityScheme(_,M),{name:_,scopes:P}}));this.addPath(Dr(u),{[T]:{operationId:pe,summary:$,description:R,tags:ae.length>0?ae:void 0,parameters:xe.length>0?xe:void 0,requestBody:lt,security:Ue.length>0?Ue:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Qr(r.tags):[]}};import{createRequest as Ps,createResponse as ws}from"node-mocks-http";var Cs=e=>Ps({...e,headers:{"content-type":O.json,...e?.headers}}),zs=e=>ws(e),Is=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:dr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Jr=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Cs(e),i=zs({req:n,...t});i.req=t?.req||n,n.res=i;let a=Is(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Es=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Jr(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Zs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:p}=Jr(o),d=De(n,p.inputSources);try{let c=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:c}}catch(c){if(!r)throw c;return r(K(c),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};import j from"typescript";import v from"typescript";import{chain as Wr,toPairs as Xr}from"ramda";var s=v.factory,V=[s.createModifier(v.SyntaxKind.ExportKeyword)],vs=[s.createModifier(v.SyntaxKind.AsyncKeyword)],js=[s.createModifier(v.SyntaxKind.PublicKeyword),s.createModifier(v.SyntaxKind.ReadonlyKeyword)],eo=[s.createModifier(v.SyntaxKind.ProtectedKeyword),s.createModifier(v.SyntaxKind.ReadonlyKeyword)],Ls=s.createTemplateHead(""),Ns=s.createTemplateMiddle(" "),Ne=s.createTemplateTail(""),jt=e=>s.createTemplateLiteralType(Ls,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?Ne:Ns))),Lt=jt(["M","P"]),at=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),pt=(e,t)=>Wr(([r,o])=>[at(s.createIdentifier(r),o,t)],Xr(e)),Nt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),to=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),ro=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),H=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],v.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(V,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),ct=(e,t)=>s.createTypeAliasDeclaration(V,e,void 0,t),oo=(e,t,r)=>s.createPropertyDeclaration(js,e,void 0,t,r),no=(e,t,r)=>s.createClassDeclaration(V,e,void 0,void 0,[t,...r]),so=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),io=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(v.SyntaxKind.AnyKeyword)]),ao=(e,t,r)=>s.createInterfaceDeclaration(V,e,void 0,t,r),ks=Wr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),po=e=>ks(Xr(e)),Mt=(e,t,r)=>s.createArrowFunction(r?vs:void 0,void 0,e.map(o=>at(o)),void 0,void 0,t),Ut=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,pt({acc:void 0,key:void 0}),void 0,void 0,t),r]),co=(...e)=>`"${e.join(" ")}"`,lo=(e,t,r)=>s.createConditionalExpression(e,s.createToken(v.SyntaxKind.QuestionToken),t,s.createToken(v.SyntaxKind.ColonToken),r);var mo=["get","post","put","delete","patch"];import y from"typescript";import{z as Kt}from"zod";import b from"typescript";var{factory:dt}=b,Ht=(e,t)=>b.addSyntheticLeadingComment(e,b.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),se=(e,t,r)=>{let o=dt.createTypeAliasDeclaration(void 0,dt.createIdentifier(t),void 0,e);return r?Ht(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)},Ms=/^[A-Za-z_$][A-Za-z0-9_$]*$/,uo=e=>Ms.test(e)?dt.createIdentifier(e):dt.createStringLiteral(e),Us=[b.SyntaxKind.AnyKeyword,b.SyntaxKind.BigIntKeyword,b.SyntaxKind.BooleanKeyword,b.SyntaxKind.NeverKeyword,b.SyntaxKind.NumberKeyword,b.SyntaxKind.ObjectKeyword,b.SyntaxKind.StringKeyword,b.SyntaxKind.SymbolKeyword,b.SyntaxKind.UndefinedKeyword,b.SyntaxKind.UnknownKeyword,b.SyntaxKind.VoidKeyword],fo=e=>Us.includes(e.kind);var{factory:f}=y,Hs={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Ds=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),Ks=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Kt.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,uo(i),p&&o?f.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description?Ht(d,a.description):d});return f.createTypeLiteralNode(n)},Fs=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),Bs=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),yo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(fo(n)?n.kind:n,n)}return f.createUnionTypeNode(Array.from(r.values()))},qs=e=>Hs?.[e.kind],Vs=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ke(e,qs(o)),i={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},$s=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),_s=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Gs=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),Ys=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),Qs=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),Js=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(y.isTypeLiteralNode)?f.createTypeLiteralNode(o.flatMap(({members:i})=>i)):f.createIntersectionTypeNode(o)},Ws=({_def:e},{next:t})=>t(e.innerType),ie=e=>()=>f.createKeywordTypeNode(e),Xs=(e,{next:t})=>t(e.unwrap()),ei=(e,{next:t})=>t(e.unwrap()),ti=({_def:e},{next:t})=>t(e.innerType),ri=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),oi=()=>f.createLiteralTypeNode(f.createNull()),ni=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),si=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof Kt.ZodString?r:t instanceof Kt.ZodUnion?n:o},ii=(e,{next:t})=>t(e.unwrap().shape.raw),ai={ZodString:ie(y.SyntaxKind.StringKeyword),ZodNumber:ie(y.SyntaxKind.NumberKeyword),ZodBigInt:ie(y.SyntaxKind.BigIntKeyword),ZodBoolean:ie(y.SyntaxKind.BooleanKeyword),ZodAny:ie(y.SyntaxKind.AnyKeyword),[W]:ie(y.SyntaxKind.StringKeyword),[X]:ie(y.SyntaxKind.StringKeyword),ZodNull:oi,ZodArray:Fs,ZodTuple:Ys,ZodRecord:Qs,ZodObject:Ks,ZodLiteral:Ds,ZodIntersection:Js,ZodUnion:yo,ZodDefault:Ws,ZodEnum:Bs,ZodNativeEnum:$s,ZodEffects:Vs,ZodOptional:_s,ZodNullable:Gs,ZodDiscriminatedUnion:yo,ZodBranded:Xs,ZodCatch:ti,ZodPipeline:ri,ZodLazy:ni,ZodReadonly:ei,[N]:si,[B]:ii},ke=(e,{brandHandling:t,ctx:r})=>oe(e,{rules:{...t,...ai},onMissing:()=>f.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Ft=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),isJsonConst:s.createIdentifier("isJSON")};interfaces=[];makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,se(n,o)),this.aliases.set(t,se(r(),o))}return s.createTypeReferenceNode(o)}constructor({routing:t,brandHandling:r,variant:o="client",splitResponse:n=!1,optionalPropStyle:i={withQuestionMark:!0,withUndefined:!0}}){re({routing:t,onEndpoint:(P,C,z)=>{let L={makeAlias:this.makeAlias.bind(this),optionalPropStyle:i},be=Z(z,C,"input"),Se=ke(P.getSchema("input"),{brandHandling:r,ctx:{...L,isResponse:!1}}),I=n?Z(z,C,"positive.response"):void 0,Bt=P.getSchema("positive"),qt=n?ke(Bt,{brandHandling:r,ctx:{...L,isResponse:!0}}):void 0,Te=n?Z(z,C,"negative.response"):void 0,Vt=P.getSchema("negative"),$t=n?ke(Vt,{brandHandling:r,ctx:{...L,isResponse:!0}}):void 0,_t=Z(z,C,"response"),go=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):ke(Bt.or(Vt),{brandHandling:r,ctx:{...L,isResponse:!0}});this.program.push(se(Se,be)),qt&&I&&this.program.push(se(qt,I)),$t&&Te&&this.program.push(se($t,Te)),this.program.push(se(go,_t)),z!=="options"&&(this.paths.push(C),this.registry.set({method:z,path:C},{input:be,positive:I,negative:Te,response:_t,isJson:P.getMimeTypes("positive").includes(O.json),tags:P.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,mo)),this.program.push(ct(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let a=[s.createHeritageClause(j.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,j.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),n&&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:z,tags:L,...be}]of this.registry){let Se=co(P,C);for(let I of this.interfaces)I.kind in be&&I.props.push(ro(Se,be[I.kind]));o!=="types"&&(z&&p.push(s.createPropertyAssignment(Se,s.createTrue())),d.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(L.map(I=>s.createStringLiteral(I))))))}for(let{id:P,props:C}of this.interfaces)this.program.push(ao(P,a,C));if(o==="types")return;let c=s.createVariableStatement(V,H(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(p))),m=s.createVariableStatement(V,H(this.ids.endpointTagsConst,s.createObjectLiteralExpression(d))),l=ct(this.ids.providerType,s.createFunctionTypeNode(po({M:this.ids.methodType,P:this.ids.pathType}),pt({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),so(this.ids.responseInterface,Lt))),u=ct(this.ids.implementationType,s.createFunctionTypeNode(void 0,pt({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(j.SyntaxKind.StringKeyword),params:Nt(j.SyntaxKind.StringKeyword,j.SyntaxKind.AnyKeyword)}),io())),S=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,Ne)]),T=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[S,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),w=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[S]),j.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),h=no(this.ids.clientClass,to([at(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),eo)]),[oo(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,w]),!0))]);this.program.push(c,m,l,u,h);let R=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),$=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(O.json))]),void 0,this.ids.undefinedValue)),ae=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),he=s.createVariableStatement(void 0,H(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,Ne)]),s.createObjectLiteralExpression([R,$,ae])])))),pe=s.createVariableStatement(void 0,H(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),xe=s.createVariableStatement(void 0,H(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Ne)])))),Me=s.createVariableStatement(void 0,H(this.ids.isJsonConst,s.createCallChain(s.createPropertyAccessChain(s.createCallExpression(s.createPropertyAccessExpression(s.createPropertyAccessExpression(this.ids.responseConst,this.ids.headersProperty),s.createIdentifier("get")),void 0,[s.createStringLiteral("content-type")]),s.createToken(j.SyntaxKind.QuestionDotToken),s.createIdentifier("startsWith")),void 0,void 0,[s.createStringLiteral(O.json)]))),lt=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,lo(this.ids.isJsonConst,s.createStringLiteral("json"),s.createStringLiteral("text"))),void 0,[])),Ue=s.createVariableStatement(V,H(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([pe,xe,he,Me,lt]),!0),s.createTypeReferenceNode(this.ids.implementationType))),M=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),_=s.createVariableStatement(void 0,H(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(Ue,_,M)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(` | ||
`)};var jr=e=>{e.startupLogo!==!1&&console.log(vr());let t=e.errorHandler||Ee,r=dr(e.logger)?e.logger:new ve(e.logger);r.debug("Running",{build:"v20.22.0 (ESM)",env:process.env.NODE_ENV||"development"}),Ir(r);let o=Cr({rootLogger:r,config:e}),i={getChildLogger:zr(r),errorHandler:t},a=Ar(i),p=Rr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},xn=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=jr(e);return Pt({app:e.app.use(i),rootLogger:r,routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},bn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=jr(e),p=wt().disable("x-powered-by").use(a);if(e.server.compression){let u=await ge("compression");p.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||wt.json()],raw:[e.server.rawParser||wt.raw(),wr],upload:e.server.upload?await Pr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Pt({app:p,routing:t,rootLogger:r,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(u,S)=>u.listen(S,()=>r.info("Listening",S)),m=gn.createServer(p),l=e.https&&hn.createServer(e.https.options,p);return e.gracefulShutdown&&Er({servers:[m].concat(l||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(m,e.server.listen),httpsServer:l&&c(l,e.https?.listen)}};import{OpenApiBuilder as Rs}from"openapi3-ts/oas31";import{keys as As,pluck as Ps}from"ramda";import{isReferenceObject as zt,isSchemaObject as nt}from"openapi3-ts/oas31";import{concat as Sn,type as kr,filter as Tn,fromPairs as Ne,has as On,isNil as Rn,map as he,mergeAll as An,mergeDeepRight as Pn,mergeDeepWith as wn,objOf as Mr,omit as st,pipe as Ur,pluck as Cn,range as zn,reject as In,toLower as En,union as Zn,when as vn,xprod as it,zip as jn}from"ramda";import{z as x}from"zod";var oe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[g]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>oe(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:p,...n});return d?{...p,...d}:p};var Lr=50,Hr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Ln={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Dr=/:([A-Za-z0-9_]+)/g,Nn=e=>e.match(Dr)?.map(t=>t.slice(1))||[],Kr=e=>e.replace(Dr,t=>`{${t.slice(1)}}`),kn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Mn=({_def:{innerType:e}},{next:t})=>t(e),Un=()=>({format:"any"}),Hn=({},e)=>{if(e.isResponse)throw new E({message:"Please use ez.upload() only for input.",...e});return{type:"string",format:"binary"}},Dn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof x.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Kn=({options:e},{next:t})=>({oneOf:e.map(t)}),Fn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Bn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Sn(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},qn=e=>{let[t,r]=e.filter(nt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=wn(Bn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Zn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=Q(t.examples||[],r.examples||[],([n,i])=>Pn(n,i))),o},Vn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return qn(o)}catch{}return{allOf:o}},$n=(e,{next:t})=>t(e.unwrap()),_n=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>{let r=t(e.unwrap());return nt(r)&&(r.type=Br(r)),r},Fr=e=>{let t=En(kr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Nr=e=>({type:Fr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Yn=({value:e})=>({type:Fr(e),const:e}),Qn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Ae(p)?p instanceof x.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=ot(e,r)),i.length&&(a.required=i),a},Jn=()=>({type:"null"}),Wn=({},e)=>{if(e.isResponse)throw new E({message:"Please use ez.dateOut() for output.",...e});return{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:Hr}}},Xn=({},e)=>{if(!e.isResponse)throw new E({message:"Please use ez.dateIn() for input.",...e});return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Hr}}},es=({},e)=>{throw new E({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})},ts=()=>({type:"boolean"}),rs=()=>({type:"integer",format:"bigint"}),os=e=>e.every(t=>t instanceof x.ZodLiteral),ns=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=ot(x.object(Ne(it(o,[t]))),r),n.required=o),n}if(e instanceof x.ZodLiteral)return{type:"object",properties:ot(x.object({[e.value]:t}),r),required:[e.value]};if(e instanceof x.ZodUnion&&os(e.options)){let o=he(i=>`${i.value}`,e.options),n=Ne(it(o,[t]));return{type:"object",properties:ot(x.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ss=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},is=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),as=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:l}})=>{let u=l.find(R=>R.kind==="regex"),S=l.find(R=>R.kind==="datetime"),T=u?u.regex:S?S.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,w={type:"string"},h={"date-time":m,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in h)if(h[R]){w.format=R;break}return r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),T&&(w.pattern=T.source),w},ps=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(l=>l.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(l=>l.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,c?m.maximum=d:m.exclusiveMaximum=d,m},ot=({shape:e},t)=>he(t,e),cs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Ln?.[t]},Br=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ds=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&nt(o)){let i=Fe(e,cs(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(x.any())}if(!t&&n.type==="preprocess"&&nt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},ls=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ms=(e,{next:t})=>t(e.unwrap()),us=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),fs=(e,{next:t})=>t(e.unwrap().shape.raw),qr=e=>e.length?Ne(jn(zn(1,e.length+1).map(t=>`example${t}`),he(Mr("value"),e))):void 0,Vr=(e,t,r=[])=>Ur(F,he(vn(o=>kr(o)==="Object",st(r))),qr)({schema:e,variant:t?"parsed":"original",validate:!0}),ys=(e,t)=>Ur(F,Tn(On(t)),Cn(t),qr)({schema:e,variant:"original",validate:!0}),ne=e=>e instanceof x.ZodObject?e:e instanceof x.ZodBranded?ne(e.unwrap()):e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion?e.options.map(t=>ne(t)).reduce((t,r)=>t.merge(r.partial()),x.object({})):e instanceof x.ZodEffects?ne(e._def.schema):e instanceof x.ZodPipeline?ne(e._def.in):ne(e._def.left).merge(ne(e._def.right)),$r=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:i,brandHandling:a,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:d}=ne(r),c=Nn(e),m=o.includes("query"),l=o.includes("params"),u=o.includes("headers"),S=h=>l&&c.includes(h),T=h=>u&&yt(h);return Object.keys(d).map(h=>({name:h,location:S(h)?"path":T(h)?"header":m?"query":void 0})).filter(h=>h.location!==void 0).map(({name:h,location:R})=>{let $=oe(d[h],{rules:{...a,...It},onEach:Et,onMissing:Zt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),ae=i==="components"?n(d[h],$,Z(p,h)):$;return{name:h,in:R,required:!d[h].isOptional(),description:$.description||p,schema:ae,examples:ys(r,h)}})},It={ZodString:as,ZodNumber:ps,ZodBigInt:rs,ZodBoolean:ts,ZodNull:Jn,ZodArray:ss,ZodTuple:is,ZodRecord:ns,ZodObject:Qn,ZodLiteral:Yn,ZodIntersection:Vn,ZodUnion:Kn,ZodAny:Un,ZodDefault:kn,ZodEnum:Nr,ZodNativeEnum:Nr,ZodEffects:ds,ZodOptional:$n,ZodNullable:Gn,ZodDiscriminatedUnion:Fn,ZodBranded:ms,ZodDate:es,ZodCatch:Mn,ZodPipeline:ls,ZodLazy:us,ZodReadonly:_n,[N]:Dn,[le]:Hn,[X]:Xn,[W]:Wn,[B]:fs},Et=(e,{isResponse:t,prev:r})=>{if(zt(r))return{};let{description:o}=e,n=e instanceof x.ZodLazy,i=r.type!==void 0,a=t&&Ae(e),p=!n&&i&&!a&&e.isNullable(),d={};if(o&&(d.description=o),p&&(d.type=Br(r)),!n){let c=F({schema:e,variant:t?"parsed":"original",validate:!0});c.length&&(d.examples=c.slice())}return d},Zt=(e,t)=>{throw new E({message:`Zod type ${e.constructor.name} is unsupported.`,...t})},Ct=(e,t)=>{if(zt(e))return e;let r={...e};return r.properties&&(r.properties=st(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>st(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ct(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ct(o,t))),r},_r=e=>zt(e)?e:st(["examples"],e),Gr=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:i,composition:a,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${gt(n)} response ${p?d:""}`.trim()})=>{let l=_r(oe(r,{rules:{...c,...It},onEach:Et,onMissing:Zt,ctx:{isResponse:!0,makeRef:i,path:t,method:e}})),u={schema:a==="components"?i(r,l,Z(m)):l,examples:Vr(r,!0)};return{description:m,content:Ne(it(o,[u]))}},gs=()=>({type:"http",scheme:"basic"}),hs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},xs=({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},bs=({name:e})=>({type:"apiKey",in:"header",name:e}),Ss=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ts=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Os=({flows:e={}})=>({type:"oauth2",flows:he(t=>({...t,scopes:t.scopes||{}}),In(Rn,e))}),Yr=(e,t)=>{let r={basic:gs,bearer:hs,input:xs,header:bs,cookie:Ss,openid:Ts,oauth2:Os};return We(e,o=>r[o.type](o,t))},at=e=>"or"in e?e.or.map(t=>"and"in t?An(he(({name:r,scopes:o})=>Mr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?at(Tt(e)):at({or:[e]}),Qr=({method:e,path:t,schema:r,mimeTypes:o,makeRef:n,composition:i,brandHandling:a,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=_r(Ct(oe(r,{rules:{...a,...It},onEach:Et,onMissing:Zt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),p)),m={schema:i==="components"?n(r,c,Z(d)):c,examples:Vr(r,!1,p)};return{description:d,content:Ne(it(o,[m]))}},Jr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),vt=e=>e.length<=Lr?e:e.slice(0,Lr-1)+"\u2026";var jt=class extends Rs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=As(te);references=new Map;makeRef(t,r,o=this.references.get(t)){return o||(o=`Schema${this.references.size+1}`,this.references.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}ensureUniqOperationId(t,r,o){let n=o||Z(r,t),i=this.lastOperationIdSuffixes.get(n);if(i===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new E({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t});return i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;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:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline"}){super(),this.addInfo({title:o,version:n});for(let l of typeof i=="string"?[i]:i)this.addServer({url:l});re({routing:t,onEndpoint:(l,u,S)=>{let T=S,w={path:u,method:T,endpoint:l,composition:c,brandHandling:p,makeRef:this.makeRef.bind(this)},[h,R]=["short","long"].map(l.getDescription.bind(l)),$=h?vt(h):d&&R?vt(R):void 0,ae=l.getTags(),xe=r.inputSources?.[T]||ut[T],pe=this.ensureUniqOperationId(u,T,l.getOperationId(T)),be=$r({...w,inputSources:xe,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:u,operationId:pe})}),Ue={};for(let M of this.responseVariants){let _=l.getResponses(M);for(let{mimeTypes:P,schema:C,statusCodes:z}of _)for(let L of z)Ue[L]=Gr({...w,variant:M,schema:C,mimeTypes:P,statusCode:L,hasMultipleStatusCodes:_.length>1||z.length>1,description:a?.[`${M}Response`]?.call(null,{method:T,path:u,operationId:pe,statusCode:L})})}let mt=xe.includes("body")?Qr({...w,paramNames:Ps("name",be),schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:u,operationId:pe})}):void 0,He=at(We(Yr(l.getSecurity(),xe),M=>{let _=this.ensureUniqSecuritySchemaName(M),P=["oauth2","openIdConnect"].includes(M.type)?l.getScopes().slice():[];return this.addSecurityScheme(_,M),{name:_,scopes:P}}));this.addPath(Kr(u),{[T]:{operationId:pe,summary:$,description:R,tags:ae.length>0?ae:void 0,parameters:be.length>0?be:void 0,requestBody:mt,security:He.length>0?He:void 0,responses:Ue}})}}),this.rootDoc.tags=r.tags?Jr(r.tags):[]}};import{createRequest as ws,createResponse as Cs}from"node-mocks-http";var zs=e=>ws({...e,headers:{"content-type":O.json,...e?.headers}}),Is=e=>Cs(e),Es=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:lr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Wr=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=zs(e),i=Is({req:n,...t});i.req=t?.req||n,n.res=i;let a=Es(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Wr(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},vs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:i,loggerMock:a,configMock:p}=Wr(o),d=Ke(n,p.inputSources);try{let c=await e.execute({request:n,response:i,logger:a,input:d,options:t});return{requestMock:n,responseMock:i,loggerMock:a,output:c}}catch(c){if(!r)throw c;return r(K(c),i),{requestMock:n,responseMock:i,loggerMock:a,output:{}}}};import j from"typescript";import v from"typescript";import{chain as Xr,toPairs as eo}from"ramda";var s=v.factory,V=[s.createModifier(v.SyntaxKind.ExportKeyword)],js=[s.createModifier(v.SyntaxKind.AsyncKeyword)],Ls=[s.createModifier(v.SyntaxKind.PublicKeyword),s.createModifier(v.SyntaxKind.ReadonlyKeyword)],to=[s.createModifier(v.SyntaxKind.ProtectedKeyword),s.createModifier(v.SyntaxKind.ReadonlyKeyword)],Ns=s.createTemplateHead(""),ks=s.createTemplateMiddle(" "),ke=s.createTemplateTail(""),Lt=e=>s.createTemplateLiteralType(Ns,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?ke:ks))),Nt=Lt(["M","P"]),pt=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ct=(e,t)=>Xr(([r,o])=>[pt(s.createIdentifier(r),o,t)],eo(e)),kt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),ro=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),oo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),H=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],v.NodeFlags.Const),Mt=(e,t)=>s.createTypeAliasDeclaration(V,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),dt=(e,t)=>s.createTypeAliasDeclaration(V,e,void 0,t),no=(e,t,r)=>s.createPropertyDeclaration(Ls,e,void 0,t,r),so=(e,t,r)=>s.createClassDeclaration(V,e,void 0,void 0,[t,...r]),io=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),ao=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(v.SyntaxKind.AnyKeyword)]),po=(e,t,r)=>s.createInterfaceDeclaration(V,e,void 0,t,r),Ms=Xr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),co=e=>Ms(eo(e)),Ut=(e,t,r)=>s.createArrowFunction(r?js:void 0,void 0,e.map(o=>pt(o)),void 0,void 0,t),Ht=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,ct({acc:void 0,key:void 0}),void 0,void 0,t),r]),lo=(...e)=>`"${e.join(" ")}"`,mo=(e,t,r)=>s.createConditionalExpression(e,s.createToken(v.SyntaxKind.QuestionToken),t,s.createToken(v.SyntaxKind.ColonToken),r);var uo=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import b from"typescript";var{factory:lt}=b,Dt=(e,t)=>b.addSyntheticLeadingComment(e,b.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),se=(e,t,r)=>{let o=lt.createTypeAliasDeclaration(void 0,lt.createIdentifier(t),void 0,e);return r?Dt(o,r):o},Kt=(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)},Us=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fo=e=>Us.test(e)?lt.createIdentifier(e):lt.createStringLiteral(e),Hs=[b.SyntaxKind.AnyKeyword,b.SyntaxKind.BigIntKeyword,b.SyntaxKind.BooleanKeyword,b.SyntaxKind.NeverKeyword,b.SyntaxKind.NumberKeyword,b.SyntaxKind.ObjectKeyword,b.SyntaxKind.StringKeyword,b.SyntaxKind.SymbolKeyword,b.SyntaxKind.UndefinedKeyword,b.SyntaxKind.UnknownKeyword,b.SyntaxKind.VoidKeyword],yo=e=>Hs.includes(e.kind);var{factory:f}=y,Ds={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Ks=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),Fs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Ae(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,fo(i),p&&o?f.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description?Dt(d,a.description):d});return f.createTypeLiteralNode(n)},Bs=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),qs=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),go=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(yo(n)?n.kind:n,n)}return f.createUnionTypeNode(Array.from(r.values()))},Vs=e=>Ds?.[e.kind],$s=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Fe(e,Vs(o)),i={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},_s=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Gs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Ys=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),Qs=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),Js=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),Ws=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);return o.every(y.isTypeLiteralNode)?f.createTypeLiteralNode(o.flatMap(({members:i})=>i)):f.createIntersectionTypeNode(o)},Xs=({_def:e},{next:t})=>t(e.innerType),ie=e=>()=>f.createKeywordTypeNode(e),ei=(e,{next:t})=>t(e.unwrap()),ti=(e,{next:t})=>t(e.unwrap()),ri=({_def:e},{next:t})=>t(e.innerType),oi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ni=()=>f.createLiteralTypeNode(f.createNull()),si=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ii=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},ai=(e,{next:t})=>t(e.unwrap().shape.raw),pi={ZodString:ie(y.SyntaxKind.StringKeyword),ZodNumber:ie(y.SyntaxKind.NumberKeyword),ZodBigInt:ie(y.SyntaxKind.BigIntKeyword),ZodBoolean:ie(y.SyntaxKind.BooleanKeyword),ZodAny:ie(y.SyntaxKind.AnyKeyword),[W]:ie(y.SyntaxKind.StringKeyword),[X]:ie(y.SyntaxKind.StringKeyword),ZodNull:ni,ZodArray:Bs,ZodTuple:Qs,ZodRecord:Js,ZodObject:Fs,ZodLiteral:Ks,ZodIntersection:Ws,ZodUnion:go,ZodDefault:Xs,ZodEnum:qs,ZodNativeEnum:_s,ZodEffects:$s,ZodOptional:Gs,ZodNullable:Ys,ZodDiscriminatedUnion:go,ZodBranded:ei,ZodCatch:ri,ZodPipeline:oi,ZodLazy:si,ZodReadonly:ti,[N]:ii,[B]:ai},Me=(e,{brandHandling:t,ctx:r})=>oe(e,{rules:{...t,...pi},onMissing:()=>f.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Bt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client"),isJsonConst:s.createIdentifier("isJSON")};interfaces=[];makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=s.createLiteralTypeNode(s.createNull());this.aliases.set(t,se(n,o)),this.aliases.set(t,se(r(),o))}return s.createTypeReferenceNode(o)}constructor({routing:t,brandHandling:r,variant:o="client",splitResponse:n=!1,optionalPropStyle:i={withQuestionMark:!0,withUndefined:!0}}){re({routing:t,onEndpoint:(P,C,z)=>{let L={makeAlias:this.makeAlias.bind(this),optionalPropStyle:i},Se=Z(z,C,"input"),Te=Me(P.getSchema("input"),{brandHandling:r,ctx:{...L,isResponse:!1}}),I=n?Z(z,C,"positive.response"):void 0,qt=P.getSchema("positive"),Vt=n?Me(qt,{brandHandling:r,ctx:{...L,isResponse:!0}}):void 0,Oe=n?Z(z,C,"negative.response"):void 0,$t=P.getSchema("negative"),_t=n?Me($t,{brandHandling:r,ctx:{...L,isResponse:!0}}):void 0,Gt=Z(z,C,"response"),ho=I&&Oe?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Oe)]):Me(qt.or($t),{brandHandling:r,ctx:{...L,isResponse:!0}});this.program.push(se(Te,Se)),Vt&&I&&this.program.push(se(Vt,I)),_t&&Oe&&this.program.push(se(_t,Oe)),this.program.push(se(ho,Gt)),z!=="options"&&(this.paths.push(C),this.registry.set({method:z,path:C},{input:Se,positive:I,negative:Oe,response:Gt,isJson:P.getMimeTypes("positive").includes(O.json),tags:P.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Mt(this.ids.pathType,this.paths)),this.program.push(Mt(this.ids.methodType,uo)),this.program.push(dt(this.ids.methodPathType,Lt([this.ids.methodType,this.ids.pathType])));let a=[s.createHeritageClause(j.SyntaxKind.ExtendsKeyword,[kt(this.ids.methodPathType,j.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),n&&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:z,tags:L,...Se}]of this.registry){let Te=lo(P,C);for(let I of this.interfaces)I.kind in Se&&I.props.push(oo(Te,Se[I.kind]));o!=="types"&&(z&&p.push(s.createPropertyAssignment(Te,s.createTrue())),d.push(s.createPropertyAssignment(Te,s.createArrayLiteralExpression(L.map(I=>s.createStringLiteral(I))))))}for(let{id:P,props:C}of this.interfaces)this.program.push(po(P,a,C));if(o==="types")return;let c=s.createVariableStatement(V,H(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(p))),m=s.createVariableStatement(V,H(this.ids.endpointTagsConst,s.createObjectLiteralExpression(d))),l=dt(this.ids.providerType,s.createFunctionTypeNode(co({M:this.ids.methodType,P:this.ids.pathType}),ct({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Nt)}),io(this.ids.responseInterface,Nt))),u=dt(this.ids.implementationType,s.createFunctionTypeNode(void 0,ct({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(j.SyntaxKind.StringKeyword),params:kt(j.SyntaxKind.StringKeyword,j.SyntaxKind.AnyKeyword)}),ao())),S=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,ke)]),T=Ht(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[S,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),w=Ht(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[S]),j.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),h=so(this.ids.clientClass,ro([pt(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),to)]),[no(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Ut([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,w]),!0))]);this.program.push(c,m,l,u,h);let R=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),$=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(O.json))]),void 0,this.ids.undefinedValue)),ae=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),xe=s.createVariableStatement(void 0,H(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,ke)]),s.createObjectLiteralExpression([R,$,ae])])))),pe=s.createVariableStatement(void 0,H(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),be=s.createVariableStatement(void 0,H(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),ke)])))),Ue=s.createVariableStatement(void 0,H(this.ids.isJsonConst,s.createCallChain(s.createPropertyAccessChain(s.createCallExpression(s.createPropertyAccessExpression(s.createPropertyAccessExpression(this.ids.responseConst,this.ids.headersProperty),s.createIdentifier("get")),void 0,[s.createStringLiteral("content-type")]),s.createToken(j.SyntaxKind.QuestionDotToken),s.createIdentifier("startsWith")),void 0,void 0,[s.createStringLiteral(O.json)]))),mt=s.createReturnStatement(s.createCallExpression(s.createElementAccessExpression(this.ids.responseConst,mo(this.ids.isJsonConst,s.createStringLiteral("json"),s.createStringLiteral("text"))),void 0,[])),He=s.createVariableStatement(V,H(this.ids.exampleImplementationConst,Ut([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([pe,be,xe,Ue,mt]),!0),s.createTypeReferenceNode(this.ids.implementationType))),M=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),_=s.createVariableStatement(void 0,H(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(He,_,M)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Kt(r,t)).join(` | ||
`):void 0}print(t){let r=this.printUsage(t),o=r&&j.addSyntheticLeadingComment(j.addSyntheticLeadingComment(s.createEmptyStatement(),j.SyntaxKind.SingleLineCommentTrivia," Usage example:"),j.SyntaxKind.MultiLineCommentTrivia,` | ||
${r}`);return this.program.concat(o||[]).map((n,i)=>Dt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(` | ||
${r}`);return this.program.concat(o||[]).map((n,i)=>Kt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(` | ||
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await ye("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var pi={dateIn:Qt,dateOut:Jt,file:$e,upload:er,raw:Xt};export{Ze as BuiltinLogger,ve as DependsOnMethod,vt as Documentation,E as DocumentationError,Ee as EndpointsFactory,U as InputValidationError,Ft as Integration,q as Middleware,Oe as MissingPeerError,G as OutputValidationError,ze as ResultHandler,ce as RoutingError,je as ServeStatic,Yo as arrayEndpointsFactory,Rt as arrayResultHandler,hn as attachRouting,No as createConfig,xn as createServer,Go as defaultEndpointsFactory,Ie as defaultResultHandler,Pe as ensureHttpError,pi as ez,F as getExamples,Y as getMessageFromError,Bo as getStatusCodeFromError,Es as testEndpoint,Zs as testMiddleware}; | ||
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await ge("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var ci={dateIn:Jt,dateOut:Wt,file:_e,upload:tr,raw:er};export{ve as BuiltinLogger,je as DependsOnMethod,jt as Documentation,E as DocumentationError,Ze as EndpointsFactory,U as InputValidationError,Bt as Integration,q as Middleware,Re as MissingPeerError,G as OutputValidationError,Ie as ResultHandler,ce as RoutingError,Le as ServeStatic,Qo as arrayEndpointsFactory,At as arrayResultHandler,xn as attachRouting,ko as createConfig,bn as createServer,Yo as defaultEndpointsFactory,Ee as defaultResultHandler,we as ensureHttpError,ci as ez,F as getExamples,Y as getMessageFromError,qo as getStatusCodeFromError,Zs as testEndpoint,vs as testMiddleware}; |
{ | ||
"name": "express-zod-api", | ||
"version": "20.21.2", | ||
"version": "20.22.0", | ||
"description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.", | ||
@@ -130,3 +130,3 @@ "license": "MIT", | ||
"@types/swagger-ui-express": "^4.1.6", | ||
"@typescript-eslint/rule-tester": "^8.0.1", | ||
"@typescript-eslint/rule-tester": "^8.15.0", | ||
"@vitest/coverage-v8": "^2.1.5", | ||
@@ -155,3 +155,3 @@ "camelize-ts": "^3.0.0", | ||
"typescript": "^5.5.2", | ||
"typescript-eslint": "^8.0.0", | ||
"typescript-eslint": "^8.15.0", | ||
"undici": "^6.19.8", | ||
@@ -158,0 +158,0 @@ "vitest": "^2.1.5", |
@@ -35,13 +35,14 @@ # Express Zod API | ||
1. [Customizing input sources](#customizing-input-sources) | ||
2. [Route path params](#route-path-params) | ||
3. [Multiple schemas for one route](#multiple-schemas-for-one-route) | ||
4. [Response customization](#response-customization) | ||
5. [Error handling](#error-handling) | ||
6. [Production mode](#production-mode) | ||
7. [Non-object response](#non-object-response) including file downloads | ||
8. [File uploads](#file-uploads) | ||
9. [Serving static files](#serving-static-files) | ||
10. [Connect to your own express app](#connect-to-your-own-express-app) | ||
11. [Testing endpoints](#testing-endpoints) | ||
12. [Testing middlewares](#testing-middlewares) | ||
2. [Nested routes](#nested-routes) | ||
3. [Route path params](#route-path-params) | ||
4. [Multiple schemas for one route](#multiple-schemas-for-one-route) | ||
5. [Response customization](#response-customization) | ||
6. [Error handling](#error-handling) | ||
7. [Production mode](#production-mode) | ||
8. [Non-object response](#non-object-response) including file downloads | ||
9. [File uploads](#file-uploads) | ||
10. [Serving static files](#serving-static-files) | ||
11. [Connect to your own express app](#connect-to-your-own-express-app) | ||
12. [Testing endpoints](#testing-endpoints) | ||
13. [Testing middlewares](#testing-middlewares) | ||
6. [Special needs](#special-needs) | ||
@@ -749,5 +750,21 @@ 1. [Different responses for different status codes](#different-responses-for-different-status-codes) | ||
## Nested routes | ||
Suppose you want to assign both `/v1/path` and `/v1/path/subpath` routes with Endpoints: | ||
```typescript | ||
import { Routing } from "express-zod-api"; | ||
const routing: Routing = { | ||
v1: { | ||
path: endpointA.nest({ | ||
subpath: endpointB, | ||
}), | ||
}, | ||
}; | ||
``` | ||
## Route path params | ||
You can describe the route of the endpoint using parameters: | ||
You can assign your Endpoint to a route like `/v1/user/:id` where `:id` is the path parameter: | ||
@@ -759,8 +776,3 @@ ```typescript | ||
v1: { | ||
user: { | ||
// route path /v1/user/:id, where :id is the path param | ||
":id": getUserEndpoint, | ||
// use the empty string to represent /v1/user if needed: | ||
// "": listAllUsersEndpoint, | ||
}, | ||
user: { ":id": getUserEndpoint }, | ||
}, | ||
@@ -767,0 +779,0 @@ }; |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
446077
1529
1449