express-zod-api 23.0.0 → 23.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## Version 23
4
4
 
5
+ ### v23.1.0
6
+
7
+ - Improved generated Documentation:
8
+ - Arrays having fixed length: `z.boolean().array().length(2)`;
9
+ - Records with non-literal keys (added `propertyNames`): `z.record(z.string().regex(/x-\w+/), z.boolean())`.
10
+
5
11
  ### v23.0.0
6
12
 
7
13
  - Minimum version of `express` (required peer dependency) is `5.1.0` (first release of v5 marked as `latest`);
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var yn=Object.create;var mt=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Sn=(e,t)=>{for(var r in t)mt(e,r,{get:t[r],enumerable:!0})},Zr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hn(t))!xn.call(e,n)&&n!==r&&mt(e,n,{get:()=>t[n],enumerable:!(o=gn(t,n))||o.enumerable});return e};var h=(e,t,r)=>(r=e!=null?yn(bn(e)):{},Zr(t||!e||!e.__esModule?mt(r,"default",{value:e,enumerable:!0}):r,e)),Rn=e=>Zr(mt({},"__esModule",{value:!0}),e);var ci={};Sn(ci,{BuiltinLogger:()=>Fe,DependsOnMethod:()=>qe,Documentation:()=>vt,DocumentationError:()=>q,EndpointsFactory:()=>ge,EventStreamFactory:()=>Ft,InputValidationError:()=>X,Integration:()=>Kt,Middleware:()=>V,MissingPeerError:()=>Ce,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>Se,ServeStatic:()=>$e,arrayEndpointsFactory:()=>Wr,arrayResultHandler:()=>At,attachRouting:()=>Zo,createConfig:()=>vr,createServer:()=>Io,defaultEndpointsFactory:()=>Jr,defaultResultHandler:()=>ye,ensureHttpError:()=>Ee,ez:()=>fn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>tn,testMiddleware:()=>rn});module.exports=Rn(ci);var D=h(require("ramda"),1),Pe=require("zod");var H=h(require("ramda"),1),Vt=require("zod");var k={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var Se=class extends Error{name="RoutingError"},q=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},lt=class extends Error{name="IOSchemaError"},ae=class extends lt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends lt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="InputValidationError"},pe=class extends Error{constructor(r,o){super(ce(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ce=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Gt=/:([A-Za-z0-9_]+)/g,ut=e=>e.match(Gt)?.map(t=>t.slice(1))||[],Tn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(k.upload);return"files"in e&&r},Jt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},On=["body","query","params"],Wt=e=>e.method.toLowerCase(),ft=(e,t={})=>{let r=Wt(e);return r==="options"?{}:(t[r]||Jt[r]||On).filter(o=>o==="files"?Tn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},de=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof Vt.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ae?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Pn=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return Re(t,(n[y]?.examples||[]).map(H.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof Vt.z.ZodObject&&(n=Pn(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},Re=(e,t,r)=>e.length&&t.length?H.xprod(e,t).map(r):e.concat(t),We=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Yt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=H.chain(o=>o.split(/[^A-Z0-9]/gi),e);return H.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Yt).join("")},yt=H.tryCatch((e,t)=>typeof e.parse(t),H.always(void 0)),Te=e=>typeof e=="object"&&e!==null,Oe=H.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var gt=h(require("ramda"),1),y=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[y]=gt.clone(t._def[y])||{examples:[]},t},Ir=(e,t)=>{if(!(y in e._def))return t;let r=Ye(t);return r._def[y].examples=Re(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?gt.mergeDeepRight({...o},{...n}):n),r};var wn=function(e){let t=Ye(this);return t._def[y].examples.push(e),t},An=function(){let e=Ye(this);return e._def[y].isDeprecated=!0,e},En=function(e){let t=Ye(this);return t._def[y].defaultLabel=e,t},zn=function(e){return new Pe.z.ZodBranded({typeName:Pe.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...D.clone(this._def[y]),brand:e}})},Zn=function(e){let t=typeof e=="function"?e:D.pipe(D.toPairs,D.map(([n,s])=>D.pair(e[String(n)]||n,s)),D.fromPairs),r=t(D.clone(this.shape)),o=Pe.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Pe.z.ZodType.prototype,{example:{get(){return wn.bind(this)}},deprecated:{get(){return An.bind(this)}},brand:{set(){},get(){return zn.bind(this)}}}),Object.defineProperty(Pe.z.ZodDefault.prototype,"label",{get(){return En.bind(this)}}),Object.defineProperty(Pe.z.ZodObject.prototype,"remap",{get(){return Zn.bind(this)}}));function vr(e){return e}var nr=require("zod");var Ue=h(require("ramda"),1),rr=require("zod");var N=require("node:assert/strict");var je=require("zod");var ht=e=>!isNaN(e.getTime());var we=Symbol("DateIn"),kr=()=>je.z.union([je.z.string().date(),je.z.string().datetime(),je.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.z.date().refine(ht)).brand(we);var Cr=require("zod");var Ae=Symbol("DateOut"),jr=()=>Cr.z.date().refine(ht).transform(e=>e.toISOString()).brand(Ae);var Qe=require("zod"),ee=Symbol("File"),Nr=Qe.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),In={buffer:()=>Nr.brand(ee),string:()=>Qe.z.string().brand(ee),binary:()=>Nr.or(Qe.z.string()).brand(ee),base64:()=>Qe.z.string().base64().brand(ee)};function bt(e){return In[e||"string"]()}var Qt=require("zod"),xt=Symbol("Form"),Lr=e=>(e instanceof Qt.z.ZodObject?e:Qt.z.object(e)).brand(xt);var Ur=require("zod");var le=Symbol("Raw"),Mr=Ur.z.object({raw:bt("buffer")});function Hr(e){return(e?Mr.extend(e):Mr).brand(le)}var Dr=require("zod"),Ne=Symbol("Upload"),Kr=()=>Dr.z.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(Ne);var Fr=(e,{next:t})=>e.options.some(t),vn=({_def:e},{next:t})=>[e.left,e.right].some(t),St=(e,{next:t})=>t(e.unwrap()),Rt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Fr,ZodDiscriminatedUnion:Fr,ZodIntersection:vn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:St,ZodNullable:St,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Xe=(e,{condition:t,rules:r=Rt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Xe(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},qr=e=>Xe(e,{condition:t=>t._def[y]?.brand===Ne,rules:{...Rt,[xt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),Tt=e=>Xe(e,{condition:t=>t._def[y]?.brand===le,maxDepth:3}),Br=e=>Xe(e,{condition:t=>t._def[y]?.brand===xt,maxDepth:3}),$r=(e,t)=>{let r=new WeakSet;return Xe(e,{maxDepth:300,rules:{...Rt,ZodBranded:St,ZodReadonly:St,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:Rt.ZodEffects}[t],ZodNaN:()=>(0,N.fail)("z.nan()"),ZodSymbol:()=>(0,N.fail)("z.symbol()"),ZodFunction:()=>(0,N.fail)("z.function()"),ZodMap:()=>(0,N.fail)("z.map()"),ZodSet:()=>(0,N.fail)("z.set()"),ZodBigInt:()=>(0,N.fail)("z.bigint()"),ZodVoid:()=>(0,N.fail)("z.void()"),ZodPromise:()=>(0,N.fail)("z.promise()"),ZodNever:()=>(0,N.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,N.fail)("z.date()"),[Ae]:()=>t==="in"&&(0,N.fail)("ez.dateOut()"),[we]:()=>t==="out"&&(0,N.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,N.fail)("ez.raw()"),[Ne]:()=>t==="out"&&(0,N.fail)("ez.upload()"),[ee]:()=>!1}})};var Ot=h(require("http-errors"),1);var et=h(require("http-errors"),1),_r=require("zod");var Xt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof _r.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new pe(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},tt=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>(0,et.isHttpError)(e)?e:(0,et.default)(e instanceof X?400:500,ce(e),{cause:e.cause||e}),ze=e=>Oe()&&!e.expose?(0,et.default)(e.statusCode).message:e.message;var Pt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ze((0,Ot.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:(0,Ot.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var er=require("zod");var tr=class{},V=class extends tr{#e;#t;#r;constructor({input:t=er.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){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 er.z.ZodError?new X(o):o}}},Le=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Me=class{nest(t){return Object.assign(t,{"":this})}};var rt=class extends Me{},wt=class e extends rt{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){return qr(this.#e.inputSchema)?"upload":Tt(this.#e.inputSchema)?"raw":Br(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=Ue.pluck("security",this.#e.middlewares||[]);return Ue.reject(Ue.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof rr.z.ZodError?new ae(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Le))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof rr.z.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){Pt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Wt(t),a={},c=null,m=null,p=ft(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};var Vr=h(require("ramda"),1),ue=require("zod");var Gr=(e,t)=>{let r=Vr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ir(s,n),o)},G=e=>e instanceof ue.z.ZodObject?e:e instanceof ue.z.ZodBranded?G(e.unwrap()):e instanceof ue.z.ZodUnion||e instanceof ue.z.ZodDiscriminatedUnion?e.options.map(t=>G(t)).reduce((t,r)=>t.merge(r.partial()),ue.z.object({})):e instanceof ue.z.ZodEffects?G(e._def.schema):e instanceof ue.z.ZodPipeline?G(e._def.in):G(e._def.left).merge(G(e._def.right));var J=require("zod");var He={positive:200,negative:400},De=Object.keys(He);var or=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends or{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Xt(this.#e,{variant:"positive",args:[t],statusCodes:[He.positive],mimeTypes:[k.json]})}getNegativeResponse(){return Xt(this.#t,{variant:"negative",args:[],statusCodes:[He.negative],mimeTypes:[k.json]})}},ye=new fe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=J.z.object({status:J.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:J.z.object({status:J.z.literal("error"),error:J.z.object({message:J.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Ee(e);return tt(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ze(a)}})}n.status(He.positive).json({status:"success",data:r})}}),At=new fe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof J.z.ZodArray?e.shape.items:J.z.array(J.z.any());return t.reduce((o,n)=>Te(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:J.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ee(r);return tt(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ze(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(He.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ge=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(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 V({handler:t})),this.resultHandler)}build({input:t=nr.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,S=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],R=typeof s=="string"?[s]:s||[];return new wt({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:R,methods:l,getOperationId:S,inputSchema:Gr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:nr.z.object({}),handler:async o=>(await t(o),{})})}},Jr=new ge(ye),Wr=new ge(At);var ro=h(require("ansis"),1),oo=require("node:util"),ir=require("node:perf_hooks");var te=require("ansis"),Yr=h(require("ramda"),1);var sr={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},Et={debug:10,info:20,warn:30,error:40},Qr=e=>Te(e)&&Object.keys(Et).some(t=>t in e),Xr=e=>e in Et,eo=(e,t)=>Et[e]<Et[t],kn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ke=Yr.memoizeWith((e,t)=>`${e}${t}`,kn),to=e=>e<1e-6?Ke("nanosecond",3).format(e/1e-6):e<.001?Ke("nanosecond").format(e/1e-6):e<1?Ke("microsecond").format(e/.001):e<1e3?Ke("millisecond").format(e):e<6e4?Ke("second",2).format(e/1e3):Ke("minute",2).format(e/6e4);var Fe=class e{config;constructor({color:t=ro.default.isSupported(),level:r=Oe()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,oo.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||eo(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?sr.ctx(s):s),m.push(c?`${sr[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.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})}get ctx(){return this.config.ctx}profile(t){let r=ir.performance.now();return()=>{let o=ir.performance.now()-r,{message:n,severity:s="debug",formatter:a=to}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Be=h(require("ramda"),1);var qe=class e extends Me{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Be.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Be.reject(Be.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var no=h(require("express"),1),$e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,no.default.static(...this.#e))}};var ot=h(require("express"),1),Ao=h(require("node:http"),1),Eo=h(require("node:https"),1);var _e=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>h(require(e))))[t]}catch{}throw new Ce(e)};var ao=h(require("http-errors"),1);var so=h(require("ramda"),1);var zt=class{constructor(t){this.logger=t}#e=so.tryCatch($r);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of De){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(k.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=ut(t);if(s.length===0)return;let{shape:a}=n||G(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var io=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new Se(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Ve=({routing:e,onEndpoint:t,onStatic:r})=>{let o=io(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof rt){let{methods:a=["get"]}=s;for(let c of a)t(s,n,c)}else if(s instanceof $e)r&&s.apply(n,r);else if(s instanceof qe)for(let[a,c,m]of s.entries){let{methods:p}=c;if(p&&!p.includes(a))throw new Se(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...io(s,n))}};var Cn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,ao.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},ar=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Oe()?void 0:new zt(t()),a=new Map;if(Ve({routing:o,onEndpoint:(m,p,l,S)=>{Oe()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.requestType]||[],R=async(b,C)=>{let w=t(b);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...S||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:b,endpoint:m,logger:w,defaultHeaders:T}):T;for(let j in Z)C.set(j,Z[j])}return m.execute({request:b,response:C,logger:w,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,R),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,R)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior!==404)for(let[m,p]of a.entries())e.all(m,Cn(p))};var go=h(require("http-errors"),1);var fo=require("node:timers/promises");var po=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",co=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",mo=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,lo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),uo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var yo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(po(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",lo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(mo(p)||co(p))&&a(p);for await(let p of(0,fo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(uo))};return{sockets:n,shutdown:()=>o??=m()}};var ho=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:de(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),bo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,go.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){Pt({response:o,logger:s,error:new pe(de(a),n)})}},jn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Nn=e=>({log:e.debug.bind(e)}),xo=async({getLogger:e,config:t})=>{let r=await _e("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Nn(l)})(c,m,p)}),o&&a.push(jn(o)),a},So=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Ro=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[y]={logger:a}),s()},To=e=>t=>t?.res?.locals[y]?.logger||e,Oo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
1
+ "use strict";var yn=Object.create;var mt=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Sn=(e,t)=>{for(var r in t)mt(e,r,{get:t[r],enumerable:!0})},Zr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hn(t))!xn.call(e,n)&&n!==r&&mt(e,n,{get:()=>t[n],enumerable:!(o=gn(t,n))||o.enumerable});return e};var h=(e,t,r)=>(r=e!=null?yn(bn(e)):{},Zr(t||!e||!e.__esModule?mt(r,"default",{value:e,enumerable:!0}):r,e)),Rn=e=>Zr(mt({},"__esModule",{value:!0}),e);var ci={};Sn(ci,{BuiltinLogger:()=>Fe,DependsOnMethod:()=>qe,Documentation:()=>vt,DocumentationError:()=>q,EndpointsFactory:()=>ge,EventStreamFactory:()=>Ft,InputValidationError:()=>X,Integration:()=>Kt,Middleware:()=>V,MissingPeerError:()=>ke,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>Se,ServeStatic:()=>$e,arrayEndpointsFactory:()=>Wr,arrayResultHandler:()=>At,attachRouting:()=>Zo,createConfig:()=>vr,createServer:()=>Io,defaultEndpointsFactory:()=>Jr,defaultResultHandler:()=>ye,ensureHttpError:()=>Ee,ez:()=>fn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>tn,testMiddleware:()=>rn});module.exports=Rn(ci);var D=h(require("ramda"),1),Pe=require("zod");var H=h(require("ramda"),1),Vt=require("zod");var C={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var Se=class extends Error{name="RoutingError"},q=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},lt=class extends Error{name="IOSchemaError"},ae=class extends lt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},X=class extends lt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="InputValidationError"},pe=class extends Error{constructor(r,o){super(ce(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},ke=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Gt=/:([A-Za-z0-9_]+)/g,ut=e=>e.match(Gt)?.map(t=>t.slice(1))||[],Tn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(C.upload);return"files"in e&&r},Jt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},On=["body","query","params"],Wt=e=>e.method.toLowerCase(),ft=(e,t={})=>{let r=Wt(e);return r==="options"?{}:(t[r]||Jt[r]||On).filter(o=>o==="files"?Tn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},de=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof Vt.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ae?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Pn=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return Re(t,(n[y]?.examples||[]).map(H.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof Vt.z.ZodObject&&(n=Pn(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},Re=(e,t,r)=>e.length&&t.length?H.xprod(e,t).map(r):e.concat(t),We=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Yt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=H.chain(o=>o.split(/[^A-Z0-9]/gi),e);return H.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Yt).join("")},yt=H.tryCatch((e,t)=>typeof e.parse(t),H.always(void 0)),Te=e=>typeof e=="object"&&e!==null,Oe=H.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var gt=h(require("ramda"),1),y=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[y]=gt.clone(t._def[y])||{examples:[]},t},Ir=(e,t)=>{if(!(y in e._def))return t;let r=Ye(t);return r._def[y].examples=Re(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?gt.mergeDeepRight({...o},{...n}):n),r};var wn=function(e){let t=Ye(this);return t._def[y].examples.push(e),t},An=function(){let e=Ye(this);return e._def[y].isDeprecated=!0,e},En=function(e){let t=Ye(this);return t._def[y].defaultLabel=e,t},zn=function(e){return new Pe.z.ZodBranded({typeName:Pe.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...D.clone(this._def[y]),brand:e}})},Zn=function(e){let t=typeof e=="function"?e:D.pipe(D.toPairs,D.map(([n,s])=>D.pair(e[String(n)]||n,s)),D.fromPairs),r=t(D.clone(this.shape)),o=Pe.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Pe.z.ZodType.prototype,{example:{get(){return wn.bind(this)}},deprecated:{get(){return An.bind(this)}},brand:{set(){},get(){return zn.bind(this)}}}),Object.defineProperty(Pe.z.ZodDefault.prototype,"label",{get(){return En.bind(this)}}),Object.defineProperty(Pe.z.ZodObject.prototype,"remap",{get(){return Zn.bind(this)}}));function vr(e){return e}var nr=require("zod");var Ue=h(require("ramda"),1),rr=require("zod");var N=require("node:assert/strict");var je=require("zod");var ht=e=>!isNaN(e.getTime());var we=Symbol("DateIn"),Cr=()=>je.z.union([je.z.string().date(),je.z.string().datetime(),je.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.z.date().refine(ht)).brand(we);var kr=require("zod");var Ae=Symbol("DateOut"),jr=()=>kr.z.date().refine(ht).transform(e=>e.toISOString()).brand(Ae);var Qe=require("zod"),ee=Symbol("File"),Nr=Qe.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),In={buffer:()=>Nr.brand(ee),string:()=>Qe.z.string().brand(ee),binary:()=>Nr.or(Qe.z.string()).brand(ee),base64:()=>Qe.z.string().base64().brand(ee)};function bt(e){return In[e||"string"]()}var Qt=require("zod"),xt=Symbol("Form"),Lr=e=>(e instanceof Qt.z.ZodObject?e:Qt.z.object(e)).brand(xt);var Ur=require("zod");var le=Symbol("Raw"),Mr=Ur.z.object({raw:bt("buffer")});function Hr(e){return(e?Mr.extend(e):Mr).brand(le)}var Dr=require("zod"),Ne=Symbol("Upload"),Kr=()=>Dr.z.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(Ne);var Fr=(e,{next:t})=>e.options.some(t),vn=({_def:e},{next:t})=>[e.left,e.right].some(t),St=(e,{next:t})=>t(e.unwrap()),Rt={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Fr,ZodDiscriminatedUnion:Fr,ZodIntersection:vn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:St,ZodNullable:St,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Xe=(e,{condition:t,rules:r=Rt,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>Xe(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},qr=e=>Xe(e,{condition:t=>t._def[y]?.brand===Ne,rules:{...Rt,[xt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),Tt=e=>Xe(e,{condition:t=>t._def[y]?.brand===le,maxDepth:3}),Br=e=>Xe(e,{condition:t=>t._def[y]?.brand===xt,maxDepth:3}),$r=(e,t)=>{let r=new WeakSet;return Xe(e,{maxDepth:300,rules:{...Rt,ZodBranded:St,ZodReadonly:St,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:Rt.ZodEffects}[t],ZodNaN:()=>(0,N.fail)("z.nan()"),ZodSymbol:()=>(0,N.fail)("z.symbol()"),ZodFunction:()=>(0,N.fail)("z.function()"),ZodMap:()=>(0,N.fail)("z.map()"),ZodSet:()=>(0,N.fail)("z.set()"),ZodBigInt:()=>(0,N.fail)("z.bigint()"),ZodVoid:()=>(0,N.fail)("z.void()"),ZodPromise:()=>(0,N.fail)("z.promise()"),ZodNever:()=>(0,N.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,N.fail)("z.date()"),[Ae]:()=>t==="in"&&(0,N.fail)("ez.dateOut()"),[we]:()=>t==="out"&&(0,N.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,N.fail)("ez.raw()"),[Ne]:()=>t==="out"&&(0,N.fail)("ez.upload()"),[ee]:()=>!1}})};var Ot=h(require("http-errors"),1);var et=h(require("http-errors"),1),_r=require("zod");var Xt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof _r.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new pe(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},tt=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>(0,et.isHttpError)(e)?e:(0,et.default)(e instanceof X?400:500,ce(e),{cause:e.cause||e}),ze=e=>Oe()&&!e.expose?(0,et.default)(e.statusCode).message:e.message;var Pt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ze((0,Ot.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:(0,Ot.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var er=require("zod");var tr=class{},V=class extends tr{#e;#t;#r;constructor({input:t=er.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){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 er.z.ZodError?new X(o):o}}},Le=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Me=class{nest(t){return Object.assign(t,{"":this})}};var rt=class extends Me{},wt=class e extends rt{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){return qr(this.#e.inputSchema)?"upload":Tt(this.#e.inputSchema)?"raw":Br(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=Ue.pluck("security",this.#e.middlewares||[]);return Ue.reject(Ue.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof rr.z.ZodError?new ae(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Le))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof rr.z.ZodError?new X(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){Pt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Wt(t),a={},c=null,m=null,p=ft(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};var Vr=h(require("ramda"),1),ue=require("zod");var Gr=(e,t)=>{let r=Vr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ir(s,n),o)},G=e=>e instanceof ue.z.ZodObject?e:e instanceof ue.z.ZodBranded?G(e.unwrap()):e instanceof ue.z.ZodUnion||e instanceof ue.z.ZodDiscriminatedUnion?e.options.map(t=>G(t)).reduce((t,r)=>t.merge(r.partial()),ue.z.object({})):e instanceof ue.z.ZodEffects?G(e._def.schema):e instanceof ue.z.ZodPipeline?G(e._def.in):G(e._def.left).merge(G(e._def.right));var J=require("zod");var He={positive:200,negative:400},De=Object.keys(He);var or=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends or{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Xt(this.#e,{variant:"positive",args:[t],statusCodes:[He.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Xt(this.#t,{variant:"negative",args:[],statusCodes:[He.negative],mimeTypes:[C.json]})}},ye=new fe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=J.z.object({status:J.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:J.z.object({status:J.z.literal("error"),error:J.z.object({message:J.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Ee(e);return tt(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ze(a)}})}n.status(He.positive).json({status:"success",data:r})}}),At=new fe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof J.z.ZodArray?e.shape.items:J.z.array(J.z.any());return t.reduce((o,n)=>Te(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:J.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ee(r);return tt(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ze(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(He.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ge=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(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 V({handler:t})),this.resultHandler)}build({input:t=nr.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,S=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],R=typeof s=="string"?[s]:s||[];return new wt({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:R,methods:l,getOperationId:S,inputSchema:Gr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:nr.z.object({}),handler:async o=>(await t(o),{})})}},Jr=new ge(ye),Wr=new ge(At);var ro=h(require("ansis"),1),oo=require("node:util"),ir=require("node:perf_hooks");var te=require("ansis"),Yr=h(require("ramda"),1);var sr={debug:te.blue,info:te.green,warn:(0,te.hex)("#FFA500"),error:te.red,ctx:te.cyanBright},Et={debug:10,info:20,warn:30,error:40},Qr=e=>Te(e)&&Object.keys(Et).some(t=>t in e),Xr=e=>e in Et,eo=(e,t)=>Et[e]<Et[t],Cn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ke=Yr.memoizeWith((e,t)=>`${e}${t}`,Cn),to=e=>e<1e-6?Ke("nanosecond",3).format(e/1e-6):e<.001?Ke("nanosecond").format(e/1e-6):e<1?Ke("microsecond").format(e/.001):e<1e3?Ke("millisecond").format(e):e<6e4?Ke("second",2).format(e/1e3):Ke("minute",2).format(e/6e4);var Fe=class e{config;constructor({color:t=ro.default.isSupported(),level:r=Oe()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,oo.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||eo(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?sr.ctx(s):s),m.push(c?`${sr[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.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})}get ctx(){return this.config.ctx}profile(t){let r=ir.performance.now();return()=>{let o=ir.performance.now()-r,{message:n,severity:s="debug",formatter:a=to}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Be=h(require("ramda"),1);var qe=class e extends Me{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Be.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Be.reject(Be.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var no=h(require("express"),1),$e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,no.default.static(...this.#e))}};var ot=h(require("express"),1),Ao=h(require("node:http"),1),Eo=h(require("node:https"),1);var _e=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>h(require(e))))[t]}catch{}throw new ke(e)};var ao=h(require("http-errors"),1);var so=h(require("ramda"),1);var zt=class{constructor(t){this.logger=t}#e=so.tryCatch($r);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of De){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(C.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=ut(t);if(s.length===0)return;let{shape:a}=n||G(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var io=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new Se(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Ve=({routing:e,onEndpoint:t,onStatic:r})=>{let o=io(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof rt){let{methods:a=["get"]}=s;for(let c of a)t(s,n,c)}else if(s instanceof $e)r&&s.apply(n,r);else if(s instanceof qe)for(let[a,c,m]of s.entries){let{methods:p}=c;if(p&&!p.includes(a))throw new Se(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...io(s,n))}};var kn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,ao.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},ar=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Oe()?void 0:new zt(t()),a=new Map;if(Ve({routing:o,onEndpoint:(m,p,l,S)=>{Oe()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.requestType]||[],R=async(b,k)=>{let w=t(b);if(r.cors){let T={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...S||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:b,endpoint:m,logger:w,defaultHeaders:T}):T;for(let j in Z)k.set(j,Z[j])}return m.execute({request:b,response:k,logger:w,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,R),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,R)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior!==404)for(let[m,p]of a.entries())e.all(m,kn(p))};var go=h(require("http-errors"),1);var fo=require("node:timers/promises");var po=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",co=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",mo=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,lo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),uo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var yo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(po(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",lo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(mo(p)||co(p))&&a(p);for await(let p of(0,fo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(uo))};return{sockets:n,shutdown:()=>o??=m()}};var ho=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:de(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),bo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,go.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){Pt({response:o,logger:s,error:new pe(de(a),n)})}},jn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Nn=e=>({log:e.debug.bind(e)}),xo=async({getLogger:e,config:t})=>{let r=await _e("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Nn(l)})(c,m,p)}),o&&a.push(jn(o)),a},So=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Ro=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[y]={logger:a}),s()},To=e=>t=>t?.res?.locals[y]?.logger||e,Oo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
3
  `).slice(1))),Po=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=yo(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var B=require("ansis"),wo=e=>{if(e.columns<132)return;let t=(0,B.italic)("Proudly supports transgender community.".padStart(109)),r=(0,B.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,B.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,B.italic)("for Sonia".padEnd(20)),s=(0,B.hex)("#F5A9B8"),a=(0,B.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(B.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill(B.gray,12,13),m=`
4
4
  8888888888 8888888888P 888 d8888 8888888b. 8888888
5
5
  888 d88P 888 d88888 888 Y88b 888
@@ -15,9 +15,9 @@ ${n}888${r}
15
15
  ${o}
16
16
  `;e.write(m.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var zo=e=>{e.startupLogo!==!1&&wo(process.stdout);let t=e.errorHandler||ye,r=Qr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v23.0.0 (CJS)",env:process.env.NODE_ENV||"development"}),Oo(r);let o=Ro({logger:r,config:e}),s={getLogger:To(r),errorHandler:t},a=bo(s),c=ho(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Zo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return ar({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Io=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=zo(e),c=(0,ot.default)().disable("x-powered-by").use(a);if(e.compression){let g=await _e("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||ot.default.json()],raw:[e.rawParser||ot.default.raw(),So],form:[e.formParser||ot.default.urlencoded()],upload:e.upload?await xo({config:e,getLogger:o}):[]};ar({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,R)=>()=>g.listen(R,()=>r.info("Listening",R)),S=[];if(e.http){let g=Ao.default.createServer(c);p.push(g),S.push(l(g,e.http.listen))}if(e.https){let g=Eo.default.createServer(e.https.options,c);p.push(g),S.push(l(g,e.https.listen))}return e.gracefulShutdown&&Po({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:S.map(g=>g())}};var Qo=require("openapi3-ts/oas31"),Xo=h(require("ramda"),1);var O=h(require("ramda"),1);var vo=e=>Te(e)&&"or"in e,ko=e=>Te(e)&&"and"in e,pr=e=>!ko(e)&&!vo(e),Co=e=>{let t=O.filter(pr,e),r=O.chain(O.prop("and"),O.filter(ko,e)),[o,n]=O.partition(pr,r),s=O.concat(t,o),a=O.filter(vo,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>Re(m,O.map(l=>pr(l)?[l]:l.and,p),([l,S])=>O.concat(l,S)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=h(require("ramda"),1),K=require("zod");var Ze=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ze(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var jo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var No=50,Mo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Mn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Un=/^\d{4}-\d{2}-\d{2}$/,Hn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Dn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Uo=e=>e.replace(Gt,t=>`{${t.slice(1)}}`),Kn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Fn=({_def:{innerType:e}},{next:t})=>t(e),qn=()=>({format:"any"}),Bn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},$n=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},_n=({options:e},{next:t})=>({oneOf:e.map(t)}),Vn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Gn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Ho={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Gn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>Re(e,t,([r,o])=>d.mergeDeepRight(r,o))},Jn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Ho)),d.isEmpty)),Wn=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Jn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Ho);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Yn=({_def:{left:e,right:t}},{next:r})=>Wn([e,t].map(r)),Qn=(e,{next:t})=>t(e.unwrap()),Xn=(e,{next:t})=>t(e.unwrap()),es=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Ko(r)),r},Do=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Lo=e=>({type:Do(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ts=({value:e})=>({type:Do(e),const:e}),rs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&We(c)?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Zt(e,r)),s.length&&(a.required=s),a},os=()=>({type:"null"}),ns=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Mo}}},ss=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Mo}}},is=({},e)=>{throw new q(`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)},as=()=>({type:"boolean"}),ps=()=>({type:"integer",format:"bigint"}),cs=e=>e.every(t=>t instanceof K.z.ZodLiteral),ds=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.z.ZodEnum||e instanceof K.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Zt(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Zt(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&cs(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Zt(K.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ms=({_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},ls=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),us=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:S,isDate:g,isTime:R,isBase64:b,isNANOID:C,isBase64url:w,isDuration:Q,_def:{checks:M}})=>{let T=M.find(v=>v.kind==="regex"),Z=M.find(v=>v.kind==="datetime"),j=M.some(v=>v.kind==="jwt"),U=M.find(v=>v.kind==="length"),P={type:"string"},_={"date-time":l,byte:b,base64url:w,date:g,time:R,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:C,jwt:j,ip:m,cidr:S,emoji:p};for(let v in _)if(_[v]){P.format=v;break}return U&&([P.minLength,P.maxLength]=[U.value,U.value]),r!==null&&(P.minLength=r),o!==null&&(P.maxLength=o),g&&(P.pattern=Un.source),R&&(P.pattern=Hn.source),l&&(P.pattern=Dn(Z?.offset).source),T&&(P.pattern=T.regex.source),P},fs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(b=>b.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(b=>b.kind==="max"),S=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,R={type:e?"integer":"number",format:e?"int64":"double"};return p?R.minimum=m:R.exclusiveMinimum=m,g?R.maximum=S:R.exclusiveMaximum=S,R},Zt=({shape:e},t)=>d.map(t,e),ys=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Mn?.[t]},Ko=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",gs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=yt(e,ys(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},hs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),bs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ss=(e,{next:t})=>t(e.unwrap().shape.raw),Fo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,qo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Rs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),Ts=(e,t)=>t?.includes(e)||e.startsWith("x-")||jo.includes(e),Bo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let S=G(r),g=ut(e),R=o.includes("query"),b=o.includes("params"),C=o.includes("headers"),w=T=>b&&g.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),M=T=>C&&(c?.(T,t,e)??Ts(T,Q));return Object.entries(S.shape).reduce((T,[Z,j])=>{let U=w(Z)?"path":M(Z)?"header":R?"query":void 0;if(!U)return T;let P=Ze(j,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),_=s==="components"?n(j,P,me(l,Z)):P,{_def:v}=j;return T.concat({name:Z,in:U,deprecated:v[y]?.isDeprecated,required:!j.isOptional(),description:P.description||l,schema:_,examples:Rs(S,Z)})},[])},cr={ZodString:us,ZodNumber:fs,ZodBigInt:ps,ZodBoolean:as,ZodNull:os,ZodArray:ms,ZodTuple:ls,ZodRecord:ds,ZodObject:rs,ZodLiteral:ts,ZodIntersection:Yn,ZodUnion:_n,ZodAny:qn,ZodDefault:Kn,ZodEnum:Lo,ZodNativeEnum:Lo,ZodEffects:gs,ZodOptional:Qn,ZodNullable:es,ZodDiscriminatedUnion:Vn,ZodBranded:bs,ZodDate:is,ZodCatch:Fn,ZodPipeline:hs,ZodLazy:xs,ZodReadonly:Xn,[ee]:$n,[Ne]:Bn,[Ae]:ss,[we]:ns,[le]:Ss},dr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof K.z.ZodLazy,a=r.type!==void 0,c=t&&We(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=Ko(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},mr=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},$o=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=$o(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},_o=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Vo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:S=`${e.toUpperCase()} ${t} ${Yt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:S};let g=_o(Ze(r,{rules:{...p,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,g,me(S)):g,examples:qo(r,!0)};return{description:S,content:d.fromPairs(d.xprod(o,[R]))}},Os=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ps=({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},ws=({name:e})=>({type:"apiKey",in:"header",name:e}),As=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Es=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),zs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Go=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Os(o):o.type==="input"?Ps(o,t):o.type==="header"?ws(o):o.type==="cookie"?As(o):o.type==="openid"?Es(o):zs(o);return e.map(o=>o.map(r))},Jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Wo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,S]=$o(Ze(r,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=_o(l),R={schema:s==="components"?n(r,g,me(p)):g,examples:qo(G(r),!1,c)},b={description:p,content:{[o]:R}};return(S||Tt(r))&&(b.required=!0),b},Yo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),lr=e=>e.length<=No?e:e.slice(0,No-1)+"\u2026",It=e=>e.length?e.slice():void 0;var vt=class extends Qo.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||me(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:S=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let b of typeof s=="string"?[s]:s)this.addServer({url:b});Ve({routing:t,onEndpoint:(b,C,w)=>{let Q={path:C,method:w,endpoint:b,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:M,shortDescription:T,scopes:Z,inputSchema:j}=b,U=T?lr(T):S&&M?lr(M):void 0,P=r.inputSources?.[w]||Jt[w],_=this.#n(C,w,b.getOperationId(w)),v=Co(b.security),be=Bo({...Q,inputSources:P,isHeader:p,security:v,schema:j,description:a?.requestParameter?.call(null,{method:w,path:C,operationId:_})}),at={};for(let ie of De){let xe=b.getResponses(ie);for(let{mimeTypes:$t,schema:ct,statusCodes:dt}of xe)for(let _t of dt)at[_t]=Vo({...Q,variant:ie,schema:ct,mimeTypes:$t,statusCode:_t,hasMultipleStatusCodes:xe.length>1||dt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:w,path:C,operationId:_,statusCode:_t})})}let qt=P.includes("body")?Wo({...Q,paramNames:Xo.pluck("name",be),schema:j,mimeType:k[b.requestType],description:a?.requestBody?.call(null,{method:w,path:C,operationId:_})}):void 0,pt=Jo(Go(v,P),Z,ie=>{let xe=this.#s(ie);return this.addSecurityScheme(xe,ie),xe}),Bt={operationId:_,summary:U,description:M,deprecated:b.isDeprecated||void 0,tags:It(b.tags),parameters:It(be),requestBody:qt,security:It(pt),responses:at};this.addPath(Uo(C),{[w]:Bt})}}),m&&(this.rootDoc.tags=Yo(m))}};var kt=require("node-mocks-http");var Zs=e=>(0,kt.createRequest)({...e,headers:{"content-type":k.json,...e?.headers}}),Is=e=>(0,kt.createResponse)(e),vs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},en=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Zs(e),s=Is({req:n,...t});s.req=t?.req||n,n.res=s;let a=vs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},tn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=en(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},rn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=ye}}=en(r),m=ft(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:de(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var dn=h(require("ramda"),1),it=h(require("typescript"),1),mn=require("zod");var pn=h(require("ramda"),1),Y=h(require("typescript"),1);var on=["get","post","put","delete","patch"];var re=h(require("ramda"),1),u=h(require("typescript"),1),i=u.default.factory,Ct=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],ks=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],nt={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},ur=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),fr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},Cs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,yr=e=>typeof e=="string"&&Cs.test(e)?i.createIdentifier(e):z(e),jt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Nt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ge=e=>Object.entries(e).map(([t,r])=>Nt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),gr=(e,t=[])=>i.createConstructorDeclaration(nt.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&re.map(f,t)):e,hr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ie=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,yr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?ur(s,a.join(" ")):s},br=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),xr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Ct,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),Sr=(e,t)=>oe(e,i.createUnionTypeNode(re.map(F,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Ct:void 0,e,n&&Pr(n),t);return o?ur(s,o):s},nn=(e,t)=>i.createPropertyDeclaration(nt.public,e,void 0,f(t),void 0),Rr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(nt.public,void 0,e,void 0,o&&Pr(o),t,n,i.createBlock(r)),Tr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Ct,e,r&&Pr(r),void 0,t),Or=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Lt=e=>f(Promise.name,[e]),Mt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Ct:void 0,e,void 0,void 0,t);return o?ur(n,o):n},Pr=e=>(Array.isArray(e)?e.map(t=>re.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ks:void 0,void 0,Array.isArray(e)?re.map(Nt,e):Ge(e),void 0,void 0,t),A=e=>e,st=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Je=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Ut=(e,t)=>f("Extract",[e,t]),wr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>i.createUnionTypeNode([f(e),Lt(e)]),Ar=(e,t)=>i.createFunctionTypeNode(void 0,Ge(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(z(e)),js=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],an=e=>js.includes(e.kind);var Ht=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Sr("Method",on);someOfType=oe("SomeOf",W("T",Or("T")),{params:["T"]});requestType=oe("Request",Or(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>Sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Mt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ie(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>L("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(yr(t),i.createArrayLiteralExpression(pn.map(z,r))))),{expose:!0});makeImplementationType=()=>oe(this.#e.implementationType,Ar({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Lt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>L(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr},i.createBlock([L(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],Y.default.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([wr(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(jt(":",[this.#e.keyParameter]),ve([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>Rr(this.#e.provideMethod,Ge({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:W(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[L(xr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Lt(W(this.interfaces.response,"K"))});makeClientClass=t=>Tr(t,[gr([Nt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:nt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>jt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,jt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),st(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(k.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),st(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=L(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=L(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=L(this.#e.searchParamsConst,st(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=L(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=L(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(k.json))),l=i.createReturnStatement(E(this.#e.responseConst,st(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return L(this.#e.defaultImplementationConst,ve([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>gr(Ge({request:"K",params:W(this.interfaces.input,"K")}),[L(xr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),L(this.#e.searchParamsConst,this.#r(this.#e.restConst)),wr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Ie(A("event"),t)]);#i=()=>Rr(this.#e.onMethod,Ge({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Ar({[this.#e.dataParameter.text]:W(Ut("R",br(this.#s("E"))),F(A("data")))},sn(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(A("event")))}});makeSubscriptionClass=t=>Tr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ut(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Ut(W(this.interfaces.positive,"K"),br(this.#s(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.#e.clientConst,Je(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Je(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),ve(["time"],i.createBlock([])))]};var I=h(require("ramda"),1),x=h(require("typescript"),1),Dt=require("zod");var{factory:$}=x.default,Ns={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Er={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Ls=({value:e})=>F(e),Ms=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&We(a)?a instanceof Dt.z.ZodOptional:a.isOptional();return Ie(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return $.createTypeLiteralNode(n)},Us=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Hs=({options:e})=>$.createUnionTypeNode(e.map(F)),cn=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(an(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},Ds=e=>Ns?.[e.kind],Ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=yt(e,Ds(o)),s={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Fs=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),qs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},Bs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),$s=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),_s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Vs=I.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(Er.name,...o))return!1;if(I.both(I.eqBy(Er.type),I.eqBy(Er.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),Gs=({_def:{left:e,right:t}},{next:r})=>Vs([e,t].map(r)),Js=({_def:e},{next:t})=>t(e.innerType),he=e=>()=>f(e),Ws=(e,{next:t})=>t(e.unwrap()),Ys=(e,{next:t})=>t(e.unwrap()),Qs=({_def:e},{next:t})=>t(e.innerType),Xs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ei=()=>F(null),ti=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ri=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof Dt.z.ZodString?r:t instanceof Dt.z.ZodUnion?n:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:he(x.default.SyntaxKind.StringKeyword),ZodNumber:he(x.default.SyntaxKind.NumberKeyword),ZodBigInt:he(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:he(x.default.SyntaxKind.BooleanKeyword),ZodAny:he(x.default.SyntaxKind.AnyKeyword),ZodUndefined:he(x.default.SyntaxKind.UndefinedKeyword),[we]:he(x.default.SyntaxKind.StringKeyword),[Ae]:he(x.default.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Us,ZodTuple:$s,ZodRecord:_s,ZodObject:Ms,ZodLiteral:Ls,ZodIntersection:Gs,ZodUnion:cn,ZodDefault:Js,ZodEnum:Hs,ZodNativeEnum:Fs,ZodEffects:Ks,ZodOptional:qs,ZodNullable:Bs,ZodDiscriminatedUnion:cn,ZodBranded:Ws,ZodCatch:Qs,ZodPipeline:Xs,ZodLazy:ti,ZodReadonly:Ys,[ee]:ri,[le]:oi},zr=(e,{brandHandling:t,ctx:r})=>Ze(e,{rules:{...t,...ni},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Kt=class extends Ht{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=F(null);this.#t.set(t,oe(o,n)),this.#t.set(t,oe(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=mn.z.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},S={brandHandling:r,ctx:{...p,isResponse:!0}};Ve({routing:t,onEndpoint:(R,b,C)=>{let w=me.bind(null,C,b),{isDeprecated:Q,inputSchema:M,tags:T}=R,Z=`${C} ${b}`,j=oe(w("input"),zr(M,l),{comment:Z});this.#e.push(j);let U=De.reduce((v,be)=>{let at=R.getResponses(be),qt=dn.chain(([Bt,{schema:ie,mimeTypes:xe,statusCodes:$t}])=>{let ct=oe(w(be,"variant",`${Bt+1}`),zr(xe?ie:m,S),{comment:Z});return this.#e.push(ct),$t.map(dt=>Ie(dt,ct.name))},Array.from(at.entries())),pt=Mt(w(be,"response","variants"),qt,{comment:Z});return this.#e.push(pt),Object.assign(v,{[be]:pt})},{});this.paths.add(b);let P=F(Z),_={input:f(j.name),positive:this.someOf(U.positive),negative:this.someOf(U.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,P),W(this.interfaces.negative,P)]),encoded:i.createIntersectionTypeNode([f(U.positive.name),f(U.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:_}),this.tags.set(Z,T)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:fr(r,t)).join(`
18
+ `))};var zo=e=>{e.startupLogo!==!1&&wo(process.stdout);let t=e.errorHandler||ye,r=Qr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v23.1.0 (CJS)",env:process.env.NODE_ENV||"development"}),Oo(r);let o=Ro({logger:r,config:e}),s={getLogger:To(r),errorHandler:t},a=bo(s),c=ho(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Zo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return ar({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Io=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=zo(e),c=(0,ot.default)().disable("x-powered-by").use(a);if(e.compression){let g=await _e("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||ot.default.json()],raw:[e.rawParser||ot.default.raw(),So],form:[e.formParser||ot.default.urlencoded()],upload:e.upload?await xo({config:e,getLogger:o}):[]};ar({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,R)=>()=>g.listen(R,()=>r.info("Listening",R)),S=[];if(e.http){let g=Ao.default.createServer(c);p.push(g),S.push(l(g,e.http.listen))}if(e.https){let g=Eo.default.createServer(e.https.options,c);p.push(g),S.push(l(g,e.https.listen))}return e.gracefulShutdown&&Po({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:S.map(g=>g())}};var Qo=require("openapi3-ts/oas31"),Xo=h(require("ramda"),1);var O=h(require("ramda"),1);var vo=e=>Te(e)&&"or"in e,Co=e=>Te(e)&&"and"in e,pr=e=>!Co(e)&&!vo(e),ko=e=>{let t=O.filter(pr,e),r=O.chain(O.prop("and"),O.filter(Co,e)),[o,n]=O.partition(pr,r),s=O.concat(t,o),a=O.filter(vo,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>Re(m,O.map(l=>pr(l)?[l]:l.and,p),([l,S])=>O.concat(l,S)),O.reject(O.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=h(require("ramda"),1),K=require("zod");var Ze=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ze(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var jo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var No=50,Mo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Mn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Un=/^\d{4}-\d{2}-\d{2}$/,Hn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Dn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Uo=e=>e.replace(Gt,t=>`{${t.slice(1)}}`),Kn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Fn=({_def:{innerType:e}},{next:t})=>t(e),qn=()=>({format:"any"}),Bn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},$n=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},_n=({options:e},{next:t})=>({oneOf:e.map(t)}),Vn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Gn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Ho={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Gn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>Re(e,t,([r,o])=>d.mergeDeepRight(r,o))},Jn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Ho)),d.isEmpty)),Wn=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(Jn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Ho);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Yn=({_def:{left:e,right:t}},{next:r})=>Wn([e,t].map(r)),Qn=(e,{next:t})=>t(e.unwrap()),Xn=(e,{next:t})=>t(e.unwrap()),es=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Ko(r)),r},Do=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Lo=e=>({type:Do(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ts=({value:e})=>({type:Do(e),const:e}),rs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&We(c)?c instanceof K.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Zt(e,r)),s.length&&(a.required=s),a},os=()=>({type:"null"}),ns=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Mo}}},ss=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Mo}}},is=({},e)=>{throw new q(`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)},as=()=>({type:"boolean"}),ps=()=>({type:"integer",format:"bigint"}),cs=e=>e.every(t=>t instanceof K.z.ZodLiteral),ds=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.z.ZodEnum||e instanceof K.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Zt(K.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.z.ZodLiteral)return{type:"object",properties:Zt(K.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.z.ZodUnion&&cs(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Zt(K.z.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},ms=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},ls=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),us=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:S,isDate:g,isTime:R,isBase64:b,isNANOID:k,isBase64url:w,isDuration:Q,_def:{checks:M}})=>{let T=M.find(v=>v.kind==="regex"),Z=M.find(v=>v.kind==="datetime"),j=M.some(v=>v.kind==="jwt"),U=M.find(v=>v.kind==="length"),P={type:"string"},_={"date-time":l,byte:b,base64url:w,date:g,time:R,duration:Q,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:k,jwt:j,ip:m,cidr:S,emoji:p};for(let v in _)if(_[v]){P.format=v;break}return U&&([P.minLength,P.maxLength]=[U.value,U.value]),r!==null&&(P.minLength=r),o!==null&&(P.maxLength=o),g&&(P.pattern=Un.source),R&&(P.pattern=Hn.source),l&&(P.pattern=Dn(Z?.offset).source),T&&(P.pattern=T.regex.source),P},fs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(b=>b.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(b=>b.kind==="max"),S=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,R={type:e?"integer":"number",format:e?"int64":"double"};return p?R.minimum=m:R.exclusiveMinimum=m,g?R.maximum=S:R.exclusiveMaximum=S,R},Zt=({shape:e},t)=>d.map(t,e),ys=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Mn?.[t]},Ko=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",gs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=yt(e,ys(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},hs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),bs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ss=(e,{next:t})=>t(e.unwrap().shape.raw),Fo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,qo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Rs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),Ts=(e,t)=>t?.includes(e)||e.startsWith("x-")||jo.includes(e),Bo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let S=G(r),g=ut(e),R=o.includes("query"),b=o.includes("params"),k=o.includes("headers"),w=T=>b&&g.includes(T),Q=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),M=T=>k&&(c?.(T,t,e)??Ts(T,Q));return Object.entries(S.shape).reduce((T,[Z,j])=>{let U=w(Z)?"path":M(Z)?"header":R?"query":void 0;if(!U)return T;let P=Ze(j,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),_=s==="components"?n(j,P,me(l,Z)):P,{_def:v}=j;return T.concat({name:Z,in:U,deprecated:v[y]?.isDeprecated,required:!j.isOptional(),description:P.description||l,schema:_,examples:Rs(S,Z)})},[])},cr={ZodString:us,ZodNumber:fs,ZodBigInt:ps,ZodBoolean:as,ZodNull:os,ZodArray:ms,ZodTuple:ls,ZodRecord:ds,ZodObject:rs,ZodLiteral:ts,ZodIntersection:Yn,ZodUnion:_n,ZodAny:qn,ZodDefault:Kn,ZodEnum:Lo,ZodNativeEnum:Lo,ZodEffects:gs,ZodOptional:Qn,ZodNullable:es,ZodDiscriminatedUnion:Vn,ZodBranded:bs,ZodDate:is,ZodCatch:Fn,ZodPipeline:hs,ZodLazy:xs,ZodReadonly:Xn,[ee]:$n,[Ne]:Bn,[Ae]:ss,[we]:ns,[le]:Ss},dr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof K.z.ZodLazy,a=r.type!==void 0,c=t&&We(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=Ko(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},mr=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},$o=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=$o(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},_o=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Vo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:S=`${e.toUpperCase()} ${t} ${Yt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:S};let g=_o(Ze(r,{rules:{...p,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,g,me(S)):g,examples:qo(r,!0)};return{description:S,content:d.fromPairs(d.xprod(o,[R]))}},Os=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Ps=({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},ws=({name:e})=>({type:"apiKey",in:"header",name:e}),As=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Es=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),zs=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Go=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Os(o):o.type==="input"?Ps(o,t):o.type==="header"?ws(o):o.type==="cookie"?As(o):o.type==="openid"?Es(o):zs(o);return e.map(o=>o.map(r))},Jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Wo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,S]=$o(Ze(r,{rules:{...a,...cr},onEach:dr,onMissing:mr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=_o(l),R={schema:s==="components"?n(r,g,me(p)):g,examples:qo(G(r),!1,c)},b={description:p,content:{[o]:R}};return(S||Tt(r))&&(b.required=!0),b},Yo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),lr=e=>e.length<=No?e:e.slice(0,No-1)+"\u2026",It=e=>e.length?e.slice():void 0;var vt=class extends Qo.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||me(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:S=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let b of typeof s=="string"?[s]:s)this.addServer({url:b});Ve({routing:t,onEndpoint:(b,k,w)=>{let Q={path:k,method:w,endpoint:b,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:M,shortDescription:T,scopes:Z,inputSchema:j}=b,U=T?lr(T):S&&M?lr(M):void 0,P=r.inputSources?.[w]||Jt[w],_=this.#n(k,w,b.getOperationId(w)),v=ko(b.security),be=Bo({...Q,inputSources:P,isHeader:p,security:v,schema:j,description:a?.requestParameter?.call(null,{method:w,path:k,operationId:_})}),at={};for(let ie of De){let xe=b.getResponses(ie);for(let{mimeTypes:$t,schema:ct,statusCodes:dt}of xe)for(let _t of dt)at[_t]=Vo({...Q,variant:ie,schema:ct,mimeTypes:$t,statusCode:_t,hasMultipleStatusCodes:xe.length>1||dt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:w,path:k,operationId:_,statusCode:_t})})}let qt=P.includes("body")?Wo({...Q,paramNames:Xo.pluck("name",be),schema:j,mimeType:C[b.requestType],description:a?.requestBody?.call(null,{method:w,path:k,operationId:_})}):void 0,pt=Jo(Go(v,P),Z,ie=>{let xe=this.#s(ie);return this.addSecurityScheme(xe,ie),xe}),Bt={operationId:_,summary:U,description:M,deprecated:b.isDeprecated||void 0,tags:It(b.tags),parameters:It(be),requestBody:qt,security:It(pt),responses:at};this.addPath(Uo(k),{[w]:Bt})}}),m&&(this.rootDoc.tags=Yo(m))}};var Ct=require("node-mocks-http");var Zs=e=>(0,Ct.createRequest)({...e,headers:{"content-type":C.json,...e?.headers}}),Is=e=>(0,Ct.createResponse)(e),vs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},en=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Zs(e),s=Is({req:n,...t});s.req=t?.req||n,n.res=s;let a=vs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},tn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=en(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},rn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=ye}}=en(r),m=ft(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:de(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var dn=h(require("ramda"),1),it=h(require("typescript"),1),mn=require("zod");var pn=h(require("ramda"),1),Y=h(require("typescript"),1);var on=["get","post","put","delete","patch"];var re=h(require("ramda"),1),u=h(require("typescript"),1),i=u.default.factory,kt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Cs=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],nt={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},ur=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),fr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},ks=/^[A-Za-z_$][A-Za-z0-9_$]*$/,yr=e=>typeof e=="string"&&ks.test(e)?i.createIdentifier(e):z(e),jt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Nt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ge=e=>Object.entries(e).map(([t,r])=>Nt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),gr=(e,t=[])=>i.createConstructorDeclaration(nt.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&re.map(f,t)):e,hr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ie=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,yr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?ur(s,a.join(" ")):s},br=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),xr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&kt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),Sr=(e,t)=>oe(e,i.createUnionTypeNode(re.map(F,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?kt:void 0,e,n&&Pr(n),t);return o?ur(s,o):s},nn=(e,t)=>i.createPropertyDeclaration(nt.public,e,void 0,f(t),void 0),Rr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(nt.public,void 0,e,void 0,o&&Pr(o),t,n,i.createBlock(r)),Tr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(kt,e,r&&Pr(r),void 0,t),Or=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Lt=e=>f(Promise.name,[e]),Mt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?kt:void 0,e,void 0,void 0,t);return o?ur(n,o):n},Pr=e=>(Array.isArray(e)?e.map(t=>re.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Cs:void 0,void 0,Array.isArray(e)?re.map(Nt,e):Ge(e),void 0,void 0,t),A=e=>e,st=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Je=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Ut=(e,t)=>f("Extract",[e,t]),wr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),W=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>i.createUnionTypeNode([f(e),Lt(e)]),Ar=(e,t)=>i.createFunctionTypeNode(void 0,Ge(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(z(e)),js=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],an=e=>js.includes(e.kind);var Ht=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Sr("Method",on);someOfType=oe("SomeOf",W("T",Or("T")),{params:["T"]});requestType=oe("Request",Or(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>Sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Mt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ie(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>L("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(yr(t),i.createArrayLiteralExpression(pn.map(z,r))))),{expose:!0});makeImplementationType=()=>oe(this.#e.implementationType,Ar({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Lt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>L(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:hr},i.createBlock([L(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],Y.default.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([wr(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(jt(":",[this.#e.keyParameter]),ve([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>Rr(this.#e.provideMethod,Ge({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:W(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[L(xr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Lt(W(this.interfaces.response,"K"))});makeClientClass=t=>Tr(t,[gr([Nt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:nt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>jt("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(URL.name,jt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),st(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(C.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),st(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=L(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=L(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=L(this.#e.searchParamsConst,st(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=L(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=L(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(C.json))),l=i.createReturnStatement(E(this.#e.responseConst,st(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return L(this.#e.defaultImplementationConst,ve([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>gr(Ge({request:"K",params:W(this.interfaces.input,"K")}),[L(xr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),L(this.#e.searchParamsConst,this.#r(this.#e.restConst)),wr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Ie(A("event"),t)]);#i=()=>Rr(this.#e.onMethod,Ge({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Ar({[this.#e.dataParameter.text]:W(Ut("R",br(this.#s("E"))),F(A("data")))},sn(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:W("R",F(A("event")))}});makeSubscriptionClass=t=>Tr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ut(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Ut(W(this.interfaces.positive,"K"),br(this.#s(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.#e.clientConst,Je(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Je(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),ve(["time"],i.createBlock([])))]};var I=h(require("ramda"),1),x=h(require("typescript"),1),Dt=require("zod");var{factory:$}=x.default,Ns={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Er={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Ls=({value:e})=>F(e),Ms=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&We(a)?a instanceof Dt.z.ZodOptional:a.isOptional();return Ie(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return $.createTypeLiteralNode(n)},Us=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Hs=({options:e})=>$.createUnionTypeNode(e.map(F)),cn=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(an(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},Ds=e=>Ns?.[e.kind],Ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=yt(e,Ds(o)),s={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Fs=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),qs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},Bs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),$s=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),_s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Vs=I.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(Er.name,...o))return!1;if(I.both(I.eqBy(Er.type),I.eqBy(Er.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),Gs=({_def:{left:e,right:t}},{next:r})=>Vs([e,t].map(r)),Js=({_def:e},{next:t})=>t(e.innerType),he=e=>()=>f(e),Ws=(e,{next:t})=>t(e.unwrap()),Ys=(e,{next:t})=>t(e.unwrap()),Qs=({_def:e},{next:t})=>t(e.innerType),Xs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ei=()=>F(null),ti=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ri=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof Dt.z.ZodString?r:t instanceof Dt.z.ZodUnion?n:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:he(x.default.SyntaxKind.StringKeyword),ZodNumber:he(x.default.SyntaxKind.NumberKeyword),ZodBigInt:he(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:he(x.default.SyntaxKind.BooleanKeyword),ZodAny:he(x.default.SyntaxKind.AnyKeyword),ZodUndefined:he(x.default.SyntaxKind.UndefinedKeyword),[we]:he(x.default.SyntaxKind.StringKeyword),[Ae]:he(x.default.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Us,ZodTuple:$s,ZodRecord:_s,ZodObject:Ms,ZodLiteral:Ls,ZodIntersection:Gs,ZodUnion:cn,ZodDefault:Js,ZodEnum:Hs,ZodNativeEnum:Fs,ZodEffects:Ks,ZodOptional:qs,ZodNullable:Bs,ZodDiscriminatedUnion:cn,ZodBranded:Ws,ZodCatch:Qs,ZodPipeline:Xs,ZodLazy:ti,ZodReadonly:Ys,[ee]:ri,[le]:oi},zr=(e,{brandHandling:t,ctx:r})=>Ze(e,{rules:{...t,...ni},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Kt=class extends Ht{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=F(null);this.#t.set(t,oe(o,n)),this.#t.set(t,oe(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=mn.z.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},S={brandHandling:r,ctx:{...p,isResponse:!0}};Ve({routing:t,onEndpoint:(R,b,k)=>{let w=me.bind(null,k,b),{isDeprecated:Q,inputSchema:M,tags:T}=R,Z=`${k} ${b}`,j=oe(w("input"),zr(M,l),{comment:Z});this.#e.push(j);let U=De.reduce((v,be)=>{let at=R.getResponses(be),qt=dn.chain(([Bt,{schema:ie,mimeTypes:xe,statusCodes:$t}])=>{let ct=oe(w(be,"variant",`${Bt+1}`),zr(xe?ie:m,S),{comment:Z});return this.#e.push(ct),$t.map(dt=>Ie(dt,ct.name))},Array.from(at.entries())),pt=Mt(w(be,"response","variants"),qt,{comment:Z});return this.#e.push(pt),Object.assign(v,{[be]:pt})},{});this.paths.add(b);let P=F(Z),_={input:f(j.name),positive:this.someOf(U.positive),negative:this.someOf(U.negative),response:i.createUnionTypeNode([W(this.interfaces.positive,P),W(this.interfaces.negative,P)]),encoded:i.createIntersectionTypeNode([f(U.positive.name),f(U.negative.name)])};this.registry.set(Z,{isDeprecated:Q,store:_}),this.tags.set(Z,T)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:fr(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&it.default.addSyntheticLeadingComment(it.default.addSyntheticLeadingComment(i.createEmptyStatement(),it.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),it.default.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>fr(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
22
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await _e("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};var ke=require("zod");var un=(e,t)=>ke.z.object({data:t,event:ke.z.literal(e),id:ke.z.string().optional(),retry:ke.z.number().int().positive().optional()}),si=(e,t,r)=>un(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),ii=1e4,ln=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":k.sse,"cache-control":"no-cache"}),ai=e=>new V({handler:async({response:t})=>setTimeout(()=>ln(t),ii)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{ln(t),t.write(si(e,r,o),"utf-8"),t.flush?.()}}}),pi=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>un(o,n));return{mimeType:k.sse,schema:r.length?ke.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ke.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ee(r);tt(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ze(a),"utf-8")}t.end()}}),Ft=class extends ge{constructor(t){super(pi(t)),this.middlewares=[ai(t)]}};var fn={dateIn:kr,dateOut:jr,form:Lr,file:bt,upload:Kr,raw:Hr};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getExamples,getMessageFromError,testEndpoint,testMiddleware});
22
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await _e("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};var Ce=require("zod");var un=(e,t)=>Ce.z.object({data:t,event:Ce.z.literal(e),id:Ce.z.string().optional(),retry:Ce.z.number().int().positive().optional()}),si=(e,t,r)=>un(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),ii=1e4,ln=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":C.sse,"cache-control":"no-cache"}),ai=e=>new V({handler:async({response:t})=>setTimeout(()=>ln(t),ii)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{ln(t),t.write(si(e,r,o),"utf-8"),t.flush?.()}}}),pi=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>un(o,n));return{mimeType:C.sse,schema:r.length?Ce.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ce.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Ee(r);tt(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ze(a),"utf-8")}t.end()}}),Ft=class extends ge{constructor(t){super(pi(t)),this.middlewares=[ai(t)]}};var fn={dateIn:Cr,dateOut:jr,form:Lr,file:bt,upload:Kr,raw:Hr};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getExamples,getMessageFromError,testEndpoint,testMiddleware});
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import*as H from"ramda";import{z as Ae}from"zod";import*as U from"ramda";import{z as br}from"zod";var v={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var we=class extends Error{name="RoutingError"},B=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},ot=class extends Error{name="IOSchemaError"},de=class extends ot{constructor(r){super(me(r),{cause:r});this.cause=r}name="OutputValidationError"},ee=class extends ot{constructor(r){super(me(r),{cause:r});this.cause=r}name="InputValidationError"},re=class extends Error{constructor(r,o){super(me(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ke=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Lt=/:([A-Za-z0-9_]+)/g,nt=e=>e.match(Lt)?.map(t=>t.slice(1))||[],Fo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(v.upload);return"files"in e&&r},Mt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},qo=["body","query","params"],Ut=e=>e.method.toLowerCase(),st=(e,t={})=>{let r=Ut(e);return r==="options"?{}:(t[r]||Mt[r]||qo).filter(o=>o==="files"?Fo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:new Error(String(e)),me=e=>e instanceof br.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof de?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Bo=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return le(t,(n[y]?.examples||[]).map(U.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof br.ZodObject&&(n=Bo(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},le=(e,t,r)=>e.length&&t.length?U.xprod(e,t).map(r):e.concat(t),Fe=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Ht=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=U.chain(o=>o.split(/[^A-Z0-9]/gi),e);return U.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Ht).join("")},it=U.tryCatch((e,t)=>typeof e.parse(t),U.always(void 0)),ue=e=>typeof e=="object"&&e!==null,fe=U.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as at from"ramda";var y=Symbol.for("express-zod-api"),qe=e=>{let t=e.describe(e.description);return t._def[y]=at.clone(t._def[y])||{examples:[]},t},xr=(e,t)=>{if(!(y in e._def))return t;let r=qe(t);return r._def[y].examples=le(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?at.mergeDeepRight({...o},{...n}):n),r};var $o=function(e){let t=qe(this);return t._def[y].examples.push(e),t},_o=function(){let e=qe(this);return e._def[y].isDeprecated=!0,e},Vo=function(e){let t=qe(this);return t._def[y].defaultLabel=e,t},Go=function(e){return new Ae.ZodBranded({typeName:Ae.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...H.clone(this._def[y]),brand:e}})},Jo=function(e){let t=typeof e=="function"?e:H.pipe(H.toPairs,H.map(([n,s])=>H.pair(e[String(n)]||n,s)),H.fromPairs),r=t(H.clone(this.shape)),o=Ae.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Ae.ZodType.prototype,{example:{get(){return $o.bind(this)}},deprecated:{get(){return _o.bind(this)}},brand:{set(){},get(){return Go.bind(this)}}}),Object.defineProperty(Ae.ZodDefault.prototype,"label",{get(){return Vo.bind(this)}}),Object.defineProperty(Ae.ZodObject.prototype,"remap",{get(){return Jo.bind(this)}}));function Wo(e){return e}import{z as Mr}from"zod";import*as ve from"ramda";import{z as jr}from"zod";import{fail as N}from"node:assert/strict";import{z as Be}from"zod";var pt=e=>!isNaN(e.getTime());var ye=Symbol("DateIn"),Sr=()=>Be.union([Be.string().date(),Be.string().datetime(),Be.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Be.date().refine(pt)).brand(ye);import{z as Yo}from"zod";var ge=Symbol("DateOut"),Rr=()=>Yo.date().refine(pt).transform(e=>e.toISOString()).brand(ge);import{z as ct}from"zod";var G=Symbol("File"),Tr=ct.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Qo={buffer:()=>Tr.brand(G),string:()=>ct.string().brand(G),binary:()=>Tr.or(ct.string()).brand(G),base64:()=>ct.string().base64().brand(G)};function dt(e){return Qo[e||"string"]()}import{z as Or}from"zod";var mt=Symbol("Form"),Pr=e=>(e instanceof Or.ZodObject?e:Or.object(e)).brand(mt);import{z as Xo}from"zod";var ie=Symbol("Raw"),wr=Xo.object({raw:dt("buffer")});function Ar(e){return(e?wr.extend(e):wr).brand(ie)}import{z as en}from"zod";var Ee=Symbol("Upload"),Er=()=>en.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(Ee);var zr=(e,{next:t})=>e.options.some(t),tn=({_def:e},{next:t})=>[e.left,e.right].some(t),lt=(e,{next:t})=>t(e.unwrap()),ut={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:zr,ZodDiscriminatedUnion:zr,ZodIntersection:tn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:lt,ZodNullable:lt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},$e=(e,{condition:t,rules:r=ut,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>$e(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Zr=e=>$e(e,{condition:t=>t._def[y]?.brand===Ee,rules:{...ut,[mt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),ft=e=>$e(e,{condition:t=>t._def[y]?.brand===ie,maxDepth:3}),Ir=e=>$e(e,{condition:t=>t._def[y]?.brand===mt,maxDepth:3}),vr=(e,t)=>{let r=new WeakSet;return $e(e,{maxDepth:300,rules:{...ut,ZodBranded:lt,ZodReadonly:lt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:ut.ZodEffects}[t],ZodNaN:()=>N("z.nan()"),ZodSymbol:()=>N("z.symbol()"),ZodFunction:()=>N("z.function()"),ZodMap:()=>N("z.map()"),ZodSet:()=>N("z.set()"),ZodBigInt:()=>N("z.bigint()"),ZodVoid:()=>N("z.void()"),ZodPromise:()=>N("z.promise()"),ZodNever:()=>N("z.never()"),ZodDate:()=>t==="in"&&N("z.date()"),[ge]:()=>t==="in"&&N("ez.dateOut()"),[ye]:()=>t==="out"&&N("ez.dateIn()"),[ie]:()=>t==="out"&&N("ez.raw()"),[Ee]:()=>t==="out"&&N("ez.upload()"),[G]:()=>!1}})};import nn,{isHttpError as sn}from"http-errors";import kr,{isHttpError as rn}from"http-errors";import{z as on}from"zod";var Dt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof on.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new re(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},_e=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),ze=e=>rn(e)?e:kr(e instanceof ee?400:500,me(e),{cause:e.cause||e}),he=e=>fe()&&!e.expose?kr(e.statusCode).message:e.message;var yt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=he(nn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:sn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Cr}from"zod";var Kt=class{},J=class extends Kt{#e;#t;#r;constructor({input:t=Cr.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){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 Cr.ZodError?new ee(o):o}}},Ze=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ie=class{nest(t){return Object.assign(t,{"":this})}};var Ve=class extends Ie{},gt=class e extends Ve{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){return Zr(this.#e.inputSchema)?"upload":ft(this.#e.inputSchema)?"raw":Ir(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ve.pluck("security",this.#e.middlewares||[]);return ve.reject(ve.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof jr.ZodError?new de(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Ze))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof jr.ZodError?new ee(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){yt({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ut(t),a={},c=null,m=null,p=st(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};import*as Nr from"ramda";import{z as be}from"zod";var Lr=(e,t)=>{let r=Nr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>xr(s,n),o)},$=e=>e instanceof be.ZodObject?e:e instanceof be.ZodBranded?$(e.unwrap()):e instanceof be.ZodUnion||e instanceof be.ZodDiscriminatedUnion?e.options.map(t=>$(t)).reduce((t,r)=>t.merge(r.partial()),be.object({})):e instanceof be.ZodEffects?$(e._def.schema):e instanceof be.ZodPipeline?$(e._def.in):$(e._def.left).merge($(e._def.right));import{z as W}from"zod";var ke={positive:200,negative:400},Ce=Object.keys(ke);var Ft=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},xe=class extends Ft{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Dt(this.#e,{variant:"positive",args:[t],statusCodes:[ke.positive],mimeTypes:[v.json]})}getNegativeResponse(){return Dt(this.#t,{variant:"negative",args:[],statusCodes:[ke.negative],mimeTypes:[v.json]})}},Se=new xe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=ze(e);return _e(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:he(a)}})}n.status(ke.positive).json({status:"success",data:r})}}),qt=new xe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>ue(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=ze(r);return _e(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(he(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(ke.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Re=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof J?t:new J(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ze(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new J({handler:t})),this.resultHandler)}build({input:t=Mr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],S=typeof s=="string"?[s]:s||[];return new gt({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:S,methods:l,getOperationId:b,inputSchema:Lr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Mr.object({}),handler:async o=>(await t(o),{})})}},an=new Re(Se),pn=new Re(qt);import yn from"ansis";import{inspect as gn}from"node:util";import{performance as qr}from"node:perf_hooks";import{blue as cn,green as dn,hex as mn,red as ln,cyanBright as un}from"ansis";import*as Ur from"ramda";var Bt={debug:cn,info:dn,warn:mn("#FFA500"),error:ln,ctx:un},ht={debug:10,info:20,warn:30,error:40},Hr=e=>ue(e)&&Object.keys(ht).some(t=>t in e),Dr=e=>e in ht,Kr=(e,t)=>ht[e]<ht[t],fn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),je=Ur.memoizeWith((e,t)=>`${e}${t}`,fn),Fr=e=>e<1e-6?je("nanosecond",3).format(e/1e-6):e<.001?je("nanosecond").format(e/1e-6):e<1?je("microsecond").format(e/.001):e<1e3?je("millisecond").format(e):e<6e4?je("second",2).format(e/1e3):je("minute",2).format(e/6e4);var Ge=class e{config;constructor({color:t=yn.isSupported(),level:r=fe()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return gn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Kr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?Bt.ctx(s):s),m.push(c?`${Bt[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.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})}get ctx(){return this.config.ctx}profile(t){let r=qr.now();return()=>{let o=qr.now()-r,{message:n,severity:s="debug",formatter:a=Fr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as Ne from"ramda";var Je=class e extends Ie{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Ne.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Ne.reject(Ne.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import hn from"express";var We=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,hn.static(...this.#e))}};import St from"express";import An from"node:http";import En from"node:https";var Le=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import bn from"http-errors";import*as Br from"ramda";var bt=class{constructor(t){this.logger=t}#e=Br.tryCatch(vr);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of Ce){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(v.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=nt(t);if(s.length===0)return;let{shape:a}=n||$(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var $r=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new we(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Me=({routing:e,onEndpoint:t,onStatic:r})=>{let o=$r(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Ve){let{methods:a=["get"]}=s;for(let c of a)t(s,n,c)}else if(s instanceof We)r&&s.apply(n,r);else if(s instanceof Je)for(let[a,c,m]of s.entries){let{methods:p}=c;if(p&&!p.includes(a))throw new we(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...$r(s,n))}};var xn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=bn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},$t=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=fe()?void 0:new bt(t()),a=new Map;if(Me({routing:o,onEndpoint:(m,p,l,b)=>{fe()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.requestType]||[],S=async(h,k)=>{let P=t(h);if(r.cors){let R={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},z=typeof r.cors=="function"?await r.cors({request:h,endpoint:m,logger:P,defaultHeaders:R}):R;for(let C in z)k.set(C,z[C])}return m.execute({request:h,response:k,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,S),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,S)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior!==404)for(let[m,p]of a.entries())e.all(m,xn(p))};import Rn from"http-errors";import{setInterval as Sn}from"node:timers/promises";var _r=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",Vr=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,Jr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Wr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Yr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(_r(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",Jr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Gr(p)||Vr(p))&&a(p);for await(let p of Sn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Wr))};return{sockets:n,shutdown:()=>o??=m()}};var Qr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:oe(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Xr=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Rn(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){yt({response:o,logger:s,error:new re(oe(a),n)})}},Tn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},On=e=>({log:e.debug.bind(e)}),eo=async({getLogger:e,config:t})=>{let r=await Le("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:On(l)})(c,m,p)}),o&&a.push(Tn(o)),a},to=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},ro=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[y]={logger:a}),s()},oo=e=>t=>t?.res?.locals[y]?.logger||e,no=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
1
+ import*as H from"ramda";import{z as Ae}from"zod";import*as U from"ramda";import{z as br}from"zod";var v={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var we=class extends Error{name="RoutingError"},B=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},ot=class extends Error{name="IOSchemaError"},de=class extends ot{constructor(r){super(me(r),{cause:r});this.cause=r}name="OutputValidationError"},ee=class extends ot{constructor(r){super(me(r),{cause:r});this.cause=r}name="InputValidationError"},re=class extends Error{constructor(r,o){super(me(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ke=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Lt=/:([A-Za-z0-9_]+)/g,nt=e=>e.match(Lt)?.map(t=>t.slice(1))||[],Fo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(v.upload);return"files"in e&&r},Mt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},qo=["body","query","params"],Ut=e=>e.method.toLowerCase(),st=(e,t={})=>{let r=Ut(e);return r==="options"?{}:(t[r]||Mt[r]||qo).filter(o=>o==="files"?Fo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:new Error(String(e)),me=e=>e instanceof br.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof de?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Bo=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return le(t,(n[y]?.examples||[]).map(U.objOf(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof br.ZodObject&&(n=Bo(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},le=(e,t,r)=>e.length&&t.length?U.xprod(e,t).map(r):e.concat(t),Fe=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Ht=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=U.chain(o=>o.split(/[^A-Z0-9]/gi),e);return U.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Ht).join("")},it=U.tryCatch((e,t)=>typeof e.parse(t),U.always(void 0)),ue=e=>typeof e=="object"&&e!==null,fe=U.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");import*as at from"ramda";var y=Symbol.for("express-zod-api"),qe=e=>{let t=e.describe(e.description);return t._def[y]=at.clone(t._def[y])||{examples:[]},t},xr=(e,t)=>{if(!(y in e._def))return t;let r=qe(t);return r._def[y].examples=le(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?at.mergeDeepRight({...o},{...n}):n),r};var $o=function(e){let t=qe(this);return t._def[y].examples.push(e),t},_o=function(){let e=qe(this);return e._def[y].isDeprecated=!0,e},Vo=function(e){let t=qe(this);return t._def[y].defaultLabel=e,t},Go=function(e){return new Ae.ZodBranded({typeName:Ae.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...H.clone(this._def[y]),brand:e}})},Jo=function(e){let t=typeof e=="function"?e:H.pipe(H.toPairs,H.map(([n,s])=>H.pair(e[String(n)]||n,s)),H.fromPairs),r=t(H.clone(this.shape)),o=Ae.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Ae.ZodType.prototype,{example:{get(){return $o.bind(this)}},deprecated:{get(){return _o.bind(this)}},brand:{set(){},get(){return Go.bind(this)}}}),Object.defineProperty(Ae.ZodDefault.prototype,"label",{get(){return Vo.bind(this)}}),Object.defineProperty(Ae.ZodObject.prototype,"remap",{get(){return Jo.bind(this)}}));function Wo(e){return e}import{z as Mr}from"zod";import*as ve from"ramda";import{z as jr}from"zod";import{fail as N}from"node:assert/strict";import{z as Be}from"zod";var pt=e=>!isNaN(e.getTime());var ye=Symbol("DateIn"),Sr=()=>Be.union([Be.string().date(),Be.string().datetime(),Be.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Be.date().refine(pt)).brand(ye);import{z as Yo}from"zod";var ge=Symbol("DateOut"),Rr=()=>Yo.date().refine(pt).transform(e=>e.toISOString()).brand(ge);import{z as ct}from"zod";var G=Symbol("File"),Tr=ct.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Qo={buffer:()=>Tr.brand(G),string:()=>ct.string().brand(G),binary:()=>Tr.or(ct.string()).brand(G),base64:()=>ct.string().base64().brand(G)};function dt(e){return Qo[e||"string"]()}import{z as Or}from"zod";var mt=Symbol("Form"),Pr=e=>(e instanceof Or.ZodObject?e:Or.object(e)).brand(mt);import{z as Xo}from"zod";var ie=Symbol("Raw"),wr=Xo.object({raw:dt("buffer")});function Ar(e){return(e?wr.extend(e):wr).brand(ie)}import{z as en}from"zod";var Ee=Symbol("Upload"),Er=()=>en.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(Ee);var zr=(e,{next:t})=>e.options.some(t),tn=({_def:e},{next:t})=>[e.left,e.right].some(t),lt=(e,{next:t})=>t(e.unwrap()),ut={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:zr,ZodDiscriminatedUnion:zr,ZodIntersection:tn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:lt,ZodNullable:lt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},$e=(e,{condition:t,rules:r=ut,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>$e(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Zr=e=>$e(e,{condition:t=>t._def[y]?.brand===Ee,rules:{...ut,[mt]:(t,{next:r})=>Object.values(t.unwrap().shape).some(r)}}),ft=e=>$e(e,{condition:t=>t._def[y]?.brand===ie,maxDepth:3}),Ir=e=>$e(e,{condition:t=>t._def[y]?.brand===mt,maxDepth:3}),vr=(e,t)=>{let r=new WeakSet;return $e(e,{maxDepth:300,rules:{...ut,ZodBranded:lt,ZodReadonly:lt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:ut.ZodEffects}[t],ZodNaN:()=>N("z.nan()"),ZodSymbol:()=>N("z.symbol()"),ZodFunction:()=>N("z.function()"),ZodMap:()=>N("z.map()"),ZodSet:()=>N("z.set()"),ZodBigInt:()=>N("z.bigint()"),ZodVoid:()=>N("z.void()"),ZodPromise:()=>N("z.promise()"),ZodNever:()=>N("z.never()"),ZodDate:()=>t==="in"&&N("z.date()"),[ge]:()=>t==="in"&&N("ez.dateOut()"),[ye]:()=>t==="out"&&N("ez.dateIn()"),[ie]:()=>t==="out"&&N("ez.raw()"),[Ee]:()=>t==="out"&&N("ez.upload()"),[G]:()=>!1}})};import nn,{isHttpError as sn}from"http-errors";import Cr,{isHttpError as rn}from"http-errors";import{z as on}from"zod";var Dt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof on.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new re(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},_e=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),ze=e=>rn(e)?e:Cr(e instanceof ee?400:500,me(e),{cause:e.cause||e}),he=e=>fe()&&!e.expose?Cr(e.statusCode).message:e.message;var yt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=he(nn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
+ Original error: ${e.handled.message}.`:""),{expose:sn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as kr}from"zod";var Kt=class{},J=class extends Kt{#e;#t;#r;constructor({input:t=kr.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){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 kr.ZodError?new ee(o):o}}},Ze=class extends J{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let m=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,m)?.catch(m)})})}};var Ie=class{nest(t){return Object.assign(t,{"":this})}};var Ve=class extends Ie{},gt=class e extends Ve{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){return Zr(this.#e.inputSchema)?"upload":ft(this.#e.inputSchema)?"raw":Ir(this.#e.inputSchema)?"form":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ve.pluck("security",this.#e.middlewares||[]);return ve.reject(ve.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof jr.ZodError?new de(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Ze))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof jr.ZodError?new ee(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){yt({...r,error:new re(oe(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ut(t),a={},c=null,m=null,p=st(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){m=oe(l)}await this.#s({input:p,output:c,request:t,response:r,error:m,logger:o,options:a})}};import*as Nr from"ramda";import{z as be}from"zod";var Lr=(e,t)=>{let r=Nr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>xr(s,n),o)},$=e=>e instanceof be.ZodObject?e:e instanceof be.ZodBranded?$(e.unwrap()):e instanceof be.ZodUnion||e instanceof be.ZodDiscriminatedUnion?e.options.map(t=>$(t)).reduce((t,r)=>t.merge(r.partial()),be.object({})):e instanceof be.ZodEffects?$(e._def.schema):e instanceof be.ZodPipeline?$(e._def.in):$(e._def.left).merge($(e._def.right));import{z as W}from"zod";var Ce={positive:200,negative:400},ke=Object.keys(Ce);var Ft=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},xe=class extends Ft{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Dt(this.#e,{variant:"positive",args:[t],statusCodes:[Ce.positive],mimeTypes:[v.json]})}getNegativeResponse(){return Dt(this.#t,{variant:"negative",args:[],statusCodes:[Ce.negative],mimeTypes:[v.json]})}},Se=new xe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=W.object({status:W.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:W.object({status:W.literal("error"),error:W.object({message:W.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=ze(e);return _e(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:he(a)}})}n.status(Ce.positive).json({status:"success",data:r})}}),qt=new xe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof W.ZodArray?e.shape.items:W.array(W.any());return t.reduce((o,n)=>ue(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:W.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=ze(r);return _e(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(he(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Ce.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Re=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof J?t:new J(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ze(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new J({handler:t})),this.resultHandler)}build({input:t=Mr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:m,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,g=typeof n=="string"?[n]:n||[],S=typeof s=="string"?[s]:s||[];return new gt({...c,middlewares:m,outputSchema:r,resultHandler:p,scopes:g,tags:S,methods:l,getOperationId:b,inputSchema:Lr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Mr.object({}),handler:async o=>(await t(o),{})})}},an=new Re(Se),pn=new Re(qt);import yn from"ansis";import{inspect as gn}from"node:util";import{performance as qr}from"node:perf_hooks";import{blue as cn,green as dn,hex as mn,red as ln,cyanBright as un}from"ansis";import*as Ur from"ramda";var Bt={debug:cn,info:dn,warn:mn("#FFA500"),error:ln,ctx:un},ht={debug:10,info:20,warn:30,error:40},Hr=e=>ue(e)&&Object.keys(ht).some(t=>t in e),Dr=e=>e in ht,Kr=(e,t)=>ht[e]<ht[t],fn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),je=Ur.memoizeWith((e,t)=>`${e}${t}`,fn),Fr=e=>e<1e-6?je("nanosecond",3).format(e/1e-6):e<.001?je("nanosecond").format(e/1e-6):e<1?je("microsecond").format(e/.001):e<1e3?je("millisecond").format(e):e<6e4?je("second",2).format(e/1e3):je("minute",2).format(e/6e4);var Ge=class e{config;constructor({color:t=yn.isSupported(),level:r=fe()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return gn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Kr(t,n))return;let m=[new Date().toISOString()];s&&m.push(c?Bt.ctx(s):s),m.push(c?`${Bt[t](t)}:`:`${t}:`,r),o!==void 0&&m.push(this.format(o)),Object.keys(a).length>0&&m.push(this.format(a)),console.log(m.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})}get ctx(){return this.config.ctx}profile(t){let r=qr.now();return()=>{let o=qr.now()-r,{message:n,severity:s="debug",formatter:a=Fr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import*as Ne from"ramda";var Je=class e extends Ie{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Ne.keys(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,Ne.reject(Ne.equals(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import hn from"express";var We=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,hn.static(...this.#e))}};import St from"express";import An from"node:http";import En from"node:https";var Le=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import bn from"http-errors";import*as Br from"ramda";var bt=class{constructor(t){this.logger=t}#e=Br.tryCatch(vr);#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.requestType==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.inputSchema,"in");for(let o of ke){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(v.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=nt(t);if(s.length===0)return;let{shape:a}=n||$(r.inputSchema);for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var $r=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new we(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Me=({routing:e,onEndpoint:t,onStatic:r})=>{let o=$r(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Ve){let{methods:a=["get"]}=s;for(let c of a)t(s,n,c)}else if(s instanceof We)r&&s.apply(n,r);else if(s instanceof Je)for(let[a,c,m]of s.entries){let{methods:p}=c;if(p&&!p.includes(a))throw new we(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,m)}else o.unshift(...$r(s,n))}};var xn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=bn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},$t=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=fe()?void 0:new bt(t()),a=new Map;if(Me({routing:o,onEndpoint:(m,p,l,b)=>{fe()||(s?.checkJsonCompat(m,{path:p,method:l}),s?.checkPathParams(p,m,{method:l}));let g=n?.[m.requestType]||[],S=async(h,C)=>{let P=t(h);if(r.cors){let R={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},z=typeof r.cors=="function"?await r.cors({request:h,endpoint:m,logger:P,defaultHeaders:R}):R;for(let k in z)C.set(k,z[k])}return m.execute({request:h,response:C,logger:P,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...g,S),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...g,S)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior!==404)for(let[m,p]of a.entries())e.all(m,xn(p))};import Rn from"http-errors";import{setInterval as Sn}from"node:timers/promises";var _r=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",Vr=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,Jr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Wr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Yr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(_r(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let m=async()=>{for(let p of e)p.on("request",Jr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Gr(p)||Vr(p))&&a(p);for await(let p of Sn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Wr))};return{sockets:n,shutdown:()=>o??=m()}};var Qr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:oe(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Xr=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Rn(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){yt({response:o,logger:s,error:new re(oe(a),n)})}},Tn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},On=e=>({log:e.debug.bind(e)}),eo=async({getLogger:e,config:t})=>{let r=await Le("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,m,p)=>{let l=e(c);return await n?.({request:c,logger:l}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:On(l)})(c,m,p)}),o&&a.push(Tn(o)),a},to=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},ro=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let a=await t?.({request:o,parent:e})||e;r?.(o,a),o.res&&(o.res.locals[y]={logger:a}),s()},oo=e=>t=>t?.res?.locals[y]?.logger||e,no=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
3
  `).slice(1))),so=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Yr(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as Pn,hex as io,italic as xt,whiteBright as wn}from"ansis";var ao=e=>{if(e.columns<132)return;let t=xt("Proudly supports transgender community.".padStart(109)),r=xt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=xt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=xt("for Sonia".padEnd(20)),s=io("#F5A9B8"),a=io("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(wn,5,7).fill(s,7,9).fill(a,9,12).fill(Pn,12,13),m=`
4
4
  8888888888 8888888888P 888 d8888 8888888b. 8888888
5
5
  888 d88P 888 d88888 888 Y88b 888
@@ -15,7 +15,7 @@ ${n}888${r}
15
15
  ${o}
16
16
  `;e.write(m.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var po=e=>{e.startupLogo!==!1&&ao(process.stdout);let t=e.errorHandler||Se,r=Hr(e.logger)?e.logger:new Ge(e.logger);r.debug("Running",{build:"v23.0.0 (ESM)",env:process.env.NODE_ENV||"development"}),no(r);let o=ro({logger:r,config:e}),s={getLogger:oo(r),errorHandler:t},a=Xr(s),c=Qr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=po(e);return $t({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Zn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=po(e),c=St().disable("x-powered-by").use(a);if(e.compression){let g=await Le("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||St.json()],raw:[e.rawParser||St.raw(),to],form:[e.formParser||St.urlencoded()],upload:e.upload?await eo({config:e,getLogger:o}):[]};$t({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,S)=>()=>g.listen(S,()=>r.info("Listening",S)),b=[];if(e.http){let g=An.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=En.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&so({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};import{OpenApiBuilder as Os}from"openapi3-ts/oas31";import*as vo from"ramda";import*as T from"ramda";var co=e=>ue(e)&&"or"in e,mo=e=>ue(e)&&"and"in e,_t=e=>!mo(e)&&!co(e),lo=e=>{let t=T.filter(_t,e),r=T.chain(T.prop("and"),T.filter(mo,e)),[o,n]=T.partition(_t,r),s=T.concat(t,o),a=T.filter(co,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((m,p)=>le(m,T.map(l=>_t(l)?[l]:l.and,p),([l,b])=>T.concat(l,b)),T.reject(T.isEmpty,[s]))};import{isReferenceObject as Vt,isSchemaObject as Tt}from"openapi3-ts/oas31";import*as d from"ramda";import{z as K}from"zod";var Te=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Te(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var uo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var fo=50,go="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",vn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},kn=/^\d{4}-\d{2}-\d{2}$/,Cn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,jn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,ho=e=>e.replace(Lt,t=>`{${t.slice(1)}}`),Nn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Ln=({_def:{innerType:e}},{next:t})=>t(e),Mn=()=>({format:"any"}),Un=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Dn=({options:e},{next:t})=>({oneOf:e.map(t)}),Kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Fn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},bo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Fn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>le(e,t,([r,o])=>d.mergeDeepRight(r,o))},qn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(bo)),d.isEmpty)),Bn=d.tryCatch(e=>{let[t,r]=e.filter(Tt).filter(qn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,bo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),$n=({_def:{left:e,right:t}},{next:r})=>Bn([e,t].map(r)),_n=(e,{next:t})=>t(e.unwrap()),Vn=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>{let r=t(e.unwrap());return Tt(r)&&(r.type=So(r)),r},xo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},yo=e=>({type:xo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Jn=({value:e})=>({type:xo(e),const:e}),Wn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Fe(c)?c instanceof K.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Rt(e,r)),s.length&&(a.required=s),a},Yn=()=>({type:"null"}),Qn=({},e)=>{if(e.isResponse)throw new B("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:go}}},Xn=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:go}}},es=({},e)=>{throw new B(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},ts=()=>({type:"boolean"}),rs=()=>({type:"integer",format:"bigint"}),os=e=>e.every(t=>t instanceof K.ZodLiteral),ns=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.ZodEnum||e instanceof K.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Rt(K.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.ZodLiteral)return{type:"object",properties:Rt(K.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.ZodUnion&&os(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Rt(K.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ss=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},is=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),as=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:g,isTime:S,isBase64:h,isNANOID:k,isBase64url:P,isDuration:V,_def:{checks:L}})=>{let R=L.find(I=>I.kind==="regex"),z=L.find(I=>I.kind==="datetime"),C=L.some(I=>I.kind==="jwt"),M=L.find(I=>I.kind==="length"),O={type:"string"},q={"date-time":l,byte:h,base64url:P,date:g,time:S,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:k,jwt:C,ip:m,cidr:b,emoji:p};for(let I in q)if(q[I]){O.format=I;break}return M&&([O.minLength,O.maxLength]=[M.value,M.value]),r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),g&&(O.pattern=kn.source),S&&(O.pattern=Cn.source),l&&(O.pattern=jn(z?.offset).source),R&&(O.pattern=R.regex.source),O},ps=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(h=>h.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(h=>h.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,S={type:e?"integer":"number",format:e?"int64":"double"};return p?S.minimum=m:S.exclusiveMinimum=m,g?S.maximum=b:S.exclusiveMaximum=b,S},Rt=({shape:e},t)=>d.map(t,e),cs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return vn?.[t]},So=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ds=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&Tt(o)){let s=it(e,cs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.any())}if(!t&&n.type==="preprocess"&&Tt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ms=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ls=(e,{next:t})=>t(e.unwrap()),us=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),fs=(e,{next:t})=>t(e.unwrap().shape.raw),Ro=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,To=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Ro)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ys=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Ro)({schema:e,variant:"original",validate:!0,pullProps:!0}),gs=(e,t)=>t?.includes(e)||e.startsWith("x-")||uo.includes(e),Oo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=$(r),g=nt(e),S=o.includes("query"),h=o.includes("params"),k=o.includes("headers"),P=R=>h&&g.includes(R),V=d.chain(d.filter(R=>R.type==="header"),m??[]).map(({name:R})=>R),L=R=>k&&(c?.(R,t,e)??gs(R,V));return Object.entries(b.shape).reduce((R,[z,C])=>{let M=P(z)?"path":L(z)?"header":S?"query":void 0;if(!M)return R;let O=Te(C,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(C,O,se(l,z)):O,{_def:I}=C;return R.concat({name:z,in:M,deprecated:I[y]?.isDeprecated,required:!C.isOptional(),description:O.description||l,schema:q,examples:ys(b,z)})},[])},Gt={ZodString:as,ZodNumber:ps,ZodBigInt:rs,ZodBoolean:ts,ZodNull:Yn,ZodArray:ss,ZodTuple:is,ZodRecord:ns,ZodObject:Wn,ZodLiteral:Jn,ZodIntersection:$n,ZodUnion:Dn,ZodAny:Mn,ZodDefault:Nn,ZodEnum:yo,ZodNativeEnum:yo,ZodEffects:ds,ZodOptional:_n,ZodNullable:Gn,ZodDiscriminatedUnion:Kn,ZodBranded:ls,ZodDate:es,ZodCatch:Ln,ZodPipeline:ms,ZodLazy:us,ZodReadonly:Vn,[G]:Hn,[Ee]:Un,[ge]:Xn,[ye]:Qn,[ie]:fs},Jt=(e,{isResponse:t,prev:r})=>{if(Vt(r))return{};let{description:o,_def:n}=e,s=e instanceof K.ZodLazy,a=r.type!==void 0,c=t&&Fe(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=So(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},Wt=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Po=(e,t)=>{if(Vt(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Po(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},wo=e=>Vt(e)?e:d.omit(["examples"],e),Ao=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Ht(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=wo(Te(r,{rules:{...p,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),S={schema:a==="components"?s(r,g,se(b)):g,examples:To(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[S]))}},hs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},bs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},xs=({name:e})=>({type:"apiKey",in:"header",name:e}),Ss=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Rs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ts=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Eo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?hs(o):o.type==="input"?bs(o,t):o.type==="header"?xs(o):o.type==="cookie"?Ss(o):o.type==="openid"?Rs(o):Ts(o);return e.map(o=>o.map(r))},zo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Zo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=Po(Te(r,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=wo(l),S={schema:s==="components"?n(r,g,se(p)):g,examples:To($(r),!1,c)},h={description:p,content:{[o]:S}};return(b||ft(r))&&(h.required=!0),h},Io=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Yt=e=>e.length<=fo?e:e.slice(0,fo-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Qt=class extends Os{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||se(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new B(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});Me({routing:t,onEndpoint:(h,k,P)=>{let V={path:k,method:P,endpoint:h,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:L,shortDescription:R,scopes:z,inputSchema:C}=h,M=R?Yt(R):b&&L?Yt(L):void 0,O=r.inputSources?.[P]||Mt[P],q=this.#n(k,P,h.getOperationId(P)),I=lo(h.security),pe=Oo({...V,inputSources:O,isHeader:p,security:I,schema:C,description:a?.requestParameter?.call(null,{method:P,path:k,operationId:q})}),Xe={};for(let te of Ce){let ce=h.getResponses(te);for(let{mimeTypes:jt,schema:tt,statusCodes:rt}of ce)for(let Nt of rt)Xe[Nt]=Ao({...V,variant:te,schema:tt,mimeTypes:jt,statusCode:Nt,hasMultipleStatusCodes:ce.length>1||rt.length>1,description:a?.[`${te}Response`]?.call(null,{method:P,path:k,operationId:q,statusCode:Nt})})}let kt=O.includes("body")?Zo({...V,paramNames:vo.pluck("name",pe),schema:C,mimeType:v[h.requestType],description:a?.requestBody?.call(null,{method:P,path:k,operationId:q})}):void 0,et=zo(Eo(I,O),z,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),Ct={operationId:q,summary:M,description:L,deprecated:h.isDeprecated||void 0,tags:Ot(h.tags),parameters:Ot(pe),requestBody:kt,security:Ot(et),responses:Xe};this.addPath(ho(k),{[P]:Ct})}}),m&&(this.rootDoc.tags=Io(m))}};import{createRequest as Ps,createResponse as ws}from"node-mocks-http";var As=e=>Ps({...e,headers:{"content-type":v.json,...e?.headers}}),Es=e=>ws(e),zs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},ko=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),s=Es({req:n,...t});s.req=t?.req||n,n.res=s;let a=zs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=ko(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Is=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Se}}=ko(r),m=st(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import vt from"typescript";import{z as ni}from"zod";import*as Mo from"ramda";import X from"typescript";var Co=["get","post","put","delete","patch"];import*as Y from"ramda";import u from"typescript";var i=u.factory,Pt=[i.createModifier(u.SyntaxKind.ExportKeyword)],vs=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Ye={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Xt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),er=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},ks=/^[A-Za-z_$][A-Za-z0-9_$]*$/,tr=e=>typeof e=="string"&&ks.test(e)?i.createIdentifier(e):E(e),wt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),At=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ue=e=>Object.entries(e).map(([t,r])=>At(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),rr=(e,t=[])=>i.createConstructorDeclaration(Ye.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,or=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,tr(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Xt(s,a.join(" ")):s},nr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),sr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Pt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),ir=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(D,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Pt:void 0,e,n&&dr(n),t);return o?Xt(s,o):s},jo=(e,t)=>i.createPropertyDeclaration(Ye.public,e,void 0,f(t),void 0),ar=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ye.public,void 0,e,void 0,o&&dr(o),t,n,i.createBlock(r)),pr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Pt,e,r&&dr(r),void 0,t),cr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Et=e=>f(Promise.name,[e]),zt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Pt:void 0,e,void 0,void 0,t);return o?Xt(n,o):n},dr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Pe=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?vs:void 0,void 0,Array.isArray(e)?Y.map(At,e):Ue(e),void 0,void 0,t),w=e=>e,Qe=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),A=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),He=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Zt=(e,t)=>f("Extract",[e,t]),mr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),No=e=>i.createUnionTypeNode([f(e),Et(e)]),lr=(e,t)=>i.createFunctionTypeNode(void 0,Ue(e),f(t)),E=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),D=e=>i.createLiteralTypeNode(E(e)),Cs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Lo=e=>Cs.includes(e.kind);var It=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=ir("Method",Co);someOfType=Q("SomeOf",_("T",cr("T")),{params:["T"]});requestType=Q("Request",cr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>ir(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>zt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(tr(t),i.createArrayLiteralExpression(Mo.map(E,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,lr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Et(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Pe({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(A(this.#e.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,Pe({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([mr(this.#e.pathParameter,A(this.#e.pathParameter,w("replace"))(wt(":",[this.#e.keyParameter]),Pe([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ar(this.#e.provideMethod,Ue({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:_(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(sr(this.#e.methodParameter,this.#e.pathParameter),A(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(A(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(A(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Et(_(this.interfaces.response,"K"))});makeClientClass=t=>pr(t,[rr([At(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ye.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>wt("?",[He(URLSearchParams.name,t)]);#o=()=>He(URL.name,wt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.#e.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),Qe(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(v.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(w("body"),Qe(this.#e.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(A(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,Qe(this.#e.hasBodyConst,E(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,A(this.#e.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,A(this.#e.contentTypeConst,w("startsWith"))(E(v.json))),l=i.createReturnStatement(A(this.#e.responseConst,Qe(this.#e.isJsonConst,E(w("json")),E(w("text"))))());return j(this.#e.defaultImplementationConst,Pe([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>rr(Ue({request:"K",params:_(this.interfaces.input,"K")}),[j(sr(this.#e.pathParameter,this.#e.restConst),A(this.#e.substituteFn)(i.createElementAccessExpression(A(this.#e.parseRequestFn)(this.#e.requestParameter),E(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),mr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),He("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Oe(w("event"),t)]);#i=()=>ar(this.#e.onMethod,Ue({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:lr({[this.#e.dataParameter.text]:_(Zt("R",nr(this.#s("E"))),D(w("data")))},No(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.#e.sourceProp,w("addEventListener"))(this.#e.eventParameter,Pe([this.#e.msgParameter],A(this.#e.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",D(w("event")))}});makeSubscriptionClass=t=>pr(t,[jo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Zt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Zt(_(this.interfaces.positive,"K"),nr(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,He(t)),A(this.#e.clientConst,this.#e.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(He(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(E("time"),Pe(["time"],i.createBlock([])))]};import*as Z from"ramda";import x from"typescript";import{z as fr}from"zod";var{factory:F}=x,js={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},ur={name:Z.path(["name","text"]),type:Z.path(["type"]),optional:Z.path(["questionToken"])},Ns=({value:e})=>D(e),Ls=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&Fe(a)?a instanceof fr.ZodOptional:a.isOptional();return Oe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return F.createTypeLiteralNode(n)},Ms=({element:e},{next:t})=>F.createArrayTypeNode(t(e)),Us=({options:e})=>F.createUnionTypeNode(e.map(D)),Uo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Lo(n)?n.kind:n,n)}return F.createUnionTypeNode(Array.from(r.values()))},Hs=e=>js?.[e.kind],Ds=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=it(e,Hs(o)),s={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.SyntaxKind.AnyKeyword)}return o},Ks=e=>F.createUnionTypeNode(Object.values(e.enum).map(D)),Fs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?F.createUnionTypeNode([o,f(x.SyntaxKind.UndefinedKeyword)]):o},qs=(e,{next:t})=>F.createUnionTypeNode([t(e.unwrap()),D(null)]),Bs=({items:e,_def:{rest:t}},{next:r})=>F.createTupleTypeNode(e.map(r).concat(t===null?[]:F.createRestTypeNode(r(t)))),$s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),_s=Z.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=Z.chain(Z.prop("members"),e),r=Z.uniqWith((...o)=>{if(!Z.eqBy(ur.name,...o))return!1;if(Z.both(Z.eqBy(ur.type),Z.eqBy(ur.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return F.createTypeLiteralNode(r)},(e,t)=>F.createIntersectionTypeNode(t)),Vs=({_def:{left:e,right:t}},{next:r})=>_s([e,t].map(r)),Gs=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),Js=(e,{next:t})=>t(e.unwrap()),Ws=(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"]),Xs=()=>D(null),ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ti=e=>{let t=e.unwrap(),r=f(x.SyntaxKind.StringKeyword),o=f("Buffer"),n=F.createUnionTypeNode([r,o]);return t instanceof fr.ZodString?r:t instanceof fr.ZodUnion?n:o},ri=(e,{next:t})=>t(e.unwrap().shape.raw),oi={ZodString:ae(x.SyntaxKind.StringKeyword),ZodNumber:ae(x.SyntaxKind.NumberKeyword),ZodBigInt:ae(x.SyntaxKind.BigIntKeyword),ZodBoolean:ae(x.SyntaxKind.BooleanKeyword),ZodAny:ae(x.SyntaxKind.AnyKeyword),ZodUndefined:ae(x.SyntaxKind.UndefinedKeyword),[ye]:ae(x.SyntaxKind.StringKeyword),[ge]:ae(x.SyntaxKind.StringKeyword),ZodNull:Xs,ZodArray:Ms,ZodTuple:Bs,ZodRecord:$s,ZodObject:Ls,ZodLiteral:Ns,ZodIntersection:Vs,ZodUnion:Uo,ZodDefault:Gs,ZodEnum:Us,ZodNativeEnum:Ks,ZodEffects:Ds,ZodOptional:Fs,ZodNullable:qs,ZodDiscriminatedUnion:Uo,ZodBranded:Js,ZodCatch:Ys,ZodPipeline:Qs,ZodLazy:ei,ZodReadonly:Ws,[G]:ti,[ie]:ri},yr=(e,{brandHandling:t,ctx:r})=>Te(e,{rules:{...t,...oi},onMissing:()=>f(x.SyntaxKind.AnyKeyword),ctx:r});var gr=class extends It{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=D(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=ni.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};Me({routing:t,onEndpoint:(S,h,k)=>{let P=se.bind(null,k,h),{isDeprecated:V,inputSchema:L,tags:R}=S,z=`${k} ${h}`,C=Q(P("input"),yr(L,l),{comment:z});this.#e.push(C);let M=Ce.reduce((I,pe)=>{let Xe=S.getResponses(pe),kt=Ho.chain(([Ct,{schema:te,mimeTypes:ce,statusCodes:jt}])=>{let tt=Q(P(pe,"variant",`${Ct+1}`),yr(ce?te:m,b),{comment:z});return this.#e.push(tt),jt.map(rt=>Oe(rt,tt.name))},Array.from(Xe.entries())),et=zt(P(pe,"response","variants"),kt,{comment:z});return this.#e.push(et),Object.assign(I,{[pe]:et})},{});this.paths.add(h);let O=D(z),q={input:f(C.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,O),_(this.interfaces.negative,O)]),encoded:i.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(z,{isDeprecated:V,store:q}),this.tags.set(z,R)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:er(r,t)).join(`
18
+ `))};var po=e=>{e.startupLogo!==!1&&ao(process.stdout);let t=e.errorHandler||Se,r=Hr(e.logger)?e.logger:new Ge(e.logger);r.debug("Running",{build:"v23.1.0 (ESM)",env:process.env.NODE_ENV||"development"}),no(r);let o=ro({logger:r,config:e}),s={getLogger:oo(r),errorHandler:t},a=Xr(s),c=Qr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=po(e);return $t({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Zn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=po(e),c=St().disable("x-powered-by").use(a);if(e.compression){let g=await Le("compression");c.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||St.json()],raw:[e.rawParser||St.raw(),to],form:[e.formParser||St.urlencoded()],upload:e.upload?await eo({config:e,getLogger:o}):[]};$t({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(g,S)=>()=>g.listen(S,()=>r.info("Listening",S)),b=[];if(e.http){let g=An.createServer(c);p.push(g),b.push(l(g,e.http.listen))}if(e.https){let g=En.createServer(e.https.options,c);p.push(g),b.push(l(g,e.https.listen))}return e.gracefulShutdown&&so({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(g=>g())}};import{OpenApiBuilder as Os}from"openapi3-ts/oas31";import*as vo from"ramda";import*as T from"ramda";var co=e=>ue(e)&&"or"in e,mo=e=>ue(e)&&"and"in e,_t=e=>!mo(e)&&!co(e),lo=e=>{let t=T.filter(_t,e),r=T.chain(T.prop("and"),T.filter(mo,e)),[o,n]=T.partition(_t,r),s=T.concat(t,o),a=T.filter(co,e);return T.map(T.prop("or"),T.concat(a,n)).reduce((m,p)=>le(m,T.map(l=>_t(l)?[l]:l.and,p),([l,b])=>T.concat(l,b)),T.reject(T.isEmpty,[s]))};import{isReferenceObject as Vt,isSchemaObject as Tt}from"openapi3-ts/oas31";import*as d from"ramda";import{z as K}from"zod";var Te=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Te(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var uo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var fo=50,go="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",vn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Cn=/^\d{4}-\d{2}-\d{2}$/,kn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,jn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,ho=e=>e.replace(Lt,t=>`{${t.slice(1)}}`),Nn=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),Ln=({_def:{innerType:e}},{next:t})=>t(e),Mn=()=>({format:"any"}),Un=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof K.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Dn=({options:e},{next:t})=>({oneOf:e.map(t)}),Kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Fn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},bo={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Fn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>le(e,t,([r,o])=>d.mergeDeepRight(r,o))},qn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(bo)),d.isEmpty)),Bn=d.tryCatch(e=>{let[t,r]=e.filter(Tt).filter(qn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,bo);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),$n=({_def:{left:e,right:t}},{next:r})=>Bn([e,t].map(r)),_n=(e,{next:t})=>t(e.unwrap()),Vn=(e,{next:t})=>t(e.unwrap()),Gn=(e,{next:t})=>{let r=t(e.unwrap());return Tt(r)&&(r.type=So(r)),r},xo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},yo=e=>({type:xo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Jn=({value:e})=>({type:xo(e),const:e}),Wn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Fe(c)?c instanceof K.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Rt(e,r)),s.length&&(a.required=s),a},Yn=()=>({type:"null"}),Qn=({},e)=>{if(e.isResponse)throw new B("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:go}}},Xn=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:go}}},es=({},e)=>{throw new B(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},ts=()=>({type:"boolean"}),rs=()=>({type:"integer",format:"bigint"}),os=e=>e.every(t=>t instanceof K.ZodLiteral),ns=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof K.ZodEnum||e instanceof K.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Rt(K.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof K.ZodLiteral)return{type:"object",properties:Rt(K.object({[e.value]:t}),r),required:[e.value]};if(e instanceof K.ZodUnion&&os(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:Rt(K.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},ss=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},is=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),as=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:b,isDate:g,isTime:S,isBase64:h,isNANOID:C,isBase64url:P,isDuration:V,_def:{checks:L}})=>{let R=L.find(I=>I.kind==="regex"),z=L.find(I=>I.kind==="datetime"),k=L.some(I=>I.kind==="jwt"),M=L.find(I=>I.kind==="length"),O={type:"string"},q={"date-time":l,byte:h,base64url:P,date:g,time:S,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:C,jwt:k,ip:m,cidr:b,emoji:p};for(let I in q)if(q[I]){O.format=I;break}return M&&([O.minLength,O.maxLength]=[M.value,M.value]),r!==null&&(O.minLength=r),o!==null&&(O.maxLength=o),g&&(O.pattern=Cn.source),S&&(O.pattern=kn.source),l&&(O.pattern=jn(z?.offset).source),R&&(O.pattern=R.regex.source),O},ps=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(h=>h.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(h=>h.kind==="max"),b=t===null?e?s?.[1]:a?.[1]:t,g=l?l.inclusive:!0,S={type:e?"integer":"number",format:e?"int64":"double"};return p?S.minimum=m:S.exclusiveMinimum=m,g?S.maximum=b:S.exclusiveMaximum=b,S},Rt=({shape:e},t)=>d.map(t,e),cs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return vn?.[t]},So=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ds=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&Tt(o)){let s=it(e,cs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(K.any())}if(!t&&n.type==="preprocess"&&Tt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ms=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ls=(e,{next:t})=>t(e.unwrap()),us=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),fs=(e,{next:t})=>t(e.unwrap().shape.raw),Ro=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,To=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Ro)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ys=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Ro)({schema:e,variant:"original",validate:!0,pullProps:!0}),gs=(e,t)=>t?.includes(e)||e.startsWith("x-")||uo.includes(e),Oo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let b=$(r),g=nt(e),S=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),P=R=>h&&g.includes(R),V=d.chain(d.filter(R=>R.type==="header"),m??[]).map(({name:R})=>R),L=R=>C&&(c?.(R,t,e)??gs(R,V));return Object.entries(b.shape).reduce((R,[z,k])=>{let M=P(z)?"path":L(z)?"header":S?"query":void 0;if(!M)return R;let O=Te(k,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),q=s==="components"?n(k,O,se(l,z)):O,{_def:I}=k;return R.concat({name:z,in:M,deprecated:I[y]?.isDeprecated,required:!k.isOptional(),description:O.description||l,schema:q,examples:ys(b,z)})},[])},Gt={ZodString:as,ZodNumber:ps,ZodBigInt:rs,ZodBoolean:ts,ZodNull:Yn,ZodArray:ss,ZodTuple:is,ZodRecord:ns,ZodObject:Wn,ZodLiteral:Jn,ZodIntersection:$n,ZodUnion:Dn,ZodAny:Mn,ZodDefault:Nn,ZodEnum:yo,ZodNativeEnum:yo,ZodEffects:ds,ZodOptional:_n,ZodNullable:Gn,ZodDiscriminatedUnion:Kn,ZodBranded:ls,ZodDate:es,ZodCatch:Ln,ZodPipeline:ms,ZodLazy:us,ZodReadonly:Vn,[G]:Hn,[Ee]:Un,[ge]:Xn,[ye]:Qn,[ie]:fs},Jt=(e,{isResponse:t,prev:r})=>{if(Vt(r))return{};let{description:o,_def:n}=e,s=e instanceof K.ZodLazy,a=r.type!==void 0,c=t&&Fe(e),m=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),m&&(p.type=So(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},Wt=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Po=(e,t)=>{if(Vt(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Po(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},wo=e=>Vt(e)?e:d.omit(["examples"],e),Ao=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:b=`${e.toUpperCase()} ${t} ${Ht(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:b};let g=wo(Te(r,{rules:{...p,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),S={schema:a==="components"?s(r,g,se(b)):g,examples:To(r,!0)};return{description:b,content:d.fromPairs(d.xprod(o,[S]))}},hs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},bs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},xs=({name:e})=>({type:"apiKey",in:"header",name:e}),Ss=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Rs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Ts=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Eo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?hs(o):o.type==="input"?bs(o,t):o.type==="header"?xs(o):o.type==="cookie"?Ss(o):o.type==="openid"?Rs(o):Ts(o);return e.map(o=>o.map(r))},zo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Zo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,b]=Po(Te(r,{rules:{...a,...Gt},onEach:Jt,onMissing:Wt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),g=wo(l),S={schema:s==="components"?n(r,g,se(p)):g,examples:To($(r),!1,c)},h={description:p,content:{[o]:S}};return(b||ft(r))&&(h.required=!0),h},Io=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Yt=e=>e.length<=fo?e:e.slice(0,fo-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Qt=class extends Os{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||se(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new B(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(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.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:b=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});Me({routing:t,onEndpoint:(h,C,P)=>{let V={path:C,method:P,endpoint:h,composition:g,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:L,shortDescription:R,scopes:z,inputSchema:k}=h,M=R?Yt(R):b&&L?Yt(L):void 0,O=r.inputSources?.[P]||Mt[P],q=this.#n(C,P,h.getOperationId(P)),I=lo(h.security),pe=Oo({...V,inputSources:O,isHeader:p,security:I,schema:k,description:a?.requestParameter?.call(null,{method:P,path:C,operationId:q})}),Xe={};for(let te of ke){let ce=h.getResponses(te);for(let{mimeTypes:jt,schema:tt,statusCodes:rt}of ce)for(let Nt of rt)Xe[Nt]=Ao({...V,variant:te,schema:tt,mimeTypes:jt,statusCode:Nt,hasMultipleStatusCodes:ce.length>1||rt.length>1,description:a?.[`${te}Response`]?.call(null,{method:P,path:C,operationId:q,statusCode:Nt})})}let Ct=O.includes("body")?Zo({...V,paramNames:vo.pluck("name",pe),schema:k,mimeType:v[h.requestType],description:a?.requestBody?.call(null,{method:P,path:C,operationId:q})}):void 0,et=zo(Eo(I,O),z,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),kt={operationId:q,summary:M,description:L,deprecated:h.isDeprecated||void 0,tags:Ot(h.tags),parameters:Ot(pe),requestBody:Ct,security:Ot(et),responses:Xe};this.addPath(ho(C),{[P]:kt})}}),m&&(this.rootDoc.tags=Io(m))}};import{createRequest as Ps,createResponse as ws}from"node-mocks-http";var As=e=>Ps({...e,headers:{"content-type":v.json,...e?.headers}}),Es=e=>ws(e),zs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Co=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),s=Es({req:n,...t});s.req=t?.req||n,n.res=s;let a=zs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Co(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Is=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Se}}=Co(r),m=st(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import vt from"typescript";import{z as ni}from"zod";import*as Mo from"ramda";import X from"typescript";var ko=["get","post","put","delete","patch"];import*as Y from"ramda";import u from"typescript";var i=u.factory,Pt=[i.createModifier(u.SyntaxKind.ExportKeyword)],vs=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Ye={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Xt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),er=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},Cs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,tr=e=>typeof e=="string"&&Cs.test(e)?i.createIdentifier(e):E(e),wt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),At=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ue=e=>Object.entries(e).map(([t,r])=>At(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),rr=(e,t=[])=>i.createConstructorDeclaration(Ye.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,or=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,tr(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Xt(s,a.join(" ")):s},nr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),sr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Pt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),ir=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(D,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Pt:void 0,e,n&&dr(n),t);return o?Xt(s,o):s},jo=(e,t)=>i.createPropertyDeclaration(Ye.public,e,void 0,f(t),void 0),ar=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ye.public,void 0,e,void 0,o&&dr(o),t,n,i.createBlock(r)),pr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Pt,e,r&&dr(r),void 0,t),cr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Et=e=>f(Promise.name,[e]),zt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Pt:void 0,e,void 0,void 0,t);return o?Xt(n,o):n},dr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Pe=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?vs:void 0,void 0,Array.isArray(e)?Y.map(At,e):Ue(e),void 0,void 0,t),w=e=>e,Qe=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),A=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),He=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Zt=(e,t)=>f("Extract",[e,t]),mr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),_=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),No=e=>i.createUnionTypeNode([f(e),Et(e)]),lr=(e,t)=>i.createFunctionTypeNode(void 0,Ue(e),f(t)),E=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),D=e=>i.createLiteralTypeNode(E(e)),ks=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Lo=e=>ks.includes(e.kind);var It=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=ir("Method",ko);someOfType=Q("SomeOf",_("T",cr("T")),{params:["T"]});requestType=Q("Request",cr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>ir(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>zt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(tr(t),i.createArrayLiteralExpression(Mo.map(E,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,lr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Et(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Pe({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(A(this.#e.requestParameter,w("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,Pe({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([mr(this.#e.pathParameter,A(this.#e.pathParameter,w("replace"))(wt(":",[this.#e.keyParameter]),Pe([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ar(this.#e.provideMethod,Ue({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:_(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(sr(this.#e.methodParameter,this.#e.pathParameter),A(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(A(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(A(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Et(_(this.interfaces.response,"K"))});makeClientClass=t=>pr(t,[rr([At(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ye.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>wt("?",[He(URLSearchParams.name,t)]);#o=()=>He(URL.name,wt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(w("method"),A(this.#e.methodParameter,w("toUpperCase"))()),r=i.createPropertyAssignment(w("headers"),Qe(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(v.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(w("body"),Qe(this.#e.hasBodyConst,A(JSON[Symbol.toStringTag],w("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(A(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(A(i.createArrayLiteralExpression([E("get"),E("delete")]),w("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,Qe(this.#e.hasBodyConst,E(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,A(this.#e.responseConst,w("headers"),w("get"))(E("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,A(this.#e.contentTypeConst,w("startsWith"))(E(v.json))),l=i.createReturnStatement(A(this.#e.responseConst,Qe(this.#e.isJsonConst,E(w("json")),E(w("text"))))());return j(this.#e.defaultImplementationConst,Pe([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>rr(Ue({request:"K",params:_(this.interfaces.input,"K")}),[j(sr(this.#e.pathParameter,this.#e.restConst),A(this.#e.substituteFn)(i.createElementAccessExpression(A(this.#e.parseRequestFn)(this.#e.requestParameter),E(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),mr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),He("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Oe(w("event"),t)]);#i=()=>ar(this.#e.onMethod,Ue({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:lr({[this.#e.dataParameter.text]:_(Zt("R",nr(this.#s("E"))),D(w("data")))},No(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(A(i.createThis(),this.#e.sourceProp,w("addEventListener"))(this.#e.eventParameter,Pe([this.#e.msgParameter],A(this.#e.handlerParameter)(A(JSON[Symbol.toStringTag],w("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),w("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:_("R",D(w("event")))}});makeSubscriptionClass=t=>pr(t,[jo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Zt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Zt(_(this.interfaces.positive,"K"),nr(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,He(t)),A(this.#e.clientConst,this.#e.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),A(He(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(E("time"),Pe(["time"],i.createBlock([])))]};import*as Z from"ramda";import x from"typescript";import{z as fr}from"zod";var{factory:F}=x,js={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},ur={name:Z.path(["name","text"]),type:Z.path(["type"]),optional:Z.path(["questionToken"])},Ns=({value:e})=>D(e),Ls=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t&&Fe(a)?a instanceof fr.ZodOptional:a.isOptional();return Oe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[y]?.isDeprecated})});return F.createTypeLiteralNode(n)},Ms=({element:e},{next:t})=>F.createArrayTypeNode(t(e)),Us=({options:e})=>F.createUnionTypeNode(e.map(D)),Uo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Lo(n)?n.kind:n,n)}return F.createUnionTypeNode(Array.from(r.values()))},Hs=e=>js?.[e.kind],Ds=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=it(e,Hs(o)),s={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.SyntaxKind.AnyKeyword)}return o},Ks=e=>F.createUnionTypeNode(Object.values(e.enum).map(D)),Fs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?F.createUnionTypeNode([o,f(x.SyntaxKind.UndefinedKeyword)]):o},qs=(e,{next:t})=>F.createUnionTypeNode([t(e.unwrap()),D(null)]),Bs=({items:e,_def:{rest:t}},{next:r})=>F.createTupleTypeNode(e.map(r).concat(t===null?[]:F.createRestTypeNode(r(t)))),$s=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),_s=Z.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=Z.chain(Z.prop("members"),e),r=Z.uniqWith((...o)=>{if(!Z.eqBy(ur.name,...o))return!1;if(Z.both(Z.eqBy(ur.type),Z.eqBy(ur.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return F.createTypeLiteralNode(r)},(e,t)=>F.createIntersectionTypeNode(t)),Vs=({_def:{left:e,right:t}},{next:r})=>_s([e,t].map(r)),Gs=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),Js=(e,{next:t})=>t(e.unwrap()),Ws=(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"]),Xs=()=>D(null),ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ti=e=>{let t=e.unwrap(),r=f(x.SyntaxKind.StringKeyword),o=f("Buffer"),n=F.createUnionTypeNode([r,o]);return t instanceof fr.ZodString?r:t instanceof fr.ZodUnion?n:o},ri=(e,{next:t})=>t(e.unwrap().shape.raw),oi={ZodString:ae(x.SyntaxKind.StringKeyword),ZodNumber:ae(x.SyntaxKind.NumberKeyword),ZodBigInt:ae(x.SyntaxKind.BigIntKeyword),ZodBoolean:ae(x.SyntaxKind.BooleanKeyword),ZodAny:ae(x.SyntaxKind.AnyKeyword),ZodUndefined:ae(x.SyntaxKind.UndefinedKeyword),[ye]:ae(x.SyntaxKind.StringKeyword),[ge]:ae(x.SyntaxKind.StringKeyword),ZodNull:Xs,ZodArray:Ms,ZodTuple:Bs,ZodRecord:$s,ZodObject:Ls,ZodLiteral:Ns,ZodIntersection:Vs,ZodUnion:Uo,ZodDefault:Gs,ZodEnum:Us,ZodNativeEnum:Ks,ZodEffects:Ds,ZodOptional:Fs,ZodNullable:qs,ZodDiscriminatedUnion:Uo,ZodBranded:Js,ZodCatch:Ys,ZodPipeline:Qs,ZodLazy:ei,ZodReadonly:Ws,[G]:ti,[ie]:ri},yr=(e,{brandHandling:t,ctx:r})=>Te(e,{rules:{...t,...oi},onMissing:()=>f(x.SyntaxKind.AnyKeyword),ctx:r});var gr=class extends It{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=D(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=ni.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};Me({routing:t,onEndpoint:(S,h,C)=>{let P=se.bind(null,C,h),{isDeprecated:V,inputSchema:L,tags:R}=S,z=`${C} ${h}`,k=Q(P("input"),yr(L,l),{comment:z});this.#e.push(k);let M=ke.reduce((I,pe)=>{let Xe=S.getResponses(pe),Ct=Ho.chain(([kt,{schema:te,mimeTypes:ce,statusCodes:jt}])=>{let tt=Q(P(pe,"variant",`${kt+1}`),yr(ce?te:m,b),{comment:z});return this.#e.push(tt),jt.map(rt=>Oe(rt,tt.name))},Array.from(Xe.entries())),et=zt(P(pe,"response","variants"),Ct,{comment:z});return this.#e.push(et),Object.assign(I,{[pe]:et})},{});this.paths.add(h);let O=D(z),q={input:f(k.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:i.createUnionTypeNode([_(this.interfaces.positive,O),_(this.interfaces.negative,O)]),encoded:i.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(z,{isDeprecated:V,store:q}),this.tags.set(z,R)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:er(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&vt.addSyntheticLeadingComment(vt.addSyntheticLeadingComment(i.createEmptyStatement(),vt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),vt.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>er(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "23.0.0",
3
+ "version": "23.1.0",
4
4
  "description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {