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