express-zod-api 19.0.0 → 19.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,53 @@
2
2
 
3
3
  ## Version 19
4
4
 
5
+ ### v19.1.0
6
+
7
+ - Feature: customizable handling rules for your branded schemas in Documentation and Integration:
8
+ - You can make your schemas special by branding them using `.brand()` method;
9
+ - The library (being a Zod Plugin as well) distinguishes the branded schemas in runtime;
10
+ - The constructors of `Documentation` and `Integration` now accept new property `brandHandling` (object);
11
+ - Its keys should be the brands you want to handle in a special way;
12
+ - Its values are functions having your schema as the first argument and a context in the second place;
13
+ - In case you need to reuse a handling rule for multiple brands, use the exposed types `Depicter` and `Producer`.
14
+
15
+ ```ts
16
+ import ts from "typescript";
17
+ import { z } from "zod";
18
+ import {
19
+ Documentation,
20
+ Integration,
21
+ Depicter,
22
+ Producer,
23
+ } from "express-zod-api";
24
+
25
+ const myBrand = Symbol("MamaToldMeImSpecial"); // I recommend to use symbols for this purpose
26
+ const myBrandedSchema = z.string().brand(myBrand);
27
+
28
+ const ruleForDocs: Depicter = (
29
+ schema: typeof myBrandedSchema, // you should assign type yourself
30
+ { next, path, method, isResponse }, // handle a nested schema using next()
31
+ ) => {
32
+ const defaultDepiction = next(schema.unwrap()); // { type: string }
33
+ return { summary: "Special type of data" };
34
+ };
35
+
36
+ const ruleForClient: Producer = (
37
+ schema: typeof myBrandedSchema, // you should assign type yourself
38
+ { next, isResponse, serializer }, // handle a nested schema using next()
39
+ ) => ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
40
+
41
+ new Documentation({
42
+ /* config, routing, title, version */
43
+ brandHandling: { [myBrand]: ruleForDocs },
44
+ });
45
+
46
+ new Integration({
47
+ /* routing */
48
+ brandHandling: { [myBrand]: ruleForClient },
49
+ });
50
+ ```
51
+
5
52
  ### v19.0.0
6
53
 
7
54
  - **Breaking changes**:
