express-zod-api 25.1.0 → 25.2.0-beta.2
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 +6 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +2 -7
- package/dist/index.d.ts +5 -46
- package/dist/index.js +7 -7
- package/package.json +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
## Version 25
|
|
4
4
|
|
|
5
|
+
### v25.2.0
|
|
6
|
+
|
|
7
|
+
- Zod Plugin extracted into a standalone package — `@express-zod-api/zod-plugin`:
|
|
8
|
+
- The framework declares the plugin as a runtime dependency, you don't need to install it;
|
|
9
|
+
- The plugin will continue to evolve independently and could now be used for developing other zod-based software.
|
|
10
|
+
|
|
5
11
|
### v25.1.0
|
|
6
12
|
|
|
7
13
|
- Ability to disable the depiction of the `HEAD` method:
|
package/CONTRIBUTING.md
CHANGED
|
@@ -23,8 +23,8 @@ Which is highly appreciated as well. Consider these steps:
|
|
|
23
23
|
- Install the dependencies using `pnpm i`,
|
|
24
24
|
- Install the pre-commit hooks using `pnpm install_hooks`,
|
|
25
25
|
- Make changes,
|
|
26
|
+
- Run `pnpm build` (needed for some tests),
|
|
26
27
|
- Run the tests using `pnpm test`,
|
|
27
|
-
- In case you wanna run tests from `example` and `*-test` workspaces, run `pnpm build` first.
|
|
28
28
|
- Commit everything,
|
|
29
29
|
- Push your branch into your fork,
|
|
30
30
|
- Create a PR between the forks:
|
package/README.md
CHANGED
|
@@ -1058,13 +1058,8 @@ expect(output).toEqual({ collectedOptions: ["prev"], testLength: 9 });
|
|
|
1058
1058
|
|
|
1059
1059
|
## Zod Plugin
|
|
1060
1060
|
|
|
1061
|
-
Express Zod API
|
|
1062
|
-
|
|
1063
|
-
- Adds `.example()` method to all Zod schemas for storing examples and reflecting them in the generated documentation;
|
|
1064
|
-
- Adds `.deprecated()` method to all schemas for marking properties and request parameters as deprecated;
|
|
1065
|
-
- Adds `.label()` method to `ZodDefault` for replacing the default value in documentation with a label;
|
|
1066
|
-
- Adds `.remap()` method to `ZodObject` for renaming object properties in a suitable way for making documentation;
|
|
1067
|
-
- Alters the `.brand()` method on all Zod schemas by making the assigned brand available in runtime.
|
|
1061
|
+
Express Zod API augments Zod using [Zod Plugin](https://www.npmjs.com/package/@express-zod-api/zod-plugin),
|
|
1062
|
+
adding the runtime helpers the framework relies on.
|
|
1068
1063
|
|
|
1069
1064
|
## Generating a Frontend Client
|
|
1070
1065
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { z } from 'zod';
|
|
1
|
+
import '@express-zod-api/zod-plugin';
|
|
3
2
|
import compression from 'compression';
|
|
4
3
|
import * as express from 'express';
|
|
5
4
|
import express__default, { Request, Response, NextFunction, RequestHandler, IRouter } from 'express';
|
|
6
5
|
import * as express_fileupload from 'express-fileupload';
|
|
7
6
|
import express_fileupload__default from 'express-fileupload';
|
|
8
7
|
import https, { ServerOptions } from 'node:https';
|
|
8
|
+
import * as zod from 'zod';
|
|
9
|
+
import { z } from 'zod';
|
|
9
10
|
import { HttpError } from 'http-errors';
|
|
10
11
|
import { ListenOptions } from 'node:net';
|
|
11
12
|
import * as qs from 'qs';
|
|
@@ -17,50 +18,8 @@ import { RequestOptions, ResponseOptions } from 'node-mocks-http';
|
|
|
17
18
|
import ts from 'typescript';
|
|
18
19
|
import * as zod_v4_core from 'zod/v4/core';
|
|
19
20
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
* @link https://stackoverflow.com/questions/55454125/typescript-remapping-object-properties-in-typesafe
|
|
23
|
-
*/
|
|
24
|
-
type TuplesFromObject<T> = {
|
|
25
|
-
[P in keyof T]: [P, T[P]];
|
|
26
|
-
}[keyof T];
|
|
27
|
-
type GetKeyByValue<T, V> = TuplesFromObject<T> extends infer TT ? TT extends [infer P, V] ? P : never : never;
|
|
28
|
-
type Remap<T, U extends {
|
|
29
|
-
[P in keyof T]?: V;
|
|
30
|
-
}, V extends string> = {
|
|
31
|
-
[P in NonNullable<U[keyof U]>]: T[GetKeyByValue<U, P>];
|
|
32
|
-
};
|
|
33
|
-
type Intact<T, U> = {
|
|
34
|
-
[K in Exclude<keyof T, keyof U>]: T[K];
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
declare module "zod/v4/core" {
|
|
38
|
-
interface GlobalMeta {
|
|
39
|
-
default?: unknown;
|
|
40
|
-
examples?: unknown[];
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
declare module "zod" {
|
|
44
|
-
interface ZodType<out Output = unknown, out Input = unknown, out Internals extends z.core.$ZodTypeInternals<Output, Input> = z.core.$ZodTypeInternals<Output, Input>> extends z.core.$ZodType<Output, Input, Internals> {
|
|
45
|
-
/** @desc Alias for .meta({examples}), but argument is typed to ensure the correct placement for transformations */
|
|
46
|
-
example(example: z.output<this>): this;
|
|
47
|
-
deprecated(): this;
|
|
48
|
-
}
|
|
49
|
-
interface ZodDefault<T extends z.core.SomeType = z.core.$ZodType> extends z._ZodType<z.core.$ZodDefaultInternals<T>>, z.core.$ZodDefault<T> {
|
|
50
|
-
/** @desc Change the default value in the generated Documentation to a label, alias for .meta({ default }) */
|
|
51
|
-
label(label: string): this;
|
|
52
|
-
}
|
|
53
|
-
interface ZodObject<out Shape extends z.core.$ZodShape = z.core.$ZodLooseShape, out Config extends z.core.$ZodObjectConfig = z.core.$strip> extends z._ZodType<z.core.$ZodObjectInternals<Shape, Config>>, z.core.$ZodObject<Shape, Config> {
|
|
54
|
-
remap<V extends string, U extends {
|
|
55
|
-
[P in keyof Shape]?: V;
|
|
56
|
-
}>(mapping: U): z.ZodPipe<z.ZodPipe<this, z.ZodTransform>, // internal type simplified
|
|
57
|
-
z.ZodObject<Remap<Shape, U, V> & Intact<Shape, U>, Config>>;
|
|
58
|
-
remap<U extends z.core.$ZodShape>(mapper: (subject: Shape) => U): z.ZodPipe<z.ZodPipe<this, z.ZodTransform>, z.ZodObject<U>>;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
declare const methods: ("delete" | "get" | "post" | "put" | "patch")[];
|
|
63
|
-
declare const clientMethods: ("delete" | "get" | "post" | "put" | "patch" | "head")[];
|
|
21
|
+
declare const methods: ("get" | "post" | "put" | "delete" | "patch")[];
|
|
22
|
+
declare const clientMethods: ("get" | "post" | "put" | "delete" | "patch" | "head")[];
|
|
64
23
|
/**
|
|
65
24
|
* @desc Methods supported by the framework API to produce Endpoints on EndpointsFactory.
|
|
66
25
|
* @see BuildProps
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:dn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as mn}from"zod";var Ft=class{},D=class extends Ft{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await(this.#e||qe).parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof mn.ZodError?new Q(o):o}}},Ie=class extends D{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var ve=class{nest(t){return Object.assign(t,{"":this})}};var Je=class extends ve{},yt=class e extends Je{#e;#t=ae.once(()=>{if(jr.get(this.#e.outputSchema)?.examples?.length||!re(this.#e.outputSchema,"object"))return;let t=Nr(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();jr.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=vr(this.#e.inputSchema);if(t){let r=G(t);if(r===se)return"upload";if(r===H)return"raw";if(r===Ue)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ae.pluck("security",this.#e.middlewares||[]);return ae.reject(ae.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Mr.ZodError?new Ze(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Ie))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Mr.ZodError?new Q(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){ft({...t,error:new ne(te(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Lt(t),i={},p={output:{},error:null},d=ct(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:te(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Lr=(e,t)=>e&&t?e.and(t):e||t,Br=(e,t)=>e?e.and(t):t;import{globalRegistry as Ve,z as K}from"zod";var Ae={positive:200,negative:400},ze=Object.keys(Ae);var $t=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Se=class extends $t{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return qt(this.#e,{variant:"positive",args:[t],statusCodes:[Ae.positive],mimeTypes:[E.json]})}getNegativeResponse(){return qt(this.#t,{variant:"negative",args:[],statusCodes:[Ae.negative],mimeTypes:[E.json]})}},be=new Se({positive:e=>{let t=K.object({status:K.literal("success"),data:e}),{examples:r}=Ve.get(e)||{};return r?.length&&Ve.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:K.object({status:K.literal("error"),error:K.object({message:K.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=ke(e);return _e(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:xe(i)}})}n.status(Ae.positive).json({status:"success",data:r})}}),Zt=new Se({positive:e=>{let t=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());if(Ve.get(t)?.examples?.length)return t;let r=Ve.get(e)?.examples?.filter(o=>k(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r?.length){let o=t.meta();Ve.remove(t).add(t,{...o,examples:r})}return t},negative:{schema:K.string().example("Sample error message"),mimeType:"text/plain"},handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=ke(r);return _e(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(xe(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ae.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Re=class e{constructor(t){this.resultHandler=t}schema=void 0;middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r.schema=Lr(this.schema,t.schema),r}addMiddleware(t){return this.#e(t instanceof D?t:new D(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new Ie(...t))}addOptions(t){return this.#e(new D({handler:t}))}build({input:t=qe,output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,y=typeof o=="function"?o:x=>o&&`${o}${x==="head"?"__HEAD":""}`,h=typeof n=="string"?[n]:n||[],S=typeof s=="string"?[s]:s||[];return new yt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:S,methods:m,getOperationId:y,inputSchema:Br(this.schema,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:qe,handler:async o=>(await t(o),{})})}},ln=new Re(be),un=new Re(Zt);import bn from"ansis";import{inspect as Rn}from"node:util";import{performance as Zr}from"node:perf_hooks";import{blue as fn,green as yn,hex as hn,red as gn,cyanBright as xn}from"ansis";import*as Hr from"ramda";var Dt={debug:fn,info:yn,warn:hn("#FFA500"),error:gn,ctx:xn},ht={debug:10,info:20,warn:30,error:40},Kr=e=>k(e)&&Object.keys(ht).some(t=>t in e),qr=e=>e in ht,Fr=(e,t)=>ht[e]<ht[t],Sn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ne=Hr.memoizeWith((e,t)=>`${e}${t}`,Sn),$r=e=>e<1e-6?Ne("nanosecond",3).format(e/1e-6):e<.001?Ne("nanosecond").format(e/1e-6):e<1?Ne("microsecond").format(e/.001):e<1e3?Ne("millisecond").format(e):e<6e4?Ne("second",2).format(e/1e3):Ne("minute",2).format(e/6e4);var Ge=class e{config;constructor({color:t=bn.isSupported(),level:r=ue()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return Rn(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,...i},color:p}=this.config;if(n==="silent"||Fr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Dt.ctx(s):s),d.push(p?`${Dt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),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=Zr.now();return()=>{let o=Zr.now()-r,{message:n,severity:s="debug",formatter:i=$r}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Dr from"ramda";var We=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Dr.filter(r=>!!r[1],Object.entries(this.#e));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 On from"express";var Ye=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,On.static(...this.#e))}};import bt from"express";import Kn from"node:http";import qn from"node:https";var Me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new De(e)};import vn from"http-errors";import{z as _r}from"zod";import*as R from"ramda";var Tn=e=>e.type==="object",Pn=R.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return R.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),wn=R.pipe(Object.keys,R.without(["type","properties","required","examples","description","additionalProperties"]),R.isEmpty),Ur=R.pair(!0),je=(e,t="coerce")=>{let r=[R.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&wn(p)))throw new Error("Can not merge");return R.pair(s,p)})),i.anyOf&&r.push(...R.map(Ur,i.anyOf)),i.oneOf&&r.push(...R.map(Ur,i.oneOf)),i.examples?.length&&(s?o.examples=R.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(k)||[],i.examples.filter(k),([p,d])=>R.mergeDeepRight(p,d))),!!Tn(i)&&(r.push([s,{examples:Cn(i)}]),i.properties&&(o.properties=(t==="throw"?Pn:R.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),k(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},Cn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=k(o)?o:{};return le(t,n.map(R.objOf(r)),([s,i])=>({...s,...i}))},[]);var gt=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[_r.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=Kt(t.inputSchema,"input");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 ze)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=Kt(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=pt(t);if(s.length===0)return;let i=n?.flat||je(_r.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||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:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var xt=e=>(t,...r)=>{e(t,...r),t==="get"&&e("head",...r)},En=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&de(t)?[r,t]:[e]},kn=e=>e.trim().split("/").filter(Boolean).join("/"),Jr=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=En(r);return[[t||""].concat(kn(n)||[]).join("/"),o,s]}),In=(e,t)=>{throw new ge("Route with explicit method can only be assigned with Endpoint",e,t)},Vr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ge(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Ut=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ge("Route has a duplicate",e,t);r.add(o)},Le=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Jr(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Je)if(p)Ut(p,s,n),Vr(p,s,i.methods),t(p,s,i);else{let{methods:d=["get"]}=i;for(let c of d)Ut(c,s,n),t(c,s,i)}else if(p&&In(p,s),i instanceof Ye)r&&i.apply(s,r);else if(i instanceof We)for(let[d,c]of i.entries){let{methods:m}=c;Ut(d,s,n),Vr(d,s,m),t(d,s,c)}else o.unshift(...Jr(i,s))}};import*as Gr from"ramda";var Wr=e=>e.sort((t,r)=>+de(r)-+de(t)||t.localeCompare(r)).join(", ").toUpperCase(),An=e=>({method:t},r,o)=>{let n=Wr(e);r.set({Allow:n});let s=vn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},zn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Wr(e),"Access-Control-Allow-Headers":"content-type"}),_t=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new gt(t()),i=new Map;Le({routing:o,onEndpoint:(c,m,y)=>{ue()||(s?.checkSchema(y,{path:m,method:c}),s?.checkPathParams(m,y,{method:c}));let h=n?.[y.requestType]||[],S=Gr.pair(h,y);i.has(m)||i.set(m,new Map(r.cors?[["options",S]]:[])),i.get(m)?.set(c,S)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let y=Array.from(m.keys());y.includes("get")&&y.push("head");for(let[h,[S,x]]of m){let z=S.slice().concat(async(P,b)=>{let v=t(P);return x.execute({request:P,response:b,logger:v,config:r})});r.cors&&z.unshift(async(P,b,v)=>{let B=t(P),N=zn(y),M=typeof r.cors=="function"?await r.cors({request:P,endpoint:x,logger:B,defaultHeaders:N}):N;b.set(M),v()}),e[h](c,...z)}r.wrongMethodBehavior!==404&&d.set(c,An(y))}for(let[c,m]of d)e.all(c,m)};import Mn from"http-errors";import{setInterval as Nn}from"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",Qr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Xr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,eo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),to=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var ro=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Yr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",eo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Xr(c)||Qr(c))&&i(c);for await(let c of Nn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(to))};return{sockets:n,shutdown:()=>o??=d()}};var oo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:te(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),no=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Mn(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){ft({response:o,logger:s,error:new ne(te(i),n)})}},jn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Ln=e=>({log:e.debug.bind(e)}),so=async({getLogger:e,config:t})=>{let r=await Me("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Ln(m)})(p,d,c)}),o&&i.push(jn(o)),i},io=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},ao=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[Ce]={logger:i}),s()},po=e=>t=>t?.res?.locals[Ce]?.logger||e,co=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
import"@express-zod-api/zod-plugin";function qo(e){return e}import*as L from"ramda";import{z as Te}from"zod";var E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var fr=["get","post","put","delete","patch"],yr=[...fr,"head"],ae=e=>fr.includes(e);var je=Te.object({}),At=/:([A-Za-z0-9_]+)/g,nt=e=>e.match(At)?.map(t=>t.slice(1))||[],Fo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Do={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Uo=["body","query","params"],zt=e=>e.method.toLowerCase(),Nt=(e,t={})=>{if(e==="options")return[];let r=e==="head"?"get":ae(e)?e:void 0;return(r?t[r]||Do[r]:void 0)||Uo},st=(e,t={})=>{let r=zt(e);return Nt(r,t).filter(o=>o==="files"?Fo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},Q=e=>e instanceof Error?e:e instanceof Te.ZodError?new Te.ZodRealError(e.issues):new Error(String(e)),pe=e=>e instanceof Te.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Te.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,X=(e,t)=>C(e)&&"_zod"in e&&(t?L.path(["_zod","def","type"],e)===t:!0),ce=(e,t,r)=>e.length&&t.length?L.xprod(e,t).map(r):e.concat(t),Mt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ee=(...e)=>{let t=L.chain(o=>o.split(/[^A-Z0-9]/gi),e);return L.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Mt).join("")},it=L.tryCatch((e,t)=>typeof Te.parse(e,t),L.always(void 0)),C=e=>typeof e=="object"&&e!==null,de=L.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production"),at=(e,t)=>!!t&&e!=="head";import*as ne from"ramda";import{z as Ar,globalRegistry as zr}from"zod";import*as oe from"ramda";import{z as Tr}from"zod";import{z as $o}from"zod";var me=Symbol("Buffer"),pt=()=>$o.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(me);import{z as He}from"zod";var le=Symbol("DateIn"),gr=({examples:e,...t}={})=>He.union([He.iso.date(),He.iso.datetime(),He.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(He.date()).brand(le).meta(t);import{z as Zo}from"zod";var ue=Symbol("DateOut"),hr=(e={})=>Zo.date().transform(t=>t.toISOString()).brand(ue).meta(e);import{z as _o}from"zod";var fe=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},V=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.`}},Be=class extends Error{name="IOSchemaError"},ct=class extends Be{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},Ke=class extends Be{constructor(r){let o=new _o.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(pe(o),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends Be{constructor(r){super(pe(r),{cause:r});this.cause=r}name="InputValidationError"},te=class extends Error{constructor(r,o){super(pe(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},qe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as xr}from"zod";var Fe=Symbol("Form"),Sr=e=>(e instanceof xr.ZodObject?e:xr.object(e)).brand(Fe);import{getBrand as Pr}from"@express-zod-api/zod-plugin";import{z as Jo}from"zod";var re=Symbol("Upload"),br=()=>Jo.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",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(re);import{z as Vo}from"zod";var B=Symbol("Raw"),Rr=Vo.object({raw:pt()}),Go=e=>Rr.extend(e).brand(B);function Or(e){return e?Go(e):Rr.brand(B)}var wr=(e,{io:t,condition:r})=>oe.tryCatch(()=>{Tr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new ct(o)}})},o=>o.cause)(),vr=(e,{io:t})=>{let o=[Tr.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(oe.is(Object,n)){if(n.$ref==="#")return!0;o.push(...oe.values(n))}oe.is(Array,n)&&o.push(...oe.values(n))}return!1},Er=e=>wr(e,{condition:t=>{let r=Pr(t);return typeof r=="symbol"&&[re,B,Fe].includes(r)},io:"input"}),Wo=["nan","symbol","map","set","bigint","void","promise","never"],Lt=(e,t)=>wr(e,{io:t,condition:r=>{let o=Pr(r),{type:n}=r._zod.def;return!!(Wo.includes(n)||o===me||t==="input"&&(n==="date"||o===ue)||t==="output"&&(o===le||o===B||o===re))}});import en,{isHttpError as tn}from"http-errors";import Cr,{isHttpError as Yo}from"http-errors";import*as Ir from"ramda";import{globalRegistry as Qo,z as Xo}from"zod";var jt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof Xo.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new te(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},De=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Pe=e=>Yo(e)?e:Cr(e instanceof G?400:500,pe(e),{cause:e.cause||e}),ye=e=>de()&&!e.expose?Cr(e.statusCode).message:e.message,kr=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=Qo.get(o)||{};return ce(t,n.map(Ir.objOf(r)),([s,i])=>({...s,...i}))},[]);var dt=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ye(en(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:tn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{getBrand as on}from"@express-zod-api/zod-plugin";import{z as rn}from"zod";var Ht=class{},U=class extends Ht{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await(this.#e||je).parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof rn.ZodError?new G(o):o}}},we=class extends U{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var ve=class{nest(t){return Object.assign(t,{"":this})}};var Ue=class extends ve{},mt=class e extends Ue{#e;#t=ne.once(()=>{if(zr.get(this.#e.outputSchema)?.examples?.length||!X(this.#e.outputSchema,"object"))return;let t=kr(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();zr.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Er(this.#e.inputSchema);if(t){let r=on(t);if(r===re)return"upload";if(r===B)return"raw";if(r===Fe)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ne.pluck("security",this.#e.middlewares||[]);return ne.reject(ne.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Ar.ZodError?new Ke(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof we))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Ar.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){dt({...t,error:new te(Q(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=zt(t),i={},p={output:{},error:null},d=st(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:Q(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var Nr=(e,t)=>e&&t?e.and(t):e||t,Mr=(e,t)=>e?e.and(t):t;import{globalRegistry as $e,z as K}from"zod";var Ee={positive:200,negative:400},Ce=Object.keys(Ee);var Bt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ge=class extends Bt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return jt(this.#e,{variant:"positive",args:[t],statusCodes:[Ee.positive],mimeTypes:[E.json]})}getNegativeResponse(){return jt(this.#t,{variant:"negative",args:[],statusCodes:[Ee.negative],mimeTypes:[E.json]})}},he=new ge({positive:e=>{let t=K.object({status:K.literal("success"),data:e}),{examples:r}=$e.get(e)||{};return r?.length&&$e.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:K.object({status:K.literal("error"),error:K.object({message:K.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Pe(e);return De(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:ye(i)}})}n.status(Ee.positive).json({status:"success",data:r})}}),Kt=new ge({positive:e=>{let t=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());if($e.get(t)?.examples?.length)return t;let r=$e.get(e)?.examples?.filter(o=>C(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r?.length){let o=t.meta();$e.remove(t).add(t,{...o,examples:r})}return t},negative:{schema:K.string().example("Sample error message"),mimeType:"text/plain"},handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Pe(r);return De(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(ye(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ee.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var xe=class e{constructor(t){this.resultHandler=t}schema=void 0;middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r.schema=Nr(this.schema,t.schema),r}addMiddleware(t){return this.#e(t instanceof U?t:new U(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new we(...t))}addOptions(t){return this.#e(new U({handler:t}))}build({input:t=je,output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,y=typeof o=="function"?o:x=>o&&`${o}${x==="head"?"__HEAD":""}`,g=typeof n=="string"?[n]:n||[],S=typeof s=="string"?[s]:s||[];return new mt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:g,tags:S,methods:m,getOperationId:y,inputSchema:Mr(this.schema,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:je,handler:async o=>(await t(o),{})})}},nn=new xe(he),sn=new xe(Kt);import un from"ansis";import{inspect as fn}from"node:util";import{performance as qr}from"node:perf_hooks";import{blue as an,green as pn,hex as cn,red as dn,cyanBright as mn}from"ansis";import*as Lr from"ramda";var qt={debug:an,info:pn,warn:cn("#FFA500"),error:dn,ctx:mn},lt={debug:10,info:20,warn:30,error:40},jr=e=>C(e)&&Object.keys(lt).some(t=>t in e),Hr=e=>e in lt,Br=(e,t)=>lt[e]<lt[t],ln=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ie=Lr.memoizeWith((e,t)=>`${e}${t}`,ln),Kr=e=>e<1e-6?Ie("nanosecond",3).format(e/1e-6):e<.001?Ie("nanosecond").format(e/1e-6):e<1?Ie("microsecond").format(e/.001):e<1e3?Ie("millisecond").format(e):e<6e4?Ie("second",2).format(e/1e3):Ie("minute",2).format(e/6e4);var Ze=class e{config;constructor({color:t=un.isSupported(),level:r=de()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return fn(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,...i},color:p}=this.config;if(n==="silent"||Br(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?qt.ctx(s):s),d.push(p?`${qt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),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=qr.now();return()=>{let o=qr.now()-r,{message:n,severity:s="debug",formatter:i=Kr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Fr from"ramda";var _e=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Fr.filter(r=>!!r[1],Object.entries(this.#e));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 yn from"express";var Je=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,yn.static(...this.#e))}};import gt from"express";import Nn from"node:http";import Mn from"node:https";var ke=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new qe(e)};import Tn from"http-errors";import{z as Ur}from"zod";import*as R from"ramda";var gn=e=>e.type==="object",hn=R.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return R.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),xn=R.pipe(Object.keys,R.without(["type","properties","required","examples","description","additionalProperties"]),R.isEmpty),Dr=R.pair(!0),Ae=(e,t="coerce")=>{let r=[R.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&xn(p)))throw new Error("Can not merge");return R.pair(s,p)})),i.anyOf&&r.push(...R.map(Dr,i.anyOf)),i.oneOf&&r.push(...R.map(Dr,i.oneOf)),i.examples?.length&&(s?o.examples=R.concat(o.examples||[],i.examples):o.examples=ce(o.examples?.filter(C)||[],i.examples.filter(C),([p,d])=>R.mergeDeepRight(p,d))),!!gn(i)&&(r.push([s,{examples:Sn(i)}]),i.properties&&(o.properties=(t==="throw"?hn:R.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),C(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},Sn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=C(o)?o:{};return ce(t,n.map(R.objOf(r)),([s,i])=>({...s,...i}))},[]);var ut=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Ur.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=Lt(t.inputSchema,"input");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 Ce)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=Lt(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=nt(t);if(s.length===0)return;let i=n?.flat||Ae(Ur.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||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:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var ft=e=>(t,...r)=>{e(t,...r),t==="get"&&e("head",...r)},bn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&ae(t)?[r,t]:[e]},Rn=e=>e.trim().split("/").filter(Boolean).join("/"),$r=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=bn(r);return[[t||""].concat(Rn(n)||[]).join("/"),o,s]}),On=(e,t)=>{throw new fe("Route with explicit method can only be assigned with Endpoint",e,t)},Zr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new fe(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Ft=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new fe("Route has a duplicate",e,t);r.add(o)},ze=({routing:e,onEndpoint:t,onStatic:r})=>{let o=$r(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Ue)if(p)Ft(p,s,n),Zr(p,s,i.methods),t(p,s,i);else{let{methods:d=["get"]}=i;for(let c of d)Ft(c,s,n),t(c,s,i)}else if(p&&On(p,s),i instanceof Je)r&&i.apply(s,r);else if(i instanceof _e)for(let[d,c]of i.entries){let{methods:m}=c;Ft(d,s,n),Zr(d,s,m),t(d,s,c)}else o.unshift(...$r(i,s))}};import*as _r from"ramda";var Jr=e=>e.sort((t,r)=>+ae(r)-+ae(t)||t.localeCompare(r)).join(", ").toUpperCase(),Pn=e=>({method:t},r,o)=>{let n=Jr(e);r.set({Allow:n});let s=Tn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},wn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Jr(e),"Access-Control-Allow-Headers":"content-type"}),Dt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=de()?void 0:new ut(t()),i=new Map;ze({routing:o,onEndpoint:(c,m,y)=>{de()||(s?.checkSchema(y,{path:m,method:c}),s?.checkPathParams(m,y,{method:c}));let g=n?.[y.requestType]||[],S=_r.pair(g,y);i.has(m)||i.set(m,new Map(r.cors?[["options",S]]:[])),i.get(m)?.set(c,S)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let y=Array.from(m.keys());y.includes("get")&&y.push("head");for(let[g,[S,x]]of m){let z=S.slice().concat(async(P,b)=>{let k=t(P);return x.execute({request:P,response:b,logger:k,config:r})});r.cors&&z.unshift(async(P,b,k)=>{let H=t(P),N=wn(y),M=typeof r.cors=="function"?await r.cors({request:P,endpoint:x,logger:H,defaultHeaders:N}):N;b.set(M),k()}),e[g](c,...z)}r.wrongMethodBehavior!==404&&d.set(c,Pn(y))}for(let[c,m]of d)e.all(c,m)};import Cn from"http-errors";import{setInterval as vn}from"node:timers/promises";var Vr=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",Gr=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,Yr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Qr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Xr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Vr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",Yr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Wr(c)||Gr(c))&&i(c);for await(let c of vn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(Qr))};return{sockets:n,shutdown:()=>o??=d()}};var eo="express-zod-api";var to=Symbol.for(eo),ro=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:Q(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),oo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Cn(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){dt({response:o,logger:s,error:new te(Q(i),n)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},kn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await ke("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:kn(m)})(p,d,c)}),o&&i.push(In(o)),i},so=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},io=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[to]={logger:i}),s()},ao=e=>t=>t?.res?.locals[to]?.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))),co=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=Xr(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};import{gray as An,hex as mo,italic as yt,whiteBright as zn}from"ansis";var lo=e=>{if(e.columns<132)return;let t=yt("Proudly supports transgender community.".padStart(109)),r=yt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=yt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=yt("for Sara".padEnd(20)),s=mo("#F5A9B8"),i=mo("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(zn,5,7).fill(s,7,9).fill(i,9,12).fill(An,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((c,m)=>p[m]?p[m](c):c).join(`
|
|
18
|
-
`))};var fo=e=>{e.startupLogo!==!1&&uo(process.stdout);let t=e.errorHandler||be,r=Kr(e.logger)?e.logger:new Ge(e.logger);r.debug("Running",{build:"v25.1.0",env:process.env.NODE_ENV||"development"}),co(r);let o=ao({logger:r,config:e}),s={getLogger:po(r),errorHandler:t},i=no(s),p=oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Fn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=fo(e);return _t({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},$n=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=fo(e),p=bt().disable("x-powered-by").use(i);if(e.compression){let h=await Me("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||bt.json()],raw:[e.rawParser||bt.raw(),io],form:[e.formParser||bt.urlencoded()],upload:e.upload?await so({config:e,getLogger:o}):[]};_t({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(h,S)=>()=>h.listen(S,()=>r.info("Listening",S)),y=[];if(e.http){let h=Kn.createServer(p);c.push(h),y.push(m(h,e.http.listen))}if(e.https){let h=qn.createServer(e.https.options,p);c.push(h),y.push(m(h,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&mo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:y.map(h=>h())}};import{OpenApiBuilder as ls}from"openapi3-ts/oas31";import*as zo from"ramda";import*as O from"ramda";var yo=e=>k(e)&&"or"in e,ho=e=>k(e)&&"and"in e,Jt=e=>!ho(e)&&!yo(e),go=e=>{let t=O.filter(Jt,e),r=O.chain(O.prop("and"),O.filter(ho,e)),[o,n]=O.partition(Jt,r),s=O.concat(t,o),i=O.filter(yo,e);return O.map(O.prop("or"),O.concat(i,n)).reduce((d,c)=>le(d,O.map(m=>Jt(m)?[m]:m.and,c),([m,y])=>O.concat(m,y)),O.reject(O.isEmpty,[s]))};import{isReferenceObject as Ro,isSchemaObject as Rt}from"openapi3-ts/oas31";import*as l from"ramda";import{z as So}from"zod";var xo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var bo=50,Oo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Dn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},To=e=>e.replace(jt,t=>`{${t.slice(1)}}`),Un=({},e)=>{if(e.isResponse)throw new Y("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},_n=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Jn=({zodSchema:e,jsonSchema:t})=>{if(!re(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Vn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return je(e,"throw")},(e,{jsonSchema:t})=>t),Gn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ts(t.type)})},Qe=e=>e,Wn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Y("Please use ez.dateOut() for output.",r);let o={description:t||"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:Oo}};return e?.length&&(o.examples=e),o},Yn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Y("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Oo}};return e?.length&&(o.examples=e),o},Qn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Xn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},es=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Dn?.[t]},ts=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],rs=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!re(o,"transform"))return t;let s=Qe(Wt(n,{ctx:r}));if(Rt(s))if(r.isResponse){let i=dt(o,es(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},os=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!k(t.properties.raw)?e:t.properties.raw},Vt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ns=(e,t)=>t?.includes(e)||e.startsWith("x-")||xo.includes(e),Po=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=je(r),m=pt(e),y=o.includes("query"),h=o.includes("params"),S=o.includes("headers"),x=b=>h&&m.includes(b),z=l.chain(l.filter(b=>b.type==="header"),p??[]).map(({name:b})=>b),P=b=>S&&(i?.(b,t,e)??ns(b,z));return Object.entries(c.properties).reduce((b,[v,B])=>{if(!k(B))return b;let N=x(v)?"path":P(v)?"header":y?"query":void 0;if(!N)return b;let M=Qe(B),X=s==="components"?n(B.id||JSON.stringify(B),M,oe(d,v)):M;return b.concat({name:v,in:N,deprecated:B.deprecated,required:c.required?.includes(v)||!1,description:M.description||d,schema:X,examples:Vt(Rt(M)&&M.examples?.length?M.examples:l.pluck(v,c.examples?.filter(l.both(k,l.has(v)))||[]))})},[])},Gt={nullable:Gn,union:Jn,bigint:Qn,intersection:Vn,tuple:Xn,pipe:rs,[ye]:Wn,[he]:Yn,[se]:Un,[H]:os,[fe]:_n},ss=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(Ro(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Qe(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Wt=(e,{ctx:t,rules:r=Gt})=>{let{$defs:o={},properties:n={}}=So.toJSONSchema(So.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=G(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return ss(k(n.subject)?n.subject:{},o,t)},wo=(e,t)=>{if(Ro(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=wo(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},Co=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${Ht(n)} response ${p?d:""}`.trim()})=>{if(!mt(e,o))return{description:m};let y=Qe(Wt(r,{rules:{...c,...Gt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];Rt(y)&&y.examples&&(h.push(...y.examples),delete y.examples);let S={schema:i==="components"?s(r,y,oe(m)):y,examples:Vt(h)};return{description:m,content:l.fromPairs(l.xprod(o,[S]))}},is=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},as=({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},ps=({name:e})=>({type:"apiKey",in:"header",name:e}),cs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ds=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ms=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Eo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?is(o):o.type==="input"?as(o,t):o.type==="header"?ps(o):o.type==="cookie"?cs(o):o.type==="openid"?ds(o):ms(o);return e.map(o=>o.map(r))},ko=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),Io=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Wt(e,{rules:{...t,...Gt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),vo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=wo(Qe(o),p),y=[];Rt(c)&&c.examples&&(y.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,oe(d)):c,examples:Vt(y.length?y:je(o).examples?.filter(x=>k(x)&&!Array.isArray(x)).map(l.omit(p))||[])},S={description:d,content:{[n]:h}};return(m||n===E.raw)&&(S.required=!0),S},Ao=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Yt=e=>e.length<=bo?e:e.slice(0,bo-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Qt=class extends ls{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||oe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new Y(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,hasHeadMethod:y=!0,composition:h="inline"}){super(),this.addInfo({title:o,version:n});for(let x of typeof s=="string"?[s]:s)this.addServer({url:x});let S=(x,z,P)=>{let b={path:z,method:x,endpoint:P,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:v,shortDescription:B,scopes:N,inputSchema:M}=P,X=B?Yt(B):m&&v?Yt(v):void 0,Pe=Bt(x,r.inputSources),we=this.#n(z,x,P.getOperationId(x)),rt=Io({...b,schema:M}),pe=go(P.security),ot=Po({...b,inputSources:Pe,isHeader:c,security:pe,request:rt,description:i?.requestParameter?.call(null,{method:x,path:z,operationId:we})}),nt={};for(let ee of ze){let ce=P.getResponses(ee);for(let{mimeTypes:Nt,schema:it,statusCodes:at}of ce)for(let Mt of at)nt[Mt]=Co({...b,variant:ee,schema:it,mimeTypes:Nt,statusCode:Mt,hasMultipleStatusCodes:ce.length>1||at.length>1,description:i?.[`${ee}Response`]?.call(null,{method:x,path:z,operationId:we,statusCode:Mt})})}let st=Pe.includes("body")?vo({...b,request:rt,paramNames:zo.pluck("name",ot),schema:M,mimeType:E[P.requestType],description:i?.requestBody?.call(null,{method:x,path:z,operationId:we})}):void 0,At=ko(Eo(pe,Pe),N,ee=>{let ce=this.#s(ee);return this.addSecurityScheme(ce,ee),ce}),zt={operationId:we,summary:X,description:v,deprecated:P.isDeprecated||void 0,tags:Ot(P.tags),parameters:Ot(ot),requestBody:st,security:Ot(At),responses:nt};this.addPath(To(z),{[x]:zt})};Le({routing:t,onEndpoint:y?xt(S):S}),d&&(this.rootDoc.tags=Ao(d))}};import{createRequest as us,createResponse as fs}from"node-mocks-http";var ys=e=>us({...e,headers:{"content-type":E.json,...e?.headers}}),hs=e=>fs(e),gs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:qr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},No=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ys(e),s=hs({req:n,...t});s.req=t?.req||n,n.res=s;let i=gs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},xs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=No(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Ss=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=No(r),d=ct(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:te(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import vt from"typescript";import{z as Ds}from"zod";import*as Lo from"ramda";import V from"typescript";import*as U from"ramda";import u from"typescript";var a=u.factory,Tt=[a.createModifier(u.SyntaxKind.ExportKeyword)],bs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Xe={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Xt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),er=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},Rs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,tr=e=>typeof e=="string"&&Rs.test(e)?a.createIdentifier(e):T(e),Pt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),wt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Be=e=>Object.entries(e).map(([t,r])=>wt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),rr=(e,t=[])=>a.createConstructorDeclaration(Xe.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&U.map(f,t)):e,or=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),_=e=>{let t=new Map;for(let r of e)t.set(Ts(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,tr(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?_([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=U.reject(U.isNil,[o?"@deprecated":void 0,n]);return p.length?Xt(i,p.join(" ")):i},nr=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),sr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),A=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&Tt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),ir=(e,t)=>J(e,_(U.map(L,t)),{expose:!0}),J=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?Tt:void 0,e,n&&dr(n),t);return o?Xt(s,o):s},Mo=(e,t)=>a.createPropertyDeclaration(Xe.public,e,void 0,f(t),void 0),ar=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Xe.public,void 0,e,void 0,o&&dr(o),t,n,a.createBlock(r)),pr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(Tt,e,r&&dr(r),void 0,t),cr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Ct=e=>f(Promise.name,[e]),Et=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?Tt:void 0,e,void 0,void 0,t);return o?Xt(n,o):n},dr=e=>(Array.isArray(e)?e.map(t=>U.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 a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Te=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?bs:void 0,void 0,Array.isArray(e)?U.map(wt,e):Be(e),void 0,void 0,t),w=e=>e,et=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),C=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),He=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),kt=(e,t)=>f("Extract",[e,t]),mr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),q=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),jo=e=>_([f(e),Ct(e)]),lr=(e,t)=>a.createFunctionTypeNode(void 0,Be(e),f(t)),T=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),L=e=>a.createLiteralTypeNode(T(e)),Os=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Ts=e=>Os.includes(e.kind);var It=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=ir("Method",Sr);someOfType=J("SomeOf",q("T",cr("T")),{params:["T"]});requestType=J("Request",cr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>ir(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Et(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>A("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(tr(t),a.createArrayLiteralExpression(Lo.map(T,r))))),{expose:!0});makeImplementationType=()=>J(this.#e.implementationType,lr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Ct(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>A(this.#e.parseRequestFn,Te({[this.#e.requestParameter.text]:V.SyntaxKind.StringKeyword},a.createAsExpression(C(this.#e.requestParameter,w("split"))(a.createRegularExpressionLiteral("/ (.+)/"),T(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>A(this.#e.substituteFn,Te({[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:or},a.createBlock([A(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],V.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([mr(this.#e.pathParameter,C(this.#e.pathParameter,w("replace"))(Pt(":",[this.#e.keyParameter]),Te([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ar(this.#e.provideMethod,Be({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:q(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[A(sr(this.#e.methodParameter,this.#e.pathParameter),C(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(C(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(C(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Ct(q(this.interfaces.response,"K"))});makeClientClass=t=>pr(t,[rr([wt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Xe.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Pt("?",[He(URLSearchParams.name,t)]);#o=()=>He(URL.name,Pt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),T(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(w("method"),C(this.#e.methodParameter,w("toUpperCase"))()),r=a.createPropertyAssignment(w("headers"),et(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(T("Content-Type"),T(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(w("body"),et(this.#e.hasBodyConst,C(JSON[Symbol.toStringTag],w("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=A(this.#e.responseConst,a.createAwaitExpression(C(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=A(this.#e.hasBodyConst,a.createLogicalNot(C(a.createArrayLiteralExpression([T("get"),T("head"),T("delete")]),w("includes"))(this.#e.methodParameter))),i=A(this.#e.searchParamsConst,et(this.#e.hasBodyConst,T(""),this.#r(this.#e.paramsArgument))),p=A(this.#e.contentTypeConst,C(this.#e.responseConst,w("headers"),w("get"))(T("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=A(this.#e.isJsonConst,C(this.#e.contentTypeConst,w("startsWith"))(T(E.json))),m=a.createReturnStatement(C(this.#e.responseConst,et(this.#e.isJsonConst,T(w("json")),T(w("text"))))());return A(this.#e.defaultImplementationConst,Te([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>rr(Be({request:"K",params:q(this.interfaces.input,"K")}),[A(sr(this.#e.pathParameter,this.#e.restConst),C(this.#e.substituteFn)(a.createElementAccessExpression(C(this.#e.parseRequestFn)(this.#e.requestParameter),T(1)),this.#e.paramsArgument)),A(this.#e.searchParamsConst,this.#r(this.#e.restConst)),mr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),He("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Oe(w("event"),t)]);#i=()=>ar(this.#e.onMethod,Be({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:lr({[this.#e.dataParameter.text]:q(kt("R",nr(this.#s("E"))),L(w("data")))},jo(V.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(C(a.createThis(),this.#e.sourceProp,w("addEventListener"))(this.#e.eventParameter,Te([this.#e.msgParameter],C(this.#e.handlerParameter)(C(JSON[Symbol.toStringTag],w("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),w("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:q("R",L(w("event")))}});makeSubscriptionClass=t=>pr(t,[Mo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:kt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(V.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:kt(q(this.interfaces.positive,"K"),nr(this.#s(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[A(this.#e.clientConst,He(t)),C(this.#e.clientConst,this.#e.provideMethod)(T("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",T("10"))])),C(He(r,T("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(T("time"),Te(["time"],a.createBlock([])))]};import*as I from"ramda";import g from"typescript";import{globalRegistry as Ps}from"zod";var ur=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=G(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>ur(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:$}=g,ws={[g.SyntaxKind.AnyKeyword]:"",[g.SyntaxKind.BigIntKeyword]:BigInt(0),[g.SyntaxKind.BooleanKeyword]:!1,[g.SyntaxKind.NumberKeyword]:0,[g.SyntaxKind.ObjectKeyword]:{},[g.SyntaxKind.StringKeyword]:"",[g.SyntaxKind.UndefinedKeyword]:void 0},fr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Cs=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(g.SyntaxKind.UndefinedKeyword):L(r));return t.length===1?t[0]:_(t)},Es=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(re(p)){r.unshift(p);break}i+=p??""}return i},n=$.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?$.createTemplateMiddle:$.createTemplateTail;s.push($.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?$.createTemplateLiteralType(n,s):L(n.text)},ks=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=Ps.get(p)||{};return Oe(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return $.createTypeLiteralNode(s)};return Ir(e,{io:t?"output":"input"})?o(e,n):n()},Is=({_zod:{def:e}},{next:t})=>$.createArrayTypeNode(t(e.element)),vs=({_zod:{def:e}})=>_(Object.values(e.entries).map(L)),As=({_zod:{def:e}},{next:t})=>_(e.options.map(t)),zs=e=>ws?.[e.kind],Ns=({_zod:{def:e}},{next:t})=>_([t(e.innerType),L(null)]),Ms=({_zod:{def:e}},{next:t})=>$.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:$.createRestTypeNode(t(e.rest)))),js=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Ls=I.tryCatch(e=>{if(!e.every(g.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(fr.name,...o))return!1;if(I.both(I.eqBy(fr.type),I.eqBy(fr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),Bs=({_zod:{def:e}},{next:t})=>Ls([e.left,e.right].map(t)),F=e=>()=>f(e),tt=({_zod:{def:e}},{next:t})=>t(e.innerType),Bo=e=>f(e?g.SyntaxKind.UnknownKeyword:g.SyntaxKind.AnyKeyword),Hs=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!re(o,"transform"))return t(o);let s=t(n),i=dt(o,zs(s)),p={number:g.SyntaxKind.NumberKeyword,bigint:g.SyntaxKind.BigIntKeyword,boolean:g.SyntaxKind.BooleanKeyword,string:g.SyntaxKind.StringKeyword,undefined:g.SyntaxKind.UndefinedKeyword,object:g.SyntaxKind.ObjectKeyword};return f(i&&p[i]||Bo(r))},Ks=()=>L(null),qs=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Fs=()=>f("Buffer"),$s=(e,{next:t})=>t(e._zod.def.shape.raw),Zs={string:F(g.SyntaxKind.StringKeyword),number:F(g.SyntaxKind.NumberKeyword),bigint:F(g.SyntaxKind.BigIntKeyword),boolean:F(g.SyntaxKind.BooleanKeyword),any:F(g.SyntaxKind.AnyKeyword),undefined:F(g.SyntaxKind.UndefinedKeyword),[ye]:F(g.SyntaxKind.StringKeyword),[he]:F(g.SyntaxKind.StringKeyword),never:F(g.SyntaxKind.NeverKeyword),void:F(g.SyntaxKind.UndefinedKeyword),unknown:F(g.SyntaxKind.UnknownKeyword),null:Ks,array:Is,tuple:Ms,record:js,object:ks,literal:Cs,template_literal:Es,intersection:Bs,union:As,default:tt,enum:vs,optional:tt,nonoptional:tt,nullable:Ns,catch:tt,pipe:Hs,lazy:qs,readonly:tt,[fe]:Fs,[H]:$s},yr=(e,{brandHandling:t,ctx:r})=>ur(e,{rules:{...t,...Zs},onMissing:({},{isResponse:o})=>Bo(o),ctx:r});var hr=class extends It{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=L(null);this.#t.set(t,J(o,n)),this.#t.set(t,J(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=Ds.undefined(),hasHeadMethod:d=!0}){super(i);let c={makeAlias:this.#o.bind(this)},m={brandHandling:r,ctx:{...c,isResponse:!1}},y={brandHandling:r,ctx:{...c,isResponse:!0}},h=(S,x,z)=>{let P=oe.bind(null,S,x),{isDeprecated:b,inputSchema:v,tags:B}=z,N=`${S} ${x}`,M=J(P("input"),yr(v,m),{comment:N});this.#e.push(M);let X=ze.reduce((rt,pe)=>{let ot=z.getResponses(pe),nt=Ho.chain(([At,{schema:zt,mimeTypes:ee,statusCodes:ce}])=>{let Nt=mt(S,ee),it=J(P(pe,"variant",`${At+1}`),yr(Nt?zt:p,y),{comment:N});return this.#e.push(it),ce.map(at=>Oe(at,it.name))},Array.from(ot.entries())),st=Et(P(pe,"response","variants"),nt,{comment:N});return this.#e.push(st),Object.assign(rt,{[pe]:st})},{});this.paths.add(x);let Pe=L(N),we={input:f(M.name),positive:this.someOf(X.positive),negative:this.someOf(X.negative),response:_([q(this.interfaces.positive,Pe),q(this.interfaces.negative,Pe)]),encoded:a.createIntersectionTypeNode([f(X.positive.name),f(X.negative.name)])};this.registry.set(N,{isDeprecated:b,store:we}),this.tags.set(N,B)};Le({routing:t,onEndpoint:d?xt(h):h}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:er(r,t)).join(`
|
|
18
|
+
`))};var uo=e=>{e.startupLogo!==!1&&lo(process.stdout);let t=e.errorHandler||he,r=jr(e.logger)?e.logger:new Ze(e.logger);r.debug("Running",{build:"v25.2.0-beta.2",env:process.env.NODE_ENV||"development"}),po(r);let o=io({logger:r,config:e}),s={getLogger:ao(r),errorHandler:t},i=oo(s),p=ro(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Ln=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=uo(e);return Dt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},jn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=uo(e),p=gt().disable("x-powered-by").use(i);if(e.compression){let g=await ke("compression");p.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||gt.json()],raw:[e.rawParser||gt.raw(),so],form:[e.formParser||gt.urlencoded()],upload:e.upload?await no({config:e,getLogger:o}):[]};Dt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(g,S)=>()=>g.listen(S,()=>r.info("Listening",S)),y=[];if(e.http){let g=Nn.createServer(p);c.push(g),y.push(m(g,e.http.listen))}if(e.https){let g=Mn.createServer(e.https.options,p);c.push(g),y.push(m(g,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&co({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:y.map(g=>g())}};import{OpenApiBuilder as as}from"openapi3-ts/oas31";import*as Ao from"ramda";import*as O from"ramda";var fo=e=>C(e)&&"or"in e,yo=e=>C(e)&&"and"in e,Ut=e=>!yo(e)&&!fo(e),go=e=>{let t=O.filter(Ut,e),r=O.chain(O.prop("and"),O.filter(yo,e)),[o,n]=O.partition(Ut,r),s=O.concat(t,o),i=O.filter(fo,e);return O.map(O.prop("or"),O.concat(i,n)).reduce((d,c)=>ce(d,O.map(m=>Ut(m)?[m]:m.and,c),([m,y])=>O.concat(m,y)),O.reject(O.isEmpty,[s]))};import{isReferenceObject as bo,isSchemaObject as ht}from"openapi3-ts/oas31";import*as l from"ramda";import{z as xo}from"zod";import{getBrand as Bn}from"@express-zod-api/zod-plugin";var ho=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var So=50,Ro="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Kn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Oo=e=>e.replace(At,t=>`{${t.slice(1)}}`),qn=({},e)=>{if(e.isResponse)throw new V("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Fn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Dn=({zodSchema:e,jsonSchema:t})=>{if(!X(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Un=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ae(e,"throw")},(e,{jsonSchema:t})=>t),$n=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Wn(t.type)})},Ve=e=>e,Zn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new V("Please use ez.dateOut() for output.",r);let o={description:t||"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}};return e?.length&&(o.examples=e),o},_n=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new V("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ro}};return e?.length&&(o.examples=e),o},Jn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Vn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Gn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Kn?.[t]},Wn=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],Yn=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!X(o,"transform"))return t;let s=Ve(_t(n,{ctx:r}));if(ht(s))if(r.isResponse){let i=it(o,Gn(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},Qn=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!C(t.properties.raw)?e:t.properties.raw},$t=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,Xn=(e,t)=>t?.includes(e)||e.startsWith("x-")||ho.includes(e),To=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Ae(r),m=nt(e),y=o.includes("query"),g=o.includes("params"),S=o.includes("headers"),x=b=>g&&m.includes(b),z=l.chain(l.filter(b=>b.type==="header"),p??[]).map(({name:b})=>b),P=b=>S&&(i?.(b,t,e)??Xn(b,z));return Object.entries(c.properties).reduce((b,[k,H])=>{if(!C(H))return b;let N=x(k)?"path":P(k)?"header":y?"query":void 0;if(!N)return b;let M=Ve(H),W=s==="components"?n(H.id||JSON.stringify(H),M,ee(d,k)):M;return b.concat({name:k,in:N,deprecated:H.deprecated,required:c.required?.includes(k)||!1,description:M.description||d,schema:W,examples:$t(ht(M)&&M.examples?.length?M.examples:l.pluck(k,c.examples?.filter(l.both(C,l.has(k)))||[]))})},[])},Zt={nullable:$n,union:Dn,bigint:Jn,intersection:Un,tuple:Vn,pipe:Yn,[le]:Zn,[ue]:_n,[re]:qn,[B]:Qn,[me]:Fn},es=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(bo(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Ve(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},_t=(e,{ctx:t,rules:r=Zt})=>{let{$defs:o={},properties:n={}}=xo.toJSONSchema(xo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=Bn(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return es(C(n.subject)?n.subject:{},o,t)},Po=(e,t)=>{if(bo(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Po(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},wo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${Mt(n)} response ${p?d:""}`.trim()})=>{if(!at(e,o))return{description:m};let y=Ve(_t(r,{rules:{...c,...Zt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),g=[];ht(y)&&y.examples&&(g.push(...y.examples),delete y.examples);let S={schema:i==="components"?s(r,y,ee(m)):y,examples:$t(g)};return{description:m,content:l.fromPairs(l.xprod(o,[S]))}},ts=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},rs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},os=({name:e})=>({type:"apiKey",in:"header",name:e}),ns=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ss=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),is=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),vo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ts(o):o.type==="input"?rs(o,t):o.type==="header"?os(o):o.type==="cookie"?ns(o):o.type==="openid"?ss(o):is(o);return e.map(o=>o.map(r))},Eo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),Co=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>_t(e,{rules:{...t,...Zt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Io=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=Po(Ve(o),p),y=[];ht(c)&&c.examples&&(y.push(...c.examples),delete c.examples);let g={schema:i==="components"?s(r,c,ee(d)):c,examples:$t(y.length?y:Ae(o).examples?.filter(x=>C(x)&&!Array.isArray(x)).map(l.omit(p))||[])},S={description:d,content:{[n]:g}};return(m||n===E.raw)&&(S.required=!0),S},ko=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)},[]),Jt=e=>e.length<=So?e:e.slice(0,So-1)+"\u2026",xt=e=>e.length?e.slice():void 0;var Vt=class extends as{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||ee(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new V(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,hasHeadMethod:y=!0,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let x of typeof s=="string"?[s]:s)this.addServer({url:x});let S=(x,z,P)=>{let b={path:z,method:x,endpoint:P,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:k,shortDescription:H,scopes:N,inputSchema:M}=P,W=H?Jt(H):m&&k?Jt(k):void 0,Re=Nt(x,r.inputSources),Oe=this.#n(z,x,P.getOperationId(x)),Qe=Co({...b,schema:M}),se=go(P.security),Xe=To({...b,inputSources:Re,isHeader:c,security:se,request:Qe,description:i?.requestParameter?.call(null,{method:x,path:z,operationId:Oe})}),et={};for(let Y of Ce){let ie=P.getResponses(Y);for(let{mimeTypes:It,schema:rt,statusCodes:ot}of ie)for(let kt of ot)et[kt]=wo({...b,variant:Y,schema:rt,mimeTypes:It,statusCode:kt,hasMultipleStatusCodes:ie.length>1||ot.length>1,description:i?.[`${Y}Response`]?.call(null,{method:x,path:z,operationId:Oe,statusCode:kt})})}let tt=Re.includes("body")?Io({...b,request:Qe,paramNames:Ao.pluck("name",Xe),schema:M,mimeType:E[P.requestType],description:i?.requestBody?.call(null,{method:x,path:z,operationId:Oe})}):void 0,Et=Eo(vo(se,Re),N,Y=>{let ie=this.#s(Y);return this.addSecurityScheme(ie,Y),ie}),Ct={operationId:Oe,summary:W,description:k,deprecated:P.isDeprecated||void 0,tags:xt(P.tags),parameters:xt(Xe),requestBody:tt,security:xt(Et),responses:et};this.addPath(Oo(z),{[x]:Ct})};ze({routing:t,onEndpoint:y?ft(S):S}),d&&(this.rootDoc.tags=ko(d))}};import{createRequest as ps,createResponse as cs}from"node-mocks-http";var ds=e=>ps({...e,headers:{"content-type":E.json,...e?.headers}}),ms=e=>cs(e),ls=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Hr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},zo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ds(e),s=ms({req:n,...t});s.req=t?.req||n,n.res=s;let i=ls(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},us=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=zo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},fs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=he}}=zo(r),d=st(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:Q(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import vt from"typescript";import{z as qs}from"zod";import*as Lo from"ramda";import J from"typescript";import*as $ from"ramda";import u from"typescript";var a=u.factory,St=[a.createModifier(u.SyntaxKind.ExportKeyword)],ys=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ge={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Gt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Wt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},gs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yt=e=>typeof e=="string"&&gs.test(e)?a.createIdentifier(e):T(e),bt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),Rt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ne=e=>Object.entries(e).map(([t,r])=>Rt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Qt=(e,t=[])=>a.createConstructorDeclaration(Ge.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&$.map(f,t)):e,Xt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Z=e=>{let t=new Map;for(let r of e)t.set(xs(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},Se=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Yt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?Z([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=$.reject($.isNil,[o?"@deprecated":void 0,n]);return p.length?Gt(i,p.join(" ")):i},er=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),tr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),A=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&St,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),rr=(e,t)=>_(e,Z($.map(j,t)),{expose:!0}),_=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?St:void 0,e,n&&ir(n),t);return o?Gt(s,o):s},No=(e,t)=>a.createPropertyDeclaration(Ge.public,e,void 0,f(t),void 0),or=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ge.public,void 0,e,void 0,o&&ir(o),t,n,a.createBlock(r)),nr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(St,e,r&&ir(r),void 0,t),sr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Ot=e=>f(Promise.name,[e]),Tt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?St:void 0,e,void 0,void 0,t);return o?Gt(n,o):n},ir=e=>(Array.isArray(e)?e.map(t=>$.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 a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),be=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?ys:void 0,void 0,Array.isArray(e)?$.map(Rt,e):Ne(e),void 0,void 0,t),w=e=>e,We=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),v=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Me=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Pt=(e,t)=>f("Extract",[e,t]),ar=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),q=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),Mo=e=>Z([f(e),Ot(e)]),pr=(e,t)=>a.createFunctionTypeNode(void 0,Ne(e),f(t)),T=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),j=e=>a.createLiteralTypeNode(T(e)),hs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],xs=e=>hs.includes(e.kind);var wt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=rr("Method",yr);someOfType=_("SomeOf",q("T",sr("T")),{params:["T"]});requestType=_("Request",sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>rr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Tt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Se(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>A("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Yt(t),a.createArrayLiteralExpression(Lo.map(T,r))))),{expose:!0});makeImplementationType=()=>_(this.#e.implementationType,pr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:J.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Ot(J.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:J.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>A(this.#e.parseRequestFn,be({[this.#e.requestParameter.text]:J.SyntaxKind.StringKeyword},a.createAsExpression(v(this.#e.requestParameter,w("split"))(a.createRegularExpressionLiteral("/ (.+)/"),T(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>A(this.#e.substituteFn,be({[this.#e.pathParameter.text]:J.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt},a.createBlock([A(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],J.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([ar(this.#e.pathParameter,v(this.#e.pathParameter,w("replace"))(bt(":",[this.#e.keyParameter]),be([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>or(this.#e.provideMethod,Ne({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:q(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[A(tr(this.#e.methodParameter,this.#e.pathParameter),v(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(v(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(v(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Ot(q(this.interfaces.response,"K"))});makeClientClass=t=>nr(t,[Qt([Rt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ge.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>bt("?",[Me(URLSearchParams.name,t)]);#o=()=>Me(URL.name,bt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),T(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(w("method"),v(this.#e.methodParameter,w("toUpperCase"))()),r=a.createPropertyAssignment(w("headers"),We(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(T("Content-Type"),T(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(w("body"),We(this.#e.hasBodyConst,v(JSON[Symbol.toStringTag],w("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=A(this.#e.responseConst,a.createAwaitExpression(v(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=A(this.#e.hasBodyConst,a.createLogicalNot(v(a.createArrayLiteralExpression([T("get"),T("head"),T("delete")]),w("includes"))(this.#e.methodParameter))),i=A(this.#e.searchParamsConst,We(this.#e.hasBodyConst,T(""),this.#r(this.#e.paramsArgument))),p=A(this.#e.contentTypeConst,v(this.#e.responseConst,w("headers"),w("get"))(T("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(J.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=A(this.#e.isJsonConst,v(this.#e.contentTypeConst,w("startsWith"))(T(E.json))),m=a.createReturnStatement(v(this.#e.responseConst,We(this.#e.isJsonConst,T(w("json")),T(w("text"))))());return A(this.#e.defaultImplementationConst,be([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>Qt(Ne({request:"K",params:q(this.interfaces.input,"K")}),[A(tr(this.#e.pathParameter,this.#e.restConst),v(this.#e.substituteFn)(a.createElementAccessExpression(v(this.#e.parseRequestFn)(this.#e.requestParameter),T(1)),this.#e.paramsArgument)),A(this.#e.searchParamsConst,this.#r(this.#e.restConst)),ar(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Me("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Se(w("event"),t)]);#i=()=>or(this.#e.onMethod,Ne({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:pr({[this.#e.dataParameter.text]:q(Pt("R",er(this.#s("E"))),j(w("data")))},Mo(J.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(v(a.createThis(),this.#e.sourceProp,w("addEventListener"))(this.#e.eventParameter,be([this.#e.msgParameter],v(this.#e.handlerParameter)(v(JSON[Symbol.toStringTag],w("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),w("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:q("R",j(w("event")))}});makeSubscriptionClass=t=>nr(t,[No(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Pt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(J.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Pt(q(this.interfaces.positive,"K"),er(this.#s(J.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[A(this.#e.clientConst,Me(t)),v(this.#e.clientConst,this.#e.provideMethod)(T("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",T("10"))])),v(Me(r,T("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(T("time"),be(["time"],a.createBlock([])))]};import*as I from"ramda";import h from"typescript";import{globalRegistry as bs}from"zod";import{getBrand as Ss}from"@express-zod-api/zod-plugin";var cr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=Ss(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>cr(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:D}=h,Rs={[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},dr={name:I.path(["name","text"]),type:I.path(["type"]),optional:I.path(["questionToken"])},Os=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(h.SyntaxKind.UndefinedKeyword):j(r));return t.length===1?t[0]:Z(t)},Ts=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(X(p)){r.unshift(p);break}i+=p??""}return i},n=D.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?D.createTemplateMiddle:D.createTemplateTail;s.push(D.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?D.createTemplateLiteralType(n,s):j(n.text)},Ps=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=bs.get(p)||{};return Se(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return D.createTypeLiteralNode(s)};return vr(e,{io:t?"output":"input"})?o(e,n):n()},ws=({_zod:{def:e}},{next:t})=>D.createArrayTypeNode(t(e.element)),vs=({_zod:{def:e}})=>Z(Object.values(e.entries).map(j)),Es=({_zod:{def:e}},{next:t})=>Z(e.options.map(t)),Cs=e=>Rs?.[e.kind],Is=({_zod:{def:e}},{next:t})=>Z([t(e.innerType),j(null)]),ks=({_zod:{def:e}},{next:t})=>D.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:D.createRestTypeNode(t(e.rest)))),As=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),zs=I.tryCatch(e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let t=I.chain(I.prop("members"),e),r=I.uniqWith((...o)=>{if(!I.eqBy(dr.name,...o))return!1;if(I.both(I.eqBy(dr.type),I.eqBy(dr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return D.createTypeLiteralNode(r)},(e,t)=>D.createIntersectionTypeNode(t)),Ns=({_zod:{def:e}},{next:t})=>zs([e.left,e.right].map(t)),F=e=>()=>f(e),Ye=({_zod:{def:e}},{next:t})=>t(e.innerType),jo=e=>f(e?h.SyntaxKind.UnknownKeyword:h.SyntaxKind.AnyKeyword),Ms=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!X(o,"transform"))return t(o);let s=t(n),i=it(o,Cs(s)),p={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 f(i&&p[i]||jo(r))},Ls=()=>j(null),js=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Hs=()=>f("Buffer"),Bs=(e,{next:t})=>t(e._zod.def.shape.raw),Ks={string:F(h.SyntaxKind.StringKeyword),number:F(h.SyntaxKind.NumberKeyword),bigint:F(h.SyntaxKind.BigIntKeyword),boolean:F(h.SyntaxKind.BooleanKeyword),any:F(h.SyntaxKind.AnyKeyword),undefined:F(h.SyntaxKind.UndefinedKeyword),[le]:F(h.SyntaxKind.StringKeyword),[ue]:F(h.SyntaxKind.StringKeyword),never:F(h.SyntaxKind.NeverKeyword),void:F(h.SyntaxKind.UndefinedKeyword),unknown:F(h.SyntaxKind.UnknownKeyword),null:Ls,array:ws,tuple:ks,record:As,object:Ps,literal:Os,template_literal:Ts,intersection:Ns,union:Es,default:Ye,enum:vs,optional:Ye,nonoptional:Ye,nullable:Is,catch:Ye,pipe:Ms,lazy:js,readonly:Ye,[me]:Hs,[B]:Bs},mr=(e,{brandHandling:t,ctx:r})=>cr(e,{rules:{...t,...Ks},onMissing:({},{isResponse:o})=>jo(o),ctx:r});var lr=class extends wt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=j(null);this.#t.set(t,_(o,n)),this.#t.set(t,_(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=qs.undefined(),hasHeadMethod:d=!0}){super(i);let c={makeAlias:this.#o.bind(this)},m={brandHandling:r,ctx:{...c,isResponse:!1}},y={brandHandling:r,ctx:{...c,isResponse:!0}},g=(S,x,z)=>{let P=ee.bind(null,S,x),{isDeprecated:b,inputSchema:k,tags:H}=z,N=`${S} ${x}`,M=_(P("input"),mr(k,m),{comment:N});this.#e.push(M);let W=Ce.reduce((Qe,se)=>{let Xe=z.getResponses(se),et=Ho.chain(([Et,{schema:Ct,mimeTypes:Y,statusCodes:ie}])=>{let It=at(S,Y),rt=_(P(se,"variant",`${Et+1}`),mr(It?Ct:p,y),{comment:N});return this.#e.push(rt),ie.map(ot=>Se(ot,rt.name))},Array.from(Xe.entries())),tt=Tt(P(se,"response","variants"),et,{comment:N});return this.#e.push(tt),Object.assign(Qe,{[se]:tt})},{});this.paths.add(x);let Re=j(N),Oe={input:f(M.name),positive:this.someOf(W.positive),negative:this.someOf(W.negative),response:Z([q(this.interfaces.positive,Re),q(this.interfaces.negative,Re)]),encoded:a.createIntersectionTypeNode([f(W.positive.name),f(W.negative.name)])};this.registry.set(N,{isDeprecated:b,store:Oe}),this.tags.set(N,H)};ze({routing:t,onEndpoint:d?ft(g):g}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Wt(r,t)).join(`
|
|
19
19
|
`):void 0}print(t){let r=this.#n(t),o=r&&vt.addSyntheticLeadingComment(vt.addSyntheticLeadingComment(a.createEmptyStatement(),vt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),vt.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
-
${r}`);return this.#e.concat(o||[]).map((n,s)=>
|
|
20
|
+
${r}`);return this.#e.concat(o||[]).map((n,s)=>Wt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await ke("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};import{z as Le}from"zod";var Ko=(e,t)=>Le.object({data:t,event:Le.literal(e),id:Le.string().optional(),retry:Le.int().positive().optional()}),Fs=(e,t,r)=>Ko(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Ds=1e4,Bo=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Us=e=>new U({handler:async({response:t})=>setTimeout(()=>Bo(t),Ds)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Bo(t),t.write(Fs(e,r,o),"utf-8"),t.flush?.()}}}),$s=e=>new ge({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Ko(o,n));return{mimeType:E.sse,schema:r.length?Le.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Le.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Pe(r);De(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(ye(i),"utf-8")}t.end()}}),ur=class extends xe{constructor(t){super($s(t)),this.middlewares=[Us(t)]}};var Zs={dateIn:gr,dateOut:hr,form:Sr,upload:br,raw:Or,buffer:pt};export{Ze as BuiltinLogger,_e as DependsOnMethod,Vt as Documentation,V as DocumentationError,xe as EndpointsFactory,ur as EventStreamFactory,G as InputValidationError,lr as Integration,U as Middleware,qe as MissingPeerError,Ke as OutputValidationError,ge as ResultHandler,fe as RoutingError,Je as ServeStatic,sn as arrayEndpointsFactory,Kt as arrayResultHandler,Ln as attachRouting,qo as createConfig,jn as createServer,nn as defaultEndpointsFactory,he as defaultResultHandler,Pe as ensureHttpError,Zs as ez,pe as getMessageFromError,us as testEndpoint,fs as testMiddleware};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "25.
|
|
3
|
+
"version": "25.2.0-beta.2",
|
|
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": {
|
|
@@ -37,7 +37,8 @@
|
|
|
37
37
|
"ansis": "^4.1.0",
|
|
38
38
|
"node-mocks-http": "^1.17.2",
|
|
39
39
|
"openapi3-ts": "^4.5.0",
|
|
40
|
-
"ramda": "^0.31.3"
|
|
40
|
+
"ramda": "^0.31.3",
|
|
41
|
+
"@express-zod-api/zod-plugin": "^1.0.0-beta.3"
|
|
41
42
|
},
|
|
42
43
|
"peerDependencies": {
|
|
43
44
|
"@types/compression": "^1.7.5",
|