express-zod-api 24.0.0-beta.2 → 24.0.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -5
- package/README.md +11 -9
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +10 -7
- package/dist/index.d.ts +10 -7
- package/dist/index.js +8 -8
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -18,18 +18,20 @@
|
|
|
18
18
|
- Now acts as an alias for `ZodType::meta({ examples })`;
|
|
19
19
|
- The argument has to be the output type of the schema (used to be the opposite):
|
|
20
20
|
- This change is only breaking for transforming schemas;
|
|
21
|
-
- In order to specify an
|
|
21
|
+
- In order to specify an example for an input schema the `.example()` method must be called before `.transform()`;
|
|
22
|
+
- The transforming proprietary schemas `ez.dateIn()` and `ez.dateOut()` now accept metadata as its argument:
|
|
23
|
+
- This allows to set examples before transformation (`ez.dateIn()`) and to avoid the examples "branding";
|
|
22
24
|
- Generating Documentation is mostly delegated to Zod 4 `z.toJSONSchema()`:
|
|
23
25
|
- The basic depiction of each schema is now natively performed by Zod 4;
|
|
24
26
|
- Express Zod API implements some overrides and improvements to fit it into OpenAPI 3.1 that extends JSON Schema;
|
|
25
27
|
- The `numericRange` option removed from `Documentation` class constructor argument;
|
|
26
|
-
- The `
|
|
27
|
-
- The `Depicter` type signature changed;
|
|
28
|
+
- The `Depicter` type signature changed: became a postprocessing function returning an overridden JSON Schema;
|
|
28
29
|
- The `optionalPropStyle` option removed from `Integration` class constructor:
|
|
29
30
|
- Use `.optional()` to add question mark to the object property as well as `undefined` to its type;
|
|
30
31
|
- Use `.or(z.undefined())` to add `undefined` to the type of the object property;
|
|
31
32
|
- Reasoning: https://x.com/colinhacks/status/1919292504861491252;
|
|
32
33
|
- `z.any()` and `z.unknown()` are not optional, details: https://v4.zod.dev/v4/changelog#changes-zunknown-optionality.
|
|
34
|
+
- The argument of `ResultHandler::handler` is now discriminated: either `output` or `error` is null, not both;
|
|
33
35
|
- The `getExamples()` public helper removed — use `.meta()?.examples` instead;
|
|
34
36
|
- Consider the automated migration using the built-in ESLint rule.
|
|
35
37
|
|
|
@@ -50,15 +52,25 @@ export default [
|
|
|
50
52
|
```
|
|
51
53
|
|
|
52
54
|
```diff
|
|
53
|
-
z.string()
|
|
55
|
+
input: z.string()
|
|
54
56
|
+ .example("123")
|
|
55
57
|
.transform(Number)
|
|
56
58
|
- .example("123")
|
|
57
|
-
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
```diff
|
|
62
|
+
- ez.dateIn().example("2021-12-31");
|
|
63
|
+
+ ez.dateIn({ examples: ["2021-12-31"] });
|
|
58
64
|
```
|
|
59
65
|
|
|
60
66
|
## Version 23
|
|
61
67
|
|
|
68
|
+
### v23.6.0
|
|
69
|
+
|
|
70
|
+
- Featuring `gracefulShutdown.beforeExit()` hook:
|
|
71
|
+
- The function to execute after the server was closed, but before terminating the process (can be asynchronous);
|
|
72
|
+
- The feature suggested by [@HeikoOsigus](https://github.com/HeikoOsigus).
|
|
73
|
+
|
|
62
74
|
### v23.5.0
|
|
63
75
|
|
|
64
76
|
- Integer number `format` in generated Documentation now also depends on the `numericRange` option:
|
package/README.md
CHANGED
|
@@ -84,6 +84,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
|
|
|
84
84
|
|
|
85
85
|
These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
|
|
86
86
|
|
|
87
|
+
[<img src="https://github.com/HeikoOsigus.png" alt="@HeikoOsigus" width="50px" />](https://github.com/HeikoOsigus)
|
|
87
88
|
[<img src="https://github.com/crgeary.png" alt="@crgeary" width="50px" />](https://github.com/crgeary)
|
|
88
89
|
[<img src="https://github.com/williamgcampbell.png" alt="@williamgcampbell" width="50px" />](https://github.com/williamgcampbell)
|
|
89
90
|
[<img src="https://github.com/gmorgen1.png" alt="@gmorgen1" width="50px" />](https://github.com/gmorgen1)
|
|
@@ -478,7 +479,7 @@ By the way, you can also refine the whole I/O object, for example in case you ne
|
|
|
478
479
|
const endpoint = endpointsFactory.build({
|
|
479
480
|
input: z
|
|
480
481
|
.object({
|
|
481
|
-
email: z.
|
|
482
|
+
email: z.email().optional(),
|
|
482
483
|
id: z.string().optional(),
|
|
483
484
|
otherThing: z.string().optional(),
|
|
484
485
|
})
|
|
@@ -561,7 +562,7 @@ in actual response by calling
|
|
|
561
562
|
which in turn calls
|
|
562
563
|
[toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString).
|
|
563
564
|
It is also impossible to transmit the `Date` in its original form to your endpoints within JSON. Therefore, there is
|
|
564
|
-
confusion with original method ~~z.date()~~ that
|
|
565
|
+
confusion with original method ~~z.date()~~ that is not recommended to use without transformations.
|
|
565
566
|
|
|
566
567
|
In order to solve this problem, the framework provides two custom methods for dealing with dates: `ez.dateIn()` and
|
|
567
568
|
`ez.dateOut()` for using within input and output schemas accordingly.
|
|
@@ -577,7 +578,7 @@ provides your endpoint handler or middleware with a `Date`. It supports the foll
|
|
|
577
578
|
```
|
|
578
579
|
|
|
579
580
|
`ez.dateOut()`, on the contrary, accepts a `Date` and provides `ResultHandler` with a `string` representation in ISO
|
|
580
|
-
format for the response transmission. Consider the following
|
|
581
|
+
format for the response transmission. Both schemas accept metadata as an argument. Consider the following example:
|
|
581
582
|
|
|
582
583
|
```typescript
|
|
583
584
|
import { z } from "zod/v4";
|
|
@@ -587,10 +588,10 @@ const updateUserEndpoint = defaultEndpointsFactory.build({
|
|
|
587
588
|
method: "post",
|
|
588
589
|
input: z.object({
|
|
589
590
|
userId: z.string(),
|
|
590
|
-
birthday: ez.dateIn(), // string -> Date in handler
|
|
591
|
+
birthday: ez.dateIn({ examples: ["1963-04-21"] }), // string -> Date in handler
|
|
591
592
|
}),
|
|
592
593
|
output: z.object({
|
|
593
|
-
createdAt: ez.dateOut(), // Date -> string in response
|
|
594
|
+
createdAt: ez.dateOut({ examples: ["2021-12-31"] }), // Date -> string in response
|
|
594
595
|
}),
|
|
595
596
|
handler: async ({ input }) => ({
|
|
596
597
|
createdAt: new Date("2022-01-22"), // 2022-01-22T00:00:00.000Z
|
|
@@ -957,7 +958,7 @@ export const submitFeedbackEndpoint = defaultEndpointsFactory.build({
|
|
|
957
958
|
method: "post",
|
|
958
959
|
input: ez.form({
|
|
959
960
|
name: z.string().min(1),
|
|
960
|
-
email: z.
|
|
961
|
+
email: z.email(),
|
|
961
962
|
message: z.string().min(1),
|
|
962
963
|
}),
|
|
963
964
|
});
|
|
@@ -1109,7 +1110,7 @@ new ResultHandler({
|
|
|
1109
1110
|
negative: [
|
|
1110
1111
|
{
|
|
1111
1112
|
statusCode: 409, // conflict: entity already exists
|
|
1112
|
-
schema: z.object({ status: z.literal("exists"), id: z.
|
|
1113
|
+
schema: z.object({ status: z.literal("exists"), id: z.int() }),
|
|
1113
1114
|
},
|
|
1114
1115
|
{
|
|
1115
1116
|
statusCode: [400, 500], // validation or internal error
|
|
@@ -1147,7 +1148,7 @@ const rawAcceptingEndpoint = defaultEndpointsFactory.build({
|
|
|
1147
1148
|
input: ez.raw({
|
|
1148
1149
|
/* the place for additional inputs, like route params, if needed */
|
|
1149
1150
|
}),
|
|
1150
|
-
output: z.object({ length: z.
|
|
1151
|
+
output: z.object({ length: z.int().nonnegative() }),
|
|
1151
1152
|
handler: async ({ input: { raw } }) => ({
|
|
1152
1153
|
length: raw.length, // raw is Buffer
|
|
1153
1154
|
}),
|
|
@@ -1167,6 +1168,7 @@ createConfig({
|
|
|
1167
1168
|
gracefulShutdown: {
|
|
1168
1169
|
timeout: 1000,
|
|
1169
1170
|
events: ["SIGINT", "SIGTERM"],
|
|
1171
|
+
beforeExit: /* async */ () => {},
|
|
1170
1172
|
},
|
|
1171
1173
|
});
|
|
1172
1174
|
```
|
|
@@ -1185,7 +1187,7 @@ import { EventStreamFactory } from "express-zod-api";
|
|
|
1185
1187
|
import { setTimeout } from "node:timers/promises";
|
|
1186
1188
|
|
|
1187
1189
|
const subscriptionEndpoint = new EventStreamFactory({
|
|
1188
|
-
time: z.
|
|
1190
|
+
time: z.int().positive(),
|
|
1189
1191
|
}).buildVoid({
|
|
1190
1192
|
input: z.object({}), // optional input schema
|
|
1191
1193
|
handler: async ({ options: { emit, isClosed } }) => {
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:(0,bt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var Jt=require("zod/v4");var Gt=class{},F=class extends Gt{#e;#t;#r;constructor({input:t=Jt.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Jt.z.ZodError?new G(o):o}}},je=class extends F{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 Le=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends Le{},St=class e extends Xe{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){let t=Dr(this.#e.inputSchema);if(t){let r=te(t);if(r===ce)return"upload";if(r===B)return"raw";if(r===Ge)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=Me.pluck("security",this.#e.middlewares||[]);return Me.reject(Me.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Wt.z.ZodError?new se(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof je))&&(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#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Wt.z.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){xt({...t,error:new ie(ae(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Bt(t),i={},p={output:{},error:null},d=ut(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:ae(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};var Vr=y(require("ramda"),1);var Jr=(e,t)=>{let r=Vr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>Ir(s,n),o)};var C=require("zod/v4");var Ze={positive:200,negative:400},$e=Object.keys(Ze);var Yt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},le=class extends Yt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Vt(this.#e,{variant:"positive",args:[t],statusCodes:[Ze.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Vt(this.#t,{variant:"negative",args:[],statusCodes:[Ze.negative],mimeTypes:[E.json]})}},ue=new le({positive:e=>{let{examples:t=[]}=C.globalRegistry.get(e)||{};!t.length&&q(e,"object")&&t.push(...ft(e)),t.length&&!C.globalRegistry.has(e)&&C.globalRegistry.add(e,{examples:t});let r=C.z.object({status:C.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:C.z.object({status:C.z.literal("error"),error:C.z.object({message:C.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Te(e);return Qe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Pe(i)}})}n.status(Ze.positive).json({status:"success",data:r})}}),Rt=new le({positive:e=>{let{examples:t=[]}=C.globalRegistry.get(e)||{},r=e instanceof C.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof C.z.ZodArray?e.shape.items:C.z.array(C.z.any());return t.reduce((o,n)=>M(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:C.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Te(r);return Qe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(Pe(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Ze.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var fe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new je(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=Qt.z.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,h=typeof o=="function"?o:()=>o,b=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new St({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:g,methods:m,getOperationId:h,inputSchema:Jr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Qt.z.object({}),handler:async o=>(await t(o),{})})}},Gr=new fe(ue),Wr=new fe(Rt);var ro=y(require("ansis"),1),oo=require("node:util"),er=require("node:perf_hooks");var Y=require("ansis"),Yr=y(require("ramda"),1);var Xt={debug:Y.blue,info:Y.green,warn:(0,Y.hex)("#FFA500"),error:Y.red,ctx:Y.cyanBright},Ot={debug:10,info:20,warn:30,error:40},Qr=e=>M(e)&&Object.keys(Ot).some(t=>t in e),Xr=e=>e in Ot,eo=(e,t)=>Ot[e]<Ot[t],zn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),He=Yr.memoizeWith((e,t)=>`${e}${t}`,zn),to=e=>e<1e-6?He("nanosecond",3).format(e/1e-6):e<.001?He("nanosecond").format(e/1e-6):e<1?He("microsecond").format(e/.001):e<1e3?He("millisecond").format(e):e<6e4?He("second",2).format(e/1e3):He("minute",2).format(e/6e4);var Ke=class e{config;constructor({color:t=ro.default.isSupported(),level:r=Se()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,oo.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...i},color:p}=this.config;if(n==="silent"||eo(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Xt.ctx(s):s),d.push(p?`${Xt[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=er.performance.now();return()=>{let o=er.performance.now()-r,{message:n,severity:s="debug",formatter:i=to}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var no=y(require("ramda"),1);var qe=class e extends Le{#e;constructor(t){super(),this.#e=t}get entries(){let t=no.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)}};var so=y(require("express"),1),Be=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,so.default.static(...this.#e))}};var et=y(require("express"),1),Io=y(require("node:http"),1),No=y(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new Ce(e)};var mo=y(require("http-errors"),1);var tr=require("zod/v4");var R=y(require("ramda"),1);var jn=e=>e.type==="object",Ln=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")}),Mn=R.pipe(Object.keys,R.without(["type","properties","required","examples","description"]),R.isEmpty),io=R.pair(!0),Ue=(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"&&Mn(p)))throw new Error("Can not merge");return R.pair(s,p)})),i.anyOf&&r.push(...R.map(io,i.anyOf)),i.oneOf&&r.push(...R.map(io,i.oneOf)),i.examples?.length&&(s?o.examples=R.concat(o.examples||[],i.examples):o.examples=xe(o.examples?.filter(M)||[],i.examples.filter(M),([p,d])=>R.mergeDeepRight(p,d))),!!jn(i)&&(i.properties&&(o.properties=(t==="throw"?Ln:R.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),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};var Tt=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=[tr.z.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=_t(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 $e)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(E.json))continue;let i=_t(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=lt(t);if(s.length===0)return;let i=n?.flat||Ue(tr.z.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 rr=["get","post","put","delete","patch"],ao=e=>rr.includes(e);var Zn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&ao(t)?[r,t]:[e]},$n=e=>e.trim().split("/").filter(Boolean).join("/"),po=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Zn(r);return[[t||""].concat($n(n)||[]).join("/"),o,s]}),Hn=(e,t)=>{throw new ne("Route with explicit method can only be assigned with Endpoint",e,t)},co=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ne(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},or=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ne("Route has a duplicate",e,t);r.add(o)},De=({routing:e,onEndpoint:t,onStatic:r})=>{let o=po(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Xe)if(p)or(p,s,n),co(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)or(c,s,n),t(i,s,c)}else if(p&&Hn(p,s),i instanceof Be)r&&i.apply(s,r);else if(i instanceof qe)for(let[d,c]of i.entries){let{methods:m}=c;or(d,s,n),co(d,s,m),t(c,s,d)}else o.unshift(...po(i,s))}};var lo=y(require("ramda"),1),uo=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),Kn=e=>({method:t},r,o)=>{let n=uo(e);r.set({Allow:n});let s=(0,mo.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},qn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":uo(e),"Access-Control-Allow-Headers":"content-type"}),nr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Se()?void 0:new Tt(t()),i=new Map;De({routing:o,onEndpoint:(c,m,h)=>{Se()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let b=n?.[c.requestType]||[],g=lo.pair(b,c);i.has(m)||i.set(m,new Map(r.cors?[["options",g]]:[])),i.get(m)?.set(h,g)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let h=Array.from(m.keys());for(let[b,[g,k]]of m){let A=async($,O)=>{let I=t($);if(r.cors){let N=qn(h),V=typeof r.cors=="function"?await r.cors({request:$,endpoint:k,logger:I,defaultHeaders:N}):N;O.set(V)}return k.execute({request:$,response:O,logger:I,config:r})};e[b](c,...g,A)}r.wrongMethodBehavior!==404&&d.set(c,Kn(h))}for(let[c,m]of d)e.all(c,m)};var Ro=y(require("http-errors"),1);var xo=require("node:timers/promises");var fo=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",yo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",go=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,ho=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),bo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var So=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(fo(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",ho);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(go(c)||yo(c))&&i(c);for await(let c of(0,xo.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(bo))};return{sockets:n,shutdown:()=>o??=d()}};var Oo=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:ae(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),To=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,Ro.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){xt({response:o,logger:s,error:new ie(ae(i),n)})}},Bn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Fn=e=>({log:e.debug.bind(e)}),Po=async({getLogger:e,config:t})=>{let r=await Fe("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:Fn(m)})(p,d,c)}),o&&i.push(Bn(o)),i},wo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Eo=({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[Ne]={logger:i}),s()},vo=e=>t=>t?.res?.locals[Ne]?.logger||e,ko=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
"use strict";var un=Object.create;var ct=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,hn=Object.prototype.hasOwnProperty;var bn=(e,t)=>{for(var r in t)ct(e,r,{get:t[r],enumerable:!0})},kr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of yn(t))!hn.call(e,n)&&n!==r&&ct(e,n,{get:()=>t[n],enumerable:!(o=fn(t,n))||o.enumerable});return e};var y=(e,t,r)=>(r=e!=null?un(gn(e)):{},kr(t||!e||!e.__esModule?ct(r,"default",{value:e,enumerable:!0}):r,e)),xn=e=>kr(ct({},"__esModule",{value:!0}),e);var Bs={};bn(Bs,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>Tt,DocumentationError:()=>J,EndpointsFactory:()=>fe,EventStreamFactory:()=>zt,InputValidationError:()=>G,Integration:()=>Nt,Middleware:()=>B,MissingPeerError:()=>Ne,OutputValidationError:()=>ie,ResultHandler:()=>le,RoutingError:()=>ae,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Jr,arrayResultHandler:()=>xt,attachRouting:()=>No,createConfig:()=>Ar,createServer:()=>zo,defaultEndpointsFactory:()=>Vr,defaultResultHandler:()=>ue,ensureHttpError:()=>Te,ez:()=>ln,getMessageFromError:()=>oe,testEndpoint:()=>en,testMiddleware:()=>tn});module.exports=xn(Bs);var L=y(require("ramda"),1),V=require("zod/v4");var Ce=Symbol.for("express-zod-api"),X=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Sn=V.z.core.$constructor("$EZBrandCheck",(e,t)=>{V.z.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),Rn=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},On=function(){return this.meta({deprecated:!0})},Tn=function(e){return this.meta({default:e})},Pn=function(e){return this.check(new Sn({brand:e,check:"$EZBrandCheck"}))},wn=function(e){let t=typeof e=="function"?e:L.pipe(L.toPairs,L.map(([s,i])=>L.pair(e[String(s)]||s,i)),L.fromPairs),r=t(L.map(L.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof V.z.ZodUnknown?V.z.looseObject:V.z.object)(r);return this.transform(t).pipe(n)};if(!(Ce in globalThis)){globalThis[Ce]=!0;for(let e of Object.keys(V.z)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=V.z[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{get(){return Rn.bind(this)}},deprecated:{get(){return On.bind(this)}},brand:{set(){},get(){return Pn.bind(this)}}})}Object.defineProperty(V.z.ZodDefault.prototype,"label",{get(){return Tn.bind(this)}}),Object.defineProperty(V.z.ZodObject.prototype,"remap",{get(){return wn.bind(this)}})}function Ar(e){return e}var Wt=require("zod/v4");var Le=y(require("ramda"),1),Jt=require("zod/v4");var me=y(require("ramda"),1),Ft=require("zod/v4");var Ie=require("zod/v4"),xe=Symbol("DateIn"),Cr=({examples:e,...t}={})=>Ie.z.union([Ie.z.iso.date(),Ie.z.iso.datetime(),Ie.z.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ie.z.date()).brand(xe).meta(t);var Ir=require("zod/v4"),Se=Symbol("DateOut"),Nr=({examples:e,...t}={})=>Ir.z.date().transform(r=>r.toISOString()).brand(Se).meta({...t,examples:e});var K=y(require("ramda"),1),Ve=require("zod/v4");var E={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var $t=/:([A-Za-z0-9_]+)/g,dt=e=>e.match($t)?.map(t=>t.slice(1))||[],En=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Ht={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},vn=["body","query","params"],Kt=e=>e.method.toLowerCase(),mt=(e,t={})=>{let r=Kt(e);return r==="options"?{}:(t[r]||Ht[r]||vn).filter(o=>o==="files"?En(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},re=e=>e instanceof Error?e:e instanceof Ve.z.ZodError?new Ve.z.ZodRealError(e.issues):new Error(String(e)),oe=e=>e instanceof Ve.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof ie?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,ne=(e,t)=>e._zod.def.type===t,Re=(e,t,r)=>e.length&&t.length?K.xprod(e,t).map(r):e.concat(t),qt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=K.chain(o=>o.split(/[^A-Z0-9]/gi),e);return K.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(qt).join("")},lt=K.tryCatch((e,t)=>typeof Ve.z.parse(e,t),K.always(void 0)),M=e=>typeof e=="object"&&e!==null,Oe=K.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ae=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},J=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.`}},Je=class extends Error{name="IOSchemaError"},ut=class extends Je{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},ie=class extends Je{constructor(r){super(oe(r),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends Je{constructor(r){super(oe(r),{cause:r});this.cause=r}name="InputValidationError"},pe=class extends Error{constructor(r,o){super(oe(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ne=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Bt=require("zod/v4"),Ge=Symbol("Form"),zr=e=>(e instanceof Bt.z.ZodObject?e:Bt.z.object(e)).brand(Ge);var jr=require("zod/v4"),ce=Symbol("Upload"),Lr=()=>jr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(ce);var Zr=require("zod/v4");var We=require("zod/v4"),de=Symbol("File"),Mr=We.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),kn={buffer:()=>Mr.brand(de),string:()=>We.z.string().brand(de),binary:()=>Mr.or(We.z.string()).brand(de),base64:()=>We.z.base64().brand(de)};function ft(e){return kn[e||"string"]()}var q=Symbol("Raw"),$r=Zr.z.object({raw:ft("buffer")}),An=e=>$r.extend(e).brand(q);function Hr(e){return e?An(e):$r.brand(q)}var Kr=(e,{io:t,condition:r})=>me.tryCatch(()=>{Ft.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new ut(o)}})},o=>o.cause)(),qr=(e,{io:t})=>{let o=[Ft.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];for(;o.length;){let n=o.shift();if(me.is(Object,n)){if(n.$ref==="#")return!0;o.push(...me.values(n))}me.is(Array,n)&&o.push(...me.values(n))}return!1},Br=e=>Kr(e,{condition:t=>{let r=X(t);return typeof r=="symbol"&&[ce,q,Ge].includes(r)},io:"input"}),Cn=["nan","symbol","map","set","bigint","void","promise","never"],Ut=(e,t)=>Kr(e,{io:t,condition:r=>{let o=X(r),{type:n}=r._zod.def;return!!(Cn.includes(n)||t==="input"&&(n==="date"||o===Se)||t==="output"&&(o===xe||o===q||o===ce))}});var gt=y(require("http-errors"),1);var Ye=y(require("http-errors"),1),Fr=y(require("ramda"),1),yt=require("zod/v4");var Dt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof yt.z.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new pe(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Qe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Te=e=>(0,Ye.isHttpError)(e)?e:(0,Ye.default)(e instanceof G?400:500,oe(e),{cause:e.cause||e}),Pe=e=>Oe()&&!e.expose?(0,Ye.default)(e.statusCode).message:e.message,Ur=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=yt.globalRegistry.get(o)||{};return Re(t,n.map(Fr.objOf(r)),([s,i])=>({...s,...i}))},[]);var ht=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=Pe((0,gt.default)(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:(0,gt.isHttpError)(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};var _t=require("zod/v4");var Vt=class{},B=class extends Vt{#e;#t;#r;constructor({input:t=_t.z.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof _t.z.ZodError?new G(o):o}}},ze=class extends B{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 je=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends je{},bt=class e extends Xe{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){let t=Br(this.#e.inputSchema);if(t){let r=X(t);if(r===ce)return"upload";if(r===q)return"raw";if(r===Ge)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=Le.pluck("security",this.#e.middlewares||[]);return Le.reject(Le.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Jt.z.ZodError?new ie(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof ze))&&(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#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Jt.z.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){ht({...t,error:new pe(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Kt(t),i={},p={output:{},error:null},d=mt(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};var Dr=y(require("ramda"),1),_r=(e,t)=>Dr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));var C=require("zod/v4");var Me={positive:200,negative:400},Ze=Object.keys(Me);var Gt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},le=class extends Gt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Dt(this.#e,{variant:"positive",args:[t],statusCodes:[Me.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Dt(this.#t,{variant:"negative",args:[],statusCodes:[Me.negative],mimeTypes:[E.json]})}},ue=new le({positive:e=>{let{examples:t=[]}=C.globalRegistry.get(e)||{};!t.length&&ne(e,"object")&&t.push(...Ur(e)),t.length&&!C.globalRegistry.has(e)&&C.globalRegistry.add(e,{examples:t});let r=C.z.object({status:C.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:C.z.object({status:C.z.literal("error"),error:C.z.object({message:C.z.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Te(e);return Qe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Pe(i)}})}n.status(Me.positive).json({status:"success",data:r})}}),xt=new le({positive:e=>{let{examples:t=[]}=C.globalRegistry.get(e)||{},r=e instanceof C.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof C.z.ZodArray?e.shape.items:C.z.array(C.z.any());return t.reduce((o,n)=>M(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:C.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Te(r);return Qe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(Pe(i))}if("items"in t&&Array.isArray(t.items))return void e.status(Me.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var fe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof B?t:new B(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new ze(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new B({handler:t})),this.resultHandler)}build({input:t=Wt.z.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,h=typeof o=="function"?o:()=>o,b=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new bt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:g,methods:m,getOperationId:h,inputSchema:_r(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Wt.z.object({}),handler:async o=>(await t(o),{})})}},Vr=new fe(ue),Jr=new fe(xt);var eo=y(require("ansis"),1),to=require("node:util"),Qt=require("node:perf_hooks");var W=require("ansis"),Gr=y(require("ramda"),1);var Yt={debug:W.blue,info:W.green,warn:(0,W.hex)("#FFA500"),error:W.red,ctx:W.cyanBright},St={debug:10,info:20,warn:30,error:40},Wr=e=>M(e)&&Object.keys(St).some(t=>t in e),Yr=e=>e in St,Qr=(e,t)=>St[e]<St[t],In=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),$e=Gr.memoizeWith((e,t)=>`${e}${t}`,In),Xr=e=>e<1e-6?$e("nanosecond",3).format(e/1e-6):e<.001?$e("nanosecond").format(e/1e-6):e<1?$e("microsecond").format(e/.001):e<1e3?$e("millisecond").format(e):e<6e4?$e("second",2).format(e/1e3):$e("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=eo.default.isSupported(),level:r=Oe()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return(0,to.inspect)(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...i},color:p}=this.config;if(n==="silent"||Qr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Yt.ctx(s):s),d.push(p?`${Yt[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=Qt.performance.now();return()=>{let o=Qt.performance.now()-r,{message:n,severity:s="debug",formatter:i=Xr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};var ro=y(require("ramda"),1);var Ke=class e extends je{#e;constructor(t){super(),this.#e=t}get entries(){let t=ro.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)}};var oo=y(require("express"),1),qe=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,oo.default.static(...this.#e))}};var et=y(require("express"),1),Ao=y(require("node:http"),1),Co=y(require("node:https"),1);var Be=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new Ne(e)};var po=y(require("http-errors"),1);var Xt=require("zod/v4");var S=y(require("ramda"),1);var Nn=e=>e.type==="object",zn=S.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return S.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")}),jn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description"]),S.isEmpty),no=S.pair(!0),Fe=(e,t="coerce")=>{let r=[S.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"&&jn(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(no,i.anyOf)),i.oneOf&&r.push(...S.map(no,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=Re(o.examples?.filter(M)||[],i.examples.filter(M),([p,d])=>S.mergeDeepRight(p,d))),!!Nn(i)&&(r.push([s,{examples:Ln(i)}]),i.properties&&(o.properties=(t==="throw"?zn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),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},Ln=e=>Object.entries(e.properties||{}).reduce((t,[r,{examples:o=[]}])=>Re(t,o.map(S.objOf(r)),([n,s])=>({...n,...s})),[]);var Rt=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=[Xt.z.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=Ut(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=Ut(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=dt(t);if(s.length===0)return;let i=n?.flat||Fe(Xt.z.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 er=["get","post","put","delete","patch"],so=e=>er.includes(e);var Mn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&so(t)?[r,t]:[e]},Zn=e=>e.trim().split("/").filter(Boolean).join("/"),io=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Mn(r);return[[t||""].concat(Zn(n)||[]).join("/"),o,s]}),$n=(e,t)=>{throw new ae("Route with explicit method can only be assigned with Endpoint",e,t)},ao=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ae(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},tr=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ae("Route has a duplicate",e,t);r.add(o)},Ue=({routing:e,onEndpoint:t,onStatic:r})=>{let o=io(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Xe)if(p)tr(p,s,n),ao(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)tr(c,s,n),t(i,s,c)}else if(p&&$n(p,s),i instanceof qe)r&&i.apply(s,r);else if(i instanceof Ke)for(let[d,c]of i.entries){let{methods:m}=c;tr(d,s,n),ao(d,s,m),t(c,s,d)}else o.unshift(...io(i,s))}};var co=y(require("ramda"),1),mo=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),Hn=e=>({method:t},r,o)=>{let n=mo(e);r.set({Allow:n});let s=(0,po.default)(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},Kn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":mo(e),"Access-Control-Allow-Headers":"content-type"}),rr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Oe()?void 0:new Rt(t()),i=new Map;Ue({routing:o,onEndpoint:(c,m,h)=>{Oe()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let b=n?.[c.requestType]||[],g=co.pair(b,c);i.has(m)||i.set(m,new Map(r.cors?[["options",g]]:[])),i.get(m)?.set(h,g)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let h=Array.from(m.keys());for(let[b,[g,k]]of m){let A=async(Z,O)=>{let I=t(Z);if(r.cors){let N=Kn(h),_=typeof r.cors=="function"?await r.cors({request:Z,endpoint:k,logger:I,defaultHeaders:N}):N;O.set(_)}return k.execute({request:Z,response:O,logger:I,config:r})};e[b](c,...g,A)}r.wrongMethodBehavior!==404&&d.set(c,Hn(h))}for(let[c,m]of d)e.all(c,m)};var xo=y(require("http-errors"),1);var ho=require("node:timers/promises");var lo=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",uo=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",fo=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,yo=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),go=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var bo=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(lo(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",yo);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(fo(c)||uo(c))&&i(c);for await(let c of(0,ho.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(go))};return{sockets:n,shutdown:()=>o??=d()}};var So=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:re(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Ro=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=(0,xo.default)(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){ht({response:o,logger:s,error:new pe(re(i),n)})}},qn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Bn=e=>({log:e.debug.bind(e)}),Oo=async({getLogger:e,config:t})=>{let r=await Be("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:Bn(m)})(p,d,c)}),o&&i.push(qn(o)),i},To=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Po=({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()},wo=e=>t=>t?.res?.locals[Ce]?.logger||e,Eo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),vo=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=bo(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};var $=require("ansis"),ko=e=>{if(e.columns<132)return;let t=(0,$.italic)("Proudly supports transgender community.".padStart(109)),r=(0,$.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=(0,$.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),n=(0,$.italic)("for Ashley".padEnd(20)),s=(0,$.hex)("#F5A9B8"),i=(0,$.hex)("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill($.whiteBright,5,7).fill(s,7,9).fill(i,9,12).fill($.gray,12,13),d=`
|
|
4
4
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
5
5
|
888 d88P 888 d88888 888 Y88b 888
|
|
6
6
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -15,9 +15,9 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((c,m)=>p[m]?p[m](c):c).join(`
|
|
18
|
-
`))};var zo=e=>{e.startupLogo!==!1&&Co(process.stdout);let t=e.errorHandler||ue,r=Qr(e.logger)?e.logger:new Ke(e.logger);r.debug("Running",{build:"v24.0.0-beta.2 (CJS)",env:process.env.NODE_ENV||"development"}),ko(r);let o=Eo({logger:r,config:e}),s={getLogger:vo(r),errorHandler:t},i=To(s),p=Oo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},jo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=zo(e);return nr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Lo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=zo(e),p=(0,et.default)().disable("x-powered-by").use(i);if(e.compression){let b=await Fe("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||et.default.json()],raw:[e.rawParser||et.default.raw(),wo],form:[e.formParser||et.default.urlencoded()],upload:e.upload?await Po({config:e,getLogger:o}):[]};nr({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,g)=>()=>b.listen(g,()=>r.info("Listening",g)),h=[];if(e.http){let b=Io.default.createServer(p);c.push(b),h.push(m(b,e.http.listen))}if(e.https){let b=No.default.createServer(e.https.options,p);c.push(b),h.push(m(b,e.https.listen))}return e.gracefulShutdown&&Ao({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(b=>b())}};var Xo=require("openapi3-ts/oas31"),en=y(require("ramda"),1);var S=y(require("ramda"),1);var Mo=e=>M(e)&&"or"in e,Zo=e=>M(e)&&"and"in e,sr=e=>!Zo(e)&&!Mo(e),$o=e=>{let t=S.filter(sr,e),r=S.chain(S.prop("and"),S.filter(Zo,e)),[o,n]=S.partition(sr,r),s=S.concat(t,o),i=S.filter(Mo,e);return S.map(S.prop("or"),S.concat(i,n)).reduce((d,c)=>xe(d,S.map(m=>sr(m)?[m]:m.and,c),([m,h])=>S.concat(m,h)),S.reject(S.isEmpty,[s]))};var ye=require("openapi3-ts/oas31"),l=y(require("ramda"),1),tt=require("zod/v4");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 Ko=50,Bo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Fo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Uo=e=>e.replace(Kt,t=>`{${t.slice(1)}}`),Dn=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},_n=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),Vn=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Jn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ue(e,"throw")},(e,{jsonSchema:t})=>t),Gn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ns(t.type)})},qo=e=>e in Fo,Wn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Yn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Qn=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{if(r||!q(e,"object"))return t;let{required:o=[]}=t,n=[];for(let s of o){let i=e._zod.def.shape[s];i&&!gt(i,{isResponse:r})&&n.push(s)}return{...t,required:n}},we=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(qo):t&&qo(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(we));return s&&(p.not=we(s)),p},Xn=({zodSchema:e},t)=>{if(t.isResponse)throw new J("Please use ez.dateOut() for output.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Bo}},o=tt.globalRegistry.get(e)?.examples?.filter(n=>n instanceof Date).map(n=>n.toISOString());return o?.length&&(r.examples=o),r},es=({jsonSchema:{examples:e}},t)=>{if(!t.isResponse)throw new J("Please use ez.dateIn() for input.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Bo}};return e?.length&&(r.examples=e),r},ts=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),rs=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},os=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Fo?.[t]},ns=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ss=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!q(o,"transform"))return t;let s=we(pr(n,{ctx:r}));if((0,ye.isSchemaObject)(s))if(r.isResponse){let i=yt(o,os(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},is=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},ir=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,as=(e,t)=>t?.includes(e)||e.startsWith("x-")||Ho.includes(e),Do=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Ue(r),m=lt(e),h=o.includes("query"),b=o.includes("params"),g=o.includes("headers"),k=O=>b&&m.includes(O),A=l.chain(l.filter(O=>O.type==="header"),p??[]).map(({name:O})=>O),$=O=>g&&(i?.(O,t,e)??as(O,A));return Object.entries(c.properties).reduce((O,[I,N])=>{let V=k(I)?"path":$(I)?"header":h?"query":void 0;if(!V)return O;let j=we(N),re=s==="components"?n(N,j,pe(d,I)):j;return O.concat({name:I,in:V,deprecated:N.deprecated,required:c.required?.includes(I)||!1,description:j.description||d,schema:re,examples:ir((0,ye.isSchemaObject)(j)&&j.examples?.length?j.examples:l.pluck(I,c.examples?.filter(l.both(M,l.has(I)))||[]))})},[])},ar={nullable:Gn,union:Vn,bigint:ts,intersection:Jn,tuple:rs,pipe:ss,literal:Yn,enum:Wn,object:Qn,[Re]:Xn,[Oe]:es,[ce]:Dn,[de]:_n,[B]:is},ps=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,ye.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i,we(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},pr=(e,{ctx:t,rules:r=ar})=>{let{$defs:o={},properties:n={}}=tt.z.toJSONSchema(tt.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=te(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 ps(n.subject,o,t)},_o=(e,t)=>{if((0,ye.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=_o(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]},Vo=({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} ${Ft(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=we(pr(r,{rules:{...c,...ar},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,ye.isSchemaObject)(h)&&h.examples&&(b.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,pe(m)):h,examples:ir(b)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},cs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ds=({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},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),ls=({name:e})=>({type:"apiKey",in:"cookie",name:e}),us=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),fs=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Jo=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?cs(o):o.type==="input"?ds(o,t):o.type==="header"?ms(o):o.type==="cookie"?ls(o):o.type==="openid"?us(o):fs(o);return e.map(o=>o.map(r))},Go=(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:[]})},{})),Wo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>pr(e,{rules:{...t,...ar},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Yo=({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]=_o(we(o),p),h=[];(0,ye.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,pe(d)):c,examples:ir(h.length?h:Ue(o).examples?.filter(k=>M(k)&&!Array.isArray(k)).map(l.omit(p))||[])},g={description:d,content:{[n]:b}};return(m||n===E.raw)&&(g.required=!0),g},Qo=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)},[]),cr=e=>e.length<=Ko?e:e.slice(0,Ko-1)+"\u2026",Pt=e=>e.length?e.slice():void 0;var wt=class extends Xo.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||pe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new J(`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,composition:h="inline"}){super(),this.addInfo({title:o,version:n});for(let g of typeof s=="string"?[s]:s)this.addServer({url:g});De({routing:t,onEndpoint:(g,k,A)=>{let $={path:k,method:A,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:I,scopes:N,inputSchema:V}=g,j=I?cr(I):m&&O?cr(O):void 0,re=r.inputSources?.[A]||qt[A],Ae=this.#n(k,A,g.getOperationId(A)),st=Wo({...$,schema:V}),he=$o(g.security),it=Do({...$,inputSources:re,isHeader:c,security:he,request:st,description:i?.requestParameter?.call(null,{method:A,path:k,operationId:Ae})}),at={};for(let oe of $e){let be=g.getResponses(oe);for(let{mimeTypes:ct,schema:$t,statusCodes:kr}of be)for(let Ht of kr)at[Ht]=Vo({...$,variant:oe,schema:$t,mimeTypes:ct,statusCode:Ht,hasMultipleStatusCodes:be.length>1||kr.length>1,description:i?.[`${oe}Response`]?.call(null,{method:A,path:k,operationId:Ae,statusCode:Ht})})}let pt=re.includes("body")?Yo({...$,request:st,paramNames:en.pluck("name",it),schema:V,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:A,path:k,operationId:Ae})}):void 0,Mt=Go(Jo(he,re),N,oe=>{let be=this.#s(oe);return this.addSecurityScheme(be,oe),be}),Zt={operationId:Ae,summary:j,description:O,deprecated:g.isDeprecated||void 0,tags:Pt(g.tags),parameters:Pt(it),requestBody:pt,security:Pt(Mt),responses:at};this.addPath(Uo(k),{[A]:Zt})}}),d&&(this.rootDoc.tags=Qo(d))}};var Et=require("node-mocks-http");var ys=e=>(0,Et.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),gs=e=>(0,Et.createResponse)(e),hs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},tn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ys(e),s=gs({req:n,...t});s.req=t?.req||n,n.res=s;let i=hs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},rn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=tn(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},on=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=ue}}=tn(r),d=ut(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:ae(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var dn=y(require("ramda"),1),nt=y(require("typescript"),1),mn=require("zod/v4");var pn=y(require("ramda"),1),D=y(require("typescript"),1);var Q=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,vt=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],bs=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],rt={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},dr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),mr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},xs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,lr=e=>typeof e=="string"&&xs.test(e)?a.createIdentifier(e):w(e),kt=(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)))),At=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),_e=e=>Object.entries(e).map(([t,r])=>At(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),ur=(e,t=[])=>a.createConstructorDeclaration(rt.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?a.createTypeReferenceNode(e,t&&Q.map(f,t)):e,fr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ee=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,lr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=Q.reject(Q.isNil,[o?"@deprecated":void 0,n]);return p.length?dr(i,p.join(" ")):i},yr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),gr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),z=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&vt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),hr=(e,t)=>X(e,a.createUnionTypeNode(Q.map(K,t)),{expose:!0}),X=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?vt:void 0,e,n&&Rr(n),t);return o?dr(s,o):s},nn=(e,t)=>a.createPropertyDeclaration(rt.public,e,void 0,f(t),void 0),br=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(rt.public,void 0,e,void 0,o&&Rr(o),t,n,a.createBlock(r)),xr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(vt,e,r&&Rr(r),void 0,t),Sr=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Ct=e=>f(Promise.name,[e]),It=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?vt:void 0,e,void 0,void 0,t);return o?dr(n,o):n},Rr=e=>(Array.isArray(e)?e.map(t=>Q.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)}),ve=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?bs:void 0,void 0,Array.isArray(e)?Q.map(At,e):_e(e),void 0,void 0,t),T=e=>e,ot=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.default.SyntaxKind.QuestionToken),t,a.createToken(u.default.SyntaxKind.ColonToken),r),P=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Ve=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Nt=(e,t)=>f("Extract",[e,t]),Or=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),U=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),sn=e=>a.createUnionTypeNode([f(e),Ct(e)]),Tr=(e,t)=>a.createFunctionTypeNode(void 0,_e(e),f(t)),w=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),K=e=>a.createLiteralTypeNode(w(e)),Ss=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],an=e=>Ss.includes(e.kind);var zt=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=hr("Method",rr);someOfType=X("SomeOf",U("T",Sr("T")),{params:["T"]});requestType=X("Request",Sr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>hr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>It(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ee(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>z("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(lr(t),a.createArrayLiteralExpression(pn.map(w,r))))),{expose:!0});makeImplementationType=()=>X(this.#e.implementationType,Tr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:D.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:fr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Ct(D.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:D.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>z(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:D.default.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),w(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>z(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:D.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:fr},a.createBlock([z(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],D.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([Or(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(kt(":",[this.#e.keyParameter]),ve([],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=()=>br(this.#e.provideMethod,_e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:U(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(gr(this.#e.methodParameter,this.#e.pathParameter),P(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(P(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(P(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Ct(U(this.interfaces.response,"K"))});makeClientClass=t=>xr(t,[ur([At(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:rt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>kt("?",[Ve(URLSearchParams.name,t)]);#o=()=>Ve(URL.name,kt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),w(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),ot(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(w("Content-Type"),w(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),ot(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=z(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=z(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=z(this.#e.searchParamsConst,ot(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=z(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(w("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(D.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=z(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(w(E.json))),m=a.createReturnStatement(P(this.#e.responseConst,ot(this.#e.isJsonConst,w(T("json")),w(T("text"))))());return z(this.#e.defaultImplementationConst,ve([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=()=>ur(_e({request:"K",params:U(this.interfaces.input,"K")}),[z(gr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),z(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Or(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Ve("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Ee(T("event"),t)]);#i=()=>br(this.#e.onMethod,_e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Tr({[this.#e.dataParameter.text]:U(Nt("R",yr(this.#s("E"))),K(T("data")))},sn(D.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],P(this.#e.handlerParameter)(P(JSON[Symbol.toStringTag],T("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),T("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:U("R",K(T("event")))}});makeSubscriptionClass=t=>xr(t,[nn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Nt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(D.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Nt(U(this.interfaces.positive,"K"),yr(this.#s(D.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,Ve(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(Ve(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),ve(["time"],a.createBlock([])))]};var v=y(require("ramda"),1),x=y(require("typescript"),1),cn=require("zod/v4");var Pr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=te(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Pr(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:_}=x.default,Rs={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},wr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Os=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):K(r));return t.length===1?t[0]:_.createUnionTypeNode(t)},Ts=(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}=cn.globalRegistry.get(p)||{};return Ee(i,r(p),{comment:d,isDeprecated:c,isOptional:gt(p,{isResponse:t})})});return _.createTypeLiteralNode(s)};return Ur(e,{io:t?"output":"input"})?o(e,n):n()},Ps=({_zod:{def:e}},{next:t})=>_.createArrayTypeNode(t(e.element)),ws=({_zod:{def:e}})=>_.createUnionTypeNode(Object.values(e.entries).map(K)),Es=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(an(n)?n.kind:n,n)}return _.createUnionTypeNode(Array.from(r.values()))},vs=e=>Rs?.[e.kind],ks=({_zod:{def:e}},{next:t})=>t(e.innerType),As=({_zod:{def:e}},{next:t})=>_.createUnionTypeNode([t(e.innerType),K(null)]),Cs=({_zod:{def:e}},{next:t})=>_.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:_.createRestTypeNode(t(e.rest)))),Is=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Ns=v.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(wr.name,...o))return!1;if(v.both(v.eqBy(wr.type),v.eqBy(wr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),zs=({_zod:{def:e}},{next:t})=>Ns([e.left,e.right].map(t)),ge=e=>()=>f(e),Er=({_zod:{def:e}},{next:t})=>t(e.innerType),js=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!q(o,"transform"))return t(o);let s=t(n),i=yt(o,vs(s)),p={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(i&&p[i]||x.default.SyntaxKind.AnyKeyword)},Ls=()=>K(null),Ms=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Zs=e=>{let t=f(x.default.SyntaxKind.StringKeyword),r=f("Buffer"),o=_.createUnionTypeNode([t,r]);return q(e,"string")?t:q(e,"union")?o:r},$s=(e,{next:t})=>t(e._zod.def.shape.raw),Hs={string:ge(x.default.SyntaxKind.StringKeyword),number:ge(x.default.SyntaxKind.NumberKeyword),bigint:ge(x.default.SyntaxKind.BigIntKeyword),boolean:ge(x.default.SyntaxKind.BooleanKeyword),any:ge(x.default.SyntaxKind.AnyKeyword),undefined:ge(x.default.SyntaxKind.UndefinedKeyword),[Re]:ge(x.default.SyntaxKind.StringKeyword),[Oe]:ge(x.default.SyntaxKind.StringKeyword),null:Ls,array:Ps,tuple:Cs,record:Is,object:Ts,literal:Os,intersection:zs,union:Es,default:Er,enum:ws,optional:ks,nullable:As,catch:Er,pipe:js,lazy:Ms,readonly:Er,[de]:Zs,[B]:$s},vr=(e,{brandHandling:t,ctx:r})=>Pr(e,{rules:{...t,...Hs},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var jt=class extends zt{#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=K(null);this.#t.set(t,X(o,n)),this.#t.set(t,X(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=mn.z.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};De({routing:t,onEndpoint:(b,g,k)=>{let A=pe.bind(null,k,g),{isDeprecated:$,inputSchema:O,tags:I}=b,N=`${k} ${g}`,V=X(A("input"),vr(O,c),{comment:N});this.#e.push(V);let j=$e.reduce((st,he)=>{let it=b.getResponses(he),at=dn.chain(([Mt,{schema:Zt,mimeTypes:oe,statusCodes:be}])=>{let ct=X(A(he,"variant",`${Mt+1}`),vr(oe?Zt:p,m),{comment:N});return this.#e.push(ct),be.map($t=>Ee($t,ct.name))},Array.from(it.entries())),pt=It(A(he,"response","variants"),at,{comment:N});return this.#e.push(pt),Object.assign(st,{[he]:pt})},{});this.paths.add(g);let re=K(N),Ae={input:f(V.name),positive:this.someOf(j.positive),negative:this.someOf(j.negative),response:a.createUnionTypeNode([U(this.interfaces.positive,re),U(this.interfaces.negative,re)]),encoded:a.createIntersectionTypeNode([f(j.positive.name),f(j.negative.name)])};this.registry.set(N,{isDeprecated:$,store:Ae}),this.tags.set(N,I)}}),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:mr(r,t)).join(`
|
|
19
|
-
`):void 0}print(t){let r=this.#n(t),o=r&&
|
|
20
|
-
${r}`);return this.#e.concat(o||[]).map((n,s)=>
|
|
18
|
+
`))};var Io=e=>{e.startupLogo!==!1&&ko(process.stdout);let t=e.errorHandler||ue,r=Wr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v24.0.0-beta.4 (CJS)",env:process.env.NODE_ENV||"development"}),Eo(r);let o=Po({logger:r,config:e}),s={getLogger:wo(r),errorHandler:t},i=Ro(s),p=So(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},No=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Io(e);return rr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},zo=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=Io(e),p=(0,et.default)().disable("x-powered-by").use(i);if(e.compression){let b=await Be("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||et.default.json()],raw:[e.rawParser||et.default.raw(),To],form:[e.formParser||et.default.urlencoded()],upload:e.upload?await Oo({config:e,getLogger:o}):[]};rr({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,g)=>()=>b.listen(g,()=>r.info("Listening",g)),h=[];if(e.http){let b=Ao.default.createServer(p);c.push(b),h.push(m(b,e.http.listen))}if(e.https){let b=Co.default.createServer(e.https.options,p);c.push(b),h.push(m(b,e.https.listen))}return e.gracefulShutdown&&vo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(b=>b())}};var Yo=require("openapi3-ts/oas31"),Qo=y(require("ramda"),1);var R=y(require("ramda"),1);var jo=e=>M(e)&&"or"in e,Lo=e=>M(e)&&"and"in e,or=e=>!Lo(e)&&!jo(e),Mo=e=>{let t=R.filter(or,e),r=R.chain(R.prop("and"),R.filter(Lo,e)),[o,n]=R.partition(or,r),s=R.concat(t,o),i=R.filter(jo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>Re(d,R.map(m=>or(m)?[m]:m.and,c),([m,h])=>R.concat(m,h)),R.reject(R.isEmpty,[s]))};var ye=require("openapi3-ts/oas31"),l=y(require("ramda"),1),nr=require("zod/v4");var Zo=["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 $o=50,Ko="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",qo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Bo=e=>e.replace($t,t=>`{${t.slice(1)}}`),Un=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Dn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),_n=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Vn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Fe(e,"throw")},(e,{jsonSchema:t})=>t),Jn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:rs(t.type)})},Ho=e=>e in qo,Gn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Wn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),we=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(Ho):t&&Ho(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(we));return s&&(p.not=we(s)),p},Yn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new J("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:Ko}};return e?.length&&(o.examples=e),o},Qn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new J("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ko}};return e?.length&&(o.examples=e),o},Xn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),es=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},ts=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},rs=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],os=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!ne(o,"transform"))return t;let s=we(ar(n,{ctx:r}));if((0,ye.isSchemaObject)(s))if(r.isResponse){let i=lt(o,ts(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},ns=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},sr=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ss=(e,t)=>t?.includes(e)||e.startsWith("x-")||Zo.includes(e),Fo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Fe(r),m=dt(e),h=o.includes("query"),b=o.includes("params"),g=o.includes("headers"),k=O=>b&&m.includes(O),A=l.chain(l.filter(O=>O.type==="header"),p??[]).map(({name:O})=>O),Z=O=>g&&(i?.(O,t,e)??ss(O,A));return Object.entries(c.properties).reduce((O,[I,N])=>{let _=k(I)?"path":Z(I)?"header":h?"query":void 0;if(!_)return O;let j=we(N),ee=s==="components"?n(N,j,se(d,I)):j;return O.concat({name:I,in:_,deprecated:N.deprecated,required:c.required?.includes(I)||!1,description:j.description||d,schema:ee,examples:sr((0,ye.isSchemaObject)(j)&&j.examples?.length?j.examples:l.pluck(I,c.examples?.filter(l.both(M,l.has(I)))||[]))})},[])},ir={nullable:Jn,union:_n,bigint:Xn,intersection:Vn,tuple:es,pipe:os,literal:Wn,enum:Gn,[xe]:Yn,[Se]:Qn,[ce]:Un,[de]:Dn,[q]:ns},is=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,ye.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i,we(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},ar=(e,{ctx:t,rules:r=ir})=>{let{$defs:o={},properties:n={}}=nr.z.toJSONSchema(nr.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=X(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 is(n.subject,o,t)},Uo=(e,t)=>{if((0,ye.isReferenceObject)(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Uo(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]},Do=({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} ${qt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=we(ar(r,{rules:{...c,...ir},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,ye.isSchemaObject)(h)&&h.examples&&(b.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,se(m)):h,examples:sr(b)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},as=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ps=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},cs=({name:e})=>({type:"apiKey",in:"header",name:e}),ds=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ms=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ls=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),_o=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?as(o):o.type==="input"?ps(o,t):o.type==="header"?cs(o):o.type==="cookie"?ds(o):o.type==="openid"?ms(o):ls(o);return e.map(o=>o.map(r))},Vo=(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:[]})},{})),Jo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>ar(e,{rules:{...t,...ir},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Go=({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]=Uo(we(o),p),h=[];(0,ye.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,se(d)):c,examples:sr(h.length?h:Fe(o).examples?.filter(k=>M(k)&&!Array.isArray(k)).map(l.omit(p))||[])},g={description:d,content:{[n]:b}};return(m||n===E.raw)&&(g.required=!0),g},Wo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),pr=e=>e.length<=$o?e:e.slice(0,$o-1)+"\u2026",Ot=e=>e.length?e.slice():void 0;var Tt=class extends Yo.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||se(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new J(`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,composition:h="inline"}){super(),this.addInfo({title:o,version:n});for(let g of typeof s=="string"?[s]:s)this.addServer({url:g});Ue({routing:t,onEndpoint:(g,k,A)=>{let Z={path:k,method:A,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:I,scopes:N,inputSchema:_}=g,j=I?pr(I):m&&O?pr(O):void 0,ee=r.inputSources?.[A]||Ht[A],Ae=this.#n(k,A,g.getOperationId(A)),nt=Jo({...Z,schema:_}),he=Mo(g.security),st=Fo({...Z,inputSources:ee,isHeader:c,security:he,request:nt,description:i?.requestParameter?.call(null,{method:A,path:k,operationId:Ae})}),it={};for(let te of Ze){let be=g.getResponses(te);for(let{mimeTypes:pt,schema:Mt,statusCodes:vr}of be)for(let Zt of vr)it[Zt]=Do({...Z,variant:te,schema:Mt,mimeTypes:pt,statusCode:Zt,hasMultipleStatusCodes:be.length>1||vr.length>1,description:i?.[`${te}Response`]?.call(null,{method:A,path:k,operationId:Ae,statusCode:Zt})})}let at=ee.includes("body")?Go({...Z,request:nt,paramNames:Qo.pluck("name",st),schema:_,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:A,path:k,operationId:Ae})}):void 0,jt=Vo(_o(he,ee),N,te=>{let be=this.#s(te);return this.addSecurityScheme(be,te),be}),Lt={operationId:Ae,summary:j,description:O,deprecated:g.isDeprecated||void 0,tags:Ot(g.tags),parameters:Ot(st),requestBody:at,security:Ot(jt),responses:it};this.addPath(Bo(k),{[A]:Lt})}}),d&&(this.rootDoc.tags=Wo(d))}};var Pt=require("node-mocks-http");var us=e=>(0,Pt.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),fs=e=>(0,Pt.createResponse)(e),ys=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Yr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Xo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=us(e),s=fs({req:n,...t});s.req=t?.req||n,n.res=s;let i=ys(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},en=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Xo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},tn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=ue}}=Xo(r),d=mt(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:re(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var pn=y(require("ramda"),1),ot=y(require("typescript"),1),cn=require("zod/v4");var sn=y(require("ramda"),1),U=y(require("typescript"),1);var Y=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,wt=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],gs=[a.createModifier(u.default.SyntaxKind.AsyncKeyword)],tt={public:[a.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.default.SyntaxKind.ProtectedKeyword),a.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},cr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),dr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mr=e=>typeof e=="string"&&hs.test(e)?a.createIdentifier(e):w(e),Et=(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)))),vt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),De=e=>Object.entries(e).map(([t,r])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),lr=(e,t=[])=>a.createConstructorDeclaration(tt.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?a.createTypeReferenceNode(e,t&&Y.map(f,t)):e,ur=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ee=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,mr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return p.length?cr(i,p.join(" ")):i},fr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),yr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),z=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&wt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),gr=(e,t)=>Q(e,a.createUnionTypeNode(Y.map(H,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?wt:void 0,e,n&&Sr(n),t);return o?cr(s,o):s},rn=(e,t)=>a.createPropertyDeclaration(tt.public,e,void 0,f(t),void 0),hr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(tt.public,void 0,e,void 0,o&&Sr(o),t,n,a.createBlock(r)),br=(e,t,{typeParams:r}={})=>a.createClassDeclaration(wt,e,r&&Sr(r),void 0,t),xr=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),kt=e=>f(Promise.name,[e]),At=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?wt:void 0,e,void 0,void 0,t);return o?cr(n,o):n},Sr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?Y.map(vt,e):De(e),void 0,void 0,t),T=e=>e,rt=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.default.SyntaxKind.QuestionToken),t,a.createToken(u.default.SyntaxKind.ColonToken),r),P=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),_e=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Ct=(e,t)=>f("Extract",[e,t]),Rr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.default.SyntaxKind.EqualsToken),t)),F=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),on=e=>a.createUnionTypeNode([f(e),kt(e)]),Or=(e,t)=>a.createFunctionTypeNode(void 0,De(e),f(t)),w=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),H=e=>a.createLiteralTypeNode(w(e)),bs=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],nn=e=>bs.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=gr("Method",er);someOfType=Q("SomeOf",F("T",xr("T")),{params:["T"]});requestType=Q("Request",xr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>gr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>At(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ee(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>z("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(mr(t),a.createArrayLiteralExpression(sn.map(w,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,Or({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:ur,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},kt(U.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:U.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>z(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:U.default.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),w(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>z(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:ur},a.createBlock([z(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],U.default.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([Rr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Et(":",[this.#e.keyParameter]),ve([],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=()=>hr(this.#e.provideMethod,De({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:F(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(yr(this.#e.methodParameter,this.#e.pathParameter),P(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(P(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(P(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:kt(F(this.interfaces.response,"K"))});makeClientClass=t=>br(t,[lr([vt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:tt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Et("?",[_e(URLSearchParams.name,t)]);#o=()=>_e(URL.name,Et("",[this.#e.pathParameter],[this.#e.searchParamsConst]),w(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),rt(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(w("Content-Type"),w(E.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),rt(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=z(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=z(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=z(this.#e.searchParamsConst,rt(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=z(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(w("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(U.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=z(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(w(E.json))),m=a.createReturnStatement(P(this.#e.responseConst,rt(this.#e.isJsonConst,w(T("json")),w(T("text"))))());return z(this.#e.defaultImplementationConst,ve([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=()=>lr(De({request:"K",params:F(this.interfaces.input,"K")}),[z(yr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),z(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Rr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),_e("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Ee(T("event"),t)]);#i=()=>hr(this.#e.onMethod,De({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Or({[this.#e.dataParameter.text]:F(Ct("R",fr(this.#s("E"))),H(T("data")))},on(U.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],P(this.#e.handlerParameter)(P(JSON[Symbol.toStringTag],T("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),T("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:F("R",H(T("event")))}});makeSubscriptionClass=t=>br(t,[rn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ct(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(U.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ct(F(this.interfaces.positive,"K"),fr(this.#s(U.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,_e(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(_e(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),ve(["time"],a.createBlock([])))]};var v=y(require("ramda"),1),x=y(require("typescript"),1),an=require("zod/v4");var Tr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=X(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Tr(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}=x.default,xs={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Pr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},Ss=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):H(r));return t.length===1?t[0]:D.createUnionTypeNode(t)},Rs=(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}=an.globalRegistry.get(p)||{};return Ee(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return D.createTypeLiteralNode(s)};return qr(e,{io:t?"output":"input"})?o(e,n):n()},Os=({_zod:{def:e}},{next:t})=>D.createArrayTypeNode(t(e.element)),Ts=({_zod:{def:e}})=>D.createUnionTypeNode(Object.values(e.entries).map(H)),Ps=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(nn(n)?n.kind:n,n)}return D.createUnionTypeNode(Array.from(r.values()))},ws=e=>xs?.[e.kind],Es=({_zod:{def:e}},{next:t})=>t(e.innerType),vs=({_zod:{def:e}},{next:t})=>D.createUnionTypeNode([t(e.innerType),H(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)),Cs=v.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(Pr.name,...o))return!1;if(v.both(v.eqBy(Pr.type),v.eqBy(Pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return D.createTypeLiteralNode(r)},(e,t)=>D.createIntersectionTypeNode(t)),Is=({_zod:{def:e}},{next:t})=>Cs([e.left,e.right].map(t)),ge=e=>()=>f(e),wr=({_zod:{def:e}},{next:t})=>t(e.innerType),Ns=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!ne(o,"transform"))return t(o);let s=t(n),i=lt(o,ws(s)),p={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(i&&p[i]||x.default.SyntaxKind.AnyKeyword)},zs=()=>H(null),js=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ls=e=>{let t=f(x.default.SyntaxKind.StringKeyword),r=f("Buffer"),o=D.createUnionTypeNode([t,r]);return ne(e,"string")?t:ne(e,"union")?o:r},Ms=(e,{next:t})=>t(e._zod.def.shape.raw),Zs={string:ge(x.default.SyntaxKind.StringKeyword),number:ge(x.default.SyntaxKind.NumberKeyword),bigint:ge(x.default.SyntaxKind.BigIntKeyword),boolean:ge(x.default.SyntaxKind.BooleanKeyword),any:ge(x.default.SyntaxKind.AnyKeyword),undefined:ge(x.default.SyntaxKind.UndefinedKeyword),[xe]:ge(x.default.SyntaxKind.StringKeyword),[Se]:ge(x.default.SyntaxKind.StringKeyword),null:zs,array:Os,tuple:ks,record:As,object:Rs,literal:Ss,intersection:Is,union:Ps,default:wr,enum:Ts,optional:Es,nullable:vs,catch:wr,pipe:Ns,lazy:js,readonly:wr,[de]:Ls,[q]:Ms},Er=(e,{brandHandling:t,ctx:r})=>Tr(e,{rules:{...t,...Zs},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Nt=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=H(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=cn.z.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};Ue({routing:t,onEndpoint:(b,g,k)=>{let A=se.bind(null,k,g),{isDeprecated:Z,inputSchema:O,tags:I}=b,N=`${k} ${g}`,_=Q(A("input"),Er(O,c),{comment:N});this.#e.push(_);let j=Ze.reduce((nt,he)=>{let st=b.getResponses(he),it=pn.chain(([jt,{schema:Lt,mimeTypes:te,statusCodes:be}])=>{let pt=Q(A(he,"variant",`${jt+1}`),Er(te?Lt:p,m),{comment:N});return this.#e.push(pt),be.map(Mt=>Ee(Mt,pt.name))},Array.from(st.entries())),at=At(A(he,"response","variants"),it,{comment:N});return this.#e.push(at),Object.assign(nt,{[he]:at})},{});this.paths.add(g);let ee=H(N),Ae={input:f(_.name),positive:this.someOf(j.positive),negative:this.someOf(j.negative),response:a.createUnionTypeNode([F(this.interfaces.positive,ee),F(this.interfaces.negative,ee)]),encoded:a.createIntersectionTypeNode([f(j.positive.name),f(j.negative.name)])};this.registry.set(N,{isDeprecated:Z,store:Ae}),this.tags.set(N,I)}}),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:dr(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.#n(t),o=r&&ot.default.addSyntheticLeadingComment(ot.default.addSyntheticLeadingComment(a.createEmptyStatement(),ot.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),ot.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.#e.concat(o||[]).map((n,s)=>dr(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 Be("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}};var ke=require("zod/v4");var mn=(e,t)=>ke.z.object({data:t,event:ke.z.literal(e),id:ke.z.string().optional(),retry:ke.z.int().positive().optional()}),$s=(e,t,r)=>mn(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Hs=1e4,dn=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Ks=e=>new B({handler:async({response:t})=>setTimeout(()=>dn(t),Hs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{dn(t),t.write($s(e,r,o),"utf-8"),t.flush?.()}}}),qs=e=>new le({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>mn(o,n));return{mimeType:E.sse,schema:r.length?ke.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ke.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Te(r);Qe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(Pe(i),"utf-8")}t.end()}}),zt=class extends fe{constructor(t){super(qs(t)),this.middlewares=[Ks(t)]}};var ln={dateIn:Cr,dateOut:Nr,form:zr,file:ft,upload:Lr,raw:Hr};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,EventStreamFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ensureHttpError,ez,getMessageFromError,testEndpoint,testMiddleware});
|
package/dist/index.d.cts
CHANGED
|
@@ -224,11 +224,11 @@ declare class ExpressMiddleware<R extends Request, S extends Response, OUT exten
|
|
|
224
224
|
});
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
-
type Base = object & {
|
|
227
|
+
type Base$1 = object & {
|
|
228
228
|
[Symbol.iterator]?: never;
|
|
229
229
|
};
|
|
230
230
|
/** @desc The type allowed on the top level of Middlewares and Endpoints */
|
|
231
|
-
type IOSchema = z.ZodType<Base>;
|
|
231
|
+
type IOSchema = z.ZodType<Base$1>;
|
|
232
232
|
|
|
233
233
|
declare const methods: ("get" | "post" | "put" | "delete" | "patch")[];
|
|
234
234
|
type Method = (typeof methods)[number];
|
|
@@ -465,7 +465,7 @@ type UploadOptions = Pick<express_fileupload__default.Options, "createParentPath
|
|
|
465
465
|
type CompressionOptions = Pick<compression.CompressionOptions, "threshold" | "level" | "strategy" | "chunkSize" | "memLevel">;
|
|
466
466
|
interface GracefulOptions {
|
|
467
467
|
/**
|
|
468
|
-
* @desc Time given to drain ongoing requests before
|
|
468
|
+
* @desc Time given to drain ongoing requests before closing the server.
|
|
469
469
|
* @default 1000
|
|
470
470
|
* */
|
|
471
471
|
timeout?: number;
|
|
@@ -475,6 +475,8 @@ interface GracefulOptions {
|
|
|
475
475
|
* @default [SIGINT, SIGTERM]
|
|
476
476
|
* */
|
|
477
477
|
events?: string[];
|
|
478
|
+
/** @desc The hook to call after the server was closed, but before terminating the process. */
|
|
479
|
+
beforeExit?: () => void | Promise<void>;
|
|
478
480
|
}
|
|
479
481
|
type BeforeRouting = (params: {
|
|
480
482
|
app: IRouter;
|
|
@@ -714,7 +716,7 @@ interface DocumentationParams {
|
|
|
714
716
|
/**
|
|
715
717
|
* @desc Handling rules for your own branded schemas.
|
|
716
718
|
* @desc Keys: brands (recommended to use unique symbols).
|
|
717
|
-
* @desc Values: functions having
|
|
719
|
+
* @desc Values: functions having Zod context as first argument, second one is the framework context.
|
|
718
720
|
* @example { MyBrand: ( { zodSchema, jsonSchema } ) => ({ type: "object" })
|
|
719
721
|
*/
|
|
720
722
|
brandHandling?: BrandHandling;
|
|
@@ -915,6 +917,7 @@ declare function file<K extends Variant>(variant: K): ReturnType<Variants[K]>;
|
|
|
915
917
|
declare const base: z.ZodObject<{
|
|
916
918
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
917
919
|
}, z.core.$strip>;
|
|
920
|
+
type Base = ReturnType<typeof base.brand<symbol>>;
|
|
918
921
|
declare const extended: <S extends $ZodShape>(extra: S) => z.core.$ZodBranded<z.ZodObject<("raw" & keyof S extends never ? {
|
|
919
922
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
920
923
|
} & S : ({
|
|
@@ -929,12 +932,12 @@ declare const extended: <S extends $ZodShape>(extra: S) => z.core.$ZodBranded<z.
|
|
|
929
932
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
930
933
|
}[K]; } : never) & { [K_1 in keyof S]: S[K_1]; })[k]; } : never, z.core.$strip>, symbol>;
|
|
931
934
|
/** Shorthand for z.object({ raw: ez.file("buffer") }) */
|
|
932
|
-
declare function raw():
|
|
935
|
+
declare function raw(): Base;
|
|
933
936
|
declare function raw<S extends $ZodShape>(extra: S): ReturnType<typeof extended<S>>;
|
|
934
937
|
|
|
935
938
|
declare const ez: {
|
|
936
|
-
dateIn: () => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.ZodString, zod_v4.ZodString, zod_v4.ZodString]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
|
|
937
|
-
dateOut: () => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
|
|
939
|
+
dateIn: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.ZodString, zod_v4.ZodString, zod_v4.ZodString]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
|
|
940
|
+
dateOut: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
|
|
938
941
|
form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<{ -readonly [P in keyof S]: S[P]; }, zod_v4_core.$strip>, symbol>;
|
|
939
942
|
file: typeof file;
|
|
940
943
|
upload: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<express_fileupload.UploadedFile, express_fileupload.UploadedFile>, symbol>;
|
package/dist/index.d.ts
CHANGED
|
@@ -224,11 +224,11 @@ declare class ExpressMiddleware<R extends Request, S extends Response, OUT exten
|
|
|
224
224
|
});
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
-
type Base = object & {
|
|
227
|
+
type Base$1 = object & {
|
|
228
228
|
[Symbol.iterator]?: never;
|
|
229
229
|
};
|
|
230
230
|
/** @desc The type allowed on the top level of Middlewares and Endpoints */
|
|
231
|
-
type IOSchema = z.ZodType<Base>;
|
|
231
|
+
type IOSchema = z.ZodType<Base$1>;
|
|
232
232
|
|
|
233
233
|
declare const methods: ("get" | "post" | "put" | "delete" | "patch")[];
|
|
234
234
|
type Method = (typeof methods)[number];
|
|
@@ -465,7 +465,7 @@ type UploadOptions = Pick<express_fileupload__default.Options, "createParentPath
|
|
|
465
465
|
type CompressionOptions = Pick<compression.CompressionOptions, "threshold" | "level" | "strategy" | "chunkSize" | "memLevel">;
|
|
466
466
|
interface GracefulOptions {
|
|
467
467
|
/**
|
|
468
|
-
* @desc Time given to drain ongoing requests before
|
|
468
|
+
* @desc Time given to drain ongoing requests before closing the server.
|
|
469
469
|
* @default 1000
|
|
470
470
|
* */
|
|
471
471
|
timeout?: number;
|
|
@@ -475,6 +475,8 @@ interface GracefulOptions {
|
|
|
475
475
|
* @default [SIGINT, SIGTERM]
|
|
476
476
|
* */
|
|
477
477
|
events?: string[];
|
|
478
|
+
/** @desc The hook to call after the server was closed, but before terminating the process. */
|
|
479
|
+
beforeExit?: () => void | Promise<void>;
|
|
478
480
|
}
|
|
479
481
|
type BeforeRouting = (params: {
|
|
480
482
|
app: IRouter;
|
|
@@ -714,7 +716,7 @@ interface DocumentationParams {
|
|
|
714
716
|
/**
|
|
715
717
|
* @desc Handling rules for your own branded schemas.
|
|
716
718
|
* @desc Keys: brands (recommended to use unique symbols).
|
|
717
|
-
* @desc Values: functions having
|
|
719
|
+
* @desc Values: functions having Zod context as first argument, second one is the framework context.
|
|
718
720
|
* @example { MyBrand: ( { zodSchema, jsonSchema } ) => ({ type: "object" })
|
|
719
721
|
*/
|
|
720
722
|
brandHandling?: BrandHandling;
|
|
@@ -915,6 +917,7 @@ declare function file<K extends Variant>(variant: K): ReturnType<Variants[K]>;
|
|
|
915
917
|
declare const base: z.ZodObject<{
|
|
916
918
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
917
919
|
}, z.core.$strip>;
|
|
920
|
+
type Base = ReturnType<typeof base.brand<symbol>>;
|
|
918
921
|
declare const extended: <S extends $ZodShape>(extra: S) => z.core.$ZodBranded<z.ZodObject<("raw" & keyof S extends never ? {
|
|
919
922
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
920
923
|
} & S : ({
|
|
@@ -929,12 +932,12 @@ declare const extended: <S extends $ZodShape>(extra: S) => z.core.$ZodBranded<z.
|
|
|
929
932
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
930
933
|
}[K]; } : never) & { [K_1 in keyof S]: S[K_1]; })[k]; } : never, z.core.$strip>, symbol>;
|
|
931
934
|
/** Shorthand for z.object({ raw: ez.file("buffer") }) */
|
|
932
|
-
declare function raw():
|
|
935
|
+
declare function raw(): Base;
|
|
933
936
|
declare function raw<S extends $ZodShape>(extra: S): ReturnType<typeof extended<S>>;
|
|
934
937
|
|
|
935
938
|
declare const ez: {
|
|
936
|
-
dateIn: () => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.ZodString, zod_v4.ZodString, zod_v4.ZodString]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
|
|
937
|
-
dateOut: () => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
|
|
939
|
+
dateIn: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodPipe<zod_v4.ZodUnion<[zod_v4.ZodString, zod_v4.ZodString, zod_v4.ZodString]>, zod_v4.ZodTransform<Date, string>>, zod_v4.ZodDate>, symbol>;
|
|
940
|
+
dateOut: ({ examples, ...rest }?: Parameters<zod_v4.ZodString["meta"]>[0]) => zod_v4_core.$ZodBranded<zod_v4.ZodPipe<zod_v4.ZodDate, zod_v4.ZodTransform<string, Date>>, symbol>;
|
|
938
941
|
form: <S extends zod_v4_core.$ZodShape>(base: S | zod_v4.ZodObject<S>) => zod_v4_core.$ZodBranded<zod_v4.ZodObject<{ -readonly [P in keyof S]: S[P]; }, zod_v4_core.$strip>, symbol>;
|
|
939
942
|
file: typeof file;
|
|
940
943
|
upload: () => zod_v4_core.$ZodBranded<zod_v4.ZodCustom<express_fileupload.UploadedFile, express_fileupload.UploadedFile>, symbol>;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import*as
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:pn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ir}from"zod/v4";var Mt=class{},U=class extends Mt{#e;#t;#r;constructor({input:t=Ir.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Ir.ZodError?new G(o):o}}},Ee=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 Fe=class extends ve{},ct=class e extends Fe{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){let t=Ar(this.#e.inputSchema);if(t){let r=W(t);if(r===ne)return"upload";if(r===H)return"raw";if(r===qe)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ke.pluck("security",this.#e.middlewares||[]);return ke.reject(ke.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Nr.ZodError?new me(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Ee))&&(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#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Nr.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){pt({...t,error:new ee(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Nt(t),i={},p={output:{},error:null},d=rt(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as zr from"ramda";var jr=(e,t)=>{let r=zr.pluck("schema",e);r.push(t);let o=r.reduce((n,s)=>n.and(s));return r.reduce((n,s)=>hr(s,n),o)};import{globalRegistry as dt,z as K}from"zod/v4";var Ae={positive:200,negative:400},Ce=Object.keys(Ae);var Zt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},he=class extends Zt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Lt(this.#e,{variant:"positive",args:[t],statusCodes:[Ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return Lt(this.#t,{variant:"negative",args:[],statusCodes:[Ae.negative],mimeTypes:[w.json]})}},be=new he({positive:e=>{let{examples:t=[]}=dt.get(e)||{};!t.length&&$(e,"object")&&t.push(...ot(e)),t.length&&!dt.has(e)&&dt.add(e,{examples:t});let r=K.object({status:K.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:K.object({status:K.literal("error"),error:K.object({message:K.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=we(e);return Be(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:ge(i)}})}n.status(Ae.positive).json({status:"success",data:r})}}),$t=new he({positive:e=>{let{examples:t=[]}=dt.get(e)||{},r=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());return t.reduce((o,n)=>j(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:K.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);return Be(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(ge(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 xe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof U?t:new U(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new U({handler:t})),this.resultHandler)}build({input:t=Lr.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,g=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new ct({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:y,methods:m,getOperationId:g,inputSchema:jr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Lr.object({}),handler:async o=>(await t(o),{})})}},cn=new xe(be),dn=new xe($t);import hn from"ansis";import{inspect as bn}from"node:util";import{performance as qr}from"node:perf_hooks";import{blue as mn,green as ln,hex as un,red as fn,cyanBright as yn}from"ansis";import*as Mr from"ramda";var Ht={debug:mn,info:ln,warn:un("#FFA500"),error:fn,ctx:yn},mt={debug:10,info:20,warn:30,error:40},Zr=e=>j(e)&&Object.keys(mt).some(t=>t in e),$r=e=>e in mt,Hr=(e,t)=>mt[e]<mt[t],gn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ie=Mr.memoizeWith((e,t)=>`${e}${t}`,gn),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 Ue=class e{config;constructor({color:t=hn.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 bn(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"||Hr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Ht.ctx(s):s),d.push(p?`${Ht[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 Br from"ramda";var De=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Br.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 xn from"express";var _e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,xn.static(...this.#e))}};import ft from"express";import Ln from"node:http";import Mn from"node:https";var Ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new He(e)};import En from"http-errors";import{z as Ur}from"zod/v4";import*as S from"ramda";var Sn=e=>e.type==="object",Rn=S.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return S.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")}),On=S.pipe(Object.keys,S.without(["type","properties","required","examples","description"]),S.isEmpty),Fr=S.pair(!0),ze=(e,t="coerce")=>{let r=[S.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"&&On(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(Fr,i.anyOf)),i.oneOf&&r.push(...S.map(Fr,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(j)||[],i.examples.filter(j),([p,d])=>S.mergeDeepRight(p,d))),!!Sn(i)&&(i.properties&&(o.properties=(t==="throw"?Rn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),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};var lt=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=jt(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(w.json))continue;let i=jt(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=tt(t);if(s.length===0)return;let i=n?.flat||ze(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 Kt=["get","post","put","delete","patch"],Dr=e=>Kt.includes(e);var Tn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Dr(t)?[r,t]:[e]},Pn=e=>e.trim().split("/").filter(Boolean).join("/"),_r=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Tn(r);return[[t||""].concat(Pn(n)||[]).join("/"),o,s]}),wn=(e,t)=>{throw new de("Route with explicit method can only be assigned with Endpoint",e,t)},Vr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new de(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},qt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new de("Route has a duplicate",e,t);r.add(o)},je=({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 Fe)if(p)qt(p,s,n),Vr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)qt(c,s,n),t(i,s,c)}else if(p&&wn(p,s),i instanceof _e)r&&i.apply(s,r);else if(i instanceof De)for(let[d,c]of i.entries){let{methods:m}=c;qt(d,s,n),Vr(d,s,m),t(c,s,d)}else o.unshift(..._r(i,s))}};import*as Jr from"ramda";var Gr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=Gr(e);r.set({Allow:n});let s=En(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},kn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Gr(e),"Access-Control-Allow-Headers":"content-type"}),Bt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new lt(t()),i=new Map;je({routing:o,onEndpoint:(c,m,g)=>{ue()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let h=n?.[c.requestType]||[],y=Jr.pair(h,c);i.has(m)||i.set(m,new Map(r.cors?[["options",y]]:[])),i.get(m)?.set(g,y)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let g=Array.from(m.keys());for(let[h,[y,v]]of m){let k=async(M,R)=>{let A=t(M);if(r.cors){let C=kn(g),F=typeof r.cors=="function"?await r.cors({request:M,endpoint:v,logger:A,defaultHeaders:C}):C;R.set(F)}return v.execute({request:M,response:R,logger:A,config:r})};e[h](c,...y,k)}r.wrongMethodBehavior!==404&&d.set(c,vn(g))}for(let[c,m]of d)e.all(c,m)};import Cn from"http-errors";import{setInterval as An}from"node:timers/promises";var Wr=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",Yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Xr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),eo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var to=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Wr(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",Xr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Qr(c)||Yr(c))&&i(c);for await(let c of An(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(eo))};return{sockets:n,shutdown:()=>o??=d()}};var ro=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:re(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){pt({response:o,logger:s,error:new ee(re(i),n)})}},In=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},Nn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await Ne("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:Nn(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[Pe]={logger:i}),s()},ao=e=>t=>t?.res?.locals[Pe]?.logger||e,po=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
-
`).slice(1))),
|
|
1
|
+
import*as z from"ramda";import{z as J}from"zod/v4";var Pe=Symbol.for("express-zod-api"),V=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Ko=J.core.$constructor("$EZBrandCheck",(e,t)=>{J.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),qo=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},Bo=function(){return this.meta({deprecated:!0})},Fo=function(e){return this.meta({default:e})},Uo=function(e){return this.check(new Ko({brand:e,check:"$EZBrandCheck"}))},Do=function(e){let t=typeof e=="function"?e:z.pipe(z.toPairs,z.map(([s,i])=>z.pair(e[String(s)]||s,i)),z.fromPairs),r=t(z.map(z.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof J.ZodUnknown?J.looseObject:J.object)(r);return this.transform(t).pipe(n)};if(!(Pe in globalThis)){globalThis[Pe]=!0;for(let e of Object.keys(J)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=J[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{get(){return qo.bind(this)}},deprecated:{get(){return Bo.bind(this)}},brand:{set(){},get(){return Uo.bind(this)}}})}Object.defineProperty(J.ZodDefault.prototype,"label",{get(){return Fo.bind(this)}}),Object.defineProperty(J.ZodObject.prototype,"remap",{get(){return Do.bind(this)}})}function _o(e){return e}import{z as zr}from"zod/v4";import*as ke from"ramda";import{z as Cr}from"zod/v4";import*as se from"ramda";import{z as Or}from"zod/v4";import{z as $e}from"zod/v4";var ce=Symbol("DateIn"),fr=({examples:e,...t}={})=>$e.union([$e.iso.date(),$e.iso.datetime(),$e.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe($e.date()).brand(ce).meta(t);import{z as Vo}from"zod/v4";var de=Symbol("DateOut"),yr=({examples:e,...t}={})=>Vo.date().transform(r=>r.toISOString()).brand(de).meta({...t,examples:e});import*as Z from"ramda";import{z as et}from"zod/v4";var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var kt=/:([A-Za-z0-9_]+)/g,tt=e=>e.match(kt)?.map(t=>t.slice(1))||[],Jo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},At={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Go=["body","query","params"],Ct=e=>e.method.toLowerCase(),rt=(e,t={})=>{let r=Ct(e);return r==="options"?{}:(t[r]||At[r]||Go).filter(o=>o==="files"?Jo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},X=e=>e instanceof Error?e:e instanceof et.ZodError?new et.ZodRealError(e.issues):new Error(String(e)),me=e=>e instanceof et.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof fe?`output${e.cause.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,ee=(e,t)=>e._zod.def.type===t,le=(e,t,r)=>e.length&&t.length?Z.xprod(e,t).map(r):e.concat(t),It=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),te=(...e)=>{let t=Z.chain(o=>o.split(/[^A-Z0-9]/gi),e);return Z.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(It).join("")},ot=Z.tryCatch((e,t)=>typeof et.parse(e,t),Z.always(void 0)),j=e=>typeof e=="object"&&e!==null,ue=Z.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ye=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},G=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.`}},He=class extends Error{name="IOSchemaError"},nt=class extends He{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},fe=class extends He{constructor(r){super(me(r),{cause:r});this.cause=r}name="OutputValidationError"},W=class extends He{constructor(r){super(me(r),{cause:r});this.cause=r}name="InputValidationError"},re=class extends Error{constructor(r,o){super(me(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ke=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as gr}from"zod/v4";var qe=Symbol("Form"),hr=e=>(e instanceof gr.ZodObject?e:gr.object(e)).brand(qe);import{z as Wo}from"zod/v4";var oe=Symbol("Upload"),br=()=>Wo.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(oe);import{z as Qo}from"zod/v4";import{z as st}from"zod/v4";var ne=Symbol("File"),xr=st.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Yo={buffer:()=>xr.brand(ne),string:()=>st.string().brand(ne),binary:()=>xr.or(st.string()).brand(ne),base64:()=>st.base64().brand(ne)};function it(e){return Yo[e||"string"]()}var $=Symbol("Raw"),Sr=Qo.object({raw:it("buffer")}),Xo=e=>Sr.extend(e).brand($);function Rr(e){return e?Xo(e):Sr.brand($)}var Tr=(e,{io:t,condition:r})=>se.tryCatch(()=>{Or.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new nt(o)}})},o=>o.cause)(),Pr=(e,{io:t})=>{let o=[Or.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];for(;o.length;){let n=o.shift();if(se.is(Object,n)){if(n.$ref==="#")return!0;o.push(...se.values(n))}se.is(Array,n)&&o.push(...se.values(n))}return!1},wr=e=>Tr(e,{condition:t=>{let r=V(t);return typeof r=="symbol"&&[oe,$,qe].includes(r)},io:"input"}),en=["nan","symbol","map","set","bigint","void","promise","never"],Nt=(e,t)=>Tr(e,{io:t,condition:r=>{let o=V(r),{type:n}=r._zod.def;return!!(en.includes(n)||t==="input"&&(n==="date"||o===de)||t==="output"&&(o===ce||o===$||o===oe))}});import nn,{isHttpError as sn}from"http-errors";import Er,{isHttpError as tn}from"http-errors";import*as vr from"ramda";import{globalRegistry as rn,z as on}from"zod/v4";var zt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof on.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new re(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Be=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>tn(e)?e:Er(e instanceof W?400:500,me(e),{cause:e.cause||e}),ge=e=>ue()&&!e.expose?Er(e.statusCode).message:e.message,kr=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=rn.get(o)||{};return le(t,n.map(vr.objOf(r)),([s,i])=>({...s,...i}))},[]);var at=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ge(nn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:sn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as Ar}from"zod/v4";var jt=class{},F=class extends jt{#e;#t;#r;constructor({input:t=Ar.object({}),security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof Ar.ZodError?new W(o):o}}},Ee=class extends F{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 Fe=class extends ve{},pt=class e extends Fe{#e;constructor(t){super(),this.#e=t}#t(t){return new e({...this.#e,...t})}deprecated(){return this.#t({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}get requestType(){let t=wr(this.#e.inputSchema);if(t){let r=V(t);if(r===oe)return"upload";if(r===$)return"raw";if(r===qe)return"form"}return"json"}getResponses(t){return Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ke.pluck("security",this.#e.middlewares||[]);return ke.reject(ke.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#r(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Cr.ZodError?new fe(r):r}}async#o({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Ee))&&(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#n({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Cr.ZodError?new W(n):n}return this.#e.handler({...r,input:o})}async#s(t){try{await this.#e.resultHandler.execute(t)}catch(r){at({...t,error:new re(X(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ct(t),i={},p={output:{},error:null},d=rt(t,n.inputSources);try{if(await this.#o({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.#r(await this.#n({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:X(c)}}await this.#s({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as Ir from"ramda";var Nr=(e,t)=>Ir.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));import{globalRegistry as ct,z as H}from"zod/v4";var Ae={positive:200,negative:400},Ce=Object.keys(Ae);var Lt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},he=class extends Lt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return zt(this.#e,{variant:"positive",args:[t],statusCodes:[Ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return zt(this.#t,{variant:"negative",args:[],statusCodes:[Ae.negative],mimeTypes:[w.json]})}},be=new he({positive:e=>{let{examples:t=[]}=ct.get(e)||{};!t.length&&ee(e,"object")&&t.push(...kr(e)),t.length&&!ct.has(e)&&ct.add(e,{examples:t});let r=H.object({status:H.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:H.object({status:H.literal("error"),error:H.object({message:H.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=we(e);return Be(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:ge(i)}})}n.status(Ae.positive).json({status:"success",data:r})}}),Mt=new he({positive:e=>{let{examples:t=[]}=ct.get(e)||{},r=e instanceof H.ZodObject&&"items"in e.shape&&e.shape.items instanceof H.ZodArray?e.shape.items:H.array(H.any());return t.reduce((o,n)=>j(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:H.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);return Be(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(ge(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 xe=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Ee(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({handler:t})),this.resultHandler)}build({input:t=zr.object({}),output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,g=typeof o=="function"?o:()=>o,h=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new pt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:y,methods:m,getOperationId:g,inputSchema:Nr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:zr.object({}),handler:async o=>(await t(o),{})})}},an=new xe(be),pn=new xe(Mt);import yn from"ansis";import{inspect as gn}from"node:util";import{performance as Hr}from"node:perf_hooks";import{blue as cn,green as dn,hex as mn,red as ln,cyanBright as un}from"ansis";import*as jr from"ramda";var Zt={debug:cn,info:dn,warn:mn("#FFA500"),error:ln,ctx:un},dt={debug:10,info:20,warn:30,error:40},Lr=e=>j(e)&&Object.keys(dt).some(t=>t in e),Mr=e=>e in dt,Zr=(e,t)=>dt[e]<dt[t],fn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ie=jr.memoizeWith((e,t)=>`${e}${t}`,fn),$r=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 Ue=class e{config;constructor({color:t=yn.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 gn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...i},color:p}=this.config;if(n==="silent"||Zr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Zt.ctx(s):s),d.push(p?`${Zt[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=Hr.now();return()=>{let o=Hr.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 Kr from"ramda";var De=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=Kr.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 hn from"express";var _e=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,hn.static(...this.#e))}};import ut from"express";import jn from"node:http";import Ln from"node:https";var Ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import wn from"http-errors";import{z as Br}from"zod/v4";import*as x from"ramda";var bn=e=>e.type==="object",xn=x.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return x.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")}),Sn=x.pipe(Object.keys,x.without(["type","properties","required","examples","description"]),x.isEmpty),qr=x.pair(!0),ze=(e,t="coerce")=>{let r=[x.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"&&Sn(p)))throw new Error("Can not merge");return x.pair(s,p)})),i.anyOf&&r.push(...x.map(qr,i.anyOf)),i.oneOf&&r.push(...x.map(qr,i.oneOf)),i.examples?.length&&(s?o.examples=x.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(j)||[],i.examples.filter(j),([p,d])=>x.mergeDeepRight(p,d))),!!bn(i)&&(r.push([s,{examples:Rn(i)}]),i.properties&&(o.properties=(t==="throw"?xn:x.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),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},Rn=e=>Object.entries(e.properties||{}).reduce((t,[r,{examples:o=[]}])=>le(t,o.map(x.objOf(r)),([n,s])=>({...n,...s})),[]);var mt=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=[Br.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=Nt(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(w.json))continue;let i=Nt(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=tt(t);if(s.length===0)return;let i=n?.flat||ze(Br.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 $t=["get","post","put","delete","patch"],Fr=e=>$t.includes(e);var On=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Fr(t)?[r,t]:[e]},Tn=e=>e.trim().split("/").filter(Boolean).join("/"),Ur=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=On(r);return[[t||""].concat(Tn(n)||[]).join("/"),o,s]}),Pn=(e,t)=>{throw new ye("Route with explicit method can only be assigned with Endpoint",e,t)},Dr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ye(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Ht=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ye("Route has a duplicate",e,t);r.add(o)},je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Ur(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Fe)if(p)Ht(p,s,n),Dr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)Ht(c,s,n),t(i,s,c)}else if(p&&Pn(p,s),i instanceof _e)r&&i.apply(s,r);else if(i instanceof De)for(let[d,c]of i.entries){let{methods:m}=c;Ht(d,s,n),Dr(d,s,m),t(c,s,d)}else o.unshift(...Ur(i,s))}};import*as _r from"ramda";var Vr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),En=e=>({method:t},r,o)=>{let n=Vr(e);r.set({Allow:n});let s=wn(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},vn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Vr(e),"Access-Control-Allow-Headers":"content-type"}),Kt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new mt(t()),i=new Map;je({routing:o,onEndpoint:(c,m,g)=>{ue()||(s?.checkSchema(c,{path:m,method:g}),s?.checkPathParams(m,c,{method:g}));let h=n?.[c.requestType]||[],y=_r.pair(h,c);i.has(m)||i.set(m,new Map(r.cors?[["options",y]]:[])),i.get(m)?.set(g,y)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let g=Array.from(m.keys());for(let[h,[y,v]]of m){let k=async(L,R)=>{let A=t(L);if(r.cors){let C=vn(g),B=typeof r.cors=="function"?await r.cors({request:L,endpoint:v,logger:A,defaultHeaders:C}):C;R.set(B)}return v.execute({request:L,response:R,logger:A,config:r})};e[h](c,...y,k)}r.wrongMethodBehavior!==404&&d.set(c,En(g))}for(let[c,m]of d)e.all(c,m)};import An from"http-errors";import{setInterval as kn}from"node:timers/promises";var Jr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",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(Jr(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 kn(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=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:X(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),to=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=An(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){at({response:o,logger:s,error:new re(X(i),n)})}},Cn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},In=e=>({log:e.debug.bind(e)}),ro=async({getLogger:e,config:t})=>{let r=await Ne("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:In(m)})(p,d,c)}),o&&i.push(Cn(o)),i},oo=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},no=({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[Pe]={logger:i}),s()},so=e=>t=>t?.res?.locals[Pe]?.logger||e,io=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
|
+
`).slice(1))),ao=({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 Nn,hex as po,italic as lt,whiteBright as zn}from"ansis";var co=e=>{if(e.columns<132)return;let t=lt("Proudly supports transgender community.".padStart(109)),r=lt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=lt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=lt("for Ashley".padEnd(20)),s=po("#F5A9B8"),i=po("#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(Nn,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 uo=e=>{e.startupLogo!==!1&&lo(process.stdout);let t=e.errorHandler||be,r=Zr(e.logger)?e.logger:new Ue(e.logger);r.debug("Running",{build:"v24.0.0-beta.2 (ESM)",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}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=uo(e);return Bt({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}=uo(e),p=ft().disable("x-powered-by").use(i);if(e.compression){let h=await Ne("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||ft.json()],raw:[e.rawParser||ft.raw(),so],form:[e.formParser||ft.urlencoded()],upload:e.upload?await no({config:e,getLogger:o}):[]};Bt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(h,y)=>()=>h.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let h=Ln.createServer(p);c.push(h),g.push(m(h,e.http.listen))}if(e.https){let h=Mn.createServer(e.https.options,p);c.push(h),g.push(m(h,e.https.listen))}return e.gracefulShutdown&&co({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(h=>h())}};import{OpenApiBuilder as ms}from"openapi3-ts/oas31";import*as zo from"ramda";import*as x from"ramda";var fo=e=>j(e)&&"or"in e,yo=e=>j(e)&&"and"in e,Ft=e=>!yo(e)&&!fo(e),go=e=>{let t=x.filter(Ft,e),r=x.chain(x.prop("and"),x.filter(yo,e)),[o,n]=x.partition(Ft,r),s=x.concat(t,o),i=x.filter(fo,e);return x.map(x.prop("or"),x.concat(i,n)).reduce((d,c)=>le(d,x.map(m=>Ft(m)?[m]:m.and,c),([m,g])=>x.concat(m,g)),x.reject(x.isEmpty,[s]))};import{isReferenceObject as Ro,isSchemaObject as yt}from"openapi3-ts/oas31";import*as l from"ramda";import{globalRegistry as Kn,z as bo}from"zod/v4";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 xo=50,Oo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",To={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Po=e=>e.replace(Ct,t=>`{${t.slice(1)}}`),qn=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Bn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),Fn=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Un=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return ze(e,"throw")},(e,{jsonSchema:t})=>t),Dn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:es(t.type)})},So=e=>e in To,_n=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Vn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Jn=({zodSchema:e,jsonSchema:t},{isResponse:r})=>{if(r||!$(e,"object"))return t;let{required:o=[]}=t,n=[];for(let s of o){let i=e._zod.def.shape[s];i&&!st(i,{isResponse:r})&&n.push(s)}return{...t,required:n}},Se=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(So):t&&So(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(Se));return s&&(p.not=Se(s)),p},Gn=({zodSchema:e},t)=>{if(t.isResponse)throw new J("Please use ez.dateOut() for output.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Oo}},o=Kn.get(e)?.examples?.filter(n=>n instanceof Date).map(n=>n.toISOString());return o?.length&&(r.examples=o),r},Wn=({jsonSchema:{examples:e}},t)=>{if(!t.isResponse)throw new J("Please use ez.dateIn() for input.",t);let r={description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Oo}};return e?.length&&(r.examples=e),r},Yn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Qn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Xn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},es=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ts=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!$(o,"transform"))return t;let s=Se(_t(n,{ctx:r}));if(yt(s))if(r.isResponse){let i=nt(o,Xn(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},rs=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},Ut=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,os=(e,t)=>t?.includes(e)||e.startsWith("x-")||ho.includes(e),wo=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=ze(r),m=tt(e),g=o.includes("query"),h=o.includes("params"),y=o.includes("headers"),v=R=>h&&m.includes(R),k=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),M=R=>y&&(i?.(R,t,e)??os(R,k));return Object.entries(c.properties).reduce((R,[A,C])=>{let F=v(A)?"path":M(A)?"header":g?"query":void 0;if(!F)return R;let N=Se(C),Q=s==="components"?n(C,N,oe(d,A)):N;return R.concat({name:A,in:F,deprecated:C.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:Q,examples:Ut(yt(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(j,l.has(A)))||[]))})},[])},Dt={nullable:Dn,union:Fn,bigint:Yn,intersection:Un,tuple:Qn,pipe:ts,literal:Vn,enum:_n,object:Jn,[fe]:Gn,[ye]:Wn,[ne]:qn,[se]:Bn,[H]:rs},ns=(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,Se(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=Dt})=>{let{$defs:o={},properties:n={}}=bo.toJSONSchema(bo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=W(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 ns(n.subject,o,t)},Eo=(e,t)=>{if(Ro(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Eo(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]},vo=({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} ${zt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=Se(_t(r,{rules:{...c,...Dt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];yt(g)&&g.examples&&(h.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,oe(m)):g,examples:Ut(h)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},ss=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},is=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},as=({name:e})=>({type:"apiKey",in:"header",name:e}),ps=({name:e})=>({type:"apiKey",in:"cookie",name:e}),cs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ds=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),ko=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ss(o):o.type==="input"?is(o,t):o.type==="header"?as(o):o.type==="cookie"?ps(o):o.type==="openid"?cs(o):ds(o);return e.map(o=>o.map(r))},Ao=(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,...Dt},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]=Eo(Se(o),p),g=[];yt(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,oe(d)):c,examples:Ut(g.length?g:ze(o).examples?.filter(v=>j(v)&&!Array.isArray(v)).map(l.omit(p))||[])},y={description:d,content:{[n]:h}};return(m||n===w.raw)&&(y.required=!0),y},No=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)},[]),Vt=e=>e.length<=xo?e:e.slice(0,xo-1)+"\u2026",gt=e=>e.length?e.slice():void 0;var Jt=class extends ms{#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 J(`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,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});je({routing:t,onEndpoint:(y,v,k)=>{let M={path:v,method:k,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:A,scopes:C,inputSchema:F}=y,N=A?Vt(A):m&&R?Vt(R):void 0,Q=r.inputSources?.[k]||It[k],Te=this.#n(v,k,y.getOperationId(k)),Ge=Co({...M,schema:F}),pe=go(y.security),We=wo({...M,inputSources:Q,isHeader:c,security:pe,request:Ge,description:i?.requestParameter?.call(null,{method:k,path:v,operationId:Te})}),Ye={};for(let X of Ce){let ce=y.getResponses(X);for(let{mimeTypes:Xe,schema:vt,statusCodes:yr}of ce)for(let kt of yr)Ye[kt]=vo({...M,variant:X,schema:vt,mimeTypes:Xe,statusCode:kt,hasMultipleStatusCodes:ce.length>1||yr.length>1,description:i?.[`${X}Response`]?.call(null,{method:k,path:v,operationId:Te,statusCode:kt})})}let Qe=Q.includes("body")?Io({...M,request:Ge,paramNames:zo.pluck("name",We),schema:F,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:v,operationId:Te})}):void 0,wt=Ao(ko(pe,Q),C,X=>{let ce=this.#s(X);return this.addSecurityScheme(ce,X),ce}),Et={operationId:Te,summary:N,description:R,deprecated:y.isDeprecated||void 0,tags:gt(y.tags),parameters:gt(We),requestBody:Qe,security:gt(wt),responses:Ye};this.addPath(Po(v),{[k]:Et})}}),d&&(this.rootDoc.tags=No(d))}};import{createRequest as ls,createResponse as us}from"node-mocks-http";var fs=e=>ls({...e,headers:{"content-type":w.json,...e?.headers}}),ys=e=>us(e),gs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:$r(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},jo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=fs(e),s=ys({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}},hs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=jo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},bs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=jo(r),d=rt(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:re(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Ho from"ramda";import Pt from"typescript";import{z as Bs}from"zod/v4";import*as $o from"ramda";import V from"typescript";import*as D from"ramda";import u from"typescript";var a=u.factory,ht=[a.createModifier(u.SyntaxKind.ExportKeyword)],xs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ve={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)},Ss=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yt=e=>typeof e=="string"&&Ss.test(e)?a.createIdentifier(e):P(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)))),xt=(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),Le=e=>Object.entries(e).map(([t,r])=>xt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Qt=(e,t=[])=>a.createConstructorDeclaration(Ve.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&D.map(f,t)):e,Xt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(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?a.createUnionTypeNode([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=D.reject(D.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))),I=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&ht,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),rr=(e,t)=>_(e,a.createUnionTypeNode(D.map(Z,t)),{expose:!0}),_=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?ht:void 0,e,n&&ir(n),t);return o?Gt(s,o):s},Lo=(e,t)=>a.createPropertyDeclaration(Ve.public,e,void 0,f(t),void 0),or=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ve.public,void 0,e,void 0,o&&ir(o),t,n,a.createBlock(r)),nr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(ht,e,r&&ir(r),void 0,t),sr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),St=e=>f(Promise.name,[e]),Rt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?ht:void 0,e,void 0,void 0,t);return o?Gt(n,o):n},ir=e=>(Array.isArray(e)?e.map(t=>D.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)}),Oe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?xs:void 0,void 0,Array.isArray(e)?D.map(xt,e):Le(e),void 0,void 0,t),O=e=>e,Je=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),T=(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),Ot=(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=>a.createUnionTypeNode([f(e),St(e)]),pr=(e,t)=>a.createFunctionTypeNode(void 0,Le(e),f(t)),P=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),Z=e=>a.createLiteralTypeNode(P(e)),Rs=[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],Zo=e=>Rs.includes(e.kind);var Tt=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",Kt);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=>Rt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>I("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Yt(t),a.createArrayLiteralExpression($o.map(P,r))))),{expose:!0});makeImplementationType=()=>_(this.#e.implementationType,pr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},St(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>I(this.#e.parseRequestFn,Oe({[this.#e.requestParameter.text]:V.SyntaxKind.StringKeyword},a.createAsExpression(T(this.#e.requestParameter,O("split"))(a.createRegularExpressionLiteral("/ (.+)/"),P(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>I(this.#e.substituteFn,Oe({[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Xt},a.createBlock([I(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([ar(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(bt(":",[this.#e.keyParameter]),Oe([],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,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:q(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[I(tr(this.#e.methodParameter,this.#e.pathParameter),T(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(T(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(T(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:St(q(this.interfaces.response,"K"))});makeClientClass=t=>nr(t,[Qt([xt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ve.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]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(O("method"),T(this.#e.methodParameter,O("toUpperCase"))()),r=a.createPropertyAssignment(O("headers"),Je(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),Je(this.#e.hasBodyConst,T(JSON[Symbol.toStringTag],O("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=I(this.#e.responseConst,a.createAwaitExpression(T(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=I(this.#e.hasBodyConst,a.createLogicalNot(T(a.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.#e.methodParameter))),i=I(this.#e.searchParamsConst,Je(this.#e.hasBodyConst,P(""),this.#r(this.#e.paramsArgument))),p=I(this.#e.contentTypeConst,T(this.#e.responseConst,O("headers"),O("get"))(P("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=I(this.#e.isJsonConst,T(this.#e.contentTypeConst,O("startsWith"))(P(w.json))),m=a.createReturnStatement(T(this.#e.responseConst,Je(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return I(this.#e.defaultImplementationConst,Oe([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(Le({request:"K",params:q(this.interfaces.input,"K")}),[I(tr(this.#e.pathParameter,this.#e.restConst),T(this.#e.substituteFn)(a.createElementAccessExpression(T(this.#e.parseRequestFn)(this.#e.requestParameter),P(1)),this.#e.paramsArgument)),I(this.#e.searchParamsConst,this.#r(this.#e.restConst)),ar(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Me("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Re(O("event"),t)]);#i=()=>or(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:pr({[this.#e.dataParameter.text]:q(Ot("R",er(this.#s("E"))),Z(O("data")))},Mo(V.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Oe([this.#e.msgParameter],T(this.#e.handlerParameter)(T(JSON[Symbol.toStringTag],O("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),O("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:q("R",Z(O("event")))}});makeSubscriptionClass=t=>nr(t,[Lo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Ot(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(V.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Ot(q(this.interfaces.positive,"K"),er(this.#s(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[I(this.#e.clientConst,Me(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Me(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Oe(["time"],a.createBlock([])))]};import*as E from"ramda";import b from"typescript";import{globalRegistry as Os}from"zod/v4";var cr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=W(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:B}=b,Ts={[b.SyntaxKind.AnyKeyword]:"",[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:"",[b.SyntaxKind.UndefinedKeyword]:void 0},dr={name:E.path(["name","text"]),type:E.path(["type"]),optional:E.path(["questionToken"])},Ps=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(b.SyntaxKind.UndefinedKeyword):Z(r));return t.length===1?t[0]:B.createUnionTypeNode(t)},ws=(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}=Os.get(p)||{};return Re(i,r(p),{comment:d,isDeprecated:c,isOptional:st(p,{isResponse:t})})});return B.createTypeLiteralNode(s)};return kr(e,{io:t?"output":"input"})?o(e,n):n()},Es=({_zod:{def:e}},{next:t})=>B.createArrayTypeNode(t(e.element)),vs=({_zod:{def:e}})=>B.createUnionTypeNode(Object.values(e.entries).map(Z)),ks=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(Zo(n)?n.kind:n,n)}return B.createUnionTypeNode(Array.from(r.values()))},As=e=>Ts?.[e.kind],Cs=({_zod:{def:e}},{next:t})=>t(e.innerType),Is=({_zod:{def:e}},{next:t})=>B.createUnionTypeNode([t(e.innerType),Z(null)]),Ns=({_zod:{def:e}},{next:t})=>B.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:B.createRestTypeNode(t(e.rest)))),zs=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),js=E.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw new Error("Not objects");let t=E.chain(E.prop("members"),e),r=E.uniqWith((...o)=>{if(!E.eqBy(dr.name,...o))return!1;if(E.both(E.eqBy(dr.type),E.eqBy(dr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return B.createTypeLiteralNode(r)},(e,t)=>B.createIntersectionTypeNode(t)),Ls=({_zod:{def:e}},{next:t})=>js([e.left,e.right].map(t)),ae=e=>()=>f(e),mr=({_zod:{def:e}},{next:t})=>t(e.innerType),Ms=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!$(o,"transform"))return t(o);let s=t(n),i=nt(o,As(s)),p={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return f(i&&p[i]||b.SyntaxKind.AnyKeyword)},Zs=()=>Z(null),$s=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Hs=e=>{let t=f(b.SyntaxKind.StringKeyword),r=f("Buffer"),o=B.createUnionTypeNode([t,r]);return $(e,"string")?t:$(e,"union")?o:r},Ks=(e,{next:t})=>t(e._zod.def.shape.raw),qs={string:ae(b.SyntaxKind.StringKeyword),number:ae(b.SyntaxKind.NumberKeyword),bigint:ae(b.SyntaxKind.BigIntKeyword),boolean:ae(b.SyntaxKind.BooleanKeyword),any:ae(b.SyntaxKind.AnyKeyword),undefined:ae(b.SyntaxKind.UndefinedKeyword),[fe]:ae(b.SyntaxKind.StringKeyword),[ye]:ae(b.SyntaxKind.StringKeyword),null:Zs,array:Es,tuple:Ns,record:zs,object:ws,literal:Ps,intersection:Ls,union:ks,default:mr,enum:vs,optional:Cs,nullable:Is,catch:mr,pipe:Ms,lazy:$s,readonly:mr,[se]:Hs,[H]:Ks},lr=(e,{brandHandling:t,ctx:r})=>cr(e,{rules:{...t,...qs},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var ur=class extends Tt{#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=Z(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=Bs.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};je({routing:t,onEndpoint:(h,y,v)=>{let k=oe.bind(null,v,y),{isDeprecated:M,inputSchema:R,tags:A}=h,C=`${v} ${y}`,F=_(k("input"),lr(R,c),{comment:C});this.#e.push(F);let N=Ce.reduce((Ge,pe)=>{let We=h.getResponses(pe),Ye=Ho.chain(([wt,{schema:Et,mimeTypes:X,statusCodes:ce}])=>{let Xe=_(k(pe,"variant",`${wt+1}`),lr(X?Et:p,m),{comment:C});return this.#e.push(Xe),ce.map(vt=>Re(vt,Xe.name))},Array.from(We.entries())),Qe=Rt(k(pe,"response","variants"),Ye,{comment:C});return this.#e.push(Qe),Object.assign(Ge,{[pe]:Qe})},{});this.paths.add(y);let Q=Z(C),Te={input:f(F.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([q(this.interfaces.positive,Q),q(this.interfaces.negative,Q)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(C,{isDeprecated:M,store:Te}),this.tags.set(C,A)}}),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
|
-
`):void 0}print(t){let r=this.#n(t),o=r&&
|
|
20
|
-
${r}`);return this.#e.concat(o||[]).map((n,s)=>
|
|
18
|
+
`))};var mo=e=>{e.startupLogo!==!1&&co(process.stdout);let t=e.errorHandler||be,r=Lr(e.logger)?e.logger:new Ue(e.logger);r.debug("Running",{build:"v24.0.0-beta.4 (ESM)",env:process.env.NODE_ENV||"development"}),io(r);let o=no({logger:r,config:e}),s={getLogger:so(r),errorHandler:t},i=to(s),p=eo(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Mn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=mo(e);return Kt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Zn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=mo(e),p=ut().disable("x-powered-by").use(i);if(e.compression){let h=await Ne("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||ut.json()],raw:[e.rawParser||ut.raw(),oo],form:[e.formParser||ut.urlencoded()],upload:e.upload?await ro({config:e,getLogger:o}):[]};Kt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(h,y)=>()=>h.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let h=jn.createServer(p);c.push(h),g.push(m(h,e.http.listen))}if(e.https){let h=Ln.createServer(e.https.options,p);c.push(h),g.push(m(h,e.https.listen))}return e.gracefulShutdown&&ao({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(h=>h())}};import{OpenApiBuilder as ps}from"openapi3-ts/oas31";import*as Io from"ramda";import*as S from"ramda";var lo=e=>j(e)&&"or"in e,uo=e=>j(e)&&"and"in e,qt=e=>!uo(e)&&!lo(e),fo=e=>{let t=S.filter(qt,e),r=S.chain(S.prop("and"),S.filter(uo,e)),[o,n]=S.partition(qt,r),s=S.concat(t,o),i=S.filter(lo,e);return S.map(S.prop("or"),S.concat(i,n)).reduce((d,c)=>le(d,S.map(m=>qt(m)?[m]:m.and,c),([m,g])=>S.concat(m,g)),S.reject(S.isEmpty,[s]))};import{isReferenceObject as xo,isSchemaObject as ft}from"openapi3-ts/oas31";import*as l from"ramda";import{z as go}from"zod/v4";var yo=["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 ho=50,So="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Ro={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Oo=e=>e.replace(kt,t=>`{${t.slice(1)}}`),Hn=({},e)=>{if(e.isResponse)throw new G("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Kn=({jsonSchema:e})=>({type:"string",format:e.type==="string"?e.format==="base64"?"byte":"file":"binary"}),qn=({zodSchema:e,jsonSchema:t})=>{if(!e._zod.disc)return t;let r=Array.from(e._zod.disc.keys()).pop();return{...t,discriminator:t.discriminator??{propertyName:r}}},Bn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return ze(e,"throw")},(e,{jsonSchema:t})=>t),Fn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Yn(t.type)})},bo=e=>e in Ro,Un=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Dn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Se=({$ref:e,type:t,allOf:r,oneOf:o,anyOf:n,not:s,...i})=>{if(e)return{$ref:e};let p={type:Array.isArray(t)?t.filter(bo):t&&bo(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(Se));return s&&(p.not=Se(s)),p},_n=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new G("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:So}};return e?.length&&(o.examples=e),o},Vn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new G("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:So}};return e?.length&&(o.examples=e),o},Jn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Gn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Wn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Ro?.[t]},Yn=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],Qn=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!ee(o,"transform"))return t;let s=Se(Ut(n,{ctx:r}));if(ft(s))if(r.isResponse){let i=ot(o,Wn(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},Xn=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},Bt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,es=(e,t)=>t?.includes(e)||e.startsWith("x-")||yo.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=ze(r),m=tt(e),g=o.includes("query"),h=o.includes("params"),y=o.includes("headers"),v=R=>h&&m.includes(R),k=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),L=R=>y&&(i?.(R,t,e)??es(R,k));return Object.entries(c.properties).reduce((R,[A,C])=>{let B=v(A)?"path":L(A)?"header":g?"query":void 0;if(!B)return R;let N=Se(C),Y=s==="components"?n(C,N,te(d,A)):N;return R.concat({name:A,in:B,deprecated:C.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:Y,examples:Bt(ft(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(j,l.has(A)))||[]))})},[])},Ft={nullable:Fn,union:qn,bigint:Jn,intersection:Bn,tuple:Gn,pipe:Qn,literal:Dn,enum:Un,[ce]:_n,[de]:Vn,[oe]:Hn,[ne]:Kn,[$]:Xn},ts=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(xo(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i,Se(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Ut=(e,{ctx:t,rules:r=Ft})=>{let{$defs:o={},properties:n={}}=go.toJSONSchema(go.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=V(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 ts(n.subject,o,t)},Po=(e,t)=>{if(xo(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} ${It(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=Se(Ut(r,{rules:{...c,...Ft},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];ft(g)&&g.examples&&(h.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,te(m)):g,examples:Bt(h)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},rs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},os=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ns=({name:e})=>({type:"apiKey",in:"header",name:e}),ss=({name:e})=>({type:"apiKey",in:"cookie",name:e}),is=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),as=({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"?rs(o):o.type==="input"?os(o,t):o.type==="header"?ns(o):o.type==="cookie"?ss(o):o.type==="openid"?is(o):as(o);return e.map(o=>o.map(r))},vo=(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:[]})},{})),ko=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Ut(e,{rules:{...t,...Ft},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Ao=({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(Se(o),p),g=[];ft(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,te(d)):c,examples:Bt(g.length?g:ze(o).examples?.filter(v=>j(v)&&!Array.isArray(v)).map(l.omit(p))||[])},y={description:d,content:{[n]:h}};return(m||n===w.raw)&&(y.required=!0),y},Co=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Dt=e=>e.length<=ho?e:e.slice(0,ho-1)+"\u2026",yt=e=>e.length?e.slice():void 0;var _t=class extends ps{#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||te(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new G(`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,composition:g="inline"}){super(),this.addInfo({title:o,version:n});for(let y of typeof s=="string"?[s]:s)this.addServer({url:y});je({routing:t,onEndpoint:(y,v,k)=>{let L={path:v,method:k,endpoint:y,composition:g,brandHandling:p,makeRef:this.#o.bind(this)},{description:R,shortDescription:A,scopes:C,inputSchema:B}=y,N=A?Dt(A):m&&R?Dt(R):void 0,Y=r.inputSources?.[k]||At[k],Te=this.#n(v,k,y.getOperationId(k)),Ge=ko({...L,schema:B}),ae=fo(y.security),We=To({...L,inputSources:Y,isHeader:c,security:ae,request:Ge,description:i?.requestParameter?.call(null,{method:k,path:v,operationId:Te})}),Ye={};for(let Q of Ce){let pe=y.getResponses(Q);for(let{mimeTypes:Xe,schema:Et,statusCodes:ur}of pe)for(let vt of ur)Ye[vt]=wo({...L,variant:Q,schema:Et,mimeTypes:Xe,statusCode:vt,hasMultipleStatusCodes:pe.length>1||ur.length>1,description:i?.[`${Q}Response`]?.call(null,{method:k,path:v,operationId:Te,statusCode:vt})})}let Qe=Y.includes("body")?Ao({...L,request:Ge,paramNames:Io.pluck("name",We),schema:B,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:v,operationId:Te})}):void 0,Pt=vo(Eo(ae,Y),C,Q=>{let pe=this.#s(Q);return this.addSecurityScheme(pe,Q),pe}),wt={operationId:Te,summary:N,description:R,deprecated:y.isDeprecated||void 0,tags:yt(y.tags),parameters:yt(We),requestBody:Qe,security:yt(Pt),responses:Ye};this.addPath(Oo(v),{[k]:wt})}}),d&&(this.rootDoc.tags=Co(d))}};import{createRequest as cs,createResponse as ds}from"node-mocks-http";var ms=e=>cs({...e,headers:{"content-type":w.json,...e?.headers}}),ls=e=>ds(e),us=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Mr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},No=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ms(e),s=ls({req:n,...t});s.req=t?.req||n,n.res=s;let i=us(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},fs=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}},ys=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=No(r),d=rt(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:X(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Zo from"ramda";import Tt from"typescript";import{z as Hs}from"zod/v4";import*as Mo from"ramda";import _ from"typescript";import*as U from"ramda";import u from"typescript";var a=u.factory,gt=[a.createModifier(u.SyntaxKind.ExportKeyword)],gs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ve={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Vt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Jt=(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)},hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Gt=e=>typeof e=="string"&&hs.test(e)?a.createIdentifier(e):P(e),ht=(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)))),bt=(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),Le=e=>Object.entries(e).map(([t,r])=>bt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Wt=(e,t=[])=>a.createConstructorDeclaration(Ve.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,Yt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Re=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Gt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=U.reject(U.isNil,[o?"@deprecated":void 0,n]);return p.length?Vt(i,p.join(" ")):i},Qt=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),Xt=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),I=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&>,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),er=(e,t)=>D(e,a.createUnionTypeNode(U.map(M,t)),{expose:!0}),D=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?gt:void 0,e,n&&nr(n),t);return o?Vt(s,o):s},zo=(e,t)=>a.createPropertyDeclaration(Ve.public,e,void 0,f(t),void 0),tr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ve.public,void 0,e,void 0,o&&nr(o),t,n,a.createBlock(r)),rr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(gt,e,r&&nr(r),void 0,t),or=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),xt=e=>f(Promise.name,[e]),St=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?gt:void 0,e,void 0,void 0,t);return o?Vt(n,o):n},nr=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)}),Oe=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?U.map(bt,e):Le(e),void 0,void 0,t),O=e=>e,Je=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),T=(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),Rt=(e,t)=>f("Extract",[e,t]),sr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),K=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),jo=e=>a.createUnionTypeNode([f(e),xt(e)]),ir=(e,t)=>a.createFunctionTypeNode(void 0,Le(e),f(t)),P=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),M=e=>a.createLiteralTypeNode(P(e)),bs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Lo=e=>bs.includes(e.kind);var Ot=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=er("Method",$t);someOfType=D("SomeOf",K("T",or("T")),{params:["T"]});requestType=D("Request",or(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>er(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>St(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Re(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>I("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Gt(t),a.createArrayLiteralExpression(Mo.map(P,r))))),{expose:!0});makeImplementationType=()=>D(this.#e.implementationType,ir({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Yt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},xt(_.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:_.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>I(this.#e.parseRequestFn,Oe({[this.#e.requestParameter.text]:_.SyntaxKind.StringKeyword},a.createAsExpression(T(this.#e.requestParameter,O("split"))(a.createRegularExpressionLiteral("/ (.+)/"),P(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>I(this.#e.substituteFn,Oe({[this.#e.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Yt},a.createBlock([I(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],_.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([sr(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(ht(":",[this.#e.keyParameter]),Oe([],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=()=>tr(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:K(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[I(Xt(this.#e.methodParameter,this.#e.pathParameter),T(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(T(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(T(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:xt(K(this.interfaces.response,"K"))});makeClientClass=t=>rr(t,[Wt([bt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ve.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>ht("?",[Me(URLSearchParams.name,t)]);#o=()=>Me(URL.name,ht("",[this.#e.pathParameter],[this.#e.searchParamsConst]),P(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(O("method"),T(this.#e.methodParameter,O("toUpperCase"))()),r=a.createPropertyAssignment(O("headers"),Je(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),Je(this.#e.hasBodyConst,T(JSON[Symbol.toStringTag],O("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=I(this.#e.responseConst,a.createAwaitExpression(T(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=I(this.#e.hasBodyConst,a.createLogicalNot(T(a.createArrayLiteralExpression([P("get"),P("delete")]),O("includes"))(this.#e.methodParameter))),i=I(this.#e.searchParamsConst,Je(this.#e.hasBodyConst,P(""),this.#r(this.#e.paramsArgument))),p=I(this.#e.contentTypeConst,T(this.#e.responseConst,O("headers"),O("get"))(P("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(_.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=I(this.#e.isJsonConst,T(this.#e.contentTypeConst,O("startsWith"))(P(w.json))),m=a.createReturnStatement(T(this.#e.responseConst,Je(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return I(this.#e.defaultImplementationConst,Oe([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=()=>Wt(Le({request:"K",params:K(this.interfaces.input,"K")}),[I(Xt(this.#e.pathParameter,this.#e.restConst),T(this.#e.substituteFn)(a.createElementAccessExpression(T(this.#e.parseRequestFn)(this.#e.requestParameter),P(1)),this.#e.paramsArgument)),I(this.#e.searchParamsConst,this.#r(this.#e.restConst)),sr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Me("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Re(O("event"),t)]);#i=()=>tr(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:ir({[this.#e.dataParameter.text]:K(Rt("R",Qt(this.#s("E"))),M(O("data")))},jo(_.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Oe([this.#e.msgParameter],T(this.#e.handlerParameter)(T(JSON[Symbol.toStringTag],O("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),O("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:K("R",M(O("event")))}});makeSubscriptionClass=t=>rr(t,[zo(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Rt(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(_.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Rt(K(this.interfaces.positive,"K"),Qt(this.#s(_.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[I(this.#e.clientConst,Me(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Me(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Oe(["time"],a.createBlock([])))]};import*as E from"ramda";import b from"typescript";import{globalRegistry as xs}from"zod/v4";var ar=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=V(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>ar(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:q}=b,Ss={[b.SyntaxKind.AnyKeyword]:"",[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:"",[b.SyntaxKind.UndefinedKeyword]:void 0},pr={name:E.path(["name","text"]),type:E.path(["type"]),optional:E.path(["questionToken"])},Rs=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(b.SyntaxKind.UndefinedKeyword):M(r));return t.length===1?t[0]:q.createUnionTypeNode(t)},Os=(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}=xs.get(p)||{};return Re(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return q.createTypeLiteralNode(s)};return Pr(e,{io:t?"output":"input"})?o(e,n):n()},Ts=({_zod:{def:e}},{next:t})=>q.createArrayTypeNode(t(e.element)),Ps=({_zod:{def:e}})=>q.createUnionTypeNode(Object.values(e.entries).map(M)),ws=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(Lo(n)?n.kind:n,n)}return q.createUnionTypeNode(Array.from(r.values()))},Es=e=>Ss?.[e.kind],vs=({_zod:{def:e}},{next:t})=>t(e.innerType),ks=({_zod:{def:e}},{next:t})=>q.createUnionTypeNode([t(e.innerType),M(null)]),As=({_zod:{def:e}},{next:t})=>q.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:q.createRestTypeNode(t(e.rest)))),Cs=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Is=E.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw new Error("Not objects");let t=E.chain(E.prop("members"),e),r=E.uniqWith((...o)=>{if(!E.eqBy(pr.name,...o))return!1;if(E.both(E.eqBy(pr.type),E.eqBy(pr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return q.createTypeLiteralNode(r)},(e,t)=>q.createIntersectionTypeNode(t)),Ns=({_zod:{def:e}},{next:t})=>Is([e.left,e.right].map(t)),ie=e=>()=>f(e),cr=({_zod:{def:e}},{next:t})=>t(e.innerType),zs=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!ee(o,"transform"))return t(o);let s=t(n),i=ot(o,Es(s)),p={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return f(i&&p[i]||b.SyntaxKind.AnyKeyword)},js=()=>M(null),Ls=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ms=e=>{let t=f(b.SyntaxKind.StringKeyword),r=f("Buffer"),o=q.createUnionTypeNode([t,r]);return ee(e,"string")?t:ee(e,"union")?o:r},Zs=(e,{next:t})=>t(e._zod.def.shape.raw),$s={string:ie(b.SyntaxKind.StringKeyword),number:ie(b.SyntaxKind.NumberKeyword),bigint:ie(b.SyntaxKind.BigIntKeyword),boolean:ie(b.SyntaxKind.BooleanKeyword),any:ie(b.SyntaxKind.AnyKeyword),undefined:ie(b.SyntaxKind.UndefinedKeyword),[ce]:ie(b.SyntaxKind.StringKeyword),[de]:ie(b.SyntaxKind.StringKeyword),null:js,array:Ts,tuple:As,record:Cs,object:Os,literal:Rs,intersection:Ns,union:ws,default:cr,enum:Ps,optional:vs,nullable:ks,catch:cr,pipe:zs,lazy:Ls,readonly:cr,[ne]:Ms,[$]:Zs},dr=(e,{brandHandling:t,ctx:r})=>ar(e,{rules:{...t,...$s},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var mr=class extends Ot{#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=M(null);this.#t.set(t,D(o,n)),this.#t.set(t,D(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=Hs.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};je({routing:t,onEndpoint:(h,y,v)=>{let k=te.bind(null,v,y),{isDeprecated:L,inputSchema:R,tags:A}=h,C=`${v} ${y}`,B=D(k("input"),dr(R,c),{comment:C});this.#e.push(B);let N=Ce.reduce((Ge,ae)=>{let We=h.getResponses(ae),Ye=Zo.chain(([Pt,{schema:wt,mimeTypes:Q,statusCodes:pe}])=>{let Xe=D(k(ae,"variant",`${Pt+1}`),dr(Q?wt:p,m),{comment:C});return this.#e.push(Xe),pe.map(Et=>Re(Et,Xe.name))},Array.from(We.entries())),Qe=St(k(ae,"response","variants"),Ye,{comment:C});return this.#e.push(Qe),Object.assign(Ge,{[ae]:Qe})},{});this.paths.add(y);let Y=M(C),Te={input:f(B.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([K(this.interfaces.positive,Y),K(this.interfaces.negative,Y)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(C,{isDeprecated:L,store:Te}),this.tags.set(C,A)}}),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:Jt(r,t)).join(`
|
|
19
|
+
`):void 0}print(t){let r=this.#n(t),o=r&&Tt.addSyntheticLeadingComment(Tt.addSyntheticLeadingComment(a.createEmptyStatement(),Tt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Tt.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
|
+
${r}`);return this.#e.concat(o||[]).map((n,s)=>Jt(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 Ne("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 Ze}from"zod/v4";var
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Ne("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 Ze}from"zod/v4";var Ho=(e,t)=>Ze.object({data:t,event:Ze.literal(e),id:Ze.string().optional(),retry:Ze.int().positive().optional()}),Ks=(e,t,r)=>Ho(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),qs=1e4,$o=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":w.sse,"cache-control":"no-cache"}),Bs=e=>new F({handler:async({response:t})=>setTimeout(()=>$o(t),qs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{$o(t),t.write(Ks(e,r,o),"utf-8"),t.flush?.()}}}),Fs=e=>new he({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Ho(o,n));return{mimeType:w.sse,schema:r.length?Ze.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Ze.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);Be(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(ge(i),"utf-8")}t.end()}}),lr=class extends xe{constructor(t){super(Fs(t)),this.middlewares=[Bs(t)]}};var Us={dateIn:fr,dateOut:yr,form:hr,file:it,upload:br,raw:Rr};export{Ue as BuiltinLogger,De as DependsOnMethod,_t as Documentation,G as DocumentationError,xe as EndpointsFactory,lr as EventStreamFactory,W as InputValidationError,mr as Integration,F as Middleware,Ke as MissingPeerError,fe as OutputValidationError,he as ResultHandler,ye as RoutingError,_e as ServeStatic,pn as arrayEndpointsFactory,Mt as arrayResultHandler,Mn as attachRouting,_o as createConfig,Zn as createServer,an as defaultEndpointsFactory,be as defaultResultHandler,we as ensureHttpError,Us as ez,me as getMessageFromError,fs as testEndpoint,ys as testMiddleware};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "24.0.0-beta.
|
|
3
|
+
"version": "24.0.0-beta.4",
|
|
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": {
|