express-zod-api 22.7.0 → 22.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/README.md +31 -6
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +26 -11
- package/dist/index.d.ts +26 -11
- package/dist/index.js +8 -8
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,66 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 22
|
|
4
4
|
|
|
5
|
+
### v22.9.0
|
|
6
|
+
|
|
7
|
+
- Featuring Deprecations:
|
|
8
|
+
- You can deprecate all usage of an `Endpoint` using `EndpointsFactory::build({ deprecated: true })`;
|
|
9
|
+
- You can deprecate a route using the assigned `Endpoint::deprecated()` or `DependsOnMethod::deprecated()`;
|
|
10
|
+
- You can deprecate a schema using `ZodType::deprecated()`;
|
|
11
|
+
- All `.deprecated()` methods are immutable — they create a new copy of the subject;
|
|
12
|
+
- Deprecated schemas and endpoints are reflected in the generated `Documentation` and `Integration`;
|
|
13
|
+
- The feature suggested by [@mlms13](https://github.com/mlms13).
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Routing, DependsOnMethod } from "express-zod-api";
|
|
17
|
+
import { z } from "zod";
|
|
18
|
+
|
|
19
|
+
const someEndpoint = factory.build({
|
|
20
|
+
deprecated: true, // deprecates all routes the endpoint assigned to
|
|
21
|
+
input: z.object({
|
|
22
|
+
prop: z.string().deprecated(), // deprecates the property or a path parameter
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const routing: Routing = {
|
|
27
|
+
v1: oldEndpoint.deprecated(), // deprecates the /v1 path
|
|
28
|
+
v2: new DependsOnMethod({ get: oldEndpoint }).deprecated(), // deprecates the /v2 path
|
|
29
|
+
v3: someEndpoint, // the path is assigned with initially deprecated endpoint (also deprecated)
|
|
30
|
+
};
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### v22.8.0
|
|
34
|
+
|
|
35
|
+
- Feature: warning about the endpoint input scheme ignoring the parameters of the route to which it is assigned:
|
|
36
|
+
- There is a technological gap between routing and endpoints, which at the same time allows an endpoint to be reused
|
|
37
|
+
across multiple routes. Therefore, there are no constraints between the route parameters and the `input` schema;
|
|
38
|
+
- This version introduces checking for such discrepancies:
|
|
39
|
+
- non-use of the path parameter or,
|
|
40
|
+
- a mistake in manually entering its name;
|
|
41
|
+
- The warning is displayed when the application is launched and NOT in production mode.
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
const updateUserEndpoint = factory.build({
|
|
45
|
+
method: "patch",
|
|
46
|
+
input: z.object({
|
|
47
|
+
id: z.string(), // implies path parameter "id"
|
|
48
|
+
}),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const routing: Routing = {
|
|
52
|
+
v1: {
|
|
53
|
+
user: {
|
|
54
|
+
":username": updateUserEndpoint, // path parameter is "username" instead of "id"
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```shell
|
|
61
|
+
warn: The input schema of the endpoint is most likely missing the parameter of the path it is assigned to.
|
|
62
|
+
{ method: 'patch', path: '/v1/user/:username', param: 'username' }
|
|
63
|
+
```
|
|
64
|
+
|
|
5
65
|
### v22.7.0
|
|
6
66
|
|
|
7
67
|
- Technical release in connection with the implementation of workspaces into the project architecture.
|
package/README.md
CHANGED
|
@@ -57,7 +57,8 @@ Start your API server with I/O schema validation and custom middlewares in minut
|
|
|
57
57
|
2. [Generating a Frontend Client](#generating-a-frontend-client)
|
|
58
58
|
3. [Creating a documentation](#creating-a-documentation)
|
|
59
59
|
4. [Tagging the endpoints](#tagging-the-endpoints)
|
|
60
|
-
5. [
|
|
60
|
+
5. [Deprecated schemas and routes](#deprecated-schemas-and-routes)
|
|
61
|
+
6. [Customizable brands handling](#customizable-brands-handling)
|
|
61
62
|
8. [Caveats](#caveats)
|
|
62
63
|
1. [Coercive schema of Zod](#coercive-schema-of-zod)
|
|
63
64
|
2. [Excessive properties in endpoint output](#excessive-properties-in-endpoint-output)
|
|
@@ -86,6 +87,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
|
|
|
86
87
|
|
|
87
88
|
These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
|
|
88
89
|
|
|
90
|
+
[<img src="https://github.com/mlms13.png" alt="@mlms13" width="50px" />](https://github.com/mlms13)
|
|
89
91
|
[<img src="https://github.com/bobgubko.png" alt="@bobgubko" width="50px" />](https://github.com/bobgubko)
|
|
90
92
|
[<img src="https://github.com/LucWag.png" alt="@LucWag" width="50px" />](https://github.com/LucWag)
|
|
91
93
|
[<img src="https://github.com/HenriJ.png" alt="@HenriJ" width="50px" />](https://github.com/HenriJ)
|
|
@@ -689,9 +691,9 @@ done(); // error: expensive operation '555.55ms'
|
|
|
689
691
|
## Enabling compression
|
|
690
692
|
|
|
691
693
|
According to [Express.js best practices guide](http://expressjs.com/en/advanced/best-practice-performance.html)
|
|
692
|
-
it might be a good idea to enable GZIP compression
|
|
694
|
+
it might be a good idea to enable GZIP and Brotli compression for your API responses.
|
|
693
695
|
|
|
694
|
-
Install
|
|
696
|
+
Install `compression` (version 1.8 supports Brotli) and `@types/compression`, and enable or configure compression:
|
|
695
697
|
|
|
696
698
|
```typescript
|
|
697
699
|
import { createConfig } from "express-zod-api";
|
|
@@ -703,7 +705,7 @@ const config = createConfig({
|
|
|
703
705
|
```
|
|
704
706
|
|
|
705
707
|
In order to receive a compressed response the client should include the following header in the request:
|
|
706
|
-
`Accept-Encoding: gzip, deflate`. Only responses with compressible content types are subject to compression.
|
|
708
|
+
`Accept-Encoding: br, gzip, deflate`. Only responses with compressible content types are subject to compression.
|
|
707
709
|
|
|
708
710
|
# Advanced features
|
|
709
711
|
|
|
@@ -1236,6 +1238,7 @@ framework, [Zod Sockets](https://github.com/RobinTail/zod-sockets), which has si
|
|
|
1236
1238
|
Express Zod API acts as a plugin for Zod, extending its functionality once you import anything from `express-zod-api`:
|
|
1237
1239
|
|
|
1238
1240
|
- Adds `.example()` method to all Zod schemas for storing examples and reflecting them in the generated documentation;
|
|
1241
|
+
- Adds `.deprecated()` method to all schemas for marking properties and request parameters as deprecated;
|
|
1239
1242
|
- Adds `.label()` method to `ZodDefault` for replacing the default value in documentation with a label;
|
|
1240
1243
|
- Adds `.remap()` method to `ZodObject` for renaming object properties in a suitable way for making documentation;
|
|
1241
1244
|
- Alters the `.brand()` method on all Zod schemas by making the assigned brand available in runtime.
|
|
@@ -1340,6 +1343,30 @@ new Documentation({
|
|
|
1340
1343
|
});
|
|
1341
1344
|
```
|
|
1342
1345
|
|
|
1346
|
+
## Deprecated schemas and routes
|
|
1347
|
+
|
|
1348
|
+
As your API evolves, you may need to mark some parameters or routes as deprecated before deleting them. For this
|
|
1349
|
+
purpose, the `.deprecated()` method is available on each schema, `Endpoint` and `DependsOnMethod`, it's immutable.
|
|
1350
|
+
You can also deprecate all routes the `Endpoint` assigned to by setting `EndpointsFactory::build({ deprecated: true })`.
|
|
1351
|
+
|
|
1352
|
+
```ts
|
|
1353
|
+
import { Routing, DependsOnMethod } from "express-zod-api";
|
|
1354
|
+
import { z } from "zod";
|
|
1355
|
+
|
|
1356
|
+
const someEndpoint = factory.build({
|
|
1357
|
+
deprecated: true, // deprecates all routes the endpoint assigned to
|
|
1358
|
+
input: z.object({
|
|
1359
|
+
prop: z.string().deprecated(), // deprecates the property or a path parameter
|
|
1360
|
+
}),
|
|
1361
|
+
});
|
|
1362
|
+
|
|
1363
|
+
const routing: Routing = {
|
|
1364
|
+
v1: oldEndpoint.deprecated(), // deprecates the /v1 path
|
|
1365
|
+
v2: new DependsOnMethod({ get: oldEndpoint }).deprecated(), // deprecates the /v2 path
|
|
1366
|
+
v3: someEndpoint, // the path is assigned with initially deprecated endpoint (also deprecated)
|
|
1367
|
+
};
|
|
1368
|
+
```
|
|
1369
|
+
|
|
1343
1370
|
## Customizable brands handling
|
|
1344
1371
|
|
|
1345
1372
|
You can customize handling rules for your schemas in Documentation and Integration. Use the `.brand()` method on your
|
|
@@ -1412,8 +1439,6 @@ const output = z.object({
|
|
|
1412
1439
|
});
|
|
1413
1440
|
|
|
1414
1441
|
endpointsFactory.build({
|
|
1415
|
-
method,
|
|
1416
|
-
input,
|
|
1417
1442
|
output,
|
|
1418
1443
|
handler: async (): Promise<z.input<typeof output>> => ({
|
|
1419
1444
|
anything: 123,
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:(0,ft.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var $t=require("zod");var Vt=class{},V=class extends Vt{#e;#t;#r;constructor({input:t=$t.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 $t.z.ZodError?new J(o):o}}},ke=class extends V{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Ce=class{nest(t){return Object.assign(t,{"":this})}};var We=class extends Ce{},ht=class extends We{#e;#t;#r;#n;#s;#i;#o;#a;#p;#c;#d;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:s,getOperationId:a=()=>{},scopes:c=[],middlewares:d=[],tags:p=[],description:l,shortDescription:g}){super(),this.#s=n,this.#i=s,this.#r=d,this.#c=a,this.#t=Object.freeze(t),this.#a=Object.freeze(c),this.#p=Object.freeze(p),this.#e={long:l,short:g},this.#o={input:r,output:o},this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#d=Cr(r)?"upload":jr(r)?"raw":"json"}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return this.#o[t]}getRequestType(){return this.#d}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return this.#a}getTags(){return this.#p}getOperationId(t){return this.#c(t)}async#m(t){try{return await this.#o.output.parseAsync(t)}catch(r){throw r instanceof _t.z.ZodError?new ne(r):r}}async#l({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof ke))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#u({input:t,...r}){let o;try{o=await this.#o.input.parseAsync(t)}catch(n){throw n instanceof _t.z.ZodError?new J(n):n}return this.#s({...r,input:o})}async#y({error:t,...r}){try{await this.#i.execute({...r,error:t})}catch(o){gt({...r,error:new se(ae(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Kt(t),a={},c=null,d=null,p=it(t,n.inputSources);try{if(await this.#l({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#m(await this.#u({input:p,logger:o,options:a}))}catch(l){d=ae(l)}await this.#y({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};var Lr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Or(s,n),o)};var _=require("zod");var je={positive:200,negative:400},Ne=Object.keys(je);var Gt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},de=class extends Gt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Bt(this.#e,{variant:"positive",args:[t],statusCodes:[je.positive],mimeTypes:[v.json]})}getNegativeResponse(){return Bt(this.#t,{variant:"negative",args:[],statusCodes:[je.negative],mimeTypes:[v.json]})}},Le=new de({positive:e=>{let t=te({schema:e,pullProps:!0}),r=_.z.object({status:_.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:_.z.object({status:_.z.literal("error"),error:_.z.object({message:_.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Oe(e);return Je(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Re(a)}})}n.status(je.positive).json({status:"success",data:r})}}),xt=new de({positive:e=>{let t=te({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof _.z.ZodArray?e.shape.items:_.z.array(_.z.any());return t.reduce((o,n)=>xe(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:_.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Oe(r);return Je(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Re(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(je.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var me=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof V?t:new V(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new ke(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new V({handler:t})),this.resultHandler)}build({input:t=Yt.z.object({}),handler:r,output:o,description:n,shortDescription:s,operationId:a,scope:c,tag:d,method:p}){let{middlewares:l,resultHandler:g}=this,b=typeof p=="string"?[p]:p,f=typeof a=="function"?a:()=>a,R=typeof c=="string"?[c]:c||[],O=typeof d=="string"?[d]:d||[];return new ht({handler:r,middlewares:l,outputSchema:o,resultHandler:g,scopes:R,tags:O,methods:b,getOperationId:f,description:n,shortDescription:s,inputSchema:Lr(l,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Yt.z.object({}),handler:async o=>(await t(o),{})})}},Mr=new me(Le),Ur=new me(xt);var Br=j(require("ansis"),1),$r=require("node:util"),Wt=require("node:perf_hooks");var Q=require("ansis"),Hr=require("ramda");var Jt={debug:Q.blue,info:Q.green,warn:(0,Q.hex)("#FFA500"),error:Q.red,ctx:Q.cyanBright},bt={debug:10,info:20,warn:30,error:40},Kr=e=>xe(e)&&Object.keys(bt).some(t=>t in e),Dr=e=>e in bt,Fr=(e,t)=>bt[e]<bt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Me=(0,Hr.memoizeWith)((e,t)=>`${e}${t}`,gn),qr=e=>e<1e-6?Me("nanosecond",3).format(e/1e-6):e<.001?Me("nanosecond").format(e/1e-6):e<1?Me("microsecond").format(e/.001):e<1e3?Me("millisecond").format(e):e<6e4?Me("second",2).format(e/1e3):Me("minute",2).format(e/6e4);var Ue=class e{config;constructor({color:t=Br.default.isSupported(),level:r=Ie()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return(0,$r.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||Fr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Jt.ctx(s):s),d.push(c?`${Jt[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})}get ctx(){return this.config.ctx}profile(t){let r=Wt.performance.now();return()=>{let o=Wt.performance.now()-r,{message:n,severity:s="debug",formatter:a=qr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Ke=require("ramda");var He=class extends Ce{entries;constructor(t){super();let r=[],o=(0,Ke.keys)(t);for(let n of o){let s=t[n];s&&r.push([n,s,(0,Ke.reject)((0,Ke.equals)(n),o)])}this.entries=Object.freeze(r)}};var Vr=j(require("express"),1),De=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Vr.default.static(...this.params))}};var Tt=j(require("express"),1),lo=j(require("node:http"),1),uo=j(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>j(require(e))))[t]}catch{}throw new ze(e)};var Gr=j(require("http-errors"),1);var St=class{constructor(t){this.logger=t}#e=new WeakSet;check(t,r){if(!this.#e.has(t)){if(t.getRequestType()==="json")try{qt(t.getSchema("input"),"in")}catch(o){this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ne)for(let{mimeTypes:n,schema:s}of t.getResponses(o))if(n?.includes(v.json))try{qt(s,"out")}catch(a){this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:a}))}this.#e.add(t)}}};var _r=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new ge(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),qe=({routing:e,onEndpoint:t,onStatic:r})=>{let o=_r(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof We){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof De)r&&s.apply(n,r);else if(s instanceof He)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new ge(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(..._r(s,n))}};var hn=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,Gr.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Qt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new St(t()),a=new Map;if(qe({routing:o,onEndpoint:(d,p,l,g)=>{Ie()||s.check(d,{path:p,method:l});let b=n?.[d.getRequestType()]||[],f=async(R,O)=>{let M=t(R);if(r.cors){let z={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...g||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},Z=typeof r.cors=="function"?await r.cors({request:R,endpoint:d,logger:M,defaultHeaders:z}):z;for(let H in Z)O.set(H,Z[H])}return d.execute({request:R,response:O,logger:M,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...b,f),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...b,f)},onStatic:e.use.bind(e)}),r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,hn(p))};var Qe=j(require("http-errors"),1);var eo=require("node:timers/promises");var Yr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Jr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Wr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Qr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Xr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var to=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Yr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let d=async()=>{for(let p of e)p.on("request",Qr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Wr(p)||Jr(p))&&a(p);for await(let p of(0,eo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Xr))};return{sockets:n,shutdown:()=>o??=d()}};var ro=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,Qe.isHttpError)(r)?r:(0,Qe.default)(400,ae(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),oo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Qe.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){gt({response:o,logger:s,error:new se(ae(a),n)})}},xn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},bn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await Fe("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(g){return p(g)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:bn(l)})(c,d,p)}),o&&a.push(xn(o)),a},so=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},io=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[x]={logger:s}),n()},ao=e=>t=>t?.res?.locals[x]?.logger||e,po=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
"use strict";var on=Object.create;var at=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var sn=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,pn=Object.prototype.hasOwnProperty;var cn=(e,t)=>{for(var r in t)at(e,r,{get:t[r],enumerable:!0})},Pr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of sn(t))!pn.call(e,n)&&n!==r&&at(e,n,{get:()=>t[n],enumerable:!(o=nn(t,n))||o.enumerable});return e};var k=(e,t,r)=>(r=e!=null?on(an(e)):{},Pr(t||!e||!e.__esModule?at(r,"default",{value:e,enumerable:!0}):r,e)),dn=e=>Pr(at({},"__esModule",{value:!0}),e);var Ys={};cn(Ys,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>wt,DocumentationError:()=>q,EndpointsFactory:()=>ye,EventStreamFactory:()=>Mt,InputValidationError:()=>Y,Integration:()=>Lt,Middleware:()=>_,MissingPeerError:()=>Ze,OutputValidationError:()=>ae,ResultHandler:()=>fe,RoutingError:()=>xe,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Fr,arrayResultHandler:()=>St,attachRouting:()=>So,createConfig:()=>wr,createServer:()=>To,defaultEndpointsFactory:()=>Kr,defaultResultHandler:()=>Ue,ensureHttpError:()=>Pe,ez:()=>rn,getExamples:()=>ne,getMessageFromError:()=>ce,testEndpoint:()=>Bo,testMiddleware:()=>$o});module.exports=dn(Ys);var U=require("ramda"),Te=require("zod");var oe=require("ramda"),Kt=require("zod");var I={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var xe=class extends Error{name="RoutingError"},q=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},pt=class extends Error{name="IOSchemaError"},ae=class extends pt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="OutputValidationError"},Y=class extends pt{constructor(r){super(ce(r),{cause:r});this.cause=r}name="InputValidationError"},pe=class extends Error{constructor(r,o){super(ce(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ze=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Ft=/:([A-Za-z0-9_]+)/g,ct=e=>e.match(Ft)?.map(t=>t.slice(1))||[],mn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(I.upload);return"files"in e&&r},qt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},ln=["body","query","params"],Bt=e=>e.method.toLowerCase(),dt=(e,t={})=>{let r=Bt(e);return r==="options"?{}:(t[r]||qt[r]||ln).filter(o=>o==="files"?mn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},de=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof Kt.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ae?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,un=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return be(t,(n[g]?.examples||[]).map((0,oe.objOf)(r)),([s,a])=>({...s,...a}))},[]),ne=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[g]?.examples||[];if(!n.length&&o&&e instanceof Kt.z.ZodObject&&(n=un(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},be=(e,t,r)=>e.length&&t.length?(0,oe.xprod)(e,t).map(r):e.concat(t),We=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,$t=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),me=(...e)=>{let t=(0,oe.chain)(o=>o.split(/[^A-Z0-9]/gi),e);return(0,oe.chain)(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map($t).join("")},mt=(e,t)=>{try{return typeof e.parse(t)}catch{return}},Se=e=>typeof e=="object"&&e!==null,ve=(0,oe.memoizeWith)(()=>"static",()=>process.env.NODE_ENV==="production");var lt=require("ramda"),g=Symbol.for("express-zod-api"),Ye=e=>{let t=e.describe(e.description);return t._def[g]=(0,lt.clone)(t._def[g])||{examples:[]},t},Ar=(e,t)=>{if(!(g in e._def))return t;let r=Ye(t);return r._def[g].examples=be(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?(0,lt.mergeDeepRight)({...o},{...n}):n),r};var fn=function(e){let t=Ye(this);return t._def[g].examples.push(e),t},yn=function(){let e=Ye(this);return e._def[g].isDeprecated=!0,e},gn=function(e){let t=Ye(this);return t._def[g].defaultLabel=e,t},hn=function(e){return new Te.z.ZodBranded({typeName:Te.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...(0,U.clone)(this._def[g]),brand:e}})},xn=function(e){let t=typeof e=="function"?e:(0,U.pipe)(U.toPairs,(0,U.map)(([n,s])=>(0,U.pair)(e[String(n)]||n,s)),U.fromPairs),r=t((0,U.clone)(this.shape)),o=Te.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(Te.z.ZodType.prototype,{example:{get(){return fn.bind(this)}},deprecated:{get(){return yn.bind(this)}},brand:{set(){},get(){return hn.bind(this)}}}),Object.defineProperty(Te.z.ZodDefault.prototype,"label",{get(){return gn.bind(this)}}),Object.defineProperty(Te.z.ZodObject.prototype,"remap",{get(){return xn.bind(this)}}));function wr(e){return e}var Qt=require("zod");var Wt=require("zod");var C=require("node:assert/strict");var ke=require("zod");var ut=e=>!isNaN(e.getTime());var Oe=Symbol("DateIn"),Er=()=>ke.z.union([ke.z.string().date(),ke.z.string().datetime(),ke.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ke.z.date().refine(ut)).brand(Oe);var zr=require("zod");var Re=Symbol("DateOut"),Ir=()=>zr.z.date().refine(ut).transform(e=>e.toISOString()).brand(Re);var Qe=require("zod"),Q=Symbol("File"),Zr=Qe.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),bn={buffer:()=>Zr.brand(Q),string:()=>Qe.z.string().brand(Q),binary:()=>Zr.or(Qe.z.string()).brand(Q),base64:()=>Qe.z.string().base64().brand(Q)};function ft(e){return bn[e||"string"]()}var vr=require("zod");var le=Symbol("Raw"),kr=(e={})=>vr.z.object({raw:ft("buffer")}).extend(e).brand(le);var Cr=require("zod"),Ce=Symbol("Upload"),jr=()=>Cr.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(Ce);var Nr=(e,{next:t})=>e.options.some(t),Sn=({_def:e},{next:t})=>[e.left,e.right].some(t),yt=(e,{next:t})=>t(e.unwrap()),_t={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Nr,ZodDiscriminatedUnion:Nr,ZodIntersection:Sn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:yt,ZodNullable:yt,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},gt=(e,{condition:t,rules:r=_t,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Lr=e=>gt(e,{condition:t=>t._def[g]?.brand===Ce}),Mr=e=>gt(e,{condition:t=>t._def[g]?.brand===le,maxDepth:3}),Ur=(e,t)=>{let r=new WeakSet;return gt(e,{maxDepth:300,rules:{..._t,ZodBranded:yt,ZodReadonly:yt,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:_t.ZodEffects}[t],ZodNaN:()=>(0,C.fail)("z.nan()"),ZodSymbol:()=>(0,C.fail)("z.symbol()"),ZodFunction:()=>(0,C.fail)("z.function()"),ZodMap:()=>(0,C.fail)("z.map()"),ZodSet:()=>(0,C.fail)("z.set()"),ZodBigInt:()=>(0,C.fail)("z.bigint()"),ZodVoid:()=>(0,C.fail)("z.void()"),ZodPromise:()=>(0,C.fail)("z.promise()"),ZodNever:()=>(0,C.fail)("z.never()"),ZodDate:()=>t==="in"&&(0,C.fail)("z.date()"),[Re]:()=>t==="in"&&(0,C.fail)("ez.dateOut()"),[Oe]:()=>t==="out"&&(0,C.fail)("ez.dateIn()"),[le]:()=>t==="out"&&(0,C.fail)("ez.raw()"),[Ce]:()=>t==="out"&&(0,C.fail)("ez.upload()"),[Q]:()=>!1}})};var ht=k(require("http-errors"),1);var Xe=k(require("http-errors"),1),Dr=require("zod");var Vt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Dr.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new pe(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},et=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Pe=e=>(0,Xe.isHttpError)(e)?e:(0,Xe.default)(e instanceof Y?400:500,ce(e),{cause:e.cause||e}),Ae=e=>ve()&&!e.expose?(0,Xe.default)(e.statusCode).message:e.message;var xt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Ae((0,ht.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:(0,ht.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Gt=require("zod");var Jt=class{},_=class extends Jt{#e;#t;#r;constructor({input:t=Gt.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 Gt.z.ZodError?new Y(o):o}}},je=class extends _{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Ne=class{nest(t){return Object.assign(t,{"":this})}};var tt=class extends Ne{},bt=class e extends tt{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return Lr(this.#e.inputSchema)?"upload":Mr(this.#e.inputSchema)?"raw":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Wt.z.ZodError?new ae(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof je))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Wt.z.ZodError?new Y(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){xt({...r,error:new pe(de(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Bt(t),a={},c=null,d=null,p=dt(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(l){d=de(l)}await this.#s({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};var ue=require("zod");var Hr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ar(s,n),o)},V=e=>e instanceof ue.z.ZodObject?e:e instanceof ue.z.ZodBranded?V(e.unwrap()):e instanceof ue.z.ZodUnion||e instanceof ue.z.ZodDiscriminatedUnion?e.options.map(t=>V(t)).reduce((t,r)=>t.merge(r.partial()),ue.z.object({})):e instanceof ue.z.ZodEffects?V(e._def.schema):e instanceof ue.z.ZodPipeline?V(e._def.in):V(e._def.left).merge(V(e._def.right));var G=require("zod");var Le={positive:200,negative:400},Me=Object.keys(Le);var Yt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},fe=class extends Yt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Vt(this.#e,{variant:"positive",args:[t],statusCodes:[Le.positive],mimeTypes:[I.json]})}getNegativeResponse(){return Vt(this.#t,{variant:"negative",args:[],statusCodes:[Le.negative],mimeTypes:[I.json]})}},Ue=new fe({positive:e=>{let t=ne({schema:e,pullProps:!0}),r=G.z.object({status:G.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:G.z.object({status:G.z.literal("error"),error:G.z.object({message:G.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Pe(e);return et(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:Ae(a)}})}n.status(Le.positive).json({status:"success",data:r})}}),St=new fe({positive:e=>{let t=ne({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof G.z.ZodArray?e.shape.items:G.z.array(G.z.any());return t.reduce((o,n)=>Se(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:G.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Pe(r);return et(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(Ae(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Le.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var ye=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof _?t:new _(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new je(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new _({handler:t})),this.resultHandler)}build({input:t=Qt.z.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:d,resultHandler:p}=this,l=typeof a=="string"?[a]:a,b=typeof o=="function"?o:()=>o,S=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new bt({...c,middlewares:d,outputSchema:r,resultHandler:p,scopes:S,tags:y,methods:l,getOperationId:b,inputSchema:Hr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Qt.z.object({}),handler:async o=>(await t(o),{})})}},Kr=new ye(Ue),Fr=new ye(St);var Gr=k(require("ansis"),1),Jr=require("node:util"),er=require("node:perf_hooks");var X=require("ansis"),qr=require("ramda");var Xt={debug:X.blue,info:X.green,warn:(0,X.hex)("#FFA500"),error:X.red,ctx:X.cyanBright},Tt={debug:10,info:20,warn:30,error:40},Br=e=>Se(e)&&Object.keys(Tt).some(t=>t in e),$r=e=>e in Tt,_r=(e,t)=>Tt[e]<Tt[t],Tn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),De=(0,qr.memoizeWith)((e,t)=>`${e}${t}`,Tn),Vr=e=>e<1e-6?De("nanosecond",3).format(e/1e-6):e<.001?De("nanosecond").format(e/1e-6):e<1?De("microsecond").format(e/.001):e<1e3?De("millisecond").format(e):e<6e4?De("second",2).format(e/1e3):De("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=Gr.default.isSupported(),level:r=ve()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return(0,Jr.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||_r(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?Xt.ctx(s):s),d.push(c?`${Xt[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})}get ctx(){return this.config.ctx}profile(t){let r=er.performance.now();return()=>{let o=er.performance.now()-r,{message:n,severity:s="debug",formatter:a=Vr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};var Fe=require("ramda");var Ke=class e extends Ne{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=(0,Fe.keys)(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,(0,Fe.reject)((0,Fe.equals)(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};var Wr=k(require("express"),1),qe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Wr.default.static(...this.params))}};var Rt=k(require("express"),1),ho=k(require("node:http"),1),xo=k(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>k(require(e))))[t]}catch{}throw new Ze(e)};var Xr=k(require("http-errors"),1);var Yr=require("ramda");var Ot=class{constructor(t){this.logger=t;this.#e=(0,Yr.tryCatch)(Ur)}#e;#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Me){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(I.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=ct(t);if(s.length===0)return;let a=n?.shape||V(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Qr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new xe(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),$e=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Qr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof tt){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof qe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new xe(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Qr(s,n))}};var On=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=(0,Xr.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},tr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new Ot(t()),a=new Map;if($e({routing:o,onEndpoint:(d,p,l,b)=>{ve()||(s?.checkJsonCompat(d,{path:p,method:l}),s?.checkPathParams(p,d,{method:l}));let S=n?.[d.getRequestType()]||[],y=async(w,A)=>{let N=t(w);if(r.cors){let Z={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[l,...b||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},E=typeof r.cors=="function"?await r.cors({request:w,endpoint:d,logger:N,defaultHeaders:Z}):Z;for(let v in E)A.set(v,E[v])}return d.execute({request:w,response:A,logger:N,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...S,y),a.get(p)?.push("options"))),a.get(p)?.push(l),e[l](p,...S,y)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,On(p))};var rt=k(require("http-errors"),1);var so=require("node:timers/promises");var eo=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",to=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",ro=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,oo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),no=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var io=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(eo(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let l of["connection","secureConnection"])p.on(l,c);let d=async()=>{for(let p of e)p.on("request",oo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(ro(p)||to(p))&&a(p);for await(let p of(0,so.setInterval)(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(no))};return{sockets:n,shutdown:()=>o??=d()}};var ao=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:(0,rt.isHttpError)(r)?r:(0,rt.default)(400,de(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),po=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,rt.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){xt({response:o,logger:s,error:new pe(de(a),n)})}},Rn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Pn=e=>({log:e.debug.bind(e)}),co=async({getLogger:e,config:t})=>{let r=await Be("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let l=e(c);try{await n?.({request:c,logger:l})}catch(b){return p(b)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Pn(l)})(c,d,p)}),o&&a.push(Rn(o)),a},mo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},lo=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:s}),n()},uo=e=>t=>t?.res?.locals[g]?.logger||e,fo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),yo=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=io(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};var B=require("ansis"),go=e=>{if(e.columns<132)return;let t=(0,B.italic)("Proudly supports transgender community.".padStart(109)),r=(0,B.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,B.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,B.italic)("for Tai".padEnd(20)),s=(0,B.hex)("#F5A9B8"),a=(0,B.hex)("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(B.whiteBright,5,7).fill(s,7,9).fill(a,9,12).fill(B.gray,12,13),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,9 +15,9 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((p,l)=>c[l]?c[l](p):p).join(`
|
|
18
|
-
`))};var yo=e=>{e.startupLogo!==!1&&mo(process.stdout);let t=e.errorHandler||Le,r=Kr(e.logger)?e.logger:new Ue(e.logger);r.debug("Running",{build:"v22.7.0 (CJS)",env:process.env.NODE_ENV||"development"}),po(r);let o=io({logger:r,config:e}),s={getLogger:ao(r),errorHandler:t},a=oo(s),c=ro(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},fo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=yo(e);return Qt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},go=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=yo(e),c=(0,Tt.default)().disable("x-powered-by").use(a);if(e.compression){let b=await Fe("compression");c.use(b(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Tt.default.json()],raw:[e.rawParser||Tt.default.raw(),so],upload:e.upload?await no({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),Qt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],l=(b,f)=>()=>b.listen(f,()=>r.info("Listening",f)),g=[];if(e.http){let b=lo.default.createServer(c);p.push(b),g.push(l(b,e.http.listen))}if(e.https){let b=uo.default.createServer(e.https.options,c);p.push(b),g.push(l(b,e.https.listen))}return e.gracefulShutdown&&co({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:g.map(b=>b())}};var Mo=require("openapi3-ts/oas31"),Uo=require("ramda");var T=require("ramda");var ho=e=>xe(e)&&"or"in e,xo=e=>xe(e)&&"and"in e,Xt=e=>!xo(e)&&!ho(e),bo=e=>{let t=(0,T.filter)(Xt,e),r=(0,T.chain)((0,T.prop)("and"),(0,T.filter)(xo,e)),[o,n]=(0,T.partition)(Xt,r),s=(0,T.concat)(t,o),a=(0,T.filter)(ho,e);return(0,T.map)((0,T.prop)("or"),(0,T.concat)(a,n)).reduce((d,p)=>he(d,(0,T.map)(l=>Xt(l)?[l]:l.and,p),([l,g])=>(0,T.concat)(l,g)),(0,T.reject)(T.isEmpty,[s]))};var re=require("openapi3-ts/oas31"),m=require("ramda"),P=require("zod");var Pe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[x]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>Pe(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var So=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var To=50,Ro="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Tn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Po=/:([A-Za-z0-9_]+)/g,On=/^\d{4}-\d{2}-\d{2}$/,Rn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Pn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,An=e=>e.match(Po)?.map(t=>t.slice(1))||[],Ao=e=>e.replace(Po,t=>`{${t.slice(1)}}`),wn=({_def:e},{next:t})=>({...t(e.innerType),default:e[x]?.defaultLabel||e.defaultValue()}),En=({_def:{innerType:e}},{next:t})=>t(e),zn=()=>({format:"any"}),In=({},e)=>{if(e.isResponse)throw new q("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 P.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Zn=({options:e},{next:t})=>({oneOf:e.map(t)}),kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Cn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},jn=e=>{let[t,r]=e.filter(re.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(Cn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=he(t.examples||[],r.examples||[],([n,s])=>(0,m.mergeDeepRight)(n,s))),o},Nn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return jn(o)}catch{}return{allOf:o}},Ln=(e,{next:t})=>t(e.unwrap()),Mn=(e,{next:t})=>t(e.unwrap()),Un=(e,{next:t})=>{let r=t(e.unwrap());return(0,re.isSchemaObject)(r)&&(r.type=Eo(r)),r},wo=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Oo=e=>({type:wo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Hn=({value:e})=>({type:wo(e),const:e}),Kn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&_e(c)?c instanceof P.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Ot(e,r)),s.length&&(a.required=s),a},Dn=()=>({type:"null"}),Fn=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ro}}},qn=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ro}}},Bn=({},e)=>{throw new q(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},$n=()=>({type:"boolean"}),Vn=()=>({type:"integer",format:"bigint"}),_n=e=>e.every(t=>t instanceof P.z.ZodLiteral),Gn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof P.z.ZodEnum||e instanceof P.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Ot(P.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof P.z.ZodLiteral)return{type:"object",properties:Ot(P.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof P.z.ZodUnion&&_n(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:Ot(P.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Yn=({_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},Jn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Wn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:g,isDate:b,isTime:f,isBase64:R,isNANOID:O,isBase64url:M,isDuration:U,_def:{checks:S}})=>{let z=S.find(C=>C.kind==="regex"),Z=S.find(C=>C.kind==="datetime"),H=S.some(C=>C.kind==="jwt"),k=S.find(C=>C.kind==="length"),I={type:"string"},ye={"date-time":l,byte:R,base64url:M,date:b,time:f,duration:U,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:O,jwt:H,ip:d,cidr:g,emoji:p};for(let C in ye)if(ye[C]){I.format=C;break}return k&&([I.minLength,I.maxLength]=[k.value,k.value]),r!==null&&(I.minLength=r),o!==null&&(I.maxLength=o),b&&(I.pattern=On.source),f&&(I.pattern=Rn.source),l&&(I.pattern=Pn(Z?.offset).source),z&&(I.pattern=z.regex.source),I},Qn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(g=>g.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(g=>g.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,p?l.maximum=d:l.exclusiveMaximum=d,l},Ot=({shape:e},t)=>(0,m.map)(t,e),Xn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Tn?.[t]},Eo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",es=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,re.isSchemaObject)(o)){let s=at(e,Xn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(P.z.any())}if(!t&&n.type==="preprocess"&&(0,re.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ts=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),rs=(e,{next:t})=>t(e.unwrap()),os=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ns=(e,{next:t})=>t(e.unwrap().shape.raw),zo=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.times)(t=>`example${t+1}`,e.length),(0,m.map)((0,m.objOf)("value"),e))):void 0,Io=(e,t,r=[])=>(0,m.pipe)(te,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),zo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ss=(e,t)=>(0,m.pipe)(te,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),zo)({schema:e,variant:"original",validate:!0,pullProps:!0}),le=e=>e instanceof P.z.ZodObject?e:e instanceof P.z.ZodBranded?le(e.unwrap()):e instanceof P.z.ZodUnion||e instanceof P.z.ZodDiscriminatedUnion?e.options.map(t=>le(t)).reduce((t,r)=>t.merge(r.partial()),P.z.object({})):e instanceof P.z.ZodEffects?le(e._def.schema):e instanceof P.z.ZodPipeline?le(e._def.in):le(e._def.left).merge(le(e._def.right)),is=(e,t)=>t?.includes(e)||e.startsWith("x-")||So.includes(e),vo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let l=le(r),g=An(e),b=o.includes("query"),f=o.includes("params"),R=o.includes("headers"),O=S=>f&&g.includes(S),M=(0,m.chain)((0,m.filter)(S=>S.type==="header"),d??[]).map(({name:S})=>S),U=S=>R&&(c?.(S,t,e)??is(S,M));return Object.entries(l.shape).reduce((S,[z,Z])=>{let H=O(z)?"path":U(z)?"header":b?"query":void 0;if(!H)return S;let k=Pe(Z,{rules:{...a,...tr},onEach:rr,onMissing:or,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),I=s==="components"?n(Z,k,pe(p,z)):k;return S.concat({name:z,in:H,required:!Z.isOptional(),description:k.description||p,schema:I,examples:ss(l,z)})},[])},tr={ZodString:Wn,ZodNumber:Qn,ZodBigInt:Vn,ZodBoolean:$n,ZodNull:Dn,ZodArray:Yn,ZodTuple:Jn,ZodRecord:Gn,ZodObject:Kn,ZodLiteral:Hn,ZodIntersection:Nn,ZodUnion:Zn,ZodAny:zn,ZodDefault:wn,ZodEnum:Oo,ZodNativeEnum:Oo,ZodEffects:es,ZodOptional:Ln,ZodNullable:Un,ZodDiscriminatedUnion:kn,ZodBranded:rs,ZodDate:Bn,ZodCatch:En,ZodPipeline:ts,ZodLazy:os,ZodReadonly:Mn,[W]:vn,[Ze]:In,[Te]:qn,[Se]:Fn,[ce]:ns},rr=(e,{isResponse:t,prev:r})=>{if((0,re.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof P.z.ZodLazy,s=r.type!==void 0,a=t&&_e(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=Eo(r)),!n){let p=te({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},or=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},er=(e,t)=>{if((0,re.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>er(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>er(o,t))),r},Zo=e=>(0,re.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),ko=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${Dt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let g=Zo(Pe(r,{rules:{...p,...tr},onEach:rr,onMissing:or,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b={schema:a==="components"?s(r,g,pe(l)):g,examples:Io(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[b]))}},as=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ps=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},cs=({name:e})=>({type:"apiKey",in:"header",name:e}),ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ms=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ls=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Co=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?as(o):o.type==="input"?ps(o,t):o.type==="header"?cs(o):o.type==="cookie"?ds(o):o.type==="openid"?ms(o):ls(o);return e.map(o=>o.map(r))},jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),No=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=Zo(er(Pe(r,{rules:{...a,...tr},onEach:rr,onMissing:or,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:s==="components"?n(r,p,pe(d)):p,examples:Io(le(r),!1,c)};return{description:d,content:{[o]:l}}},Lo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),nr=e=>e.length<=To?e:e.slice(0,To-1)+"\u2026";var Rt=class extends Mo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;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||pe(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}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:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:l=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});qe({routing:t,onEndpoint:(f,R,O)=>{let M={path:R,method:O,endpoint:f,composition:g,brandHandling:c,makeRef:this.makeRef.bind(this)},[U,S]=["short","long"].map(f.getDescription.bind(f)),z=U?nr(U):l&&S?nr(S):void 0,Z=r.inputSources?.[O]||Ht[O],H=this.ensureUniqOperationId(R,O,f.getOperationId(O)),k=bo(f.getSecurity()),I=vo({...M,inputSources:Z,isHeader:p,security:k,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:O,path:R,operationId:H})}),ye={};for(let oe of Ne){let fe=f.getResponses(oe);for(let{mimeTypes:Lt,schema:rt,statusCodes:ot}of fe)for(let Mt of ot)ye[Mt]=ko({...M,variant:oe,schema:rt,mimeTypes:Lt,statusCode:Mt,hasMultipleStatusCodes:fe.length>1||ot.length>1,description:a?.[`${oe}Response`]?.call(null,{method:O,path:R,operationId:H,statusCode:Mt})})}let C=Z.includes("body")?No({...M,paramNames:(0,Uo.pluck)("name",I),schema:f.getSchema("input"),mimeType:v[f.getRequestType()],description:a?.requestBody?.call(null,{method:O,path:R,operationId:H})}):void 0,Nt=jo(Co(k,Z),f.getScopes(),oe=>{let fe=this.ensureUniqSecuritySchemaName(oe);return this.addSecurityScheme(fe,oe),fe});this.addPath(Ao(R),{[O]:{operationId:H,summary:z,description:S,tags:pt(f.getTags()),parameters:pt(I),requestBody:C,security:pt(Nt),responses:ye}})}}),d&&(this.rootDoc.tags=Lo(d))}};var Pt=require("node-mocks-http"),us=e=>(0,Pt.createRequest)({...e,headers:{"content-type":v.json,...e?.headers}}),ys=e=>(0,Pt.createResponse)(e),fs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Ho=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=us(e),s=ys({req:n,...t});s.req=t?.req||n,n.res=s;let a=fs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Ko=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Ho(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Do=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Ho(o),d=it(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(ae(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};var Go=require("ramda"),tt=j(require("typescript"),1),Yo=require("zod");var Vo=require("ramda"),Y=j(require("typescript"),1);var Fo=["get","post","put","delete","patch"];var Be=require("ramda"),u=j(require("typescript"),1),i=u.default.factory,At=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],gs=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],Xe={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},sr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),ir=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ar=e=>typeof e=="string"&&hs.test(e)?i.createIdentifier(e):E(e),wt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Et=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?y(t):void 0,o),$e=e=>Object.entries(e).map(([t,r])=>Et(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),pr=(e,t=[])=>i.createConstructorDeclaration(Xe.public,e,i.createBlock(t)),y=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&(0,Be.map)(y,t)):e,cr=y("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ae=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,ar(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,y(t));return o?sr(n,o):n},dr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),mr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),L=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&At,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?y(r):void 0,t)],u.default.NodeFlags.Const)),lr=(e,t)=>X(e,i.createUnionTypeNode((0,Be.map)(F,t)),{expose:!0}),X=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?At:void 0,e,n&&gr(n),t);return o?sr(s,o):s},qo=(e,t)=>i.createPropertyDeclaration(Xe.public,e,void 0,y(t),void 0),ur=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Xe.public,void 0,e,void 0,o&&gr(o),t,n,i.createBlock(r)),yr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(At,e,r&&gr(r),void 0,t),fr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,y(e)),zt=e=>y(Promise.name,[e]),It=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?At:void 0,e,void 0,void 0,t);return o?sr(n,o):n},gr=e=>(Array.isArray(e)?e.map(t=>(0,Be.pair)(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?y(o):void 0,n?y(n):void 0)}),we=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?(0,Be.map)(Et,e):$e(e),void 0,void 0,t),A=e=>e,et=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),w=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ve=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),vt=(e,t)=>y("Extract",[e,t]),hr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),G=(e,t)=>i.createIndexedAccessTypeNode(y(e),y(t)),Bo=e=>i.createUnionTypeNode([y(e),zt(e)]),xr=(e,t)=>i.createFunctionTypeNode(void 0,$e(e),y(t)),E=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),F=e=>i.createLiteralTypeNode(E(e)),xs=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],$o=e=>xs.includes(e.kind);var Zt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=lr("Method",Fo);someOfType=X("SomeOf",G("T",fr("T")),{params:["T"]});requestType=X("Request",fr(this.interfaces.input),{expose:!0});someOf=({name:t})=>y(this.someOfType.name,[t]);makePathType=()=>lr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>It(this.interfaces[t],Array.from(this.registry).map(([r,o])=>Ae(r,o[t])),{expose:!0}));makeEndpointTags=()=>L("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(ar(t),i.createArrayLiteralExpression((0,Vo.map)(E,r))))),{expose:!0});makeImplementationType=()=>X(this.ids.implementationType,xr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:cr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},zt(Y.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Y.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>L(this.ids.parseRequestFn,we({[this.ids.requestParameter.text]:Y.default.SyntaxKind.StringKeyword},i.createAsExpression(w(this.ids.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),E(2)),i.createTupleTypeNode([y(this.methodType.name),y(this.ids.pathType)]))));makeSubstituteFn=()=>L(this.ids.substituteFn,we({[this.ids.pathParameter.text]:Y.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:cr},i.createBlock([L(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],Y.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([hr(this.ids.pathParameter,w(this.ids.pathParameter,A("replace"))(wt(":",[this.ids.keyParameter]),we([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),y("const")))])));makeProvider=()=>ur(this.ids.provideMethod,$e({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:G(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[L(mr(this.ids.methodParameter,this.ids.pathParameter),w(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(w(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(w(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:zt(G(this.interfaces.response,"K"))});makeClientClass=t=>yr(t,[pr([Et(this.ids.implementationArgument,{type:y(this.ids.implementationType,["T"]),mod:Xe.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>wt("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,wt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),E(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),w(this.ids.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),et(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(E("Content-Type"),E(v.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(A("body"),et(this.ids.hasBodyConst,w(JSON[Symbol.toStringTag],A("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=L(this.ids.responseConst,i.createAwaitExpression(w(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=L(this.ids.hasBodyConst,i.createLogicalNot(w(i.createArrayLiteralExpression([E("get"),E("delete")]),A("includes"))(this.ids.methodParameter))),a=L(this.ids.searchParamsConst,et(this.ids.hasBodyConst,E(""),this.makeSearchParams(this.ids.paramsArgument))),c=L(this.ids.contentTypeConst,w(this.ids.responseConst,A("headers"),A("get"))(E("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(Y.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=L(this.ids.isJsonConst,w(this.ids.contentTypeConst,A("startsWith"))(E(v.json))),l=i.createReturnStatement(w(this.ids.responseConst,et(this.ids.isJsonConst,E(A("json")),E(A("text"))))());return L(this.ids.defaultImplementationConst,we([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>pr($e({request:"K",params:G(this.interfaces.input,"K")}),[L(mr(this.ids.pathParameter,this.ids.restConst),w(this.ids.substituteFn)(i.createElementAccessExpression(w(this.ids.parseRequestFn)(this.ids.requestParameter),E(1)),this.ids.paramsArgument)),L(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),hr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([Ae(A("event"),t)]);makeOnMethod=()=>ur(this.ids.onMethod,$e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:xr({[this.ids.dataParameter.text]:G(vt("R",dr(this.makeEventNarrow("E"))),F(A("data")))},Bo(Y.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(w(i.createThis(),this.ids.sourceProp,A("addEventListener"))(this.ids.eventParameter,we([this.ids.msgParameter],w(this.ids.handlerParameter)(w(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,y(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:G("R",F(A("event")))}});makeSubscriptionClass=t=>yr(t,[qo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:vt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(y(Y.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:vt(G(this.interfaces.positive,"K"),dr(this.makeEventNarrow(Y.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[L(this.ids.clientConst,Ve(t)),w(this.ids.clientConst,this.ids.provideMethod)(E("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",E("10"))])),w(Ve(r,E("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(E("time"),we(["time"],i.createBlock([])))]};var K=require("ramda"),h=j(require("typescript"),1),kt=require("zod");var{factory:$}=h.default,bs={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},br={name:(0,K.path)(["name","text"]),type:(0,K.path)(["type"]),optional:(0,K.path)(["questionToken"])},Ss=({value:e})=>F(e),Ts=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&_e(a)?a instanceof kt.z.ZodOptional:a.isOptional();return Ae(s,r(a),{isOptional:c&&o,comment:a.description})});return $.createTypeLiteralNode(n)},Os=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Rs=({options:e})=>$.createUnionTypeNode(e.map(F)),_o=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set($o(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},Ps=e=>bs?.[e.kind],As=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=at(e,Ps(o)),s={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return y(n&&s[n]||h.default.SyntaxKind.AnyKeyword)}return o},ws=e=>$.createUnionTypeNode(Object.values(e.enum).map(F)),Es=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,y(h.default.SyntaxKind.UndefinedKeyword)]):o},zs=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),F(null)]),Is=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),vs=({keySchema:e,valueSchema:t},{next:r})=>y("Record",[e,t].map(r)),Zs=e=>{if(!e.every(h.default.isTypeLiteralNode))throw new Error("Not objects");let r=(0,K.chain)((0,K.prop)("members"),e),o=(0,K.uniqWith)((...n)=>{if(!(0,K.eqBy)(br.name,...n))return!1;if((0,K.eqBy)(br.type,...n)&&(0,K.eqBy)(br.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return $.createTypeLiteralNode(o)},ks=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Zs(o)}catch{}return $.createIntersectionTypeNode(o)},Cs=({_def:e},{next:t})=>t(e.innerType),ue=e=>()=>y(e),js=(e,{next:t})=>t(e.unwrap()),Ns=(e,{next:t})=>t(e.unwrap()),Ls=({_def:e},{next:t})=>t(e.innerType),Ms=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Us=()=>F(null),Hs=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Ks=e=>{let t=e.unwrap(),r=y(h.default.SyntaxKind.StringKeyword),o=y("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof kt.z.ZodString?r:t instanceof kt.z.ZodUnion?n:o},Ds=(e,{next:t})=>t(e.unwrap().shape.raw),Fs={ZodString:ue(h.default.SyntaxKind.StringKeyword),ZodNumber:ue(h.default.SyntaxKind.NumberKeyword),ZodBigInt:ue(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:ue(h.default.SyntaxKind.BooleanKeyword),ZodAny:ue(h.default.SyntaxKind.AnyKeyword),ZodUndefined:ue(h.default.SyntaxKind.UndefinedKeyword),[Se]:ue(h.default.SyntaxKind.StringKeyword),[Te]:ue(h.default.SyntaxKind.StringKeyword),ZodNull:Us,ZodArray:Os,ZodTuple:Is,ZodRecord:vs,ZodObject:Ts,ZodLiteral:Ss,ZodIntersection:ks,ZodUnion:_o,ZodDefault:Cs,ZodEnum:Rs,ZodNativeEnum:ws,ZodEffects:As,ZodOptional:Es,ZodNullable:zs,ZodDiscriminatedUnion:_o,ZodBranded:js,ZodCatch:Ls,ZodPipeline:Ms,ZodLazy:Hs,ZodReadonly:Ns,[W]:Ks,[ce]:Ds},Sr=(e,{brandHandling:t,ctx:r})=>Pe(e,{rules:{...t,...Fs},onMissing:()=>y(h.default.SyntaxKind.AnyKeyword),ctx:r});var Ct=class extends Zt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=F(null);this.aliases.set(t,X(o,n)),this.aliases.set(t,X(o,r()))}return y(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=Yo.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},g={brandHandling:r,ctx:{...p,isResponse:!0}};qe({routing:t,onEndpoint:(f,R,O)=>{let M=pe.bind(null,O,R),U=`${O} ${R}`,S=X(M("input"),Sr(f.getSchema("input"),l),{comment:U});this.program.push(S);let z=Ne.reduce((H,k)=>{let I=f.getResponses(k),ye=(0,Go.chain)(([Nt,{schema:oe,mimeTypes:fe,statusCodes:Lt}])=>{let rt=X(M(k,"variant",`${Nt+1}`),Sr(fe?oe:d,g),{comment:U});return this.program.push(rt),Lt.map(ot=>Ae(ot,rt.name))},Array.from(I.entries())),C=It(M(k,"response","variants"),ye,{comment:U});return this.program.push(C),Object.assign(H,{[k]:C})},{});this.paths.add(R);let Z=F(U);this.registry.set(U,{input:y(S.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:i.createUnionTypeNode([G(this.interfaces.positive,Z),G(this.interfaces.negative,Z)]),encoded:i.createIntersectionTypeNode([y(z.positive.name),y(z.negative.name)])}),this.tags.set(U,f.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:ir(r,t)).join(`
|
|
19
|
-
`):void 0}print(t){let r=this.printUsage(t),o=r&&
|
|
20
|
-
${r}`);return this.program.concat(o||[]).map((n,s)=>
|
|
18
|
+
`))};var bo=e=>{e.startupLogo!==!1&&go(process.stdout);let t=e.errorHandler||Ue,r=Br(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.9.0 (CJS)",env:process.env.NODE_ENV||"development"}),fo(r);let o=lo({logger:r,config:e}),s={getLogger:uo(r),errorHandler:t},a=po(s),c=ao(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},So=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=bo(e);return tr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},To=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=bo(e),c=(0,Rt.default)().disable("x-powered-by").use(a);if(e.compression){let S=await Be("compression");c.use(S(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Rt.default.json()],raw:[e.rawParser||Rt.default.raw(),mo],upload:e.upload?await co({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),tr({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],l=(S,y)=>()=>S.listen(y,()=>r.info("Listening",y)),b=[];if(e.http){let S=ho.default.createServer(c);p.push(S),b.push(l(S,e.http.listen))}if(e.https){let S=xo.default.createServer(e.https.options,c);p.push(S),b.push(l(S,e.https.listen))}return e.gracefulShutdown&&yo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:b.map(S=>S())}};var Ko=require("openapi3-ts/oas31"),Fo=require("ramda");var T=require("ramda");var Oo=e=>Se(e)&&"or"in e,Ro=e=>Se(e)&&"and"in e,rr=e=>!Ro(e)&&!Oo(e),Po=e=>{let t=(0,T.filter)(rr,e),r=(0,T.chain)((0,T.prop)("and"),(0,T.filter)(Ro,e)),[o,n]=(0,T.partition)(rr,r),s=(0,T.concat)(t,o),a=(0,T.filter)(Oo,e);return(0,T.map)((0,T.prop)("or"),(0,T.concat)(a,n)).reduce((d,p)=>be(d,(0,T.map)(l=>rr(l)?[l]:l.and,p),([l,b])=>(0,T.concat)(l,b)),(0,T.reject)(T.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),m=require("ramda"),D=require("zod");var we=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>we(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var Ao=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var wo=50,zo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",wn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},En=/^\d{4}-\d{2}-\d{2}$/,zn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,In=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Io=e=>e.replace(Ft,t=>`{${t.slice(1)}}`),Zn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),vn=({_def:{innerType:e}},{next:t})=>t(e),kn=()=>({format:"any"}),Cn=({},e)=>{if(e.isResponse)throw new q("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},jn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof D.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Nn=({options:e},{next:t})=>({oneOf:e.map(t)}),Ln=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Mn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return(0,m.concat)(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Un=e=>{let[t,r]=e.filter(se.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,m.mergeDeepWith)(Mn,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,m.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=be(t.examples||[],r.examples||[],([n,s])=>(0,m.mergeDeepRight)(n,s))),o},Dn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Un(o)}catch{}return{allOf:o}},Hn=(e,{next:t})=>t(e.unwrap()),Kn=(e,{next:t})=>t(e.unwrap()),Fn=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=vo(r)),r},Zo=e=>{let t=(0,m.toLower)((0,m.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Eo=e=>({type:Zo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),qn=({value:e})=>({type:Zo(e),const:e}),Bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&We(c)?c instanceof D.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=Pt(e,r)),s.length&&(a.required=s),a},$n=()=>({type:"null"}),_n=({},e)=>{if(e.isResponse)throw new q("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:zo}}},Vn=({},e)=>{if(!e.isResponse)throw new q("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:zo}}},Gn=({},e)=>{throw new q(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},Jn=()=>({type:"boolean"}),Wn=()=>({type:"integer",format:"bigint"}),Yn=e=>e.every(t=>t instanceof D.z.ZodLiteral),Qn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof D.z.ZodEnum||e instanceof D.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=Pt(D.z.object((0,m.fromPairs)((0,m.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof D.z.ZodLiteral)return{type:"object",properties:Pt(D.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof D.z.ZodUnion&&Yn(e.options)){let o=(0,m.map)(s=>`${s.value}`,e.options),n=(0,m.fromPairs)((0,m.xprod)(o,[t]));return{type:"object",properties:Pt(D.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Xn=({_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},es=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ts=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:l,isCIDR:b,isDate:S,isTime:y,isBase64:w,isNANOID:A,isBase64url:N,isDuration:re,_def:{checks:h}})=>{let Z=h.find(L=>L.kind==="regex"),E=h.find(L=>L.kind==="datetime"),v=h.some(L=>L.kind==="jwt"),K=h.find(L=>L.kind==="length"),z={type:"string"},F={"date-time":l,byte:w,base64url:N,date:S,time:y,duration:re,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:A,jwt:v,ip:d,cidr:b,emoji:p};for(let L in F)if(F[L]){z.format=L;break}return K&&([z.minLength,z.maxLength]=[K.value,K.value]),r!==null&&(z.minLength=r),o!==null&&(z.maxLength=o),S&&(z.pattern=En.source),y&&(z.pattern=zn.source),l&&(z.pattern=In(E?.offset).source),Z&&(z.pattern=Z.regex.source),z},rs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(b=>b.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(b=>b.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=s:l.exclusiveMinimum=s,p?l.maximum=d:l.exclusiveMaximum=d,l},Pt=({shape:e},t)=>(0,m.map)(t,e),os=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return wn?.[t]},vo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",ns=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=mt(e,os(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(D.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ss=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),is=(e,{next:t})=>t(e.unwrap()),as=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),ps=(e,{next:t})=>t(e.unwrap().shape.raw),ko=e=>e.length?(0,m.fromPairs)((0,m.zip)((0,m.times)(t=>`example${t+1}`,e.length),(0,m.map)((0,m.objOf)("value"),e))):void 0,Co=(e,t,r=[])=>(0,m.pipe)(ne,(0,m.map)((0,m.when)(o=>(0,m.type)(o)==="Object",(0,m.omit)(r))),ko)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),cs=(e,t)=>(0,m.pipe)(ne,(0,m.filter)((0,m.has)(t)),(0,m.pluck)(t),ko)({schema:e,variant:"original",validate:!0,pullProps:!0}),ds=(e,t)=>t?.includes(e)||e.startsWith("x-")||Ao.includes(e),jo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let l=V(r),b=ct(e),S=o.includes("query"),y=o.includes("params"),w=o.includes("headers"),A=h=>y&&b.includes(h),N=(0,m.chain)((0,m.filter)(h=>h.type==="header"),d??[]).map(({name:h})=>h),re=h=>w&&(c?.(h,t,e)??ds(h,N));return Object.entries(l.shape).reduce((h,[Z,E])=>{let v=A(Z)?"path":re(Z)?"header":S?"query":void 0;if(!v)return h;let K=we(E,{rules:{...a,...nr},onEach:sr,onMissing:ir,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),z=s==="components"?n(E,K,me(p,Z)):K,{_def:F}=E;return h.concat({name:Z,in:v,deprecated:F[g]?.isDeprecated,required:!E.isOptional(),description:K.description||p,schema:z,examples:cs(l,Z)})},[])},nr={ZodString:ts,ZodNumber:rs,ZodBigInt:Wn,ZodBoolean:Jn,ZodNull:$n,ZodArray:Xn,ZodTuple:es,ZodRecord:Qn,ZodObject:Bn,ZodLiteral:qn,ZodIntersection:Dn,ZodUnion:Nn,ZodAny:kn,ZodDefault:Zn,ZodEnum:Eo,ZodNativeEnum:Eo,ZodEffects:ns,ZodOptional:Hn,ZodNullable:Fn,ZodDiscriminatedUnion:Ln,ZodBranded:is,ZodDate:Gn,ZodCatch:vn,ZodPipeline:ss,ZodLazy:as,ZodReadonly:Kn,[Q]:jn,[Ce]:Cn,[Re]:Vn,[Oe]:_n,[le]:ps},sr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof D.z.ZodLazy,a=r.type!==void 0,c=t&&We(e),d=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[g]?.isDeprecated&&(p.deprecated=!0),d&&(p.type=vo(r)),!s){let l=ne({schema:e,variant:t?"parsed":"original",validate:!0});l.length&&(p.examples=l.slice())}return p},ir=(e,t)=>{throw new q(`Zod type ${e.constructor.name} is unsupported.`,t)},or=(e,t)=>{if((0,se.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,m.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,m.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>or(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>or(o,t))),r},No=e=>(0,se.isReferenceObject)(e)?e:(0,m.omit)(["examples"],e),Lo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:l=`${e.toUpperCase()} ${t} ${$t(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:l};let b=No(we(r,{rules:{...p,...nr},onEach:sr,onMissing:ir,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),S={schema:a==="components"?s(r,b,me(l)):b,examples:Co(r,!0)};return{description:l,content:(0,m.fromPairs)((0,m.xprod)(o,[S]))}},ms=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ls=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},us=({name:e})=>({type:"apiKey",in:"header",name:e}),fs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ys=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),gs=({flows:e={}})=>({type:"oauth2",flows:(0,m.map)(t=>({...t,scopes:t.scopes||{}}),(0,m.reject)(m.isNil,e))}),Mo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ms(o):o.type==="input"?ls(o,t):o.type==="header"?us(o):o.type==="cookie"?fs(o):o.type==="openid"?ys(o):gs(o);return e.map(o=>o.map(r))},Uo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Do=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=No(or(we(r,{rules:{...a,...nr},onEach:sr,onMissing:ir,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),l={schema:s==="components"?n(r,p,me(d)):p,examples:Co(V(r),!1,c)};return{description:d,content:{[o]:l}}},Ho=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),ar=e=>e.length<=wo?e:e.slice(0,wo-1)+"\u2026",At=e=>e.length?e.slice():void 0;var wt=class extends Ko.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;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||me(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new q(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}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:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:l=!0,composition:b="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});$e({routing:t,onEndpoint:(y,w,A)=>{let N={path:w,method:A,endpoint:y,composition:b,brandHandling:c,makeRef:this.makeRef.bind(this)},[re,h]=["short","long"].map(y.getDescription.bind(y)),Z=re?ar(re):l&&h?ar(h):void 0,E=r.inputSources?.[A]||qt[A],v=this.ensureUniqOperationId(w,A,y.getOperationId(A)),K=Po(y.getSecurity()),z=jo({...N,inputSources:E,isHeader:p,security:K,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:A,path:w,operationId:v})}),F={};for(let ie of Me){let he=y.getResponses(ie);for(let{mimeTypes:Dt,schema:Ht,statusCodes:Ge}of he)for(let Je of Ge)F[Je]=Lo({...N,variant:ie,schema:Ht,mimeTypes:Dt,statusCode:Je,hasMultipleStatusCodes:he.length>1||Ge.length>1,description:a?.[`${ie}Response`]?.call(null,{method:A,path:w,operationId:v,statusCode:Je})})}let L=E.includes("body")?Do({...N,paramNames:(0,Fo.pluck)("name",z),schema:y.getSchema("input"),mimeType:I[y.getRequestType()],description:a?.requestBody?.call(null,{method:A,path:w,operationId:v})}):void 0,Ut=Uo(Mo(K,E),y.getScopes(),ie=>{let he=this.ensureUniqSecuritySchemaName(ie);return this.addSecurityScheme(he,ie),he}),it={operationId:v,summary:Z,description:h,deprecated:y.isDeprecated||void 0,tags:At(y.getTags()),parameters:At(z),requestBody:L,security:At(Ut),responses:F};this.addPath(Io(w),{[A]:it})}}),d&&(this.rootDoc.tags=Ho(d))}};var Et=require("node-mocks-http"),hs=e=>(0,Et.createRequest)({...e,headers:{"content-type":I.json,...e?.headers}}),xs=e=>(0,Et.createResponse)(e),bs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:$r(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},qo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=hs(e),s=xs({req:n,...t});s.req=t?.req||n,n.res=s;let a=bs(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Bo=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=qo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},$o=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=qo(o),d=dt(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(de(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};var Qo=require("ramda"),st=k(require("typescript"),1),Xo=require("zod");var Wo=require("ramda"),W=k(require("typescript"),1);var _o=["get","post","put","delete","patch"];var ee=require("ramda"),u=k(require("typescript"),1),i=u.default.factory,zt=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Ss=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],ot={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},pr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},Ts=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=e=>typeof e=="string"&&Ts.test(e)?i.createIdentifier(e):P(e),It=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Zt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),_e=e=>Object.entries(e).map(([t,r])=>Zt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),mr=(e,t=[])=>i.createConstructorDeclaration(ot.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&(0,ee.map)(f,t)):e,lr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ee=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,dr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=(0,ee.reject)(ee.isNil,[o?"@deprecated":void 0,n]);return a.length?pr(s,a.join(" ")):s},ur=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),fr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&zt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),yr=(e,t)=>te(e,i.createUnionTypeNode((0,ee.map)(H,t)),{expose:!0}),te=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?zt:void 0,e,n&&br(n),t);return o?pr(s,o):s},Vo=(e,t)=>i.createPropertyDeclaration(ot.public,e,void 0,f(t),void 0),gr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(ot.public,void 0,e,void 0,o&&br(o),t,n,i.createBlock(r)),hr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(zt,e,r&&br(r),void 0,t),xr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),vt=e=>f(Promise.name,[e]),kt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?zt:void 0,e,void 0,void 0,t);return o?pr(n,o):n},br=e=>(Array.isArray(e)?e.map(t=>(0,ee.pair)(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ze=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Ss:void 0,void 0,Array.isArray(e)?(0,ee.map)(Zt,e):_e(e),void 0,void 0,t),O=e=>e,nt=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),R=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ve=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Ct=(e,t)=>f("Extract",[e,t]),Sr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),J=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Go=e=>i.createUnionTypeNode([f(e),vt(e)]),Tr=(e,t)=>i.createFunctionTypeNode(void 0,_e(e),f(t)),P=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),H=e=>i.createLiteralTypeNode(P(e)),Os=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],Jo=e=>Os.includes(e.kind);var jt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=yr("Method",_o);someOfType=te("SomeOf",J("T",xr("T")),{params:["T"]});requestType=te("Request",xr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>yr(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>kt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ee(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(dr(t),i.createArrayLiteralExpression((0,Wo.map)(P,r))))),{expose:!0});makeImplementationType=()=>te(this.ids.implementationType,Tr({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:W.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:lr,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},vt(W.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:W.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.ids.parseRequestFn,ze({[this.ids.requestParameter.text]:W.default.SyntaxKind.StringKeyword},i.createAsExpression(R(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.ids.pathType)]))));makeSubstituteFn=()=>j(this.ids.substituteFn,ze({[this.ids.pathParameter.text]:W.default.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:lr},i.createBlock([j(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],W.default.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([Sr(this.ids.pathParameter,R(this.ids.pathParameter,O("replace"))(It(":",[this.ids.keyParameter]),ze([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),f("const")))])));makeProvider=()=>gr(this.ids.provideMethod,_e({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:J(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[j(fr(this.ids.methodParameter,this.ids.pathParameter),R(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(R(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(R(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:vt(J(this.interfaces.response,"K"))});makeClientClass=t=>hr(t,[mr([Zt(this.ids.implementationArgument,{type:f(this.ids.implementationType,["T"]),mod:ot.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>It("?",[Ve(URLSearchParams.name,t)]);makeFetchURL=()=>Ve(URL.name,It("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),R(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),nt(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(I.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),nt(this.ids.hasBodyConst,R(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=j(this.ids.responseConst,i.createAwaitExpression(R(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.ids.hasBodyConst,i.createLogicalNot(R(i.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.ids.methodParameter))),a=j(this.ids.searchParamsConst,nt(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=j(this.ids.contentTypeConst,R(this.ids.responseConst,O("headers"),O("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(W.default.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=j(this.ids.isJsonConst,R(this.ids.contentTypeConst,O("startsWith"))(P(I.json))),l=i.createReturnStatement(R(this.ids.responseConst,nt(this.ids.isJsonConst,P(O("json")),P(O("text"))))());return j(this.ids.defaultImplementationConst,ze([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,l]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>mr(_e({request:"K",params:J(this.interfaces.input,"K")}),[j(fr(this.ids.pathParameter,this.ids.restConst),R(this.ids.substituteFn)(i.createElementAccessExpression(R(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),j(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),Sr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ve("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([Ee(O("event"),t)]);makeOnMethod=()=>gr(this.ids.onMethod,_e({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:Tr({[this.ids.dataParameter.text]:J(Ct("R",ur(this.makeEventNarrow("E"))),H(O("data")))},Go(W.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(R(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,ze([this.ids.msgParameter],R(this.ids.handlerParameter)(R(JSON[Symbol.toStringTag],O("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,f(MessageEvent.name))),O("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:J("R",H(O("event")))}});makeSubscriptionClass=t=>hr(t,[Vo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:Ct(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(W.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Ct(J(this.interfaces.positive,"K"),ur(this.makeEventNarrow(W.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.ids.clientConst,Ve(t)),R(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),R(Ve(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),ze(["time"],i.createBlock([])))]};var M=require("ramda"),x=k(require("typescript"),1),Nt=require("zod");var{factory:$}=x.default,Rs={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Or={name:(0,M.path)(["name","text"]),type:(0,M.path)(["type"]),optional:(0,M.path)(["questionToken"])},Ps=({value:e})=>H(e),As=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:d}=a,p=t&&We(a)?a instanceof Nt.z.ZodOptional:a.isOptional();return Ee(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:d[g]?.isDeprecated})});return $.createTypeLiteralNode(n)},ws=({element:e},{next:t})=>$.createArrayTypeNode(t(e)),Es=({options:e})=>$.createUnionTypeNode(e.map(H)),Yo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Jo(n)?n.kind:n,n)}return $.createUnionTypeNode(Array.from(r.values()))},zs=e=>Rs?.[e.kind],Is=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=mt(e,zs(o)),s={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Zs=e=>$.createUnionTypeNode(Object.values(e.enum).map(H)),vs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?$.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},ks=(e,{next:t})=>$.createUnionTypeNode([t(e.unwrap()),H(null)]),Cs=({items:e,_def:{rest:t}},{next:r})=>$.createTupleTypeNode(e.map(r).concat(t===null?[]:$.createRestTypeNode(r(t)))),js=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),Ns=e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let r=(0,M.chain)((0,M.prop)("members"),e),o=(0,M.uniqWith)((...n)=>{if(!(0,M.eqBy)(Or.name,...n))return!1;if((0,M.eqBy)(Or.type,...n)&&(0,M.eqBy)(Or.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return $.createTypeLiteralNode(o)},Ls=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Ns(o)}catch{}return $.createIntersectionTypeNode(o)},Ms=({_def:e},{next:t})=>t(e.innerType),ge=e=>()=>f(e),Us=(e,{next:t})=>t(e.unwrap()),Ds=(e,{next:t})=>t(e.unwrap()),Hs=({_def:e},{next:t})=>t(e.innerType),Ks=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Fs=()=>H(null),qs=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),Bs=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=$.createUnionTypeNode([r,o]);return t instanceof Nt.z.ZodString?r:t instanceof Nt.z.ZodUnion?n:o},$s=(e,{next:t})=>t(e.unwrap().shape.raw),_s={ZodString:ge(x.default.SyntaxKind.StringKeyword),ZodNumber:ge(x.default.SyntaxKind.NumberKeyword),ZodBigInt:ge(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:ge(x.default.SyntaxKind.BooleanKeyword),ZodAny:ge(x.default.SyntaxKind.AnyKeyword),ZodUndefined:ge(x.default.SyntaxKind.UndefinedKeyword),[Oe]:ge(x.default.SyntaxKind.StringKeyword),[Re]:ge(x.default.SyntaxKind.StringKeyword),ZodNull:Fs,ZodArray:ws,ZodTuple:Cs,ZodRecord:js,ZodObject:As,ZodLiteral:Ps,ZodIntersection:Ls,ZodUnion:Yo,ZodDefault:Ms,ZodEnum:Es,ZodNativeEnum:Zs,ZodEffects:Is,ZodOptional:vs,ZodNullable:ks,ZodDiscriminatedUnion:Yo,ZodBranded:Us,ZodCatch:Hs,ZodPipeline:Ks,ZodLazy:qs,ZodReadonly:Ds,[Q]:Bs,[le]:$s},Rr=(e,{brandHandling:t,ctx:r})=>we(e,{rules:{...t,..._s},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Lt=class extends jt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=H(null);this.aliases.set(t,te(o,n)),this.aliases.set(t,te(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=Xo.z.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},b={brandHandling:r,ctx:{...p,isResponse:!0}};$e({routing:t,onEndpoint:(y,w,A)=>{let N=me.bind(null,A,w),{isDeprecated:re}=y,h=`${A} ${w}`,Z=te(N("input"),Rr(y.getSchema("input"),l),{comment:h});this.program.push(Z);let E=Me.reduce((z,F)=>{let L=y.getResponses(F),Ut=(0,Qo.chain)(([ie,{schema:he,mimeTypes:Dt,statusCodes:Ht}])=>{let Ge=te(N(F,"variant",`${ie+1}`),Rr(Dt?he:d,b),{comment:h});return this.program.push(Ge),Ht.map(Je=>Ee(Je,Ge.name))},Array.from(L.entries())),it=kt(N(F,"response","variants"),Ut,{comment:h});return this.program.push(it),Object.assign(z,{[F]:it})},{});this.paths.add(w);let v=H(h),K={input:f(Z.name),positive:this.someOf(E.positive),negative:this.someOf(E.negative),response:i.createUnionTypeNode([J(this.interfaces.positive,v),J(this.interfaces.negative,v)]),encoded:i.createIntersectionTypeNode([f(E.positive.name),f(E.negative.name)])};this.registry.set(h,{isDeprecated:re,store:K}),this.tags.set(h,y.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:cr(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&st.default.addSyntheticLeadingComment(st.default.addSyntheticLeadingComment(i.createEmptyStatement(),st.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),st.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.program.concat(o||[]).map((n,s)=>cr(n,s<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
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Be("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};var Ie=require("zod");var tn=(e,t)=>Ie.z.object({data:t,event:Ie.z.literal(e),id:Ie.z.string().optional(),retry:Ie.z.number().int().positive().optional()}),Vs=(e,t,r)=>tn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Gs=1e4,en=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":I.sse,"cache-control":"no-cache"}),Js=e=>new _({handler:async({response:t})=>setTimeout(()=>en(t),Gs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{en(t),t.write(Vs(e,r,o),"utf-8"),t.flush?.()}}}),Ws=e=>new fe({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>tn(o,n));return{mimeType:I.sse,schema:r.length?Ie.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ie.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Pe(r);et(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(Ae(a),"utf-8")}t.end()}}),Mt=class extends ye{constructor(t){super(Ws(t)),this.middlewares=[Js(t)]}};var rn={dateIn:Er,dateOut:Ir,file:ft,upload:jr,raw:kr};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getExamples,getMessageFromError,testEndpoint,testMiddleware});
|
package/dist/index.d.cts
CHANGED
|
@@ -276,10 +276,12 @@ declare const contentTypes: {
|
|
|
276
276
|
};
|
|
277
277
|
type ContentType = keyof typeof contentTypes;
|
|
278
278
|
|
|
279
|
-
declare class DependsOnMethod extends
|
|
280
|
-
|
|
281
|
-
readonly entries: ReadonlyArray<[Method, AbstractEndpoint, Method[]]>;
|
|
279
|
+
declare class DependsOnMethod extends Routable {
|
|
280
|
+
#private;
|
|
282
281
|
constructor(endpoints: Partial<Record<Method, AbstractEndpoint>>);
|
|
282
|
+
/** @desc [method, endpoint, siblingMethods] */
|
|
283
|
+
get entries(): ReadonlyArray<[Method, AbstractEndpoint, Method[]]>;
|
|
284
|
+
deprecated(): this;
|
|
283
285
|
}
|
|
284
286
|
|
|
285
287
|
type OriginalStatic = typeof express__default.static;
|
|
@@ -374,7 +376,9 @@ interface Routing {
|
|
|
374
376
|
[SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
|
|
375
377
|
}
|
|
376
378
|
|
|
377
|
-
declare abstract class
|
|
379
|
+
declare abstract class Routable {
|
|
380
|
+
/** @desc Marks the route as deprecated (makes a copy of the endpoint) */
|
|
381
|
+
abstract deprecated(): this;
|
|
378
382
|
/** @desc Enables nested routes within the path assigned to the subject */
|
|
379
383
|
nest(routing: Routing): Routing;
|
|
380
384
|
}
|
|
@@ -386,7 +390,7 @@ type Handler<IN, OUT, OPT> = (params: {
|
|
|
386
390
|
}) => Promise<OUT>;
|
|
387
391
|
type DescriptionVariant = "short" | "long";
|
|
388
392
|
type IOVariant = "input" | "output";
|
|
389
|
-
declare abstract class AbstractEndpoint extends
|
|
393
|
+
declare abstract class AbstractEndpoint extends Routable {
|
|
390
394
|
abstract execute(params: {
|
|
391
395
|
request: Request;
|
|
392
396
|
response: Response;
|
|
@@ -402,10 +406,12 @@ declare abstract class AbstractEndpoint extends Nesting {
|
|
|
402
406
|
abstract getTags(): ReadonlyArray<string>;
|
|
403
407
|
abstract getOperationId(method: Method): string | undefined;
|
|
404
408
|
abstract getRequestType(): ContentType;
|
|
409
|
+
abstract get isDeprecated(): boolean;
|
|
405
410
|
}
|
|
406
411
|
declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends FlatObject> extends AbstractEndpoint {
|
|
407
412
|
#private;
|
|
408
|
-
constructor(
|
|
413
|
+
constructor(def: {
|
|
414
|
+
deprecated?: boolean;
|
|
409
415
|
middlewares?: AbstractMiddleware[];
|
|
410
416
|
inputSchema: IN;
|
|
411
417
|
outputSchema: OUT;
|
|
@@ -418,11 +424,13 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends Fl
|
|
|
418
424
|
scopes?: string[];
|
|
419
425
|
tags?: string[];
|
|
420
426
|
});
|
|
427
|
+
deprecated(): this;
|
|
428
|
+
get isDeprecated(): boolean;
|
|
421
429
|
getDescription(variant: DescriptionVariant): string | undefined;
|
|
422
|
-
getMethods():
|
|
430
|
+
getMethods(): Readonly<("get" | "post" | "put" | "delete" | "patch")[] | undefined>;
|
|
423
431
|
getSchema(variant: "input"): IN;
|
|
424
432
|
getSchema(variant: "output"): OUT;
|
|
425
|
-
getRequestType(): "
|
|
433
|
+
getRequestType(): "json" | "upload" | "raw";
|
|
426
434
|
getResponses(variant: ResponseVariant): readonly NormalizedResponse[];
|
|
427
435
|
getSecurity(): LogicalContainer<Security>[];
|
|
428
436
|
getScopes(): readonly string[];
|
|
@@ -606,7 +614,7 @@ interface TagOverrides {
|
|
|
606
614
|
}
|
|
607
615
|
type Tag = NoNever<keyof TagOverrides, string>;
|
|
608
616
|
declare const getMessageFromError: (error: Error) => string;
|
|
609
|
-
declare const getExamples: <T extends z.
|
|
617
|
+
declare const getExamples: <T extends z.ZodType, V extends "original" | "parsed" | undefined>({ schema, variant, validate, pullProps, }: {
|
|
610
618
|
schema: T;
|
|
611
619
|
/**
|
|
612
620
|
* @desc examples variant: original or parsed
|
|
@@ -633,6 +641,7 @@ interface Metadata {
|
|
|
633
641
|
/** @override ZodDefault::_def.defaultValue() in depictDefault */
|
|
634
642
|
defaultLabel?: string;
|
|
635
643
|
brand?: string | number | symbol;
|
|
644
|
+
isDeprecated?: boolean;
|
|
636
645
|
}
|
|
637
646
|
|
|
638
647
|
/**
|
|
@@ -659,6 +668,7 @@ declare module "zod" {
|
|
|
659
668
|
interface ZodType {
|
|
660
669
|
/** @desc Add an example value (before any transformations, can be called multiple times) */
|
|
661
670
|
example(example: this["_input"]): this;
|
|
671
|
+
deprecated(): this;
|
|
662
672
|
}
|
|
663
673
|
interface ZodDefault<T extends z.ZodTypeAny> {
|
|
664
674
|
/** @desc Change the default value in the generated Documentation to a label */
|
|
@@ -683,6 +693,7 @@ interface BuildProps<IN extends IOSchema, OUT extends IOSchema | z.ZodVoid, MIN
|
|
|
683
693
|
method?: Method | [Method, ...Method[]];
|
|
684
694
|
scope?: SCO | SCO[];
|
|
685
695
|
tag?: Tag | Tag[];
|
|
696
|
+
deprecated?: boolean;
|
|
686
697
|
}
|
|
687
698
|
declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT extends FlatObject = EmptyObject, SCO extends string = string> {
|
|
688
699
|
#private;
|
|
@@ -696,7 +707,7 @@ declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT e
|
|
|
696
707
|
} | undefined) => EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
697
708
|
addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
698
709
|
addOptions<AOUT extends FlatObject>(getOptions: () => Promise<AOUT>): EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
699
|
-
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input,
|
|
710
|
+
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input, output: outputSchema, operationId, scope, tag, method, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO>): Endpoint<z.ZodIntersection<IN, BIN>, BOUT, OUT>;
|
|
700
711
|
/** @desc shorthand for returning {} while having output schema z.object({}) */
|
|
701
712
|
buildVoid<BIN extends IOSchema = EmptySchema>({ handler, ...rest }: Omit<BuildProps<BIN, z.ZodVoid, IN, OUT, SCO>, "output">): Endpoint<z.ZodIntersection<IN, BIN>, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, OUT>;
|
|
702
713
|
}
|
|
@@ -933,11 +944,15 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
|
|
|
933
944
|
type Typeable = ts.TypeNode | ts.Identifier | string | ts.KeywordTypeSyntaxKind;
|
|
934
945
|
|
|
935
946
|
type IOKind = "input" | "response" | ResponseVariant | "encoded";
|
|
947
|
+
type Store = Record<IOKind, ts.TypeNode>;
|
|
936
948
|
declare abstract class IntegrationBase {
|
|
937
949
|
private readonly serverUrl;
|
|
938
950
|
protected paths: Set<string>;
|
|
939
951
|
protected tags: Map<string, readonly string[]>;
|
|
940
|
-
protected registry: Map<string,
|
|
952
|
+
protected registry: Map<string, {
|
|
953
|
+
store: Store;
|
|
954
|
+
isDeprecated: boolean;
|
|
955
|
+
}>;
|
|
941
956
|
protected ids: {
|
|
942
957
|
pathType: ts.Identifier;
|
|
943
958
|
implementationType: ts.Identifier;
|
package/dist/index.d.ts
CHANGED
|
@@ -276,10 +276,12 @@ declare const contentTypes: {
|
|
|
276
276
|
};
|
|
277
277
|
type ContentType = keyof typeof contentTypes;
|
|
278
278
|
|
|
279
|
-
declare class DependsOnMethod extends
|
|
280
|
-
|
|
281
|
-
readonly entries: ReadonlyArray<[Method, AbstractEndpoint, Method[]]>;
|
|
279
|
+
declare class DependsOnMethod extends Routable {
|
|
280
|
+
#private;
|
|
282
281
|
constructor(endpoints: Partial<Record<Method, AbstractEndpoint>>);
|
|
282
|
+
/** @desc [method, endpoint, siblingMethods] */
|
|
283
|
+
get entries(): ReadonlyArray<[Method, AbstractEndpoint, Method[]]>;
|
|
284
|
+
deprecated(): this;
|
|
283
285
|
}
|
|
284
286
|
|
|
285
287
|
type OriginalStatic = typeof express__default.static;
|
|
@@ -374,7 +376,9 @@ interface Routing {
|
|
|
374
376
|
[SEGMENT: string]: Routing | DependsOnMethod | AbstractEndpoint | ServeStatic;
|
|
375
377
|
}
|
|
376
378
|
|
|
377
|
-
declare abstract class
|
|
379
|
+
declare abstract class Routable {
|
|
380
|
+
/** @desc Marks the route as deprecated (makes a copy of the endpoint) */
|
|
381
|
+
abstract deprecated(): this;
|
|
378
382
|
/** @desc Enables nested routes within the path assigned to the subject */
|
|
379
383
|
nest(routing: Routing): Routing;
|
|
380
384
|
}
|
|
@@ -386,7 +390,7 @@ type Handler<IN, OUT, OPT> = (params: {
|
|
|
386
390
|
}) => Promise<OUT>;
|
|
387
391
|
type DescriptionVariant = "short" | "long";
|
|
388
392
|
type IOVariant = "input" | "output";
|
|
389
|
-
declare abstract class AbstractEndpoint extends
|
|
393
|
+
declare abstract class AbstractEndpoint extends Routable {
|
|
390
394
|
abstract execute(params: {
|
|
391
395
|
request: Request;
|
|
392
396
|
response: Response;
|
|
@@ -402,10 +406,12 @@ declare abstract class AbstractEndpoint extends Nesting {
|
|
|
402
406
|
abstract getTags(): ReadonlyArray<string>;
|
|
403
407
|
abstract getOperationId(method: Method): string | undefined;
|
|
404
408
|
abstract getRequestType(): ContentType;
|
|
409
|
+
abstract get isDeprecated(): boolean;
|
|
405
410
|
}
|
|
406
411
|
declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends FlatObject> extends AbstractEndpoint {
|
|
407
412
|
#private;
|
|
408
|
-
constructor(
|
|
413
|
+
constructor(def: {
|
|
414
|
+
deprecated?: boolean;
|
|
409
415
|
middlewares?: AbstractMiddleware[];
|
|
410
416
|
inputSchema: IN;
|
|
411
417
|
outputSchema: OUT;
|
|
@@ -418,11 +424,13 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, OPT extends Fl
|
|
|
418
424
|
scopes?: string[];
|
|
419
425
|
tags?: string[];
|
|
420
426
|
});
|
|
427
|
+
deprecated(): this;
|
|
428
|
+
get isDeprecated(): boolean;
|
|
421
429
|
getDescription(variant: DescriptionVariant): string | undefined;
|
|
422
|
-
getMethods():
|
|
430
|
+
getMethods(): Readonly<("get" | "post" | "put" | "delete" | "patch")[] | undefined>;
|
|
423
431
|
getSchema(variant: "input"): IN;
|
|
424
432
|
getSchema(variant: "output"): OUT;
|
|
425
|
-
getRequestType(): "
|
|
433
|
+
getRequestType(): "json" | "upload" | "raw";
|
|
426
434
|
getResponses(variant: ResponseVariant): readonly NormalizedResponse[];
|
|
427
435
|
getSecurity(): LogicalContainer<Security>[];
|
|
428
436
|
getScopes(): readonly string[];
|
|
@@ -606,7 +614,7 @@ interface TagOverrides {
|
|
|
606
614
|
}
|
|
607
615
|
type Tag = NoNever<keyof TagOverrides, string>;
|
|
608
616
|
declare const getMessageFromError: (error: Error) => string;
|
|
609
|
-
declare const getExamples: <T extends z.
|
|
617
|
+
declare const getExamples: <T extends z.ZodType, V extends "original" | "parsed" | undefined>({ schema, variant, validate, pullProps, }: {
|
|
610
618
|
schema: T;
|
|
611
619
|
/**
|
|
612
620
|
* @desc examples variant: original or parsed
|
|
@@ -633,6 +641,7 @@ interface Metadata {
|
|
|
633
641
|
/** @override ZodDefault::_def.defaultValue() in depictDefault */
|
|
634
642
|
defaultLabel?: string;
|
|
635
643
|
brand?: string | number | symbol;
|
|
644
|
+
isDeprecated?: boolean;
|
|
636
645
|
}
|
|
637
646
|
|
|
638
647
|
/**
|
|
@@ -659,6 +668,7 @@ declare module "zod" {
|
|
|
659
668
|
interface ZodType {
|
|
660
669
|
/** @desc Add an example value (before any transformations, can be called multiple times) */
|
|
661
670
|
example(example: this["_input"]): this;
|
|
671
|
+
deprecated(): this;
|
|
662
672
|
}
|
|
663
673
|
interface ZodDefault<T extends z.ZodTypeAny> {
|
|
664
674
|
/** @desc Change the default value in the generated Documentation to a label */
|
|
@@ -683,6 +693,7 @@ interface BuildProps<IN extends IOSchema, OUT extends IOSchema | z.ZodVoid, MIN
|
|
|
683
693
|
method?: Method | [Method, ...Method[]];
|
|
684
694
|
scope?: SCO | SCO[];
|
|
685
695
|
tag?: Tag | Tag[];
|
|
696
|
+
deprecated?: boolean;
|
|
686
697
|
}
|
|
687
698
|
declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT extends FlatObject = EmptyObject, SCO extends string = string> {
|
|
688
699
|
#private;
|
|
@@ -696,7 +707,7 @@ declare class EndpointsFactory<IN extends IOSchema<"strip"> = EmptySchema, OUT e
|
|
|
696
707
|
} | undefined) => EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
697
708
|
addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
698
709
|
addOptions<AOUT extends FlatObject>(getOptions: () => Promise<AOUT>): EndpointsFactory<IN, OUT & AOUT, SCO>;
|
|
699
|
-
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input,
|
|
710
|
+
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input, output: outputSchema, operationId, scope, tag, method, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO>): Endpoint<z.ZodIntersection<IN, BIN>, BOUT, OUT>;
|
|
700
711
|
/** @desc shorthand for returning {} while having output schema z.object({}) */
|
|
701
712
|
buildVoid<BIN extends IOSchema = EmptySchema>({ handler, ...rest }: Omit<BuildProps<BIN, z.ZodVoid, IN, OUT, SCO>, "output">): Endpoint<z.ZodIntersection<IN, BIN>, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, OUT>;
|
|
702
713
|
}
|
|
@@ -933,11 +944,15 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
|
|
|
933
944
|
type Typeable = ts.TypeNode | ts.Identifier | string | ts.KeywordTypeSyntaxKind;
|
|
934
945
|
|
|
935
946
|
type IOKind = "input" | "response" | ResponseVariant | "encoded";
|
|
947
|
+
type Store = Record<IOKind, ts.TypeNode>;
|
|
936
948
|
declare abstract class IntegrationBase {
|
|
937
949
|
private readonly serverUrl;
|
|
938
950
|
protected paths: Set<string>;
|
|
939
951
|
protected tags: Map<string, readonly string[]>;
|
|
940
|
-
protected registry: Map<string,
|
|
952
|
+
protected registry: Map<string, {
|
|
953
|
+
store: Store;
|
|
954
|
+
isDeprecated: boolean;
|
|
955
|
+
}>;
|
|
941
956
|
protected ids: {
|
|
942
957
|
pathType: ts.Identifier;
|
|
943
958
|
implementationType: ts.Identifier;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{clone as
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:nn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Pr}from"zod";var wt=class{},F=class extends wt{#e;#t;#r;constructor({input:t=Pr.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 Pr.ZodError?new V(o):o}}},Se=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Te=class{nest(t){return Object.assign(t,{"":this})}};var je=class extends Te{},tt=class extends je{#e;#t;#r;#n;#s;#i;#o;#a;#p;#c;#d;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:s,getOperationId:a=()=>{},scopes:c=[],middlewares:d=[],tags:p=[],description:m,shortDescription:f}){super(),this.#s=n,this.#i=s,this.#r=d,this.#c=a,this.#t=Object.freeze(t),this.#a=Object.freeze(c),this.#p=Object.freeze(p),this.#e={long:m,short:f},this.#o={input:r,output:o},this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#d=Tr(r)?"upload":Or(r)?"raw":"json"}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return this.#o[t]}getRequestType(){return this.#d}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return this.#a}getTags(){return this.#p}getOperationId(t){return this.#c(t)}async#m(t){try{return await this.#o.output.parseAsync(t)}catch(r){throw r instanceof Ar.ZodError?new oe(r):r}}async#l({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#r)if(!(t==="options"&&!(a instanceof Se))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#u({input:t,...r}){let o;try{o=await this.#o.input.parseAsync(t)}catch(n){throw n instanceof Ar.ZodError?new V(n):n}return this.#s({...r,input:o})}async#y({error:t,...r}){try{await this.#i.execute({...r,error:t})}catch(o){et({...r,error:new G(Y(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Tt(t),a={},c=null,d=null,p=$e(t,n.inputSources);try{if(await this.#l({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#m(await this.#u({input:p,logger:o,options:a}))}catch(m){d=Y(m)}await this.#y({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};var wr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>ur(s,n),o)};import{z as q}from"zod";var Oe={positive:200,negative:400},Re=Object.keys(Oe);var Et=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},de=class extends Et{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return At(this.#e,{variant:"positive",args:[t],statusCodes:[Oe.positive],mimeTypes:[z.json]})}getNegativeResponse(){return At(this.#t,{variant:"negative",args:[],statusCodes:[Oe.negative],mimeTypes:[z.json]})}},Ne=new de({positive:e=>{let t=J({schema:e,pullProps:!0}),r=q.object({status:q.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:q.object({status:q.literal("error"),error:q.object({message:q.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=be(e);return Ce(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ce(a)}})}n.status(Oe.positive).json({status:"success",data:r})}}),zt=new de({positive:e=>{let t=J({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof q.ZodArray?e.shape.items:q.array(q.any());return t.reduce((o,n)=>ie(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:q.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=be(r);return Ce(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ce(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Oe.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var me=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Se(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Er.object({}),handler:r,output:o,description:n,shortDescription:s,operationId:a,scope:c,tag:d,method:p}){let{middlewares:m,resultHandler:f}=this,x=typeof p=="string"?[p]:p,y=typeof a=="function"?a:()=>a,T=typeof c=="string"?[c]:c||[],S=typeof d=="string"?[d]:d||[];return new tt({handler:r,middlewares:m,outputSchema:o,resultHandler:f,scopes:T,tags:S,methods:x,getOperationId:y,description:n,shortDescription:s,inputSchema:wr(m,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Er.object({}),handler:async o=>(await t(o),{})})}},sn=new me(Ne),an=new me(zt);import fn from"ansis";import{inspect as gn}from"node:util";import{performance as kr}from"node:perf_hooks";import{blue as pn,green as cn,hex as dn,red as mn,cyanBright as ln}from"ansis";import{memoizeWith as un}from"ramda";var It={debug:pn,info:cn,warn:dn("#FFA500"),error:mn,ctx:ln},rt={debug:10,info:20,warn:30,error:40},zr=e=>ie(e)&&Object.keys(rt).some(t=>t in e),Ir=e=>e in rt,vr=(e,t)=>rt[e]<rt[t],yn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Pe=un((e,t)=>`${e}${t}`,yn),Zr=e=>e<1e-6?Pe("nanosecond",3).format(e/1e-6):e<.001?Pe("nanosecond").format(e/1e-6):e<1?Pe("microsecond").format(e/.001):e<1e3?Pe("millisecond").format(e):e<6e4?Pe("second",2).format(e/1e3):Pe("minute",2).format(e/6e4);var Le=class e{config;constructor({color:t=fn.isSupported(),level:r=ge()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return gn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||vr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?It.ctx(s):s),d.push(c?`${It[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})}get ctx(){return this.config.ctx}profile(t){let r=kr.now();return()=>{let o=kr.now()-r,{message:n,severity:s="debug",formatter:a=Zr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import{keys as hn,reject as xn,equals as bn}from"ramda";var Me=class extends Te{entries;constructor(t){super();let r=[],o=hn(t);for(let n of o){let s=t[n];s&&r.push([n,s,xn(bn(n),o)])}this.entries=Object.freeze(r)}};import Sn from"express";var Ue=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Sn.static(...this.params))}};import Zt from"express";import In from"node:http";import vn from"node:https";var Ae=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new ve(e)};import Tn from"http-errors";var ot=class{constructor(t){this.logger=t}#e=new WeakSet;check(t,r){if(!this.#e.has(t)){if(t.getRequestType()==="json")try{Pt(t.getSchema("input"),"in")}catch(o){this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Re)for(let{mimeTypes:n,schema:s}of t.getResponses(o))if(n?.includes(z.json))try{Pt(s,"out")}catch(a){this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:a}))}this.#e.add(t)}}};var Cr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new fe(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),we=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Cr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof je){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Ue)r&&s.apply(n,r);else if(s instanceof Me)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new fe(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Cr(s,n))}};var On=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=Tn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},vt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new ot(t()),a=new Map;if(we({routing:o,onEndpoint:(d,p,m,f)=>{ge()||s.check(d,{path:p,method:m});let x=n?.[d.getRequestType()]||[],y=async(T,S)=>{let C=t(T);if(r.cors){let w={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[m,...f||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},I=typeof r.cors=="function"?await r.cors({request:T,endpoint:d,logger:C,defaultHeaders:w}):w;for(let N in I)S.set(N,I[N])}return d.execute({request:T,response:S,logger:C,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...x,y),a.get(p)?.push("options"))),a.get(p)?.push(m),e[m](p,...x,y)},onStatic:e.use.bind(e)}),r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,On(p))};import Kr,{isHttpError as Pn}from"http-errors";import{setInterval as Rn}from"node:timers/promises";var jr=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",Nr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Lr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Mr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Ur=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Hr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(jr(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let m of["connection","secureConnection"])p.on(m,c);let d=async()=>{for(let p of e)p.on("request",Mr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Lr(p)||Nr(p))&&a(p);for await(let p of Rn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Ur))};return{sockets:n,shutdown:()=>o??=d()}};var Dr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:Pn(r)?r:Kr(400,Y(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Fr=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Kr(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){et({response:o,logger:s,error:new G(Y(a),n)})}},An=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},wn=e=>({log:e.debug.bind(e)}),qr=async({getLogger:e,config:t})=>{let r=await Ae("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let m=e(c);try{await n?.({request:c,logger:m})}catch(f){return p(f)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:wn(m)})(c,d,p)}),o&&a.push(An(o)),a},Br=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},$r=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:s}),n()},Vr=e=>t=>t?.res?.locals[g]?.logger||e,_r=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 hr,fromPairs as qo,map as Bo,pipe as $o,toPairs as _o,pair as Vo}from"ramda";import{z as xe}from"zod";import{chain as fr,memoizeWith as No,objOf as Lo,xprod as Mo}from"ramda";import{z as yr}from"zod";var E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream"};var ge=class extends Error{name="RoutingError"},D=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},Ve=class extends Error{name="IOSchemaError"},oe=class extends Ve{constructor(r){super(ne(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends Ve{constructor(r){super(ne(r),{cause:r});this.cause=r}name="InputValidationError"},W=class extends Error{constructor(r,o){super(ne(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ce=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Rt=/:([A-Za-z0-9_]+)/g,Ge=e=>e.match(Rt)?.map(t=>t.slice(1))||[],Uo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Pt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Do=["body","query","params"],At=e=>e.method.toLowerCase(),Je=(e,t={})=>{let r=At(e);return r==="options"?{}:(t[r]||Pt[r]||Do).filter(o=>o==="files"?Uo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},Y=e=>e instanceof Error?e:new Error(String(e)),ne=e=>e instanceof yr.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof oe?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Ho=e=>Object.entries(e.shape).reduce((t,[r,o])=>{let{_def:n}=o;return se(t,(n[y]?.examples||[]).map(Lo(r)),([s,a])=>({...s,...a}))},[]),Q=({schema:e,variant:t="original",validate:r=t==="parsed",pullProps:o=!1})=>{let n=e._def[y]?.examples||[];if(!n.length&&o&&e instanceof yr.ZodObject&&(n=Ho(e)),!r&&t==="original")return n;let s=[];for(let a of n){let c=e.safeParse(a);c.success&&s.push(t==="parsed"?c.data:a)}return s},se=(e,t,r)=>e.length&&t.length?Mo(e,t).map(r):e.concat(t),je=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,wt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),X=(...e)=>{let t=fr(o=>o.split(/[^A-Z0-9]/gi),e);return fr(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(wt).join("")},We=(e,t)=>{try{return typeof e.parse(t)}catch{return}},ie=e=>typeof e=="object"&&e!==null,he=No(()=>"static",()=>process.env.NODE_ENV==="production");import{clone as Ko,mergeDeepRight as Fo}from"ramda";var y=Symbol.for("express-zod-api"),Ne=e=>{let t=e.describe(e.description);return t._def[y]=Ko(t._def[y])||{examples:[]},t},gr=(e,t)=>{if(!(y in e._def))return t;let r=Ne(t);return r._def[y].examples=se(r._def[y].examples,e._def[y].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Fo({...o},{...n}):n),r};var Go=function(e){let t=Ne(this);return t._def[y].examples.push(e),t},Jo=function(){let e=Ne(this);return e._def[y].isDeprecated=!0,e},Wo=function(e){let t=Ne(this);return t._def[y].defaultLabel=e,t},Yo=function(e){return new xe.ZodBranded({typeName:xe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[y]:{examples:[],...hr(this._def[y]),brand:e}})},Qo=function(e){let t=typeof e=="function"?e:$o(_o,Bo(([n,s])=>Vo(e[String(n)]||n,s)),qo),r=t(hr(this.shape)),o=xe.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};y in globalThis||(globalThis[y]=!0,Object.defineProperties(xe.ZodType.prototype,{example:{get(){return Go.bind(this)}},deprecated:{get(){return Jo.bind(this)}},brand:{set(){},get(){return Yo.bind(this)}}}),Object.defineProperty(xe.ZodDefault.prototype,"label",{get(){return Wo.bind(this)}}),Object.defineProperty(xe.ZodObject.prototype,"remap",{get(){return Qo.bind(this)}}));function Xo(e){return e}import{z as vr}from"zod";import{z as Ir}from"zod";import{fail as C}from"node:assert/strict";import{z as Le}from"zod";var Ye=e=>!isNaN(e.getTime());var ae=Symbol("DateIn"),xr=()=>Le.union([Le.string().date(),Le.string().datetime(),Le.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Le.date().refine(Ye)).brand(ae);import{z as en}from"zod";var pe=Symbol("DateOut"),br=()=>en.date().refine(Ye).transform(e=>e.toISOString()).brand(pe);import{z as Qe}from"zod";var F=Symbol("File"),Sr=Qe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),tn={buffer:()=>Sr.brand(F),string:()=>Qe.string().brand(F),binary:()=>Sr.or(Qe.string()).brand(F),base64:()=>Qe.string().base64().brand(F)};function Xe(e){return tn[e||"string"]()}import{z as rn}from"zod";var ee=Symbol("Raw"),Tr=(e={})=>rn.object({raw:Xe("buffer")}).extend(e).brand(ee);import{z as on}from"zod";var be=Symbol("Upload"),Or=()=>on.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(be);var Rr=(e,{next:t})=>e.options.some(t),nn=({_def:e},{next:t})=>[e.left,e.right].some(t),et=(e,{next:t})=>t(e.unwrap()),Et={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Rr,ZodDiscriminatedUnion:Rr,ZodIntersection:nn,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:et,ZodNullable:et,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},tt=(e,{condition:t,rules:r=Et,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t?.(e))return!0;let s=o<n?r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName]:void 0;return s?s(e,{next:a=>tt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},Pr=e=>tt(e,{condition:t=>t._def[y]?.brand===be}),Ar=e=>tt(e,{condition:t=>t._def[y]?.brand===ee,maxDepth:3}),wr=(e,t)=>{let r=new WeakSet;return tt(e,{maxDepth:300,rules:{...Et,ZodBranded:et,ZodReadonly:et,ZodCatch:({_def:{innerType:o}},{next:n})=>n(o),ZodPipeline:({_def:o},{next:n})=>n(o[t]),ZodLazy:(o,{next:n})=>r.has(o)?!1:r.add(o)&&n(o.schema),ZodTuple:({items:o,_def:{rest:n}},{next:s})=>[...o].concat(n??[]).some(s),ZodEffects:{out:void 0,in:Et.ZodEffects}[t],ZodNaN:()=>C("z.nan()"),ZodSymbol:()=>C("z.symbol()"),ZodFunction:()=>C("z.function()"),ZodMap:()=>C("z.map()"),ZodSet:()=>C("z.set()"),ZodBigInt:()=>C("z.bigint()"),ZodVoid:()=>C("z.void()"),ZodPromise:()=>C("z.promise()"),ZodNever:()=>C("z.never()"),ZodDate:()=>t==="in"&&C("z.date()"),[pe]:()=>t==="in"&&C("ez.dateOut()"),[ae]:()=>t==="out"&&C("ez.dateIn()"),[ee]:()=>t==="out"&&C("ez.raw()"),[be]:()=>t==="out"&&C("ez.upload()"),[F]:()=>!1}})};import pn,{isHttpError as cn}from"http-errors";import Er,{isHttpError as sn}from"http-errors";import{z as an}from"zod";var zt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof an.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new W(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:a})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof a=="string"?[a]:a===void 0?o.mimeTypes:a}))},Me=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Se=e=>sn(e)?e:Er(e instanceof G?400:500,ne(e),{cause:e.cause||e}),ce=e=>he()&&!e.expose?Er(e.statusCode).message:e.message;var rt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ce(pn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:cn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as zr}from"zod";var It=class{},q=class extends It{#e;#t;#r;constructor({input:t=zr.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 zr.ZodError?new G(o):o}}},Te=class extends q{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((a,c)=>{let d=p=>{if(p&&p instanceof Error)return c(o(p));a(r(n,s))};t(n,s,d)?.catch(d)})})}};var Oe=class{nest(t){return Object.assign(t,{"":this})}};var Ue=class extends Oe{},ot=class e extends Ue{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}getDescription(t){return this.#e[t==="short"?"shortDescription":"description"]}getMethods(){return Object.freeze(this.#e.methods)}getSchema(t){return this.#e[t==="output"?"outputSchema":"inputSchema"]}getRequestType(){return Pr(this.#e.inputSchema)?"upload":Ar(this.#e.inputSchema)?"raw":"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}getSecurity(){return(this.#e.middlewares||[]).map(t=>t.getSecurity()).filter(t=>t!==void 0)}getScopes(){return Object.freeze(this.#e.scopes||[])}getTags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Ir.ZodError?new oe(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let a of this.#e.middlewares||[])if(!(t==="options"&&!(a instanceof Te))&&(Object.assign(o,await a.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Ir.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s({error:t,...r}){try{await this.#e.resultHandler.execute({...r,error:t})}catch(o){rt({...r,error:new W(Y(o),t||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=At(t),a={},c=null,d=null,p=Je(t,n.inputSources);try{if(await this.#o({method:s,input:p,request:t,response:r,logger:o,options:a}),r.writableEnded)return;if(s==="options")return void r.status(200).end();c=await this.#r(await this.#n({input:p,logger:o,options:a}))}catch(m){d=Y(m)}await this.#s({input:p,output:c,request:t,response:r,error:d,logger:o,options:a})}};import{z as de}from"zod";var Zr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>gr(s,n),o)},H=e=>e instanceof de.ZodObject?e:e instanceof de.ZodBranded?H(e.unwrap()):e instanceof de.ZodUnion||e instanceof de.ZodDiscriminatedUnion?e.options.map(t=>H(t)).reduce((t,r)=>t.merge(r.partial()),de.object({})):e instanceof de.ZodEffects?H(e._def.schema):e instanceof de.ZodPipeline?H(e._def.in):H(e._def.left).merge(H(e._def.right));import{z as B}from"zod";var Re={positive:200,negative:400},Pe=Object.keys(Re);var Zt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},me=class extends Zt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return zt(this.#e,{variant:"positive",args:[t],statusCodes:[Re.positive],mimeTypes:[E.json]})}getNegativeResponse(){return zt(this.#t,{variant:"negative",args:[],statusCodes:[Re.negative],mimeTypes:[E.json]})}},De=new me({positive:e=>{let t=Q({schema:e,pullProps:!0}),r=B.object({status:B.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:B.object({status:B.literal("error"),error:B.object({message:B.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let a=Se(e);return Me(a,s,o,t),void n.status(a.statusCode).set(a.headers).json({status:"error",error:{message:ce(a)}})}n.status(Re.positive).json({status:"success",data:r})}}),vt=new me({positive:e=>{let t=Q({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof B.ZodArray?e.shape.items:B.array(B.any());return t.reduce((o,n)=>ie(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:B.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Se(r);return Me(a,o,n,s),void e.status(a.statusCode).type("text/plain").send(ce(a))}if(t&&"items"in t&&Array.isArray(t.items))return void e.status(Re.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var le=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof q?t:new q(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Te(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new q({handler:t})),this.resultHandler)}build({input:t=vr.object({}),output:r,operationId:o,scope:n,tag:s,method:a,...c}){let{middlewares:d,resultHandler:p}=this,m=typeof a=="string"?[a]:a,x=typeof o=="function"?o:()=>o,b=typeof n=="string"?[n]:n||[],f=typeof s=="string"?[s]:s||[];return new ot({...c,middlewares:d,outputSchema:r,resultHandler:p,scopes:b,tags:f,methods:m,getOperationId:x,inputSchema:Zr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:vr.object({}),handler:async o=>(await t(o),{})})}},dn=new le(De),mn=new le(vt);import bn from"ansis";import{inspect as Sn}from"node:util";import{performance as Lr}from"node:perf_hooks";import{blue as ln,green as un,hex as fn,red as yn,cyanBright as gn}from"ansis";import{memoizeWith as hn}from"ramda";var kt={debug:ln,info:un,warn:fn("#FFA500"),error:yn,ctx:gn},nt={debug:10,info:20,warn:30,error:40},kr=e=>ie(e)&&Object.keys(nt).some(t=>t in e),Cr=e=>e in nt,jr=(e,t)=>nt[e]<nt[t],xn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ae=hn((e,t)=>`${e}${t}`,xn),Nr=e=>e<1e-6?Ae("nanosecond",3).format(e/1e-6):e<.001?Ae("nanosecond").format(e/1e-6):e<1?Ae("microsecond").format(e/.001):e<1e3?Ae("millisecond").format(e):e<6e4?Ae("second",2).format(e/1e3):Ae("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=bn.isSupported(),level:r=he()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}prettyPrint(t){let{depth:r,color:o,level:n}=this.config;return Sn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...a},color:c}=this.config;if(n==="silent"||jr(t,n))return;let d=[new Date().toISOString()];s&&d.push(c?kt.ctx(s):s),d.push(c?`${kt[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})}get ctx(){return this.config.ctx}profile(t){let r=Lr.now();return()=>{let o=Lr.now()-r,{message:n,severity:s="debug",formatter:a=Nr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,a(o))}}};import{keys as Tn,reject as On,equals as Rn}from"ramda";var Ke=class e extends Oe{#e;constructor(t){super(),this.#e=t}get entries(){let t=[],r=Tn(this.#e);for(let o of r){let n=this.#e[o];n&&t.push([o,n,On(Rn(o),r)])}return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import Pn from"express";var Fe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Pn.static(...this.params))}};import jt from"express";import jn from"node:http";import Nn from"node:https";var we=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ce(e)};import wn from"http-errors";import{tryCatch as An}from"ramda";var st=class{constructor(t){this.logger=t;this.#e=An(wr)}#e;#t=new WeakSet;#r=new WeakMap;checkJsonCompat(t,r){if(!this.#t.has(t)){t.getRequestType()==="json"&&this.#e(o=>this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o})))(t.getSchema("input"),"in");for(let o of Pe){let n=this.#e(s=>this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:s})));for(let{mimeTypes:s,schema:a}of t.getResponses(o))s?.includes(E.json)&&n(a,"out")}this.#t.add(t)}}checkPathParams(t,r,o){let n=this.#r.get(r);if(n?.paths.includes(t))return;let s=Ge(t);if(s.length===0)return;let a=n?.shape||H(r.getSchema("input")).shape;for(let c of s)c in a||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:c}));n?n.paths.push(t):this.#r.set(r,{shape:a,paths:[t]})}};var Mr=(e,t)=>Object.entries(e).map(([r,o])=>{if(r.includes("/"))throw new ge(`The entry '${r}' must avoid having slashes \u2014 use nesting instead.`);let n=r.trim();return[`${t||""}${n?`/${n}`:""}`,o]}),Ee=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Mr(e);for(;o.length;){let[n,s]=o.shift();if(s instanceof Ue){let a=s.getMethods()||["get"];for(let c of a)t(s,n,c)}else if(s instanceof Fe)r&&s.apply(n,r);else if(s instanceof Ke)for(let[a,c,d]of s.entries){let p=c.getMethods();if(p&&!p.includes(a))throw new ge(`Endpoint assigned to ${a} method of ${n} must support ${a} method.`);t(c,n,a,d)}else o.unshift(...Mr(s,n))}};var En=e=>({method:t},r,o)=>{let n=e.join(", ").toUpperCase();r.set({Allow:n});let s=wn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Ct=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=new st(t()),a=new Map;if(Ee({routing:o,onEndpoint:(d,p,m,x)=>{he()||(s?.checkJsonCompat(d,{path:p,method:m}),s?.checkPathParams(p,d,{method:m}));let b=n?.[d.getRequestType()]||[],f=async(P,R)=>{let v=t(P);if(r.cors){let z={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":[m,...x||[],"options"].join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"},A=typeof r.cors=="function"?await r.cors({request:P,endpoint:d,logger:v,defaultHeaders:z}):z;for(let I in A)R.set(I,A[I])}return d.execute({request:P,response:R,logger:v,config:r})};a.has(p)||(a.set(p,[]),r.cors&&(e.options(p,...b,f),a.get(p)?.push("options"))),a.get(p)?.push(m),e[m](p,...b,f)},onStatic:e.use.bind(e)}),s=void 0,r.wrongMethodBehavior===405)for(let[d,p]of a.entries())e.all(d,En(p))};import Br,{isHttpError as In}from"http-errors";import{setInterval as zn}from"node:timers/promises";var Ur=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",Dr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Hr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Kr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Fr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var qr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=p=>void n.delete(p.destroy()),a=p=>void(Ur(p)?!p._httpMessage.headersSent&&p._httpMessage.setHeader("connection","close"):s(p)),c=p=>void(o?p.destroy():n.add(p.once("close",()=>void n.delete(p))));for(let p of e)for(let m of["connection","secureConnection"])p.on(m,c);let d=async()=>{for(let p of e)p.on("request",Kr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let p of n)(Hr(p)||Dr(p))&&a(p);for await(let p of zn(10,Date.now()))if(n.size===0||Date.now()-p>=t)break;for(let p of n)s(p);return Promise.allSettled(e.map(Fr))};return{sockets:n,shutdown:()=>o??=d()}};var $r=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:In(r)?r:Br(400,Y(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),_r=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Br(404,`Can not ${r.method} ${r.path}`),s=t(r);try{e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(a){rt({response:o,logger:s,error:new W(Y(a),n)})}},Zn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},vn=e=>({log:e.debug.bind(e)}),Vr=async({getLogger:e,config:t})=>{let r=await we("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},a=[];return a.push(async(c,d,p)=>{let m=e(c);try{await n?.({request:c,logger:m})}catch(x){return p(x)}return r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:vn(m)})(c,d,p)}),o&&a.push(Zn(o)),a},Gr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Jr=({logger:e,config:t})=>async(r,o,n)=>{let s=await t.childLoggerProvider?.({request:r,parent:e})||e;s.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[y]={logger:s}),n()},Wr=e=>t=>t?.res?.locals[y]?.logger||e,Yr=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),Qr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=qr(e,{logger:t,timeout:r}),s=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,s)};import{gray as kn,hex as Xr,italic as it,whiteBright as Cn}from"ansis";var eo=e=>{if(e.columns<132)return;let t=it("Proudly supports transgender community.".padStart(109)),r=it("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=it("Thank you for choosing Express Zod API for your project.".padStart(132)),n=it("for Tai".padEnd(20)),s=Xr("#F5A9B8"),a=Xr("#5BCEFA"),c=new Array(14).fill(a,1,3).fill(s,3,5).fill(Cn,5,7).fill(s,7,9).fill(a,9,12).fill(kn,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,9 +15,9 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((p,m)=>c[m]?c[m](p):p).join(`
|
|
18
|
-
`))};var Wr=e=>{e.startupLogo!==!1&&Jr(process.stdout);let t=e.errorHandler||Ne,r=zr(e.logger)?e.logger:new Le(e.logger);r.debug("Running",{build:"v22.7.0 (ESM)",env:process.env.NODE_ENV||"development"}),_r(r);let o=$r({logger:r,config:e}),s={getLogger:Vr(r),errorHandler:t},a=Fr(s),c=Dr(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Wr(e);return vt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},kn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Wr(e),c=Zt().disable("x-powered-by").use(a);if(e.compression){let x=await Ae("compression");c.use(x(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||Zt.json()],raw:[e.rawParser||Zt.raw(),Br],upload:e.upload?await qr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),vt({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],m=(x,y)=>()=>x.listen(y,()=>r.info("Listening",y)),f=[];if(e.http){let x=In.createServer(c);p.push(x),f.push(m(x,e.http.listen))}if(e.https){let x=vn.createServer(e.https.options,c);p.push(x),f.push(m(x,e.https.listen))}return e.gracefulShutdown&&Gr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:f.map(x=>x())}};import{OpenApiBuilder as Bs}from"openapi3-ts/oas31";import{pluck as $s}from"ramda";import{chain as Cn,isEmpty as jn,map as Qr,partition as Nn,prop as Xr,reject as Ln,filter as kt,concat as Ct}from"ramda";var eo=e=>ie(e)&&"or"in e,to=e=>ie(e)&&"and"in e,jt=e=>!to(e)&&!eo(e),ro=e=>{let t=kt(jt,e),r=Cn(Xr("and"),kt(to,e)),[o,n]=Nn(jt,r),s=Ct(t,o),a=kt(eo,e);return Qr(Xr("or"),Ct(a,n)).reduce((d,p)=>se(d,Qr(m=>jt(m)?[m]:m.and,p),([m,f])=>Ct(m,f)),Ln(jn,[s]))};import{isReferenceObject as Mt,isSchemaObject as it}from"openapi3-ts/oas31";import{concat as Un,chain as Hn,type as io,filter as ao,fromPairs as at,has as Kn,isNil as Dn,map as He,mergeDeepRight as Fn,mergeDeepWith as qn,objOf as Bn,omit as pt,pipe as po,pluck as $n,reject as Vn,times as _n,toLower as Gn,union as Yn,when as Jn,xprod as Nt,zip as Wn}from"ramda";import{z as A}from"zod";var le=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],c=s?s(e,{...n,next:p=>le(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var oo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var no=50,co="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Qn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},mo=/:([A-Za-z0-9_]+)/g,Xn=/^\d{4}-\d{2}-\d{2}$/,es=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,ts=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,rs=e=>e.match(mo)?.map(t=>t.slice(1))||[],lo=e=>e.replace(mo,t=>`{${t.slice(1)}}`),os=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),ns=({_def:{innerType:e}},{next:t})=>t(e),ss=()=>({format:"any"}),is=({},e)=>{if(e.isResponse)throw new H("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},as=e=>{let t=e.unwrap();return{type:"string",format:t instanceof A.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ps=({options:e},{next:t})=>({oneOf:e.map(t)}),cs=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),ds=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Un(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},ms=e=>{let[t,r]=e.filter(it).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=qn(ds,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Yn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,s])=>Fn(n,s))),o},ls=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return ms(o)}catch{}return{allOf:o}},us=(e,{next:t})=>t(e.unwrap()),ys=(e,{next:t})=>t(e.unwrap()),fs=(e,{next:t})=>{let r=t(e.unwrap());return it(r)&&(r.type=yo(r)),r},uo=e=>{let t=Gn(io(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},so=e=>({type:uo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),gs=({value:e})=>({type:uo(e),const:e}),hs=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&Ze(c)?c instanceof A.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=st(e,r)),s.length&&(a.required=s),a},xs=()=>({type:"null"}),bs=({},e)=>{if(e.isResponse)throw new H("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:co}}},Ss=({},e)=>{if(!e.isResponse)throw new H("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:co}}},Ts=({},e)=>{throw new H(`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)},Os=()=>({type:"boolean"}),Rs=()=>({type:"integer",format:"bigint"}),Ps=e=>e.every(t=>t instanceof A.ZodLiteral),As=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof A.ZodEnum||e instanceof A.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=st(A.object(at(Nt(o,[t]))),r),n.required=o),n}if(e instanceof A.ZodLiteral)return{type:"object",properties:st(A.object({[e.value]:t}),r),required:[e.value]};if(e instanceof A.ZodUnion&&Ps(e.options)){let o=He(s=>`${s.value}`,e.options),n=at(Nt(o,[t]));return{type:"object",properties:st(A.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},ws=({_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},Es=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),zs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:f,isDate:x,isTime:y,isBase64:T,isNANOID:S,isBase64url:C,isDuration:j,_def:{checks:b}})=>{let w=b.find(Z=>Z.kind==="regex"),I=b.find(Z=>Z.kind==="datetime"),N=b.some(Z=>Z.kind==="jwt"),v=b.find(Z=>Z.kind==="length"),E={type:"string"},te={"date-time":m,byte:T,base64url:C,date:x,time:y,duration:j,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:S,jwt:N,ip:d,cidr:f,emoji:p};for(let Z in te)if(te[Z]){E.format=Z;break}return v&&([E.minLength,E.maxLength]=[v.value,v.value]),r!==null&&(E.minLength=r),o!==null&&(E.maxLength=o),x&&(E.pattern=Xn.source),y&&(E.pattern=es.source),m&&(E.pattern=ts(I?.offset).source),w&&(E.pattern=w.regex.source),E},Is=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,p?m.maximum=d:m.exclusiveMaximum=d,m},st=({shape:e},t)=>He(t,e),vs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Qn?.[t]},yo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Zs=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&it(o)){let s=Ve(e,vs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(A.any())}if(!t&&n.type==="preprocess"&&it(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},ks=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Cs=(e,{next:t})=>t(e.unwrap()),js=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ns=(e,{next:t})=>t(e.unwrap().shape.raw),fo=e=>e.length?at(Wn(_n(t=>`example${t+1}`,e.length),He(Bn("value"),e))):void 0,go=(e,t,r=[])=>po(J,He(Jn(o=>io(o)==="Object",pt(r))),fo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Ls=(e,t)=>po(J,ao(Kn(t)),$n(t),fo)({schema:e,variant:"original",validate:!0,pullProps:!0}),X=e=>e instanceof A.ZodObject?e:e instanceof A.ZodBranded?X(e.unwrap()):e instanceof A.ZodUnion||e instanceof A.ZodDiscriminatedUnion?e.options.map(t=>X(t)).reduce((t,r)=>t.merge(r.partial()),A.object({})):e instanceof A.ZodEffects?X(e._def.schema):e instanceof A.ZodPipeline?X(e._def.in):X(e._def.left).merge(X(e._def.right)),Ms=(e,t)=>t?.includes(e)||e.startsWith("x-")||oo.includes(e),ho=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let m=X(r),f=rs(e),x=o.includes("query"),y=o.includes("params"),T=o.includes("headers"),S=b=>y&&f.includes(b),C=Hn(ao(b=>b.type==="header"),d??[]).map(({name:b})=>b),j=b=>T&&(c?.(b,t,e)??Ms(b,C));return Object.entries(m.shape).reduce((b,[w,I])=>{let N=S(w)?"path":j(w)?"header":x?"query":void 0;if(!N)return b;let v=le(I,{rules:{...a,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),E=s==="components"?n(I,v,W(p,w)):v;return b.concat({name:w,in:N,required:!I.isOptional(),description:v.description||p,schema:E,examples:Ls(m,w)})},[])},Ut={ZodString:zs,ZodNumber:Is,ZodBigInt:Rs,ZodBoolean:Os,ZodNull:xs,ZodArray:ws,ZodTuple:Es,ZodRecord:As,ZodObject:hs,ZodLiteral:gs,ZodIntersection:ls,ZodUnion:ps,ZodAny:ss,ZodDefault:os,ZodEnum:so,ZodNativeEnum:so,ZodEffects:Zs,ZodOptional:us,ZodNullable:fs,ZodDiscriminatedUnion:cs,ZodBranded:Cs,ZodDate:Ts,ZodCatch:ns,ZodPipeline:ks,ZodLazy:js,ZodReadonly:ys,[D]:as,[xe]:is,[pe]:Ss,[ae]:bs,[Q]:Ns},Ht=(e,{isResponse:t,prev:r})=>{if(Mt(r))return{};let{description:o}=e,n=e instanceof A.ZodLazy,s=r.type!==void 0,a=t&&Ze(e),c=!n&&s&&!a&&e.isNullable(),d={};if(o&&(d.description=o),c&&(d.type=yo(r)),!n){let p=J({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(d.examples=p.slice())}return d},Kt=(e,t)=>{throw new H(`Zod type ${e.constructor.name} is unsupported.`,t)},Lt=(e,t)=>{if(Mt(e))return e;let r={...e};return r.properties&&(r.properties=pt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>pt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Lt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Lt(o,t))),r},xo=e=>Mt(e)?e:pt(["examples"],e),bo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${Ot(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let f=xo(le(r,{rules:{...p,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x={schema:a==="components"?s(r,f,W(m)):f,examples:go(r,!0)};return{description:m,content:at(Nt(o,[x]))}},Us=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Hs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Ks=({name:e})=>({type:"apiKey",in:"header",name:e}),Ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Fs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),qs=({flows:e={}})=>({type:"oauth2",flows:He(t=>({...t,scopes:t.scopes||{}}),Vn(Dn,e))}),So=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Us(o):o.type==="input"?Hs(o,t):o.type==="header"?Ks(o):o.type==="cookie"?Ds(o):o.type==="openid"?Fs(o):qs(o);return e.map(o=>o.map(r))},To=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Oo=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=xo(Lt(le(r,{rules:{...a,...Ut},onEach:Ht,onMissing:Kt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:s==="components"?n(r,p,W(d)):p,examples:go(X(r),!1,c)};return{description:d,content:{[o]:m}}},Ro=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Dt=e=>e.length<=no?e:e.slice(0,no-1)+"\u2026";var Ft=class extends Bs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;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||W(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new H(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}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:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:f="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});we({routing:t,onEndpoint:(y,T,S)=>{let C={path:T,method:S,endpoint:y,composition:f,brandHandling:c,makeRef:this.makeRef.bind(this)},[j,b]=["short","long"].map(y.getDescription.bind(y)),w=j?Dt(j):m&&b?Dt(b):void 0,I=r.inputSources?.[S]||St[S],N=this.ensureUniqOperationId(T,S,y.getOperationId(S)),v=ro(y.getSecurity()),E=ho({...C,inputSources:I,isHeader:p,security:v,schema:y.getSchema("input"),description:a?.requestParameter?.call(null,{method:S,path:T,operationId:N})}),te={};for(let _ of Re){let re=y.getResponses(_);for(let{mimeTypes:xt,schema:Fe,statusCodes:qe}of re)for(let bt of qe)te[bt]=bo({...C,variant:_,schema:Fe,mimeTypes:xt,statusCode:bt,hasMultipleStatusCodes:re.length>1||qe.length>1,description:a?.[`${_}Response`]?.call(null,{method:S,path:T,operationId:N,statusCode:bt})})}let Z=I.includes("body")?Oo({...C,paramNames:$s("name",E),schema:y.getSchema("input"),mimeType:z[y.getRequestType()],description:a?.requestBody?.call(null,{method:S,path:T,operationId:N})}):void 0,ht=To(So(v,I),y.getScopes(),_=>{let re=this.ensureUniqSecuritySchemaName(_);return this.addSecurityScheme(re,_),re});this.addPath(lo(T),{[S]:{operationId:N,summary:w,description:b,tags:_e(y.getTags()),parameters:_e(E),requestBody:Z,security:_e(ht),responses:te}})}}),d&&(this.rootDoc.tags=Ro(d))}};import{createRequest as Vs,createResponse as _s}from"node-mocks-http";var Gs=e=>Vs({...e,headers:{"content-type":z.json,...e?.headers}}),Ys=e=>_s(e),Js=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Ir(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Po=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Gs(e),s=Ys({req:n,...t});s.req=t?.req||n,n.res=s;let a=Js(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Ws=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Po(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Qs=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Po(o),d=$e(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(Y(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import{chain as Zi}from"ramda";import gt from"typescript";import{z as ki}from"zod";import{map as oi}from"ramda";import $ from"typescript";var Ao=["get","post","put","delete","patch"];import{map as qt,pair as Xs}from"ramda";import l from"typescript";var i=l.factory,ct=[i.createModifier(l.SyntaxKind.ExportKeyword)],ei=[i.createModifier(l.SyntaxKind.AsyncKeyword)],Ke={public:[i.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(l.SyntaxKind.ProtectedKeyword),i.createModifier(l.SyntaxKind.ReadonlyKeyword)]},Bt=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),$t=(e,t)=>{let r=l.createSourceFile("print.ts","",l.ScriptTarget.Latest,!1,l.ScriptKind.TS);return l.createPrinter(t).printNode(l.EmitHint.Unspecified,e,r)},ti=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Vt=e=>typeof e=="string"&&ti.test(e)?i.createIdentifier(e):P(e),dt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),mt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(l.SyntaxKind.QuestionToken):void 0,t?u(t):void 0,o),Ee=e=>Object.entries(e).map(([t,r])=>mt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),_t=(e,t=[])=>i.createConstructorDeclaration(Ke.public,e,i.createBlock(t)),u=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||l.isIdentifier(e)?i.createTypeReferenceNode(e,t&&qt(u,t)):e,Gt=u("Record",[l.SyntaxKind.StringKeyword,l.SyntaxKind.AnyKeyword]),ue=(e,t,{isOptional:r,comment:o}={})=>{let n=i.createPropertySignature(void 0,Vt(e),r?i.createToken(l.SyntaxKind.QuestionToken):void 0,u(t));return o?Bt(n,o):n},Yt=e=>l.setEmitFlags(e,l.EmitFlags.SingleLine),Jt=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),k=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&ct,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?u(r):void 0,t)],l.NodeFlags.Const)),Wt=(e,t)=>B(e,i.createUnionTypeNode(qt(M,t)),{expose:!0}),B=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?ct:void 0,e,n&&tr(n),t);return o?Bt(s,o):s},wo=(e,t)=>i.createPropertyDeclaration(Ke.public,e,void 0,u(t),void 0),Qt=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Ke.public,void 0,e,void 0,o&&tr(o),t,n,i.createBlock(r)),Xt=(e,t,{typeParams:r}={})=>i.createClassDeclaration(ct,e,r&&tr(r),void 0,t),er=e=>i.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,u(e)),lt=e=>u(Promise.name,[e]),ut=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?ct:void 0,e,void 0,void 0,t);return o?Bt(n,o):n},tr=e=>(Array.isArray(e)?e.map(t=>Xs(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?u(o):void 0,n?u(n):void 0)}),ye=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ei:void 0,void 0,Array.isArray(e)?qt(mt,e):Ee(e),void 0,void 0,t),O=e=>e,De=(e,t,r)=>i.createConditionalExpression(e,i.createToken(l.SyntaxKind.QuestionToken),t,i.createToken(l.SyntaxKind.ColonToken),r),R=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||l.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),ze=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),yt=(e,t)=>u("Extract",[e,t]),rr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(l.SyntaxKind.EqualsToken),t)),K=(e,t)=>i.createIndexedAccessTypeNode(u(e),u(t)),Eo=e=>i.createUnionTypeNode([u(e),lt(e)]),or=(e,t)=>i.createFunctionTypeNode(void 0,Ee(e),u(t)),P=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),M=e=>i.createLiteralTypeNode(P(e)),ri=[l.SyntaxKind.AnyKeyword,l.SyntaxKind.BigIntKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.NeverKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.ObjectKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.SymbolKeyword,l.SyntaxKind.UndefinedKeyword,l.SyntaxKind.UnknownKeyword,l.SyntaxKind.VoidKeyword],zo=e=>ri.includes(e.kind);var ft=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=Wt("Method",Ao);someOfType=B("SomeOf",K("T",er("T")),{params:["T"]});requestType=B("Request",er(this.interfaces.input),{expose:!0});someOf=({name:t})=>u(this.someOfType.name,[t]);makePathType=()=>Wt(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>ut(this.interfaces[t],Array.from(this.registry).map(([r,o])=>ue(r,o[t])),{expose:!0}));makeEndpointTags=()=>k("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Vt(t),i.createArrayLiteralExpression(oi(P,r))))),{expose:!0});makeImplementationType=()=>B(this.ids.implementationType,or({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:$.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Gt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},lt($.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:$.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>k(this.ids.parseRequestFn,ye({[this.ids.requestParameter.text]:$.SyntaxKind.StringKeyword},i.createAsExpression(R(this.ids.requestParameter,O("split"))(i.createRegularExpressionLiteral("/ (.+)/"),P(2)),i.createTupleTypeNode([u(this.methodType.name),u(this.ids.pathType)]))));makeSubstituteFn=()=>k(this.ids.substituteFn,ye({[this.ids.pathParameter.text]:$.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Gt},i.createBlock([k(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],$.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([rr(this.ids.pathParameter,R(this.ids.pathParameter,O("replace"))(dt(":",[this.ids.keyParameter]),ye([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),u("const")))])));makeProvider=()=>Qt(this.ids.provideMethod,Ee({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:K(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[k(Jt(this.ids.methodParameter,this.ids.pathParameter),R(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(R(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(R(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:lt(K(this.interfaces.response,"K"))});makeClientClass=t=>Xt(t,[_t([mt(this.ids.implementationArgument,{type:u(this.ids.implementationType,["T"]),mod:Ke.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>dt("?",[ze(URLSearchParams.name,t)]);makeFetchURL=()=>ze(URL.name,dt("",[this.ids.pathParameter],[this.ids.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(O("method"),R(this.ids.methodParameter,O("toUpperCase"))()),r=i.createPropertyAssignment(O("headers"),De(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(P("Content-Type"),P(z.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(O("body"),De(this.ids.hasBodyConst,R(JSON[Symbol.toStringTag],O("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=k(this.ids.responseConst,i.createAwaitExpression(R(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=k(this.ids.hasBodyConst,i.createLogicalNot(R(i.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.ids.methodParameter))),a=k(this.ids.searchParamsConst,De(this.ids.hasBodyConst,P(""),this.makeSearchParams(this.ids.paramsArgument))),c=k(this.ids.contentTypeConst,R(this.ids.responseConst,O("headers"),O("get"))(P("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression($.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=k(this.ids.isJsonConst,R(this.ids.contentTypeConst,O("startsWith"))(P(z.json))),m=i.createReturnStatement(R(this.ids.responseConst,De(this.ids.isJsonConst,P(O("json")),P(O("text"))))());return k(this.ids.defaultImplementationConst,ye([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,m]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>_t(Ee({request:"K",params:K(this.interfaces.input,"K")}),[k(Jt(this.ids.pathParameter,this.ids.restConst),R(this.ids.substituteFn)(i.createElementAccessExpression(R(this.ids.parseRequestFn)(this.ids.requestParameter),P(1)),this.ids.paramsArgument)),k(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),rr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),ze("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([ue(O("event"),t)]);makeOnMethod=()=>Qt(this.ids.onMethod,Ee({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:or({[this.ids.dataParameter.text]:K(yt("R",Yt(this.makeEventNarrow("E"))),M(O("data")))},Eo($.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(R(i.createThis(),this.ids.sourceProp,O("addEventListener"))(this.ids.eventParameter,ye([this.ids.msgParameter],R(this.ids.handlerParameter)(R(JSON[Symbol.toStringTag],O("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,u(MessageEvent.name))),O("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:K("R",M(O("event")))}});makeSubscriptionClass=t=>Xt(t,[wo(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:yt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(u($.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:yt(K(this.interfaces.positive,"K"),Yt(this.makeEventNarrow($.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[k(this.ids.clientConst,ze(t)),R(this.ids.clientConst,this.ids.provideMethod)(P("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",P("10"))])),R(ze(r,P("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(P("time"),ye(["time"],i.createBlock([])))]};import{chain as ni,eqBy as nr,path as sr,prop as si,uniqWith as ii}from"ramda";import h from"typescript";import{z as ar}from"zod";var{factory:U}=h,ai={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},ir={name:sr(["name","text"]),type:sr(["type"]),optional:sr(["questionToken"])},pi=({value:e})=>M(e),ci=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let c=t&&Ze(a)?a instanceof ar.ZodOptional:a.isOptional();return ue(s,r(a),{isOptional:c&&o,comment:a.description})});return U.createTypeLiteralNode(n)},di=({element:e},{next:t})=>U.createArrayTypeNode(t(e)),mi=({options:e})=>U.createUnionTypeNode(e.map(M)),Io=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(zo(n)?n.kind:n,n)}return U.createUnionTypeNode(Array.from(r.values()))},li=e=>ai?.[e.kind],ui=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ve(e,li(o)),s={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return u(n&&s[n]||h.SyntaxKind.AnyKeyword)}return o},yi=e=>U.createUnionTypeNode(Object.values(e.enum).map(M)),fi=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?U.createUnionTypeNode([o,u(h.SyntaxKind.UndefinedKeyword)]):o},gi=(e,{next:t})=>U.createUnionTypeNode([t(e.unwrap()),M(null)]),hi=({items:e,_def:{rest:t}},{next:r})=>U.createTupleTypeNode(e.map(r).concat(t===null?[]:U.createRestTypeNode(r(t)))),xi=({keySchema:e,valueSchema:t},{next:r})=>u("Record",[e,t].map(r)),bi=e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let r=ni(si("members"),e),o=ii((...n)=>{if(!nr(ir.name,...n))return!1;if(nr(ir.type,...n)&&nr(ir.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return U.createTypeLiteralNode(o)},Si=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return bi(o)}catch{}return U.createIntersectionTypeNode(o)},Ti=({_def:e},{next:t})=>t(e.innerType),ee=e=>()=>u(e),Oi=(e,{next:t})=>t(e.unwrap()),Ri=(e,{next:t})=>t(e.unwrap()),Pi=({_def:e},{next:t})=>t(e.innerType),Ai=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),wi=()=>M(null),Ei=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),zi=e=>{let t=e.unwrap(),r=u(h.SyntaxKind.StringKeyword),o=u("Buffer"),n=U.createUnionTypeNode([r,o]);return t instanceof ar.ZodString?r:t instanceof ar.ZodUnion?n:o},Ii=(e,{next:t})=>t(e.unwrap().shape.raw),vi={ZodString:ee(h.SyntaxKind.StringKeyword),ZodNumber:ee(h.SyntaxKind.NumberKeyword),ZodBigInt:ee(h.SyntaxKind.BigIntKeyword),ZodBoolean:ee(h.SyntaxKind.BooleanKeyword),ZodAny:ee(h.SyntaxKind.AnyKeyword),ZodUndefined:ee(h.SyntaxKind.UndefinedKeyword),[ae]:ee(h.SyntaxKind.StringKeyword),[pe]:ee(h.SyntaxKind.StringKeyword),ZodNull:wi,ZodArray:di,ZodTuple:hi,ZodRecord:xi,ZodObject:ci,ZodLiteral:pi,ZodIntersection:Si,ZodUnion:Io,ZodDefault:Ti,ZodEnum:mi,ZodNativeEnum:yi,ZodEffects:ui,ZodOptional:fi,ZodNullable:gi,ZodDiscriminatedUnion:Io,ZodBranded:Oi,ZodCatch:Pi,ZodPipeline:Ai,ZodLazy:Ei,ZodReadonly:Ri,[D]:zi,[Q]:Ii},pr=(e,{brandHandling:t,ctx:r})=>le(e,{rules:{...t,...vi},onMissing:()=>u(h.SyntaxKind.AnyKeyword),ctx:r});var cr=class extends ft{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=M(null);this.aliases.set(t,B(o,n)),this.aliases.set(t,B(o,r()))}return u(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=ki.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},m={brandHandling:r,ctx:{...p,isResponse:!1}},f={brandHandling:r,ctx:{...p,isResponse:!0}};we({routing:t,onEndpoint:(y,T,S)=>{let C=W.bind(null,S,T),j=`${S} ${T}`,b=B(C("input"),pr(y.getSchema("input"),m),{comment:j});this.program.push(b);let w=Re.reduce((N,v)=>{let E=y.getResponses(v),te=Zi(([ht,{schema:_,mimeTypes:re,statusCodes:xt}])=>{let Fe=B(C(v,"variant",`${ht+1}`),pr(re?_:d,f),{comment:j});return this.program.push(Fe),xt.map(qe=>ue(qe,Fe.name))},Array.from(E.entries())),Z=ut(C(v,"response","variants"),te,{comment:j});return this.program.push(Z),Object.assign(N,{[v]:Z})},{});this.paths.add(T);let I=M(j);this.registry.set(j,{input:u(b.name),positive:this.someOf(w.positive),negative:this.someOf(w.negative),response:i.createUnionTypeNode([K(this.interfaces.positive,I),K(this.interfaces.negative,I)]),encoded:i.createIntersectionTypeNode([u(w.positive.name),u(w.negative.name)])}),this.tags.set(j,y.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:$t(r,t)).join(`
|
|
19
|
-
`):void 0}print(t){let r=this.printUsage(t),o=r&&
|
|
20
|
-
${r}`);return this.program.concat(o||[]).map((n,s)
|
|
18
|
+
`))};var to=e=>{e.startupLogo!==!1&&eo(process.stdout);let t=e.errorHandler||De,r=kr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v22.9.0 (ESM)",env:process.env.NODE_ENV||"development"}),Yr(r);let o=Jr({logger:r,config:e}),s={getLogger:Wr(r),errorHandler:t},a=_r(s),c=$r(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Ln=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=to(e);return Ct({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Mn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=to(e),c=jt().disable("x-powered-by").use(a);if(e.compression){let b=await we("compression");c.use(b(typeof e.compression=="object"?e.compression:void 0))}let d={json:[e.jsonParser||jt.json()],raw:[e.rawParser||jt.raw(),Gr],upload:e.upload?await Vr({config:e,getLogger:o}):[]};await e.beforeRouting?.({app:c,getLogger:o}),Ct({app:c,routing:t,getLogger:o,config:e,parsers:d}),c.use(s,n);let p=[],m=(b,f)=>()=>b.listen(f,()=>r.info("Listening",f)),x=[];if(e.http){let b=jn.createServer(c);p.push(b),x.push(m(b,e.http.listen))}if(e.https){let b=Nn.createServer(e.https.options,c);p.push(b),x.push(m(b,e.https.listen))}return e.gracefulShutdown&&Qr({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:x.map(b=>b())}};import{OpenApiBuilder as Gs}from"openapi3-ts/oas31";import{pluck as Js}from"ramda";import{chain as Un,isEmpty as Dn,map as ro,partition as Hn,prop as oo,reject as Kn,filter as Nt,concat as Lt}from"ramda";var no=e=>ie(e)&&"or"in e,so=e=>ie(e)&&"and"in e,Mt=e=>!so(e)&&!no(e),io=e=>{let t=Nt(Mt,e),r=Un(oo("and"),Nt(so,e)),[o,n]=Hn(Mt,r),s=Lt(t,o),a=Nt(no,e);return ro(oo("or"),Lt(a,n)).reduce((d,p)=>se(d,ro(m=>Mt(m)?[m]:m.and,p),([m,x])=>Lt(m,x)),Kn(Dn,[s]))};import{isReferenceObject as Ht,isSchemaObject as pt}from"openapi3-ts/oas31";import{concat as qn,chain as Bn,type as mo,filter as lo,fromPairs as ct,has as $n,isNil as _n,map as qe,mergeDeepRight as Vn,mergeDeepWith as Gn,objOf as Jn,omit as dt,pipe as uo,pluck as Wn,reject as Yn,times as Qn,toLower as Xn,union as es,when as ts,xprod as Ut,zip as rs}from"ramda";import{z as M}from"zod";var ue=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[y]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>ue(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:c,...n});return d?{...c,...d}:c};var ao=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var po=50,fo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",os={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},ns=/^\d{4}-\d{2}-\d{2}$/,ss=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,is=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,yo=e=>e.replace(Rt,t=>`{${t.slice(1)}}`),as=({_def:e},{next:t})=>({...t(e.innerType),default:e[y]?.defaultLabel||e.defaultValue()}),ps=({_def:{innerType:e}},{next:t})=>t(e),cs=()=>({format:"any"}),ds=({},e)=>{if(e.isResponse)throw new D("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},ms=e=>{let t=e.unwrap();return{type:"string",format:t instanceof M.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ls=({options:e},{next:t})=>({oneOf:e.map(t)}),us=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),fs=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return qn(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},ys=e=>{let[t,r]=e.filter(pt).filter(n=>n.type==="object"&&Object.keys(n).every(s=>["type","properties","required","examples"].includes(s)));if(!t||!r)throw new Error("Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Gn(fs,t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=es(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=se(t.examples||[],r.examples||[],([n,s])=>Vn(n,s))),o},gs=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return ys(o)}catch{}return{allOf:o}},hs=(e,{next:t})=>t(e.unwrap()),xs=(e,{next:t})=>t(e.unwrap()),bs=(e,{next:t})=>{let r=t(e.unwrap());return pt(r)&&(r.type=ho(r)),r},go=e=>{let t=Xn(mo(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},co=e=>({type:go(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Ss=({value:e})=>({type:go(e),const:e}),Ts=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t&&je(c)?c instanceof M.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=at(e,r)),s.length&&(a.required=s),a},Os=()=>({type:"null"}),Rs=({},e)=>{if(e.isResponse)throw new D("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:fo}}},Ps=({},e)=>{if(!e.isResponse)throw new D("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:fo}}},As=({},e)=>{throw new D(`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)},ws=()=>({type:"boolean"}),Es=()=>({type:"integer",format:"bigint"}),zs=e=>e.every(t=>t instanceof M.ZodLiteral),Is=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof M.ZodEnum||e instanceof M.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=at(M.object(ct(Ut(o,[t]))),r),n.required=o),n}if(e instanceof M.ZodLiteral)return{type:"object",properties:at(M.object({[e.value]:t}),r),required:[e.value]};if(e instanceof M.ZodUnion&&zs(e.options)){let o=qe(s=>`${s.value}`,e.options),n=ct(Ut(o,[t]));return{type:"object",properties:at(M.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Zs=({_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},vs=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),ks=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:d,isEmoji:p,isDatetime:m,isCIDR:x,isDate:b,isTime:f,isBase64:P,isNANOID:R,isBase64url:v,isDuration:V,_def:{checks:g}})=>{let z=g.find(k=>k.kind==="regex"),A=g.find(k=>k.kind==="datetime"),I=g.some(k=>k.kind==="jwt"),N=g.find(k=>k.kind==="length"),w={type:"string"},L={"date-time":m,byte:P,base64url:v,date:b,time:f,duration:V,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:R,jwt:I,ip:d,cidr:x,emoji:p};for(let k in L)if(L[k]){w.format=k;break}return N&&([w.minLength,w.maxLength]=[N.value,N.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),b&&(w.pattern=ns.source),f&&(w.pattern=ss.source),m&&(w.pattern=is(A?.offset).source),z&&(w.pattern=z.regex.source),w},Cs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(x=>x.kind==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,c=o.find(x=>x.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,p=c?c.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,p?m.maximum=d:m.exclusiveMaximum=d,m},at=({shape:e},t)=>qe(t,e),js=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return os?.[t]},ho=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Ns=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&pt(o)){let s=We(e,js(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(M.any())}if(!t&&n.type==="preprocess"&&pt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Ls=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Ms=(e,{next:t})=>t(e.unwrap()),Us=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ds=(e,{next:t})=>t(e.unwrap().shape.raw),xo=e=>e.length?ct(rs(Qn(t=>`example${t+1}`,e.length),qe(Jn("value"),e))):void 0,bo=(e,t,r=[])=>uo(Q,qe(ts(o=>mo(o)==="Object",dt(r))),xo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),Hs=(e,t)=>uo(Q,lo($n(t)),Wn(t),xo)({schema:e,variant:"original",validate:!0,pullProps:!0}),Ks=(e,t)=>t?.includes(e)||e.startsWith("x-")||ao.includes(e),So=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:d,description:p=`${t.toUpperCase()} ${e} Parameter`})=>{let m=H(r),x=Ge(e),b=o.includes("query"),f=o.includes("params"),P=o.includes("headers"),R=g=>f&&x.includes(g),v=Bn(lo(g=>g.type==="header"),d??[]).map(({name:g})=>g),V=g=>P&&(c?.(g,t,e)??Ks(g,v));return Object.entries(m.shape).reduce((g,[z,A])=>{let I=R(z)?"path":V(z)?"header":b?"query":void 0;if(!I)return g;let N=ue(A,{rules:{...a,...Kt},onEach:Ft,onMissing:qt,ctx:{isResponse:!1,makeRef:n,path:e,method:t}}),w=s==="components"?n(A,N,X(p,z)):N,{_def:L}=A;return g.concat({name:z,in:I,deprecated:L[y]?.isDeprecated,required:!A.isOptional(),description:N.description||p,schema:w,examples:Hs(m,z)})},[])},Kt={ZodString:ks,ZodNumber:Cs,ZodBigInt:Es,ZodBoolean:ws,ZodNull:Os,ZodArray:Zs,ZodTuple:vs,ZodRecord:Is,ZodObject:Ts,ZodLiteral:Ss,ZodIntersection:gs,ZodUnion:ls,ZodAny:cs,ZodDefault:as,ZodEnum:co,ZodNativeEnum:co,ZodEffects:Ns,ZodOptional:hs,ZodNullable:bs,ZodDiscriminatedUnion:us,ZodBranded:Ms,ZodDate:As,ZodCatch:ps,ZodPipeline:Ls,ZodLazy:Us,ZodReadonly:xs,[F]:ms,[be]:ds,[pe]:Ps,[ae]:Rs,[ee]:Ds},Ft=(e,{isResponse:t,prev:r})=>{if(Ht(r))return{};let{description:o,_def:n}=e,s=e instanceof M.ZodLazy,a=r.type!==void 0,c=t&&je(e),d=!s&&a&&!c&&e.isNullable(),p={};if(o&&(p.description=o),n[y]?.isDeprecated&&(p.deprecated=!0),d&&(p.type=ho(r)),!s){let m=Q({schema:e,variant:t?"parsed":"original",validate:!0});m.length&&(p.examples=m.slice())}return p},qt=(e,t)=>{throw new D(`Zod type ${e.constructor.name} is unsupported.`,t)},Dt=(e,t)=>{if(Ht(e))return e;let r={...e};return r.properties&&(r.properties=dt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>dt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Dt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Dt(o,t))),r},To=e=>Ht(e)?e:dt(["examples"],e),Oo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:d,brandHandling:p,description:m=`${e.toUpperCase()} ${t} ${wt(n)} response ${c?d:""}`.trim()})=>{if(!o)return{description:m};let x=To(ue(r,{rules:{...p,...Kt},onEach:Ft,onMissing:qt,ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b={schema:a==="components"?s(r,x,X(m)):x,examples:bo(r,!0)};return{description:m,content:ct(Ut(o,[b]))}},Fs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},qs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Bs=({name:e})=>({type:"apiKey",in:"header",name:e}),$s=({name:e})=>({type:"apiKey",in:"cookie",name:e}),_s=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Vs=({flows:e={}})=>({type:"oauth2",flows:qe(t=>({...t,scopes:t.scopes||{}}),Yn(_n,e))}),Ro=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Fs(o):o.type==="input"?qs(o,t):o.type==="header"?Bs(o):o.type==="cookie"?$s(o):o.type==="openid"?_s(o):Vs(o);return e.map(o=>o.map(r))},Po=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),Ao=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let p=To(Dt(ue(r,{rules:{...a,...Kt},onEach:Ft,onMissing:qt,ctx:{isResponse:!1,makeRef:n,path:t,method:e}}),c)),m={schema:s==="components"?n(r,p,X(d)):p,examples:bo(H(r),!1,c)};return{description:d,content:{[o]:m}}},wo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Bt=e=>e.length<=po?e:e.slice(0,po-1)+"\u2026",mt=e=>e.length?e.slice():void 0;var $t=class extends Gs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;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||X(r,t),s=this.lastOperationIdSuffixes.get(n);if(s===void 0)return this.lastOperationIdSuffixes.set(n,1),n;if(o)throw new D(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.lastOperationIdSuffixes.set(n,s),`${n}${s}`}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:s,descriptions:a,brandHandling:c,tags:d,isHeader:p,hasSummaryFromDescription:m=!0,composition:x="inline"}){super(),this.addInfo({title:o,version:n});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});Ee({routing:t,onEndpoint:(f,P,R)=>{let v={path:P,method:R,endpoint:f,composition:x,brandHandling:c,makeRef:this.makeRef.bind(this)},[V,g]=["short","long"].map(f.getDescription.bind(f)),z=V?Bt(V):m&&g?Bt(g):void 0,A=r.inputSources?.[R]||Pt[R],I=this.ensureUniqOperationId(P,R,f.getOperationId(R)),N=io(f.getSecurity()),w=So({...v,inputSources:A,isHeader:p,security:N,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:R,path:P,operationId:I})}),L={};for(let J of Pe){let re=f.getResponses(J);for(let{mimeTypes:Tt,schema:Ot,statusCodes:ve}of re)for(let ke of ve)L[ke]=Oo({...v,variant:J,schema:Ot,mimeTypes:Tt,statusCode:ke,hasMultipleStatusCodes:re.length>1||ve.length>1,description:a?.[`${J}Response`]?.call(null,{method:R,path:P,operationId:I,statusCode:ke})})}let k=A.includes("body")?Ao({...v,paramNames:Js("name",w),schema:f.getSchema("input"),mimeType:E[f.getRequestType()],description:a?.requestBody?.call(null,{method:R,path:P,operationId:I})}):void 0,St=Po(Ro(N,A),f.getScopes(),J=>{let re=this.ensureUniqSecuritySchemaName(J);return this.addSecurityScheme(re,J),re}),_e={operationId:I,summary:z,description:g,deprecated:f.isDeprecated||void 0,tags:mt(f.getTags()),parameters:mt(w),requestBody:k,security:mt(St),responses:L};this.addPath(yo(P),{[R]:_e})}}),d&&(this.rootDoc.tags=wo(d))}};import{createRequest as Ws,createResponse as Ys}from"node-mocks-http";var Qs=e=>Ws({...e,headers:{"content-type":E.json,...e?.headers}}),Xs=e=>Ys(e),ei=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Cr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Eo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Qs(e),s=Xs({req:n,...t});s.req=t?.req||n,n.res=s;let a=ei(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},ti=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Eo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},ri=async({middleware:e,options:t={},errorHandler:r,...o})=>{let{requestMock:n,responseMock:s,loggerMock:a,configMock:c}=Eo(o),d=Je(n,c.inputSources);try{let p=await e.execute({request:n,response:s,logger:a,input:d,options:t});return{requestMock:n,responseMock:s,loggerMock:a,output:p}}catch(p){if(!r)throw p;return r(Y(p),s),{requestMock:n,responseMock:s,loggerMock:a,output:{}}}};import{chain as Mi}from"ramda";import bt from"typescript";import{z as Ui}from"zod";import{map as ci}from"ramda";import _ from"typescript";var zo=["get","post","put","delete","patch"];import{isNil as oi,map as _t,pair as ni,reject as si}from"ramda";import l from"typescript";var i=l.factory,lt=[i.createModifier(l.SyntaxKind.ExportKeyword)],ii=[i.createModifier(l.SyntaxKind.AsyncKeyword)],Be={public:[i.createModifier(l.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(l.SyntaxKind.ProtectedKeyword),i.createModifier(l.SyntaxKind.ReadonlyKeyword)]},Vt=(e,t)=>l.addSyntheticLeadingComment(e,l.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Gt=(e,t)=>{let r=l.createSourceFile("print.ts","",l.ScriptTarget.Latest,!1,l.ScriptKind.TS);return l.createPrinter(t).printNode(l.EmitHint.Unspecified,e,r)},ai=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Jt=e=>typeof e=="string"&&ai.test(e)?i.createIdentifier(e):O(e),ut=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),ft=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(l.SyntaxKind.QuestionToken):void 0,t?u(t):void 0,o),ze=e=>Object.entries(e).map(([t,r])=>ft(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Wt=(e,t=[])=>i.createConstructorDeclaration(Be.public,e,i.createBlock(t)),u=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||l.isIdentifier(e)?i.createTypeReferenceNode(e,t&&_t(u,t)):e,Yt=u("Record",[l.SyntaxKind.StringKeyword,l.SyntaxKind.AnyKeyword]),fe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,Jt(e),r?i.createToken(l.SyntaxKind.QuestionToken):void 0,u(t)),a=si(oi,[o?"@deprecated":void 0,n]);return a.length?Vt(s,a.join(" ")):s},Qt=e=>l.setEmitFlags(e,l.EmitFlags.SingleLine),Xt=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),Z=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&<,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?u(r):void 0,t)],l.NodeFlags.Const)),er=(e,t)=>$(e,i.createUnionTypeNode(_t(j,t)),{expose:!0}),$=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?lt:void 0,e,n&&nr(n),t);return o?Vt(s,o):s},Io=(e,t)=>i.createPropertyDeclaration(Be.public,e,void 0,u(t),void 0),tr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Be.public,void 0,e,void 0,o&&nr(o),t,n,i.createBlock(r)),rr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(lt,e,r&&nr(r),void 0,t),or=e=>i.createTypeOperatorNode(l.SyntaxKind.KeyOfKeyword,u(e)),yt=e=>u(Promise.name,[e]),gt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?lt:void 0,e,void 0,void 0,t);return o?Vt(n,o):n},nr=e=>(Array.isArray(e)?e.map(t=>ni(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?u(o):void 0,n?u(n):void 0)}),ye=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?ii:void 0,void 0,Array.isArray(e)?_t(ft,e):ze(e),void 0,void 0,t),S=e=>e,$e=(e,t,r)=>i.createConditionalExpression(e,i.createToken(l.SyntaxKind.QuestionToken),t,i.createToken(l.SyntaxKind.ColonToken),r),T=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||l.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ie=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),ht=(e,t)=>u("Extract",[e,t]),sr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(l.SyntaxKind.EqualsToken),t)),K=(e,t)=>i.createIndexedAccessTypeNode(u(e),u(t)),Zo=e=>i.createUnionTypeNode([u(e),yt(e)]),ir=(e,t)=>i.createFunctionTypeNode(void 0,ze(e),u(t)),O=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),j=e=>i.createLiteralTypeNode(O(e)),pi=[l.SyntaxKind.AnyKeyword,l.SyntaxKind.BigIntKeyword,l.SyntaxKind.BooleanKeyword,l.SyntaxKind.NeverKeyword,l.SyntaxKind.NumberKeyword,l.SyntaxKind.ObjectKeyword,l.SyntaxKind.StringKeyword,l.SyntaxKind.SymbolKeyword,l.SyntaxKind.UndefinedKeyword,l.SyntaxKind.UnknownKeyword,l.SyntaxKind.VoidKeyword],vo=e=>pi.includes(e.kind);var xt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;ids={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=er("Method",zo);someOfType=$("SomeOf",K("T",or("T")),{params:["T"]});requestType=$("Request",or(this.interfaces.input),{expose:!0});someOf=({name:t})=>u(this.someOfType.name,[t]);makePathType=()=>er(this.ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>gt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>fe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>Z("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(Jt(t),i.createArrayLiteralExpression(ci(O,r))))),{expose:!0});makeImplementationType=()=>$(this.ids.implementationType,ir({[this.ids.methodParameter.text]:this.methodType.name,[this.ids.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Yt,[this.ids.ctxArgument.text]:{optional:!0,type:"T"}},yt(_.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:_.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>Z(this.ids.parseRequestFn,ye({[this.ids.requestParameter.text]:_.SyntaxKind.StringKeyword},i.createAsExpression(T(this.ids.requestParameter,S("split"))(i.createRegularExpressionLiteral("/ (.+)/"),O(2)),i.createTupleTypeNode([u(this.methodType.name),u(this.ids.pathType)]))));makeSubstituteFn=()=>Z(this.ids.substituteFn,ye({[this.ids.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.ids.paramsArgument.text]:Yt},i.createBlock([Z(this.ids.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.ids.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.ids.keyParameter)],_.NodeFlags.Const),this.ids.paramsArgument,i.createBlock([sr(this.ids.pathParameter,T(this.ids.pathParameter,S("replace"))(ut(":",[this.ids.keyParameter]),ye([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.ids.restConst,this.ids.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.ids.pathParameter,this.ids.restConst]),u("const")))])));makeProvider=()=>tr(this.ids.provideMethod,ze({[this.ids.requestParameter.text]:"K",[this.ids.paramsArgument.text]:K(this.interfaces.input,"K"),[this.ids.ctxArgument.text]:{optional:!0,type:"T"}}),[Z(Xt(this.ids.methodParameter,this.ids.pathParameter),T(this.ids.parseRequestFn)(this.ids.requestParameter)),i.createReturnStatement(T(i.createThis(),this.ids.implementationArgument)(this.ids.methodParameter,i.createSpreadElement(T(this.ids.substituteFn)(this.ids.pathParameter,this.ids.paramsArgument)),this.ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:yt(K(this.interfaces.response,"K"))});makeClientClass=t=>rr(t,[Wt([ft(this.ids.implementationArgument,{type:u(this.ids.implementationType,["T"]),mod:Be.protectedReadonly,init:this.ids.defaultImplementationConst})]),this.makeProvider()],{typeParams:["T"]});makeSearchParams=t=>ut("?",[Ie(URLSearchParams.name,t)]);makeFetchURL=()=>Ie(URL.name,ut("",[this.ids.pathParameter],[this.ids.searchParamsConst]),O(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(S("method"),T(this.ids.methodParameter,S("toUpperCase"))()),r=i.createPropertyAssignment(S("headers"),$e(this.ids.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(O("Content-Type"),O(E.json))]),this.ids.undefinedValue)),o=i.createPropertyAssignment(S("body"),$e(this.ids.hasBodyConst,T(JSON[Symbol.toStringTag],S("stringify"))(this.ids.paramsArgument),this.ids.undefinedValue)),n=Z(this.ids.responseConst,i.createAwaitExpression(T(fetch.name)(this.makeFetchURL(),i.createObjectLiteralExpression([t,r,o])))),s=Z(this.ids.hasBodyConst,i.createLogicalNot(T(i.createArrayLiteralExpression([O("get"),O("delete")]),S("includes"))(this.ids.methodParameter))),a=Z(this.ids.searchParamsConst,$e(this.ids.hasBodyConst,O(""),this.makeSearchParams(this.ids.paramsArgument))),c=Z(this.ids.contentTypeConst,T(this.ids.responseConst,S("headers"),S("get"))(O("content-type"))),d=i.createIfStatement(i.createPrefixUnaryExpression(_.SyntaxKind.ExclamationToken,this.ids.contentTypeConst),i.createReturnStatement()),p=Z(this.ids.isJsonConst,T(this.ids.contentTypeConst,S("startsWith"))(O(E.json))),m=i.createReturnStatement(T(this.ids.responseConst,$e(this.ids.isJsonConst,O(S("json")),O(S("text"))))());return Z(this.ids.defaultImplementationConst,ye([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],i.createBlock([s,a,n,c,d,p,m]),{isAsync:!0}),{type:this.ids.implementationType})};makeSubscriptionConstructor=()=>Wt(ze({request:"K",params:K(this.interfaces.input,"K")}),[Z(Xt(this.ids.pathParameter,this.ids.restConst),T(this.ids.substituteFn)(i.createElementAccessExpression(T(this.ids.parseRequestFn)(this.ids.requestParameter),O(1)),this.ids.paramsArgument)),Z(this.ids.searchParamsConst,this.makeSearchParams(this.ids.restConst)),sr(i.createPropertyAccessExpression(i.createThis(),this.ids.sourceProp),Ie("EventSource",this.makeFetchURL()))]);makeEventNarrow=t=>i.createTypeLiteralNode([fe(S("event"),t)]);makeOnMethod=()=>tr(this.ids.onMethod,ze({[this.ids.eventParameter.text]:"E",[this.ids.handlerParameter.text]:ir({[this.ids.dataParameter.text]:K(ht("R",Qt(this.makeEventNarrow("E"))),j(S("data")))},Zo(_.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(T(i.createThis(),this.ids.sourceProp,S("addEventListener"))(this.ids.eventParameter,ye([this.ids.msgParameter],T(this.ids.handlerParameter)(T(JSON[Symbol.toStringTag],S("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.ids.msgParameter,u(MessageEvent.name))),S("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:K("R",j(S("event")))}});makeSubscriptionClass=t=>rr(t,[Io(this.ids.sourceProp,"EventSource"),this.makeSubscriptionConstructor(),this.makeOnMethod()],{typeParams:{K:ht(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(u(_.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:ht(K(this.interfaces.positive,"K"),Qt(this.makeEventNarrow(_.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[Z(this.ids.clientConst,Ie(t)),T(this.ids.clientConst,this.ids.provideMethod)(O("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",O("10"))])),T(Ie(r,O("get /v1/events/stream"),i.createObjectLiteralExpression()),this.ids.onMethod)(O("time"),ye(["time"],i.createBlock([])))]};import{chain as di,eqBy as ar,path as pr,prop as mi,uniqWith as li}from"ramda";import h from"typescript";import{z as dr}from"zod";var{factory:U}=h,ui={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},cr={name:pr(["name","text"]),type:pr(["type"]),optional:pr(["questionToken"])},fi=({value:e})=>j(e),yi=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:d}=a,p=t&&je(a)?a instanceof dr.ZodOptional:a.isOptional();return fe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:d[y]?.isDeprecated})});return U.createTypeLiteralNode(n)},gi=({element:e},{next:t})=>U.createArrayTypeNode(t(e)),hi=({options:e})=>U.createUnionTypeNode(e.map(j)),ko=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(vo(n)?n.kind:n,n)}return U.createUnionTypeNode(Array.from(r.values()))},xi=e=>ui?.[e.kind],bi=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=We(e,xi(o)),s={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return u(n&&s[n]||h.SyntaxKind.AnyKeyword)}return o},Si=e=>U.createUnionTypeNode(Object.values(e.enum).map(j)),Ti=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?U.createUnionTypeNode([o,u(h.SyntaxKind.UndefinedKeyword)]):o},Oi=(e,{next:t})=>U.createUnionTypeNode([t(e.unwrap()),j(null)]),Ri=({items:e,_def:{rest:t}},{next:r})=>U.createTupleTypeNode(e.map(r).concat(t===null?[]:U.createRestTypeNode(r(t)))),Pi=({keySchema:e,valueSchema:t},{next:r})=>u("Record",[e,t].map(r)),Ai=e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let r=di(mi("members"),e),o=li((...n)=>{if(!ar(cr.name,...n))return!1;if(ar(cr.type,...n)&&ar(cr.optional,...n))return!0;throw new Error("Has conflicting prop")},r);return U.createTypeLiteralNode(o)},wi=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Ai(o)}catch{}return U.createIntersectionTypeNode(o)},Ei=({_def:e},{next:t})=>t(e.innerType),te=e=>()=>u(e),zi=(e,{next:t})=>t(e.unwrap()),Ii=(e,{next:t})=>t(e.unwrap()),Zi=({_def:e},{next:t})=>t(e.innerType),vi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ki=()=>j(null),Ci=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),ji=e=>{let t=e.unwrap(),r=u(h.SyntaxKind.StringKeyword),o=u("Buffer"),n=U.createUnionTypeNode([r,o]);return t instanceof dr.ZodString?r:t instanceof dr.ZodUnion?n:o},Ni=(e,{next:t})=>t(e.unwrap().shape.raw),Li={ZodString:te(h.SyntaxKind.StringKeyword),ZodNumber:te(h.SyntaxKind.NumberKeyword),ZodBigInt:te(h.SyntaxKind.BigIntKeyword),ZodBoolean:te(h.SyntaxKind.BooleanKeyword),ZodAny:te(h.SyntaxKind.AnyKeyword),ZodUndefined:te(h.SyntaxKind.UndefinedKeyword),[ae]:te(h.SyntaxKind.StringKeyword),[pe]:te(h.SyntaxKind.StringKeyword),ZodNull:ki,ZodArray:gi,ZodTuple:Ri,ZodRecord:Pi,ZodObject:yi,ZodLiteral:fi,ZodIntersection:wi,ZodUnion:ko,ZodDefault:Ei,ZodEnum:hi,ZodNativeEnum:Si,ZodEffects:bi,ZodOptional:Ti,ZodNullable:Oi,ZodDiscriminatedUnion:ko,ZodBranded:zi,ZodCatch:Zi,ZodPipeline:vi,ZodLazy:Ci,ZodReadonly:Ii,[F]:ji,[ee]:Ni},mr=(e,{brandHandling:t,ctx:r})=>ue(e,{rules:{...t,...Li},onMissing:()=>u(h.SyntaxKind.AnyKeyword),ctx:r});var lr=class extends xt{program=[this.someOfType];usage=[];aliases=new Map;makeAlias(t,r){let o=this.aliases.get(t)?.name?.text;if(!o){o=`Type${this.aliases.size+1}`;let n=j(null);this.aliases.set(t,$(o,n)),this.aliases.set(t,$(o,r()))}return u(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:d=Ui.undefined()}){super(a);let p={makeAlias:this.makeAlias.bind(this),optionalPropStyle:c},m={brandHandling:r,ctx:{...p,isResponse:!1}},x={brandHandling:r,ctx:{...p,isResponse:!0}};Ee({routing:t,onEndpoint:(f,P,R)=>{let v=X.bind(null,R,P),{isDeprecated:V}=f,g=`${R} ${P}`,z=$(v("input"),mr(f.getSchema("input"),m),{comment:g});this.program.push(z);let A=Pe.reduce((w,L)=>{let k=f.getResponses(L),St=Mi(([J,{schema:re,mimeTypes:Tt,statusCodes:Ot}])=>{let ve=$(v(L,"variant",`${J+1}`),mr(Tt?re:d,x),{comment:g});return this.program.push(ve),Ot.map(ke=>fe(ke,ve.name))},Array.from(k.entries())),_e=gt(v(L,"response","variants"),St,{comment:g});return this.program.push(_e),Object.assign(w,{[L]:_e})},{});this.paths.add(P);let I=j(g),N={input:u(z.name),positive:this.someOf(A.positive),negative:this.someOf(A.negative),response:i.createUnionTypeNode([K(this.interfaces.positive,I),K(this.interfaces.negative,I)]),encoded:i.createIntersectionTypeNode([u(A.positive.name),u(A.negative.name)])};this.registry.set(g,{isDeprecated:V,store:N}),this.tags.set(g,f.getTags())}}),this.program.unshift(...this.aliases.values()),this.program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.usage.push(...this.makeUsageStatements(n,s)))}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Gt(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.printUsage(t),o=r&&bt.addSyntheticLeadingComment(bt.addSyntheticLeadingComment(i.createEmptyStatement(),bt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),bt.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.program.concat(o||[]).map((n,s)=>Gt(n,s<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
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await we("prettier")).format;o=c=>a(c,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let s=this.print(t);return o?o(s):s}};import{z as Ze}from"zod";var jo=(e,t)=>Ze.object({data:t,event:Ze.literal(e),id:Ze.string().optional(),retry:Ze.number().int().positive().optional()}),Di=(e,t,r)=>jo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Hi=1e4,Co=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Ki=e=>new q({handler:async({response:t})=>setTimeout(()=>Co(t),Hi)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Co(t),t.write(Di(e,r,o),"utf-8"),t.flush?.()}}}),Fi=e=>new me({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>jo(o,n));return{mimeType:E.sse,schema:r.length?Ze.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ze.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let a=Se(r);Me(a,o,n,s),t.headersSent||t.status(a.statusCode).type("text/plain").write(ce(a),"utf-8")}t.end()}}),ur=class extends le{constructor(t){super(Fi(t)),this.middlewares=[Ki(t)]}};var qi={dateIn:xr,dateOut:br,file:Xe,upload:Or,raw:Tr};export{He as BuiltinLogger,Ke as DependsOnMethod,$t as Documentation,D as DocumentationError,le as EndpointsFactory,ur as EventStreamFactory,G as InputValidationError,lr as Integration,q as Middleware,Ce as MissingPeerError,oe as OutputValidationError,me as ResultHandler,ge as RoutingError,Fe as ServeStatic,mn as arrayEndpointsFactory,vt as arrayResultHandler,Ln as attachRouting,Xo as createConfig,Mn as createServer,dn as defaultEndpointsFactory,De as defaultResultHandler,Se as ensureHttpError,qi as ez,Q as getExamples,ne as getMessageFromError,ti as testEndpoint,ri as testMiddleware};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "22.
|
|
3
|
+
"version": "22.9.0",
|
|
4
4
|
"description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"node": "^20.9.0 || ^22.0.0"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"ansis": "^3.
|
|
64
|
+
"ansis": "^3.11.0",
|
|
65
65
|
"node-mocks-http": "^1.16.2",
|
|
66
66
|
"openapi3-ts": "^4.4.0",
|
|
67
67
|
"ramda": "^0.30.1"
|