express-zod-api 24.0.0-beta.8 → 24.0.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  - Switched to Zod 4:
8
8
  - Minimum supported version of `zod` is 3.25.1, BUT imports MUST be from `zod/v4`;
9
- - Explanation of the versioning strategy: https://github.com/colinhacks/zod/issues/4371;
9
+ - Read the [Explanation of the versioning strategy](https://github.com/colinhacks/zod/issues/4371);
10
10
  - Express Zod API, however, is not aiming to support both Zod 3 and Zod 4 simultaneously due to:
11
11
  - incompatibility of data structures;
12
12
  - operating composite schemas (need to avoid mixing schemas of different versions);
@@ -21,19 +21,23 @@
21
21
  - In order to specify an example for an input schema the `.example()` method must be called before `.transform()`;
22
22
  - The transforming proprietary schemas `ez.dateIn()` and `ez.dateOut()` now accept metadata as its argument:
23
23
  - This allows to set examples before transformation (`ez.dateIn()`) and to avoid the examples "branding";
24
- - Generating Documentation is mostly delegated to Zod 4 `z.toJSONSchema()`:
25
- - The basic depiction of each schema is now natively performed by Zod 4;
24
+ - Changes to `Documentation`:
25
+ - Generating Documentation is mostly delegated to Zod 4 `z.toJSONSchema()`;
26
26
  - Express Zod API implements some overrides and improvements to fit it into OpenAPI 3.1 that extends JSON Schema;
27
27
  - The `numericRange` option removed from `Documentation` class constructor argument;
28
28
  - The `Depicter` type signature changed: became a postprocessing function returning an overridden JSON Schema;
29
- - The `optionalPropStyle` option removed from `Integration` class constructor:
29
+ - Changes to `Integration`:
30
+ - The `optionalPropStyle` option removed from `Integration` class constructor:
30
31
  - Use `.optional()` to add question mark to the object property as well as `undefined` to its type;
31
32
  - Use `.or(z.undefined())` to add `undefined` to the type of the object property;
32
- - Reasoning: https://x.com/colinhacks/status/1919292504861491252;
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
+ - See the [reasoning](https://x.com/colinhacks/status/1919292504861491252);
34
+ - `z.any()` and `z.unknown()` are required: [details](https://v4.zod.dev/v4/changelog#changes-zunknown-optionality);
35
+ - Added types generation for `z.never()`, `z.void()` and `z.unknown()` schemas;
36
+ - The fallback type for unsupported schemas and unclear transformations in response changed from `any` to `unknown`;
37
+ - The argument of `ResultHandler::handler` is now discriminated: either `output` or `error` is `null`, not both;
35
38
  - The `getExamples()` public helper removed — use `.meta()?.examples` instead;
36
- - The `ez.file()` schema removed: use `z.string()`, `z.base64()` or the new `ez.buffer()` instead;
39
+ - Added the new proprietary schema `ez.buffer()`;
40
+ - The `ez.file()` schema removed: use `z.string()`, `z.base64()`, `ez.buffer()` or their union;
37
41
  - Consider the automated migration using the built-in ESLint rule.
38
42
 
39
43
  ```js
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
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})},vr=(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)):{},vr(t||!e||!e.__esModule?ct(r,"default",{value:e,enumerable:!0}):r,e)),xn=e=>vr(ct({},"__esModule",{value:!0}),e);var qs={};bn(qs,{BuiltinLogger:()=>He,DependsOnMethod:()=>qe,Documentation:()=>Tt,DocumentationError:()=>J,EndpointsFactory:()=>le,EventStreamFactory:()=>zt,InputValidationError:()=>V,Integration:()=>Nt,Middleware:()=>K,MissingPeerError:()=>je,OutputValidationError:()=>ze,ResultHandler:()=>de,RoutingError:()=>se,ServeStatic:()=>Ke,arrayEndpointsFactory:()=>Vr,arrayResultHandler:()=>xt,attachRouting:()=>No,createConfig:()=>kr,createServer:()=>zo,defaultEndpointsFactory:()=>Jr,defaultResultHandler:()=>me,ensureHttpError:()=>Oe,ez:()=>ln,getMessageFromError:()=>oe,testEndpoint:()=>en,testMiddleware:()=>tn});module.exports=xn(qs);var L=y(require("ramda"),1),_=require("zod/v4");var Ae=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=_.z.core.$constructor("$EZBrandCheck",(e,t)=>{_.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 _.z.ZodUnknown?_.z.looseObject:_.z.object)(r);return this.transform(t).pipe(n)};if(!(Ae in globalThis)){globalThis[Ae]=!0;for(let e of Object.keys(_.z)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=_.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(_.z.ZodDefault.prototype,"label",{get(){return Tn.bind(this)}}),Object.defineProperty(_.z.ZodObject.prototype,"remap",{get(){return wn.bind(this)}})}function kr(e){return e}var Gt=require("zod/v4");var ce=y(require("ramda"),1),Qe=require("zod/v4");var pe=y(require("ramda"),1),Ft=require("zod/v4");var Ar=require("zod/v4"),he=Symbol("Buffer"),dt=()=>Ar.z.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(he);var Ce=require("zod/v4"),be=Symbol("DateIn"),Cr=({examples:e,...t}={})=>Ce.z.union([Ce.z.iso.date(),Ce.z.iso.datetime(),Ce.z.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ce.z.date()).brand(be).meta(t);var Ir=require("zod/v4"),xe=Symbol("DateOut"),Nr=({examples:e,...t}={})=>Ir.z.date().transform(r=>r.toISOString()).brand(xe).meta({...t,examples:e});var zr=require("zod/v4");var H=y(require("ramda"),1),Ie=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,mt=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},Bt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},vn=["body","query","params"],Ht=e=>e.method.toLowerCase(),lt=(e,t={})=>{let r=Ht(e);return r==="options"?{}:(t[r]||Bt[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 Ie.z.ZodError?new Ie.z.ZodRealError(e.issues):new Error(String(e)),oe=e=>e instanceof Ie.z.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Ie.z.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,Ne=(e,t)=>e._zod.def.type===t,Se=(e,t,r)=>e.length&&t.length?H.xprod(e,t).map(r):e.concat(t),qt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ne=(...e)=>{let t=H.chain(o=>o.split(/[^A-Z0-9]/gi),e);return H.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(qt).join("")},ut=H.tryCatch((e,t)=>typeof Ie.z.parse(e,t),H.always(void 0)),M=e=>typeof e=="object"&&e!==null,Re=H.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var se=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.`}},Ve=class extends Error{name="IOSchemaError"},ft=class extends Ve{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},ze=class extends Ve{constructor(r){let o=new zr.z.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(oe(o),{cause:r});this.cause=r}name="OutputValidationError"},V=class extends Ve{constructor(r){super(oe(r),{cause:r});this.cause=r}name="InputValidationError"},ie=class extends Error{constructor(r,o){super(oe(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},je=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var Kt=require("zod/v4"),Ge=Symbol("Form"),jr=e=>(e instanceof Kt.z.ZodObject?e:Kt.z.object(e)).brand(Ge);var Lr=require("zod/v4"),ae=Symbol("Upload"),Mr=()=>Lr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(ae);var Zr=require("zod/v4");var q=Symbol("Raw"),$r=Zr.z.object({raw:dt()}),kn=e=>$r.extend(e).brand(q);function Br(e){return e?kn(e):$r.brand(q)}var Hr=(e,{io:t,condition:r})=>pe.tryCatch(()=>{Ft.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new ft(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(pe.is(Object,n)){if(n.$ref==="#")return!0;o.push(...pe.values(n))}pe.is(Array,n)&&o.push(...pe.values(n))}return!1},Kr=e=>Hr(e,{condition:t=>{let r=X(t);return typeof r=="symbol"&&[ae,q,Ge].includes(r)},io:"input"}),An=["nan","symbol","map","set","bigint","void","promise","never"],Ut=(e,t)=>Hr(e,{io:t,condition:r=>{let o=X(r),{type:n}=r._zod.def;return!!(An.includes(n)||o===he||t==="input"&&(n==="date"||o===xe)||t==="output"&&(o===be||o===q||o===ae))}});var gt=y(require("http-errors"),1);var We=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 ie(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}))},Ye=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Oe=e=>(0,We.isHttpError)(e)?e:(0,We.default)(e instanceof V?400:500,oe(e),{cause:e.cause||e}),Te=e=>Re()&&!e.expose?(0,We.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 Se(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=Te((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 Jt=class{},K=class extends Jt{#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 V(o):o}}},Le=class extends K{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 Me=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends Me{},bt=class e extends Xe{#e;#t=ce.once(()=>{let t=this.#e.outputSchema.meta();if(t?.examples?.length||!Ne(this.#e.outputSchema,"object"))return;let r=Ur(this.#e.outputSchema);r.length&&Qe.globalRegistry.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...t,examples:r})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Kr(this.#e.inputSchema);if(t){let r=X(t);if(r===ae)return"upload";if(r===q)return"raw";if(r===Ge)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ce.pluck("security",this.#e.middlewares||[]);return ce.reject(ce.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Qe.z.ZodError?new ze(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Le))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Qe.z.ZodError?new V(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){ht({...t,error:new ie(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ht(t),i={},p={output:{},error:null},d=lt(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#i({...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 Ze={positive:200,negative:400},$e=Object.keys(Ze);var Vt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},de=class extends Vt{#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:[Ze.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Dt(this.#t,{variant:"negative",args:[],statusCodes:[Ze.negative],mimeTypes:[E.json]})}},me=new de({positive:e=>{let t=C.z.object({status:C.z.literal("success"),data:e}),{examples:r=[]}=C.globalRegistry.get(e)||{};return r.length&&C.globalRegistry.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},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=Oe(e);return Ye(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Te(i)}})}n.status(Ze.positive).json({status:"success",data:r})}}),xt=new de({positive:e=>{let t=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()),r=t.meta();if(r?.examples?.length)return t;let o=(C.globalRegistry.get(e)?.examples||[]).filter(n=>M(n)&&"items"in n&&Array.isArray(n.items)).map(n=>n.items);return o.length&&C.globalRegistry.remove(t).add(t,{...r,examples:o}),t},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=Oe(r);return Ye(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(Te(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 le=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof K?t:new K(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new K({handler:t})),this.resultHandler)}build({input:t=Gt.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:Gt.z.object({}),handler:async o=>(await t(o),{})})}},Jr=new le(me),Vr=new le(xt);var eo=y(require("ansis"),1),to=require("node:util"),Yt=require("node:perf_hooks");var G=require("ansis"),Gr=y(require("ramda"),1);var Wt={debug:G.blue,info:G.green,warn:(0,G.hex)("#FFA500"),error:G.red,ctx:G.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],Cn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Be=Gr.memoizeWith((e,t)=>`${e}${t}`,Cn),Xr=e=>e<1e-6?Be("nanosecond",3).format(e/1e-6):e<.001?Be("nanosecond").format(e/1e-6):e<1?Be("microsecond").format(e/.001):e<1e3?Be("millisecond").format(e):e<6e4?Be("second",2).format(e/1e3):Be("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=eo.default.isSupported(),level:r=Re()?"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?Wt.ctx(s):s),d.push(p?`${Wt[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=Yt.performance.now();return()=>{let o=Yt.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 qe=class e extends Me{#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),Ke=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 Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new je(e)};var po=y(require("http-errors"),1);var Qt=require("zod/v4");var S=y(require("ramda"),1);var In=e=>e.type==="object",Nn=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")}),zn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),no=S.pair(!0),Ue=(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"&&zn(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=Se(o.examples?.filter(M)||[],i.examples.filter(M),([p,d])=>S.mergeDeepRight(p,d))),!!In(i)&&(r.push([s,{examples:jn(i)}]),i.properties&&(o.properties=(t==="throw"?Nn: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},jn=e=>Object.entries(e.properties||{}).reduce((t,[r,{examples:o=[]}])=>Se(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=[Qt.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 $e)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=mt(t);if(s.length===0)return;let i=n?.flat||Ue(Qt.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 Xt=["get","post","put","delete","patch"],so=e=>Xt.includes(e);var Ln=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&so(t)?[r,t]:[e]},Mn=e=>e.trim().split("/").filter(Boolean).join("/"),io=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Ln(r);return[[t||""].concat(Mn(n)||[]).join("/"),o,s]}),Zn=(e,t)=>{throw new se("Route with explicit method can only be assigned with Endpoint",e,t)},ao=(e,t,r)=>{if(!(!r||r.includes(e)))throw new se(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},er=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new se("Route has a duplicate",e,t);r.add(o)},De=({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)er(p,s,n),ao(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)er(c,s,n),t(i,s,c)}else if(p&&Zn(p,s),i instanceof Ke)r&&i.apply(s,r);else if(i instanceof qe)for(let[d,c]of i.entries){let{methods:m}=c;er(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(),$n=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)},Bn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":mo(e),"Access-Control-Allow-Headers":"content-type"}),tr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new Rt(t()),i=new Map;De({routing:o,onEndpoint:(c,m,h)=>{Re()||(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 N=t(Z);if(r.cors){let I=Bn(h),D=typeof r.cors=="function"?await r.cors({request:Z,endpoint:k,logger:N,defaultHeaders:I}):I;O.set(D)}return k.execute({request:Z,response:O,logger:N,config:r})};e[b](c,...g,A)}r.wrongMethodBehavior!==404&&d.set(c,$n(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 ie(re(i),n)})}},Hn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},qn=e=>({log:e.debug.bind(e)}),Oo=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:qn(m)})(p,d,c)}),o&&i.push(Hn(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[Ae]={logger:i}),s()},wo=e=>t=>t?.res?.locals[Ae]?.logger||e,Eo=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
1
+ "use strict";var fn=Object.create;var ct=Object.defineProperty;var yn=Object.getOwnPropertyDescriptor;var gn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,bn=Object.prototype.hasOwnProperty;var xn=(e,t)=>{for(var r in t)ct(e,r,{get:t[r],enumerable:!0})},vr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of gn(t))!bn.call(e,n)&&n!==r&&ct(e,n,{get:()=>t[n],enumerable:!(o=yn(t,n))||o.enumerable});return e};var y=(e,t,r)=>(r=e!=null?fn(hn(e)):{},vr(t||!e||!e.__esModule?ct(r,"default",{value:e,enumerable:!0}):r,e)),Sn=e=>vr(ct({},"__esModule",{value:!0}),e);var qs={};xn(qs,{BuiltinLogger:()=>He,DependsOnMethod:()=>Ke,Documentation:()=>Tt,DocumentationError:()=>V,EndpointsFactory:()=>ue,EventStreamFactory:()=>jt,InputValidationError:()=>G,Integration:()=>Nt,Middleware:()=>q,MissingPeerError:()=>ze,OutputValidationError:()=>je,ResultHandler:()=>me,RoutingError:()=>ie,ServeStatic:()=>qe,arrayEndpointsFactory:()=>Vr,arrayResultHandler:()=>xt,attachRouting:()=>No,createConfig:()=>kr,createServer:()=>jo,defaultEndpointsFactory:()=>Jr,defaultResultHandler:()=>le,ensureHttpError:()=>Oe,ez:()=>un,getMessageFromError:()=>ne,testEndpoint:()=>en,testMiddleware:()=>tn});module.exports=Sn(qs);var L=y(require("ramda"),1),J=require("zod/v4");var Ce=Symbol.for("express-zod-api"),ee=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Rn=J.z.core.$constructor("$EZBrandCheck",(e,t)=>{J.z.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),On=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},Tn=function(){return this.meta({deprecated:!0})},Pn=function(e){return this.meta({default:e})},wn=function(e){return this.check(new Rn({brand:e,check:"$EZBrandCheck"}))},En=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 J.z.ZodUnknown?J.z.looseObject:J.z.object)(r);return this.transform(t).pipe(n)};if(!(Ce in globalThis)){globalThis[Ce]=!0;for(let e of Object.keys(J.z)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=J.z[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:On,writable:!1},deprecated:{value:Tn,writable:!1},brand:{set(){},get(){return wn.bind(this)}}})}Object.defineProperty(J.z.ZodDefault.prototype,"label",{value:Pn,writable:!1}),Object.defineProperty(J.z.ZodObject.prototype,"remap",{value:En,writable:!1})}function kr(e){return e}var Gt=require("zod/v4");var de=y(require("ramda"),1),Qe=require("zod/v4");var ce=y(require("ramda"),1),Ft=require("zod/v4");var Cr=require("zod/v4"),he=Symbol("Buffer"),dt=()=>Cr.z.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(he);var Ae=require("zod/v4"),be=Symbol("DateIn"),Ar=({examples:e,...t}={})=>Ae.z.union([Ae.z.iso.date(),Ae.z.iso.datetime(),Ae.z.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ae.z.date()).brand(be).meta(t);var Ir=require("zod/v4"),xe=Symbol("DateOut"),Nr=({examples:e,...t}={})=>Ir.z.date().transform(r=>r.toISOString()).brand(xe).meta({...t,examples:e});var jr=require("zod/v4");var H=y(require("ramda"),1),Ie=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,mt=e=>e.match($t)?.map(t=>t.slice(1))||[],vn=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(E.upload);return"files"in e&&r},Bt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},kn=["body","query","params"],Ht=e=>e.method.toLowerCase(),lt=(e,t={})=>{let r=Ht(e);return r==="options"?{}:(t[r]||Bt[r]||kn).filter(o=>o==="files"?vn(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},oe=e=>e instanceof Error?e:e instanceof Ie.z.ZodError?new Ie.z.ZodRealError(e.issues):new Error(String(e)),ne=e=>e instanceof Ie.z.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Ie.z.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,Ne=(e,t)=>e._zod.def.type===t,Se=(e,t,r)=>e.length&&t.length?H.xprod(e,t).map(r):e.concat(t),Kt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),se=(...e)=>{let t=H.chain(o=>o.split(/[^A-Z0-9]/gi),e);return H.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Kt).join("")},ut=H.tryCatch((e,t)=>typeof Ie.z.parse(e,t),H.always(void 0)),M=e=>typeof e=="object"&&e!==null,Re=H.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var ie=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},V=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},Ve=class extends Error{name="IOSchemaError"},ft=class extends Ve{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},je=class extends Ve{constructor(r){let o=new jr.z.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(ne(o),{cause:r});this.cause=r}name="OutputValidationError"},G=class extends Ve{constructor(r){super(ne(r),{cause:r});this.cause=r}name="InputValidationError"},ae=class extends Error{constructor(r,o){super(ne(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},ze=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var qt=require("zod/v4"),Ge=Symbol("Form"),zr=e=>(e instanceof qt.z.ZodObject?e:qt.z.object(e)).brand(Ge);var Lr=require("zod/v4"),pe=Symbol("Upload"),Mr=()=>Lr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(pe);var Zr=require("zod/v4");var K=Symbol("Raw"),$r=Zr.z.object({raw:dt()}),Cn=e=>$r.extend(e).brand(K);function Br(e){return e?Cn(e):$r.brand(K)}var Hr=(e,{io:t,condition:r})=>ce.tryCatch(()=>{Ft.z.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new ft(o)}})},o=>o.cause)(),Kr=(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(ce.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ce.values(n))}ce.is(Array,n)&&o.push(...ce.values(n))}return!1},qr=e=>Hr(e,{condition:t=>{let r=ee(t);return typeof r=="symbol"&&[pe,K,Ge].includes(r)},io:"input"}),An=["nan","symbol","map","set","bigint","void","promise","never"],Ut=(e,t)=>Hr(e,{io:t,condition:r=>{let o=ee(r),{type:n}=r._zod.def;return!!(An.includes(n)||o===he||t==="input"&&(n==="date"||o===xe)||t==="output"&&(o===be||o===K||o===pe))}});var gt=y(require("http-errors"),1);var We=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 ae(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}))},Ye=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Oe=e=>(0,We.isHttpError)(e)?e:(0,We.default)(e instanceof G?400:500,ne(e),{cause:e.cause||e}),Te=e=>Re()&&!e.expose?(0,We.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 Se(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=Te((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 Jt=class{},q=class extends Jt{#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}}},Le=class extends q{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 Me=class{nest(t){return Object.assign(t,{"":this})}};var Xe=class extends Me{},bt=class e extends Xe{#e;#t=de.once(()=>{let t=this.#e.outputSchema.meta();if(t?.examples?.length||!Ne(this.#e.outputSchema,"object"))return;let r=Ur(this.#e.outputSchema);r.length&&Qe.globalRegistry.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...t,examples:r})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=qr(this.#e.inputSchema);if(t){let r=ee(t);if(r===pe)return"upload";if(r===K)return"raw";if(r===Ge)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=de.pluck("security",this.#e.middlewares||[]);return de.reject(de.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Qe.z.ZodError?new je(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof Le))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Qe.z.ZodError?new G(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){ht({...t,error:new ae(oe(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=Ht(t),i={},p={output:{},error:null},d=lt(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:oe(c)}}await this.#i({...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 A=require("zod/v4");var Ze={positive:200,negative:400},$e=Object.keys(Ze);var Vt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},me=class extends Vt{#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:[Ze.positive],mimeTypes:[E.json]})}getNegativeResponse(){return Dt(this.#t,{variant:"negative",args:[],statusCodes:[Ze.negative],mimeTypes:[E.json]})}},le=new me({positive:e=>{let t=A.z.object({status:A.z.literal("success"),data:e}),{examples:r=[]}=A.globalRegistry.get(e)||{};return r.length&&A.globalRegistry.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:A.z.object({status:A.z.literal("error"),error:A.z.object({message:A.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=Oe(e);return Ye(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:Te(i)}})}n.status(Ze.positive).json({status:"success",data:r})}}),xt=new me({positive:e=>{let t=e instanceof A.z.ZodObject&&"items"in e.shape&&e.shape.items instanceof A.z.ZodArray?e.shape.items:A.z.array(A.z.any()),r=t.meta();if(r?.examples?.length)return t;let o=(A.globalRegistry.get(e)?.examples||[]).filter(n=>M(n)&&"items"in n&&Array.isArray(n.items)).map(n=>n.items);return o.length&&A.globalRegistry.remove(t).add(t,{...r,examples:o}),t},negative:A.z.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Oe(r);return Ye(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(Te(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 ue=class e{constructor(t){this.resultHandler=t}middlewares=[];static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof q?t:new q(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new Le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new q({handler:t})),this.resultHandler)}build({input:t=Gt.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,x=typeof n=="string"?[n]:n||[],g=typeof s=="string"?[s]:s||[];return new bt({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:x,tags:g,methods:m,getOperationId:h,inputSchema:_r(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Gt.z.object({}),handler:async o=>(await t(o),{})})}},Jr=new ue(le),Vr=new ue(xt);var eo=y(require("ansis"),1),to=require("node:util"),Yt=require("node:perf_hooks");var W=require("ansis"),Gr=y(require("ramda"),1);var Wt={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}),Be=Gr.memoizeWith((e,t)=>`${e}${t}`,In),Xr=e=>e<1e-6?Be("nanosecond",3).format(e/1e-6):e<.001?Be("nanosecond").format(e/1e-6):e<1?Be("microsecond").format(e/.001):e<1e3?Be("millisecond").format(e):e<6e4?Be("second",2).format(e/1e3):Be("minute",2).format(e/6e4);var He=class e{config;constructor({color:t=eo.default.isSupported(),level:r=Re()?"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?Wt.ctx(s):s),d.push(p?`${Wt[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=Yt.performance.now();return()=>{let o=Yt.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 Me{#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),Co=y(require("node:http"),1),Ao=y(require("node:https"),1);var Fe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>y(require(e))))[t]}catch{}throw new ze(e)};var po=y(require("http-errors"),1);var Qt=require("zod/v4");var S=y(require("ramda"),1);var Nn=e=>e.type==="object",jn=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",{cause:{a:e,b:t}})}),zn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),no=S.pair(!0),Ue=(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"&&zn(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=Se(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"?jn: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=[]}])=>Se(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=[Qt.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 $e)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=mt(t);if(s.length===0)return;let i=n?.flat||Ue(Qt.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 Xt=["get","post","put","delete","patch"],so=e=>Xt.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 ie("Route with explicit method can only be assigned with Endpoint",e,t)},ao=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ie(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},er=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ie("Route has a duplicate",e,t);r.add(o)},De=({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)er(p,s,n),ao(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)er(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;er(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(),Bn=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)},Hn=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":mo(e),"Access-Control-Allow-Headers":"content-type"}),tr=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=Re()?void 0:new Rt(t()),i=new Map;De({routing:o,onEndpoint:(c,m,h)=>{Re()||(s?.checkSchema(c,{path:m,method:h}),s?.checkPathParams(m,c,{method:h}));let x=n?.[c.requestType]||[],g=co.pair(x,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[x,[g,k]]of m){let C=async(Z,O)=>{let N=t(Z);if(r.cors){let I=Hn(h),_=typeof r.cors=="function"?await r.cors({request:Z,endpoint:k,logger:N,defaultHeaders:I}):I;O.set(_)}return k.execute({request:Z,response:O,logger:N,config:r})};e[x](c,...g,C)}r.wrongMethodBehavior!==404&&d.set(c,Bn(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:oe(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 ae(oe(i),n)})}},Kn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},qn=e=>({log:e.debug.bind(e)}),Oo=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:qn(m)})(p,d,c)}),o&&i.push(Kn(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
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
@@ -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 Io=e=>{e.startupLogo!==!1&&ko(process.stdout);let t=e.errorHandler||me,r=Wr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v24.0.0-beta.8 (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 tr({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 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(),To],form:[e.formParser||et.default.urlencoded()],upload:e.upload?await Oo({config:e,getLogger:o}):[]};tr({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 c.length||r.warn("No servers configured."),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,rr=e=>!Lo(e)&&!jo(e),Mo=e=>{let t=R.filter(rr,e),r=R.chain(R.prop("and"),R.filter(Lo,e)),[o,n]=R.partition(rr,r),s=R.concat(t,o),i=R.filter(jo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>Se(d,R.map(m=>rr(m)?[m]:m.and,c),([m,h])=>R.concat(m,h)),R.reject(R.isEmpty,[s]))};var ue=require("openapi3-ts/oas31"),l=y(require("ramda"),1),or=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,Ho="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:[]},Ko=e=>e.replace($t,t=>`{${t.slice(1)}}`),Fn=({},e)=>{if(e.isResponse)throw new J("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Un=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),Dn=({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}}},_n=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ue(e,"throw")},(e,{jsonSchema:t})=>t),Jn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:ts(t.type)})},Bo=e=>e in qo,Vn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Gn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Pe=({$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(Pe));return s&&(p.not=Pe(s)),p},Wn=({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:Ho}};return e?.length&&(o.examples=e),o},Yn=({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:Ho}};return e?.length&&(o.examples=e),o},Qn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Xn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},es=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},ts=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],rs=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!Ne(o,"transform"))return t;let s=Pe(ir(n,{ctx:r}));if((0,ue.isSchemaObject)(s))if(r.isResponse){let i=ut(o,es(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},os=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},nr=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ns=(e,t)=>t?.includes(e)||e.startsWith("x-")||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=Ue(r),m=mt(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)??ns(O,A));return Object.entries(c.properties).reduce((O,[N,I])=>{let D=k(N)?"path":Z(N)?"header":h?"query":void 0;if(!D)return O;let j=Pe(I),ee=s==="components"?n(I.id||JSON.stringify(I),j,ne(d,N)):j;return O.concat({name:N,in:D,deprecated:I.deprecated,required:c.required?.includes(N)||!1,description:j.description||d,schema:ee,examples:nr((0,ue.isSchemaObject)(j)&&j.examples?.length?j.examples:l.pluck(N,c.examples?.filter(l.both(M,l.has(N)))||[]))})},[])},sr={nullable:Jn,union:Dn,bigint:Qn,intersection:_n,tuple:Xn,pipe:rs,literal:Gn,enum:Vn,[be]:Wn,[xe]:Yn,[ae]:Fn,[q]:os,[he]:Un},ss=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,ue.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Pe(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},ir=(e,{ctx:t,rules:r=sr})=>{let{$defs:o={},properties:n={}}=or.z.toJSONSchema(or.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 ss(n.subject,o,t)},Uo=(e,t)=>{if((0,ue.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=Pe(ir(r,{rules:{...c,...sr},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];(0,ue.isSchemaObject)(h)&&h.examples&&(b.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,ne(m)):h,examples:nr(b)};return{description:m,content:l.fromPairs(l.xprod(o,[g]))}},is=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},as=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ps=({name:e})=>({type:"apiKey",in:"header",name:e}),cs=({name:e})=>({type:"apiKey",in:"cookie",name:e}),ds=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ms=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),_o=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?is(o):o.type==="input"?as(o,t):o.type==="header"?ps(o):o.type==="cookie"?cs(o):o.type==="openid"?ds(o):ms(o);return e.map(o=>o.map(r))},Jo=(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:[]})},{})),Vo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>ir(e,{rules:{...t,...sr},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(Pe(o),p),h=[];(0,ue.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,ne(d)):c,examples:nr(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},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)},[]),ar=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||ne(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 Z={path:k,method:A,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:N,scopes:I,inputSchema:D}=g,j=N?ar(N):m&&O?ar(O):void 0,ee=r.inputSources?.[A]||Bt[A],ke=this.#n(k,A,g.getOperationId(A)),nt=Vo({...Z,schema:D}),ye=Mo(g.security),st=Fo({...Z,inputSources:ee,isHeader:c,security:ye,request:nt,description:i?.requestParameter?.call(null,{method:A,path:k,operationId:ke})}),it={};for(let te of $e){let ge=g.getResponses(te);for(let{mimeTypes:pt,schema:Mt,statusCodes:Er}of ge)for(let Zt of Er)it[Zt]=Do({...Z,variant:te,schema:Mt,mimeTypes:pt,statusCode:Zt,hasMultipleStatusCodes:ge.length>1||Er.length>1,description:i?.[`${te}Response`]?.call(null,{method:A,path:k,operationId:ke,statusCode:Zt})})}let at=ee.includes("body")?Go({...Z,request:nt,paramNames:Qo.pluck("name",st),schema:D,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:A,path:k,operationId:ke})}):void 0,jt=Jo(_o(ye,ee),I,te=>{let ge=this.#s(te);return this.addSecurityScheme(ge,te),ge}),Lt={operationId:ke,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(Ko(k),{[A]:Lt})}}),d&&(this.rootDoc.tags=Wo(d))}};var Pt=require("node-mocks-http");var ls=e=>(0,Pt.createRequest)({...e,headers:{"content-type":E.json,...e?.headers}}),us=e=>(0,Pt.createResponse)(e),fs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Yr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Xo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ls(e),s=us({req:n,...t});s.req=t?.req||n,n.res=s;let i=fs(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=me}}=Xo(r),d=lt(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 W=y(require("ramda"),1),u=y(require("typescript"),1),a=u.default.factory,wt=[a.createModifier(u.default.SyntaxKind.ExportKeyword)],ys=[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)]},pr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},gs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=e=>typeof e=="string"&&gs.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),_e=e=>Object.entries(e).map(([t,r])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),mr=(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&&W.map(f,t)):e,lr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),we=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,dr(e),r?a.createToken(u.default.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.default.SyntaxKind.UndefinedKeyword)]):s),p=W.reject(W.isNil,[o?"@deprecated":void 0,n]);return p.length?pr(i,p.join(" ")):i},ur=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),fr=(...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)),yr=(e,t)=>Y(e,a.createUnionTypeNode(W.map(B,t)),{expose:!0}),Y=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?wt:void 0,e,n&&xr(n),t);return o?pr(s,o):s},rn=(e,t)=>a.createPropertyDeclaration(tt.public,e,void 0,f(t),void 0),gr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(tt.public,void 0,e,void 0,o&&xr(o),t,n,a.createBlock(r)),hr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(wt,e,r&&xr(r),void 0,t),br=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?pr(n,o):n},xr=e=>(Array.isArray(e)?e.map(t=>W.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)}),Ee=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?ys:void 0,void 0,Array.isArray(e)?W.map(vt,e):_e(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),Je=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Ct=(e,t)=>f("Extract",[e,t]),Sr=(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)]),Rr=(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),B=e=>a.createLiteralTypeNode(w(e)),hs=[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=>hs.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=yr("Method",Xt);someOfType=Y("SomeOf",F("T",br("T")),{params:["T"]});requestType=Y("Request",br(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>yr(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}])=>we(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>z("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(dr(t),a.createArrayLiteralExpression(sn.map(w,r))))),{expose:!0});makeImplementationType=()=>Y(this.#e.implementationType,Rr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:lr,[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,Ee({[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,Ee({[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:lr},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([Sr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Et(":",[this.#e.keyParameter]),Ee([],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=()=>gr(this.#e.provideMethod,_e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:F(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[z(fr(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=>hr(t,[mr([vt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:tt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Et("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(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,Ee([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=()=>mr(_e({request:"K",params:F(this.interfaces.input,"K")}),[z(fr(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)),Sr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([we(T("event"),t)]);#i=()=>gr(this.#e.onMethod,_e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Rr({[this.#e.dataParameter.text]:F(Ct("R",ur(this.#s("E"))),B(T("data")))},on(U.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,Ee([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",B(T("event")))}});makeSubscriptionClass=t=>hr(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"),ur(this.#s(U.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[z(this.#e.clientConst,Je(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(Je(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),Ee(["time"],a.createBlock([])))]};var v=y(require("ramda"),1),x=y(require("typescript"),1),an=require("zod/v4");var Or=(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=>Or(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}=x.default,bs={[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},Tr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},xs=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.default.SyntaxKind.UndefinedKeyword):B(r));return t.length===1?t[0]:Q.createUnionTypeNode(t)},Ss=(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 we(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return Q.createTypeLiteralNode(s)};return qr(e,{io:t?"output":"input"})?o(e,n):n()},Rs=({_zod:{def:e}},{next:t})=>Q.createArrayTypeNode(t(e.element)),Os=({_zod:{def:e}})=>Q.createUnionTypeNode(Object.values(e.entries).map(B)),Ts=({_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 Q.createUnionTypeNode(Array.from(r.values()))},Ps=e=>bs?.[e.kind],ws=({_zod:{def:e}},{next:t})=>t(e.innerType),Es=({_zod:{def:e}},{next:t})=>Q.createUnionTypeNode([t(e.innerType),B(null)]),vs=({_zod:{def:e}},{next:t})=>Q.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:Q.createRestTypeNode(t(e.rest)))),ks=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),As=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(Tr.name,...o))return!1;if(v.both(v.eqBy(Tr.type),v.eqBy(Tr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return Q.createTypeLiteralNode(r)},(e,t)=>Q.createIntersectionTypeNode(t)),Cs=({_zod:{def:e}},{next:t})=>As([e.left,e.right].map(t)),fe=e=>()=>f(e),Pr=({_zod:{def:e}},{next:t})=>t(e.innerType),Is=({_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=ut(o,Ps(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)},Ns=()=>B(null),zs=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),js=()=>f("Buffer"),Ls=(e,{next:t})=>t(e._zod.def.shape.raw),Ms={string:fe(x.default.SyntaxKind.StringKeyword),number:fe(x.default.SyntaxKind.NumberKeyword),bigint:fe(x.default.SyntaxKind.BigIntKeyword),boolean:fe(x.default.SyntaxKind.BooleanKeyword),any:fe(x.default.SyntaxKind.AnyKeyword),undefined:fe(x.default.SyntaxKind.UndefinedKeyword),[be]:fe(x.default.SyntaxKind.StringKeyword),[xe]:fe(x.default.SyntaxKind.StringKeyword),null:Ns,array:Rs,tuple:vs,record:ks,object:Ss,literal:xs,intersection:Cs,union:Ts,default:Pr,enum:Os,optional:ws,nullable:Es,catch:Pr,pipe:Is,lazy:zs,readonly:Pr,[he]:js,[q]:Ls},wr=(e,{brandHandling:t,ctx:r})=>Or(e,{rules:{...t,...Ms},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=B(null);this.#t.set(t,Y(o,n)),this.#t.set(t,Y(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}};De({routing:t,onEndpoint:(b,g,k)=>{let A=ne.bind(null,k,g),{isDeprecated:Z,inputSchema:O,tags:N}=b,I=`${k} ${g}`,D=Y(A("input"),wr(O,c),{comment:I});this.#e.push(D);let j=$e.reduce((nt,ye)=>{let st=b.getResponses(ye),it=pn.chain(([jt,{schema:Lt,mimeTypes:te,statusCodes:ge}])=>{let pt=Y(A(ye,"variant",`${jt+1}`),wr(te?Lt:p,m),{comment:I});return this.#e.push(pt),ge.map(Mt=>we(Mt,pt.name))},Array.from(st.entries())),at=At(A(ye,"response","variants"),it,{comment:I});return this.#e.push(at),Object.assign(nt,{[ye]:at})},{});this.paths.add(g);let ee=B(I),ke={input:f(D.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(I,{isDeprecated:Z,store:ke}),this.tags.set(I,N)}}),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:cr(r,t)).join(`
18
+ `))};var Io=e=>{e.startupLogo!==!1&&ko(process.stdout);let t=e.errorHandler||le,r=Wr(e.logger)?e.logger:new He(e.logger);r.debug("Running",{build:"v24.0.0-beta.9 (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 tr({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},jo=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 x=await Fe("compression");p.use(x(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}):[]};tr({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(x,g)=>()=>x.listen(g,()=>r.info("Listening",g)),h=[];if(e.http){let x=Co.default.createServer(p);c.push(x),h.push(m(x,e.http.listen))}if(e.https){let x=Ao.default.createServer(e.https.options,p);c.push(x),h.push(m(x,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&vo({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:h.map(x=>x())}};var Yo=require("openapi3-ts/oas31"),Qo=y(require("ramda"),1);var R=y(require("ramda"),1);var zo=e=>M(e)&&"or"in e,Lo=e=>M(e)&&"and"in e,rr=e=>!Lo(e)&&!zo(e),Mo=e=>{let t=R.filter(rr,e),r=R.chain(R.prop("and"),R.filter(Lo,e)),[o,n]=R.partition(rr,r),s=R.concat(t,o),i=R.filter(zo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>Se(d,R.map(m=>rr(m)?[m]:m.and,c),([m,h])=>R.concat(m,h)),R.reject(R.isEmpty,[s]))};var fe=require("openapi3-ts/oas31"),l=y(require("ramda"),1),or=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,Ho="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Ko={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},qo=e=>e.replace($t,t=>`{${t.slice(1)}}`),Un=({},e)=>{if(e.isResponse)throw new V("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Dn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),_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}}},Jn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ue(e,"throw")},(e,{jsonSchema:t})=>t),Vn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:rs(t.type)})},Bo=e=>e in Ko,Gn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Wn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),Pe=({$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(Pe));return s&&(p.not=Pe(s)),p},Yn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new V("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ho}};return e?.length&&(o.examples=e),o},Qn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new V("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ho}};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 Ko?.[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=Pe(ir(n,{ctx:r}));if((0,fe.isSchemaObject)(s))if(r.isResponse){let i=ut(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},nr=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=Ue(r),m=mt(e),h=o.includes("query"),x=o.includes("params"),g=o.includes("headers"),k=O=>x&&m.includes(O),C=l.chain(l.filter(O=>O.type==="header"),p??[]).map(({name:O})=>O),Z=O=>g&&(i?.(O,t,e)??ss(O,C));return Object.entries(c.properties).reduce((O,[N,I])=>{let _=k(N)?"path":Z(N)?"header":h?"query":void 0;if(!_)return O;let z=Pe(I),te=s==="components"?n(I.id||JSON.stringify(I),z,se(d,N)):z;return O.concat({name:N,in:_,deprecated:I.deprecated,required:c.required?.includes(N)||!1,description:z.description||d,schema:te,examples:nr((0,fe.isSchemaObject)(z)&&z.examples?.length?z.examples:l.pluck(N,c.examples?.filter(l.both(M,l.has(N)))||[]))})},[])},sr={nullable:Vn,union:_n,bigint:Xn,intersection:Jn,tuple:es,pipe:os,literal:Wn,enum:Gn,[be]:Yn,[xe]:Qn,[pe]:Un,[K]:ns,[he]:Dn},is=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if((0,fe.isReferenceObject)(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Pe(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},ir=(e,{ctx:t,rules:r=sr})=>{let{$defs:o={},properties:n={}}=or.z.toJSONSchema(or.z.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=ee(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,fe.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} ${Kt(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let h=Pe(ir(r,{rules:{...c,...sr},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),x=[];(0,fe.isSchemaObject)(h)&&h.examples&&(x.push(...h.examples),delete h.examples);let g={schema:i==="components"?s(r,h,se(m)):h,examples:nr(x)};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))},Jo=(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:[]})},{})),Vo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>ir(e,{rules:{...t,...sr},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(Pe(o),p),h=[];(0,fe.isSchemaObject)(c)&&c.examples&&(h.push(...c.examples),delete c.examples);let x={schema:i==="components"?s(r,c,se(d)):c,examples:nr(h.length?h:Ue(o).examples?.filter(k=>M(k)&&!Array.isArray(k)).map(l.omit(p))||[])},g={description:d,content:{[n]:x}};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)},[]),ar=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 V(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,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,C)=>{let Z={path:k,method:C,endpoint:g,composition:h,brandHandling:p,makeRef:this.#o.bind(this)},{description:O,shortDescription:N,scopes:I,inputSchema:_}=g,z=N?ar(N):m&&O?ar(O):void 0,te=r.inputSources?.[C]||Bt[C],ke=this.#n(k,C,g.getOperationId(C)),nt=Vo({...Z,schema:_}),ye=Mo(g.security),st=Fo({...Z,inputSources:te,isHeader:c,security:ye,request:nt,description:i?.requestParameter?.call(null,{method:C,path:k,operationId:ke})}),it={};for(let re of $e){let ge=g.getResponses(re);for(let{mimeTypes:pt,schema:Mt,statusCodes:Er}of ge)for(let Zt of Er)it[Zt]=Do({...Z,variant:re,schema:Mt,mimeTypes:pt,statusCode:Zt,hasMultipleStatusCodes:ge.length>1||Er.length>1,description:i?.[`${re}Response`]?.call(null,{method:C,path:k,operationId:ke,statusCode:Zt})})}let at=te.includes("body")?Go({...Z,request:nt,paramNames:Qo.pluck("name",st),schema:_,mimeType:E[g.requestType],description:i?.requestBody?.call(null,{method:C,path:k,operationId:ke})}):void 0,zt=Jo(_o(ye,te),I,re=>{let ge=this.#s(re);return this.addSecurityScheme(ge,re),ge}),Lt={operationId:ke,summary:z,description:O,deprecated:g.isDeprecated||void 0,tags:Ot(g.tags),parameters:Ot(st),requestBody:at,security:Ot(zt),responses:it};this.addPath(qo(k),{[C]: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=le}}=Xo(r),d=lt(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:oe(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var cn=y(require("ramda"),1),ot=y(require("typescript"),1),dn=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)]},pr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),cr=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},hs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=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),_e=e=>Object.entries(e).map(([t,r])=>vt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),mr=(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,lr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),we=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,dr(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?pr(i,p.join(" ")):i},ur=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),fr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),j=(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)),yr=(e,t)=>Q(e,a.createUnionTypeNode(Y.map(B,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?wt:void 0,e,n&&xr(n),t);return o?pr(s,o):s},rn=(e,t)=>a.createPropertyDeclaration(tt.public,e,void 0,f(t),void 0),gr=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(tt.public,void 0,e,void 0,o&&xr(o),t,n,a.createBlock(r)),hr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(wt,e,r&&xr(r),void 0,t),br=e=>a.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),kt=e=>f(Promise.name,[e]),Ct=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?wt:void 0,e,void 0,void 0,t);return o?pr(n,o):n},xr=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)}),Ee=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?Y.map(vt,e):_e(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),Je=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),At=(e,t)=>f("Extract",[e,t]),Sr=(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)]),Rr=(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),B=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=yr("Method",Xt);someOfType=Q("SomeOf",F("T",br("T")),{params:["T"]});requestType=Q("Request",br(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>yr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Ct(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>we(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(dr(t),a.createArrayLiteralExpression(sn.map(w,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,Rr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:lr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},kt(U.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:U.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,Ee({[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=()=>j(this.#e.substituteFn,Ee({[this.#e.pathParameter.text]:U.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:lr},a.createBlock([j(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([Sr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Et(":",[this.#e.keyParameter]),Ee([],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=()=>gr(this.#e.provideMethod,_e({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:F(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(fr(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=>hr(t,[mr([vt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:tt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Et("?",[Je(URLSearchParams.name,t)]);#o=()=>Je(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=j(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([w("get"),w("delete")]),T("includes"))(this.#e.methodParameter))),i=j(this.#e.searchParamsConst,rt(this.#e.hasBodyConst,w(""),this.#r(this.#e.paramsArgument))),p=j(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=j(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 j(this.#e.defaultImplementationConst,Ee([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=()=>mr(_e({request:"K",params:F(this.interfaces.input,"K")}),[j(fr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),w(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Sr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Je("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([we(T("event"),t)]);#i=()=>gr(this.#e.onMethod,_e({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:Rr({[this.#e.dataParameter.text]:F(At("R",ur(this.#s("E"))),B(T("data")))},on(U.default.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,Ee([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",B(T("event")))}});makeSubscriptionClass=t=>hr(t,[rn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:At(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(U.default.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:At(F(this.interfaces.positive,"K"),ur(this.#s(U.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,Je(t)),P(this.#e.clientConst,this.#e.provideMethod)(w("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",w("10"))])),P(Je(r,w("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(w("time"),Ee(["time"],a.createBlock([])))]};var v=y(require("ramda"),1),b=y(require("typescript"),1),an=require("zod/v4");var Or=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=ee(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>Or(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}=b.default,xs={[b.default.SyntaxKind.AnyKeyword]:"",[b.default.SyntaxKind.BigIntKeyword]:BigInt(0),[b.default.SyntaxKind.BooleanKeyword]:!1,[b.default.SyntaxKind.NumberKeyword]:0,[b.default.SyntaxKind.ObjectKeyword]:{},[b.default.SyntaxKind.StringKeyword]:"",[b.default.SyntaxKind.UndefinedKeyword]:void 0},Tr={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(b.default.SyntaxKind.UndefinedKeyword):B(r));return t.length===1?t[0]:X.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 we(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return X.createTypeLiteralNode(s)};return Kr(e,{io:t?"output":"input"})?o(e,n):n()},Os=({_zod:{def:e}},{next:t})=>X.createArrayTypeNode(t(e.element)),Ts=({_zod:{def:e}})=>X.createUnionTypeNode(Object.values(e.entries).map(B)),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 X.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})=>X.createUnionTypeNode([t(e.innerType),B(null)]),ks=({_zod:{def:e}},{next:t})=>X.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:X.createRestTypeNode(t(e.rest)))),Cs=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),As=v.tryCatch(e=>{if(!e.every(b.default.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(Tr.name,...o))return!1;if(v.both(v.eqBy(Tr.type),v.eqBy(Tr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return X.createTypeLiteralNode(r)},(e,t)=>X.createIntersectionTypeNode(t)),Is=({_zod:{def:e}},{next:t})=>As([e.left,e.right].map(t)),D=e=>()=>f(e),Pr=({_zod:{def:e}},{next:t})=>t(e.innerType),pn=e=>f(e?b.default.SyntaxKind.UnknownKeyword:b.default.SyntaxKind.AnyKeyword),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=ut(o,ws(s)),p={number:b.default.SyntaxKind.NumberKeyword,bigint:b.default.SyntaxKind.BigIntKeyword,boolean:b.default.SyntaxKind.BooleanKeyword,string:b.default.SyntaxKind.StringKeyword,undefined:b.default.SyntaxKind.UndefinedKeyword,object:b.default.SyntaxKind.ObjectKeyword};return f(i&&p[i]||pn(r))},js=()=>B(null),zs=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Ls=()=>f("Buffer"),Ms=(e,{next:t})=>t(e._zod.def.shape.raw),Zs={string:D(b.default.SyntaxKind.StringKeyword),number:D(b.default.SyntaxKind.NumberKeyword),bigint:D(b.default.SyntaxKind.BigIntKeyword),boolean:D(b.default.SyntaxKind.BooleanKeyword),any:D(b.default.SyntaxKind.AnyKeyword),undefined:D(b.default.SyntaxKind.UndefinedKeyword),[be]:D(b.default.SyntaxKind.StringKeyword),[xe]:D(b.default.SyntaxKind.StringKeyword),never:D(b.default.SyntaxKind.NeverKeyword),void:D(b.default.SyntaxKind.UndefinedKeyword),unknown:D(b.default.SyntaxKind.UnknownKeyword),null:js,array:Os,tuple:ks,record:Cs,object:Rs,literal:Ss,intersection:Is,union:Ps,default:Pr,enum:Ts,optional:Es,nullable:vs,catch:Pr,pipe:Ns,lazy:zs,readonly:Pr,[he]:Ls,[K]:Ms},wr=(e,{brandHandling:t,ctx:r})=>Or(e,{rules:{...t,...Zs},onMissing:({},{isResponse:o})=>pn(o),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=B(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=dn.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:(x,g,k)=>{let C=se.bind(null,k,g),{isDeprecated:Z,inputSchema:O,tags:N}=x,I=`${k} ${g}`,_=Q(C("input"),wr(O,c),{comment:I});this.#e.push(_);let z=$e.reduce((nt,ye)=>{let st=x.getResponses(ye),it=cn.chain(([zt,{schema:Lt,mimeTypes:re,statusCodes:ge}])=>{let pt=Q(C(ye,"variant",`${zt+1}`),wr(re?Lt:p,m),{comment:I});return this.#e.push(pt),ge.map(Mt=>we(Mt,pt.name))},Array.from(st.entries())),at=Ct(C(ye,"response","variants"),it,{comment:I});return this.#e.push(at),Object.assign(nt,{[ye]:at})},{});this.paths.add(g);let te=B(I),ke={input:f(_.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:a.createUnionTypeNode([F(this.interfaces.positive,te),F(this.interfaces.negative,te)]),encoded:a.createIntersectionTypeNode([f(z.positive.name),f(z.negative.name)])};this.registry.set(I,{isDeprecated:Z,store:ke}),this.tags.set(I,N)}}),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:cr(r,t)).join(`
19
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
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>cr(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 Fe("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 ve=require("zod/v4");var mn=(e,t)=>ve.z.object({data:t,event:ve.z.literal(e),id:ve.z.string().optional(),retry:ve.z.int().positive().optional()}),Zs=(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}),$s=1e4,dn=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Bs=e=>new K({handler:async({response:t})=>setTimeout(()=>dn(t),$s)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{dn(t),t.write(Zs(e,r,o),"utf-8"),t.flush?.()}}}),Hs=e=>new de({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>mn(o,n));return{mimeType:E.sse,schema:r.length?ve.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ve.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Oe(r);Ye(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(Te(i),"utf-8")}t.end()}}),zt=class extends le{constructor(t){super(Hs(t)),this.middlewares=[Bs(t)]}};var ln={dateIn:Cr,dateOut:Nr,form:jr,upload:Mr,raw:Br,buffer:dt};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});
22
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Fe("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 ve=require("zod/v4");var ln=(e,t)=>ve.z.object({data:t,event:ve.z.literal(e),id:ve.z.string().optional(),retry:ve.z.int().positive().optional()}),$s=(e,t,r)=>ln(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),Bs=1e4,mn=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":E.sse,"cache-control":"no-cache"}),Hs=e=>new q({handler:async({response:t})=>setTimeout(()=>mn(t),Bs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{mn(t),t.write($s(e,r,o),"utf-8"),t.flush?.()}}}),Ks=e=>new me({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>ln(o,n));return{mimeType:E.sse,schema:r.length?ve.z.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:ve.z.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Oe(r);Ye(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(Te(i),"utf-8")}t.end()}}),jt=class extends ue{constructor(t){super(Ks(t)),this.middlewares=[Hs(t)]}};var un={dateIn:Ar,dateOut:Nr,form:zr,upload:Mr,raw:Br,buffer:dt};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
@@ -195,8 +195,7 @@ declare abstract class AbstractMiddleware {
195
195
  }
196
196
  declare class Middleware<OPT extends FlatObject, OUT extends FlatObject, SCO extends string, IN extends IOSchema = EmptySchema> extends AbstractMiddleware {
197
197
  #private;
198
- constructor({ input, // @todo revisit
199
- security, handler, }: {
198
+ constructor({ input, security, handler, }: {
200
199
  /**
201
200
  * @desc Input schema of the Middleware, combining properties from all the enabled input sources
202
201
  * @default z.object({})
@@ -545,6 +544,7 @@ declare function createConfig(config: AppConfig): AppConfig;
545
544
 
546
545
  /** @desc this type does not allow props assignment, but it works for reading them when merged with another interface */
547
546
  type EmptyObject = z.output<EmptySchema>;
547
+ /** Avoiding z.ZodObject<Record<string, never>, $strip>, because its z.output<> is generic "object" (external issue) */
548
548
  type EmptySchema = z.ZodRecord<z.ZodString, z.ZodNever>;
549
549
  type FlatObject = Record<string, unknown>;
550
550
  /** @link https://stackoverflow.com/a/65492934 */
@@ -649,8 +649,7 @@ declare class EndpointsFactory<IN extends IOSchema = EmptySchema, OUT extends Fl
649
649
  } | undefined) => EndpointsFactory<IN, OUT & AOUT, SCO>;
650
650
  addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<IN, OUT & AOUT, SCO>;
651
651
  addOptions<AOUT extends FlatObject>(getOptions: () => Promise<AOUT>): EndpointsFactory<IN, OUT & AOUT, SCO>;
652
- build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input, // @todo revisit
653
- output: outputSchema, operationId, scope, tag, method, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO>): Endpoint<z.ZodIntersection<IN, BIN>, BOUT, OUT>;
652
+ build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input, output: outputSchema, operationId, scope, tag, method, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO>): Endpoint<z.ZodIntersection<IN, BIN>, BOUT, OUT>;
654
653
  /** @desc shorthand for returning {} while having output schema z.object({}) */
655
654
  buildVoid<BIN extends IOSchema = EmptySchema>({ handler, ...rest }: Omit<BuildProps<BIN, z.ZodVoid, IN, OUT, SCO>, "output">): Endpoint<z.ZodIntersection<IN, BIN>, z.ZodObject<{}, z.core.$strip>, OUT>;
656
655
  }
package/dist/index.d.ts CHANGED
@@ -195,8 +195,7 @@ declare abstract class AbstractMiddleware {
195
195
  }
196
196
  declare class Middleware<OPT extends FlatObject, OUT extends FlatObject, SCO extends string, IN extends IOSchema = EmptySchema> extends AbstractMiddleware {
197
197
  #private;
198
- constructor({ input, // @todo revisit
199
- security, handler, }: {
198
+ constructor({ input, security, handler, }: {
200
199
  /**
201
200
  * @desc Input schema of the Middleware, combining properties from all the enabled input sources
202
201
  * @default z.object({})
@@ -545,6 +544,7 @@ declare function createConfig(config: AppConfig): AppConfig;
545
544
 
546
545
  /** @desc this type does not allow props assignment, but it works for reading them when merged with another interface */
547
546
  type EmptyObject = z.output<EmptySchema>;
547
+ /** Avoiding z.ZodObject<Record<string, never>, $strip>, because its z.output<> is generic "object" (external issue) */
548
548
  type EmptySchema = z.ZodRecord<z.ZodString, z.ZodNever>;
549
549
  type FlatObject = Record<string, unknown>;
550
550
  /** @link https://stackoverflow.com/a/65492934 */
@@ -649,8 +649,7 @@ declare class EndpointsFactory<IN extends IOSchema = EmptySchema, OUT extends Fl
649
649
  } | undefined) => EndpointsFactory<IN, OUT & AOUT, SCO>;
650
650
  addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<IN, OUT & AOUT, SCO>;
651
651
  addOptions<AOUT extends FlatObject>(getOptions: () => Promise<AOUT>): EndpointsFactory<IN, OUT & AOUT, SCO>;
652
- build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input, // @todo revisit
653
- output: outputSchema, operationId, scope, tag, method, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO>): Endpoint<z.ZodIntersection<IN, BIN>, BOUT, OUT>;
652
+ build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({ input, output: outputSchema, operationId, scope, tag, method, ...rest }: BuildProps<BIN, BOUT, IN, OUT, SCO>): Endpoint<z.ZodIntersection<IN, BIN>, BOUT, OUT>;
654
653
  /** @desc shorthand for returning {} while having output schema z.object({}) */
655
654
  buildVoid<BIN extends IOSchema = EmptySchema>({ handler, ...rest }: Omit<BuildProps<BIN, z.ZodVoid, IN, OUT, SCO>, "output">): Endpoint<z.ZodIntersection<IN, BIN>, z.ZodObject<{}, z.core.$strip>, OUT>;
656
655
  }
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as z from"ramda";import{z as V}from"zod/v4";var Te=Symbol.for("express-zod-api"),J=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var $o=V.core.$constructor("$EZBrandCheck",(e,t)=>{V.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),Bo=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},Ho=function(){return this.meta({deprecated:!0})},qo=function(e){return this.meta({default:e})},Ko=function(e){return this.check(new $o({brand:e,check:"$EZBrandCheck"}))},Fo=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 V.ZodUnknown?V.looseObject:V.object)(r);return this.transform(t).pipe(n)};if(!(Te in globalThis)){globalThis[Te]=!0;for(let e of Object.keys(V)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=V[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{get(){return Bo.bind(this)}},deprecated:{get(){return Ho.bind(this)}},brand:{set(){},get(){return Ko.bind(this)}}})}Object.defineProperty(V.ZodDefault.prototype,"label",{get(){return qo.bind(this)}}),Object.defineProperty(V.ZodObject.prototype,"remap",{get(){return Fo.bind(this)}})}function Uo(e){return e}import{z as Ir}from"zod/v4";import*as ne from"ramda";import{z as kr,globalRegistry as sn}from"zod/v4";import*as oe from"ramda";import{z as Sr}from"zod/v4";import{z as Do}from"zod/v4";var pe=Symbol("Buffer"),tt=()=>Do.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(pe);import{z as Ze}from"zod/v4";var ce=Symbol("DateIn"),ur=({examples:e,...t}={})=>Ze.union([Ze.iso.date(),Ze.iso.datetime(),Ze.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ze.date()).brand(ce).meta(t);import{z as _o}from"zod/v4";var de=Symbol("DateOut"),fr=({examples:e,...t}={})=>_o.date().transform(r=>r.toISOString()).brand(de).meta({...t,examples:e});import{z as Go}from"zod/v4";import*as Z from"ramda";import{z as $e}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 vt=/:([A-Za-z0-9_]+)/g,rt=e=>e.match(vt)?.map(t=>t.slice(1))||[],Jo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},kt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Vo=["body","query","params"],At=e=>e.method.toLowerCase(),ot=(e,t={})=>{let r=At(e);return r==="options"?{}:(t[r]||kt[r]||Vo).filter(o=>o==="files"?Jo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},X=e=>e instanceof Error?e:e instanceof $e.ZodError?new $e.ZodRealError(e.issues):new Error(String(e)),me=e=>e instanceof $e.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${$e.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,Pe=(e,t)=>e._zod.def.type===t,le=(e,t,r)=>e.length&&t.length?Z.xprod(e,t).map(r):e.concat(t),Ct=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ee=(...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(Ct).join("")},nt=Z.tryCatch((e,t)=>typeof $e.parse(e,t),Z.always(void 0)),j=e=>typeof e=="object"&&e!==null,ue=Z.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var fe=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.`}},Be=class extends Error{name="IOSchemaError"},st=class extends Be{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},He=class extends Be{constructor(r){let o=new Go.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(me(o),{cause:r});this.cause=r}name="OutputValidationError"},W=class extends Be{constructor(r){super(me(r),{cause:r});this.cause=r}name="InputValidationError"},te=class extends Error{constructor(r,o){super(me(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},qe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as yr}from"zod/v4";var Ke=Symbol("Form"),gr=e=>(e instanceof yr.ZodObject?e:yr.object(e)).brand(Ke);import{z as Wo}from"zod/v4";var re=Symbol("Upload"),hr=()=>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(re);import{z as Yo}from"zod/v4";var $=Symbol("Raw"),br=Yo.object({raw:tt()}),Qo=e=>br.extend(e).brand($);function xr(e){return e?Qo(e):br.brand($)}var Rr=(e,{io:t,condition:r})=>oe.tryCatch(()=>{Sr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new st(o)}})},o=>o.cause)(),Or=(e,{io:t})=>{let o=[Sr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];for(;o.length;){let n=o.shift();if(oe.is(Object,n)){if(n.$ref==="#")return!0;o.push(...oe.values(n))}oe.is(Array,n)&&o.push(...oe.values(n))}return!1},Tr=e=>Rr(e,{condition:t=>{let r=J(t);return typeof r=="symbol"&&[re,$,Ke].includes(r)},io:"input"}),Xo=["nan","symbol","map","set","bigint","void","promise","never"],It=(e,t)=>Rr(e,{io:t,condition:r=>{let o=J(r),{type:n}=r._zod.def;return!!(Xo.includes(n)||o===pe||t==="input"&&(n==="date"||o===de)||t==="output"&&(o===ce||o===$||o===re))}});import on,{isHttpError as nn}from"http-errors";import Pr,{isHttpError as en}from"http-errors";import*as wr from"ramda";import{globalRegistry as tn,z as rn}from"zod/v4";var Nt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof rn.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new te(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Fe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>en(e)?e:Pr(e instanceof W?400:500,me(e),{cause:e.cause||e}),ye=e=>ue()&&!e.expose?Pr(e.statusCode).message:e.message,Er=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=tn.get(o)||{};return le(t,n.map(wr.objOf(r)),([s,i])=>({...s,...i}))},[]);var it=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ye(on(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
2
- Original error: ${e.handled.message}.`:""),{expose:nn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as vr}from"zod/v4";var zt=class{},K=class extends zt{#e;#t;#r;constructor({input:t=vr.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 vr.ZodError?new W(o):o}}},Ee=class extends K{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var ve=class{nest(t){return Object.assign(t,{"":this})}};var Ue=class extends ve{},at=class e extends Ue{#e;#t=ne.once(()=>{let t=this.#e.outputSchema.meta();if(t?.examples?.length||!Pe(this.#e.outputSchema,"object"))return;let r=Er(this.#e.outputSchema);r.length&&sn.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...t,examples:r})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Tr(this.#e.inputSchema);if(t){let r=J(t);if(r===re)return"upload";if(r===$)return"raw";if(r===Ke)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ne.pluck("security",this.#e.middlewares||[]);return ne.reject(ne.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof kr.ZodError?new He(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof 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#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof kr.ZodError?new W(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){it({...t,error:new te(X(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=At(t),i={},p={output:{},error:null},d=ot(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:X(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as Ar from"ramda";var Cr=(e,t)=>Ar.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));import{globalRegistry as pt,z as B}from"zod/v4";var ke={positive:200,negative:400},Ae=Object.keys(ke);var jt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ge=class extends jt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Nt(this.#e,{variant:"positive",args:[t],statusCodes:[ke.positive],mimeTypes:[w.json]})}getNegativeResponse(){return Nt(this.#t,{variant:"negative",args:[],statusCodes:[ke.negative],mimeTypes:[w.json]})}},he=new ge({positive:e=>{let t=B.object({status:B.literal("success"),data:e}),{examples:r=[]}=pt.get(e)||{};return r.length&&pt.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:B.object({status:B.literal("error"),error:B.object({message:B.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=we(e);return Fe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:ye(i)}})}n.status(ke.positive).json({status:"success",data:r})}}),Lt=new ge({positive:e=>{let t=e instanceof B.ZodObject&&"items"in e.shape&&e.shape.items instanceof B.ZodArray?e.shape.items:B.array(B.any()),r=t.meta();if(r?.examples?.length)return t;let o=(pt.get(e)?.examples||[]).filter(n=>j(n)&&"items"in n&&Array.isArray(n.items)).map(n=>n.items);return o.length&&pt.remove(t).add(t,{...r,examples:o}),t},negative:B.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 Fe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(ye(i))}if("items"in t&&Array.isArray(t.items))return void e.status(ke.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var be=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 K?t:new K(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 K({handler:t})),this.resultHandler)}build({input:t=Ir.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 at({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:h,tags:y,methods:m,getOperationId:g,inputSchema:Cr(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Ir.object({}),handler:async o=>(await t(o),{})})}},an=new be(he),pn=new be(Lt);import yn from"ansis";import{inspect as gn}from"node:util";import{performance as Zr}from"node:perf_hooks";import{blue as cn,green as dn,hex as mn,red as ln,cyanBright as un}from"ansis";import*as Nr from"ramda";var Mt={debug:cn,info:dn,warn:mn("#FFA500"),error:ln,ctx:un},ct={debug:10,info:20,warn:30,error:40},zr=e=>j(e)&&Object.keys(ct).some(t=>t in e),jr=e=>e in ct,Lr=(e,t)=>ct[e]<ct[t],fn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ce=Nr.memoizeWith((e,t)=>`${e}${t}`,fn),Mr=e=>e<1e-6?Ce("nanosecond",3).format(e/1e-6):e<.001?Ce("nanosecond").format(e/1e-6):e<1?Ce("microsecond").format(e/.001):e<1e3?Ce("millisecond").format(e):e<6e4?Ce("second",2).format(e/1e3):Ce("minute",2).format(e/6e4);var De=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"||Lr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Mt.ctx(s):s),d.push(p?`${Mt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),console.log(d.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Zr.now();return()=>{let o=Zr.now()-r,{message:n,severity:s="debug",formatter:i=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as $r from"ramda";var _e=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=$r.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 Je=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,hn.static(...this.#e))}};import lt from"express";import jn from"node:http";import Ln from"node:https";var Ie=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new qe(e)};import wn from"http-errors";import{z as Hr}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","additionalProperties"]),x.isEmpty),Br=x.pair(!0),Ne=(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(Br,i.anyOf)),i.oneOf&&r.push(...x.map(Br,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 dt=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=[Hr.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=It(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 Ae)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(w.json))continue;let i=It(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=rt(t);if(s.length===0)return;let i=n?.flat||Ne(Hr.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 Zt=["get","post","put","delete","patch"],qr=e=>Zt.includes(e);var On=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&qr(t)?[r,t]:[e]},Tn=e=>e.trim().split("/").filter(Boolean).join("/"),Kr=(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 fe("Route with explicit method can only be assigned with Endpoint",e,t)},Fr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new fe(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},$t=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new fe("Route has a duplicate",e,t);r.add(o)},ze=({routing:e,onEndpoint:t,onStatic:r})=>{let o=Kr(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Ue)if(p)$t(p,s,n),Fr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)$t(c,s,n),t(i,s,c)}else if(p&&Pn(p,s),i instanceof Je)r&&i.apply(s,r);else if(i instanceof _e)for(let[d,c]of i.entries){let{methods:m}=c;$t(d,s,n),Fr(d,s,m),t(c,s,d)}else o.unshift(...Kr(i,s))}};import*as Ur from"ramda";var Dr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),En=e=>({method:t},r,o)=>{let n=Dr(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":Dr(e),"Access-Control-Allow-Headers":"content-type"}),Bt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new dt(t()),i=new Map;ze({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=Ur.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 C=t(L);if(r.cors){let A=vn(g),q=typeof r.cors=="function"?await r.cors({request:L,endpoint:v,logger:C,defaultHeaders:A}):A;R.set(q)}return v.execute({request:L,response:R,logger:C,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 _r=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Jr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Vr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Gr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Wr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Yr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(_r(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",Gr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Vr(c)||Jr(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(Wr))};return{sockets:n,shutdown:()=>o??=d()}};var Qr=({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(),Xr=({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){it({response:o,logger:s,error:new te(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)}),eo=async({getLogger:e,config:t})=>{let r=await Ie("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},to=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},ro=({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[Te]={logger:i}),s()},oo=e=>t=>t?.res?.locals[Te]?.logger||e,no=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
- `).slice(1))),so=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=Yr(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 io,italic as mt,whiteBright as zn}from"ansis";var ao=e=>{if(e.columns<132)return;let t=mt("Proudly supports transgender community.".padStart(109)),r=mt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=mt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=mt("for Ashley".padEnd(20)),s=io("#F5A9B8"),i=io("#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=`
1
+ import*as j from"ramda";import{z as G}from"zod/v4";var Te=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 Bo=G.core.$constructor("$EZBrandCheck",(e,t)=>{G.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),Ho=function(e){let{examples:t=[]}=this.meta()||{},r=t.slice();return r.push(e),this.meta({examples:r})},Ko=function(){return this.meta({deprecated:!0})},qo=function(e){return this.meta({default:e})},Fo=function(e){return this.check(new Bo({brand:e,check:"$EZBrandCheck"}))},Uo=function(e){let t=typeof e=="function"?e:j.pipe(j.toPairs,j.map(([s,i])=>j.pair(e[String(s)]||s,i)),j.fromPairs),r=t(j.map(j.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof G.ZodUnknown?G.looseObject:G.object)(r);return this.transform(t).pipe(n)};if(!(Te in globalThis)){globalThis[Te]=!0;for(let e of Object.keys(G)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=G[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:Ho,writable:!1},deprecated:{value:Ko,writable:!1},brand:{set(){},get(){return Fo.bind(this)}}})}Object.defineProperty(G.ZodDefault.prototype,"label",{value:qo,writable:!1}),Object.defineProperty(G.ZodObject.prototype,"remap",{value:Uo,writable:!1})}function Do(e){return e}import{z as Ir}from"zod/v4";import*as se from"ramda";import{z as kr,globalRegistry as an}from"zod/v4";import*as ne from"ramda";import{z as Sr}from"zod/v4";import{z as _o}from"zod/v4";var pe=Symbol("Buffer"),tt=()=>_o.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(pe);import{z as Ze}from"zod/v4";var ce=Symbol("DateIn"),ur=({examples:e,...t}={})=>Ze.union([Ze.iso.date(),Ze.iso.datetime(),Ze.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(Ze.date()).brand(ce).meta(t);import{z as Jo}from"zod/v4";var de=Symbol("DateOut"),fr=({examples:e,...t}={})=>Jo.date().transform(r=>r.toISOString()).brand(de).meta({...t,examples:e});import{z as Wo}from"zod/v4";import*as Z from"ramda";import{z as $e}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 vt=/:([A-Za-z0-9_]+)/g,rt=e=>e.match(vt)?.map(t=>t.slice(1))||[],Vo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},kt={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(),ot=(e,t={})=>{let r=Ct(e);return r==="options"?{}:(t[r]||kt[r]||Go).filter(o=>o==="files"?Vo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},ee=e=>e instanceof Error?e:e instanceof $e.ZodError?new $e.ZodRealError(e.issues):new Error(String(e)),me=e=>e instanceof $e.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${$e.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,Pe=(e,t)=>e._zod.def.type===t,le=(e,t,r)=>e.length&&t.length?Z.xprod(e,t).map(r):e.concat(t),At=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(At).join("")},nt=Z.tryCatch((e,t)=>typeof $e.parse(e,t),Z.always(void 0)),z=e=>typeof e=="object"&&e!==null,ue=Z.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production");var fe=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},W=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},Be=class extends Error{name="IOSchemaError"},st=class extends Be{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},He=class extends Be{constructor(r){let o=new Wo.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(me(o),{cause:r});this.cause=r}name="OutputValidationError"},Y=class extends Be{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 yr}from"zod/v4";var qe=Symbol("Form"),gr=e=>(e instanceof yr.ZodObject?e:yr.object(e)).brand(qe);import{z as Yo}from"zod/v4";var oe=Symbol("Upload"),hr=()=>Yo.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";var $=Symbol("Raw"),br=Qo.object({raw:tt()}),Xo=e=>br.extend(e).brand($);function xr(e){return e?Xo(e):br.brand($)}var Rr=(e,{io:t,condition:r})=>ne.tryCatch(()=>{Sr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new st(o)}})},o=>o.cause)(),Or=(e,{io:t})=>{let o=[Sr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({jsonSchema:n})=>{typeof n.default=="bigint"&&delete n.default}})];for(;o.length;){let n=o.shift();if(ne.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ne.values(n))}ne.is(Array,n)&&o.push(...ne.values(n))}return!1},Tr=e=>Rr(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"],It=(e,t)=>Rr(e,{io:t,condition:r=>{let o=V(r),{type:n}=r._zod.def;return!!(en.includes(n)||o===pe||t==="input"&&(n==="date"||o===de)||t==="output"&&(o===ce||o===$||o===oe))}});import nn,{isHttpError as sn}from"http-errors";import Pr,{isHttpError as tn}from"http-errors";import*as wr from"ramda";import{globalRegistry as rn,z as on}from"zod/v4";var Nt=(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}))},Fe=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),we=e=>tn(e)?e:Pr(e instanceof Y?400:500,me(e),{cause:e.cause||e}),ye=e=>ue()&&!e.expose?Pr(e.statusCode).message:e.message,Er=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=rn.get(o)||{};return le(t,n.map(wr.objOf(r)),([s,i])=>({...s,...i}))},[]);var it=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=ye(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 vr}from"zod/v4";var jt=class{},F=class extends jt{#e;#t;#r;constructor({input:t=vr.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 vr.ZodError?new Y(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 Ue=class extends ve{},at=class e extends Ue{#e;#t=se.once(()=>{let t=this.#e.outputSchema.meta();if(t?.examples?.length||!Pe(this.#e.outputSchema,"object"))return;let r=Er(this.#e.outputSchema);r.length&&an.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...t,examples:r})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Tr(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 t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=se.pluck("security",this.#e.middlewares||[]);return se.reject(se.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof kr.ZodError?new He(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof 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#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof kr.ZodError?new Y(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){it({...t,error:new re(ee(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=ot(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:ee(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};import*as Cr from"ramda";var Ar=(e,t)=>Cr.pluck("schema",e).concat(t).reduce((r,o)=>r.and(o));import{globalRegistry as pt,z as B}from"zod/v4";var ke={positive:200,negative:400},Ce=Object.keys(ke);var zt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},ge=class extends zt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Nt(this.#e,{variant:"positive",args:[t],statusCodes:[ke.positive],mimeTypes:[w.json]})}getNegativeResponse(){return Nt(this.#t,{variant:"negative",args:[],statusCodes:[ke.negative],mimeTypes:[w.json]})}},he=new ge({positive:e=>{let t=B.object({status:B.literal("success"),data:e}),{examples:r=[]}=pt.get(e)||{};return r.length&&pt.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:B.object({status:B.literal("error"),error:B.object({message:B.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=we(e);return Fe(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:ye(i)}})}n.status(ke.positive).json({status:"success",data:r})}}),Lt=new ge({positive:e=>{let t=e instanceof B.ZodObject&&"items"in e.shape&&e.shape.items instanceof B.ZodArray?e.shape.items:B.array(B.any()),r=t.meta();if(r?.examples?.length)return t;let o=(pt.get(e)?.examples||[]).filter(n=>z(n)&&"items"in n&&Array.isArray(n.items)).map(n=>n.items);return o.length&&pt.remove(t).add(t,{...r,examples:o}),t},negative:B.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 Fe(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(ye(i))}if("items"in t&&Array.isArray(t.items))return void e.status(ke.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var be=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=Ir.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,b=typeof n=="string"?[n]:n||[],y=typeof s=="string"?[s]:s||[];return new at({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:b,tags:y,methods:m,getOperationId:g,inputSchema:Ar(d,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Ir.object({}),handler:async o=>(await t(o),{})})}},pn=new be(he),cn=new be(Lt);import gn from"ansis";import{inspect as hn}from"node:util";import{performance as Zr}from"node:perf_hooks";import{blue as dn,green as mn,hex as ln,red as un,cyanBright as fn}from"ansis";import*as Nr from"ramda";var Mt={debug:dn,info:mn,warn:ln("#FFA500"),error:un,ctx:fn},ct={debug:10,info:20,warn:30,error:40},jr=e=>z(e)&&Object.keys(ct).some(t=>t in e),zr=e=>e in ct,Lr=(e,t)=>ct[e]<ct[t],yn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),Ae=Nr.memoizeWith((e,t)=>`${e}${t}`,yn),Mr=e=>e<1e-6?Ae("nanosecond",3).format(e/1e-6):e<.001?Ae("nanosecond").format(e/1e-6):e<1?Ae("microsecond").format(e/.001):e<1e3?Ae("millisecond").format(e):e<6e4?Ae("second",2).format(e/1e3):Ae("minute",2).format(e/6e4);var De=class e{config;constructor({color:t=gn.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 hn(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"||Lr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Mt.ctx(s):s),d.push(p?`${Mt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),console.log(d.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(t){let r=Zr.now();return()=>{let o=Zr.now()-r,{message:n,severity:s="debug",formatter:i=Mr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as $r from"ramda";var _e=class e extends ve{#e;constructor(t){super(),this.#e=t}get entries(){let t=$r.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 bn from"express";var Je=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,bn.static(...this.#e))}};import lt from"express";import Ln from"node:http";import Mn from"node:https";var Ie=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ke(e)};import En from"http-errors";import{z as Hr}from"zod/v4";import*as x from"ramda";var xn=e=>e.type==="object",Sn=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",{cause:{a:e,b:t}})}),Rn=x.pipe(Object.keys,x.without(["type","properties","required","examples","description","additionalProperties"]),x.isEmpty),Br=x.pair(!0),Ne=(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"&&Rn(p)))throw new Error("Can not merge");return x.pair(s,p)})),i.anyOf&&r.push(...x.map(Br,i.anyOf)),i.oneOf&&r.push(...x.map(Br,i.oneOf)),i.examples?.length&&(s?o.examples=x.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(z)||[],i.examples.filter(z),([p,d])=>x.mergeDeepRight(p,d))),!!xn(i)&&(r.push([s,{examples:On(i)}]),i.properties&&(o.properties=(t==="throw"?Sn: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},On=e=>Object.entries(e.properties||{}).reduce((t,[r,{examples:o=[]}])=>le(t,o.map(x.objOf(r)),([n,s])=>({...n,...s})),[]);var dt=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=[Hr.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=It(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=It(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=rt(t);if(s.length===0)return;let i=n?.flat||Ne(Hr.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 Zt=["get","post","put","delete","patch"],Kr=e=>Zt.includes(e);var Tn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&Kr(t)?[r,t]:[e]},Pn=e=>e.trim().split("/").filter(Boolean).join("/"),qr=(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 fe("Route with explicit method can only be assigned with Endpoint",e,t)},Fr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new fe(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},$t=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new fe("Route has a duplicate",e,t);r.add(o)},je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=qr(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof Ue)if(p)$t(p,s,n),Fr(p,s,i.methods),t(i,s,p);else{let{methods:d=["get"]}=i;for(let c of d)$t(c,s,n),t(i,s,c)}else if(p&&wn(p,s),i instanceof Je)r&&i.apply(s,r);else if(i instanceof _e)for(let[d,c]of i.entries){let{methods:m}=c;$t(d,s,n),Fr(d,s,m),t(c,s,d)}else o.unshift(...qr(i,s))}};import*as Ur from"ramda";var Dr=e=>e.sort((t,r)=>+(t==="options")-+(r==="options")).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=Dr(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":Dr(e),"Access-Control-Allow-Headers":"content-type"}),Bt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new dt(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 b=n?.[c.requestType]||[],y=Ur.pair(b,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[b,[y,v]]of m){let k=async(L,R)=>{let A=t(L);if(r.cors){let C=kn(g),q=typeof r.cors=="function"?await r.cors({request:L,endpoint:v,logger:A,defaultHeaders:C}):C;R.set(q)}return v.execute({request:L,response:R,logger:A,config:r})};e[b](c,...y,k)}r.wrongMethodBehavior!==404&&d.set(c,vn(g))}for(let[c,m]of d)e.all(c,m)};import An from"http-errors";import{setInterval as Cn}from"node:timers/promises";var _r=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Jr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Vr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Gr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Wr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Yr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(_r(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",Gr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Vr(c)||Jr(c))&&i(c);for await(let c of Cn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(Wr))};return{sockets:n,shutdown:()=>o??=d()}};var Qr=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:ee(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),Xr=({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){it({response:o,logger:s,error:new re(ee(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)}),eo=async({getLogger:e,config:t})=>{let r=await Ie("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},to=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},ro=({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[Te]={logger:i}),s()},oo=e=>t=>t?.res?.locals[Te]?.logger||e,no=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
3
+ `).slice(1))),so=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=Yr(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 jn,hex as io,italic as mt,whiteBright as zn}from"ansis";var ao=e=>{if(e.columns<132)return;let t=mt("Proudly supports transgender community.".padStart(109)),r=mt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=mt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=mt("for Ashley".padEnd(20)),s=io("#F5A9B8"),i=io("#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(jn,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 po=e=>{e.startupLogo!==!1&&ao(process.stdout);let t=e.errorHandler||he,r=zr(e.logger)?e.logger:new De(e.logger);r.debug("Running",{build:"v24.0.0-beta.8 (ESM)",env:process.env.NODE_ENV||"development"}),no(r);let o=ro({logger:r,config:e}),s={getLogger:oo(r),errorHandler:t},i=Xr(s),p=Qr(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Mn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=po(e);return Bt({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}=po(e),p=lt().disable("x-powered-by").use(i);if(e.compression){let h=await Ie("compression");p.use(h(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||lt.json()],raw:[e.rawParser||lt.raw(),to],form:[e.formParser||lt.urlencoded()],upload:e.upload?await eo({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=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 c.length||r.warn("No servers configured."),e.gracefulShutdown&&so({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 Ao from"ramda";import*as S from"ramda";var co=e=>j(e)&&"or"in e,mo=e=>j(e)&&"and"in e,Ht=e=>!mo(e)&&!co(e),lo=e=>{let t=S.filter(Ht,e),r=S.chain(S.prop("and"),S.filter(mo,e)),[o,n]=S.partition(Ht,r),s=S.concat(t,o),i=S.filter(co,e);return S.map(S.prop("or"),S.concat(i,n)).reduce((d,c)=>le(d,S.map(m=>Ht(m)?[m]:m.and,c),([m,g])=>S.concat(m,g)),S.reject(S.isEmpty,[s]))};import{isReferenceObject as ho,isSchemaObject as ut}from"openapi3-ts/oas31";import*as l from"ramda";import{z as fo}from"zod/v4";var uo=["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 yo=50,bo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",xo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},So=e=>e.replace(vt,t=>`{${t.slice(1)}}`),Bn=({},e)=>{if(e.isResponse)throw new G("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Hn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),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}}},Kn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ne(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)})},go=e=>e in xo,Un=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),Dn=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),xe=({$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(go):t&&go(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(xe));return s&&(p.not=xe(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:bo}};return e?.length&&(o.examples=e),o},Jn=({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:bo}};return e?.length&&(o.examples=e),o},Vn=()=>({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 xo?.[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(!Pe(o,"transform"))return t;let s=xe(Ft(n,{ctx:r}));if(ut(s))if(r.isResponse){let i=nt(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},qt=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-")||uo.includes(e),Ro=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Ne(r),m=rt(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,[C,A])=>{let q=v(C)?"path":L(C)?"header":g?"query":void 0;if(!q)return R;let N=xe(A),Y=s==="components"?n(A.id||JSON.stringify(A),N,ee(d,C)):N;return R.concat({name:C,in:q,deprecated:A.deprecated,required:c.required?.includes(C)||!1,description:N.description||d,schema:Y,examples:qt(ut(N)&&N.examples?.length?N.examples:l.pluck(C,c.examples?.filter(l.both(j,l.has(C)))||[]))})},[])},Kt={nullable:Fn,union:qn,bigint:Vn,intersection:Kn,tuple:Gn,pipe:Qn,literal:Dn,enum:Un,[ce]:_n,[de]:Jn,[re]:Bn,[$]:Xn,[pe]:Hn},ts=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(ho(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,xe(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Ft=(e,{ctx:t,rules:r=Kt})=>{let{$defs:o={},properties:n={}}=fo.toJSONSchema(fo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=J(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)},Oo=(e,t)=>{if(ho(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Oo(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]},To=({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} ${Ct(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=xe(Ft(r,{rules:{...c,...Kt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),h=[];ut(g)&&g.examples&&(h.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,ee(m)):g,examples:qt(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))}),Po=(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))},wo=(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:[]})},{})),Eo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Ft(e,{rules:{...t,...Kt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),vo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=Oo(xe(o),p),g=[];ut(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let h={schema:i==="components"?s(r,c,ee(d)):c,examples:qt(g.length?g:Ne(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},ko=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Ut=e=>e.length<=yo?e:e.slice(0,yo-1)+"\u2026",ft=e=>e.length?e.slice():void 0;var Dt=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||ee(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});ze({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:C,scopes:A,inputSchema:q}=y,N=C?Ut(C):m&&R?Ut(R):void 0,Y=r.inputSources?.[k]||kt[k],Oe=this.#n(v,k,y.getOperationId(k)),We=Eo({...L,schema:q}),ie=lo(y.security),Ye=Ro({...L,inputSources:Y,isHeader:c,security:ie,request:We,description:i?.requestParameter?.call(null,{method:k,path:v,operationId:Oe})}),Qe={};for(let Q of Ae){let ae=y.getResponses(Q);for(let{mimeTypes:et,schema:wt,statusCodes:lr}of ae)for(let Et of lr)Qe[Et]=To({...L,variant:Q,schema:wt,mimeTypes:et,statusCode:Et,hasMultipleStatusCodes:ae.length>1||lr.length>1,description:i?.[`${Q}Response`]?.call(null,{method:k,path:v,operationId:Oe,statusCode:Et})})}let Xe=Y.includes("body")?vo({...L,request:We,paramNames:Ao.pluck("name",Ye),schema:q,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:v,operationId:Oe})}):void 0,Tt=wo(Po(ie,Y),A,Q=>{let ae=this.#s(Q);return this.addSecurityScheme(ae,Q),ae}),Pt={operationId:Oe,summary:N,description:R,deprecated:y.isDeprecated||void 0,tags:ft(y.tags),parameters:ft(Ye),requestBody:Xe,security:ft(Tt),responses:Qe};this.addPath(So(v),{[k]:Pt})}}),d&&(this.rootDoc.tags=ko(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:jr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Co=({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}=Co(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=he}}=Co(r),d=ot(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 Lo from"ramda";import Ot from"typescript";import{z as Bs}from"zod/v4";import*as jo from"ramda";import D from"typescript";import*as F from"ramda";import u from"typescript";var a=u.factory,yt=[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)]},_t=(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_$]*$/,Vt=e=>typeof e=="string"&&hs.test(e)?a.createIdentifier(e):P(e),gt=(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)))),ht=(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),je=e=>Object.entries(e).map(([t,r])=>ht(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Gt=(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&&F.map(f,t)):e,Wt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Se=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Vt(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?a.createUnionTypeNode([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=F.reject(F.isNil,[o?"@deprecated":void 0,n]);return p.length?_t(i,p.join(" ")):i},Yt=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),Qt=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),I=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&yt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),Xt=(e,t)=>U(e,a.createUnionTypeNode(F.map(M,t)),{expose:!0}),U=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?yt:void 0,e,n&&or(n),t);return o?_t(s,o):s},Io=(e,t)=>a.createPropertyDeclaration(Ve.public,e,void 0,f(t),void 0),er=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ve.public,void 0,e,void 0,o&&or(o),t,n,a.createBlock(r)),tr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(yt,e,r&&or(r),void 0,t),rr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),bt=e=>f(Promise.name,[e]),xt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?yt:void 0,e,void 0,void 0,t);return o?_t(n,o):n},or=e=>(Array.isArray(e)?e.map(t=>F.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)}),Re=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?gs:void 0,void 0,Array.isArray(e)?F.map(ht,e):je(e),void 0,void 0,t),O=e=>e,Ge=(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),Le=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),St=(e,t)=>f("Extract",[e,t]),nr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),H=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),No=e=>a.createUnionTypeNode([f(e),bt(e)]),sr=(e,t)=>a.createFunctionTypeNode(void 0,je(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],zo=e=>bs.includes(e.kind);var Rt=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=Xt("Method",Zt);someOfType=U("SomeOf",H("T",rr("T")),{params:["T"]});requestType=U("Request",rr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>Xt(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>xt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Se(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>I("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Vt(t),a.createArrayLiteralExpression(jo.map(P,r))))),{expose:!0});makeImplementationType=()=>U(this.#e.implementationType,sr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:D.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Wt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},bt(D.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:D.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>I(this.#e.parseRequestFn,Re({[this.#e.requestParameter.text]:D.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,Re({[this.#e.pathParameter.text]:D.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Wt},a.createBlock([I(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],D.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([nr(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(gt(":",[this.#e.keyParameter]),Re([],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=()=>er(this.#e.provideMethod,je({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:H(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[I(Qt(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:bt(H(this.interfaces.response,"K"))});makeClientClass=t=>tr(t,[Gt([ht(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ve.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>gt("?",[Le(URLSearchParams.name,t)]);#o=()=>Le(URL.name,gt("",[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"),Ge(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),Ge(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,Ge(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(D.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,Ge(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return I(this.#e.defaultImplementationConst,Re([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=()=>Gt(je({request:"K",params:H(this.interfaces.input,"K")}),[I(Qt(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)),nr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Le("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Se(O("event"),t)]);#i=()=>er(this.#e.onMethod,je({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:sr({[this.#e.dataParameter.text]:H(St("R",Yt(this.#s("E"))),M(O("data")))},No(D.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Re([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:H("R",M(O("event")))}});makeSubscriptionClass=t=>tr(t,[Io(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:St(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(D.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:St(H(this.interfaces.positive,"K"),Yt(this.#s(D.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[I(this.#e.clientConst,Le(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Le(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Re(["time"],a.createBlock([])))]};import*as E from"ramda";import b from"typescript";import{globalRegistry as xs}from"zod/v4";var ir=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=J(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>ir(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,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},ar={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]:_.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 Se(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return _.createTypeLiteralNode(s)};return Or(e,{io:t?"output":"input"})?o(e,n):n()},Ts=({_zod:{def:e}},{next:t})=>_.createArrayTypeNode(t(e.element)),Ps=({_zod:{def:e}})=>_.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(zo(n)?n.kind:n,n)}return _.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})=>_.createUnionTypeNode([t(e.innerType),M(null)]),As=({_zod:{def:e}},{next:t})=>_.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:_.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(ar.name,...o))return!1;if(E.both(E.eqBy(ar.type),E.eqBy(ar.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),Ns=({_zod:{def:e}},{next:t})=>Is([e.left,e.right].map(t)),se=e=>()=>f(e),pr=({_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(!Pe(o,"transform"))return t(o);let s=t(n),i=nt(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=()=>f("Buffer"),Zs=(e,{next:t})=>t(e._zod.def.shape.raw),$s={string:se(b.SyntaxKind.StringKeyword),number:se(b.SyntaxKind.NumberKeyword),bigint:se(b.SyntaxKind.BigIntKeyword),boolean:se(b.SyntaxKind.BooleanKeyword),any:se(b.SyntaxKind.AnyKeyword),undefined:se(b.SyntaxKind.UndefinedKeyword),[ce]:se(b.SyntaxKind.StringKeyword),[de]:se(b.SyntaxKind.StringKeyword),null:js,array:Ts,tuple:As,record:Cs,object:Os,literal:Rs,intersection:Ns,union:ws,default:pr,enum:Ps,optional:vs,nullable:ks,catch:pr,pipe:zs,lazy:Ls,readonly:pr,[pe]:Ms,[$]:Zs},cr=(e,{brandHandling:t,ctx:r})=>ir(e,{rules:{...t,...$s},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var dr=class extends Rt{#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,U(o,n)),this.#t.set(t,U(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}};ze({routing:t,onEndpoint:(h,y,v)=>{let k=ee.bind(null,v,y),{isDeprecated:L,inputSchema:R,tags:C}=h,A=`${v} ${y}`,q=U(k("input"),cr(R,c),{comment:A});this.#e.push(q);let N=Ae.reduce((We,ie)=>{let Ye=h.getResponses(ie),Qe=Lo.chain(([Tt,{schema:Pt,mimeTypes:Q,statusCodes:ae}])=>{let et=U(k(ie,"variant",`${Tt+1}`),cr(Q?Pt:p,m),{comment:A});return this.#e.push(et),ae.map(wt=>Se(wt,et.name))},Array.from(Ye.entries())),Xe=xt(k(ie,"response","variants"),Qe,{comment:A});return this.#e.push(Xe),Object.assign(We,{[ie]:Xe})},{});this.paths.add(y);let Y=M(A),Oe={input:f(q.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([H(this.interfaces.positive,Y),H(this.interfaces.negative,Y)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(A,{isDeprecated:L,store:Oe}),this.tags.set(A,C)}}),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(`
18
+ `))};var po=e=>{e.startupLogo!==!1&&ao(process.stdout);let t=e.errorHandler||he,r=jr(e.logger)?e.logger:new De(e.logger);r.debug("Running",{build:"v24.0.0-beta.9 (ESM)",env:process.env.NODE_ENV||"development"}),no(r);let o=ro({logger:r,config:e}),s={getLogger:oo(r),errorHandler:t},i=Xr(s),p=Qr(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},Zn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=po(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}=po(e),p=lt().disable("x-powered-by").use(i);if(e.compression){let b=await Ie("compression");p.use(b(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||lt.json()],raw:[e.rawParser||lt.raw(),to],form:[e.formParser||lt.urlencoded()],upload:e.upload?await eo({config:e,getLogger:o}):[]};Bt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(b,y)=>()=>b.listen(y,()=>r.info("Listening",y)),g=[];if(e.http){let b=Ln.createServer(p);c.push(b),g.push(m(b,e.http.listen))}if(e.https){let b=Mn.createServer(e.https.options,p);c.push(b),g.push(m(b,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&so({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:g.map(b=>b())}};import{OpenApiBuilder as cs}from"openapi3-ts/oas31";import*as Co from"ramda";import*as S from"ramda";var co=e=>z(e)&&"or"in e,mo=e=>z(e)&&"and"in e,Ht=e=>!mo(e)&&!co(e),lo=e=>{let t=S.filter(Ht,e),r=S.chain(S.prop("and"),S.filter(mo,e)),[o,n]=S.partition(Ht,r),s=S.concat(t,o),i=S.filter(co,e);return S.map(S.prop("or"),S.concat(i,n)).reduce((d,c)=>le(d,S.map(m=>Ht(m)?[m]:m.and,c),([m,g])=>S.concat(m,g)),S.reject(S.isEmpty,[s]))};import{isReferenceObject as ho,isSchemaObject as ut}from"openapi3-ts/oas31";import*as l from"ramda";import{z as fo}from"zod/v4";var uo=["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 yo=50,bo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",xo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},So=e=>e.replace(vt,t=>`{${t.slice(1)}}`),Hn=({},e)=>{if(e.isResponse)throw new W("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Kn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),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}}},Fn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Ne(e,"throw")},(e,{jsonSchema:t})=>t),Un=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:Qn(t.type)})},go=e=>e in xo,Dn=({jsonSchema:e})=>({type:typeof e.enum?.[0],...e}),_n=({jsonSchema:e})=>({type:typeof(e.const||e.enum?.[0]),...e}),xe=({$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(go):t&&go(t)?t:void 0,...i};for(let[d,c]of l.toPairs({allOf:r,oneOf:o,anyOf:n}))c&&(p[d]=c.map(xe));return s&&(p.not=xe(s)),p},Jn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new W("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:bo}};return e?.length&&(o.examples=e),o},Vn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new W("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:bo}};return e?.length&&(o.examples=e),o},Gn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Wn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Yn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return xo?.[t]},Qn=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],Xn=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!Pe(o,"transform"))return t;let s=xe(Ft(n,{ctx:r}));if(ut(s))if(r.isResponse){let i=nt(o,Yn(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},es=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)?e:t.properties.raw},Kt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,ts=(e,t)=>t?.includes(e)||e.startsWith("x-")||uo.includes(e),Ro=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Ne(r),m=rt(e),g=o.includes("query"),b=o.includes("params"),y=o.includes("headers"),v=R=>b&&m.includes(R),k=l.chain(l.filter(R=>R.type==="header"),p??[]).map(({name:R})=>R),L=R=>y&&(i?.(R,t,e)??ts(R,k));return Object.entries(c.properties).reduce((R,[A,C])=>{let q=v(A)?"path":L(A)?"header":g?"query":void 0;if(!q)return R;let N=xe(C),Q=s==="components"?n(C.id||JSON.stringify(C),N,te(d,A)):N;return R.concat({name:A,in:q,deprecated:C.deprecated,required:c.required?.includes(A)||!1,description:N.description||d,schema:Q,examples:Kt(ut(N)&&N.examples?.length?N.examples:l.pluck(A,c.examples?.filter(l.both(z,l.has(A)))||[]))})},[])},qt={nullable:Un,union:qn,bigint:Gn,intersection:Fn,tuple:Wn,pipe:Xn,literal:_n,enum:Dn,[ce]:Jn,[de]:Vn,[oe]:Hn,[$]:es,[pe]:Kn},rs=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(ho(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,xe(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Ft=(e,{ctx:t,rules:r=qt})=>{let{$defs:o={},properties:n={}}=fo.toJSONSchema(fo.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 rs(n.subject,o,t)},Oo=(e,t)=>{if(ho(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Oo(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]},To=({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} ${At(n)} response ${p?d:""}`.trim()})=>{if(!o)return{description:m};let g=xe(Ft(r,{rules:{...c,...qt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),b=[];ut(g)&&g.examples&&(b.push(...g.examples),delete g.examples);let y={schema:i==="components"?s(r,g,te(m)):g,examples:Kt(b)};return{description:m,content:l.fromPairs(l.xprod(o,[y]))}},os=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ns=({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},ss=({name:e})=>({type:"apiKey",in:"header",name:e}),is=({name:e})=>({type:"apiKey",in:"cookie",name:e}),as=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ps=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Po=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?os(o):o.type==="input"?ns(o,t):o.type==="header"?ss(o):o.type==="cookie"?is(o):o.type==="openid"?as(o):ps(o);return e.map(o=>o.map(r))},wo=(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:[]})},{})),Eo=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Ft(e,{rules:{...t,...qt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),vo=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=Oo(xe(o),p),g=[];ut(c)&&c.examples&&(g.push(...c.examples),delete c.examples);let b={schema:i==="components"?s(r,c,te(d)):c,examples:Kt(g.length?g:Ne(o).examples?.filter(v=>z(v)&&!Array.isArray(v)).map(l.omit(p))||[])},y={description:d,content:{[n]:b}};return(m||n===w.raw)&&(y.required=!0),y},ko=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Ut=e=>e.length<=yo?e:e.slice(0,yo-1)+"\u2026",ft=e=>e.length?e.slice():void 0;var Dt=class extends cs{#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 W(`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:q}=y,N=A?Ut(A):m&&R?Ut(R):void 0,Q=r.inputSources?.[k]||kt[k],Oe=this.#n(v,k,y.getOperationId(k)),We=Eo({...L,schema:q}),ie=lo(y.security),Ye=Ro({...L,inputSources:Q,isHeader:c,security:ie,request:We,description:i?.requestParameter?.call(null,{method:k,path:v,operationId:Oe})}),Qe={};for(let X of Ce){let ae=y.getResponses(X);for(let{mimeTypes:et,schema:wt,statusCodes:lr}of ae)for(let Et of lr)Qe[Et]=To({...L,variant:X,schema:wt,mimeTypes:et,statusCode:Et,hasMultipleStatusCodes:ae.length>1||lr.length>1,description:i?.[`${X}Response`]?.call(null,{method:k,path:v,operationId:Oe,statusCode:Et})})}let Xe=Q.includes("body")?vo({...L,request:We,paramNames:Co.pluck("name",Ye),schema:q,mimeType:w[y.requestType],description:i?.requestBody?.call(null,{method:k,path:v,operationId:Oe})}):void 0,Tt=wo(Po(ie,Q),C,X=>{let ae=this.#s(X);return this.addSecurityScheme(ae,X),ae}),Pt={operationId:Oe,summary:N,description:R,deprecated:y.isDeprecated||void 0,tags:ft(y.tags),parameters:ft(Ye),requestBody:Xe,security:ft(Tt),responses:Qe};this.addPath(So(v),{[k]:Pt})}}),d&&(this.rootDoc.tags=ko(d))}};import{createRequest as ds,createResponse as ms}from"node-mocks-http";var ls=e=>ds({...e,headers:{"content-type":w.json,...e?.headers}}),us=e=>ms(e),fs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:zr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Ao=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=ls(e),s=us({req:n,...t});s.req=t?.req||n,n.res=s;let i=fs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},ys=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Ao(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},gs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=he}}=Ao(r),d=ot(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:ee(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Mo from"ramda";import Ot from"typescript";import{z as Hs}from"zod/v4";import*as zo from"ramda";import _ from"typescript";import*as U from"ramda";import u from"typescript";var a=u.factory,yt=[a.createModifier(u.SyntaxKind.ExportKeyword)],hs=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Ve={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},_t=(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)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Vt=e=>typeof e=="string"&&bs.test(e)?a.createIdentifier(e):P(e),gt=(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)))),ht=(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),ze=e=>Object.entries(e).map(([t,r])=>ht(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),Gt=(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,Wt=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Se=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,Vt(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?_t(i,p.join(" ")):i},Yt=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),Qt=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),I=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&yt,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),Xt=(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?yt:void 0,e,n&&or(n),t);return o?_t(s,o):s},Io=(e,t)=>a.createPropertyDeclaration(Ve.public,e,void 0,f(t),void 0),er=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Ve.public,void 0,e,void 0,o&&or(o),t,n,a.createBlock(r)),tr=(e,t,{typeParams:r}={})=>a.createClassDeclaration(yt,e,r&&or(r),void 0,t),rr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),bt=e=>f(Promise.name,[e]),xt=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?yt:void 0,e,void 0,void 0,t);return o?_t(n,o):n},or=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)}),Re=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?hs:void 0,void 0,Array.isArray(e)?U.map(ht,e):ze(e),void 0,void 0,t),O=e=>e,Ge=(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),Le=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),St=(e,t)=>f("Extract",[e,t]),nr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),H=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),No=e=>a.createUnionTypeNode([f(e),bt(e)]),sr=(e,t)=>a.createFunctionTypeNode(void 0,ze(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)),xs=[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],jo=e=>xs.includes(e.kind);var Rt=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=Xt("Method",Zt);someOfType=D("SomeOf",H("T",rr("T")),{params:["T"]});requestType=D("Request",rr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>Xt(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>xt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Se(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>I("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(Vt(t),a.createArrayLiteralExpression(zo.map(P,r))))),{expose:!0});makeImplementationType=()=>D(this.#e.implementationType,sr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Wt,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},bt(_.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:_.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>I(this.#e.parseRequestFn,Re({[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,Re({[this.#e.pathParameter.text]:_.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:Wt},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([nr(this.#e.pathParameter,T(this.#e.pathParameter,O("replace"))(gt(":",[this.#e.keyParameter]),Re([],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=()=>er(this.#e.provideMethod,ze({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:H(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[I(Qt(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:bt(H(this.interfaces.response,"K"))});makeClientClass=t=>tr(t,[Gt([ht(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Ve.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>gt("?",[Le(URLSearchParams.name,t)]);#o=()=>Le(URL.name,gt("",[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"),Ge(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(P("Content-Type"),P(w.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(O("body"),Ge(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,Ge(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,Ge(this.#e.isJsonConst,P(O("json")),P(O("text"))))());return I(this.#e.defaultImplementationConst,Re([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=()=>Gt(ze({request:"K",params:H(this.interfaces.input,"K")}),[I(Qt(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)),nr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Le("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Se(O("event"),t)]);#i=()=>er(this.#e.onMethod,ze({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:sr({[this.#e.dataParameter.text]:H(St("R",Yt(this.#s("E"))),M(O("data")))},No(_.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(T(a.createThis(),this.#e.sourceProp,O("addEventListener"))(this.#e.eventParameter,Re([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:H("R",M(O("event")))}});makeSubscriptionClass=t=>tr(t,[Io(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:St(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(_.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:St(H(this.interfaces.positive,"K"),Yt(this.#s(_.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[I(this.#e.clientConst,Le(t)),T(this.#e.clientConst,this.#e.provideMethod)(P("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",P("10"))])),T(Le(r,P("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(P("time"),Re(["time"],a.createBlock([])))]};import*as E from"ramda";import h from"typescript";import{globalRegistry as Ss}from"zod/v4";var ir=(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=>ir(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:J}=h,Rs={[h.SyntaxKind.AnyKeyword]:"",[h.SyntaxKind.BigIntKeyword]:BigInt(0),[h.SyntaxKind.BooleanKeyword]:!1,[h.SyntaxKind.NumberKeyword]:0,[h.SyntaxKind.ObjectKeyword]:{},[h.SyntaxKind.StringKeyword]:"",[h.SyntaxKind.UndefinedKeyword]:void 0},ar={name:E.path(["name","text"]),type:E.path(["type"]),optional:E.path(["questionToken"])},Os=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(h.SyntaxKind.UndefinedKeyword):M(r));return t.length===1?t[0]:J.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}=Ss.get(p)||{};return Se(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return J.createTypeLiteralNode(s)};return Or(e,{io:t?"output":"input"})?o(e,n):n()},Ps=({_zod:{def:e}},{next:t})=>J.createArrayTypeNode(t(e.element)),ws=({_zod:{def:e}})=>J.createUnionTypeNode(Object.values(e.entries).map(M)),Es=({_zod:{def:e}},{next:t})=>{let r=new Map;for(let o of e.options){let n=t(o);r.set(jo(n)?n.kind:n,n)}return J.createUnionTypeNode(Array.from(r.values()))},vs=e=>Rs?.[e.kind],ks=({_zod:{def:e}},{next:t})=>t(e.innerType),Cs=({_zod:{def:e}},{next:t})=>J.createUnionTypeNode([t(e.innerType),M(null)]),As=({_zod:{def:e}},{next:t})=>J.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:J.createRestTypeNode(t(e.rest)))),Is=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),Ns=E.tryCatch(e=>{if(!e.every(h.isTypeLiteralNode))throw new Error("Not objects");let t=E.chain(E.prop("members"),e),r=E.uniqWith((...o)=>{if(!E.eqBy(ar.name,...o))return!1;if(E.both(E.eqBy(ar.type),E.eqBy(ar.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return J.createTypeLiteralNode(r)},(e,t)=>J.createIntersectionTypeNode(t)),js=({_zod:{def:e}},{next:t})=>Ns([e.left,e.right].map(t)),K=e=>()=>f(e),pr=({_zod:{def:e}},{next:t})=>t(e.innerType),Lo=e=>f(e?h.SyntaxKind.UnknownKeyword:h.SyntaxKind.AnyKeyword),zs=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!Pe(o,"transform"))return t(o);let s=t(n),i=nt(o,vs(s)),p={number:h.SyntaxKind.NumberKeyword,bigint:h.SyntaxKind.BigIntKeyword,boolean:h.SyntaxKind.BooleanKeyword,string:h.SyntaxKind.StringKeyword,undefined:h.SyntaxKind.UndefinedKeyword,object:h.SyntaxKind.ObjectKeyword};return f(i&&p[i]||Lo(r))},Ls=()=>M(null),Ms=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),Zs=()=>f("Buffer"),$s=(e,{next:t})=>t(e._zod.def.shape.raw),Bs={string:K(h.SyntaxKind.StringKeyword),number:K(h.SyntaxKind.NumberKeyword),bigint:K(h.SyntaxKind.BigIntKeyword),boolean:K(h.SyntaxKind.BooleanKeyword),any:K(h.SyntaxKind.AnyKeyword),undefined:K(h.SyntaxKind.UndefinedKeyword),[ce]:K(h.SyntaxKind.StringKeyword),[de]:K(h.SyntaxKind.StringKeyword),never:K(h.SyntaxKind.NeverKeyword),void:K(h.SyntaxKind.UndefinedKeyword),unknown:K(h.SyntaxKind.UnknownKeyword),null:Ls,array:Ps,tuple:As,record:Is,object:Ts,literal:Os,intersection:js,union:Es,default:pr,enum:ws,optional:ks,nullable:Cs,catch:pr,pipe:zs,lazy:Ms,readonly:pr,[pe]:Zs,[$]:$s},cr=(e,{brandHandling:t,ctx:r})=>ir(e,{rules:{...t,...Bs},onMissing:({},{isResponse:o})=>Lo(o),ctx:r});var dr=class extends Rt{#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:(b,y,v)=>{let k=te.bind(null,v,y),{isDeprecated:L,inputSchema:R,tags:A}=b,C=`${v} ${y}`,q=D(k("input"),cr(R,c),{comment:C});this.#e.push(q);let N=Ce.reduce((We,ie)=>{let Ye=b.getResponses(ie),Qe=Mo.chain(([Tt,{schema:Pt,mimeTypes:X,statusCodes:ae}])=>{let et=D(k(ie,"variant",`${Tt+1}`),cr(X?Pt:p,m),{comment:C});return this.#e.push(et),ae.map(wt=>Se(wt,et.name))},Array.from(Ye.entries())),Xe=xt(k(ie,"response","variants"),Qe,{comment:C});return this.#e.push(Xe),Object.assign(We,{[ie]:Xe})},{});this.paths.add(y);let Q=M(C),Oe={input:f(q.name),positive:this.someOf(N.positive),negative:this.someOf(N.negative),response:a.createUnionTypeNode([H(this.interfaces.positive,Q),H(this.interfaces.negative,Q)]),encoded:a.createIntersectionTypeNode([f(N.positive.name),f(N.negative.name)])};this.registry.set(C,{isDeprecated:L,store:Oe}),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
19
  `):void 0}print(t){let r=this.#n(t),o=r&&Ot.addSyntheticLeadingComment(Ot.addSyntheticLeadingComment(a.createEmptyStatement(),Ot.SyntaxKind.SingleLineCommentTrivia," Usage example:"),Ot.SyntaxKind.MultiLineCommentTrivia,`
20
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 Ie("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 Me}from"zod/v4";var Zo=(e,t)=>Me.object({data:t,event:Me.literal(e),id:Me.string().optional(),retry:Me.int().positive().optional()}),Hs=(e,t,r)=>Zo(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
- `)).parse({event:t,data:r}),qs=1e4,Mo=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":w.sse,"cache-control":"no-cache"}),Ks=e=>new K({handler:async({response:t})=>setTimeout(()=>Mo(t),qs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Mo(t),t.write(Hs(e,r,o),"utf-8"),t.flush?.()}}}),Fs=e=>new ge({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Zo(o,n));return{mimeType:w.sse,schema:r.length?Me.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Me.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);Fe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(ye(i),"utf-8")}t.end()}}),mr=class extends be{constructor(t){super(Fs(t)),this.middlewares=[Ks(t)]}};var Us={dateIn:ur,dateOut:fr,form:gr,upload:hr,raw:xr,buffer:tt};export{De as BuiltinLogger,_e as DependsOnMethod,Dt as Documentation,G as DocumentationError,be as EndpointsFactory,mr as EventStreamFactory,W as InputValidationError,dr as Integration,K as Middleware,qe as MissingPeerError,He as OutputValidationError,ge as ResultHandler,fe as RoutingError,Je as ServeStatic,pn as arrayEndpointsFactory,Lt as arrayResultHandler,Mn as attachRouting,Uo as createConfig,Zn as createServer,an as defaultEndpointsFactory,he as defaultResultHandler,we as ensureHttpError,Us as ez,me as getMessageFromError,fs as testEndpoint,ys as testMiddleware};
22
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Ie("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 Me}from"zod/v4";var $o=(e,t)=>Me.object({data:t,event:Me.literal(e),id:Me.string().optional(),retry:Me.int().positive().optional()}),Ks=(e,t,r)=>$o(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
23
+ `)).parse({event:t,data:r}),qs=1e4,Zo=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":w.sse,"cache-control":"no-cache"}),Fs=e=>new F({handler:async({response:t})=>setTimeout(()=>Zo(t),qs)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Zo(t),t.write(Ks(e,r,o),"utf-8"),t.flush?.()}}}),Us=e=>new ge({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>$o(o,n));return{mimeType:w.sse,schema:r.length?Me.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:Me.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=we(r);Fe(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(ye(i),"utf-8")}t.end()}}),mr=class extends be{constructor(t){super(Us(t)),this.middlewares=[Fs(t)]}};var Ds={dateIn:ur,dateOut:fr,form:gr,upload:hr,raw:xr,buffer:tt};export{De as BuiltinLogger,_e as DependsOnMethod,Dt as Documentation,W as DocumentationError,be as EndpointsFactory,mr as EventStreamFactory,Y as InputValidationError,dr as Integration,F as Middleware,Ke as MissingPeerError,He as OutputValidationError,ge as ResultHandler,fe as RoutingError,Je as ServeStatic,cn as arrayEndpointsFactory,Lt as arrayResultHandler,Zn as attachRouting,Do as createConfig,$n as createServer,pn as defaultEndpointsFactory,he as defaultResultHandler,we as ensureHttpError,Ds as ez,me as getMessageFromError,ys as testEndpoint,gs as testMiddleware};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "24.0.0-beta.8",
3
+ "version": "24.0.0-beta.9",
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": {