package/README.md CHANGED
@@ -58,6 +58,7 @@ Start your API server with I/O schema validation and custom middlewares in minut
58
58
  2. [Generating a Frontend Client](#generating-a-frontend-client)
59
59
  3. [Creating a documentation](#creating-a-documentation)
60
60
  4. [Tagging the endpoints](#tagging-the-endpoints)
61
+ 5. [Customizable brands handling](#customizable-brands-handling)
61
62
  8. [Caveats](#caveats)
62
63
  1. [Coercive schema of Zod](#coercive-schema-of-zod)
63
64
  2. [Excessive properties in endpoint output](#excessive-properties-in-endpoint-output)
@@ -1170,6 +1171,50 @@ const exampleEndpoint = taggedEndpointsFactory.build({
1170
1171
  });
1171
1172
  ```
1172
1173
 
1174
+ ## Customizable brands handling
1175
+
1176
+ You can customize handling rules for your schemas in Documentation and Integration. Use the `.brand()` method on your
1177
+ schema to make it special and distinguishable for the library in runtime. Using symbols is recommended for branding.
1178
+ After that utilize the `brandHandling` feature of both constructors to declare your custom implementation. In case you
1179
+ need to reuse a handling rule for multiple brands, use the exposed types `Depicter` and `Producer`.
1180
+
1181
+ ```ts
1182
+ import ts from "typescript";
1183
+ import { z } from "zod";
1184
+ import {
1185
+ Documentation,
1186
+ Integration,
1187
+ Depicter,
1188
+ Producer,
1189
+ } from "express-zod-api";
1190
+
1191
+ const myBrand = Symbol("MamaToldMeImSpecial"); // I recommend to use symbols for this purpose
1192
+ const myBrandedSchema = z.string().brand(myBrand);
1193
+
1194
+ const ruleForDocs: Depicter = (
1195
+ schema: typeof myBrandedSchema, // you should assign type yourself
1196
+ { next, path, method, isResponse }, // handle a nested schema using next()
1197
+ ) => {
1198
+ const defaultDepiction = next(schema.unwrap()); // { type: string }
1199
+ return { summary: "Special type of data" };
1200
+ };
1201
+
1202
+ const ruleForClient: Producer = (
1203
+ schema: typeof myBrandedSchema, // you should assign type yourself
1204
+ { next, isResponse, serializer }, // handle a nested schema using next()
1205
+ ) => ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
1206
+
1207
+ new Documentation({
1208
+ /* config, routing, title, version */
1209
+ brandHandling: { [myBrand]: ruleForDocs },
1210
+ });
1211
+
1212
+ new Integration({
1213
+ /* routing */
1214
+ brandHandling: { [myBrand]: ruleForClient },
1215
+ });
1216
+ ```
1217
+
1173
1218
  # Caveats
1174
1219
 
1175
1220
  There are some well-known issues and limitations, or third party bugs that cannot be fixed in the usual way, but you
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var Oo=Object.create;var qe=Object.defineProperty;var Ao=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var Co=Object.getPrototypeOf,Io=Object.prototype.hasOwnProperty;var wo=(e,t)=>{for(var r in t)qe(e,r,{get:t[r],enumerable:!0})},Xt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Po(t))!Io.call(e,i)&&i!==r&&qe(e,i,{get:()=>t[i],enumerable:!(o=Ao(t,i))||o.enumerable});return e};var R=(e,t,r)=>(r=e!=null?Oo(Co(e)):{},Xt(t||!e||!e.__esModule?qe(r,"default",{value:e,enumerable:!0}):r,e)),Eo=e=>Xt(qe({},"__esModule",{value:!0}),e);var pi={};wo(pi,{AbstractEndpoint:()=>oe,DependsOnMethod:()=>he,Documentation:()=>ct,DocumentationError:()=>I,EndpointsFactory:()=>ge,InputValidationError:()=>j,Integration:()=>gt,MissingPeerError:()=>X,OutputValidationError:()=>V,RoutingError:()=>J,ServeStatic:()=>be,arrayEndpointsFactory:()=>Rr,arrayResultHandler:()=>nt,attachRouting:()=>kr,createConfig:()=>sr,createLogger:()=>it,createMiddleware:()=>rt,createResultHandler:()=>ot,createServer:()=>jr,defaultEndpointsFactory:()=>Sr,defaultResultHandler:()=>ye,ez:()=>So,getExamples:()=>H,getMessageFromError:()=>U,getStatusCodeFromError:()=>Ze,testEndpoint:()=>so});module.exports=Eo(pi);var ir=require("ramda"),Me=require("zod");var er=require("http-errors"),tr=require("crypto"),ce=require("ramda"),rr=require("zod");var J=class extends Error{name="RoutingError"},I=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
2
- Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},q=class extends Error{name="IOSchemaError"},V=class extends q{name="OutputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},j=class extends q{name="InputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},W=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},X=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var N={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var zo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(N.upload);return"files"in e&&r},xt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Zo=["body","query","params"],bt=e=>e.method.toLowerCase(),Tt=e=>e.startsWith("x-"),No=e=>(0,ce.pickBy)((0,ce.flip)(Tt),e),or=(e,t={})=>{let r=bt(e);return r==="options"?{}:(t[r]||xt[r]||Zo).filter(o=>o==="files"?zo(e):!0).map(o=>o==="headers"?No(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},le=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),U=e=>e instanceof rr.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Ze=e=>(0,er.isHttpError)(e)?e.statusCode:e instanceof j?400:500,St=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
1
+ "use strict";var Ao=Object.create;var $e=Object.defineProperty;var Po=Object.getOwnPropertyDescriptor;var Co=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,wo=Object.prototype.hasOwnProperty;var Eo=(e,t)=>{for(var r in t)$e(e,r,{get:t[r],enumerable:!0})},er=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Co(t))!wo.call(e,i)&&i!==r&&$e(e,i,{get:()=>t[i],enumerable:!(o=Po(t,i))||o.enumerable});return e};var R=(e,t,r)=>(r=e!=null?Ao(Io(e)):{},er(t||!e||!e.__esModule?$e(r,"default",{value:e,enumerable:!0}):r,e)),zo=e=>er($e({},"__esModule",{value:!0}),e);var ni={};Eo(ni,{AbstractEndpoint:()=>ne,DependsOnMethod:()=>xe,Documentation:()=>lt,DocumentationError:()=>P,EndpointsFactory:()=>he,InputValidationError:()=>H,Integration:()=>ht,MissingPeerError:()=>ee,OutputValidationError:()=>V,RoutingError:()=>W,ServeStatic:()=>Te,arrayEndpointsFactory:()=>Or,arrayResultHandler:()=>it,attachRouting:()=>kr,createConfig:()=>ar,createLogger:()=>st,createMiddleware:()=>ot,createResultHandler:()=>nt,createServer:()=>Hr,defaultEndpointsFactory:()=>Rr,defaultResultHandler:()=>ge,ez:()=>Ro,getExamples:()=>F,getMessageFromError:()=>U,getStatusCodeFromError:()=>Ne,testEndpoint:()=>ao});module.exports=zo(ni);var sr=require("ramda"),ve=require("zod");var tr=require("http-errors"),rr=require("crypto"),le=require("ramda"),or=require("zod");var W=class extends Error{name="RoutingError"},P=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
2
+ Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},$=class extends Error{name="IOSchemaError"},V=class extends ${name="OutputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},H=class extends ${name="InputValidationError";originalError;constructor(t){super(U(t)),this.originalError=t}},X=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ee=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var Z={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var Zo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(Z.upload);return"files"in e&&r},bt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},No=["body","query","params"],Tt=e=>e.method.toLowerCase(),St=e=>e.startsWith("x-"),Mo=e=>(0,le.pickBy)((0,le.flip)(St),e),nr=(e,t={})=>{let r=Tt(e);return r==="options"?{}:(t[r]||bt[r]||No).filter(o=>o==="files"?Zo(e):!0).map(o=>o==="headers"?Mo(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},me=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),U=e=>e instanceof or.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Ne=e=>(0,tr.isHttpError)(e)?e.statusCode:e instanceof H?400:500,Rt=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
3
3
  ${o.stack}
4
- `,{url:t.url,payload:r})},H=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},ee=(e,t,r)=>e.length&&t.length?(0,ce.xprod)(e,t).map(r):e.concat(t),Ne=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Rt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),M=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(Rt).join(""),Ve=e=>(0,tr.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),$e=(e,t)=>{try{return typeof e.parse(t)}catch{return}},F=e=>typeof e=="object"&&e!==null;var _e=require("ramda"),g=Symbol.for("express-zod-api"),Ge=e=>{let t=e.describe(e.description);return t._def[g]=(0,_e.clone)(t._def[g])||{examples:[]},t},nr=(e,t)=>{if(!(g in e._def))return t;let r=Ge(t);return r._def[g].examples=ee(r._def[g].examples,e._def[g].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?(0,_e.mergeDeepRight)({...o},{...i}):i),r};var Mo=function(e){let t=Ge(this);return t._def[g].examples.push(e),t},vo=function(e){let t=Ge(this);return t._def[g].defaultLabel=e,t},Lo=function(e){return new Me.z.ZodBranded({typeName:Me.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...(0,ir.clone)(this._def[g]),brand:e}})};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Me.z.ZodType.prototype,{example:{get(){return Mo.bind(this)}},brand:{set(){},get(){return Lo.bind(this)}}}),Object.defineProperty(Me.z.ZodDefault.prototype,"label",{get(){return vo.bind(this)}}));function sr(e){return e}var It=R(require("assert/strict"),1),et=require("zod");var ar=require("zod"),me={positive:200,negative:400},Ot=(e,t)=>e instanceof ar.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));var fr=require("zod");var dr=require("zod");var ve=require("zod"),$=Symbol("File"),pr=ve.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Do={buffer:()=>pr.brand($),string:()=>ve.z.string().brand($),binary:()=>pr.or(ve.z.string()).brand($),base64:()=>ve.z.string().base64().brand($)};function Ye(e){return Do[e||"string"]()}var te=Symbol("Raw"),cr=(e={})=>dr.z.object({raw:Ye("buffer")}).extend(e).brand(te);var lr=require("zod"),Le=Symbol("Upload"),mr=()=>lr.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(Le);var At=({schema:{options:e},next:t})=>e.some(t),yr=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),ko=({schema:e,next:t})=>Object.values(e.shape).some(t),ur=({schema:e,next:t})=>t(e.unwrap()),jo=({schema:e,next:t})=>t(e.innerType()),Uo=({schema:e,next:t})=>t(e.valueSchema),Ho=({schema:e,next:t})=>t(e.element),Fo=({schema:e,next:t})=>t(e._def.innerType),Ko={ZodObject:ko,ZodUnion:At,ZodDiscriminatedUnion:At,ZodIntersection:yr,ZodEffects:jo,ZodOptional:ur,ZodNullable:ur,ZodRecord:Uo,ZodArray:Ho,ZodDefault:Fo},Qe=({subject:e,condition:t,rules:r=Ko,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s({schema:e,next:a=>Qe({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},Je=e=>Qe({subject:e,maxDepth:3,rules:{ZodUnion:At,ZodIntersection:yr},condition:t=>t instanceof fr.z.ZodEffects&&t._def.effect.type!=="refinement"}),gr=e=>Qe({subject:e,condition:t=>t._def[g]?.brand===Le}),hr=e=>Qe({subject:e,condition:t=>t._def[g]?.brand===te,maxDepth:3});var We=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
- Original error: ${e.originalError.message}.`:""))};var xr=require("ramda");var re=e=>F(e)&&"or"in e,fe=e=>F(e)&&"and"in e,Pt=e=>({and:(0,xr.chain)(t=>fe(t)?t.and:[t],e)}),Xe=(e,t)=>fe(e)?{and:e.and.map(r=>re(r)?{or:r.or.map(t)}:t(r))}:re(e)?{or:e.or.map(r=>fe(r)?{and:r.and.map(t)}:t(r))}:t(e),Ct=e=>e.and.reduce((t,r)=>({or:ee(t.or,re(r)?r.or:[r],Pt)}),{or:[]}),ue=(e,t)=>fe(e)?re(t)?ue(Ct(e),t):Pt([e,t]):re(e)?fe(t)?ue(t,e):re(t)?{or:ee(e.or,t.or,Pt)}:ue(e,{and:[t]}):fe(t)||re(t)?ue(t,e):{and:[e,t]};var oe=class{},tt=class extends oe{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:l=[],description:u,shortDescription:m}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(l),this.#e={long:u,short:m},this.#r={input:r,output:o};for(let[y,T]of Object.entries(this.#r))(0,It.default)(!Je(T),new q(`Using transformations on the top level of endpoint ${y} schema is not allowed.`));this.#t={positive:Object.freeze(Ot(s.getPositiveResponse(o),{mimeTypes:[N.json],statusCodes:[me.positive]})),negative:Object.freeze(Ot(s.getNegativeResponse(),{mimeTypes:[N.json],statusCodes:[me.negative]}))};for(let[y,T]of Object.entries(this.#t))(0,It.default)(T.length,new W(`ResultHandler must have at least one ${y} response schema specified.`));this.#i=gr(r)?"upload":hr(r)?"raw":"json",this.#s={input:Object.freeze([N[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:y})=>y)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:y})=>y))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ue(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof et.z.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(l){throw l instanceof et.z.ZodError?new j(l):l}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof et.z.ZodError?new j(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){We({logger:i,response:o,error:new W(le(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=bt(t),p={},d=null,l=null;if(i.cors){let m=this.#m(s);typeof i.cors=="function"&&(m=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:m}));for(let y in m)r.set(y,m[y])}let u=or(t,i.inputSources);try{if(await this.#f({method:a,input:u,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:u,logger:o,options:p}))}catch(m){l=le(m)}await this.#g({input:u,output:d,request:t,response:r,error:l,logger:o,options:p})}};var wt=require("zod");var br=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>nr(s,i),o)};var Tr=R(require("assert/strict"),1),rt=e=>((0,Tr.default)(!Je(e.input),new q("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var v=require("zod");var ot=e=>e,ye=ot({getPositiveResponse:e=>{let t=H({schema:e}),r=v.z.object({status:v.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>v.z.object({status:v.z.literal("error"),error:v.z.object({message:v.z.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(me.positive).json({status:"success",data:r});return}let a=Ze(e);St({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),nt=ot({getPositiveResponse:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.z.ZodArray?e.shape.items:v.z.array(v.z.any());return t.reduce((o,i)=>F(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>v.z.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Ze(r);St({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(me.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var ge=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:wt.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,l)=>{t(a,p,m=>{if(m&&m instanceof Error)return l(o(m));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(rt({input:wt.z.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:l}=this,u="methods"in p?p.methods:[p.method],m=typeof a=="function"?a:()=>a,y="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],T="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new tt({handler:r,middlewares:d,outputSchema:o,resultHandler:l,scopes:y,tags:T,methods:u,getOperationId:m,description:i,shortDescription:s,inputSchema:br(d,t)})}},Sr=new ge(ye),Rr=new ge(nt);var Or=require("util");var Ar=require("ramda"),L=require("ansis"),Et={debug:10,info:20,warn:30,error:40},Pr=e=>F(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),it=({level:e,color:t=new L.Ansis().isSupported(),depth:r=2})=>{let o={debug:L.blue,info:L.green,warn:(0,L.hex)("#FFA500"),error:L.red},i=e==="debug",s=e==="silent"?100:Et[e],a=(p,d,l)=>{if(Et[p]<s)return;let u=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];l!==void 0&&u.push((0,Or.inspect)(l,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(u.join(" "))};return(0,Ar.mapObjIndexed)(({},p)=>(d,l)=>a(p,d,l),Et)};var xe=require("ramda"),he=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,xe.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,xe.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,xe.tail)(this.pairs).map(([r])=>r))}};var Cr=R(require("express"),1),be=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Cr.default.static(...this.params))}};var st=R(require("express"),1),vr=R(require("http"),1),Lr=R(require("https"),1);var ne=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>R(require(e))))[t]}catch{}throw new X(e)},Ir=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await ne(t,r)}catch{}throw new X(e.map(({moduleName:t})=>t))};var zt=R(require("assert/strict"),1);var ie=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){zt.default.doesNotMatch(a,/\//,new J(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof oe){let l=p.getMethods().slice();i&&l.push("options");for(let u of l)t(p,d,u)}else if(p instanceof be)r&&p.apply(d,r);else if(p instanceof he){for(let[l,u]of p.pairs)(0,zt.default)(u.getMethods().includes(l),new J(`Endpoint assigned to ${l} method of ${d} must support ${l} method.`)),t(u,d,l);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else ie({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Zt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>ie({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(l,u)=>s.execute({request:l,response:u,logger:u.locals[g]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});var De=R(require("http-errors"),1);var wr=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:(0,De.isHttpError)(r)?r:(0,De.default)(400,le(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[g]?.logger||t})},Er=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=(0,De.default)(404,`Can not ${r.method} ${r.path}`),s=o.locals[g]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){We({response:o,logger:s,error:new W(le(a).message,i)})}},Bo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},qo=e=>({log:e.debug.bind(e)}),zr=async({rootLogger:e,config:t})=>{let r=await ne("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,l)=>{let u=d.locals[g]?.logger||e;try{await i?.({request:p,logger:u})}catch(m){return l(m)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:qo(u)})(p,d,l)}),o&&a.push(Bo(o)),a},Zr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Nr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[g]={logger:s},i()};var E=require("ansis"),Mr=()=>{let e=(0,E.italic)("Proudly supports transgender community.".padStart(109)),t=(0,E.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,E.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,E.italic)("for Dime".padEnd(20)),i=(0,E.hex)("#F5A9B8"),s=(0,E.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(E.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(E.gray,12,13);return`
4
+ `,{url:t.url,payload:r})},F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},te=(e,t,r)=>e.length&&t.length?(0,le.xprod)(e,t).map(r):e.concat(t),Me=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,Ot=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),N=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(Ot).join(""),Ve=e=>(0,rr.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ge=(e,t)=>{try{return typeof e.parse(t)}catch{return}},K=e=>typeof e=="object"&&e!==null;var _e=require("ramda"),g=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[g]=(0,_e.clone)(t._def[g])||{examples:[]},t},ir=(e,t)=>{if(!(g in e._def))return t;let r=Ye(t);return r._def[g].examples=te(r._def[g].examples,e._def[g].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?(0,_e.mergeDeepRight)({...o},{...i}):i),r};var vo=function(e){let t=Ye(this);return t._def[g].examples.push(e),t},Do=function(e){let t=Ye(this);return t._def[g].defaultLabel=e,t},Lo=function(e){return new ve.z.ZodBranded({typeName:ve.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...(0,sr.clone)(this._def[g]),brand:e}})};g in globalThis||(globalThis[g]=!0,Object.defineProperties(ve.z.ZodType.prototype,{example:{get(){return vo.bind(this)}},brand:{set(){},get(){return Lo.bind(this)}}}),Object.defineProperty(ve.z.ZodDefault.prototype,"label",{get(){return Do.bind(this)}}));function ar(e){return e}var wt=R(require("assert/strict"),1),tt=require("zod");var pr=require("zod"),ue={positive:200,negative:400},At=(e,t)=>e instanceof pr.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));var yr=require("zod");var cr=require("zod");var De=require("zod"),G=Symbol("File"),dr=De.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),jo={buffer:()=>dr.brand(G),string:()=>De.z.string().brand(G),binary:()=>dr.or(De.z.string()).brand(G),base64:()=>De.z.string().base64().brand(G)};function Qe(e){return jo[e||"string"]()}var re=Symbol("Raw"),lr=(e={})=>cr.z.object({raw:Qe("buffer")}).extend(e).brand(re);var mr=require("zod"),Le=Symbol("Upload"),ur=()=>mr.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(Le);var Pt=(e,{next:t})=>e.options.some(t),gr=({_def:e},{next:t})=>[e.left,e.right].some(t),fr=(e,{next:t})=>t(e.unwrap()),ko={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Pt,ZodDiscriminatedUnion:Pt,ZodIntersection:gr,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:fr,ZodNullable:fr,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Je=(e,{condition:t,rules:r=ko,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s(e,{next:a=>Je(a,{condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},We=e=>Je(e,{maxDepth:3,rules:{ZodUnion:Pt,ZodIntersection:gr},condition:t=>t instanceof yr.z.ZodEffects&&t._def.effect.type!=="refinement"}),hr=e=>Je(e,{condition:t=>t._def[g]?.brand===Le}),xr=e=>Je(e,{condition:t=>t._def[g]?.brand===re,maxDepth:3});var Xe=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
+ Original error: ${e.originalError.message}.`:""))};var br=require("ramda");var oe=e=>K(e)&&"or"in e,ye=e=>K(e)&&"and"in e,Ct=e=>({and:(0,br.chain)(t=>ye(t)?t.and:[t],e)}),et=(e,t)=>ye(e)?{and:e.and.map(r=>oe(r)?{or:r.or.map(t)}:t(r))}:oe(e)?{or:e.or.map(r=>ye(r)?{and:r.and.map(t)}:t(r))}:t(e),It=e=>e.and.reduce((t,r)=>({or:te(t.or,oe(r)?r.or:[r],Ct)}),{or:[]}),fe=(e,t)=>ye(e)?oe(t)?fe(It(e),t):Ct([e,t]):oe(e)?ye(t)?fe(t,e):oe(t)?{or:te(e.or,t.or,Ct)}:fe(e,{and:[t]}):ye(t)||oe(t)?fe(t,e):{and:[e,t]};var ne=class{},rt=class extends ne{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:m,shortDescription:y}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:m,short:y},this.#r={input:r,output:o};for(let[u,b]of Object.entries(this.#r))(0,wt.default)(!We(b),new $(`Using transformations on the top level of endpoint ${u} schema is not allowed.`));this.#t={positive:Object.freeze(At(s.getPositiveResponse(o),{mimeTypes:[Z.json],statusCodes:[ue.positive]})),negative:Object.freeze(At(s.getNegativeResponse(),{mimeTypes:[Z.json],statusCodes:[ue.negative]}))};for(let[u,b]of Object.entries(this.#t))(0,wt.default)(b.length,new X(`ResultHandler must have at least one ${u} response schema specified.`));this.#i=hr(r)?"upload":xr(r)?"raw":"json",this.#s={input:Object.freeze([Z[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?fe(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof tt.z.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof tt.z.ZodError?new H(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof tt.z.ZodError?new H(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){Xe({logger:i,response:o,error:new X(me(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=Tt(t),p={},d=null,c=null;if(i.cors){let y=this.#m(s);typeof i.cors=="function"&&(y=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:y}));for(let u in y)r.set(u,y[u])}let m=nr(t,i.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(y){c=me(y)}await this.#g({input:m,output:d,request:t,response:r,error:c,logger:o,options:p})}};var Et=require("zod");var Tr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>ir(s,i),o)};var Sr=R(require("assert/strict"),1),ot=e=>((0,Sr.default)(!We(e.input),new $("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var M=require("zod");var nt=e=>e,ge=nt({getPositiveResponse:e=>{let t=F({schema:e}),r=M.z.object({status:M.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>M.z.object({status:M.z.literal("error"),error:M.z.object({message:M.z.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(ue.positive).json({status:"success",data:r});return}let a=Ne(e);Rt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),it=nt({getPositiveResponse:e=>{let t=F({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof M.z.ZodArray?e.shape.items:M.z.array(M.z.any());return t.reduce((o,i)=>K(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>M.z.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Ne(r);Rt({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ue.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var he=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:Et.z.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,y=>{if(y&&y instanceof Error)return c(o(y));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ot({input:Et.z.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],y=typeof a=="function"?a:()=>a,u="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],b="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new rt({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:u,tags:b,methods:m,getOperationId:y,description:i,shortDescription:s,inputSchema:Tr(d,t)})}},Rr=new he(ge),Or=new he(it);var Ar=require("util");var Pr=require("ramda"),D=require("ansis"),zt={debug:10,info:20,warn:30,error:40},Cr=e=>K(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),st=({level:e,color:t=new D.Ansis().isSupported(),depth:r=2})=>{let o={debug:D.blue,info:D.green,warn:(0,D.hex)("#FFA500"),error:D.red},i=e==="debug",s=e==="silent"?100:zt[e],a=(p,d,c)=>{if(zt[p]<s)return;let m=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&m.push((0,Ar.inspect)(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(m.join(" "))};return(0,Pr.mapObjIndexed)(({},p)=>(d,c)=>a(p,d,c),zt)};var be=require("ramda"),xe=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,be.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,be.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,be.tail)(this.pairs).map(([r])=>r))}};var Ir=R(require("express"),1),Te=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Ir.default.static(...this.params))}};var at=R(require("express"),1),Dr=R(require("http"),1),Lr=R(require("https"),1);var ie=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>R(require(e))))[t]}catch{}throw new ee(e)},wr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await ie(t,r)}catch{}throw new ee(e.map(({moduleName:t})=>t))};var Zt=R(require("assert/strict"),1);var se=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){Zt.default.doesNotMatch(a,/\//,new W(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof ne){let c=p.getMethods().slice();i&&c.push("options");for(let m of c)t(p,d,m)}else if(p instanceof Te)r&&p.apply(d,r);else if(p instanceof xe){for(let[c,m]of p.pairs)(0,Zt.default)(m.getMethods().includes(c),new W(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(m,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else se({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Nt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>se({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,m)=>s.execute({request:c,response:m,logger:m.locals[g]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});var je=R(require("http-errors"),1);var Er=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:(0,je.isHttpError)(r)?r:(0,je.default)(400,me(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[g]?.logger||t})},zr=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=(0,je.default)(404,`Can not ${r.method} ${r.path}`),s=o.locals[g]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){Xe({response:o,logger:s,error:new X(me(a).message,i)})}},Ho=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Uo=e=>({log:e.debug.bind(e)}),Zr=async({rootLogger:e,config:t})=>{let r=await ie("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let m=d.locals[g]?.logger||e;try{await i?.({request:p,logger:m})}catch(y){return c(y)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Uo(m)})(p,d,c)}),o&&a.push(Ho(o)),a},Nr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Mr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[g]={logger:s},i()};var I=require("ansis"),vr=()=>{let e=(0,I.italic)("Proudly supports transgender community.".padStart(109)),t=(0,I.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,I.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,I.italic)("for Dime".padEnd(20)),i=(0,I.hex)("#F5A9B8"),s=(0,I.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(I.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(I.gray,12,13);return`
6
6
  8888888888 8888888888P 888 d8888 8888888b. 8888888
7
7
  888 d88P 888 d88888 888 Y88b 888
8
8
  888 d88P 888 d88P888 888 888 888
@@ -16,9 +16,9 @@ Original error: ${e.originalError.message}.`:""))};var xr=require("ramda");var r
16
16
  ${o}888${t}
17
17
  ${r}
18
18
  `.split(`
19
- `).map((d,l)=>a[l]?a[l](d):d).join(`
20
- `)};var Dr=e=>{e.startupLogo!==!1&&console.log(Mr());let t=e.errorHandler||ye,r=Pr(e.logger)?it(e.logger):e.logger;r.debug("Running","v19.0.0 (CJS)");let o=Nr({rootLogger:r,config:e}),i=Er({rootLogger:r,errorHandler:t}),s=wr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=Dr(e);return Zt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},jr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=Dr(e),a=(0,st.default)().disable("x-powered-by").use(s);if(e.server.compression){let u=await ne("compression");a.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||st.default.json()],raw:[e.server.rawParser||st.default.raw(),Zr],upload:e.server.upload?await zr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Zt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(u,m)=>u.listen(m,()=>{r.info("Listening",m)}),l={httpServer:d(vr.default.createServer(a),e.server.listen),httpsServer:e.https?d(Lr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...l,logger:r}};var no=R(require("assert/strict"),1),io=require("openapi3-ts/oas31");var K=R(require("assert/strict"),1),_=require("openapi3-ts/oas31"),c=require("ramda"),b=require("zod");var Te=require("zod");var at=e=>!isNaN(e.getTime());var ke=Symbol("DateIn"),Ur=()=>Te.z.union([Te.z.string().date(),Te.z.string().datetime(),Te.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Te.z.date().refine(at)).brand(ke);var Hr=require("zod");var je=Symbol("DateOut"),Fr=()=>Hr.z.date().refine(at).transform(e=>e.toISOString()).brand(je);var se=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],a=i,d=s?s({schema:e,...a,next:u=>se({schema:u,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),l=t&&t({schema:e,prev:d,...a});return l?{...d,...l}:d};var Kr=50,qr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Vo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vr=/:([A-Za-z0-9_]+)/g,$r=e=>e.match(Vr)?.map(t=>t.slice(1))||[],_r=e=>e.replace(Vr,t=>`{${t.slice(1)}}`),$o=({schema:e,next:t})=>({...t(e._def.innerType),default:e._def[g]?.defaultLabel||e._def.defaultValue()}),_o=({schema:{_def:{innerType:e}},next:t})=>t(e),Go=()=>({format:"any"}),Yo=e=>((0,K.default)(!e.isResponse,new I({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Qo=({schema:e})=>{let t=e.unwrap();return{type:"string",format:t instanceof b.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Jo=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Wo=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Xo=e=>{let[t,r]=e.filter(i=>!(0,_.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,K.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,c.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,c.concat)(i,s):i===s?s:K.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,c.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=ee(t.examples||[],r.examples||[],([i,s])=>(0,c.mergeDeepRight)(i,s))),o},en=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Xo(o)}catch{}return{allOf:o}},tn=({schema:e,next:t})=>t(e.unwrap()),rn=({schema:e,next:t})=>t(e._def.innerType),on=({schema:e,next:t})=>{let r=t(e.unwrap());return(0,_.isReferenceObject)(r)||(r.type=Yr(r)),r},Gr=e=>{let t=(0,c.toLower)((0,c.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Br=({schema:e})=>({type:Gr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),nn=({schema:{value:e}})=>({type:Gr(e),const:e}),sn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Ne(p)?p instanceof b.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=pt({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},an=()=>({type:"null"}),pn=e=>((0,K.default)(!e.isResponse,new I({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:qr}}),dn=e=>((0,K.default)(e.isResponse,new I({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:qr}}),cn=e=>K.default.fail(new I({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),ln=()=>({type:"boolean"}),mn=()=>({type:"integer",format:"bigint"}),un=e=>e.every(t=>t instanceof b.z.ZodLiteral),fn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof b.z.ZodEnum||e instanceof b.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=pt({schema:b.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),...r}),i.required=o),i}if(e instanceof b.z.ZodLiteral)return{type:"object",properties:pt({schema:b.z.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof b.z.ZodUnion&&un(e.options)){let o=(0,c.map)(s=>`${s.value}`,e.options),i=(0,c.fromPairs)((0,c.xprod)(o,[t]));return{type:"object",properties:pt({schema:b.z.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},yn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},gn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),hn=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:l,isDatetime:u,_def:{checks:m}}})=>{let y=m.find(O=>O.kind==="regex"),T=m.find(O=>O.kind==="datetime"),S=y?y.regex:T?T.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,A={type:"string"},x={"date-time":u,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:l};for(let O in x)if(x[O]){A.format=O;break}return r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),S&&(A.pattern=S.source),A},xn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},pt=({schema:{shape:e},next:t})=>(0,c.map)(t,e),bn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Vo?.[t]},Yr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Tn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,_.isReferenceObject)(o)){let s=$e(e,bn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(b.z.any())}if(!t&&i.type==="preprocess"&&!(0,_.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Sn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),Rn=({schema:e,next:t})=>t(e.unwrap()),On=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},An=({next:e,schema:t})=>e(t.unwrap().shape.raw),Qr=e=>e.length?(0,c.fromPairs)((0,c.zip)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e))):void 0,Jr=(e,t,r=[])=>(0,c.pipe)(H,(0,c.map)((0,c.when)((0,c.both)(F,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),Qr)({schema:e,variant:t?"parsed":"original",validate:!0}),Pn=(e,t)=>(0,c.pipe)(H,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),Qr)({schema:e,variant:"original",validate:!0}),Se=(e,t)=>e instanceof b.z.ZodObject?e:e instanceof b.z.ZodBranded?Se(e.unwrap(),t):e instanceof b.z.ZodUnion||e instanceof b.z.ZodDiscriminatedUnion?e.options.map(r=>Se(r,t)).reduce((r,o)=>r.merge(o.partial()),b.z.object({})):e instanceof b.z.ZodEffects?((0,K.default)(e._def.effect.type==="refinement",t),Se(e._def.schema,t)):Se(e._def.left,t).merge(Se(e._def.right,t)),Wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=Se(r,new I({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),u=$r(e),m=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=x=>y&&u.includes(x),A=x=>T&&Tt(x);return Object.keys(l).filter(x=>m||S(x)).map(x=>{let O=se({schema:l[x],isResponse:!1,rules:Mt,onEach:vt,onMissing:Lt,serializer:i,getRef:s,makeRef:a,path:e,method:t}),Pe=p==="components"?a(M(d,x),O):O;return{name:x,in:S(x)?"path":A(x)?"header":"query",required:!l[x].isOptional(),description:O.description||d,schema:Pe,examples:Pn(r,x)}})},Mt={ZodString:hn,ZodNumber:xn,ZodBigInt:mn,ZodBoolean:ln,ZodNull:an,ZodArray:yn,ZodTuple:gn,ZodRecord:fn,ZodObject:sn,ZodLiteral:nn,ZodIntersection:en,ZodUnion:Jo,ZodAny:Go,ZodDefault:$o,ZodEnum:Br,ZodNativeEnum:Br,ZodEffects:Tn,ZodOptional:tn,ZodNullable:on,ZodDiscriminatedUnion:Wo,ZodBranded:Rn,ZodDate:cn,ZodCatch:_o,ZodPipeline:Sn,ZodLazy:On,ZodReadonly:rn,[$]:Qo,[Le]:Yo,[je]:dn,[ke]:pn,[te]:An},vt=({schema:e,isResponse:t,prev:r})=>{if((0,_.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof b.z.ZodLazy,s=r.type!==void 0,a=t&&Ne(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),l={};return o&&(l.description=o),p&&(l.type=Yr(r)),d.length&&(l.examples=d.slice()),l},Lt=({schema:e,...t})=>K.default.fail(new I({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Nt=(e,t)=>{if((0,_.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,c.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,c.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Nt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Nt(o,t))),r},Xr=e=>(0,_.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),eo=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:l,statusCode:u,description:m=`${e.toUpperCase()} ${t} ${Rt(i)} response ${l?u:""}`.trim()})=>{let y=Xr(se({schema:r,isResponse:!0,rules:Mt,onEach:vt,onMissing:Lt,serializer:s,getRef:a,makeRef:p,path:t,method:e})),T={schema:d==="components"?p(M(m),y):y,examples:Jr(r,!0)};return{description:m,content:(0,c.fromPairs)((0,c.xprod)(o,[T]))}},Cn=()=>({type:"http",scheme:"basic"}),In=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},wn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},En=({name:e})=>({type:"apiKey",in:"header",name:e}),zn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Zn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Nn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),to=(e,t)=>{let r={basic:Cn,bearer:In,input:wn,header:En,cookie:zn,openid:Zn,oauth2:Nn};return Xe(e,o=>r[o.type](o,t))},dt=e=>"or"in e?e.or.map(t=>"and"in t?(0,c.mergeAll)((0,c.map)(({name:r,scopes:o})=>(0,c.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?dt(Ct(e)):dt({or:[e]}),ro=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let l=$r(t),u=Xr(Nt(se({schema:r,isResponse:!1,rules:Mt,onEach:vt,onMissing:Lt,serializer:i,getRef:s,makeRef:a,path:t,method:e}),l)),m={schema:p==="components"?a(M(d),u):u,examples:Jr(r,!1,l)};return{description:d,content:(0,c.fromPairs)((0,c.xprod)(o,[m]))}},oo=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Dt=e=>e.length<=Kr?e:e.slice(0,Kr-1)+"\u2026";var ct=class extends io.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||M(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&no.default.fail(new I({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:l=Ve}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});ie({routing:t,onEndpoint:(m,y,T)=>{let S=T,A={path:y,method:S,endpoint:m,composition:d,serializer:l,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[x,O]=["short","long"].map(m.getDescription.bind(m)),Pe=x?Dt(x):p&&O?Dt(O):void 0,He=m.getTags(),Ce=r.inputSources?.[S]||xt[S],pe=this.ensureUniqOperationId(y,S,m.getOperationId(S)),Fe=Wr({...A,inputSources:Ce,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:y,operationId:pe})}),Ke={};for(let k of["positive","negative"]){let Q=m.getResponses(k);for(let{mimeTypes:Ie,schema:P,statusCodes:C}of Q)for(let w of C)Ke[w]=eo({...A,variant:k,schema:P,mimeTypes:Ie,statusCode:w,hasMultipleStatusCodes:Q.length>1||C.length>1,description:a?.[`${k}Response`]?.call(null,{method:S,path:y,operationId:pe,statusCode:w})})}let ht=Ce.includes("body")?ro({...A,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:S,path:y,operationId:pe})}):void 0,Be=dt(Xe(to(m.getSecurity(),Ce),k=>{let Q=this.ensureUniqSecuritySchemaName(k),Ie=["oauth2","openIdConnect"].includes(k.type)?m.getScopes().slice():[];return this.addSecurityScheme(Q,k),{name:Q,scopes:Ie}}));this.addPath(_r(y),{[S]:{operationId:pe,summary:Pe,description:O,tags:He.length>0?He:void 0,parameters:Fe.length>0?Fe:void 0,requestBody:ht,security:Be.length>0?Be:void 0,responses:Ke}})}}),this.rootDoc.tags=r.tags?oo(r.tags):[]}};var kt=R(require("http"),1);var Mn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N.json),...t}),vn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},Ln=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),so=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await Ir([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Mn({fnMethod:a,requestProps:t}),d=vn({fnMethod:a,responseProps:r}),l=Ln({fnMethod:a,loggerProps:i}),u={cors:!1,logger:l,...o};return await e.execute({request:p,response:d,config:u,logger:l}),{requestMock:p,responseMock:d,loggerMock:l}};var z=R(require("typescript"),1);var D=R(require("typescript"),1),Re=require("ramda"),n=D.default.factory,G=[n.createModifier(D.default.SyntaxKind.ExportKeyword)],Dn=[n.createModifier(D.default.SyntaxKind.AsyncKeyword)],kn=[n.createModifier(D.default.SyntaxKind.PublicKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],ao=[n.createModifier(D.default.SyntaxKind.ProtectedKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],jt=n.createTemplateHead(""),Oe=n.createTemplateTail(""),Ut=n.createTemplateMiddle(" "),Ht=e=>n.createTemplateLiteralType(jt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Oe:Ut))),Ft=Ht(["M","P"]),lt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),mt=(e,t)=>(0,Re.chain)(([r,o])=>[lt(n.createIdentifier(r),o,t)],(0,Re.toPairs)(e)),Kt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),po=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),co=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),Y=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],D.default.NodeFlags.Const),Bt=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ut=(e,t)=>n.createTypeAliasDeclaration(G,e,void 0,t),lo=(e,t,r)=>n.createPropertyDeclaration(kn,e,void 0,t,r),mo=(e,t,r)=>n.createClassDeclaration(G,e,void 0,void 0,[t,...r]),uo=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),fo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.default.SyntaxKind.AnyKeyword)]),yo=(e,t,r)=>n.createInterfaceDeclaration(G,e,void 0,t,r),go=e=>(0,Re.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Re.toPairs)(e)),qt=(e,t,r)=>n.createArrowFunction(r?Dn:void 0,void 0,e.map(o=>lt(o)),void 0,void 0,t),Vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,mt({acc:void 0,key:void 0}),void 0,void 0,t),r]),ho=(...e)=>`"${e.join(" ")}"`;var xo=["get","post","put","delete","patch"];var h=R(require("typescript"),1),yt=require("zod");var B=R(require("typescript"),1),{factory:ft}=B.default,$t=(e,t)=>{B.default.addSyntheticLeadingComment(e,B.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ae=(e,t,r)=>{let o=ft.createTypeAliasDeclaration(void 0,ft.createIdentifier(t),void 0,e);return r&&$t(o,r),o},_t=(e,t)=>{let r=B.default.createSourceFile("print.ts","",B.default.ScriptTarget.Latest,!1,B.default.ScriptKind.TS);return B.default.createPrinter(t).printNode(B.default.EmitHint.Unspecified,e,r)},jn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,bo=e=>jn.test(e)?ft.createIdentifier(e):ft.createStringLiteral(e);var{factory:f}=h.default,Un={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Hn=({schema:{value:e}})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),Fn=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ne(a)?a instanceof yt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,bo(s),p&&o?f.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&$t(d,a.description),d});return f.createTypeLiteralNode(i)},Kn=({schema:{element:e},next:t})=>f.createArrayTypeNode(t(e)),Bn=({schema:{options:e}})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),To=({schema:{options:e},next:t})=>f.createUnionTypeNode(e.map(t)),qn=e=>Un?.[e.kind],Vn=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=$e(e,qn(o)),a={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||h.default.SyntaxKind.AnyKeyword)}return o},$n=({schema:e})=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),_n=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},Gn=({next:e,schema:t})=>f.createUnionTypeNode([e(t.unwrap()),f.createLiteralTypeNode(f.createNull())]),Yn=({next:e,schema:{items:t,_def:{rest:r}}})=>f.createTupleTypeNode(t.map(e).concat(r===null?[]:f.createRestTypeNode(e(r)))),Qn=({next:e,schema:{keySchema:t,valueSchema:r}})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[t,r].map(e)),Jn=({next:e,schema:t})=>f.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Wn=({next:e,schema:t})=>e(t._def.innerType),ae=e=>()=>f.createKeywordTypeNode(e),Xn=({next:e,schema:t})=>e(t.unwrap()),ei=({next:e,schema:t})=>e(t._def.innerType),ti=({next:e,schema:t})=>e(t._def.innerType),ri=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),oi=()=>f.createLiteralTypeNode(f.createNull()),ni=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,f.createLiteralTypeNode(f.createNull())),t(s,r(i.schema)))},ii=({schema:e})=>{let t=e.unwrap(),r=f.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),i=f.createUnionTypeNode([r,o]);return t instanceof yt.z.ZodString?r:t instanceof yt.z.ZodUnion?i:o},si=({next:e,schema:t})=>e(t.unwrap().shape.raw),ai={ZodString:ae(h.default.SyntaxKind.StringKeyword),ZodNumber:ae(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ae(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ae(h.default.SyntaxKind.BooleanKeyword),ZodAny:ae(h.default.SyntaxKind.AnyKeyword),[ke]:ae(h.default.SyntaxKind.StringKeyword),[je]:ae(h.default.SyntaxKind.StringKeyword),ZodNull:oi,ZodArray:Kn,ZodTuple:Yn,ZodRecord:Qn,ZodObject:Fn,ZodLiteral:Hn,ZodIntersection:Jn,ZodUnion:To,ZodDefault:Wn,ZodEnum:Bn,ZodNativeEnum:$n,ZodEffects:Vn,ZodOptional:_n,ZodNullable:Gn,ZodDiscriminatedUnion:To,ZodBranded:Xn,ZodCatch:ti,ZodPipeline:ri,ZodLazy:ni,ZodReadonly:ei,[$]:ii,[te]:si},Ue=({schema:e,...t})=>se({schema:e,rules:ai,onMissing:()=>f.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),...t});var gt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ae(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=Ve,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){ie({routing:t,onEndpoint:(P,C,w)=>{let de={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},we=M(w,C,"input"),Ee=Ue({...de,schema:P.getSchema("input"),isResponse:!1}),Z=i?M(w,C,"positive.response"):void 0,Gt=P.getSchema("positive"),Yt=i?Ue({...de,isResponse:!0,schema:Gt}):void 0,ze=i?M(w,C,"negative.response"):void 0,Qt=P.getSchema("negative"),Jt=i?Ue({...de,isResponse:!0,schema:Qt}):void 0,Wt=M(w,C,"response"),Ro=Z&&ze?n.createUnionTypeNode([n.createTypeReferenceNode(Z),n.createTypeReferenceNode(ze)]):Ue({...de,isResponse:!0,schema:Gt.or(Qt)});this.program.push(Ae(Ee,we)),Yt&&Z&&this.program.push(Ae(Yt,Z)),Jt&&ze&&this.program.push(Ae(Jt,ze)),this.program.push(Ae(Ro,Wt)),w!=="options"&&(this.paths.push(C),this.registry.set({method:w,path:C},{input:we,positive:Z,negative:ze,response:Wt,isJson:P.getMimeTypes("positive").includes(N.json),tags:P.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Bt(this.ids.pathType,this.paths)),this.program.push(Bt(this.ids.methodType,xo)),this.program.push(ut(this.ids.methodPathType,Ht([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.default.SyntaxKind.ExtendsKeyword,[Kt(this.ids.methodPathType,z.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:P,path:C},{isJson:w,tags:de,...we}]of this.registry){let Ee=ho(P,C);for(let Z of this.interfaces)Z.kind in we&&Z.props.push(co(Ee,we[Z.kind]));r!=="types"&&(w&&p.push(n.createPropertyAssignment(Ee,n.createTrue())),d.push(n.createPropertyAssignment(Ee,n.createArrayLiteralExpression(de.map(Z=>n.createStringLiteral(Z))))))}for(let{id:P,props:C}of this.interfaces)this.program.push(yo(P,a,C));if(r==="types")return;let l=n.createVariableStatement(G,Y(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),u=n.createVariableStatement(G,Y(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),m=ut(this.ids.providerType,n.createFunctionTypeNode(go({M:this.ids.methodType,P:this.ids.pathType}),mt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Ft)}),uo(this.ids.responseInterface,Ft))),y=ut(this.ids.implementationType,n.createFunctionTypeNode(void 0,mt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.default.SyntaxKind.StringKeyword),params:Kt(z.default.SyntaxKind.StringKeyword,z.default.SyntaxKind.AnyKeyword)}),fo())),T=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Oe)]),S=Vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[T,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),A=Vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[T]),z.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),x=mo(this.ids.clientClass,po([lt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),ao)]),[lo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,S,A]),!0))]);this.program.push(l,u,m,y,x);let O=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Pe=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(N.json))]),void 0,this.ids.undefinedValue)),He=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),Ce=n.createVariableStatement(void 0,Y(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Oe)]),n.createObjectLiteralExpression([O,Pe,He])])))),pe=n.createVariableStatement(void 0,Y(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Fe=n.createVariableStatement(void 0,Y(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Oe)])))),[Ke,ht]=["json","text"].map(P=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,P),void 0,void 0))),Be=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(jt,[n.createTemplateSpan(this.ids.methodParameter,Ut),n.createTemplateSpan(this.ids.pathParameter,Oe)]),z.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Ke])),k=n.createVariableStatement(G,Y(this.ids.exampleImplementationConst,qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([pe,Fe,Ce,Be,ht]),!0),n.createTypeReferenceNode(this.ids.implementationType))),Q=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),Ie=n.createVariableStatement(void 0,Y(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(k,Ie,Q)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
21
- `):void 0}print(t){let r=this.printUsage(t),o=r&&z.default.addSyntheticLeadingComment(z.default.addSyntheticLeadingComment(n.createEmptyStatement(),z.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),z.default.SyntaxKind.MultiLineCommentTrivia,`
19
+ `).map((d,c)=>a[c]?a[c](d):d).join(`
20
+ `)};var jr=e=>{e.startupLogo!==!1&&console.log(vr());let t=e.errorHandler||ge,r=Cr(e.logger)?st(e.logger):e.logger;r.debug("Running","v19.1.0 (CJS)");let o=Mr({rootLogger:r,config:e}),i=zr({rootLogger:r,errorHandler:t}),s=Er({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=jr(e);return Nt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Hr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=jr(e),a=(0,at.default)().disable("x-powered-by").use(s);if(e.server.compression){let m=await ie("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||at.default.json()],raw:[e.server.rawParser||at.default.raw(),Nr],upload:e.server.upload?await Zr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Nt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(m,y)=>m.listen(y,()=>{r.info("Listening",y)}),c={httpServer:d(Dr.default.createServer(a),e.server.listen),httpsServer:e.https?d(Lr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...c,logger:r}};var io=R(require("assert/strict"),1),so=require("openapi3-ts/oas31");var B=R(require("assert/strict"),1),_=require("openapi3-ts/oas31"),l=require("ramda"),S=require("zod");var Se=require("zod");var pt=e=>!isNaN(e.getTime());var ke=Symbol("DateIn"),Ur=()=>Se.z.union([Se.z.string().date(),Se.z.string().datetime(),Se.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Se.z.date().refine(pt)).brand(ke);var Fr=require("zod");var He=Symbol("DateOut"),Kr=()=>Fr.z.date().refine(pt).transform(e=>e.toISOString()).brand(He);var ae=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:c=>ae(c,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),d=t&&t(e,{prev:p,...i});return d?{...p,...d}:p};var Br=50,$r="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Fo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vr=/:([A-Za-z0-9_]+)/g,Gr=e=>e.match(Vr)?.map(t=>t.slice(1))||[],_r=e=>e.replace(Vr,t=>`{${t.slice(1)}}`),Ko=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Bo=({_def:{innerType:e}},{next:t})=>t(e),qo=()=>({format:"any"}),$o=({},e)=>((0,B.default)(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Vo=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Go=({options:e},{next:t})=>({oneOf:e.map(t)}),_o=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Yo=e=>{let[t,r]=e.filter(i=>!(0,_.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,B.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,l.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,l.concat)(i,s):i===s?s:B.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,l.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=te(t.examples||[],r.examples||[],([i,s])=>(0,l.mergeDeepRight)(i,s))),o},Qo=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Yo(o)}catch{}return{allOf:o}},Jo=(e,{next:t})=>t(e.unwrap()),Wo=(e,{next:t})=>t(e.unwrap()),Xo=(e,{next:t})=>{let r=t(e.unwrap());return(0,_.isReferenceObject)(r)||(r.type=Qr(r)),r},Yr=e=>{let t=(0,l.toLower)((0,l.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},qr=e=>({type:Yr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),en=({value:e})=>({type:Yr(e),const:e}),tn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Me(p)?p instanceof S.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=dt(e,r)),s.length&&(a.required=s),a},rn=()=>({type:"null"}),on=({},e)=>((0,B.default)(!e.isResponse,new P({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:$r}}),nn=({},e)=>((0,B.default)(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:$r}}),sn=({},e)=>B.default.fail(new P({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),an=()=>({type:"boolean"}),pn=()=>({type:"integer",format:"bigint"}),dn=e=>e.every(t=>t instanceof S.z.ZodLiteral),cn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=dt(S.z.object((0,l.fromPairs)((0,l.xprod)(o,[t]))),r),i.required=o),i}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:dt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&dn(e.options)){let o=(0,l.map)(s=>`${s.value}`,e.options),i=(0,l.fromPairs)((0,l.xprod)(o,[t]));return{type:"object",properties:dt(S.z.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},ln=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},mn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),un=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:y}})=>{let u=y.find(x=>x.kind==="regex"),b=y.find(x=>x.kind==="datetime"),E=u?u.regex:b?b.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,T={type:"string"},v={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let x in v)if(v[x]){T.format=x;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),E&&(T.pattern=E.source),T},fn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(({kind:y})=>y==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(({kind:y})=>y==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,c?m.maximum=d:m.exclusiveMaximum=d,m},dt=({shape:e},t)=>(0,l.map)(t,e),yn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Fo?.[t]},Qr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},gn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,_.isReferenceObject)(o)){let s=Ge(e,yn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.z.any())}if(!t&&i.type==="preprocess"&&!(0,_.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},hn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),xn=(e,{next:t})=>t(e.unwrap()),bn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},Tn=(e,{next:t})=>t(e.unwrap().shape.raw),Jr=e=>e.length?(0,l.fromPairs)((0,l.zip)((0,l.range)(1,e.length+1).map(t=>`example${t}`),(0,l.map)((0,l.objOf)("value"),e))):void 0,Wr=(e,t,r=[])=>(0,l.pipe)(F,(0,l.map)((0,l.when)((0,l.both)(K,(0,l.complement)(Array.isArray)),(0,l.omit)(r))),Jr)({schema:e,variant:t?"parsed":"original",validate:!0}),Sn=(e,t)=>(0,l.pipe)(F,(0,l.filter)((0,l.has)(t)),(0,l.pluck)(t),Jr)({schema:e,variant:"original",validate:!0}),Re=(e,t)=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?Re(e.unwrap(),t):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(r=>Re(r,t)).reduce((r,o)=>r.merge(o.partial()),S.z.object({})):e instanceof S.z.ZodEffects?((0,B.default)(e._def.effect.type==="refinement",t),Re(e._def.schema,t)):Re(e._def.left,t).merge(Re(e._def.right,t)),Xr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=Re(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),y=Gr(e),u=o.includes("query"),b=o.includes("params"),E=o.includes("headers"),T=x=>b&&y.includes(x),v=x=>E&&St(x);return Object.keys(m).filter(x=>u||T(x)).map(x=>{let j=ae(m[x],{rules:{...d,...vt},onEach:Dt,onMissing:Lt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),Ce=p==="components"?a(N(c,x),j):j;return{name:x,in:T(x)?"path":v(x)?"header":"query",required:!m[x].isOptional(),description:j.description||c,schema:Ce,examples:Sn(r,x)}})},vt={ZodString:un,ZodNumber:fn,ZodBigInt:pn,ZodBoolean:an,ZodNull:rn,ZodArray:ln,ZodTuple:mn,ZodRecord:cn,ZodObject:tn,ZodLiteral:en,ZodIntersection:Qo,ZodUnion:Go,ZodAny:qo,ZodDefault:Ko,ZodEnum:qr,ZodNativeEnum:qr,ZodEffects:gn,ZodOptional:Jo,ZodNullable:Xo,ZodDiscriminatedUnion:_o,ZodBranded:xn,ZodDate:sn,ZodCatch:Bo,ZodPipeline:hn,ZodLazy:bn,ZodReadonly:Wo,[G]:Vo,[Le]:$o,[He]:nn,[ke]:on,[re]:Tn},Dt=(e,{isResponse:t,prev:r})=>{if((0,_.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof S.z.ZodLazy,s=r.type!==void 0,a=t&&Me(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Qr(r)),d.length&&(c.examples=d.slice()),c},Lt=(e,t)=>B.default.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Mt=(e,t)=>{if((0,_.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,l.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,l.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Mt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Mt(o,t))),r},eo=e=>(0,_.isReferenceObject)(e)?e:(0,l.omit)(["examples"],e),to=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${Ot(i)} response ${c?m:""}`.trim()})=>{let b=eo(ae(r,{rules:{...y,...vt},onEach:Dt,onMissing:Lt,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),E={schema:d==="components"?p(N(u),b):b,examples:Wr(r,!0)};return{description:u,content:(0,l.fromPairs)((0,l.xprod)(o,[E]))}},Rn=()=>({type:"http",scheme:"basic"}),On=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},An=({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},Pn=({name:e})=>({type:"apiKey",in:"header",name:e}),Cn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),In=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),wn=({flows:e={}})=>({type:"oauth2",flows:(0,l.map)(t=>({...t,scopes:t.scopes||{}}),(0,l.reject)(l.isNil,e))}),ro=(e,t)=>{let r={basic:Rn,bearer:On,input:An,header:Pn,cookie:Cn,openid:In,oauth2:wn};return et(e,o=>r[o.type](o,t))},ct=e=>"or"in e?e.or.map(t=>"and"in t?(0,l.mergeAll)((0,l.map)(({name:r,scopes:o})=>(0,l.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?ct(It(e)):ct({or:[e]}),oo=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:c=`${e.toUpperCase()} ${t} Request body`})=>{let m=Gr(t),y=eo(Mt(ae(r,{rules:{...d,...vt},onEach:Dt,onMissing:Lt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),m)),u={schema:p==="components"?a(N(c),y):y,examples:Wr(r,!1,m)};return{description:c,content:(0,l.fromPairs)((0,l.xprod)(o,[u]))}},no=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),jt=e=>e.length<=Br?e:e.slice(0,Br-1)+"\u2026";var lt=class extends so.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||N(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&io.default.fail(new P({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:m=Ve}){super(),this.addInfo({title:o,version:i});for(let u of typeof s=="string"?[s]:s)this.addServer({url:u});se({routing:t,onEndpoint:(u,b,E)=>{let T=E,v={path:b,method:T,endpoint:u,composition:c,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[x,j]=["short","long"].map(u.getDescription.bind(u)),Ce=x?jt(x):d&&j?jt(j):void 0,Fe=u.getTags(),Ie=r.inputSources?.[T]||bt[T],de=this.ensureUniqOperationId(b,T,u.getOperationId(T)),Ke=Xr({...v,inputSources:Ie,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:b,operationId:de})}),Be={};for(let k of["positive","negative"]){let J=u.getResponses(k);for(let{mimeTypes:we,schema:O,statusCodes:A}of J)for(let C of A)Be[C]=to({...v,variant:k,schema:O,mimeTypes:we,statusCode:C,hasMultipleStatusCodes:J.length>1||A.length>1,description:a?.[`${k}Response`]?.call(null,{method:T,path:b,operationId:de,statusCode:C})})}let xt=Ie.includes("body")?oo({...v,schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:b,operationId:de})}):void 0,qe=ct(et(ro(u.getSecurity(),Ie),k=>{let J=this.ensureUniqSecuritySchemaName(k),we=["oauth2","openIdConnect"].includes(k.type)?u.getScopes().slice():[];return this.addSecurityScheme(J,k),{name:J,scopes:we}}));this.addPath(_r(b),{[T]:{operationId:de,summary:Ce,description:j,tags:Fe.length>0?Fe:void 0,parameters:Ke.length>0?Ke:void 0,requestBody:xt,security:qe.length>0?qe:void 0,responses:Be}})}}),this.rootDoc.tags=r.tags?no(r.tags):[]}};var kt=R(require("http"),1);var En=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>Z.json),...t}),zn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},Zn=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),ao=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await wr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=En({fnMethod:a,requestProps:t}),d=zn({fnMethod:a,responseProps:r}),c=Zn({fnMethod:a,loggerProps:i}),m={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:m,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};var w=R(require("typescript"),1);var L=R(require("typescript"),1),Oe=require("ramda"),n=L.default.factory,Y=[n.createModifier(L.default.SyntaxKind.ExportKeyword)],Nn=[n.createModifier(L.default.SyntaxKind.AsyncKeyword)],Mn=[n.createModifier(L.default.SyntaxKind.PublicKeyword),n.createModifier(L.default.SyntaxKind.ReadonlyKeyword)],po=[n.createModifier(L.default.SyntaxKind.ProtectedKeyword),n.createModifier(L.default.SyntaxKind.ReadonlyKeyword)],Ht=n.createTemplateHead(""),Ae=n.createTemplateTail(""),Ut=n.createTemplateMiddle(" "),Ft=e=>n.createTemplateLiteralType(Ht,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Ae:Ut))),Kt=Ft(["M","P"]),mt=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ut=(e,t)=>(0,Oe.chain)(([r,o])=>[mt(n.createIdentifier(r),o,t)],(0,Oe.toPairs)(e)),Bt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),co=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),lo=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),Q=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],L.default.NodeFlags.Const),qt=(e,t)=>n.createTypeAliasDeclaration(Y,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),ft=(e,t)=>n.createTypeAliasDeclaration(Y,e,void 0,t),mo=(e,t,r)=>n.createPropertyDeclaration(Mn,e,void 0,t,r),uo=(e,t,r)=>n.createClassDeclaration(Y,e,void 0,void 0,[t,...r]),fo=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),yo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(L.default.SyntaxKind.AnyKeyword)]),go=(e,t,r)=>n.createInterfaceDeclaration(Y,e,void 0,t,r),ho=e=>(0,Oe.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Oe.toPairs)(e)),$t=(e,t,r)=>n.createArrowFunction(r?Nn:void 0,void 0,e.map(o=>mt(o)),void 0,void 0,t),Vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,ut({acc:void 0,key:void 0}),void 0,void 0,t),r]),xo=(...e)=>`"${e.join(" ")}"`;var bo=["get","post","put","delete","patch"];var h=R(require("typescript"),1),gt=require("zod");var q=R(require("typescript"),1),{factory:yt}=q.default,Gt=(e,t)=>{q.default.addSyntheticLeadingComment(e,q.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Pe=(e,t,r)=>{let o=yt.createTypeAliasDeclaration(void 0,yt.createIdentifier(t),void 0,e);return r&&Gt(o,r),o},_t=(e,t)=>{let r=q.default.createSourceFile("print.ts","",q.default.ScriptTarget.Latest,!1,q.default.ScriptKind.TS);return q.default.createPrinter(t).printNode(q.default.EmitHint.Unspecified,e,r)},vn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,To=e=>vn.test(e)?yt.createIdentifier(e):yt.createStringLiteral(e);var{factory:f}=h.default,Dn={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Ln=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),jn=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Me(a)?a instanceof gt.z.ZodOptional:a.isOptional(),d=f.createPropertySignature(void 0,To(s),p&&o?f.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Gt(d,a.description),d});return f.createTypeLiteralNode(i)},kn=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),Hn=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),So=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),Un=e=>Dn?.[e.kind],Fn=(e,{next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=Ge(e,Un(o)),a={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||h.default.SyntaxKind.AnyKeyword)}return o},Kn=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),Bn=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},qn=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),$n=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),Vn=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),Gn=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),_n=({_def:e},{next:t})=>t(e.innerType),pe=e=>()=>f.createKeywordTypeNode(e),Yn=(e,{next:t})=>t(e.unwrap()),Qn=(e,{next:t})=>t(e.unwrap()),Jn=({_def:e},{next:t})=>t(e.innerType),Wn=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Xn=()=>f.createLiteralTypeNode(f.createNull()),ei=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,f.createLiteralTypeNode(f.createNull())),r(s,o(e)))},ti=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),i=f.createUnionTypeNode([r,o]);return t instanceof gt.z.ZodString?r:t instanceof gt.z.ZodUnion?i:o},ri=(e,{next:t})=>t(e.unwrap().shape.raw),oi={ZodString:pe(h.default.SyntaxKind.StringKeyword),ZodNumber:pe(h.default.SyntaxKind.NumberKeyword),ZodBigInt:pe(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:pe(h.default.SyntaxKind.BooleanKeyword),ZodAny:pe(h.default.SyntaxKind.AnyKeyword),[ke]:pe(h.default.SyntaxKind.StringKeyword),[He]:pe(h.default.SyntaxKind.StringKeyword),ZodNull:Xn,ZodArray:kn,ZodTuple:$n,ZodRecord:Vn,ZodObject:jn,ZodLiteral:Ln,ZodIntersection:Gn,ZodUnion:So,ZodDefault:_n,ZodEnum:Hn,ZodNativeEnum:Kn,ZodEffects:Fn,ZodOptional:Bn,ZodNullable:qn,ZodDiscriminatedUnion:So,ZodBranded:Yn,ZodCatch:Jn,ZodPipeline:Wn,ZodLazy:ei,ZodReadonly:Qn,[G]:ti,[re]:ri},Ue=(e,{brandHandling:t,ctx:r})=>ae(e,{rules:{...t,...oi},onMissing:()=>f.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),ctx:r});var ht=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Pe(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=Ve,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){se({routing:t,onEndpoint:(O,A,C)=>{let ce={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Ee=N(C,A,"input"),ze=Ue(O.getSchema("input"),{brandHandling:r,ctx:{...ce,isResponse:!1}}),z=s?N(C,A,"positive.response"):void 0,Yt=O.getSchema("positive"),Qt=s?Ue(Yt,{brandHandling:r,ctx:{...ce,isResponse:!0}}):void 0,Ze=s?N(C,A,"negative.response"):void 0,Jt=O.getSchema("negative"),Wt=s?Ue(Jt,{brandHandling:r,ctx:{...ce,isResponse:!0}}):void 0,Xt=N(C,A,"response"),Oo=z&&Ze?n.createUnionTypeNode([n.createTypeReferenceNode(z),n.createTypeReferenceNode(Ze)]):Ue(Yt.or(Jt),{brandHandling:r,ctx:{...ce,isResponse:!0}});this.program.push(Pe(ze,Ee)),Qt&&z&&this.program.push(Pe(Qt,z)),Wt&&Ze&&this.program.push(Pe(Wt,Ze)),this.program.push(Pe(Oo,Xt)),C!=="options"&&(this.paths.push(A),this.registry.set({method:C,path:A},{input:Ee,positive:z,negative:Ze,response:Xt,isJson:O.getMimeTypes("positive").includes(Z.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(qt(this.ids.pathType,this.paths)),this.program.push(qt(this.ids.methodType,bo)),this.program.push(ft(this.ids.methodPathType,Ft([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(w.default.SyntaxKind.ExtendsKeyword,[Bt(this.ids.methodPathType,w.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:O,path:A},{isJson:C,tags:ce,...Ee}]of this.registry){let ze=xo(O,A);for(let z of this.interfaces)z.kind in Ee&&z.props.push(lo(ze,Ee[z.kind]));o!=="types"&&(C&&d.push(n.createPropertyAssignment(ze,n.createTrue())),c.push(n.createPropertyAssignment(ze,n.createArrayLiteralExpression(ce.map(z=>n.createStringLiteral(z))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(go(O,p,A));if(o==="types")return;let m=n.createVariableStatement(Y,Q(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(d))),y=n.createVariableStatement(Y,Q(this.ids.endpointTagsConst,n.createObjectLiteralExpression(c))),u=ft(this.ids.providerType,n.createFunctionTypeNode(ho({M:this.ids.methodType,P:this.ids.pathType}),ut({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Kt)}),fo(this.ids.responseInterface,Kt))),b=ft(this.ids.implementationType,n.createFunctionTypeNode(void 0,ut({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(w.default.SyntaxKind.StringKeyword),params:Bt(w.default.SyntaxKind.StringKeyword,w.default.SyntaxKind.AnyKeyword)}),yo())),E=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Ae)]),T=Vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[E,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),v=Vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[E]),w.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),x=uo(this.ids.clientClass,co([mt(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),po)]),[mo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),$t([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,v]),!0))]);this.program.push(m,y,u,b,x);let j=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ce=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(Z.json))]),void 0,this.ids.undefinedValue)),Fe=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),Ie=n.createVariableStatement(void 0,Q(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Ae)]),n.createObjectLiteralExpression([j,Ce,Fe])])))),de=n.createVariableStatement(void 0,Q(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ke=n.createVariableStatement(void 0,Q(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Ae)])))),[Be,xt]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),qe=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ht,[n.createTemplateSpan(this.ids.methodParameter,Ut),n.createTemplateSpan(this.ids.pathParameter,Ae)]),w.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Be])),k=n.createVariableStatement(Y,Q(this.ids.exampleImplementationConst,$t([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([de,Ke,Ie,qe,xt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),J=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),we=n.createVariableStatement(void 0,Q(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(k,we,J)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
21
+ `):void 0}print(t){let r=this.printUsage(t),o=r&&w.default.addSyntheticLeadingComment(w.default.addSyntheticLeadingComment(n.createEmptyStatement(),w.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),w.default.SyntaxKind.MultiLineCommentTrivia,`
22
22
  ${r}`);return this.program.concat(o||[]).map((i,s)=>_t(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
23
23
 
24
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await ne("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var So={dateIn:Ur,dateOut:Fr,file:Ye,upload:mr,raw:cr};0&&(module.exports={AbstractEndpoint,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,InputValidationError,Integration,MissingPeerError,OutputValidationError,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createLogger,createMiddleware,createResultHandler,createServer,defaultEndpointsFactory,defaultResultHandler,ez,getExamples,getMessageFromError,getStatusCodeFromError,testEndpoint});
24
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await ie("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var Ro={dateIn:Ur,dateOut:Kr,file:Qe,upload:ur,raw:lr};0&&(module.exports={AbstractEndpoint,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,InputValidationError,Integration,MissingPeerError,OutputValidationError,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createLogger,createMiddleware,createResultHandler,createServer,defaultEndpointsFactory,defaultResultHandler,ez,getExamples,getMessageFromError,getStatusCodeFromError,testEndpoint});
package/dist/index.d.cts CHANGED
@@ -10,7 +10,7 @@ import { ListenOptions } from 'node:net';
10
10
  import * as qs from 'qs';
11
11
  import * as express_serve_static_core from 'express-serve-static-core';
12
12
  import http from 'node:http';
13
- import { OpenApiBuilder, SecuritySchemeType, SchemaObject, ReferenceObject, SecuritySchemeObject } from 'openapi3-ts/oas31';
13
+ import { ReferenceObject, SchemaObject, OpenApiBuilder, SecuritySchemeType, SecuritySchemeObject } from 'openapi3-ts/oas31';
14
14
  import ts from 'typescript';
15
15
 
16
16
  declare const metaSymbol: unique symbol;
@@ -590,41 +590,38 @@ declare const createServer: (config: ServerConfig, routing: Routing) => Promise<
590
590
  app: express_serve_static_core.Express;
591
591
  }>;
592
592
 
593
- type Component = "positiveResponse" | "negativeResponse" | "requestParameter" | "requestBody";
594
- /** @desc user defined function that creates a component description from its properties */
595
- type Descriptor = (props: Record<"method" | "path" | "operationId", string> & {
596
- statusCode?: number;
597
- }) => string;
598
- interface DocumentationParams {
599
- title: string;
600
- version: string;
601
- serverUrl: string | [string, ...string[]];
602
- routing: Routing;
603
- config: CommonConfig;
604
- /**
605
- * @desc Descriptions of various components based on their properties (method, path, operationId).
606
- * @desc When composition set to "components", component name is generated from this description
607
- * @default () => `${method} ${path} ${component}`
608
- * */
609
- descriptions?: Partial<Record<Component, Descriptor>>;
610
- /** @default true */
611
- hasSummaryFromDescription?: boolean;
612
- /** @default inline */
613
- composition?: "inline" | "components";
614
- /**
615
- * @desc Used for comparing schemas wrapped into z.lazy() to limit the recursion
616
- * @default JSON.stringify() + SHA1 hash as a hex digest
617
- * */
618
- serializer?: (schema: z.ZodTypeAny) => string;
593
+ /** @desc An error related to the wrong Routing declaration */
594
+ declare class RoutingError extends Error {
595
+ name: string;
619
596
  }
620
- declare class Documentation extends OpenApiBuilder {
621
- protected lastSecuritySchemaIds: Map<SecuritySchemeType, number>;
622
- protected lastOperationIdSuffixes: Map<string, number>;
623
- protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;
624
- protected getRef(name: string): ReferenceObject | undefined;
625
- protected ensureUniqOperationId(path: string, method: Method, userDefined?: string): string;
626
- protected ensureUniqSecuritySchemaName(subject: SecuritySchemeObject): string;
627
- constructor({ routing, config, title, version, serverUrl, descriptions, hasSummaryFromDescription, composition, serializer, }: DocumentationParams);
597
+ /**
598
+ * @desc An error related to the generating of the documentation
599
+ * */
600
+ declare class DocumentationError extends Error {
601
+ name: string;
602
+ constructor({ message, method, path, isResponse, }: {
603
+ message: string;
604
+ } & Pick<OpenAPIContext, "path" | "method" | "isResponse">);
605
+ }
606
+ /** @desc An error related to the input and output schemas declaration */
607
+ declare class IOSchemaError extends Error {
608
+ name: string;
609
+ }
610
+ /** @desc An error of validating the Endpoint handler's returns against the Endpoint output schema */
611
+ declare class OutputValidationError extends IOSchemaError {
612
+ name: string;
613
+ readonly originalError: ZodError;
614
+ constructor(originalError: ZodError);
615
+ }
616
+ /** @desc An error of validating the input sources against the Middleware or Endpoint input schema */
617
+ declare class InputValidationError extends IOSchemaError {
618
+ name: string;
619
+ readonly originalError: ZodError;
620
+ constructor(originalError: ZodError);
621
+ }
622
+ declare class MissingPeerError extends Error {
623
+ name: string;
624
+ constructor(module: string | string[]);
628
625
  }
629
626
 
630
627
  declare const variants: {
@@ -656,6 +653,19 @@ declare const ez: {
656
653
  }, S>>[k_1]; } : never>, symbol>;
657
654
  };
658
655
 
656
+ interface VariantDependingProps<U> {
657
+ regular: {
658
+ next: (schema: z.ZodTypeAny) => U;
659
+ };
660
+ each: {
661
+ prev: U;
662
+ };
663
+ last: {};
664
+ }
665
+ type HandlingVariant = keyof VariantDependingProps<unknown>;
666
+ type SchemaHandler<U, Context extends FlatObject = {}, Variant extends HandlingVariant = "regular"> = (schema: any, ctx: Context & VariantDependingProps<U>[Variant]) => U;
667
+ type HandlingRules<U, Context extends FlatObject = {}, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
668
+
659
669
  interface OpenAPIContext extends FlatObject {
660
670
  isResponse: boolean;
661
671
  serializer: (schema: z.ZodTypeAny) => string;
@@ -664,39 +674,50 @@ interface OpenAPIContext extends FlatObject {
664
674
  path: string;
665
675
  method: Method;
666
676
  }
677
+ type Depicter = SchemaHandler<SchemaObject | ReferenceObject, OpenAPIContext>;
667
678
 
668
- /** @desc An error related to the wrong Routing declaration */
669
- declare class RoutingError extends Error {
670
- name: string;
671
- }
672
- /**
673
- * @desc An error related to the generating of the documentation
674
- * */
675
- declare class DocumentationError extends Error {
676
- name: string;
677
- constructor({ message, method, path, isResponse, }: {
678
- message: string;
679
- } & Pick<OpenAPIContext, "path" | "method" | "isResponse">);
680
- }
681
- /** @desc An error related to the input and output schemas declaration */
682
- declare class IOSchemaError extends Error {
683
- name: string;
684
- }
685
- /** @desc An error of validating the Endpoint handler's returns against the Endpoint output schema */
686
- declare class OutputValidationError extends IOSchemaError {
687
- name: string;
688
- readonly originalError: ZodError;
689
- constructor(originalError: ZodError);
690
- }
691
- /** @desc An error of validating the input sources against the Middleware or Endpoint input schema */
692
- declare class InputValidationError extends IOSchemaError {
693
- name: string;
694
- readonly originalError: ZodError;
695
- constructor(originalError: ZodError);
679
+ type Component = "positiveResponse" | "negativeResponse" | "requestParameter" | "requestBody";
680
+ /** @desc user defined function that creates a component description from its properties */
681
+ type Descriptor = (props: Record<"method" | "path" | "operationId", string> & {
682
+ statusCode?: number;
683
+ }) => string;
684
+ interface DocumentationParams {
685
+ title: string;
686
+ version: string;
687
+ serverUrl: string | [string, ...string[]];
688
+ routing: Routing;
689
+ config: CommonConfig;
690
+ /**
691
+ * @desc Descriptions of various components based on their properties (method, path, operationId).
692
+ * @desc When composition set to "components", component name is generated from this description
693
+ * @default () => `${method} ${path} ${component}`
694
+ * */
695
+ descriptions?: Partial<Record<Component, Descriptor>>;
696
+ /** @default true */
697
+ hasSummaryFromDescription?: boolean;
698
+ /** @default inline */
699
+ composition?: "inline" | "components";
700
+ /**
701
+ * @desc Used for comparing schemas wrapped into z.lazy() to limit the recursion
702
+ * @default JSON.stringify() + SHA1 hash as a hex digest
703
+ * */
704
+ serializer?: (schema: z.ZodTypeAny) => string;
705
+ /**
706
+ * @desc Handling rules for your own branded schemas.
707
+ * @desc Keys: brands (recommended to use unique symbols).
708
+ * @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
709
+ * @example { MyBrand: ( schema: typeof myBrandSchema, { next } ) => ({ type: "object" })
710
+ */
711
+ brandHandling?: HandlingRules<SchemaObject | ReferenceObject, OpenAPIContext>;
696
712
  }
697
- declare class MissingPeerError extends Error {
698
- name: string;
699
- constructor(module: string | string[]);
713
+ declare class Documentation extends OpenApiBuilder {
714
+ protected lastSecuritySchemaIds: Map<SecuritySchemeType, number>;
715
+ protected lastOperationIdSuffixes: Map<string, number>;
716
+ protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;
717
+ protected getRef(name: string): ReferenceObject | undefined;
718
+ protected ensureUniqOperationId(path: string, method: Method, userDefined?: string): string;
719
+ protected ensureUniqSecuritySchemaName(subject: SecuritySchemeObject): string;
720
+ constructor({ routing, config, title, version, serverUrl, descriptions, brandHandling, hasSummaryFromDescription, composition, serializer, }: DocumentationParams);
700
721
  }
701
722
 
702
723
  type LocalResponse = Response<unknown, {
@@ -758,6 +779,18 @@ declare const testEndpoint: <LOG extends Record<string, any>, REQ extends Record
758
779
  loggerMock: Record<"error" | "info" | "debug" | "warn", MockOverrides> & LOG;
759
780
  }>;
760
781
 
782
+ interface ZTSContext extends FlatObject {
783
+ isResponse: boolean;
784
+ getAlias: (name: string) => ts.TypeReferenceNode | undefined;
785
+ makeAlias: (name: string, type: ts.TypeNode) => ts.TypeReferenceNode;
786
+ serializer: (schema: z.ZodTypeAny) => string;
787
+ optionalPropStyle: {
788
+ withQuestionMark?: boolean;
789
+ withUndefined?: boolean;
790
+ };
791
+ }
792
+ type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
793
+
761
794
  type IOKind = "input" | "response" | "positive" | "negative";
762
795
  interface IntegrationParams {
763
796
  routing: Routing;
@@ -794,6 +827,13 @@ interface IntegrationParams {
794
827
  */
795
828
  withUndefined?: boolean;
796
829
  };
830
+ /**
831
+ * @desc Handling rules for your own branded schemas.
832
+ * @desc Keys: brands (recommended to use unique symbols).
833
+ * @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
834
+ * @example { MyBrand: ( schema: typeof myBrandSchema, { next } ) => createKeywordTypeNode(SyntaxKind.AnyKeyword)
835
+ */
836
+ brandHandling?: HandlingRules<ts.TypeNode, ZTSContext>;
797
837
  }
798
838
  interface FormattedPrintingOptions {
799
839
  /** @desc Typescript printer options */
@@ -852,10 +892,10 @@ declare class Integration {
852
892
  }>;
853
893
  protected getAlias(name: string): ts.TypeReferenceNode | undefined;
854
894
  protected makeAlias(name: string, type: ts.TypeNode): ts.TypeReferenceNode;
855
- constructor({ routing, variant, serializer, splitResponse, optionalPropStyle, }: IntegrationParams);
895
+ constructor({ routing, brandHandling, variant, serializer, splitResponse, optionalPropStyle, }: IntegrationParams);
856
896
  protected printUsage(printerOptions?: ts.PrinterOptions): string | undefined;
857
897
  print(printerOptions?: ts.PrinterOptions): string;
858
898
  printFormatted({ printerOptions, format: userDefined, }?: FormattedPrintingOptions): Promise<string>;
859
899
  }
860
900
 
861
- export { AbstractEndpoint, type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, type MiddlewareDefinition, MissingPeerError, type MockOverrides, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type ResultHandlerDefinition, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createLogger, createMiddleware, createResultHandler, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
901
+ export { AbstractEndpoint, type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, type MiddlewareDefinition, MissingPeerError, type MockOverrides, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, type ResultHandlerDefinition, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createLogger, createMiddleware, createResultHandler, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ import { ListenOptions } from 'node:net';
10
10
  import * as qs from 'qs';
11
11
  import * as express_serve_static_core from 'express-serve-static-core';
12
12
  import http from 'node:http';
13
- import { OpenApiBuilder, SecuritySchemeType, SchemaObject, ReferenceObject, SecuritySchemeObject } from 'openapi3-ts/oas31';
13
+ import { ReferenceObject, SchemaObject, OpenApiBuilder, SecuritySchemeType, SecuritySchemeObject } from 'openapi3-ts/oas31';
14
14
  import ts from 'typescript';
15
15
 
16
16
  declare const metaSymbol: unique symbol;
@@ -590,41 +590,38 @@ declare const createServer: (config: ServerConfig, routing: Routing) => Promise<
590
590
  app: express_serve_static_core.Express;
591
591
  }>;
592
592
 
593
- type Component = "positiveResponse" | "negativeResponse" | "requestParameter" | "requestBody";
594
- /** @desc user defined function that creates a component description from its properties */
595
- type Descriptor = (props: Record<"method" | "path" | "operationId", string> & {
596
- statusCode?: number;
597
- }) => string;
598
- interface DocumentationParams {
599
- title: string;
600
- version: string;
601
- serverUrl: string | [string, ...string[]];
602
- routing: Routing;
603
- config: CommonConfig;
604
- /**
605
- * @desc Descriptions of various components based on their properties (method, path, operationId).
606
- * @desc When composition set to "components", component name is generated from this description
607
- * @default () => `${method} ${path} ${component}`
608
- * */
609
- descriptions?: Partial<Record<Component, Descriptor>>;
610
- /** @default true */
611
- hasSummaryFromDescription?: boolean;
612
- /** @default inline */
613
- composition?: "inline" | "components";
614
- /**
615
- * @desc Used for comparing schemas wrapped into z.lazy() to limit the recursion
616
- * @default JSON.stringify() + SHA1 hash as a hex digest
617
- * */
618
- serializer?: (schema: z.ZodTypeAny) => string;
593
+ /** @desc An error related to the wrong Routing declaration */
594
+ declare class RoutingError extends Error {
595
+ name: string;
619
596
  }
620
- declare class Documentation extends OpenApiBuilder {
621
- protected lastSecuritySchemaIds: Map<SecuritySchemeType, number>;
622
- protected lastOperationIdSuffixes: Map<string, number>;
623
- protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;
624
- protected getRef(name: string): ReferenceObject | undefined;
625
- protected ensureUniqOperationId(path: string, method: Method, userDefined?: string): string;
626
- protected ensureUniqSecuritySchemaName(subject: SecuritySchemeObject): string;
627
- constructor({ routing, config, title, version, serverUrl, descriptions, hasSummaryFromDescription, composition, serializer, }: DocumentationParams);
597
+ /**
598
+ * @desc An error related to the generating of the documentation
599
+ * */
600
+ declare class DocumentationError extends Error {
601
+ name: string;
602
+ constructor({ message, method, path, isResponse, }: {
603
+ message: string;
604
+ } & Pick<OpenAPIContext, "path" | "method" | "isResponse">);
605
+ }
606
+ /** @desc An error related to the input and output schemas declaration */
607
+ declare class IOSchemaError extends Error {
608
+ name: string;
609
+ }
610
+ /** @desc An error of validating the Endpoint handler's returns against the Endpoint output schema */
611
+ declare class OutputValidationError extends IOSchemaError {
612
+ name: string;
613
+ readonly originalError: ZodError;
614
+ constructor(originalError: ZodError);
615
+ }
616
+ /** @desc An error of validating the input sources against the Middleware or Endpoint input schema */
617
+ declare class InputValidationError extends IOSchemaError {
618
+ name: string;
619
+ readonly originalError: ZodError;
620
+ constructor(originalError: ZodError);
621
+ }
622
+ declare class MissingPeerError extends Error {
623
+ name: string;
624
+ constructor(module: string | string[]);
628
625
  }
629
626
 
630
627
  declare const variants: {
@@ -656,6 +653,19 @@ declare const ez: {
656
653
  }, S>>[k_1]; } : never>, symbol>;
657
654
  };
658
655
 
656
+ interface VariantDependingProps<U> {
657
+ regular: {
658
+ next: (schema: z.ZodTypeAny) => U;
659
+ };
660
+ each: {
661
+ prev: U;
662
+ };
663
+ last: {};
664
+ }
665
+ type HandlingVariant = keyof VariantDependingProps<unknown>;
666
+ type SchemaHandler<U, Context extends FlatObject = {}, Variant extends HandlingVariant = "regular"> = (schema: any, ctx: Context & VariantDependingProps<U>[Variant]) => U;
667
+ type HandlingRules<U, Context extends FlatObject = {}, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
668
+
659
669
  interface OpenAPIContext extends FlatObject {
660
670
  isResponse: boolean;
661
671
  serializer: (schema: z.ZodTypeAny) => string;
@@ -664,39 +674,50 @@ interface OpenAPIContext extends FlatObject {
664
674
  path: string;
665
675
  method: Method;
666
676
  }
677
+ type Depicter = SchemaHandler<SchemaObject | ReferenceObject, OpenAPIContext>;
667
678
 
668
- /** @desc An error related to the wrong Routing declaration */
669
- declare class RoutingError extends Error {
670
- name: string;
671
- }
672
- /**
673
- * @desc An error related to the generating of the documentation
674
- * */
675
- declare class DocumentationError extends Error {
676
- name: string;
677
- constructor({ message, method, path, isResponse, }: {
678
- message: string;
679
- } & Pick<OpenAPIContext, "path" | "method" | "isResponse">);
680
- }
681
- /** @desc An error related to the input and output schemas declaration */
682
- declare class IOSchemaError extends Error {
683
- name: string;
684
- }
685
- /** @desc An error of validating the Endpoint handler's returns against the Endpoint output schema */
686
- declare class OutputValidationError extends IOSchemaError {
687
- name: string;
688
- readonly originalError: ZodError;
689
- constructor(originalError: ZodError);
690
- }
691
- /** @desc An error of validating the input sources against the Middleware or Endpoint input schema */
692
- declare class InputValidationError extends IOSchemaError {
693
- name: string;
694
- readonly originalError: ZodError;
695
- constructor(originalError: ZodError);
679
+ type Component = "positiveResponse" | "negativeResponse" | "requestParameter" | "requestBody";
680
+ /** @desc user defined function that creates a component description from its properties */
681
+ type Descriptor = (props: Record<"method" | "path" | "operationId", string> & {
682
+ statusCode?: number;
683
+ }) => string;
684
+ interface DocumentationParams {
685
+ title: string;
686
+ version: string;
687
+ serverUrl: string | [string, ...string[]];
688
+ routing: Routing;
689
+ config: CommonConfig;
690
+ /**
691
+ * @desc Descriptions of various components based on their properties (method, path, operationId).
692
+ * @desc When composition set to "components", component name is generated from this description
693
+ * @default () => `${method} ${path} ${component}`
694
+ * */
695
+ descriptions?: Partial<Record<Component, Descriptor>>;
696
+ /** @default true */
697
+ hasSummaryFromDescription?: boolean;
698
+ /** @default inline */
699
+ composition?: "inline" | "components";
700
+ /**
701
+ * @desc Used for comparing schemas wrapped into z.lazy() to limit the recursion
702
+ * @default JSON.stringify() + SHA1 hash as a hex digest
703
+ * */
704
+ serializer?: (schema: z.ZodTypeAny) => string;
705
+ /**
706
+ * @desc Handling rules for your own branded schemas.
707
+ * @desc Keys: brands (recommended to use unique symbols).
708
+ * @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
709
+ * @example { MyBrand: ( schema: typeof myBrandSchema, { next } ) => ({ type: "object" })
710
+ */
711
+ brandHandling?: HandlingRules<SchemaObject | ReferenceObject, OpenAPIContext>;
696
712
  }
697
- declare class MissingPeerError extends Error {
698
- name: string;
699
- constructor(module: string | string[]);
713
+ declare class Documentation extends OpenApiBuilder {
714
+ protected lastSecuritySchemaIds: Map<SecuritySchemeType, number>;
715
+ protected lastOperationIdSuffixes: Map<string, number>;
716
+ protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;
717
+ protected getRef(name: string): ReferenceObject | undefined;
718
+ protected ensureUniqOperationId(path: string, method: Method, userDefined?: string): string;
719
+ protected ensureUniqSecuritySchemaName(subject: SecuritySchemeObject): string;
720
+ constructor({ routing, config, title, version, serverUrl, descriptions, brandHandling, hasSummaryFromDescription, composition, serializer, }: DocumentationParams);
700
721
  }
701
722
 
702
723
  type LocalResponse = Response<unknown, {
@@ -758,6 +779,18 @@ declare const testEndpoint: <LOG extends Record<string, any>, REQ extends Record
758
779
  loggerMock: Record<"error" | "info" | "debug" | "warn", MockOverrides> & LOG;
759
780
  }>;
760
781
 
782
+ interface ZTSContext extends FlatObject {
783
+ isResponse: boolean;
784
+ getAlias: (name: string) => ts.TypeReferenceNode | undefined;
785
+ makeAlias: (name: string, type: ts.TypeNode) => ts.TypeReferenceNode;
786
+ serializer: (schema: z.ZodTypeAny) => string;
787
+ optionalPropStyle: {
788
+ withQuestionMark?: boolean;
789
+ withUndefined?: boolean;
790
+ };
791
+ }
792
+ type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
793
+
761
794
  type IOKind = "input" | "response" | "positive" | "negative";
762
795
  interface IntegrationParams {
763
796
  routing: Routing;
@@ -794,6 +827,13 @@ interface IntegrationParams {
794
827
  */
795
828
  withUndefined?: boolean;
796
829
  };
830
+ /**
831
+ * @desc Handling rules for your own branded schemas.
832
+ * @desc Keys: brands (recommended to use unique symbols).
833
+ * @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
834
+ * @example { MyBrand: ( schema: typeof myBrandSchema, { next } ) => createKeywordTypeNode(SyntaxKind.AnyKeyword)
835
+ */
836
+ brandHandling?: HandlingRules<ts.TypeNode, ZTSContext>;
797
837
  }
798
838
  interface FormattedPrintingOptions {
799
839
  /** @desc Typescript printer options */
@@ -852,10 +892,10 @@ declare class Integration {
852
892
  }>;
853
893
  protected getAlias(name: string): ts.TypeReferenceNode | undefined;
854
894
  protected makeAlias(name: string, type: ts.TypeNode): ts.TypeReferenceNode;
855
- constructor({ routing, variant, serializer, splitResponse, optionalPropStyle, }: IntegrationParams);
895
+ constructor({ routing, brandHandling, variant, serializer, splitResponse, optionalPropStyle, }: IntegrationParams);
856
896
  protected printUsage(printerOptions?: ts.PrinterOptions): string | undefined;
857
897
  print(printerOptions?: ts.PrinterOptions): string;
858
898
  printFormatted({ printerOptions, format: userDefined, }?: FormattedPrintingOptions): Promise<string>;
859
899
  }
860
900
 
861
- export { AbstractEndpoint, type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, type MiddlewareDefinition, MissingPeerError, type MockOverrides, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type ResultHandlerDefinition, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createLogger, createMiddleware, createResultHandler, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
901
+ export { AbstractEndpoint, type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, type CommonConfig, type CookieSecurity, type CustomHeaderSecurity, DependsOnMethod, type Depicter, Documentation, DocumentationError, EndpointsFactory, type FlatObject, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, type MiddlewareDefinition, MissingPeerError, type MockOverrides, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, type ResultHandlerDefinition, type Routing, RoutingError, ServeStatic, type ServerConfig, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createLogger, createMiddleware, createResultHandler, createServer, defaultEndpointsFactory, defaultResultHandler, ez, getExamples, getMessageFromError, getStatusCodeFromError, testEndpoint };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import{clone as po}from"ramda";import{z as Ue}from"zod";import{isHttpError as Jr}from"http-errors";import{createHash as Wr}from"crypto";import{flip as Xr,pickBy as eo,xprod as to}from"ramda";import{z as ro}from"zod";var oe=class extends Error{name="RoutingError"},C=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
2
- Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},L=class extends Error{name="IOSchemaError"},V=class extends L{name="OutputValidationError";originalError;constructor(t){super(k(t)),this.originalError=t}},D=class extends L{name="InputValidationError";originalError;constructor(t){super(k(t)),this.originalError=t}},$=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ne=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var oo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},nt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},no=["body","query","params"],it=e=>e.method.toLowerCase(),st=e=>e.startsWith("x-"),io=e=>eo(Xr(st),e),qt=(e,t={})=>{let r=it(e);return r==="options"?{}:(t[r]||nt[r]||no).filter(o=>o==="files"?oo(e):!0).map(o=>o==="headers"?io(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},ie=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),k=e=>e instanceof ro.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Le=e=>Jr(e)?e.statusCode:e instanceof D?400:500,at=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
1
+ import{clone as co}from"ramda";import{z as Ue}from"zod";import{isHttpError as Wr}from"http-errors";import{createHash as Xr}from"crypto";import{flip as eo,pickBy as to,xprod as ro}from"ramda";import{z as oo}from"zod";var ne=class extends Error{name="RoutingError"},A=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
2
+ Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},L=class extends Error{name="IOSchemaError"},V=class extends L{name="OutputValidationError";originalError;constructor(t){super(k(t)),this.originalError=t}},j=class extends L{name="InputValidationError";originalError;constructor(t){super(k(t)),this.originalError=t}},G=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},ie=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var I={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var no=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(I.upload);return"files"in e&&r},it={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},io=["body","query","params"],st=e=>e.method.toLowerCase(),at=e=>e.startsWith("x-"),so=e=>to(eo(at),e),$t=(e,t={})=>{let r=st(e);return r==="options"?{}:(t[r]||it[r]||io).filter(o=>o==="files"?no(e):!0).map(o=>o==="headers"?so(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},se=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),k=e=>e instanceof oo.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Le=e=>Wr(e)?e.statusCode:e instanceof j?400:500,pt=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
3
3
  ${o.stack}
4
- `,{url:t.url,payload:r})},j=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[y]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},_=(e,t,r)=>e.length&&t.length?to(e,t).map(r):e.concat(t),Te=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,pt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),E=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(pt).join(""),De=e=>Wr("sha1").update(JSON.stringify(e),"utf8").digest("hex"),ke=(e,t)=>{try{return typeof e.parse(t)}catch{return}},M=e=>typeof e=="object"&&e!==null;import{clone as so,mergeDeepRight as ao}from"ramda";var y=Symbol.for("express-zod-api"),je=e=>{let t=e.describe(e.description);return t._def[y]=so(t._def[y])||{examples:[]},t},Vt=(e,t)=>{if(!(y in e._def))return t;let r=je(t);return r._def[y].examples=_(r._def[y].examples,e._def[y].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?ao({...o},{...i}):i),r};var co=function(e){let t=je(this);return t._def[y].examples.push(e),t},lo=function(e){let t=je(this);return t._def[y].defaultLabel=e,t},mo=function(e){return new Ue.ZodBranded({typeName:Ue.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...po(this._def[y]),brand:e}})};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Ue.ZodType.prototype,{example:{get(){return co.bind(this)}},brand:{set(){},get(){return mo.bind(this)}}}),Object.defineProperty(Ue.ZodDefault.prototype,"label",{get(){return lo.bind(this)}}));function uo(e){return e}import Xt from"assert/strict";import{z as ut}from"zod";import{z as fo}from"zod";var se={positive:200,negative:400},dt=(e,t)=>e instanceof fo.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));import{z as xo}from"zod";import{z as go}from"zod";import{z as He}from"zod";var U=Symbol("File"),$t=He.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),yo={buffer:()=>$t.brand(U),string:()=>He.string().brand(U),binary:()=>$t.or(He.string()).brand(U),base64:()=>He.string().base64().brand(U)};function Fe(e){return yo[e||"string"]()}var G=Symbol("Raw"),_t=(e={})=>go.object({raw:Fe("buffer")}).extend(e).brand(G);import{z as ho}from"zod";var Se=Symbol("Upload"),Gt=()=>ho.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Se);var ct=({schema:{options:e},next:t})=>e.some(t),Qt=({schema:{_def:e},next:t})=>[e.left,e.right].some(t),bo=({schema:e,next:t})=>Object.values(e.shape).some(t),Yt=({schema:e,next:t})=>t(e.unwrap()),To=({schema:e,next:t})=>t(e.innerType()),So=({schema:e,next:t})=>t(e.valueSchema),Ro=({schema:e,next:t})=>t(e.element),Oo=({schema:e,next:t})=>t(e._def.innerType),Ao={ZodObject:bo,ZodUnion:ct,ZodDiscriminatedUnion:ct,ZodIntersection:Qt,ZodEffects:To,ZodOptional:Yt,ZodNullable:Yt,ZodRecord:So,ZodArray:Ro,ZodDefault:Oo},Ke=({subject:e,condition:t,rules:r=Ao,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s({schema:e,next:a=>Ke({subject:a,condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},Be=e=>Ke({subject:e,maxDepth:3,rules:{ZodUnion:ct,ZodIntersection:Qt},condition:t=>t instanceof xo.ZodEffects&&t._def.effect.type!=="refinement"}),Jt=e=>Ke({subject:e,condition:t=>t._def[y]?.brand===Se}),Wt=e=>Ke({subject:e,condition:t=>t._def[y]?.brand===G,maxDepth:3});var qe=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
- Original error: ${e.originalError.message}.`:""))};import{chain as Po}from"ramda";var Y=e=>M(e)&&"or"in e,pe=e=>M(e)&&"and"in e,lt=e=>({and:Po(t=>pe(t)?t.and:[t],e)}),Ve=(e,t)=>pe(e)?{and:e.and.map(r=>Y(r)?{or:r.or.map(t)}:t(r))}:Y(e)?{or:e.or.map(r=>pe(r)?{and:r.and.map(t)}:t(r))}:t(e),mt=e=>e.and.reduce((t,r)=>({or:_(t.or,Y(r)?r.or:[r],lt)}),{or:[]}),ae=(e,t)=>pe(e)?Y(t)?ae(mt(e),t):lt([e,t]):Y(e)?pe(t)?ae(t,e):Y(t)?{or:_(e.or,t.or,lt)}:ae(e,{and:[t]}):pe(t)||Y(t)?ae(t,e):{and:[e,t]};var de=class{},$e=class extends de{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:m,shortDescription:l}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:m,short:l},this.#r={input:r,output:o};for(let[f,b]of Object.entries(this.#r))Xt(!Be(b),new L(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#t={positive:Object.freeze(dt(s.getPositiveResponse(o),{mimeTypes:[w.json],statusCodes:[se.positive]})),negative:Object.freeze(dt(s.getNegativeResponse(),{mimeTypes:[w.json],statusCodes:[se.negative]}))};for(let[f,b]of Object.entries(this.#t))Xt(b.length,new $(`ResultHandler must have at least one ${f} response schema specified.`));this.#i=Jt(r)?"upload":Wt(r)?"raw":"json",this.#s={input:Object.freeze([w[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:f})=>f)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:f})=>f))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?ae(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof ut.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof ut.ZodError?new D(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof ut.ZodError?new D(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){qe({logger:i,response:o,error:new $(ie(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=it(t),p={},d=null,c=null;if(i.cors){let l=this.#m(s);typeof i.cors=="function"&&(l=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:l}));for(let f in l)r.set(f,l[f])}let m=qt(t,i.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(l){c=ie(l)}await this.#g({input:m,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as tr}from"zod";var er=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Vt(s,i),o)};import Co from"assert/strict";var ft=e=>(Co(!Be(e.input),new L("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as Z}from"zod";var yt=e=>e,Re=yt({getPositiveResponse:e=>{let t=j({schema:e}),r=Z.object({status:Z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>Z.object({status:Z.literal("error"),error:Z.object({message:Z.string()})}).example({status:"error",error:{message:k(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(se.positive).json({status:"success",data:r});return}let a=Le(e);at({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:k(e)}})}}),gt=yt({getPositiveResponse:e=>{let t=j({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof Z.ZodArray?e.shape.items:Z.array(Z.any());return t.reduce((o,i)=>M(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>Z.string().example(k(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Le(r);at({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(se.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var Oe=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:tr.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,l=>{if(l&&l instanceof Error)return c(o(l));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(ft({input:tr.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],l=typeof a=="function"?a:()=>a,f="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],b="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new $e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:f,tags:b,methods:m,getOperationId:l,description:i,shortDescription:s,inputSchema:er(d,t)})}},Io=new Oe(Re),wo=new Oe(gt);import{inspect as Eo}from"util";import{mapObjIndexed as zo}from"ramda";import{Ansis as Zo,blue as No,green as Mo,hex as vo,red as Lo}from"ansis";var ht={debug:10,info:20,warn:30,error:40},rr=e=>M(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),xt=({level:e,color:t=new Zo().isSupported(),depth:r=2})=>{let o={debug:No,info:Mo,warn:vo("#FFA500"),error:Lo},i=e==="debug",s=e==="silent"?100:ht[e],a=(p,d,c)=>{if(ht[p]<s)return;let m=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&m.push(Eo(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(m.join(" "))};return zo(({},p)=>(d,c)=>a(p,d,c),ht)};import{head as Do,tail as ko,toPairs as jo}from"ramda";var Ae=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(jo(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=Do(this.pairs)?.[1],this.siblingMethods=Object.freeze(ko(this.pairs).map(([r])=>r))}};import Uo from"express";var Pe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Uo.static(...this.params))}};import Tt from"express";import Vo from"http";import $o from"https";var Q=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new ne(e)},or=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await Q(t,r)}catch{}throw new ne(e.map(({moduleName:t})=>t))};import nr from"assert/strict";var J=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){nr.doesNotMatch(a,/\//,new oe(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof de){let c=p.getMethods().slice();i&&c.push("options");for(let m of c)t(p,d,m)}else if(p instanceof Pe)r&&p.apply(d,r);else if(p instanceof Ae){for(let[c,m]of p.pairs)nr(m.getMethods().includes(c),new oe(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(m,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else J({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var bt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>J({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,m)=>s.execute({request:c,response:m,logger:m.locals[y]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});import ir,{isHttpError as Ho}from"http-errors";var sr=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:Ho(r)?r:ir(400,ie(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[y]?.logger||t})},ar=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=ir(404,`Can not ${r.method} ${r.path}`),s=o.locals[y]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){qe({response:o,logger:s,error:new $(ie(a).message,i)})}},Fo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Ko=e=>({log:e.debug.bind(e)}),pr=async({rootLogger:e,config:t})=>{let r=await Q("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let m=d.locals[y]?.logger||e;try{await i?.({request:p,logger:m})}catch(l){return c(l)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Ko(m)})(p,d,c)}),o&&a.push(Fo(o)),a},dr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},cr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[y]={logger:s},i()};import{gray as Bo,hex as lr,italic as _e,whiteBright as qo}from"ansis";var mr=()=>{let e=_e("Proudly supports transgender community.".padStart(109)),t=_e("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=_e("Thank you for choosing Express Zod API for your project.".padStart(132)),o=_e("for Dime".padEnd(20)),i=lr("#F5A9B8"),s=lr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(qo,5,7).fill(i,7,9).fill(s,9,12).fill(Bo,12,13);return`
4
+ `,{url:t.url,payload:r})},H=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[y]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},_=(e,t,r)=>e.length&&t.length?ro(e,t).map(r):e.concat(t),Se=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,dt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),w=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(dt).join(""),je=e=>Xr("sha1").update(JSON.stringify(e),"utf8").digest("hex"),ke=(e,t)=>{try{return typeof e.parse(t)}catch{return}},v=e=>typeof e=="object"&&e!==null;import{clone as ao,mergeDeepRight as po}from"ramda";var y=Symbol.for("express-zod-api"),He=e=>{let t=e.describe(e.description);return t._def[y]=ao(t._def[y])||{examples:[]},t},Vt=(e,t)=>{if(!(y in e._def))return t;let r=He(t);return r._def[y].examples=_(r._def[y].examples,e._def[y].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?po({...o},{...i}):i),r};var lo=function(e){let t=He(this);return t._def[y].examples.push(e),t},mo=function(e){let t=He(this);return t._def[y].defaultLabel=e,t},uo=function(e){return new Ue.ZodBranded({typeName:Ue.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...co(this._def[y]),brand:e}})};y in globalThis||(globalThis[y]=!0,Object.defineProperties(Ue.ZodType.prototype,{example:{get(){return lo.bind(this)}},brand:{set(){},get(){return uo.bind(this)}}}),Object.defineProperty(Ue.ZodDefault.prototype,"label",{get(){return mo.bind(this)}}));function fo(e){return e}import er from"assert/strict";import{z as ft}from"zod";import{z as yo}from"zod";var ae={positive:200,negative:400},ct=(e,t)=>e instanceof yo.ZodType?[{...t,schema:e}]:(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes}));import{z as bo}from"zod";import{z as ho}from"zod";import{z as Fe}from"zod";var U=Symbol("File"),Gt=Fe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),go={buffer:()=>Gt.brand(U),string:()=>Fe.string().brand(U),binary:()=>Gt.or(Fe.string()).brand(U),base64:()=>Fe.string().base64().brand(U)};function Ke(e){return go[e||"string"]()}var Y=Symbol("Raw"),_t=(e={})=>ho.object({raw:Ke("buffer")}).extend(e).brand(Y);import{z as xo}from"zod";var Re=Symbol("Upload"),Yt=()=>xo.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(Re);var lt=(e,{next:t})=>e.options.some(t),Jt=({_def:e},{next:t})=>[e.left,e.right].some(t),Qt=(e,{next:t})=>t(e.unwrap()),To={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:lt,ZodDiscriminatedUnion:lt,ZodIntersection:Jt,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:Qt,ZodNullable:Qt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},Be=(e,{condition:t,rules:r=To,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s(e,{next:a=>Be(a,{condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},qe=e=>Be(e,{maxDepth:3,rules:{ZodUnion:lt,ZodIntersection:Jt},condition:t=>t instanceof bo.ZodEffects&&t._def.effect.type!=="refinement"}),Wt=e=>Be(e,{condition:t=>t._def[y]?.brand===Re}),Xt=e=>Be(e,{condition:t=>t._def[y]?.brand===Y,maxDepth:3});var $e=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
+ Original error: ${e.originalError.message}.`:""))};import{chain as So}from"ramda";var Q=e=>v(e)&&"or"in e,de=e=>v(e)&&"and"in e,mt=e=>({and:So(t=>de(t)?t.and:[t],e)}),Ve=(e,t)=>de(e)?{and:e.and.map(r=>Q(r)?{or:r.or.map(t)}:t(r))}:Q(e)?{or:e.or.map(r=>de(r)?{and:r.and.map(t)}:t(r))}:t(e),ut=e=>e.and.reduce((t,r)=>({or:_(t.or,Q(r)?r.or:[r],mt)}),{or:[]}),pe=(e,t)=>de(e)?Q(t)?pe(ut(e),t):mt([e,t]):Q(e)?de(t)?pe(t,e):Q(t)?{or:_(e.or,t.or,mt)}:pe(e,{and:[t]}):de(t)||Q(t)?pe(t,e):{and:[e,t]};var ce=class{},Ge=class extends ce{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:f}){super(),this.#a=i,this.#p=s,this.#n=d,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(c),this.#e={long:l,short:f},this.#r={input:r,output:o};for(let[m,x]of Object.entries(this.#r))er(!qe(x),new L(`Using transformations on the top level of endpoint ${m} schema is not allowed.`));this.#t={positive:Object.freeze(ct(s.getPositiveResponse(o),{mimeTypes:[I.json],statusCodes:[ae.positive]})),negative:Object.freeze(ct(s.getNegativeResponse(),{mimeTypes:[I.json],statusCodes:[ae.negative]}))};for(let[m,x]of Object.entries(this.#t))er(x.length,new G(`ResultHandler must have at least one ${m} response schema specified.`));this.#i=Wt(r)?"upload":Xt(r)?"raw":"json",this.#s={input:Object.freeze([I[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:m})=>m)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:m})=>m))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?pe(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof ft.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let d;try{d=await p.input.parseAsync(r)}catch(c){throw c instanceof ft.ZodError?new j(c):c}if(Object.assign(a,await p.middleware({input:d,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof ft.ZodError?new j(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){$e({logger:i,response:o,error:new G(se(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=st(t),p={},d=null,c=null;if(i.cors){let f=this.#m(s);typeof i.cors=="function"&&(f=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:f}));for(let m in f)r.set(m,f[m])}let l=$t(t,i.inputSources);try{if(await this.#f({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:l,logger:o,options:p}))}catch(f){c=se(f)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};import{z as rr}from"zod";var tr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>Vt(s,i),o)};import Ro from"assert/strict";var yt=e=>(Ro(!qe(e.input),new L("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});import{z as Z}from"zod";var gt=e=>e,Oe=gt({getPositiveResponse:e=>{let t=H({schema:e}),r=Z.object({status:Z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>Z.object({status:Z.literal("error"),error:Z.object({message:Z.string()})}).example({status:"error",error:{message:k(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(ae.positive).json({status:"success",data:r});return}let a=Le(e);pt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:k(e)}})}}),ht=gt({getPositiveResponse:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof Z.ZodArray?e.shape.items:Z.array(Z.any());return t.reduce((o,i)=>v(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>Z.string().example(k(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Le(r);pt({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ae.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var Ae=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:rr.object({}),middleware:async({request:a,response:p})=>new Promise((d,c)=>{t(a,p,f=>{if(f&&f instanceof Error)return c(o(f));d(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(yt({input:rr.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],f=typeof a=="function"?a:()=>a,m="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],x="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new Ge({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:m,tags:x,methods:l,getOperationId:f,description:i,shortDescription:s,inputSchema:tr(d,t)})}},Oo=new Ae(Oe),Ao=new Ae(ht);import{inspect as Po}from"util";import{mapObjIndexed as Co}from"ramda";import{Ansis as Io,blue as wo,green as Eo,hex as zo,red as Zo}from"ansis";var xt={debug:10,info:20,warn:30,error:40},or=e=>v(e)&&"level"in e&&("color"in e?typeof e.color=="boolean":!0)&&("depth"in e?typeof e.depth=="number"||e.depth===null:!0)&&typeof e.level=="string"&&["silent","warn","info","debug"].includes(e.level)&&!Object.values(e).some(t=>typeof t=="function"),bt=({level:e,color:t=new Io().isSupported(),depth:r=2})=>{let o={debug:wo,info:Eo,warn:zo("#FFA500"),error:Zo},i=e==="debug",s=e==="silent"?100:xt[e],a=(p,d,c)=>{if(xt[p]<s)return;let l=[new Date().toISOString(),t?`${o[p](p)}:`:`${p}:`,d];c!==void 0&&l.push(Po(c,{colors:t,depth:r,breakLength:i?80:1/0,compact:i?3:!0})),console.log(l.join(" "))};return Co(({},p)=>(d,c)=>a(p,d,c),xt)};import{head as No,tail as Mo,toPairs as vo}from"ramda";var Pe=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(vo(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=No(this.pairs)?.[1],this.siblingMethods=Object.freeze(Mo(this.pairs).map(([r])=>r))}};import Do from"express";var Ce=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Do.static(...this.params))}};import St from"express";import Fo from"http";import Ko from"https";var J=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new ie(e)},nr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await J(t,r)}catch{}throw new ie(e.map(({moduleName:t})=>t))};import ir from"assert/strict";var W=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){ir.doesNotMatch(a,/\//,new ne(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof ce){let c=p.getMethods().slice();i&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof Ce)r&&p.apply(d,r);else if(p instanceof Pe){for(let[c,l]of p.pairs)ir(l.getMethods().includes(c),new ne(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else W({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Tt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>W({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(c,l)=>s.execute({request:c,response:l,logger:l.locals[y]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});import sr,{isHttpError as Lo}from"http-errors";var ar=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:Lo(r)?r:sr(400,se(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[y]?.logger||t})},pr=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=sr(404,`Can not ${r.method} ${r.path}`),s=o.locals[y]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){$e({response:o,logger:s,error:new G(se(a).message,i)})}},jo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},ko=e=>({log:e.debug.bind(e)}),dr=async({rootLogger:e,config:t})=>{let r=await J("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let l=d.locals[y]?.logger||e;try{await i?.({request:p,logger:l})}catch(f){return c(f)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:ko(l)})(p,d,c)}),o&&a.push(jo(o)),a},cr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},lr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[y]={logger:s},i()};import{gray as Ho,hex as mr,italic as _e,whiteBright as Uo}from"ansis";var ur=()=>{let e=_e("Proudly supports transgender community.".padStart(109)),t=_e("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=_e("Thank you for choosing Express Zod API for your project.".padStart(132)),o=_e("for Dime".padEnd(20)),i=mr("#F5A9B8"),s=mr("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(Uo,5,7).fill(i,7,9).fill(s,9,12).fill(Ho,12,13);return`
6
6
  8888888888 8888888888P 888 d8888 8888888b. 8888888
7
7
  888 d88P 888 d88888 888 Y88b 888
8
8
  888 d88P 888 d88P888 888 888 888
@@ -17,8 +17,8 @@ ${o}888${t}
17
17
  ${r}
18
18
  `.split(`
19
19
  `).map((d,c)=>a[c]?a[c](d):d).join(`
20
- `)};var ur=e=>{e.startupLogo!==!1&&console.log(mr());let t=e.errorHandler||Re,r=rr(e.logger)?xt(e.logger):e.logger;r.debug("Running","v19.0.0 (ESM)");let o=cr({rootLogger:r,config:e}),i=ar({rootLogger:r,errorHandler:t}),s=sr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},_o=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=ur(e);return bt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Go=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=ur(e),a=Tt().disable("x-powered-by").use(s);if(e.server.compression){let m=await Q("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||Tt.json()],raw:[e.server.rawParser||Tt.raw(),dr],upload:e.server.upload?await pr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),bt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(m,l)=>m.listen(l,()=>{r.info("Listening",l)}),c={httpServer:d(Vo.createServer(a),e.server.listen),httpsServer:e.https?d($o.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...c,logger:r}};import ti from"assert/strict";import{OpenApiBuilder as ri}from"openapi3-ts/oas31";import H from"assert/strict";import{isReferenceObject as X}from"openapi3-ts/oas31";import{both as Qo,complement as Jo,concat as Wo,type as Xo,filter as en,fromPairs as Ee,has as tn,isNil as rn,map as le,mergeAll as on,mergeDeepRight as nn,mergeDeepWith as sn,objOf as xr,omit as Qe,pipe as br,pluck as an,range as pn,reject as dn,toLower as cn,union as ln,when as mn,xprod as Je,zip as un}from"ramda";import{z as x}from"zod";import{z as Ce}from"zod";var Ge=e=>!isNaN(e.getTime());var Ie=Symbol("DateIn"),fr=()=>Ce.union([Ce.string().date(),Ce.string().datetime(),Ce.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ce.date().refine(Ge)).brand(Ie);import{z as Yo}from"zod";var we=Symbol("DateOut"),yr=()=>Yo.date().refine(Ge).transform(e=>e.toISOString()).brand(we);var W=({schema:e,onEach:t,rules:r,onMissing:o,...i})=>{let s=r[e._def[y]?.brand]||r[e._def.typeName],a=i,d=s?s({schema:e,...a,next:m=>W({schema:m,...a,onEach:t,rules:r,onMissing:o})}):o({schema:e,...a}),c=t&&t({schema:e,prev:d,...a});return c?{...d,...c}:d};var gr=50,Tr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",fn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Sr=/:([A-Za-z0-9_]+)/g,Rr=e=>e.match(Sr)?.map(t=>t.slice(1))||[],Or=e=>e.replace(Sr,t=>`{${t.slice(1)}}`),yn=({schema:e,next:t})=>({...t(e._def.innerType),default:e._def[y]?.defaultLabel||e._def.defaultValue()}),gn=({schema:{_def:{innerType:e}},next:t})=>t(e),hn=()=>({format:"any"}),xn=e=>(H(!e.isResponse,new C({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),bn=({schema:e})=>{let t=e.unwrap();return{type:"string",format:t instanceof x.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Tn=({schema:{options:e},next:t})=>({oneOf:e.map(t)}),Sn=({schema:{options:e,discriminator:t},next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Rn=e=>{let[t,r]=e.filter(i=>!X(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));H(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=sn((i,s)=>Array.isArray(i)&&Array.isArray(s)?Wo(i,s):i===s?s:H.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=ln(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([i,s])=>nn(i,s))),o},On=({schema:{_def:{left:e,right:t}},next:r})=>{let o=[e,t].map(r);try{return Rn(o)}catch{}return{allOf:o}},An=({schema:e,next:t})=>t(e.unwrap()),Pn=({schema:e,next:t})=>t(e._def.innerType),Cn=({schema:e,next:t})=>{let r=t(e.unwrap());return X(r)||(r.type=Pr(r)),r},Ar=e=>{let t=cn(Xo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},hr=({schema:e})=>({type:Ar(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),In=({schema:{value:e}})=>({type:Ar(e),const:e}),wn=({schema:e,isResponse:t,...r})=>{let o=Object.keys(e.shape),i=p=>t&&Te(p)?p instanceof x.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=Ye({schema:e,isResponse:t,...r})),s.length&&(a.required=s),a},En=()=>({type:"null"}),zn=e=>(H(!e.isResponse,new C({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Tr}}),Zn=e=>(H(e.isResponse,new C({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Tr}}),Nn=e=>H.fail(new C({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),Mn=()=>({type:"boolean"}),vn=()=>({type:"integer",format:"bigint"}),Ln=e=>e.every(t=>t instanceof x.ZodLiteral),Dn=({schema:{keySchema:e,valueSchema:t},...r})=>{if(e instanceof x.ZodEnum||e instanceof x.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=Ye({schema:x.object(Ee(Je(o,[t]))),...r}),i.required=o),i}if(e instanceof x.ZodLiteral)return{type:"object",properties:Ye({schema:x.object({[e.value]:t}),...r}),required:[e.value]};if(e instanceof x.ZodUnion&&Ln(e.options)){let o=le(s=>`${s.value}`,e.options),i=Ee(Je(o,[t]));return{type:"object",properties:Ye({schema:x.object(i),...r}),required:o}}return{type:"object",additionalProperties:r.next(t)}},kn=({schema:{_def:e,element:t},next:r})=>{let o={type:"array",items:r(t)};return e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),o},jn=({schema:{items:e,_def:{rest:t}},next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Un=({schema:{isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:m,_def:{checks:l}}})=>{let f=l.find(S=>S.kind==="regex"),b=l.find(S=>S.kind==="datetime"),T=f?f.regex:b?b.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,R={type:"string"},h={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let S in h)if(h[S]){R.format=S;break}return r!==null&&(R.minLength=r),o!==null&&(R.maxLength=o),T&&(R.pattern=T.source),R},Hn=({schema:e})=>{let t=e._def.checks.find(({kind:d})=>d==="min"),r=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,o=t?t.inclusive:!0,i=e._def.checks.find(({kind:d})=>d==="max"),s=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=i?i.inclusive:!0,p={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return o?p.minimum=r:p.exclusiveMinimum=r,a?p.maximum=s:p.exclusiveMaximum=s,p},Ye=({schema:{shape:e},next:t})=>le(t,e),Fn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return fn?.[t]},Pr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Kn=({schema:e,isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!X(o)){let s=ke(e,Fn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(x.any())}if(!t&&i.type==="preprocess"&&!X(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Bn=({schema:e,isResponse:t,next:r})=>r(e._def[t?"out":"in"]),qn=({schema:e,next:t})=>t(e.unwrap()),Vn=({next:e,schema:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(t.schema);return o(s)||(i(s,{}),i(s,e(t.schema)))},$n=({next:e,schema:t})=>e(t.unwrap().shape.raw),Cr=e=>e.length?Ee(un(pn(1,e.length+1).map(t=>`example${t}`),le(xr("value"),e))):void 0,Ir=(e,t,r=[])=>br(j,le(mn(Qo(M,Jo(Array.isArray)),Qe(r))),Cr)({schema:e,variant:t?"parsed":"original",validate:!0}),_n=(e,t)=>br(j,en(tn(t)),an(t),Cr)({schema:e,variant:"original",validate:!0}),ce=(e,t)=>e instanceof x.ZodObject?e:e instanceof x.ZodBranded?ce(e.unwrap(),t):e instanceof x.ZodUnion||e instanceof x.ZodDiscriminatedUnion?e.options.map(r=>ce(r,t)).reduce((r,o)=>r.merge(o.partial()),x.object({})):e instanceof x.ZodEffects?(H(e._def.effect.type==="refinement",t),ce(e._def.schema,t)):ce(e._def.left,t).merge(ce(e._def.right,t)),wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:c}=ce(r,new C({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),m=Rr(e),l=o.includes("query"),f=o.includes("params"),b=o.includes("headers"),T=h=>f&&m.includes(h),R=h=>b&&st(h);return Object.keys(c).filter(h=>l||T(h)).map(h=>{let S=W({schema:c[h],isResponse:!1,rules:Rt,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:e,method:t}),fe=p==="components"?a(E(d,h),S):S;return{name:h,in:T(h)?"path":R(h)?"header":"query",required:!c[h].isOptional(),description:S.description||d,schema:fe,examples:_n(r,h)}})},Rt={ZodString:Un,ZodNumber:Hn,ZodBigInt:vn,ZodBoolean:Mn,ZodNull:En,ZodArray:kn,ZodTuple:jn,ZodRecord:Dn,ZodObject:wn,ZodLiteral:In,ZodIntersection:On,ZodUnion:Tn,ZodAny:hn,ZodDefault:yn,ZodEnum:hr,ZodNativeEnum:hr,ZodEffects:Kn,ZodOptional:An,ZodNullable:Cn,ZodDiscriminatedUnion:Sn,ZodBranded:qn,ZodDate:Nn,ZodCatch:gn,ZodPipeline:Bn,ZodLazy:Vn,ZodReadonly:Pn,[U]:bn,[Se]:xn,[we]:Zn,[Ie]:zn,[G]:$n},Ot=({schema:e,isResponse:t,prev:r})=>{if(X(r))return{};let{description:o}=e,i=e instanceof x.ZodLazy,s=r.type!==void 0,a=t&&Te(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:j({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Pr(r)),d.length&&(c.examples=d.slice()),c},At=({schema:e,...t})=>H.fail(new C({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),St=(e,t)=>{if(X(e))return e;let r={...e};return r.properties&&(r.properties=Qe(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Qe(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>St(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>St(o,t))),r},Er=e=>X(e)?e:Qe(["examples"],e),zr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:m,description:l=`${e.toUpperCase()} ${t} ${pt(i)} response ${c?m:""}`.trim()})=>{let f=Er(W({schema:r,isResponse:!0,rules:Rt,onEach:Ot,onMissing:At,serializer:s,getRef:a,makeRef:p,path:t,method:e})),b={schema:d==="components"?p(E(l),f):f,examples:Ir(r,!0)};return{description:l,content:Ee(Je(o,[b]))}},Gn=()=>({type:"http",scheme:"basic"}),Yn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Qn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Jn=({name:e})=>({type:"apiKey",in:"header",name:e}),Wn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Xn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ei=({flows:e={}})=>({type:"oauth2",flows:le(t=>({...t,scopes:t.scopes||{}}),dn(rn,e))}),Zr=(e,t)=>{let r={basic:Gn,bearer:Yn,input:Qn,header:Jn,cookie:Wn,openid:Xn,oauth2:ei};return Ve(e,o=>r[o.type](o,t))},We=e=>"or"in e?e.or.map(t=>"and"in t?on(le(({name:r,scopes:o})=>xr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?We(mt(e)):We({or:[e]}),Nr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let c=Rr(t),m=Er(St(W({schema:r,isResponse:!1,rules:Rt,onEach:Ot,onMissing:At,serializer:i,getRef:s,makeRef:a,path:t,method:e}),c)),l={schema:p==="components"?a(E(d),m):m,examples:Ir(r,!1,c)};return{description:d,content:Ee(Je(o,[l]))}},Mr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Pt=e=>e.length<=gr?e:e.slice(0,gr-1)+"\u2026";var Ct=class extends ri{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||E(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&ti.fail(new C({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,hasSummaryFromDescription:p=!0,composition:d="inline",serializer:c=De}){super(),this.addInfo({title:o,version:i});for(let l of typeof s=="string"?[s]:s)this.addServer({url:l});J({routing:t,onEndpoint:(l,f,b)=>{let T=b,R={path:f,method:T,endpoint:l,composition:d,serializer:c,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,S]=["short","long"].map(l.getDescription.bind(l)),fe=h?Pt(h):p&&S?Pt(S):void 0,Ze=l.getTags(),ye=r.inputSources?.[T]||nt[T],te=this.ensureUniqOperationId(f,T,l.getOperationId(T)),Ne=wr({...R,inputSources:ye,schema:l.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:f,operationId:te})}),Me={};for(let N of["positive","negative"]){let q=l.getResponses(N);for(let{mimeTypes:ge,schema:O,statusCodes:A}of q)for(let P of A)Me[P]=zr({...R,variant:N,schema:O,mimeTypes:ge,statusCode:P,hasMultipleStatusCodes:q.length>1||A.length>1,description:a?.[`${N}Response`]?.call(null,{method:T,path:f,operationId:te,statusCode:P})})}let ot=ye.includes("body")?Nr({...R,schema:l.getSchema("input"),mimeTypes:l.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:f,operationId:te})}):void 0,ve=We(Ve(Zr(l.getSecurity(),ye),N=>{let q=this.ensureUniqSecuritySchemaName(N),ge=["oauth2","openIdConnect"].includes(N.type)?l.getScopes().slice():[];return this.addSecurityScheme(q,N),{name:q,scopes:ge}}));this.addPath(Or(f),{[T]:{operationId:te,summary:fe,description:S,tags:Ze.length>0?Ze:void 0,parameters:Ne.length>0?Ne:void 0,requestBody:ot,security:ve.length>0?ve:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Mr(r.tags):[]}};import vr from"http";var oi=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>w.json),...t}),ni=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:vr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=vr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},ii=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),si=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await or([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=oi({fnMethod:a,requestProps:t}),d=ni({fnMethod:a,responseProps:r}),c=ii({fnMethod:a,loggerProps:i}),m={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:m,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import z from"typescript";import v from"typescript";import{chain as Lr,toPairs as Dr}from"ramda";var n=v.factory,F=[n.createModifier(v.SyntaxKind.ExportKeyword)],ai=[n.createModifier(v.SyntaxKind.AsyncKeyword)],pi=[n.createModifier(v.SyntaxKind.PublicKeyword),n.createModifier(v.SyntaxKind.ReadonlyKeyword)],kr=[n.createModifier(v.SyntaxKind.ProtectedKeyword),n.createModifier(v.SyntaxKind.ReadonlyKeyword)],It=n.createTemplateHead(""),me=n.createTemplateTail(""),wt=n.createTemplateMiddle(" "),Et=e=>n.createTemplateLiteralType(It,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?me:wt))),zt=Et(["M","P"]),Xe=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),et=(e,t)=>Lr(([r,o])=>[Xe(n.createIdentifier(r),o,t)],Dr(e)),Zt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),jr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Ur=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),K=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],v.NodeFlags.Const),Nt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),tt=(e,t)=>n.createTypeAliasDeclaration(F,e,void 0,t),Hr=(e,t,r)=>n.createPropertyDeclaration(pi,e,void 0,t,r),Fr=(e,t,r)=>n.createClassDeclaration(F,e,void 0,void 0,[t,...r]),Kr=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),Br=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(v.SyntaxKind.AnyKeyword)]),qr=(e,t,r)=>n.createInterfaceDeclaration(F,e,void 0,t,r),Vr=e=>Lr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],Dr(e)),Mt=(e,t,r)=>n.createArrowFunction(r?ai:void 0,void 0,e.map(o=>Xe(o)),void 0,void 0,t),vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,et({acc:void 0,key:void 0}),void 0,void 0,t),r]),$r=(...e)=>`"${e.join(" ")}"`;var _r=["get","post","put","delete","patch"];import g from"typescript";import{z as kt}from"zod";import B from"typescript";var{factory:rt}=B,Lt=(e,t)=>{B.addSyntheticLeadingComment(e,B.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ue=(e,t,r)=>{let o=rt.createTypeAliasDeclaration(void 0,rt.createIdentifier(t),void 0,e);return r&&Lt(o,r),o},Dt=(e,t)=>{let r=B.createSourceFile("print.ts","",B.ScriptTarget.Latest,!1,B.ScriptKind.TS);return B.createPrinter(t).printNode(B.EmitHint.Unspecified,e,r)},di=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gr=e=>di.test(e)?rt.createIdentifier(e):rt.createStringLiteral(e);var{factory:u}=g,ci={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},li=({schema:{value:e}})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),mi=({schema:{shape:e},isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Te(a)?a instanceof kt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Gr(s),p&&o?u.createToken(g.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Lt(d,a.description),d});return u.createTypeLiteralNode(i)},ui=({schema:{element:e},next:t})=>u.createArrayTypeNode(t(e)),fi=({schema:{options:e}})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Yr=({schema:{options:e},next:t})=>u.createUnionTypeNode(e.map(t)),yi=e=>ci?.[e.kind],gi=({schema:e,next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,yi(o)),a={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||g.SyntaxKind.AnyKeyword)}return o},hi=({schema:e})=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),xi=({next:e,schema:t,optionalPropStyle:{withUndefined:r}})=>{let o=e(t.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(g.SyntaxKind.UndefinedKeyword)]):o},bi=({next:e,schema:t})=>u.createUnionTypeNode([e(t.unwrap()),u.createLiteralTypeNode(u.createNull())]),Ti=({next:e,schema:{items:t,_def:{rest:r}}})=>u.createTupleTypeNode(t.map(e).concat(r===null?[]:u.createRestTypeNode(e(r)))),Si=({next:e,schema:{keySchema:t,valueSchema:r}})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[t,r].map(e)),Ri=({next:e,schema:t})=>u.createIntersectionTypeNode([t._def.left,t._def.right].map(e)),Oi=({next:e,schema:t})=>e(t._def.innerType),ee=e=>()=>u.createKeywordTypeNode(e),Ai=({next:e,schema:t})=>e(t.unwrap()),Pi=({next:e,schema:t})=>e(t._def.innerType),Ci=({next:e,schema:t})=>e(t._def.innerType),Ii=({schema:e,next:t,isResponse:r})=>t(e._def[r?"out":"in"]),wi=()=>u.createLiteralTypeNode(u.createNull()),Ei=({getAlias:e,makeAlias:t,next:r,serializer:o,schema:i})=>{let s=`Type${o(i.schema)}`;return e(s)||(t(s,u.createLiteralTypeNode(u.createNull())),t(s,r(i.schema)))},zi=({schema:e})=>{let t=e.unwrap(),r=u.createKeywordTypeNode(g.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof kt.ZodString?r:t instanceof kt.ZodUnion?i:o},Zi=({next:e,schema:t})=>e(t.unwrap().shape.raw),Ni={ZodString:ee(g.SyntaxKind.StringKeyword),ZodNumber:ee(g.SyntaxKind.NumberKeyword),ZodBigInt:ee(g.SyntaxKind.BigIntKeyword),ZodBoolean:ee(g.SyntaxKind.BooleanKeyword),ZodAny:ee(g.SyntaxKind.AnyKeyword),[Ie]:ee(g.SyntaxKind.StringKeyword),[we]:ee(g.SyntaxKind.StringKeyword),ZodNull:wi,ZodArray:ui,ZodTuple:Ti,ZodRecord:Si,ZodObject:mi,ZodLiteral:li,ZodIntersection:Ri,ZodUnion:Yr,ZodDefault:Oi,ZodEnum:fi,ZodNativeEnum:hi,ZodEffects:gi,ZodOptional:xi,ZodNullable:bi,ZodDiscriminatedUnion:Yr,ZodBranded:Ai,ZodCatch:Ci,ZodPipeline:Ii,ZodLazy:Ei,ZodReadonly:Pi,[U]:zi,[G]:Zi},ze=({schema:e,...t})=>W({schema:e,rules:Ni,onMissing:()=>u.createKeywordTypeNode(g.SyntaxKind.AnyKeyword),...t});var jt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ue(r,t)),this.getAlias(t)}constructor({routing:t,variant:r="client",serializer:o=De,splitResponse:i=!1,optionalPropStyle:s={withQuestionMark:!0,withUndefined:!0}}){J({routing:t,onEndpoint:(O,A,P)=>{let re={serializer:o,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:s},he=E(P,A,"input"),xe=ze({...re,schema:O.getSchema("input"),isResponse:!1}),I=i?E(P,A,"positive.response"):void 0,Ut=O.getSchema("positive"),Ht=i?ze({...re,isResponse:!0,schema:Ut}):void 0,be=i?E(P,A,"negative.response"):void 0,Ft=O.getSchema("negative"),Kt=i?ze({...re,isResponse:!0,schema:Ft}):void 0,Bt=E(P,A,"response"),Qr=I&&be?n.createUnionTypeNode([n.createTypeReferenceNode(I),n.createTypeReferenceNode(be)]):ze({...re,isResponse:!0,schema:Ut.or(Ft)});this.program.push(ue(xe,he)),Ht&&I&&this.program.push(ue(Ht,I)),Kt&&be&&this.program.push(ue(Kt,be)),this.program.push(ue(Qr,Bt)),P!=="options"&&(this.paths.push(A),this.registry.set({method:P,path:A},{input:he,positive:I,negative:be,response:Bt,isJson:O.getMimeTypes("positive").includes(w.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Nt(this.ids.pathType,this.paths)),this.program.push(Nt(this.ids.methodType,_r)),this.program.push(tt(this.ids.methodPathType,Et([this.ids.methodType,this.ids.pathType])));let a=[n.createHeritageClause(z.SyntaxKind.ExtendsKeyword,[Zt(this.ids.methodPathType,z.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let p=[],d=[];for(let[{method:O,path:A},{isJson:P,tags:re,...he}]of this.registry){let xe=$r(O,A);for(let I of this.interfaces)I.kind in he&&I.props.push(Ur(xe,he[I.kind]));r!=="types"&&(P&&p.push(n.createPropertyAssignment(xe,n.createTrue())),d.push(n.createPropertyAssignment(xe,n.createArrayLiteralExpression(re.map(I=>n.createStringLiteral(I))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(qr(O,a,A));if(r==="types")return;let c=n.createVariableStatement(F,K(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(p))),m=n.createVariableStatement(F,K(this.ids.endpointTagsConst,n.createObjectLiteralExpression(d))),l=tt(this.ids.providerType,n.createFunctionTypeNode(Vr({M:this.ids.methodType,P:this.ids.pathType}),et({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),zt)}),Kr(this.ids.responseInterface,zt))),f=tt(this.ids.implementationType,n.createFunctionTypeNode(void 0,et({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(z.SyntaxKind.StringKeyword),params:Zt(z.SyntaxKind.StringKeyword,z.SyntaxKind.AnyKeyword)}),Br())),b=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,me)]),T=vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[b,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),R=vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[b]),z.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),h=Fr(this.ids.clientClass,jr([Xe(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),kr)]),[Hr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,R]),!0))]);this.program.push(c,m,l,f,h);let S=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),fe=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),Ze=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),ye=n.createVariableStatement(void 0,K(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,me)]),n.createObjectLiteralExpression([S,fe,Ze])])))),te=n.createVariableStatement(void 0,K(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ne=n.createVariableStatement(void 0,K(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),me)])))),[Me,ot]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),ve=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(It,[n.createTemplateSpan(this.ids.methodParameter,wt),n.createTemplateSpan(this.ids.pathParameter,me)]),z.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Me])),N=n.createVariableStatement(F,K(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([te,Ne,ye,ve,ot]),!0),n.createTypeReferenceNode(this.ids.implementationType))),q=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),ge=n.createVariableStatement(void 0,K(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(N,ge,q)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
21
- `):void 0}print(t){let r=this.printUsage(t),o=r&&z.addSyntheticLeadingComment(z.addSyntheticLeadingComment(n.createEmptyStatement(),z.SyntaxKind.SingleLineCommentTrivia," Usage example:"),z.SyntaxKind.MultiLineCommentTrivia,`
22
- ${r}`);return this.program.concat(o||[]).map((i,s)=>Dt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
20
+ `)};var fr=e=>{e.startupLogo!==!1&&console.log(ur());let t=e.errorHandler||Oe,r=or(e.logger)?bt(e.logger):e.logger;r.debug("Running","v19.1.0 (ESM)");let o=lr({rootLogger:r,config:e}),i=pr({rootLogger:r,errorHandler:t}),s=ar({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},Bo=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=fr(e);return Tt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},qo=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=fr(e),a=St().disable("x-powered-by").use(s);if(e.server.compression){let l=await J("compression");a.use(l(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||St.json()],raw:[e.server.rawParser||St.raw(),cr],upload:e.server.upload?await dr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Tt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(l,f)=>l.listen(f,()=>{r.info("Listening",f)}),c={httpServer:d(Fo.createServer(a),e.server.listen),httpsServer:e.https?d(Ko.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...c,logger:r}};import Jn from"assert/strict";import{OpenApiBuilder as Wn}from"openapi3-ts/oas31";import F from"assert/strict";import{isReferenceObject as ee}from"openapi3-ts/oas31";import{both as Vo,complement as Go,concat as _o,type as Yo,filter as Qo,fromPairs as ze,has as Jo,isNil as Wo,map as me,mergeAll as Xo,mergeDeepRight as en,mergeDeepWith as tn,objOf as br,omit as Je,pipe as Tr,pluck as rn,range as on,reject as nn,toLower as sn,union as an,when as pn,xprod as We,zip as dn}from"ramda";import{z as T}from"zod";import{z as Ie}from"zod";var Ye=e=>!isNaN(e.getTime());var we=Symbol("DateIn"),yr=()=>Ie.union([Ie.string().date(),Ie.string().datetime(),Ie.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.date().refine(Ye)).brand(we);import{z as $o}from"zod";var Ee=Symbol("DateOut"),gr=()=>$o.date().refine(Ye).transform(e=>e.toISOString()).brand(Ee);var X=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[y]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:c=>X(c,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),d=t&&t(e,{prev:p,...i});return d?{...p,...d}:p};var hr=50,Sr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",cn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Rr=/:([A-Za-z0-9_]+)/g,Or=e=>e.match(Rr)?.map(t=>t.slice(1))||[],Ar=e=>e.replace(Rr,t=>`{${t.slice(1)}}`),ln=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),mn=({_def:{innerType:e}},{next:t})=>t(e),un=()=>({format:"any"}),fn=({},e)=>(F(!e.isResponse,new A({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),yn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof T.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},gn=({options:e},{next:t})=>({oneOf:e.map(t)}),hn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),xn=e=>{let[t,r]=e.filter(i=>!ee(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));F(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=tn((i,s)=>Array.isArray(i)&&Array.isArray(s)?_o(i,s):i===s?s:F.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=an(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([i,s])=>en(i,s))),o},bn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return xn(o)}catch{}return{allOf:o}},Tn=(e,{next:t})=>t(e.unwrap()),Sn=(e,{next:t})=>t(e.unwrap()),Rn=(e,{next:t})=>{let r=t(e.unwrap());return ee(r)||(r.type=Cr(r)),r},Pr=e=>{let t=sn(Yo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},xr=e=>({type:Pr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),On=({value:e})=>({type:Pr(e),const:e}),An=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Se(p)?p instanceof T.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=Qe(e,r)),s.length&&(a.required=s),a},Pn=()=>({type:"null"}),Cn=({},e)=>(F(!e.isResponse,new A({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Sr}}),In=({},e)=>(F(e.isResponse,new A({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Sr}}),wn=({},e)=>F.fail(new A({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),En=()=>({type:"boolean"}),zn=()=>({type:"integer",format:"bigint"}),Zn=e=>e.every(t=>t instanceof T.ZodLiteral),Nn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof T.ZodEnum||e instanceof T.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=Qe(T.object(ze(We(o,[t]))),r),i.required=o),i}if(e instanceof T.ZodLiteral)return{type:"object",properties:Qe(T.object({[e.value]:t}),r),required:[e.value]};if(e instanceof T.ZodUnion&&Zn(e.options)){let o=me(s=>`${s.value}`,e.options),i=ze(We(o,[t]));return{type:"object",properties:Qe(T.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},Mn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},vn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Dn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(h=>h.kind==="regex"),x=f.find(h=>h.kind==="datetime"),P=m?m.regex:x?x.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,b={type:"string"},z={"date-time":l,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:c};for(let h in z)if(z[h]){b.format=h;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),P&&(b.pattern=P.source),b},Ln=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(({kind:f})=>f==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(({kind:f})=>f==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,c?l.maximum=d:l.exclusiveMaximum=d,l},Qe=({shape:e},t)=>me(t,e),jn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return cn?.[t]},Cr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},kn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!ee(o)){let s=ke(e,jn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(T.any())}if(!t&&i.type==="preprocess"&&!ee(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Hn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Un=(e,{next:t})=>t(e.unwrap()),Fn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},Kn=(e,{next:t})=>t(e.unwrap().shape.raw),Ir=e=>e.length?ze(dn(on(1,e.length+1).map(t=>`example${t}`),me(br("value"),e))):void 0,wr=(e,t,r=[])=>Tr(H,me(pn(Vo(v,Go(Array.isArray)),Je(r))),Ir)({schema:e,variant:t?"parsed":"original",validate:!0}),Bn=(e,t)=>Tr(H,Qo(Jo(t)),rn(t),Ir)({schema:e,variant:"original",validate:!0}),le=(e,t)=>e instanceof T.ZodObject?e:e instanceof T.ZodBranded?le(e.unwrap(),t):e instanceof T.ZodUnion||e instanceof T.ZodDiscriminatedUnion?e.options.map(r=>le(r,t)).reduce((r,o)=>r.merge(o.partial()),T.object({})):e instanceof T.ZodEffects?(F(e._def.effect.type==="refinement",t),le(e._def.schema,t)):le(e._def.left,t).merge(le(e._def.right,t)),Er=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=le(r,new A({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),f=Or(e),m=o.includes("query"),x=o.includes("params"),P=o.includes("headers"),b=h=>x&&f.includes(h),z=h=>P&&at(h);return Object.keys(l).filter(h=>m||b(h)).map(h=>{let N=X(l[h],{rules:{...d,...Ot},onEach:At,onMissing:Pt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),ye=p==="components"?a(w(c,h),N):N;return{name:h,in:b(h)?"path":z(h)?"header":"query",required:!l[h].isOptional(),description:N.description||c,schema:ye,examples:Bn(r,h)}})},Ot={ZodString:Dn,ZodNumber:Ln,ZodBigInt:zn,ZodBoolean:En,ZodNull:Pn,ZodArray:Mn,ZodTuple:vn,ZodRecord:Nn,ZodObject:An,ZodLiteral:On,ZodIntersection:bn,ZodUnion:gn,ZodAny:un,ZodDefault:ln,ZodEnum:xr,ZodNativeEnum:xr,ZodEffects:kn,ZodOptional:Tn,ZodNullable:Rn,ZodDiscriminatedUnion:hn,ZodBranded:Un,ZodDate:wn,ZodCatch:mn,ZodPipeline:Hn,ZodLazy:Fn,ZodReadonly:Sn,[U]:yn,[Re]:fn,[Ee]:In,[we]:Cn,[Y]:Kn},At=(e,{isResponse:t,prev:r})=>{if(ee(r))return{};let{description:o}=e,i=e instanceof T.ZodLazy,s=r.type!==void 0,a=t&&Se(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Cr(r)),d.length&&(c.examples=d.slice()),c},Pt=(e,t)=>F.fail(new A({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Rt=(e,t)=>{if(ee(e))return e;let r={...e};return r.properties&&(r.properties=Je(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>Je(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Rt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Rt(o,t))),r},zr=e=>ee(e)?e:Je(["examples"],e),Zr=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${dt(i)} response ${c?l:""}`.trim()})=>{let x=zr(X(r,{rules:{...f,...Ot},onEach:At,onMissing:Pt,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),P={schema:d==="components"?p(w(m),x):x,examples:wr(r,!0)};return{description:m,content:ze(We(o,[P]))}},qn=()=>({type:"http",scheme:"basic"}),$n=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Vn=({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},Gn=({name:e})=>({type:"apiKey",in:"header",name:e}),_n=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Yn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Qn=({flows:e={}})=>({type:"oauth2",flows:me(t=>({...t,scopes:t.scopes||{}}),nn(Wo,e))}),Nr=(e,t)=>{let r={basic:qn,bearer:$n,input:Vn,header:Gn,cookie:_n,openid:Yn,oauth2:Qn};return Ve(e,o=>r[o.type](o,t))},Xe=e=>"or"in e?e.or.map(t=>"and"in t?Xo(me(({name:r,scopes:o})=>br(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?Xe(ut(e)):Xe({or:[e]}),Mr=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:c=`${e.toUpperCase()} ${t} Request body`})=>{let l=Or(t),f=zr(Rt(X(r,{rules:{...d,...Ot},onEach:At,onMissing:Pt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),l)),m={schema:p==="components"?a(w(c),f):f,examples:wr(r,!1,l)};return{description:c,content:ze(We(o,[m]))}},vr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Ct=e=>e.length<=hr?e:e.slice(0,hr-1)+"\u2026";var It=class extends Wn{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let i=o||w(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&Jn.fail(new A({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:i,serverUrl:s,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:l=je}){super(),this.addInfo({title:o,version:i});for(let m of typeof s=="string"?[s]:s)this.addServer({url:m});W({routing:t,onEndpoint:(m,x,P)=>{let b=P,z={path:x,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[h,N]=["short","long"].map(m.getDescription.bind(m)),ye=h?Ct(h):d&&N?Ct(N):void 0,Ne=m.getTags(),ge=r.inputSources?.[b]||it[b],re=this.ensureUniqOperationId(x,b,m.getOperationId(b)),Me=Er({...z,inputSources:ge,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:x,operationId:re})}),ve={};for(let M of["positive","negative"]){let $=m.getResponses(M);for(let{mimeTypes:he,schema:S,statusCodes:R}of $)for(let O of R)ve[O]=Zr({...z,variant:M,schema:S,mimeTypes:he,statusCode:O,hasMultipleStatusCodes:$.length>1||R.length>1,description:a?.[`${M}Response`]?.call(null,{method:b,path:x,operationId:re,statusCode:O})})}let nt=ge.includes("body")?Mr({...z,schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:x,operationId:re})}):void 0,De=Xe(Ve(Nr(m.getSecurity(),ge),M=>{let $=this.ensureUniqSecuritySchemaName(M),he=["oauth2","openIdConnect"].includes(M.type)?m.getScopes().slice():[];return this.addSecurityScheme($,M),{name:$,scopes:he}}));this.addPath(Ar(x),{[b]:{operationId:re,summary:ye,description:N,tags:Ne.length>0?Ne:void 0,parameters:Me.length>0?Me:void 0,requestBody:nt,security:De.length>0?De:void 0,responses:ve}})}}),this.rootDoc.tags=r.tags?vr(r.tags):[]}};import Dr from"http";var Xn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>I.json),...t}),ei=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:Dr.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=Dr.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},ti=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),ri=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await nr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=Xn({fnMethod:a,requestProps:t}),d=ei({fnMethod:a,responseProps:r}),c=ti({fnMethod:a,loggerProps:i}),l={cors:!1,logger:c,...o};return await e.execute({request:p,response:d,config:l,logger:c}),{requestMock:p,responseMock:d,loggerMock:c}};import E from"typescript";import D from"typescript";import{chain as Lr,toPairs as jr}from"ramda";var n=D.factory,K=[n.createModifier(D.SyntaxKind.ExportKeyword)],oi=[n.createModifier(D.SyntaxKind.AsyncKeyword)],ni=[n.createModifier(D.SyntaxKind.PublicKeyword),n.createModifier(D.SyntaxKind.ReadonlyKeyword)],kr=[n.createModifier(D.SyntaxKind.ProtectedKeyword),n.createModifier(D.SyntaxKind.ReadonlyKeyword)],wt=n.createTemplateHead(""),ue=n.createTemplateTail(""),Et=n.createTemplateMiddle(" "),zt=e=>n.createTemplateLiteralType(wt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?ue:Et))),Zt=zt(["M","P"]),et=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),tt=(e,t)=>Lr(([r,o])=>[et(n.createIdentifier(r),o,t)],jr(e)),Nt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),Hr=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),Ur=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),B=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],D.NodeFlags.Const),Mt=(e,t)=>n.createTypeAliasDeclaration(K,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),rt=(e,t)=>n.createTypeAliasDeclaration(K,e,void 0,t),Fr=(e,t,r)=>n.createPropertyDeclaration(ni,e,void 0,t,r),Kr=(e,t,r)=>n.createClassDeclaration(K,e,void 0,void 0,[t,...r]),Br=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),qr=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.SyntaxKind.AnyKeyword)]),$r=(e,t,r)=>n.createInterfaceDeclaration(K,e,void 0,t,r),Vr=e=>Lr(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],jr(e)),vt=(e,t,r)=>n.createArrowFunction(r?oi:void 0,void 0,e.map(o=>et(o)),void 0,void 0,t),Dt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,tt({acc:void 0,key:void 0}),void 0,void 0,t),r]),Gr=(...e)=>`"${e.join(" ")}"`;var _r=["get","post","put","delete","patch"];import g from"typescript";import{z as kt}from"zod";import q from"typescript";var{factory:ot}=q,Lt=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},fe=(e,t,r)=>{let o=ot.createTypeAliasDeclaration(void 0,ot.createIdentifier(t),void 0,e);return r&&Lt(o,r),o},jt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},ii=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yr=e=>ii.test(e)?ot.createIdentifier(e):ot.createStringLiteral(e);var{factory:u}=g,si={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},ai=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),pi=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Se(a)?a instanceof kt.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Yr(s),p&&o?u.createToken(g.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Lt(d,a.description),d});return u.createTypeLiteralNode(i)},di=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),ci=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Qr=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),li=e=>si?.[e.kind],mi=(e,{next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=ke(e,li(o)),a={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||g.SyntaxKind.AnyKeyword)}return o},ui=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),fi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(g.SyntaxKind.UndefinedKeyword)]):o},yi=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),gi=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),hi=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),xi=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),bi=({_def:e},{next:t})=>t(e.innerType),te=e=>()=>u.createKeywordTypeNode(e),Ti=(e,{next:t})=>t(e.unwrap()),Si=(e,{next:t})=>t(e.unwrap()),Ri=({_def:e},{next:t})=>t(e.innerType),Oi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ai=()=>u.createLiteralTypeNode(u.createNull()),Pi=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,u.createLiteralTypeNode(u.createNull())),r(s,o(e)))},Ci=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(g.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof kt.ZodString?r:t instanceof kt.ZodUnion?i:o},Ii=(e,{next:t})=>t(e.unwrap().shape.raw),wi={ZodString:te(g.SyntaxKind.StringKeyword),ZodNumber:te(g.SyntaxKind.NumberKeyword),ZodBigInt:te(g.SyntaxKind.BigIntKeyword),ZodBoolean:te(g.SyntaxKind.BooleanKeyword),ZodAny:te(g.SyntaxKind.AnyKeyword),[we]:te(g.SyntaxKind.StringKeyword),[Ee]:te(g.SyntaxKind.StringKeyword),ZodNull:Ai,ZodArray:di,ZodTuple:gi,ZodRecord:hi,ZodObject:pi,ZodLiteral:ai,ZodIntersection:xi,ZodUnion:Qr,ZodDefault:bi,ZodEnum:ci,ZodNativeEnum:ui,ZodEffects:mi,ZodOptional:fi,ZodNullable:yi,ZodDiscriminatedUnion:Qr,ZodBranded:Ti,ZodCatch:Ri,ZodPipeline:Oi,ZodLazy:Pi,ZodReadonly:Si,[U]:Ci,[Y]:Ii},Ze=(e,{brandHandling:t,ctx:r})=>X(e,{rules:{...t,...wi},onMissing:()=>u.createKeywordTypeNode(g.SyntaxKind.AnyKeyword),ctx:r});var Ht=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,fe(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=je,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){W({routing:t,onEndpoint:(S,R,O)=>{let oe={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},xe=w(O,R,"input"),be=Ze(S.getSchema("input"),{brandHandling:r,ctx:{...oe,isResponse:!1}}),C=s?w(O,R,"positive.response"):void 0,Ut=S.getSchema("positive"),Ft=s?Ze(Ut,{brandHandling:r,ctx:{...oe,isResponse:!0}}):void 0,Te=s?w(O,R,"negative.response"):void 0,Kt=S.getSchema("negative"),Bt=s?Ze(Kt,{brandHandling:r,ctx:{...oe,isResponse:!0}}):void 0,qt=w(O,R,"response"),Jr=C&&Te?n.createUnionTypeNode([n.createTypeReferenceNode(C),n.createTypeReferenceNode(Te)]):Ze(Ut.or(Kt),{brandHandling:r,ctx:{...oe,isResponse:!0}});this.program.push(fe(be,xe)),Ft&&C&&this.program.push(fe(Ft,C)),Bt&&Te&&this.program.push(fe(Bt,Te)),this.program.push(fe(Jr,qt)),O!=="options"&&(this.paths.push(R),this.registry.set({method:O,path:R},{input:xe,positive:C,negative:Te,response:qt,isJson:S.getMimeTypes("positive").includes(I.json),tags:S.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Mt(this.ids.pathType,this.paths)),this.program.push(Mt(this.ids.methodType,_r)),this.program.push(rt(this.ids.methodPathType,zt([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:S,path:R},{isJson:O,tags:oe,...xe}]of this.registry){let be=Gr(S,R);for(let C of this.interfaces)C.kind in xe&&C.props.push(Ur(be,xe[C.kind]));o!=="types"&&(O&&d.push(n.createPropertyAssignment(be,n.createTrue())),c.push(n.createPropertyAssignment(be,n.createArrayLiteralExpression(oe.map(C=>n.createStringLiteral(C))))))}for(let{id:S,props:R}of this.interfaces)this.program.push($r(S,p,R));if(o==="types")return;let l=n.createVariableStatement(K,B(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(d))),f=n.createVariableStatement(K,B(this.ids.endpointTagsConst,n.createObjectLiteralExpression(c))),m=rt(this.ids.providerType,n.createFunctionTypeNode(Vr({M:this.ids.methodType,P:this.ids.pathType}),tt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Zt)}),Br(this.ids.responseInterface,Zt))),x=rt(this.ids.implementationType,n.createFunctionTypeNode(void 0,tt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),qr())),P=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,ue)]),b=Dt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[P,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),z=Dt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[P]),E.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),h=Kr(this.ids.clientClass,Hr([et(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),kr)]),[Fr(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),vt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,z]),!0))]);this.program.push(l,f,m,x,h);let N=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ye=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(I.json))]),void 0,this.ids.undefinedValue)),Ne=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),ge=n.createVariableStatement(void 0,B(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,ue)]),n.createObjectLiteralExpression([N,ye,Ne])])))),re=n.createVariableStatement(void 0,B(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Me=n.createVariableStatement(void 0,B(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),ue)])))),[ve,nt]=["json","text"].map(S=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,S),void 0,void 0))),De=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(wt,[n.createTemplateSpan(this.ids.methodParameter,Et),n.createTemplateSpan(this.ids.pathParameter,ue)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([ve])),M=n.createVariableStatement(K,B(this.ids.exampleImplementationConst,vt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([re,Me,ge,De,nt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),$=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),he=n.createVariableStatement(void 0,B(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(M,he,$)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:jt(r,t)).join(`
21
+ `):void 0}print(t){let r=this.printUsage(t),o=r&&E.addSyntheticLeadingComment(E.addSyntheticLeadingComment(n.createEmptyStatement(),E.SyntaxKind.SingleLineCommentTrivia," Usage example:"),E.SyntaxKind.MultiLineCommentTrivia,`
22
+ ${r}`);return this.program.concat(o||[]).map((i,s)=>jt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
23
23
 
24
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Q("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var Mi={dateIn:fr,dateOut:yr,file:Fe,upload:Gt,raw:_t};export{de as AbstractEndpoint,Ae as DependsOnMethod,Ct as Documentation,C as DocumentationError,Oe as EndpointsFactory,D as InputValidationError,jt as Integration,ne as MissingPeerError,V as OutputValidationError,oe as RoutingError,Pe as ServeStatic,wo as arrayEndpointsFactory,gt as arrayResultHandler,_o as attachRouting,uo as createConfig,xt as createLogger,ft as createMiddleware,yt as createResultHandler,Go as createServer,Io as defaultEndpointsFactory,Re as defaultResultHandler,Mi as ez,j as getExamples,k as getMessageFromError,Le as getStatusCodeFromError,si as testEndpoint};
24
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await J("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var Ei={dateIn:yr,dateOut:gr,file:Ke,upload:Yt,raw:_t};export{ce as AbstractEndpoint,Pe as DependsOnMethod,It as Documentation,A as DocumentationError,Ae as EndpointsFactory,j as InputValidationError,Ht as Integration,ie as MissingPeerError,V as OutputValidationError,ne as RoutingError,Ce as ServeStatic,Ao as arrayEndpointsFactory,ht as arrayResultHandler,Bo as attachRouting,fo as createConfig,bt as createLogger,yt as createMiddleware,gt as createResultHandler,qo as createServer,Oo as defaultEndpointsFactory,Oe as defaultResultHandler,Ei as ez,H as getExamples,k as getMessageFromError,Le as getStatusCodeFromError,ri as testEndpoint};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "19.0.0",
3
+ "version": "19.1.0",
4
4
  "description": "A Typescript library to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {