New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

express-zod-api

Package Overview
Dependencies
Maintainers
0
Versions
430
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-zod-api - npm Package Compare versions

Comparing version 20.14.1 to 20.14.2

26

dist/index.d.ts

@@ -19,4 +19,11 @@ import * as zod from 'zod';

declare const severity: {
debug: number;
info: number;
warn: number;
error: number;
};
type Severity = keyof typeof severity;
/** @desc You can use any logger compatible with this type. */
type AbstractLogger = Record<"info" | "debug" | "warn" | "error", (message: string, meta?: any) => any>;
type AbstractLogger = Record<Severity, (message: string, meta?: any) => any>;
/**

@@ -61,3 +68,3 @@ * @desc Using module augmentation approach you can set the type of the actual logger used

/** @default "debug" */
severity?: keyof AbstractLogger | ((ms: number) => keyof AbstractLogger);
severity?: Severity | ((ms: number) => Severity);
/** @default formatDuration - adaptive units and limited fraction */

@@ -70,7 +77,7 @@ formatter?: (ms: number) => string | number;

protected hasColor: boolean;
protected readonly styles: Record<keyof AbstractLogger, Ansis>;
protected readonly styles: Record<Severity, Ansis>;
/** @example new BuiltinLogger({ level: "debug", color: true, depth: 4 }) */
constructor(config: BuiltinLoggerConfig);
protected prettyPrint(subject: unknown): string;
protected print(method: keyof AbstractLogger, message: string, meta?: unknown): void;
protected print(method: Severity, message: string, meta?: unknown): void;
debug(message: string, meta?: unknown): void;

@@ -86,2 +93,7 @@ info(message: string, meta?: unknown): void;

declare const defaultStatusCodes: {
positive: number;
negative: number;
};
type ResponseVariant = keyof typeof defaultStatusCodes;
interface ApiResponse<S extends z.ZodTypeAny> {

@@ -347,3 +359,2 @@ schema: S;

type IOVariant = "input" | "output";
type ResponseVariant = "positive" | "negative";
type MimeVariant = Extract<IOVariant, "input"> | ResponseVariant;

@@ -806,2 +817,3 @@ declare abstract class AbstractEndpoint {

protected lastOperationIdSuffixes: Map<string, number>;
protected responseVariants: ("positive" | "negative")[];
protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;

@@ -890,3 +902,3 @@ protected getRef(name: string): ReferenceObject | undefined;

loggerMock: AbstractLogger & LOG & {
_getLogs: () => Record<"info" | "debug" | "warn" | "error", unknown[]>;
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
};

@@ -907,3 +919,3 @@ }>;

type IOKind = "input" | "response" | "positive" | "negative";
type IOKind = "input" | "response" | ResponseVariant;
interface IntegrationParams {

@@ -910,0 +922,0 @@ routing: Routing;

@@ -1,7 +0,7 @@

import{clone as Yt,fromPairs as Ro,map as Ao,pipe as Po,toPairs as Co,pair as Io}from"ramda";import{z as ae}from"zod";import{isHttpError as uo}from"http-errors";import{createHash as fo}from"node:crypto";import{pickBy as yo,xprod as go}from"ramda";import{z as ho}from"zod";var se=class extends Error{name="RoutingError"},z=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:n}){let i=`${t}
Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},De=class extends Error{name="IOSchemaError"},V=class extends De{constructor(r){super(U(r));this.originalError=r}name="OutputValidationError"},L=class extends De{constructor(r){super(U(r));this.originalError=r}name="InputValidationError"},M=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},Oe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var P={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var xo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(P.upload);return"files"in e&&r},dt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},bo=["body","query","params"],lt=e=>e.method.toLowerCase(),mt=e=>e.startsWith("x-"),So=e=>yo((t,r)=>mt(r),e),ut=(e,t={})=>{let r=lt(e);return r==="options"?{}:(t[r]||dt[r]||bo).filter(o=>o==="files"?xo(e):!0).map(o=>o==="headers"?So(e[o]):e[o]).reduce((o,n)=>({...o,...n}),{})},ie=e=>e instanceof Error?e:new Error(String(e)),U=e=>e instanceof ho.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Fe=e=>uo(e)?e.statusCode:e instanceof L?400:500,ft=({logger:e,request:t,input:r,error:o,statusCode:n})=>{n===500&&e.error(`Internal server error
import{clone as Yt,fromPairs as Po,map as Co,pipe as Io,toPairs as zo,pair as wo}from"ramda";import{z as pe}from"zod";import{isHttpError as yo}from"http-errors";import{createHash as go}from"node:crypto";import{pickBy as ho,xprod as xo}from"ramda";import{z as bo}from"zod";var ie=class extends Error{name="RoutingError"},z=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:n}){let i=`${t}
Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},He=class extends Error{name="IOSchemaError"},G=class extends He{constructor(r){super(U(r));this.originalError=r}name="OutputValidationError"},L=class extends He{constructor(r){super(U(r));this.originalError=r}name="InputValidationError"},M=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},Oe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var P={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var So=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(P.upload);return"files"in e&&r},dt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},To=["body","query","params"],lt=e=>e.method.toLowerCase(),mt=e=>e.startsWith("x-"),Oo=e=>ho((t,r)=>mt(r),e),ut=(e,t={})=>{let r=lt(e);return r==="options"?{}:(t[r]||dt[r]||To).filter(o=>o==="files"?So(e):!0).map(o=>o==="headers"?Oo(e[o]):e[o]).reduce((o,n)=>({...o,...n}),{})},ae=e=>e instanceof Error?e:new Error(String(e)),U=e=>e instanceof bo.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof G?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,De=e=>yo(e)?e.statusCode:e instanceof L?400:500,ft=({logger:e,request:t,input:r,error:o,statusCode:n})=>{n===500&&e.error(`Internal server error
${o.stack}
`,{url:t.url,payload:r})},H=({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},_=(e,t,r)=>e.length&&t.length?go(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(),w=(...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=>fo("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Be=(e,t)=>{try{return typeof e.parse(t)}catch{return}},Y=e=>typeof e=="object"&&e!==null;import{clone as To,mergeDeepRight as Oo}from"ramda";var g=Symbol.for("express-zod-api"),qe=e=>{let t=e.describe(e.description);return t._def[g]=To(t._def[g])||{examples:[]},t},_t=(e,t)=>{if(!(g in e._def))return t;let r=qe(t);return r._def[g].examples=_(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Oo({...o},{...n}):n),r};var zo=function(e){let t=qe(this);return t._def[g].examples.push(e),t},wo=function(e){let t=qe(this);return t._def[g].defaultLabel=e,t},Eo=function(e){return new ae.ZodBranded({typeName:ae.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...Yt(this._def[g]),brand:e}})},Zo=function(e){let t=typeof e=="function"?e:Po(Co,Ao(([n,i])=>Io(e[String(n)]||n,i)),Ro),r=t(Yt(this.shape)),o=ae.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(ae.ZodType.prototype,{example:{get(){return zo.bind(this)}},brand:{set(){},get(){return Eo.bind(this)}}}),Object.defineProperty(ae.ZodDefault.prototype,"label",{get(){return wo.bind(this)}}),Object.defineProperty(ae.ZodObject.prototype,"remap",{get(){return Zo.bind(this)}}));function vo(e){return e}import{z as Fo}from"zod";import{z as nr}from"zod";import{z as Lo}from"zod";import{z as $e}from"zod";var D=Symbol("File"),Qt=$e.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),jo={buffer:()=>Qt.brand(D),string:()=>$e.string().brand(D),binary:()=>Qt.or($e.string()).brand(D),base64:()=>$e.string().base64().brand(D)};function Ge(e){return jo[e||"string"]()}var Q=Symbol("Raw"),Jt=(e={})=>Lo.object({raw:Ge("buffer")}).extend(e).brand(Q);import{z as No}from"zod";var Ae=Symbol("Upload"),Wt=()=>No.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(Ae);var Xt=(e,{next:t})=>e.options.some(t),ko=({_def:e},{next:t})=>[e.left,e.right].some(t),er=(e,{next:t})=>t(e.unwrap()),Mo={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Xt,ZodDiscriminatedUnion:Xt,ZodIntersection:ko,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:er,ZodNullable:er,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},gt=(e,{condition:t,rules:r=Mo,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let i=o<n?r[e._def.typeName]:void 0;return i?i(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},tr=e=>gt(e,{condition:t=>t._def[g]?.brand===Ae}),rr=e=>gt(e,{condition:t=>t._def[g]?.brand===Q,maxDepth:3});var Ve=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).type("text/plain").end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
Original error: ${e.originalError.message}.`:""))};import{chain as Uo}from"ramda";var J=e=>Y(e)&&"or"in e,ce=e=>Y(e)&&"and"in e,ht=e=>({and:Uo(t=>ce(t)?t.and:[t],e)}),_e=(e,t)=>ce(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>ce(r)?{and:r.and.map(t)}:t(r))}:t(e),xt=e=>e.and.reduce((t,r)=>({or:_(t.or,J(r)?r.or:[r],ht)}),{or:[]}),pe=(e,t)=>ce(e)?J(t)?pe(xt(e),t):ht([e,t]):J(e)?ce(t)?pe(t,e):J(t)?{or:_(e.or,t.or,ht)}:pe(e,{and:[t]}):ce(t)||J(t)?pe(t,e):{and:[e,t]};import{z as or}from"zod";var bt=class{},F=class extends bt{#e;#t;#r;constructor({input:t,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 or.ZodError?new L(o):o}}},de=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:or.object({}),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 Pe=class{},Ye=class extends Pe{#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:l,shortDescription:f}){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:l,short:f},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=tr(r)?"upload":rr(r)?"raw":"json",this.#i={input:Object.freeze([P[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:m})=>m)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:m})=>m))}}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?pe(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 nr.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof de))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof nr.ZodError?new L(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(d){Ve({logger:n,response:o,error:new M(ie(d).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=lt(t),p={},d=null,c=null;if(n.cors){let f=this.#m(i);typeof n.cors=="function"&&(f=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:f}));for(let m in f)r.set(m,f[m])}let l=ut(t,n.inputSources);try{if(await this.#f({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:l,logger:o,options:p}))}catch(f){c=ie(f)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};var sr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>_t(i,n),o)};import{z as v}from"zod";var Ce={positive:200,negative:400};import Ho from"node:assert/strict";import{z as Do}from"zod";var Qe=(e,t)=>typeof e=="function"?Qe(e(...t.arguments),t):e instanceof Do.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&Ho(e.length,new M(`At least one ${t.variant} response schema required.`)),(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})));var St=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Ie=class extends St{#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:[Ce.positive],mimeTypes:[P.json]})}getNegativeResponse(){return Qe(this.#t,{variant:"negative",arguments:[],statusCodes:[Ce.negative],mimeTypes:[P.json]})}},ze=new Ie({positive:e=>{let t=H({schema:e}),r=v.object({status:v.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:v.object({status:v.literal("error"),error:v.object({message:v.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(Ce.positive).json({status:"success",data:r});return}let a=Fe(e);ft({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:U(e)}})}}),Tt=new Ie({positive:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.ZodArray?e.shape.items:v.array(v.any());return t.reduce((o,n)=>Y(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:v.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=Fe(r);ft({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(Ce.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var we=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 F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new de(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({input:Fo.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],f=typeof a=="function"?a:()=>a,m="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new Ye({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:m,tags:h,methods:l,getOperationId:f,description:n,shortDescription:i,inputSchema:sr(d,t)})}},Ko=new we(ze),Bo=new we(Tt);import{Ansis as $o,blue as Go,cyanBright as Vo,green as _o,hex as Yo,red as Qo}from"ansis";import{inspect as Jo}from"node:util";import{performance as dr}from"node:perf_hooks";var le={debug:10,info:20,warn:30,error:40},ar=e=>Y(e)&&Object.keys(le).some(t=>t in e),pr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),Je=pr(),ir=pr(2),qo=e=>e<1e-6?["picosecond",e/1e-9,Je]:e<.001?["nanosecond",e/1e-6,Je]:e<1?["microsecond",e/.001,Je]:e<1e3?["millisecond",e,Je]:e<6e4?["second",e/1e3,ir]:["minute",e/6e4,ir],cr=e=>{let[t,r,o]=qo(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var Ee=class e{constructor(t){this.config=t;let{color:r=new $o().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:Go,info:_o,warn:Yo("#FFA500"),error:Qo};prettyPrint(t){let{depth:r=2}=this.config;return Jo(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||le[t]<le[this.config.level])return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?Vo(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.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=dr.now();return()=>{let o=dr.now()-r,{message:n,severity:i="debug",formatter:a=cr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};import{head as Wo,tail as Xo,toPairs as en}from"ramda";var Ze=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(en(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=Wo(this.pairs)?.[1],this.siblingMethods=Object.freeze(Xo(this.pairs).map(([r])=>r))}};import tn from"express";var ve=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,tn.static(...this.params))}};import Rt from"express";import cn from"node:http";import dn from"node:https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Oe(e)};import lr from"node:assert/strict";var W=({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){lr.doesNotMatch(a,/\//,new se(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof Pe){let c=p.getMethods().slice();n&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof ve)r&&p.apply(d,r);else if(p instanceof Ze){for(let[c,l]of p.pairs)lr(l.getMethods().includes(c),new se(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);n&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else W({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:d})}};var Ot=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>W({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,d)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,l)=>i.execute({request:c,response:l,logger:t(c),config:r,siblingMethods:d}))},onStatic:(i,a)=>{e.use(i,a)}});import xr,{isHttpError as on}from"http-errors";import{setInterval as rn}from"node:timers/promises";var mr=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",ur=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",fr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,yr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),gr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var hr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(mr(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 l of["connection","secureConnection"])c.on(l,p);let d=async()=>{for(let c of e)c.on("request",yr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(fr(c)||ur(c))&&a(c);for await(let c of rn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(gr))};return{sockets:n,shutdown:()=>o??=d()}};var br=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:on(r)?r:xr(400,ie(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Sr=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=xr(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){Ve({response:o,logger:i,error:new M(ie(a).message,n)})}},nn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},sn=e=>({log:e.debug.bind(e)}),Tr=async({getChildLogger:e,config:t})=>{let r=await me("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let l=e(p);try{await n?.({request:p,logger:l})}catch(f){return c(f)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:sn(l)})(p,d,c)}),o&&a.push(nn(o)),a},Or=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Rr=({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()},Ar=e=>t=>t.res?.locals[g]?.logger||e,Pr=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
`).slice(1))),Cr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=hr(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};import{gray as an,hex as Ir,italic as We,whiteBright as pn}from"ansis";var zr=()=>{let e=We("Proudly supports transgender community.".padStart(109)),t=We("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=We("Thank you for choosing Express Zod API for your project.".padStart(132)),o=We("for Zoey".padEnd(20)),n=Ir("#F5A9B8"),i=Ir("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(pn,5,7).fill(n,7,9).fill(i,9,12).fill(an,12,13);return`
`,{url:t.url,payload:r})},H=({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},_=(e,t,r)=>e.length&&t.length?xo(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(),w=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(yt).join(""),Fe=e=>go("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ke=(e,t)=>{try{return typeof e.parse(t)}catch{return}},Y=e=>typeof e=="object"&&e!==null;import{clone as Ro,mergeDeepRight as Ao}from"ramda";var g=Symbol.for("express-zod-api"),Be=e=>{let t=e.describe(e.description);return t._def[g]=Ro(t._def[g])||{examples:[]},t},_t=(e,t)=>{if(!(g in e._def))return t;let r=Be(t);return r._def[g].examples=_(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Ao({...o},{...n}):n),r};var Eo=function(e){let t=Be(this);return t._def[g].examples.push(e),t},Zo=function(e){let t=Be(this);return t._def[g].defaultLabel=e,t},vo=function(e){return new pe.ZodBranded({typeName:pe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...Yt(this._def[g]),brand:e}})},jo=function(e){let t=typeof e=="function"?e:Io(zo,Co(([n,i])=>wo(e[String(n)]||n,i)),Po),r=t(Yt(this.shape)),o=pe.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(pe.ZodType.prototype,{example:{get(){return Eo.bind(this)}},brand:{set(){},get(){return vo.bind(this)}}}),Object.defineProperty(pe.ZodDefault.prototype,"label",{get(){return Zo.bind(this)}}),Object.defineProperty(pe.ZodObject.prototype,"remap",{get(){return jo.bind(this)}}));function Lo(e){return e}import{z as Bo}from"zod";import{z as nr}from"zod";import{z as ko}from"zod";import{z as qe}from"zod";var D=Symbol("File"),Qt=qe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),No={buffer:()=>Qt.brand(D),string:()=>qe.string().brand(D),binary:()=>Qt.or(qe.string()).brand(D),base64:()=>qe.string().base64().brand(D)};function $e(e){return No[e||"string"]()}var Q=Symbol("Raw"),Jt=(e={})=>ko.object({raw:$e("buffer")}).extend(e).brand(Q);import{z as Mo}from"zod";var Ae=Symbol("Upload"),Wt=()=>Mo.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(Ae);var Xt=(e,{next:t})=>e.options.some(t),Uo=({_def:e},{next:t})=>[e.left,e.right].some(t),er=(e,{next:t})=>t(e.unwrap()),Ho={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Xt,ZodDiscriminatedUnion:Xt,ZodIntersection:Uo,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:er,ZodNullable:er,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},gt=(e,{condition:t,rules:r=Ho,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let i=o<n?r[e._def.typeName]:void 0;return i?i(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},tr=e=>gt(e,{condition:t=>t._def[g]?.brand===Ae}),rr=e=>gt(e,{condition:t=>t._def[g]?.brand===Q,maxDepth:3});var Ve=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).type("text/plain").end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
Original error: ${e.originalError.message}.`:""))};import{chain as Do}from"ramda";var J=e=>Y(e)&&"or"in e,de=e=>Y(e)&&"and"in e,ht=e=>({and:Do(t=>de(t)?t.and:[t],e)}),Ge=(e,t)=>de(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>de(r)?{and:r.and.map(t)}:t(r))}:t(e),xt=e=>e.and.reduce((t,r)=>({or:_(t.or,J(r)?r.or:[r],ht)}),{or:[]}),ce=(e,t)=>de(e)?J(t)?ce(xt(e),t):ht([e,t]):J(e)?de(t)?ce(t,e):J(t)?{or:_(e.or,t.or,ht)}:ce(e,{and:[t]}):de(t)||J(t)?ce(t,e):{and:[e,t]};import{z as or}from"zod";var bt=class{},F=class extends bt{#e;#t;#r;constructor({input:t,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 or.ZodError?new L(o):o}}},le=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:or.object({}),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 Pe=class{},_e=class extends Pe{#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:l,shortDescription:f}){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:l,short:f},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=tr(r)?"upload":rr(r)?"raw":"json",this.#i={input:Object.freeze([P[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:m})=>m)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:m})=>m))}}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?ce(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 nr.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof le))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof nr.ZodError?new L(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(d){Ve({logger:n,response:o,error:new M(ae(d).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=lt(t),p={},d=null,c=null;if(n.cors){let f=this.#m(i);typeof n.cors=="function"&&(f=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:f}));for(let m in f)r.set(m,f[m])}let l=ut(t,n.inputSources);try{if(await this.#f({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:l,logger:o,options:p}))}catch(f){c=ae(f)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};var sr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>_t(i,n),o)};import{z as v}from"zod";var W={positive:200,negative:400};import Fo from"node:assert/strict";import{z as Ko}from"zod";var Ye=(e,t)=>typeof e=="function"?Ye(e(...t.arguments),t):e instanceof Ko.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&Fo(e.length,new M(`At least one ${t.variant} response schema required.`)),(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})));var St=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Ce=class extends St{#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:[W.positive],mimeTypes:[P.json]})}getNegativeResponse(){return Ye(this.#t,{variant:"negative",arguments:[],statusCodes:[W.negative],mimeTypes:[P.json]})}},Ie=new Ce({positive:e=>{let t=H({schema:e}),r=v.object({status:v.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:v.object({status:v.literal("error"),error:v.object({message:v.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(W.positive).json({status:"success",data:r});return}let a=De(e);ft({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:U(e)}})}}),Tt=new Ce({positive:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.ZodArray?e.shape.items:v.array(v.any());return t.reduce((o,n)=>Y(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:v.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=De(r);ft({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(W.positive).json(t.items):e.status(500).type("text/plain").send("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 F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({input:Bo.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],f=typeof a=="function"?a:()=>a,m="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new _e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:m,tags:h,methods:l,getOperationId:f,description:n,shortDescription:i,inputSchema:sr(d,t)})}},qo=new ze(Ie),$o=new ze(Tt);import{Ansis as Go,blue as _o,cyanBright as Yo,green as Qo,hex as Jo,red as Wo}from"ansis";import{inspect as Xo}from"node:util";import{performance as mr}from"node:perf_hooks";var Je={debug:10,info:20,warn:30,error:40},ar=e=>Y(e)&&Object.keys(Je).some(t=>t in e),pr=e=>e in Je,cr=(e,t)=>Je[e]<Je[t],dr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),Qe=dr(),ir=dr(2),Vo=e=>e<1e-6?["picosecond",e/1e-9,Qe]:e<.001?["nanosecond",e/1e-6,Qe]:e<1?["microsecond",e/.001,Qe]:e<1e3?["millisecond",e,Qe]:e<6e4?["second",e/1e3,ir]:["minute",e/6e4,ir],lr=e=>{let[t,r,o]=Vo(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var we=class e{constructor(t){this.config=t;let{color:r=new Go().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:_o,info:Qo,warn:Jo("#FFA500"),error:Wo};prettyPrint(t){let{depth:r=2}=this.config;return Xo(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||cr(t,this.config.level))return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?Yo(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.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=mr.now();return()=>{let o=mr.now()-r,{message:n,severity:i="debug",formatter:a=lr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};import{head as en,tail as tn,toPairs as rn}from"ramda";var Ee=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(rn(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=en(this.pairs)?.[1],this.siblingMethods=Object.freeze(tn(this.pairs).map(([r])=>r))}};import on from"express";var Ze=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,on.static(...this.params))}};import Rt from"express";import ln from"node:http";import mn from"node:https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Oe(e)};import ur from"node:assert/strict";var X=({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){ur.doesNotMatch(a,/\//,new ie(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof Pe){let c=p.getMethods().slice();n&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof Ze)r&&p.apply(d,r);else if(p instanceof Ee){for(let[c,l]of p.pairs)ur(l.getMethods().includes(c),new ie(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);n&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else X({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:d})}};var Ot=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>X({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,d)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,l)=>i.execute({request:c,response:l,logger:t(c),config:r,siblingMethods:d}))},onStatic:(i,a)=>{e.use(i,a)}});import Sr,{isHttpError as sn}from"http-errors";import{setInterval as nn}from"node:timers/promises";var fr=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",yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",gr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,hr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),xr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var br=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(fr(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 l of["connection","secureConnection"])c.on(l,p);let d=async()=>{for(let c of e)c.on("request",hr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(gr(c)||yr(c))&&a(c);for await(let c of nn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(xr))};return{sockets:n,shutdown:()=>o??=d()}};var Tr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:sn(r)?r:Sr(400,ae(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Or=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=Sr(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){Ve({response:o,logger:i,error:new M(ae(a).message,n)})}},an=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},pn=e=>({log:e.debug.bind(e)}),Rr=async({getChildLogger:e,config:t})=>{let r=await me("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let l=e(p);try{await n?.({request:p,logger:l})}catch(f){return c(f)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:pn(l)})(p,d,c)}),o&&a.push(an(o)),a},Ar=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Pr=({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,Ir=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
`).slice(1))),zr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=br(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};import{gray as cn,hex as wr,italic as We,whiteBright as dn}from"ansis";var Er=()=>{let e=We("Proudly supports transgender community.".padStart(109)),t=We("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=We("Thank you for choosing Express Zod API for your project.".padStart(132)),o=We("for Zoey".padEnd(20)),n=wr("#F5A9B8"),i=wr("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(dn,5,7).fill(n,7,9).fill(i,9,12).fill(cn,12,13);return`
8888888888 8888888888P 888 d8888 8888888b. 8888888

@@ -21,6 +21,6 @@ 888 d88P 888 d88888 888 Y88b 888

`).map((d,c)=>a[c]?a[c](d):d).join(`
`)};var wr=e=>{e.startupLogo!==!1&&console.log(zr());let t=e.errorHandler||ze,r=ar(e.logger)?e.logger:new Ee(e.logger);r.debug("Running","v20.14.1 (ESM)"),Pr(r);let o=Rr({rootLogger:r,config:e}),i={getChildLogger:Ar(r),errorHandler:t},a=Sr(i),p=br(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},ln=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=wr(e);return Ot({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},mn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=wr(e),p=Rt().disable("x-powered-by").use(a);if(e.server.compression){let m=await me("compression");p.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),Or],upload:e.server.upload?await Tr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ot({app:p,routing:t,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(m,h)=>m.listen(h,()=>r.info("Listening",h)),l=cn.createServer(p),f=e.https&&dn.createServer(e.https.options,p);return e.gracefulShutdown&&Cr({servers:[l].concat(f||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(l,e.server.listen),httpsServer:f&&c(f,e.https?.listen)}};import gs from"node:assert/strict";import{OpenApiBuilder as hs}from"openapi3-ts/oas31";import{pluck as xs}from"ramda";import te from"node:assert/strict";import{isReferenceObject as Pt,isSchemaObject as tt}from"openapi3-ts/oas31";import{concat as fn,type as Lr,filter as yn,fromPairs as ke,has as gn,isNil as hn,map as ue,mergeAll as xn,mergeDeepRight as bn,mergeDeepWith as Sn,objOf as Nr,omit as rt,pipe as kr,pluck as Tn,range as On,reject as Rn,toLower as An,union as Pn,when as Cn,xprod as ot,zip as In}from"ramda";import{z as S}from"zod";import{z as je}from"zod";var Xe=e=>!isNaN(e.getTime());var Le=Symbol("DateIn"),Er=()=>je.union([je.string().date(),je.string().datetime(),je.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.date().refine(Xe)).brand(Le);import{z as un}from"zod";var Ne=Symbol("DateOut"),Zr=()=>un.date().refine(Xe).transform(e=>e.toISOString()).brand(Ne);var X=(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=>X(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 vr=50,Mr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Ur=/:([A-Za-z0-9_]+)/g,wn=e=>e.match(Ur)?.map(t=>t.slice(1))||[],Hr=e=>e.replace(Ur,t=>`{${t.slice(1)}}`),En=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Zn=({_def:{innerType:e}},{next:t})=>t(e),vn=()=>({format:"any"}),jn=({},e)=>(te(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Ln=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Nn=({options:e},{next:t})=>({oneOf:e.map(t)}),kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Mn=e=>{let[t,r]=e.filter(tt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));te(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Sn((n,i)=>Array.isArray(n)&&Array.isArray(i)?fn(n,i):n===i?i:te.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Pn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([n,i])=>bn(n,i))),o},Un=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Mn(o)}catch{}return{allOf:o}},Hn=(e,{next:t})=>t(e.unwrap()),Dn=(e,{next:t})=>t(e.unwrap()),Fn=(e,{next:t})=>{let r=t(e.unwrap());return tt(r)&&(r.type=Fr(r)),r},Dr=e=>{let t=An(Lr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},jr=e=>({type:Dr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Kn=({value:e})=>({type:Dr(e),const:e}),Bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof S.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=et(e,r)),i.length&&(a.required=i),a},qn=()=>({type:"null"}),$n=({},e)=>(te(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Mr}}),Gn=({},e)=>(te(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Mr}}),Vn=({},e)=>te.fail(new z({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})),_n=()=>({type:"boolean"}),Yn=()=>({type:"integer",format:"bigint"}),Qn=e=>e.every(t=>t instanceof S.ZodLiteral),Jn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=et(S.object(ke(ot(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:et(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Qn(e.options)){let o=ue(i=>`${i.value}`,e.options),n=ke(ot(o,[t]));return{type:"object",properties:et(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Wn=({_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},Xn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),es=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(R=>R.kind==="regex"),h=f.find(R=>R.kind==="datetime"),C=m?m.regex:h?h.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,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in Z)if(Z[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},ts=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,c?l.maximum=d:l.exclusiveMaximum=d,l},et=({shape:e},t)=>ue(t,e),rs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return zn?.[t]},Fr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},os=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&tt(o)){let i=Be(e,rs(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&&tt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},ns=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ss=(e,{next:t})=>t(e.unwrap()),is=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},as=(e,{next:t})=>t(e.unwrap().shape.raw),Kr=e=>e.length?ke(In(On(1,e.length+1).map(t=>`example${t}`),ue(Nr("value"),e))):void 0,Br=(e,t,r=[])=>kr(H,ue(Cn(o=>Lr(o)==="Object",rt(r))),Kr)({schema:e,variant:t?"parsed":"original",validate:!0}),ps=(e,t)=>kr(H,yn(gn(t)),Tn(t),Kr)({schema:e,variant:"original",validate:!0}),ee=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?ee(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>ee(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?ee(e._def.schema):e instanceof S.ZodPipeline?ee(e._def.in):ee(e._def.left).merge(ee(e._def.right)),qr=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=ee(r),f=wn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&mt(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ge})=>{let k=X(l[x],{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),$=p==="components"?a(w(c,x),k):k;return{name:x,in:ge,required:!l[x].isOptional(),description:k.description||c,schema:$,examples:ps(r,x)}})},Ct={ZodString:es,ZodNumber:ts,ZodBigInt:Yn,ZodBoolean:_n,ZodNull:qn,ZodArray:Wn,ZodTuple:Xn,ZodRecord:Jn,ZodObject:Bn,ZodLiteral:Kn,ZodIntersection:Un,ZodUnion:Nn,ZodAny:vn,ZodDefault:En,ZodEnum:jr,ZodNativeEnum:jr,ZodEffects:os,ZodOptional:Hn,ZodNullable:Fn,ZodDiscriminatedUnion:kn,ZodBranded:ss,ZodDate:Vn,ZodCatch:Zn,ZodPipeline:ns,ZodLazy:is,ZodReadonly:Dn,[D]:Ln,[Ae]:jn,[Ne]:Gn,[Le]:$n,[Q]:as},It=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d=n?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Fr(r)),d.length&&(c.examples=d.slice()),c},zt=(e,t)=>te.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=rt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>rt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},$r=e=>Pt(e)?e:rt(["examples"],e),Gr=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${c?l:""}`.trim()})=>{let h=$r(X(r,{rules:{...f,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(w(m),h):h,examples:Br(r,!0)};return{description:m,content:ke(ot(o,[C]))}},cs=()=>({type:"http",scheme:"basic"}),ds=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ls=({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},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),us=({name:e})=>({type:"apiKey",in:"cookie",name:e}),fs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ys=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),Rn(hn,e))}),Vr=(e,t)=>{let r={basic:cs,bearer:ds,input:ls,header:ms,cookie:us,openid:fs,oauth2:ys};return _e(e,o=>r[o.type](o,t))},nt=e=>"or"in e?e.or.map(t=>"and"in t?xn(ue(({name:r,scopes:o})=>Nr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?nt(xt(e)):nt({or:[e]}),_r=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=$r(At(X(r,{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(w(l),f):f,examples:Br(r,!1,c)};return{description:l,content:ke(ot(o,[m]))}},Yr=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}),wt=e=>e.length<=vr?e:e.slice(0,vr-1)+"\u2026";var Et=class extends hs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||w(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&gs.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),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",serializer:l=Ke}){super(),this.addInfo({title:o,version:n});for(let m of typeof i=="string"?[i]:i)this.addServer({url:m});W({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,x]=["short","long"].map(m.getDescription.bind(m)),ge=R?wt(R):d&&x?wt(x):void 0,k=m.getTags(),$=r.inputSources?.[b]||dt[b],oe=this.ensureUniqOperationId(h,b,m.getOperationId(b)),he=qr({...Z,inputSources:$,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:oe})}),Ue={};for(let j of["positive","negative"]){let G=m.getResponses(j);for(let{mimeTypes:xe,schema:T,statusCodes:O}of G)for(let A of O)Ue[A]=Gr({...Z,variant:j,schema:T,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:G.length>1||O.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:h,operationId:oe,statusCode:A})})}let ct=$.includes("body")?_r({...Z,paramNames:xs("name",he),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:oe})}):void 0,He=nt(_e(Vr(m.getSecurity(),$),j=>{let G=this.ensureUniqSecuritySchemaName(j),xe=["oauth2","openIdConnect"].includes(j.type)?m.getScopes().slice():[];return this.addSecurityScheme(G,j),{name:G,scopes:xe}}));this.addPath(Hr(h),{[b]:{operationId:oe,summary:ge,description:x,tags:k.length>0?k:void 0,parameters:he.length>0?he:void 0,requestBody:ct,security:He.length>0?He:void 0,responses:Ue}})}}),this.rootDoc.tags=r.tags?Yr(r.tags):[]}};import{createRequest as bs,createResponse as Ss}from"node-mocks-http";var Ts=e=>bs({...e,headers:{"content-type":P.json,...e?.headers}}),Os=e=>Ss(e),Rs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:o in le?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},As=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ts(e),i=Os({req:n,...t});i.req=t?.req||n,n.res=i;let a=Rs(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Ps=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=As(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};import E from"typescript";import N from"typescript";import{chain as Qr,toPairs as Jr}from"ramda";var s=N.factory,K=[s.createModifier(N.SyntaxKind.ExportKeyword)],Cs=[s.createModifier(N.SyntaxKind.AsyncKeyword)],Is=[s.createModifier(N.SyntaxKind.PublicKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Wr=[s.createModifier(N.SyntaxKind.ProtectedKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Zt=s.createTemplateHead(""),fe=s.createTemplateTail(""),vt=s.createTemplateMiddle(" "),jt=e=>s.createTemplateLiteralType(Zt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Lt=jt(["M","P"]),st=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),it=(e,t)=>Qr(([r,o])=>[st(s.createIdentifier(r),o,t)],Jr(e)),Nt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Xr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),eo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),B=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],N.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),at=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,t),to=(e,t,r)=>s.createPropertyDeclaration(Is,e,void 0,t,r),ro=(e,t,r)=>s.createClassDeclaration(K,e,void 0,void 0,[t,...r]),oo=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),no=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(N.SyntaxKind.AnyKeyword)]),so=(e,t,r)=>s.createInterfaceDeclaration(K,e,void 0,t,r),zs=Qr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),io=e=>zs(Jr(e)),Mt=(e,t,r)=>s.createArrowFunction(r?Cs:void 0,void 0,e.map(o=>st(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,it({acc:void 0,key:void 0}),void 0,void 0,t),r]),ao=(...e)=>`"${e.join(" ")}"`;var po=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import q from"typescript";var{factory:pt}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=pt.createTypeAliasDeclaration(void 0,pt.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},ws=/^[A-Za-z_$][A-Za-z0-9_$]*$/,co=e=>ws.test(e)?pt.createIdentifier(e):pt.createStringLiteral(e);var{factory:u}=y,Es={[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},Zs=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),vs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,co(i),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(n)},js=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ls=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),lo=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),Ns=e=>Es?.[e.kind],ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Be(e,Ns(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 u.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},Ms=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Hs=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Ds=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),Fs=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Ks=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Bs=({_def:e},{next:t})=>t(e.innerType),re=e=>()=>u.createKeywordTypeNode(e),qs=(e,{next:t})=>t(e.unwrap()),$s=(e,{next:t})=>t(e.unwrap()),Gs=({_def:e},{next:t})=>t(e.innerType),Vs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),_s=()=>u.createLiteralTypeNode(u.createNull()),Ys=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,u.createLiteralTypeNode(u.createNull())),r(i,o(e)))},Qs=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},Js=(e,{next:t})=>t(e.unwrap().shape.raw),Ws={ZodString:re(y.SyntaxKind.StringKeyword),ZodNumber:re(y.SyntaxKind.NumberKeyword),ZodBigInt:re(y.SyntaxKind.BigIntKeyword),ZodBoolean:re(y.SyntaxKind.BooleanKeyword),ZodAny:re(y.SyntaxKind.AnyKeyword),[Le]:re(y.SyntaxKind.StringKeyword),[Ne]:re(y.SyntaxKind.StringKeyword),ZodNull:_s,ZodArray:js,ZodTuple:Ds,ZodRecord:Fs,ZodObject:vs,ZodLiteral:Zs,ZodIntersection:Ks,ZodUnion:lo,ZodDefault:Bs,ZodEnum:Ls,ZodNativeEnum:Ms,ZodEffects:ks,ZodOptional:Us,ZodNullable:Hs,ZodDiscriminatedUnion:lo,ZodBranded:qs,ZodCatch:Gs,ZodPipeline:Vs,ZodLazy:Ys,ZodReadonly:$s,[D]:Qs,[Q]:Js},Me=(e,{brandHandling:t,ctx:r})=>X(e,{rules:{...t,...Ws},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Kt=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")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Ke,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){W({routing:t,onEndpoint:(T,O,A)=>{let ne={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Se=Me(T.getSchema("input"),{brandHandling:r,ctx:{...ne,isResponse:!1}}),I=i?w(A,O,"positive.response"):void 0,Bt=T.getSchema("positive"),qt=i?Me(Bt,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Te=i?w(A,O,"negative.response"):void 0,$t=T.getSchema("negative"),Gt=i?Me($t,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Vt=w(A,O,"response"),mo=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):Me(Bt.or($t),{brandHandling:r,ctx:{...ne,isResponse:!0}});this.program.push(ye(Se,be)),qt&&I&&this.program.push(ye(qt,I)),Gt&&Te&&this.program.push(ye(Gt,Te)),this.program.push(ye(mo,Vt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:I,negative:Te,response:Vt,isJson:T.getMimeTypes("positive").includes(P.json),tags:T.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,po)),this.program.push(at(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:T,path:O},{isJson:A,tags:ne,...be}]of this.registry){let Se=ao(T,O);for(let I of this.interfaces)I.kind in be&&I.props.push(eo(Se,be[I.kind]));o!=="types"&&(A&&d.push(s.createPropertyAssignment(Se,s.createTrue())),c.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(ne.map(I=>s.createStringLiteral(I))))))}for(let{id:T,props:O}of this.interfaces)this.program.push(so(T,p,O));if(o==="types")return;let l=s.createVariableStatement(K,B(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(d))),f=s.createVariableStatement(K,B(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),m=at(this.ids.providerType,s.createFunctionTypeNode(io({M:this.ids.methodType,P:this.ids.pathType}),it({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),oo(this.ids.responseInterface,Lt))),h=at(this.ids.implementationType,s.createFunctionTypeNode(void 0,it({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),no())),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),E.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()),R=ro(this.ids.clientClass,Xr([st(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Wr)]),[to(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,b,Z]),!0))]);this.program.push(l,f,m,h,R);let x=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(P.json))]),void 0,this.ids.undefinedValue)),k=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)),$=s.createVariableStatement(void 0,B(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,fe)]),s.createObjectLiteralExpression([x,ge,k])])))),oe=s.createVariableStatement(void 0,B(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=s.createVariableStatement(void 0,B(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]),fe)])))),[Ue,ct]=["json","text"].map(T=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,T),void 0,void 0))),He=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Zt,[s.createTemplateSpan(this.ids.methodParameter,vt),s.createTemplateSpan(this.ids.pathParameter,fe)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ue])),j=s.createVariableStatement(K,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([oe,he,$,He,ct]),!0),s.createTypeReferenceNode(this.ids.implementationType))),G=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"))])])),xe=s.createVariableStatement(void 0,B(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(j,xe,G)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
`)};var Zr=e=>{e.startupLogo!==!1&&console.log(Er());let t=e.errorHandler||Ie,r=ar(e.logger)?e.logger:new we(e.logger);r.debug("Running","v20.14.2 (ESM)"),Ir(r);let o=Pr({rootLogger:r,config:e}),i={getChildLogger:Cr(r),errorHandler:t},a=Or(i),p=Tr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},un=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Zr(e);return Ot({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},fn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Zr(e),p=Rt().disable("x-powered-by").use(a);if(e.server.compression){let m=await me("compression");p.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),Ar],upload:e.server.upload?await Rr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ot({app:p,routing:t,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(m,h)=>m.listen(h,()=>r.info("Listening",h)),l=ln.createServer(p),f=e.https&&mn.createServer(e.https.options,p);return e.gracefulShutdown&&zr({servers:[l].concat(f||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(l,e.server.listen),httpsServer:f&&c(f,e.https?.listen)}};import xs from"node:assert/strict";import{OpenApiBuilder as bs}from"openapi3-ts/oas31";import{keys as Ss,pluck as Ts}from"ramda";import re from"node:assert/strict";import{isReferenceObject as Pt,isSchemaObject as tt}from"openapi3-ts/oas31";import{concat as gn,type as kr,filter as hn,fromPairs as Ne,has as xn,isNil as bn,map as ue,mergeAll as Sn,mergeDeepRight as Tn,mergeDeepWith as On,objOf as Mr,omit as rt,pipe as Ur,pluck as Rn,range as An,reject as Pn,toLower as Cn,union as In,when as zn,xprod as ot,zip as wn}from"ramda";import{z as S}from"zod";import{z as ve}from"zod";var Xe=e=>!isNaN(e.getTime());var je=Symbol("DateIn"),vr=()=>ve.union([ve.string().date(),ve.string().datetime(),ve.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ve.date().refine(Xe)).brand(je);import{z as yn}from"zod";var Le=Symbol("DateOut"),jr=()=>yn.date().refine(Xe).transform(e=>e.toISOString()).brand(Le);var ee=(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=>ee(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",En={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Dr=/:([A-Za-z0-9_]+)/g,Zn=e=>e.match(Dr)?.map(t=>t.slice(1))||[],Fr=e=>e.replace(Dr,t=>`{${t.slice(1)}}`),vn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),jn=({_def:{innerType:e}},{next:t})=>t(e),Ln=()=>({format:"any"}),Nn=({},e)=>(re(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),kn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Mn=({options:e},{next:t})=>({oneOf:e.map(t)}),Un=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Hn=e=>{let[t,r]=e.filter(tt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));re(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=On((n,i)=>Array.isArray(n)&&Array.isArray(i)?gn(n,i):n===i?i:re.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=In(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([n,i])=>Tn(n,i))),o},Dn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Hn(o)}catch{}return{allOf:o}},Fn=(e,{next:t})=>t(e.unwrap()),Kn=(e,{next:t})=>t(e.unwrap()),Bn=(e,{next:t})=>{let r=t(e.unwrap());return tt(r)&&(r.type=Br(r)),r},Kr=e=>{let t=Cn(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:Kr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),qn=({value:e})=>({type:Kr(e),const:e}),$n=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof S.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=et(e,r)),i.length&&(a.required=i),a},Vn=()=>({type:"null"}),Gn=({},e)=>(re(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Hr}}),_n=({},e)=>(re(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Hr}}),Yn=({},e)=>re.fail(new z({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})),Qn=()=>({type:"boolean"}),Jn=()=>({type:"integer",format:"bigint"}),Wn=e=>e.every(t=>t instanceof S.ZodLiteral),Xn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=et(S.object(Ne(ot(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:et(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Wn(e.options)){let o=ue(i=>`${i.value}`,e.options),n=Ne(ot(o,[t]));return{type:"object",properties:et(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},es=({_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},ts=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),rs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(R=>R.kind==="regex"),h=f.find(R=>R.kind==="datetime"),C=m?m.regex:h?h.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,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in Z)if(Z[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},os=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,c?l.maximum=d:l.exclusiveMaximum=d,l},et=({shape:e},t)=>ue(t,e),ns=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return En?.[t]},Br=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},ss=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&tt(o)){let i=Ke(e,ns(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&&tt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},is=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),as=(e,{next:t})=>t(e.unwrap()),ps=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},cs=(e,{next:t})=>t(e.unwrap().shape.raw),qr=e=>e.length?Ne(wn(An(1,e.length+1).map(t=>`example${t}`),ue(Mr("value"),e))):void 0,$r=(e,t,r=[])=>Ur(H,ue(zn(o=>kr(o)==="Object",rt(r))),qr)({schema:e,variant:t?"parsed":"original",validate:!0}),ds=(e,t)=>Ur(H,hn(xn(t)),Rn(t),qr)({schema:e,variant:"original",validate:!0}),te=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?te(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>te(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?te(e._def.schema):e instanceof S.ZodPipeline?te(e._def.in):te(e._def.left).merge(te(e._def.right)),Vr=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=te(r),f=Zn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&mt(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ge})=>{let k=ee(l[x],{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),$=p==="components"?a(w(c,x),k):k;return{name:x,in:ge,required:!l[x].isOptional(),description:k.description||c,schema:$,examples:ds(r,x)}})},Ct={ZodString:rs,ZodNumber:os,ZodBigInt:Jn,ZodBoolean:Qn,ZodNull:Vn,ZodArray:es,ZodTuple:ts,ZodRecord:Xn,ZodObject:$n,ZodLiteral:qn,ZodIntersection:Dn,ZodUnion:Mn,ZodAny:Ln,ZodDefault:vn,ZodEnum:Nr,ZodNativeEnum:Nr,ZodEffects:ss,ZodOptional:Fn,ZodNullable:Bn,ZodDiscriminatedUnion:Un,ZodBranded:as,ZodDate:Yn,ZodCatch:jn,ZodPipeline:is,ZodLazy:ps,ZodReadonly:Kn,[D]:kn,[Ae]:Nn,[Le]:_n,[je]:Gn,[Q]:cs},It=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d=n?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Br(r)),d.length&&(c.examples=d.slice()),c},zt=(e,t)=>re.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=rt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>rt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},Gr=e=>Pt(e)?e:rt(["examples"],e),_r=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${c?l:""}`.trim()})=>{let h=Gr(ee(r,{rules:{...f,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(w(m),h):h,examples:$r(r,!0)};return{description:m,content:Ne(ot(o,[C]))}},ls=()=>({type:"http",scheme:"basic"}),ms=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},us=({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},fs=({name:e})=>({type:"apiKey",in:"header",name:e}),ys=({name:e})=>({type:"apiKey",in:"cookie",name:e}),gs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),hs=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),Pn(bn,e))}),Yr=(e,t)=>{let r={basic:ls,bearer:ms,input:us,header:fs,cookie:ys,openid:gs,oauth2:hs};return Ge(e,o=>r[o.type](o,t))},nt=e=>"or"in e?e.or.map(t=>"and"in t?Sn(ue(({name:r,scopes:o})=>Mr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?nt(xt(e)):nt({or:[e]}),Qr=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=Gr(At(ee(r,{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(w(l),f):f,examples:$r(r,!1,c)};return{description:l,content:Ne(ot(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}),wt=e=>e.length<=Lr?e:e.slice(0,Lr-1)+"\u2026";var Et=class extends bs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=Ss(W);makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||w(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&xs.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),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",serializer:l=Fe}){super(),this.addInfo({title:o,version:n});for(let m of typeof i=="string"?[i]:i)this.addServer({url:m});X({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,x]=["short","long"].map(m.getDescription.bind(m)),ge=R?wt(R):d&&x?wt(x):void 0,k=m.getTags(),$=r.inputSources?.[b]||dt[b],ne=this.ensureUniqOperationId(h,b,m.getOperationId(b)),he=Vr({...Z,inputSources:$,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:ne})}),Me={};for(let j of this.responseVariants){let V=m.getResponses(j);for(let{mimeTypes:xe,schema:T,statusCodes:O}of V)for(let A of O)Me[A]=_r({...Z,variant:j,schema:T,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:V.length>1||O.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:h,operationId:ne,statusCode:A})})}let ct=$.includes("body")?Qr({...Z,paramNames:Ts("name",he),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:ne})}):void 0,Ue=nt(Ge(Yr(m.getSecurity(),$),j=>{let V=this.ensureUniqSecuritySchemaName(j),xe=["oauth2","openIdConnect"].includes(j.type)?m.getScopes().slice():[];return this.addSecurityScheme(V,j),{name:V,scopes:xe}}));this.addPath(Fr(h),{[b]:{operationId:ne,summary:ge,description:x,tags:k.length>0?k:void 0,parameters:he.length>0?he:void 0,requestBody:ct,security:Ue.length>0?Ue:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Jr(r.tags):[]}};import{createRequest as Os,createResponse as Rs}from"node-mocks-http";var As=e=>Os({...e,headers:{"content-type":P.json,...e?.headers}}),Ps=e=>Rs(e),Cs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:pr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Is=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),i=Ps({req:n,...t});i.req=t?.req||n,n.res=i;let a=Cs(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}=Is(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};import E from"typescript";import N from"typescript";import{chain as Wr,toPairs as Xr}from"ramda";var s=N.factory,K=[s.createModifier(N.SyntaxKind.ExportKeyword)],ws=[s.createModifier(N.SyntaxKind.AsyncKeyword)],Es=[s.createModifier(N.SyntaxKind.PublicKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],eo=[s.createModifier(N.SyntaxKind.ProtectedKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Zt=s.createTemplateHead(""),fe=s.createTemplateTail(""),vt=s.createTemplateMiddle(" "),jt=e=>s.createTemplateLiteralType(Zt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Lt=jt(["M","P"]),st=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),it=(e,t)=>Wr(([r,o])=>[st(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)),B=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],N.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),at=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,t),oo=(e,t,r)=>s.createPropertyDeclaration(Es,e,void 0,t,r),no=(e,t,r)=>s.createClassDeclaration(K,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(N.SyntaxKind.AnyKeyword)]),ao=(e,t,r)=>s.createInterfaceDeclaration(K,e,void 0,t,r),Zs=Wr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),po=e=>Zs(Xr(e)),Mt=(e,t,r)=>s.createArrowFunction(r?ws:void 0,void 0,e.map(o=>st(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,it({acc:void 0,key:void 0}),void 0,void 0,t),r]),co=(...e)=>`"${e.join(" ")}"`;var lo=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import q from"typescript";var{factory:pt}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=pt.createTypeAliasDeclaration(void 0,pt.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},vs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mo=e=>vs.test(e)?pt.createIdentifier(e):pt.createStringLiteral(e);var{factory:u}=y,js={[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},Ls=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Ns=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,mo(i),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(n)},ks=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ms=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),uo=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),Us=e=>js?.[e.kind],Hs=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ke(e,Us(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 u.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},Ds=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Fs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Ks=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Bs=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),qs=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),$s=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Vs=({_def:e},{next:t})=>t(e.innerType),oe=e=>()=>u.createKeywordTypeNode(e),Gs=(e,{next:t})=>t(e.unwrap()),_s=(e,{next:t})=>t(e.unwrap()),Ys=({_def:e},{next:t})=>t(e.innerType),Qs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Js=()=>u.createLiteralTypeNode(u.createNull()),Ws=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,u.createLiteralTypeNode(u.createNull())),r(i,o(e)))},Xs=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},ei=(e,{next:t})=>t(e.unwrap().shape.raw),ti={ZodString:oe(y.SyntaxKind.StringKeyword),ZodNumber:oe(y.SyntaxKind.NumberKeyword),ZodBigInt:oe(y.SyntaxKind.BigIntKeyword),ZodBoolean:oe(y.SyntaxKind.BooleanKeyword),ZodAny:oe(y.SyntaxKind.AnyKeyword),[je]:oe(y.SyntaxKind.StringKeyword),[Le]:oe(y.SyntaxKind.StringKeyword),ZodNull:Js,ZodArray:ks,ZodTuple:Bs,ZodRecord:qs,ZodObject:Ns,ZodLiteral:Ls,ZodIntersection:$s,ZodUnion:uo,ZodDefault:Vs,ZodEnum:Ms,ZodNativeEnum:Ds,ZodEffects:Hs,ZodOptional:Fs,ZodNullable:Ks,ZodDiscriminatedUnion:uo,ZodBranded:Gs,ZodCatch:Ys,ZodPipeline:Qs,ZodLazy:Ws,ZodReadonly:_s,[D]:Xs,[Q]:ei},ke=(e,{brandHandling:t,ctx:r})=>ee(e,{rules:{...t,...ti},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Kt=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")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Fe,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){X({routing:t,onEndpoint:(T,O,A)=>{let se={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Se=ke(T.getSchema("input"),{brandHandling:r,ctx:{...se,isResponse:!1}}),I=i?w(A,O,"positive.response"):void 0,Bt=T.getSchema("positive"),qt=i?ke(Bt,{brandHandling:r,ctx:{...se,isResponse:!0}}):void 0,Te=i?w(A,O,"negative.response"):void 0,$t=T.getSchema("negative"),Vt=i?ke($t,{brandHandling:r,ctx:{...se,isResponse:!0}}):void 0,Gt=w(A,O,"response"),fo=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):ke(Bt.or($t),{brandHandling:r,ctx:{...se,isResponse:!0}});this.program.push(ye(Se,be)),qt&&I&&this.program.push(ye(qt,I)),Vt&&Te&&this.program.push(ye(Vt,Te)),this.program.push(ye(fo,Gt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:I,negative:Te,response:Gt,isJson:T.getMimeTypes("positive").includes(P.json),tags:T.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,lo)),this.program.push(at(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:T,path:O},{isJson:A,tags:se,...be}]of this.registry){let Se=co(T,O);for(let I of this.interfaces)I.kind in be&&I.props.push(ro(Se,be[I.kind]));o!=="types"&&(A&&d.push(s.createPropertyAssignment(Se,s.createTrue())),c.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(se.map(I=>s.createStringLiteral(I))))))}for(let{id:T,props:O}of this.interfaces)this.program.push(ao(T,p,O));if(o==="types")return;let l=s.createVariableStatement(K,B(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(d))),f=s.createVariableStatement(K,B(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),m=at(this.ids.providerType,s.createFunctionTypeNode(po({M:this.ids.methodType,P:this.ids.pathType}),it({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),so(this.ids.responseInterface,Lt))),h=at(this.ids.implementationType,s.createFunctionTypeNode(void 0,it({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),io())),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),E.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()),R=no(this.ids.clientClass,to([st(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,b,Z]),!0))]);this.program.push(l,f,m,h,R);let x=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(P.json))]),void 0,this.ids.undefinedValue)),k=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)),$=s.createVariableStatement(void 0,B(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,fe)]),s.createObjectLiteralExpression([x,ge,k])])))),ne=s.createVariableStatement(void 0,B(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=s.createVariableStatement(void 0,B(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]),fe)])))),[Me,ct]=["json","text"].map(T=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,T),void 0,void 0))),Ue=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Zt,[s.createTemplateSpan(this.ids.methodParameter,vt),s.createTemplateSpan(this.ids.pathParameter,fe)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Me])),j=s.createVariableStatement(K,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([ne,he,$,Ue,ct]),!0),s.createTypeReferenceNode(this.ids.implementationType))),V=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"))])])),xe=s.createVariableStatement(void 0,B(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(j,xe,V)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
`):void 0}print(t){let r=this.printUsage(t),o=r&&E.addSyntheticLeadingComment(E.addSyntheticLeadingComment(s.createEmptyStatement(),E.SyntaxKind.SingleLineCommentTrivia," Usage example:"),E.SyntaxKind.MultiLineCommentTrivia,`
${r}`);return this.program.concat(o||[]).map((n,i)=>Dt(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 me("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 Xs={dateIn:Er,dateOut:Zr,file:Ge,upload:Wt,raw:Jt};export{Ee as BuiltinLogger,Ze as DependsOnMethod,Et as Documentation,z as DocumentationError,we as EndpointsFactory,L as InputValidationError,Kt as Integration,F as Middleware,Oe as MissingPeerError,V as OutputValidationError,Ie as ResultHandler,se as RoutingError,ve as ServeStatic,Bo as arrayEndpointsFactory,Tt as arrayResultHandler,ln as attachRouting,vo as createConfig,mn as createServer,Ko as defaultEndpointsFactory,ze as defaultResultHandler,Xs as ez,H as getExamples,U as getMessageFromError,Fe as getStatusCodeFromError,Ps as testEndpoint};
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await me("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 ri={dateIn:vr,dateOut:jr,file:$e,upload:Wt,raw:Jt};export{we as BuiltinLogger,Ee as DependsOnMethod,Et as Documentation,z as DocumentationError,ze as EndpointsFactory,L as InputValidationError,Kt as Integration,F as Middleware,Oe as MissingPeerError,G as OutputValidationError,Ce as ResultHandler,ie as RoutingError,Ze as ServeStatic,$o as arrayEndpointsFactory,Tt as arrayResultHandler,un as attachRouting,Lo as createConfig,fn as createServer,qo as defaultEndpointsFactory,Ie as defaultResultHandler,ri as ez,H as getExamples,U as getMessageFromError,De as getStatusCodeFromError,zs as testEndpoint};

@@ -1,1 +0,1 @@

import{ESLintUtils as c}from"@typescript-eslint/utils";var p="express-zod-api";var d="testEndpoint",i={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},o={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},m={fnMethod:null},a=(r,t)=>typeof r=="string"&&r in t,u=c.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:r=>({ImportDeclaration:t=>{if(t.source.value===p){for(let e of t.specifiers)if(e.type==="ImportSpecifier"&&a(e.imported.name,i)){let s=i[e.imported.name];r.report({node:e.imported,messageId:"change",data:{subject:"import",from:e.imported.name,to:s},fix:n=>n.replaceText(e,s)})}}},CallExpression:t=>{if(t.callee.type==="Identifier"&&a(t.callee.name,i)){let e=`new ${i[t.callee.name]}`;r.report({node:t.callee,messageId:"change",data:{subject:"call",from:t.callee.name,to:e},fix:s=>s.replaceText(t.callee,e)})}if(t.callee.type==="Identifier"&&t.callee.name===d&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(a(e.key.name,o)){let s=o[e.key.name];r.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:s},fix:n=>n.replaceText(e.key,s)})}a(e.key.name,m)&&r.report({node:e,messageId:"remove",data:{subject:"property",name:e.key.name},fix:s=>r.sourceCode.getTokenAfter(e)?.value===","&&e.range?s.removeRange([e.range[0],e.range[1]+1]):s.remove(e)})}}},NewExpression:t=>{if(t.callee.type==="Identifier"&&[i.createResultHandler,i.createMiddleware].includes(t.callee.name)&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&a(e.key.name,o)){let s=o[e.key.name];r.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:s},fix:n=>n.replaceText(e.key,s)})}}},Identifier:t=>{t.name==="MockOverrides"&&t.parent.type==="TSInterfaceDeclaration"&&r.report({node:t,messageId:"remove",data:{subject:"augmentation",name:t.name},fix:e=>e.remove(t.parent)})}})}),x={rules:{v20:u}};export{x as default};
import{ESLintUtils as c}from"@typescript-eslint/utils";var p="express-zod-api";var d="testEndpoint",i={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},o={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},m={fnMethod:null},a=(r,t)=>typeof r=="string"&&r in t,u=c.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:r=>({ImportDeclaration:t=>{if(t.source.value===p){for(let e of t.specifiers)if(e.type==="ImportSpecifier"&&a(e.imported.name,i)){let s=i[e.imported.name];r.report({node:e.imported,messageId:"change",data:{subject:"import",from:e.imported.name,to:s},fix:n=>n.replaceText(e,s)})}}},CallExpression:t=>{if(t.callee.type==="Identifier"&&a(t.callee.name,i)){let e=`new ${i[t.callee.name]}`;r.report({node:t.callee,messageId:"change",data:{subject:"call",from:t.callee.name,to:e},fix:s=>s.replaceText(t.callee,e)})}if(t.callee.type==="Identifier"&&t.callee.name===d&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(a(e.key.name,o)){let s=o[e.key.name];r.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:s},fix:n=>n.replaceText(e.key,s)})}a(e.key.name,m)&&r.report({node:e,messageId:"remove",data:{subject:"property",name:e.key.name},fix:s=>r.sourceCode.getTokenAfter(e)?.value===","&&e.range?s.removeRange([e.range[0],e.range[1]+1]):s.remove(e)})}}},NewExpression:t=>{if(t.callee.type==="Identifier"&&[i.createResultHandler,i.createMiddleware].includes(t.callee.name)&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&a(e.key.name,o)){let s=o[e.key.name];r.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:s},fix:n=>n.replaceText(e.key,s)})}}},Identifier:t=>{t.name==="MockOverrides"&&t.parent.type==="TSInterfaceDeclaration"&&r.report({node:t,messageId:"remove",data:{subject:"augmentation",name:t.name},fix:e=>e.remove(t.parent)})}})}),h={rules:{v20:u}};export{h as default};
{
"name": "express-zod-api",
"version": "20.14.1",
"version": "20.14.2",
"description": "A Typescript library to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",

@@ -16,5 +16,4 @@ "license": "MIT",

},
"bugs": {
"url": "https://github.com/RobinTail/express-zod-api/issues"
},
"bugs": "https://github.com/RobinTail/express-zod-api/issues",
"funding": "https://github.com/sponsors/RobinTail",
"scripts": {

@@ -21,0 +20,0 @@ "start": "tsx example/index.ts",

@@ -16,14 +16,5 @@ # Express Zod API

1. [Why and what is it for](#why-and-what-is-it-for)
1. [Overview](#overview)
2. [How it works](#how-it-works)
1. [Technologies](#technologies)
2. [Concept](#concept)
3. [Quick start](#quick-start) — Fast Track
1. [Installation](#installation)
2. [Set up config](#set-up-config)
3. [Create an endpoints factory](#create-an-endpoints-factory)
4. [Create your first endpoint](#create-your-first-endpoint)
5. [Set up routing](#set-up-routing)
6. [Create your server](#create-your-server)
7. [Try it](#try-it)
3. [Quick start](#quick-start) — **Fast Track**
4. [Basic features](#basic-features)

@@ -75,3 +66,3 @@ 1. [Middlewares](#middlewares)

# Why and what is it for
# Overview

@@ -93,4 +84,45 @@ I made this library because of the often repetitive tasks of starting a web server APIs with the need to validate input

## Contributors
These people contributed to the improvement of the library by reporting bugs, making changes and suggesting ideas:
[<img src="https://github.com/rottmann.png" alt="@rottmann" width="50px" />](https://github.com/rottmann)
[<img src="https://github.com/boarush.png" alt="@boarush" width="50px" />](https://github.com/boarush)
[<img src="https://github.com/daniel-white.png" alt="@daniel-white" width="50px" />](https://github.com/daniel-white)
[<img src="https://github.com/kotsmile.png" alt="@kotsmile" width="50px" />](https://github.com/kotsmile)
[<img src="https://github.com/arlyon.png" alt="@arlyon" width="50px" />](https://github.com/arlyon)
[<img src="https://github.com/elee1766.png" alt="@elee1766" width="50px" />](https://github.com/elee1766)
[<img src="https://github.com/danclaytondev.png" alt="@danclaytondev" width="50px" />](https://github.com/danclaytondev)
[<img src="https://github.com/huyhoang160593.png" alt="@huyhoang160593" width="50px" />](https://github.com/huyhoang160593)
[<img src="https://github.com/sarahssharkey.png" alt="@sarahssharkey" width="50px" />](https://github.com/sarahssharkey)
[<img src="https://github.com/shawncarr.png" alt="@shawncarr" width="50px" />](https://github.com/shawncarr)
[<img src="https://github.com/alindsay55661.png" alt="@alindsay55661" width="50px" />](https://github.com/alindsay55661)
[<img src="https://github.com/john-schmitz.png" alt="@john-schmitz" width="50px" />](https://github.com/john-schmitz)
[<img src="https://github.com/bobgubko.png" alt="@bobgubko" width="50px" />](https://github.com/bobgubko)
[<img src="https://github.com/miki725.png" alt="@miki725" width="50px" />](https://github.com/miki725)
[<img src="https://github.com/dev-m1-macbook.png" alt="@dev-m1-macbook" width="50px" />](https://github.com/dev-m1-macbook)
[<img src="https://github.com/McMerph.png" alt="@McMerph" width="50px" />](https://github.com/McMerph)
[<img src="https://github.com/shroudedcode.png" alt="@shroudedcode" width="50px" />](https://github.com/shroudedcode)
[<img src="https://github.com/maxcohn.png" alt="@maxcohn" width="50px" />](https://github.com/maxcohn)
[<img src="https://github.com/VideoSystemsTech.png" alt="@VideoSystemsTech" width="50px" />](https://github.com/VideoSystemsTech)
[<img src="https://github.com/TheWisestOne.png" alt="@TheWisestOne" width="50px" />](https://github.com/TheWisestOne)
[<img src="https://github.com/lazylace37.png" alt="@lazylace37" width="50px" />](https://github.com/lazylace37)
[<img src="https://github.com/leosuncin.png" alt="@leosuncin" width="50px" />](https://github.com/leosuncin)
[<img src="https://github.com/kirdk.png" alt="@kirdk" width="50px" />](https://github.com/kirdk)
[<img src="https://github.com/rayzr522.png" alt="@rayzr522" width="50px" />](https://github.com/rayzr522)
# How it works
## Concept
The API operates object schemas for input and output validation.
The object being validated is the combination of certain `request` properties.
It is available to the endpoint handler as the `input` parameter.
Middlewares have access to all `request` properties, they can provide endpoints with `options`.
The object returned by the endpoint handler is called `output`. It goes to the `ResultHandler` which is
responsible for transmitting consistent responses containing the `output` or possible error.
Much can be customized to fit your needs.
![Dataflow](https://raw.githubusercontent.com/RobinTail/express-zod-api/master/dataflow.svg)
## Technologies

@@ -109,14 +141,2 @@

## Concept
The API operates object schemas for input and output validation.
The object being validated is the combination of certain `request` properties.
It is available to the endpoint handler as the `input` parameter.
Middlewares have access to all `request` properties, they can provide endpoints with `options`.
The object returned by the endpoint handler is called `output`. It goes to the `ResultHandler` which is
responsible for transmitting consistent responses containing the `output` or possible error.
Much can be customized to fit your needs.
![Dataflow](https://raw.githubusercontent.com/RobinTail/express-zod-api/master/dataflow.svg)
# Quick start

@@ -126,16 +146,11 @@

Run one of the following commands to install the library, its peer dependencies and packages for types assistance.
Install the library, its peer dependencies and type assistance packages using your favorite
[package manager](https://nodesource.com/blog/nodejs-package-manager-comparative-guide-2024/).
```shell
yarn add express-zod-api express zod typescript http-errors
yarn add --dev @types/express @types/node @types/http-errors
# example for yarn and express 5 (recommended):
yarn add express-zod-api express@^5 zod typescript http-errors
yarn add -D @types/express@^5 @types/node @types/http-errors
```
or
```shell
npm install express-zod-api express zod typescript http-errors
npm install -D @types/express @types/node @types/http-errors
```
Ensure having the following options in your `tsconfig.json` file in order to make it work as expected:

@@ -142,0 +157,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

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc