express-zod-api 29.0.0-beta.2 → 29.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,7 @@
1
- import{createRequire as e}from"node:module";import{globalRegistry as t,z as n}from"zod";import*as r from"ramda";import{isPromise as i}from"node:util/types";import a,{isHttpError as o}from"http-errors";import s,{blue as c,cyanBright as l,green as u,hex as d,italic as f,red as p,whiteBright as m}from"ansis";import{inspect as h}from"node:util";import{performance as g}from"node:perf_hooks";import _ from"express";import ee from"node:http";import te from"node:https";import{setInterval as ne}from"node:timers/promises";import{OpenApiBuilder as re,isReferenceObject as ie,isSchemaObject as v}from"openapi3-ts/oas32";import{createRequest as ae,createResponse as oe}from"node-mocks-http";function se(e){return e}const y={json:`application/json`,upload:`multipart/form-data`,raw:`application/octet-stream`,sse:`text/event-stream`,form:`application/x-www-form-urlencoded`},ce=[`get`,`post`,`put`,`delete`,`patch`,`query`],le=[...ce,`head`],b=e=>ce.includes(e),ue=n.object({}),de=/:([A-Za-z0-9_]+)/g,fe=e=>e.match(de)?.map(e=>e.slice(1))||[],pe=e=>{let t=(e.header(`content-type`)||``).toLowerCase().startsWith(y.upload);return`files`in e&&t},me={get:[`query`,`params`],post:[`body`,`params`,`files`],put:[`body`,`params`],patch:[`body`,`params`],delete:[`query`,`params`],query:[`query`,`body`,`params`]},he=[`body`,`query`,`params`],ge=e=>e.method.toLowerCase(),_e=(e,t={})=>{if(e===`options`)return[];let n=e===`head`?`get`:b(e)?e:void 0;return(n?t[n]||me[n]:void 0)||he},ve=(e,t={})=>_e(ge(e),t).filter(t=>t===`files`?pe(e):!0).reduce((t,n)=>Object.assign(t,e[n]),{}),x=e=>e instanceof Error?e:e instanceof n.ZodError?new n.ZodRealError(e.issues):Error(String(e)),S=e=>e instanceof n.ZodError?e.issues.map(({path:e,message:t})=>`${e.length?`${n.core.toDotPath(e)}: `:``}${t}`).join(`; `):e.message,C=(e,t)=>E(e)&&`_zod`in e&&(t?r.path([`_zod`,`def`,`type`],e)===t:!0),w=(e,t,n)=>e.length&&t.length?r.xprod(e,t).map(n):e.concat(t),ye=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),T=(...e)=>{let t=r.chain(e=>e.split(/[^A-Z0-9]/gi),e);return r.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),t).map(ye).join(``)},be=r.tryCatch((e,t)=>typeof n.parse(e,t),r.always(void 0)),E=e=>typeof e==`object`&&!!e,xe=r.memoizeWith(()=>`static`,()=>process.env.NODE_ENV===`production`),Se=(e,t)=>!!t&&e!==`head`,D=`x-brand`,O=e=>{let{[D]:n}=t.get(e)||{};if(typeof n==`symbol`||typeof n==`string`||typeof n==`number`)return n},k=e=>{let{examples:n}=t.get(e)||{};return Array.isArray(n)?n:[]},A=Symbol(`Buffer`),Ce=()=>n.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).meta({[D]:A}),j=Symbol(`DateIn`),we=({examples:e,...t}={})=>n.union([n.iso.date(),n.iso.datetime({local:!0,offset:!0})]).meta({examples:e}).transform(e=>new Date(e)).pipe(n.date()).meta({...t,[D]:j}),M=Symbol(`DateOut`),Te=(e={})=>n.date().transform(e=>e.toISOString()).pipe(n.iso.datetime()).meta({...e,[D]:M});var N=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},P=class extends Error{name=`DocumentationError`;cause;constructor(e,{method:t,path:n,isResponse:r}){super(e),this.cause=`${r?`Response`:`Input`} schema of an Endpoint assigned to ${t.toUpperCase()} method of ${n} path.`}},Ee=class extends Error{name=`IOSchemaError`},De=class extends Ee{cause;name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},Oe=class extends Ee{cause;name=`OutputValidationError`;constructor(e){let t=new n.ZodError(e.issues.map(({path:e,...t})=>({...t,path:[`output`,...e]})));super(S(t),{cause:e}),this.cause=e}},F=class extends Ee{cause;name=`InputValidationError`;constructor(e){super(S(e),{cause:e}),this.cause=e}},ke=class extends Error{cause;handled;name=`ResultHandlerError`;constructor(e,t){super(S(e),{cause:e}),this.cause=e,this.handled=t}},Ae=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const je=Symbol(`Form`),Me=e=>(e instanceof n.ZodObject?e:n.object(e)).meta({[D]:je}),I=Symbol(`Upload`),Ne=e=>E(e)&&`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,Pe=()=>n.custom(e=>Ne(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}`})}).meta({[D]:I}),L=Symbol(`Raw`),Fe=n.object({raw:Ce()}),Ie=e=>Fe.extend(e).meta({[D]:L});function Le(e){return e?Ie(e):Fe.meta({[D]:L})}const Re=(e,{io:t,condition:i})=>r.tryCatch(()=>void n.toJSONSchema(e,{io:t,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new De(e)}}),e=>e.cause)(),ze=(e,{io:t})=>{let i=[n.toJSONSchema(e,{io:t,unrepresentable:`any`})];for(let e=0;e<i.length;e++){let t=i[e];if(r.is(Object,t)){if(t.$ref===`#`)return!0;i.push(...r.values(t))}r.is(Array,t)&&i.push(...r.values(t))}return!1},Be=e=>Re(e,{condition:e=>{let t=O(e);return typeof t==`symbol`&&[I,L,je].includes(t)},io:`input`}),Ve=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`,`function`],He=(e,t)=>Re(e,{io:t,condition:e=>{let n=O(e),{type:r}=e._zod.def;return!!(Ve.includes(r)||n===A||t===`input`&&(r===`date`||n===M)||t===`output`&&(n===j||n===L||n===I))}});var Ue=class{},R=class extends Ue{#e;#t;#n;constructor({input:e,security:t,handler:n}){super(),this.#e=e,this.#t=t,this.#n=n}get security(){return this.#t}get schema(){return this.#e}async execute({input:e,...t}){try{let n=await(this.#e||ue).parseAsync(e);return this.#n({...t,input:n})}catch(e){throw e instanceof n.ZodError?new F(e):e}}},We=class extends R{constructor(e,{provider:t=()=>({}),transformer:n=e=>e}={}){super({handler:async({request:r,response:a})=>{let{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=e=>{if(e&&e instanceof Error)return c(n(e));s(t(r,a))},u=e(r,a,l);return i(u)&&u.catch(l),o}})}};const Ge=(e,{variant:t,args:r,...i})=>{if(typeof e==`function`&&(e=e(...r)),e instanceof n.ZodType)return[{schema:e,...i}];if(Array.isArray(e)&&!e.length)throw new ke(Error(`At least one ${t} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:e,statusCode:t,mimeType:n})=>({schema:e,statusCodes:typeof t==`number`?[t]:t||i.statusCodes,mimeTypes:typeof n==`string`?[n]:n===void 0?i.mimeTypes:n}))},Ke=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),z=e=>o(e)?e:a(e instanceof F?400:500,S(e),{cause:e.cause||e}),B=e=>xe()&&!e.expose?a(e.statusCode).message:e.message,qe=e=>Object.entries(e._zod.def.shape).reduce((e,[t,n])=>w(e,k(n).map(r.objOf(t)),([e,t])=>({...e,...t})),[]);var Je=class{nest(e){return{...e,"":this}}},Ye=class e extends Je{#e;#t;#n=r.once(()=>{if(k(this.#e.outputSchema).length||!C(this.#e.outputSchema,`object`))return;let e=qe(this.#e.outputSchema);if(!e.length)return;let n=this.#e.outputSchema.meta();t.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...n,examples:e})});constructor(e){super(),this.#e=e}#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 summary(){return this.#e.summary}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}getProbableRequestType(e){return e===`query`?`form`:this.#t??=(()=>{let e=Be(this.#e.inputSchema);if(e){let t=O(e);if(t===I)return`upload`;if(t===L)return`raw`;if(t===je)return`form`}return`json`})()}getResponses(e){return e===`positive`&&this.#n(),Object.freeze(e===`negative`?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let e=r.pluck(`security`,this.#e.middlewares||[]);return r.reject(r.isNil,e)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(e){return this.#e.getOperationId?.(e)}async#i(e){try{return await this.#e.outputSchema.parseAsync(e)}catch(e){throw e instanceof n.ZodError?new Oe(e):e}}async#a({method:e,logger:t,ctx:n,response:r,...i}){for(let a of this.#e.middlewares||[])if(!(e===`options`&&!(a instanceof We))&&(Object.assign(n,await a.execute({...i,ctx:n,response:r,logger:t})),r.writableEnded)){t.warn(`A middleware has closed the stream. Accumulated context:`,n);break}}async#o({input:e,...t}){let r;try{r=await this.#e.inputSchema.parseAsync(e)}catch(e){throw e instanceof n.ZodError?new F(e):e}return this.#e.handler({...t,input:r})}async#s(e){await this.#e.resultHandler.execute(e)}async execute({request:e,response:t,logger:n,config:r}){let i=ge(e),a={},o,s=ve(e,r.inputSources);try{if(await this.#a({method:i,input:s,request:e,response:t,logger:n,ctx:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();let r=await this.#o({input:s,logger:n,ctx:a});if(t.writableEnded)return;o={output:await this.#i(r),error:null}}catch(e){o={output:null,error:x(e)}}await this.#s({...o,input:s,request:e,response:t,logger:n,ctx:a})}};const Xe=(e,t)=>e&&t?e.and(t):e||t,Ze=(e,t)=>e?e.and(t):t,V={positive:200,negative:400},Qe=Object.keys(V);var $e=class e{#e;constructor(e){this.#e=e}async execute(...t){try{return await this.#e(...t)}catch(n){let{response:r,logger:i,error:a}=t[0],o=new ke(x(n),a||void 0);e.lastResort({response:r,logger:i,error:o})}}static lastResort({error:e,logger:t,response:n}){t.error(`Result handler failure`,e);let r=B(a(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`\nOriginal error: ${e.handled.message}.`:``),{expose:o(e.cause)?e.cause.expose:!1}));n.status(500).type(`text/plain`).end(r)}},H=class extends $e{#e;#t;constructor(e){super(e.handler),this.#e=e.positive,this.#t=e.negative}getPositiveResponse(e){return Ge(this.#e,{variant:`positive`,args:[e],statusCodes:[V.positive],mimeTypes:[y.json]})}getNegativeResponse(){return Ge(this.#t,{variant:`negative`,args:[],statusCodes:[V.negative],mimeTypes:[y.json]})}};const et=n.object({status:n.literal(`error`),error:n.object({message:n.string()})});t.add(et,{examples:[{status:`error`,error:{message:`Sample error message`}}]});const U=new H({positive:e=>{let r=n.object({status:n.literal(`success`),data:e}),i=k(e);return i.length&&t.add(r,{examples:i.map(e=>({status:`success`,data:e}))}),r},negative:et,handler:({error:e,input:t,output:n,request:r,response:i,logger:a})=>{if(e){let n=z(e);Ke(n,a,r,t),i.status(n.statusCode).set(n.headers).json({status:`error`,error:{message:B(n)}});return}i.status(V.positive).json({status:`success`,data:n})}}),tt=n.string();t.add(tt,{examples:[`Sample error message`]});const nt=new H({positive:e=>{let r=e instanceof n.ZodObject&&`items`in e.shape&&e.shape.items instanceof n.ZodArray?e.shape.items:n.array(n.any());if(k(r).length)return r;let i=k(e).filter(e=>E(e)&&`items`in e&&Array.isArray(e.items)).map(e=>e.items);if(i?.length){let e=r.meta();t.remove(r).add(r,{...e,examples:i})}return r},negative:{schema:tt,mimeType:`text/plain`},handler:({response:e,output:t,error:n,logger:r,request:i,input:a})=>{if(n){let t=z(n);Ke(t,r,i,a),e.status(t.statusCode).type(`text/plain`).send(B(t));return}if(`items`in t&&Array.isArray(t.items)){e.status(V.positive).json(t.items);return}throw Error(`Property 'items' is missing in the endpoint output`)}}),rt=e=>{let t=[];return e.scope&&t.push(e.scope),e.noStore&&t.push(`no-store`),e.noCache&&t.push(`no-cache`),e.maxAge!==void 0&&t.push(`max-age=${e.maxAge}`),e.sMaxAge!==void 0&&t.push(`s-maxage=${e.sMaxAge}`),e.mustRevalidate&&t.push(`must-revalidate`),e.proxyRevalidate&&t.push(`proxy-revalidate`),e.mustUnderstand&&t.push(`must-understand`),e.immutable&&t.push(`immutable`),e.noTransform&&t.push(`no-transform`),e.staleWhileRevalidate!==void 0&&t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&t.push(`stale-if-error=${e.staleIfError}`),t.join(`, `)},it={"max-age":`maxAge`,"max-stale":`maxStale`,"min-fresh":`minFresh`,"stale-if-error":`staleIfError`},at={"no-cache":`noCache`,"no-store":`noStore`,"no-transform":`noTransform`,"only-if-cached":`onlyIfCached`},ot=e=>{if(!e)return;let t={};for(let n of e.toLowerCase().split(`,`)){let[e,r]=n.split(`=`),i=it[e.trim()];if(i){let e=parseInt(r?.trim()??``,10);isNaN(e)||(t[i]=e);continue}let a=at[e.trim()];a&&(t[a]=!0)}return t},st=e=>new R({handler:async({request:t,response:n})=>(e&&n.setHeader(`Cache-Control`,rt(e)),{get ifNoneMatch(){let e=t.headers[`if-none-match`];if(!e)return;let n=e.trim();return n===`*`?n:n.split(`,`).map(e=>e.trim().replace(/^(?:W\/)?"/,``).replace(/"$/,``))},get ifModifiedSince(){let e=t.headers[`if-modified-since`];if(!e)return;let n=new Date(e);return isNaN(n.getTime())?void 0:n},get cacheControl(){return ot(t.headers[`cache-control`])},addCachePolicy:t=>{n.setHeader(`Cache-Control`,rt({...e,...t}))},setETag:e=>{n.setHeader(`ETag`,e.startsWith(`"`)?e:`"${e}"`)},setLastModified:e=>{n.setHeader(`Last-Modified`,e.toUTCString())},setVary:(...e)=>{n.setHeader(`Vary`,e.join(`, `))},setExpires:e=>{n.setHeader(`Expires`,e.toUTCString())},clearSiteData:()=>{n.setHeader(`Clear-Site-Data`,`"cache"`)},notModified:()=>{n.status(304).end()}})}),ct=e=>new R({handler:async({request:t,response:n})=>({getCookie:e=>t.signedCookies?.[e]??t.cookies?.[e],setCookie:(t,r,i)=>{n.cookie(t,r,{...e,...i})},clearCookie:(t,r)=>{n.clearCookie(t,{...e,...r})}})});let lt;const W=(t,n=`default`)=>{try{let r=(lt??=e(import.meta.url))(t);return n==="default"?r.default===void 0?r:r.default:r[n]}catch{throw new Ae(t)}},ut=e=>{let t=W(`express-rate-limit`)({...e,handler:(e,t,n,r)=>{n(a(429,r.message))}}),{getKey:n,resetKey:r}=t,i={getKey:n,resetKey:r};return new We(t,{provider:t=>({rateLimit:{...i,...t[e?.requestPropertyName??`rateLimit`]}})})};var G=class e{resultHandler;schema=void 0;middlewares=[];constructor(e){this.resultHandler=e}#e(t){let n=new e(this.resultHandler);return n.middlewares=this.middlewares.concat(t),n.schema=Xe(this.schema,t.schema),n}addMiddleware(e){return this.#e(e instanceof R?e:new R(e))}useCookies(...e){return this.#e(ct(...e))}useCache(...e){return this.#e(st(...e))}useRateLimit(...e){return this.#e(ut(...e))}use=this.addExpressMiddleware;addExpressMiddleware(...e){return this.#e(new We(...e))}addContext(e){return this.#e(new R({handler:({ctx:t})=>e(t)}))}build({input:e=ue,output:t,operationId:n,scope:r,tag:i,method:a,...o}){let{middlewares:s,resultHandler:c}=this,l=typeof a==`string`?[a]:a,u=typeof n==`function`?n:e=>n&&`${n}${e===`head`?`__HEAD`:``}`,d=typeof r==`string`?[r]:r||[],f=typeof i==`string`?[i]:i||[];return new Ye({...o,middlewares:s,outputSchema:t,resultHandler:c,scopes:d,tags:f,methods:l,getOperationId:u,inputSchema:Ze(this.schema,e)})}buildVoid({handler:e,...t}){return this.build({...t,output:ue,handler:async t=>(await e(t),{})})}};const dt=new G(U),ft=new G(nt),pt={debug:c,info:u,warn:d(`#FFA500`),error:p,ctx:l},K={debug:10,info:20,warn:30,error:40},mt=e=>E(e)&&Object.keys(K).some(t=>t in e),ht=e=>e in K,gt=(e,t)=>K[e]<K[t],q=r.memoizeWith((e,t)=>`${e}${t}`,(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:`unit`,unitDisplay:`long`,unit:e})),_t=e=>e<1e-6?q(`nanosecond`,3).format(e/1e-6):e<.001?q(`nanosecond`).format(e/1e-6):e<1?q(`microsecond`).format(e/.001):e<1e3?q(`millisecond`).format(e):e<6e4?q(`second`,2).format(e/1e3):q(`minute`,2).format(e/6e4);var vt=class e{config;constructor({color:e=s.isSupported(),level:t=xe()?`warn`:`debug`,depth:n=2,ctx:r={}}={}){this.config={color:e,level:t,depth:n,ctx:r}}format(e){let{depth:t,color:n,level:r}=this.config;return h(e,{depth:t,colors:n,breakLength:r===`debug`?80:1/0,compact:r===`debug`?3:!0})}print(e,t,n){let{level:r,ctx:{requestId:i,...a},color:o}=this.config;if(r===`silent`||gt(e,r))return;let s=[new Date().toISOString()];i&&s.push(o?pt.ctx(i):i),s.push(o?`${pt[e](e)}:`:`${e}:`,t),n!==void 0&&s.push(this.format(n)),Object.keys(a).length>0&&s.push(this.format(a)),console.log(s.join(` `))}debug(e,t){this.print(`debug`,e,t)}info(e,t){this.print(`info`,e,t)}warn(e,t){this.print(`warn`,e,t)}error(e,t){this.print(`error`,e,t)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(e){let t=g.now();return()=>{let n=g.now()-t,{message:r,severity:i=`debug`,formatter:a=_t}=typeof e==`object`?e:{message:e};this.print(typeof i==`function`?i(n):i,r,a(n))}}},yt=class{#e;constructor(...e){this.#e=e}apply(e,t){return t(e,_.static(...this.#e))}};const bt=e=>e.type===`object`,xt=r.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return r.concat(e,t);if(e===t)return t;throw Error(`Can not flatten properties`,{cause:{a:e,b:t}})}),St=new Set([`type`,`properties`,`required`,`examples`,`description`,`additionalProperties`]),Ct=e=>{for(let t of Object.keys(e))if(!St.has(t))return!1;return!0},wt=r.pair(!0),Tt=(e,t,n)=>!(`allOf`in e)||!e.allOf?[]:e.allOf.map(e=>{if(t===`throw`&&!(e.type===`object`&&Ct(e)))throw Error(`Can not merge`);return r.pair(n,e)}),Et=e=>{let t=[];return e.anyOf&&t.push(...r.map(wt,e.anyOf)),e.oneOf&&t.push(...r.map(wt,e.oneOf)),t},Dt=(e,t,n,r)=>{if(!E(e.propertyNames))return;let i=[];typeof e.propertyNames.const==`string`&&i.push(e.propertyNames.const),e.propertyNames.enum&&i.push(...e.propertyNames.enum.filter(e=>typeof e==`string`));let a={...Object(e.additionalProperties)};for(let e of i)t.properties[e]??=a;r||n.push(...i)},Ot=(e,t,n)=>{t.examples?.length&&(n?e.examples=r.concat(e.examples||[],t.examples):e.examples=w(e.examples?.filter(E)||[],t.examples.filter(E),([e,t])=>r.mergeDeepRight(e,t)))},J=(e,t=`coerce`)=>{let n=[r.pair(!1,e)],i={type:`object`,properties:{}},a=[];for(let[e,o]of n)o.description&&(i.description??=o.description),n.push(...Tt(o,t,e)),n.push(...Et(o)),Ot(i,o,e),bt(o)&&(n.push([e,{examples:kt(o)}]),o.properties&&(i.properties=(t===`throw`?xt:r.mergeDeepRight)(i.properties,o.properties),!e&&o.required&&a.push(...o.required)),Dt(o,i,a,e));return a.length&&(i.required=[...new Set(a)]),i},kt=e=>Object.entries(e.properties||{}).reduce((e,[t,n])=>{let{examples:i=[]}=E(n)?n:{};return w(e,i.map(r.objOf(t)),([e,t])=>({...e,...t}))},[]);var At=class{logger;#e=new WeakMap;constructor(e){this.logger=e}#t(e,t,r){if(!e.isSchemaChecked){for(let e of[`input`,`output`]){let i=[n.toJSONSchema(t[`${e}Schema`],{unrepresentable:`any`})];for(let t of i){t.type&&t.type!==`object`&&this.logger.warn(`Endpoint ${e} schema is not object-based`,r);for(let e of[`allOf`,`oneOf`,`anyOf`])t[e]&&i.push(...t[e])}}if(t.getProbableRequestType()===`json`){let e=He(t.inputSchema,`input`);e&&this.logger.warn(`The final input schema of the endpoint contains an unsupported JSON payload type.`,{...r,reason:e})}for(let e of Qe)for(let{mimeTypes:n,schema:i}of t.getResponses(e)){if(!n?.includes(y.json))continue;let t=He(i,`output`);t&&this.logger.warn(`The final ${e} response schema of the endpoint contains an unsupported JSON payload type.`,{...r,reason:t})}e.isSchemaChecked=!0}}#n(e,t,r,i){if(e.paths.has(r))return;let a=fe(r);if(a.length!==0){e.flat??=J(n.toJSONSchema(t.inputSchema,{unrepresentable:`any`,io:`input`}));for(let t of a)t in e.flat.properties||this.logger.warn(`The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.`,{...i,path:r,param:t});e.paths.add(r)}}check=(e,t,n)=>{let r=this.#e.get(n);r||(r={isSchemaChecked:!1,paths:new Set},this.#e.set(n,r)),this.#t(r,n,{method:e,path:t}),this.#n(r,n,t,{method:e})}};const jt=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},Mt=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&b(t)?[n,t]:[e]},Nt=e=>e.trim().split(`/`).filter(Boolean).join(`/`),Pt=({recognizeMethodDependentRoutes:e=!0},t,n)=>Object.entries(t).map(([t,r])=>{let[i,a]=e&&b(t)&&r instanceof Je?[`/`,t]:Mt(t);return[[n||``].concat(Nt(i)||[]).join(`/`),r,a]}),Ft=(e,t)=>{throw new N(`Route with explicit method can only be assigned with Endpoint`,e,t)},It=(e,t,n)=>{if(!(!n||n.includes(e)))throw new N(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Lt=(e,t,n)=>{let r=`${e} ${t}`;if(n.has(r))throw new N(`Route has a duplicate`,e,t);n.add(r)},Rt=({routing:e,config:t,onEndpoint:n,onStatic:r})=>{let i=Pt(t,e),a=new Set;for(let e=0;e<i.length;e++){let[o,s,c]=i[e];if(s instanceof Je)if(c)Lt(c,o,a),It(c,o,s.methods),n(c,o,s);else{let{methods:e=[`get`]}=s;for(let t of e)Lt(t,o,a),n(t,o,s)}else c&&Ft(c,o),s instanceof yt?r&&s.apply(o,r):i.splice(e+1,0,...Pt(t,s,o))}},zt=e=>e.sort((e,t)=>b(t)-+b(e)||e.localeCompare(t)).join(`, `).toUpperCase(),Bt=e=>({method:t},n,r)=>{let i=zt(e);n.set({Allow:i}),r(a(405,`${t} is not allowed`,{headers:{Allow:i}}))},Vt=({app:e,getLogger:t,config:n,routing:r})=>{let i=xe()?void 0:new At(t()),a=new Map;return Rt({routing:r,config:n,onEndpoint:(e,t,r)=>{i?.check(e,t,r),a.has(t)||a.set(t,new Map(n.cors?[[`options`,r]]:[])),a.get(t)?.set(e,r)},onStatic:e.use.bind(e)}),a},Ht=({app:e,config:t,getLogger:n,...r})=>{let i=Vt({app:e,getLogger:n,config:t,...r}),a=new Map;for(let[r,o]of i){let i=Array.from(o.keys());i.includes(`get`)&&i.push(`head`);for(let[a,s]of o){let o=[];t.cors&&o.push((e,t,n)=>{t.set(`Access-Control-Allow-Methods`,zt(i)),n()}),o.push(async(e,r)=>{let i=n(e);return s.execute({request:e,response:r,logger:i,config:t})}),e[a]?.(r,...o)}t.hintAllowedMethods!==!1&&a.set(r,Bt(i))}for(let[t,n]of a)e.all(t,n)},Ut=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`,Wt=e=>`server`in e&&typeof e.server==`object`&&e.server!==null&&`close`in e.server&&typeof e.server.close==`function`,Gt=e=>`encrypted`in e&&typeof e.encrypted==`boolean`&&e.encrypted,Kt=({},e)=>void(!e.headersSent&&e.setHeader(`connection`,`close`)),qt=e=>{let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.close(e=>e?r(e):n()),t},Jt=({timeout:e=1e3,logger:t}={})=>{let n,r=new Set,i=new Set,a=e=>void i.delete(e),o=e=>a(e.destroy()),s=e=>void(Ut(e)?!e._httpMessage.headersSent&&e._httpMessage.setHeader(`connection`,`close`):o(e)),c=e=>void(n?e.destroy():i.add(e.once(`close`,()=>a(e)).once(`error`,()=>o(e)))),l=async()=>{for(let e of r)e.on(`request`,Kt);t?.info(`Graceful shutdown`,{sockets:i.size,timeout:e});for(let e of i)(Gt(e)||Wt(e))&&s(e);for await(let t of ne(10,Date.now()))if(i.size===0||Date.now()-t>=e)break;for(let e of i)o(e);return Promise.allSettled(r.values().map(qt))},u={sockets:i,add:(...e)=>{for(let t of e)if(!r.has(t)){r.add(t);for(let e of[`connection`,`secureConnection`])t.on(e,c)}return u},shutdown:()=>n??=l(),get isShuttingDown(){return!!n}};return u},Yt=Symbol.for(`express-zod-api`),Xt=({errorHandler:e,getLogger:t})=>async(n,r,i,a)=>n?e.execute({error:x(n),request:r,response:i,input:null,output:null,ctx:{},logger:t(r)}):a(),Zt=({errorHandler:e,getLogger:t})=>async(n,r)=>{let i=a(404,`Can not ${n.method} ${n.path}`),o=t(n);await e.execute({request:n,response:r,logger:o,error:i,input:null,output:null,ctx:{}})},Qt=e=>(t,{},n)=>{if(Object.values(t?.files||[]).flat().find(({truncated:e})=>e))return n(e);n()},$t=({config:e})=>{let t=W(`cookie-parser`),{secret:n,...r}={...typeof e.cookies==`object`&&e.cookies};return t(n,Object.keys(r).length?r:void 0)},en=e=>typeof e==`function`?e:({},e,t)=>{e.set({"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Headers":`content-type`}),t()},tn=e=>({log:t=>{/not eligible/i.test(t)||e.debug(t)}}),nn=({getLogger:e,config:t})=>{let n=W(`express-fileupload`),{limitError:r,beforeUpload:i,...a}={...typeof t.upload==`object`&&t.upload},o=[];return o.push(async(t,r,o)=>{let s=e(t);return await i?.({request:t,logger:s}),n({debug:!0,...a,abortOnLimit:!1,parseNested:!0,logger:tn(s)})(t,r,o)}),r&&o.push(Qt(r)),o},rn=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},an=({logger:e,config:{childLoggerProvider:t,accessLogger:n=({method:e,path:t},n)=>n.debug(`${e}: ${t}`)}})=>async(r,i,a)=>{let o=await t?.({request:r,parent:e})||e;n?.(r,o),r.res&&(r.res.locals[Yt]={logger:o}),a()},on=e=>t=>t?.res?.locals[Yt]?.logger||e;let sn=!1;const cn=e=>{sn||(sn=!0,process.on(`deprecation`,({message:t,namespace:n,name:r,stack:i})=>e.warn(`${r} (${n}): ${t}`,i.split(`
2
- `).slice(1))))};let Y,ln,un;const dn=({servers:e,logger:t,options:{timeout:n,beforeExit:r,events:i=[`SIGINT`,`SIGTERM`]}})=>{Y??=Jt({logger:t,timeout:n}),Y.add(...e),r&&(un??=new Set).add(r),ln??=async()=>{Y?.isShuttingDown||(await Y?.shutdown(),un&&await Promise.allSettled(un.values().map(async e=>e())),process.exit())};for(let e of i)process.listeners(e).includes(ln)||process.on(e,ln)},fn=e=>{if(e.columns<62)return;let t=f(`for Angie`.padStart(52)),n=d(`#F5A9B8`),r=d(`#5BCEFA`),i=[r`8888888888${t}`,r`888`,r`888`,r`8888888 888 888 88888b. 888d888 .d88b. .d8888b .d8888b`,n`888 `Y8bd8P' 888 "88b 888P" d8P Y8b 88K 88K`,n`888 X88K 888 888 888 88888888 "Y8888b. "Y8888b.`,n`888 .d8""8b. 888 d88P 888 Y8b. X88 X88`,m`8888888888 888 888 88888P" 888 "Y8888 88888P' 88888P'`,m` 888`,m`8888888888P 888 888 d8888 8888888b. 8888888`,m` d88P 888 d88888 888 Y88b 888`,n` d88P 888 d88P888 888 888 888`,n` d88P .d88b. .d88888 d88P 888 888 d88P 888`,n` d88P d88""88b d88" 888 d88P 888 8888888P" 888`,r` d88P 888 888 888 888 d88P 888 888 888`,r` d88P Y88..88P Y88b 888 d8888888888 888 888`,r`d8888888888 "Y88P" "Y88888 d88P 888 888 8888888`];e.write(`
1
+ import{B as e,C as t,D as n,E as r,I as i,L as a,P as o,Q as s,R as c,S as l,T as u,U as d,V as f,W as p,Z as ee,_ as te,a as m,b as ne,c as h,d as g,f as _,i as re,j as ie,k as ae,l as v,m as y,o as oe,p as b,r as se,s as ce,t as le,u as x,w as ue,x as de,y as fe}from"./routing-walker-Uax31V_v.js";import{t as S}from"./peer-helpers-BFaGRU7x.js";import{t as pe}from"./json-schema-helpers-C1xkaMOk.js";import{globalRegistry as C,z as w}from"zod";import*as me from"ramda";import T,{isHttpError as he}from"http-errors";import ge,{blue as _e,cyanBright as ve,green as ye,hex as E,italic as be,red as xe,whiteBright as D}from"ansis";import{inspect as Se}from"node:util";import{performance as O}from"node:perf_hooks";import k from"express";import Ce from"node:http";import we from"node:https";import{setInterval as Te}from"node:timers/promises";import{createRequest as Ee,createResponse as De}from"node-mocks-http";function Oe(e){return e}const ke=(e,t)=>e&&t?e.and(t):e||t,Ae=(e,t)=>e?e.and(t):t;var je=class e{#e;constructor(e){this.#e=e}async execute(...t){try{return await this.#e(...t)}catch(n){let{response:r,logger:i,error:o}=t[0],s=new u(a(n),o||void 0);e.lastResort({response:r,logger:i,error:s})}}static lastResort({error:e,logger:t,response:n}){t.error(`Result handler failure`,e);let r=v(T(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`\nOriginal error: ${e.handled.message}.`:``),{expose:he(e.cause)?e.cause.expose:!1}));n.status(500).type(`text/plain`).end(r)}},A=class extends je{#e;#t;constructor(e){super(e.handler),this.#e=e.positive,this.#t=e.negative}getPositiveResponse(e){return g(this.#e,{variant:`positive`,args:[e],statusCodes:[m.positive],mimeTypes:[s.json]})}getNegativeResponse(){return g(this.#t,{variant:`negative`,args:[],statusCodes:[m.negative],mimeTypes:[s.json]})}};const j=w.object({status:w.literal(`error`),error:w.object({message:w.string()})});C.add(j,{examples:[{status:`error`,error:{message:`Sample error message`}}]});const M=new A({positive:e=>{let t=w.object({status:w.literal(`success`),data:e}),n=o(e);return n.length&&C.add(t,{examples:n.map(e=>({status:`success`,data:e}))}),t},negative:j,handler:({error:e,input:t,output:n,request:r,response:i,logger:a})=>{if(e){let n=h(e);x(n,a,r,t),i.status(n.statusCode).set(n.headers).json({status:`error`,error:{message:v(n)}});return}i.status(m.positive).json({status:`success`,data:n})}}),N=w.string();C.add(N,{examples:[`Sample error message`]});const P=new A({positive:e=>{let t=e instanceof w.ZodObject&&`items`in e.shape&&e.shape.items instanceof w.ZodArray?e.shape.items:w.array(w.any());if(o(t).length)return t;let n=o(e).filter(e=>d(e)&&`items`in e&&Array.isArray(e.items)).map(e=>e.items);if(n?.length){let e=t.meta();C.remove(t).add(t,{...e,examples:n})}return t},negative:{schema:N,mimeType:`text/plain`},handler:({response:e,output:t,error:n,logger:r,request:i,input:a})=>{if(n){let t=h(n);x(t,r,i,a),e.status(t.statusCode).type(`text/plain`).send(v(t));return}if(`items`in t&&Array.isArray(t.items)){e.status(m.positive).json(t.items);return}throw Error(`Property 'items' is missing in the endpoint output`)}}),F=e=>{let t=[];return e.scope&&t.push(e.scope),e.noStore&&t.push(`no-store`),e.noCache&&t.push(`no-cache`),e.maxAge!==void 0&&t.push(`max-age=${e.maxAge}`),e.sMaxAge!==void 0&&t.push(`s-maxage=${e.sMaxAge}`),e.mustRevalidate&&t.push(`must-revalidate`),e.proxyRevalidate&&t.push(`proxy-revalidate`),e.mustUnderstand&&t.push(`must-understand`),e.immutable&&t.push(`immutable`),e.noTransform&&t.push(`no-transform`),e.staleWhileRevalidate!==void 0&&t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`),e.staleIfError!==void 0&&t.push(`stale-if-error=${e.staleIfError}`),t.join(`, `)},Me={"max-age":`maxAge`,"max-stale":`maxStale`,"min-fresh":`minFresh`,"stale-if-error":`staleIfError`},Ne={"no-cache":`noCache`,"no-store":`noStore`,"no-transform":`noTransform`,"only-if-cached":`onlyIfCached`},Pe=e=>{if(!e)return;let t={};for(let n of e.toLowerCase().split(`,`)){let[e,r]=n.split(`=`),i=Me[e.trim()];if(i){let e=parseInt(r?.trim()??``,10);isNaN(e)||(t[i]=e);continue}let a=Ne[e.trim()];a&&(t[a]=!0)}return t},I=e=>new b({handler:async({request:t,response:n})=>(e&&n.setHeader(`Cache-Control`,F(e)),{get ifNoneMatch(){let e=t.headers[`if-none-match`];if(!e)return;let n=e.trim();return n===`*`?n:n.split(`,`).map(e=>e.trim().replace(/^(?:W\/)?"/,``).replace(/"$/,``))},get ifModifiedSince(){let e=t.headers[`if-modified-since`];if(!e)return;let n=new Date(e);return isNaN(n.getTime())?void 0:n},get cacheControl(){return Pe(t.headers[`cache-control`])},addCachePolicy:t=>{n.setHeader(`Cache-Control`,F({...e,...t}))},setETag:e=>{n.setHeader(`ETag`,e.startsWith(`"`)?e:`"${e}"`)},setLastModified:e=>{n.setHeader(`Last-Modified`,e.toUTCString())},setVary:(...e)=>{n.setHeader(`Vary`,e.join(`, `))},setExpires:e=>{n.setHeader(`Expires`,e.toUTCString())},clearSiteData:()=>{n.setHeader(`Clear-Site-Data`,`"cache"`)},notModified:()=>{n.status(304).end()}})}),L=e=>new b({handler:async({request:t,response:n})=>({getCookie:e=>t.signedCookies?.[e]??t.cookies?.[e],setCookie:(t,r,i)=>{n.cookie(t,r,{...e,...i})},clearCookie:(t,r)=>{n.clearCookie(t,{...e,...r})}})}),R=e=>{let t=S(`express-rate-limit`)({...e,handler:(e,t,n,r)=>{n(T(429,r.message))}}),{getKey:n,resetKey:r}=t,i={getKey:n,resetKey:r};return new _(t,{provider:t=>({rateLimit:{...i,...t[e?.requestPropertyName??`rateLimit`]}})})};var z=class e{resultHandler;schema=void 0;middlewares=[];constructor(e){this.resultHandler=e}#e(t){let n=new e(this.resultHandler);return n.middlewares=this.middlewares.concat(t),n.schema=ke(this.schema,t.schema),n}addMiddleware(e){return this.#e(e instanceof b?e:new b(e))}useCookies(...e){return this.#e(L(...e))}useCache(...e){return this.#e(I(...e))}useRateLimit(...e){return this.#e(R(...e))}use=this.addExpressMiddleware;addExpressMiddleware(...e){return this.#e(new _(...e))}addContext(e){return this.#e(new b({handler:({ctx:t})=>e(t)}))}build({input:e=i,output:t,operationId:n,scope:r,tag:a,method:o,...s}){let{middlewares:c,resultHandler:l}=this,u=typeof o==`string`?[o]:o,d=typeof n==`function`?n:e=>n&&`${n}${e===`head`?`__HEAD`:``}`,f=typeof r==`string`?[r]:r||[],p=typeof a==`string`?[a]:a||[];return new ce({...s,middlewares:c,outputSchema:t,resultHandler:l,scopes:f,tags:p,methods:u,getOperationId:d,inputSchema:Ae(this.schema,e)})}buildVoid({handler:e,...t}){return this.build({...t,output:i,handler:async t=>(await e(t),{})})}};const Fe=new z(M),Ie=new z(P),B={debug:_e,info:ye,warn:E(`#FFA500`),error:xe,ctx:ve},V={debug:10,info:20,warn:30,error:40},Le=e=>d(e)&&Object.keys(V).some(t=>t in e),Re=e=>e in V,ze=(e,t)=>V[e]<V[t],H=me.memoizeWith((e,t)=>`${e}${t}`,(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:`unit`,unitDisplay:`long`,unit:e})),Be=e=>e<1e-6?H(`nanosecond`,3).format(e/1e-6):e<.001?H(`nanosecond`).format(e/1e-6):e<1?H(`microsecond`).format(e/.001):e<1e3?H(`millisecond`).format(e):e<6e4?H(`second`,2).format(e/1e3):H(`minute`,2).format(e/6e4);var U=class e{config;constructor({color:e=ge.isSupported(),level:t=p()?`warn`:`debug`,depth:n=2,ctx:r={}}={}){this.config={color:e,level:t,depth:n,ctx:r}}format(e){let{depth:t,color:n,level:r}=this.config;return Se(e,{depth:t,colors:n,breakLength:r===`debug`?80:1/0,compact:r!==`debug`||3})}print(e,t,n){let{level:r,ctx:{requestId:i,...a},color:o}=this.config;if(r===`silent`||ze(e,r))return;let s=[new Date().toISOString()];i&&s.push(o?B.ctx(i):i),s.push(o?`${B[e](e)}:`:`${e}:`,t),n!==void 0&&s.push(this.format(n)),Object.keys(a).length>0&&s.push(this.format(a)),console.log(s.join(` `))}debug(e,t){this.print(`debug`,e,t)}info(e,t){this.print(`info`,e,t)}warn(e,t){this.print(`warn`,e,t)}error(e,t){this.print(`error`,e,t)}child(t){return new e({...this.config,ctx:t})}get ctx(){return this.config.ctx}profile(e){let t=O.now();return()=>{let n=O.now()-t,{message:r,severity:i=`debug`,formatter:a=Be}=typeof e==`object`?e:{message:e};this.print(typeof i==`function`?i(n):i,r,a(n))}}},Ve=class{logger;#e=new WeakMap;constructor(e){this.logger=e}#t(e,t,n){if(!e.isSchemaChecked){for(let e of[`input`,`output`]){let r=[w.toJSONSchema(t[`${e}Schema`],{unrepresentable:`any`})];for(let t of r){t.type&&t.type!==`object`&&this.logger.warn(`Endpoint ${e} schema is not object-based`,n);for(let e of[`allOf`,`oneOf`,`anyOf`])t[e]&&r.push(...t[e])}}if(t.getProbableRequestType()===`json`){let e=y(t.inputSchema,`input`);e&&this.logger.warn(`The final input schema of the endpoint contains an unsupported JSON payload type.`,{...n,reason:e})}for(let e of oe)for(let{mimeTypes:r,schema:i}of t.getResponses(e)){if(!r?.includes(s.json))continue;let t=y(i,`output`);t&&this.logger.warn(`The final ${e} response schema of the endpoint contains an unsupported JSON payload type.`,{...n,reason:t})}e.isSchemaChecked=!0}}#n(e,t,n,r){if(e.paths.has(n))return;let i=f(n);if(i.length!==0){e.flat??=pe(w.toJSONSchema(t.inputSchema,{unrepresentable:`any`,io:`input`}));for(let t of i)t in e.flat.properties||this.logger.warn(`The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.`,{...r,path:n,param:t});e.paths.add(n)}}check=(e,t,n)=>{let r=this.#e.get(n);r||(r={isSchemaChecked:!1,paths:new Set},this.#e.set(n,r)),this.#t(r,n,{method:e,path:t}),this.#n(r,n,t,{method:e})}};const W=e=>e.sort((e,t)=>ee(t)-+ee(e)||e.localeCompare(t)).join(`, `).toUpperCase(),He=e=>({method:t},n,r)=>{let i=W(e);n.set({Allow:i}),r(T(405,`${t} is not allowed`,{headers:{Allow:i}}))},Ue=({app:e,getLogger:t,config:n,routing:r})=>{let i=p()?void 0:new Ve(t()),a=new Map;return le({routing:r,config:n,onEndpoint:(e,t,r)=>{i?.check(e,t,r),a.has(t)||a.set(t,new Map(n.cors?[[`options`,r]]:[])),a.get(t)?.set(e,r)},onStatic:e.use.bind(e)}),a},G=({app:e,config:t,getLogger:n,...r})=>{let i=Ue({app:e,getLogger:n,config:t,...r}),a=new Map;for(let[r,o]of i){let i=Array.from(o.keys());i.includes(`get`)&&i.push(`head`);for(let[a,s]of o){let o=[];t.cors&&o.push((e,t,n)=>{t.set(`Access-Control-Allow-Methods`,W(i)),n()}),o.push(async(e,r)=>{let i=n(e);return s.execute({request:e,response:r,logger:i,config:t})}),e[a]?.(r,...o)}t.hintAllowedMethods!==!1&&a.set(r,He(i))}for(let[t,n]of a)e.all(t,n)},We=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`,Ge=e=>`server`in e&&typeof e.server==`object`&&e.server!==null&&`close`in e.server&&typeof e.server.close==`function`,Ke=e=>`encrypted`in e&&typeof e.encrypted==`boolean`&&e.encrypted,qe=({},e)=>void(!e.headersSent&&e.setHeader(`connection`,`close`)),Je=e=>{let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.close(e=>e?r(e):n()),t},Ye=({timeout:e=1e3,logger:t}={})=>{let n,r=new Set,i=new Set,a=e=>void i.delete(e),o=e=>a(e.destroy()),s=e=>void(We(e)?!e._httpMessage.headersSent&&e._httpMessage.setHeader(`connection`,`close`):o(e)),c=e=>void(n?e.destroy():i.add(e.once(`close`,()=>a(e)).once(`error`,()=>o(e)))),l=async()=>{for(let e of r)e.on(`request`,qe);t?.info(`Graceful shutdown`,{sockets:i.size,timeout:e});for(let e of i)(Ke(e)||Ge(e))&&s(e);for await(let t of Te(10,Date.now()))if(i.size===0||Date.now()-t>=e)break;for(let e of i)o(e);return Promise.allSettled(r.values().map(Je))},u={sockets:i,add:(...e)=>{for(let t of e)if(!r.has(t)){r.add(t);for(let e of[`connection`,`secureConnection`])t.on(e,c)}return u},shutdown:()=>n??=l(),get isShuttingDown(){return!!n}};return u},K=Symbol.for(`express-zod-api`),Xe=({errorHandler:e,getLogger:t})=>async(n,r,i,o)=>n?e.execute({error:a(n),request:r,response:i,input:null,output:null,ctx:{},logger:t(r)}):o(),Ze=({errorHandler:e,getLogger:t})=>async(n,r)=>{let i=T(404,`Can not ${n.method} ${n.path}`),a=t(n);await e.execute({request:n,response:r,logger:a,error:i,input:null,output:null,ctx:{}})},Qe=e=>(t,{},n)=>{if(Object.values(t?.files||[]).flat().find(({truncated:e})=>e))return n(e);n()},$e=({config:e})=>{let t=S(`cookie-parser`),{secret:n,...r}={...typeof e.cookies==`object`&&e.cookies};return t(n,Object.keys(r).length?r:void 0)},q=e=>typeof e==`function`?e:({},e,t)=>{e.set({"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Headers":`content-type`}),t()},et=e=>({log:t=>{/not eligible/i.test(t)||e.debug(t)}}),tt=({getLogger:e,config:t})=>{let n=S(`express-fileupload`),{limitError:r,beforeUpload:i,...a}={...typeof t.upload==`object`&&t.upload},o=[];return o.push(async(t,r,o)=>{let s=e(t);return await i?.({request:t,logger:s}),n({debug:!0,...a,abortOnLimit:!1,parseNested:!0,logger:et(s)})(t,r,o)}),r&&o.push(Qe(r)),o},nt=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},rt=({logger:e,config:{childLoggerProvider:t,accessLogger:n=({method:e,path:t},n)=>n.debug(`${e}: ${t}`)}})=>async(r,i,a)=>{let o=await t?.({request:r,parent:e})||e;n?.(r,o),r.res&&(r.res.locals[K]={logger:o}),a()},it=e=>t=>t?.res?.locals[K]?.logger||e;let J=!1;const at=e=>{J||(J=!0,process.on(`deprecation`,({message:t,namespace:n,name:r,stack:i})=>e.warn(`${r} (${n}): ${t}`,i.split(`
2
+ `).slice(1))))};let Y,X,Z;const ot=({servers:e,logger:t,options:{timeout:n,beforeExit:r,events:i=[`SIGINT`,`SIGTERM`]}})=>{Y??=Ye({logger:t,timeout:n}),Y.add(...e),r&&(Z??=new Set).add(r),X??=async()=>{Y?.isShuttingDown||(await Y?.shutdown(),Z&&await Promise.allSettled(Z.values().map(async e=>e())),process.exit())};for(let e of i)process.listeners(e).includes(X)||process.on(e,X)},st=e=>{if(e.columns<62)return;let t=be(`for Angie`.padStart(52)),n=E(`#F5A9B8`),r=E(`#5BCEFA`),i=[r`8888888888${t}`,r`888`,r`888`,r`8888888 888 888 88888b. 888d888 .d88b. .d8888b .d8888b`,n`888 `Y8bd8P' 888 "88b 888P" d8P Y8b 88K 88K`,n`888 X88K 888 888 888 88888888 "Y8888b. "Y8888b.`,n`888 .d8""8b. 888 d88P 888 Y8b. X88 X88`,D`8888888888 888 888 88888P" 888 "Y8888 88888P' 88888P'`,D` 888`,D`8888888888P 888 888 d8888 8888888b. 8888888`,D` d88P 888 d88888 888 Y88b 888`,n` d88P 888 d88P888 888 888 888`,n` d88P .d88b. .d88888 d88P 888 888 d88P 888`,n` d88P d88""88b d88" 888 d88P 888 8888888P" 888`,r` d88P 888 888 888 888 d88P 888 888 888`,r` d88P Y88..88P Y88b 888 d8888888888 888 888`,r`d8888888888 "Y88P" "Y88888 d88P 888 888 8888888`];e.write(`
3
3
  `+i.join(`
4
4
  `)+`
5
5
 
6
- `)},pn=e=>{e.startupLogo!==!1&&fn(process.stdout);let t=e.errorHandler||U,n=mt(e.logger)?e.logger:new vt(e.logger);n.debug(`Running`,{build:`v29.0.0-beta.2`,env:process.env.NODE_ENV||`development`}),cn(n);let r=an({logger:n,config:e}),i={getLogger:on(n),errorHandler:t},a=Zt(i),o=Xt(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},mn=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=pn(e),o=e.app.use(a);return e.cors&&o.use(en(e.cors)),Ht({app:o,routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},hn=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=pn(e),s=_().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.beforeParsers?.({app:s,getLogger:r}),e.compression){let t=W(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}return e.cookies&&s.use($t({config:e})),e.cors&&s.use(en(e.cors)),s.use(e.jsonParser||_.json()).use(e.formParser||_.urlencoded()).use(e.rawParser||_.raw(),rn),e.upload&&s.use(...nn({config:e,getLogger:r})),e.beforeRouting?.({app:s,getLogger:r}),Ht({app:s,routing:t,getLogger:r,config:e}),e.afterRouting?.({app:s,getLogger:r}),s.use(a,i),{app:s,logger:n}},gn=(e,t)=>{let{app:n,logger:r}=hn(e,t),i=[],a=(e,t)=>()=>e.listen(t,()=>r.info(`Listening`,t)),o=[];if(e.http){let t=ee.createServer(n);i.push(t),o.push(a(t,e.http.listen))}if(e.https){let t=te.createServer(e.https.options,n);i.push(t),o.push(a(t,e.https.listen))}return i.length||r.warn(`No servers configured.`),e.gracefulShutdown&&dn({logger:r,servers:i,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:n,logger:r,servers:o.map(e=>e())}},_n=e=>E(e)&&`or`in e,vn=e=>E(e)&&`and`in e,yn=e=>!vn(e)&&!_n(e),bn=e=>{let t=r.filter(yn,e),n=r.chain(r.prop(`and`),r.filter(vn,e)),[i,a]=r.partition(yn,n),o=r.concat(t,i),s=r.filter(_n,e);return r.map(r.prop(`or`),r.concat(s,a)).reduce((e,t)=>w(e,r.map(e=>yn(e)?[e]:e.and,t),([e,t])=>r.concat(e,t)),r.reject(r.isEmpty,[o]))},xn=(e,t)=>vn(e)?r.chain(e=>xn(e,t),e.and):_n(e)?r.chain(e=>xn(e,t),e.or):e.type===t?[e.name]:[],Sn=(e,t)=>new Set(r.chain(e=>xn(e,t),e));let Cn;const wn=()=>Cn??=new Set(`a-im.accept.accept-additions.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.amp-cache-transform.apply-to-redirect-ref.authorization.available-dictionary.c-ext.c-man.c-opt.c-pep.c-pep-info.cache-control.cal-managed-id.caldav-timezones.capsule-protocol.cdn-loop.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.cta-common-access-token.dasl.date.dav.default-style.delta-base.deprecation.depth.derived-from.destination.detached-jws.dictionary-id.differential-id.digest.dpop.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.incremental.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.odata-entityid.odata-isolation.odata-maxversion.odata-version.opt.ordering-type.origin.origin-agent-cluster.oscore.oslc-core-version.overwrite.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.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.signature.signature-input.slug.soapaction.status-uri.sunset.surrogate-capability.tcn.te.timeout.topic.traceparent.tracestate.trailer.transfer-encoding.ttl.upgrade.urgency.uri.user-agent.variant-vary.via.want-content-digest.want-digest.want-repr-digest.warning.x-content-type-options.x-frame-options`.split(`.`)),Tn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},En=e=>e.replace(de,e=>`{${e.slice(1)}}`),Dn=({},e)=>{if(e.isResponse)throw new P(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},On=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),kn=({zodSchema:e,jsonSchema:t})=>{if(!C(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},An=r.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return J(e,`throw`)},(e,{jsonSchema:t})=>t),jn=({jsonSchema:e})=>{if(!e.anyOf||!e.anyOf.length)return e;let t=e.anyOf[0];return Object.assign(t,{type:Ln(t.type)})},X=e=>e,Mn=({jsonSchema:e},t)=>{if(t.isResponse)throw new P(`Please use ez.dateOut() for output.`,t);return e},Nn=({jsonSchema:e},t)=>{if(!t.isResponse)throw new P(`Please use ez.dateIn() for input.`,t);return e},Pn=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),Fn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,In=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Tn?.[t]},Ln=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],Rn=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!C(r,`transform`))return t;let a=X(Gn(i,{ctx:n}));if(v(a))if(n.isResponse){let e=be(r,In(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},zn=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!E(t.properties.raw)?e:t.properties.raw},Bn=e=>e.length?r.fromPairs(r.zip(r.times(e=>`example${e+1}`,e.length),r.map(r.objOf(`dataValue`),e))):void 0,Vn=(e,t)=>t?.has(e)||e.startsWith(`x-`)||wn().has(e),Hn=({path:e,method:t,request:n,inputSources:i,makeRef:a,composition:o,isHeader:s,securityHeaders:c,securityCookies:l,description:u=`${t.toUpperCase()} ${e} Parameter`})=>{let d=J(n),f=fe(e),p=i.includes(`query`),m=i.includes(`params`),h=i.includes(`headers`),g=i.includes(`cookies`)||i.includes(`signedCookies`),_=n=>{if(m&&f.includes(n))return`path`;if(g&&l?.has(n))return`cookie`;if(h&&(s?.(n,t,e)??Vn(n,c)))return`header`;if(p&&t!==`query`)return`query`};return Object.entries(d.properties).reduce((e,[t,n])=>{if(!E(n))return e;let i=_(t);if(!i)return e;let s=X(n),c=o===`components`?a(n.id||JSON.stringify(n),s,n.id||T(u,t)):s;return e.concat({name:t,in:i,deprecated:n.deprecated,required:d.required?.includes(t)||!1,description:s.description||u,schema:c,examples:Bn(v(s)&&s.examples?.length?s.examples:r.pluck(t,d.examples?.filter(r.both(E,r.has(t)))||[]))})},[])},Un={nullable:jn,union:kn,bigint:Pn,intersection:An,tuple:Fn,pipe:Rn,[j]:Mn,[M]:Nn,[I]:Dn,[L]:zn,[A]:On},Wn=(e,t,n)=>{let i=[e,t],a=e=>/schema\d+$/.test(e)?void 0:e;for(let e=0;e<i.length;e++){let o=i[e];if(r.is(Object,o)){if(ie(o)&&!o.$ref.startsWith(`#/components`)){let e=o.$ref.split(`/`).pop(),r=t[e];r&&(o.$ref=n.makeRef(r.id||r,X(r),r.id||a(e)).$ref);continue}i.push(...r.values(o))}r.is(Array,o)&&i.push(...r.values(o))}return e},Gn=(e,{ctx:t,rules:r=Un})=>{let{$defs:i={},properties:a={}}=n.toJSONSchema(n.object({subject:e}),{unrepresentable:`any`,io:t.isResponse?`output`:`input`,override:e=>{let n=O(e.zodSchema),i=r[n&&n in r?n:e.zodSchema._zod.def.type];if(i){let n={...i(e,t)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,n)}}});return Wn(E(a.subject)?a.subject:{},i,t)},Kn=(e,t)=>{if(ie(e))return[e,!1];let n=!1,i=r.map(e=>{let[r,i]=Kn(e,t);return n||=i,r}),a=r.omit(t),o={properties:a,examples:r.map(a),required:r.without(t),allOf:i,oneOf:i,anyOf:i},s=r.evolve(o,e);return[s,n||!!s.required?.length]},qn=({method:e,path:t,schema:n,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${t} ${ye(a)} response ${c?l:``}`.trim()})=>{if(!Se(e,i))return{description:d};let f=X(Gn(n,{rules:{...u,...Un},ctx:{isResponse:!0,makeRef:o,path:t,method:e}})),p=[];v(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m=s===`components`?o(n,f,T(d)):f;return{description:d,content:r.fromPairs(i.map(e=>[e,{[e===y.sse?`itemSchema`:`schema`]:m,examples:Bn(p)}]))}},Jn=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Yn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},Xn=({name:e})=>({type:`apiKey`,in:`header`,name:e}),Zn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),Qn=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),$n=({flows:e={},oauth2MetadataUrl:t})=>({type:`oauth2`,flows:r.map(e=>({...e,scopes:e.scopes||{}}),r.reject(r.isNil,e)),oauth2MetadataUrl:t}),er=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?Jn(e):e.type===`input`?Yn(e,t):e.type===`header`?Xn(e):e.type===`cookie`?Zn(e):e.type===`openid`?Qn(e):$n(e);return e.map(e=>e.map(({deprecated:e,...t})=>({...n(t),deprecated:e})))},tr=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),nr=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Gn(e,{rules:{...t,...Un},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),rr=({method:e,path:t,schema:n,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let[u,d]=Kn(i,c),f=X(u),p=[];v(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(n,f,T(l)):f,examples:Bn(p.length?p:J(i).examples?.filter(e=>E(e)&&!Array.isArray(e)).map(r.omit(c))||[])},h={description:l,content:{[a]:m}};return(d||a===y.raw)&&(h.required=!0),h},ir=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;if(typeof n==`string`)return e.concat({name:t,description:n});let{url:r,...i}=n,a={...i,name:t};return r&&(a.externalDocs={...a.externalDocs,url:r}),e.concat(a)},[]),ar=(e,t=50)=>!e||e.length<=t?e:e.slice(0,Math.max(1,t||0)-1)+`…`,or=e=>e.length?e.slice():void 0,sr=({description:e,summary:t=e,trim:n})=>n(t);var cr=class extends re{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n){let r=this.#n.get(e);if(!r){let t=+!n;do r=`${n??`Schema`}${t?this.#n.size+t:``}`,t++;while(this.rootDoc.components?.schemas?.[r]);this.#n.set(e,r)}return this.addSchema(r,t),{$ref:`#/components/schemas/${r}`}}#i(e,t,n){let r=n||T(t,e),i=this.#t.get(r);if(i===void 0)return this.#t.set(r,1),r;if(n)throw new P(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#t.set(r,i),`${r}${i}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}#o({tags:e,info:t,server:n}){this.addInfo(t),e&&(this.rootDoc.tags=ir(e));for(let e of Array.isArray(n)?n:[n])this.addServer(typeof e==`string`?{url:e}:e)}#s({config:e,descriptions:t,brandHandling:n,isHeader:i,summarizer:a=sr,composition:o=`inline`}){return(s,c,l)=>{let u={path:c,method:s,endpoint:l,composition:o,brandHandling:n,makeRef:this.#r.bind(this)},{description:d,summary:f,scopes:p,inputSchema:m}=l,h=_e(s,e.inputSources),g=this.#i(c,s,l.getOperationId(s)),_=nr({...u,schema:m}),ee=Hn({...u,inputSources:h,isHeader:i,securityHeaders:Sn(l.security,`header`),securityCookies:Sn(l.security,`cookie`),request:_,description:t?.requestParameter?.({method:s,path:c,operationId:g})}),te={};for(let e of Qe){let n=l.getResponses(e);for(let{mimeTypes:r,schema:i,statusCodes:a}of n)for(let o of a)te[o]=qn({...u,variant:e,schema:i,mimeTypes:r,statusCode:o,hasMultipleStatusCodes:n.length>1||a.length>1,description:t?.[`${e}Response`]?.({method:s,path:c,operationId:g,statusCode:o})})}let ne=h.includes(`body`)?rr({...u,request:_,paramNames:r.pluck(`name`,ee),schema:m,mimeType:y[l.getProbableRequestType(s)],description:t?.requestBody?.({method:s,path:c,operationId:g})}):void 0,re=tr(er(bn(l.security),h),p,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),ie={operationId:g,summary:a({summary:f,description:d,trim:ar}),description:d,deprecated:l.isDeprecated||void 0,tags:or(l.tags),parameters:or(ee),requestBody:ne,security:or(re),responses:te};this.addPath(En(c),{[s]:ie})}}constructor({hasHeadMethod:e=!0,...t}){super(),this.#o(t);let n=this.#s(t),r=e?jt(n):n;Rt({...t,onEndpoint:r})}};const lr=e=>ae({...e,headers:{"content-type":y.json,...e?.headers}}),ur=e=>oe(e),dr=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:ht(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},fr=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=lr(e),a=ur({req:i,...t});a.req=t?.req||i,i.res=a;let o=dr(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},pr=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=fr(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},mr=async({middleware:e,ctx:t={},...n})=>{let{configMock:{inputSources:r,errorHandler:i=U},...a}=fr(n),o=ve(a.requestMock,r),s={request:a.requestMock,response:a.responseMock,logger:a.loggerMock,input:o,ctx:t};try{let t=await e.execute(s);return{...a,output:t}}catch(e){return await i.execute({...s,error:x(e),output:null}),{...a,output:{}}}};var hr=class e{ts;f;exportModifier;asyncModifier;accessModifiers;#e;static#t=/^[A-Za-z_$][A-Za-z0-9_$]*$/;constructor(e){this.ts=e,this.f=this.ts.factory,this.exportModifier=[this.f.createModifier(this.ts.SyntaxKind.ExportKeyword)],this.asyncModifier=[this.f.createModifier(this.ts.SyntaxKind.AsyncKeyword)],this.accessModifiers={public:[this.f.createModifier(this.ts.SyntaxKind.PublicKeyword)],publicStatic:[this.f.createModifier(this.ts.SyntaxKind.PublicKeyword),this.f.createModifier(this.ts.SyntaxKind.StaticKeyword)],protectedReadonly:[this.f.createModifier(this.ts.SyntaxKind.ProtectedKeyword),this.f.createModifier(this.ts.SyntaxKind.ReadonlyKeyword)]},this.#e=[this.ts.SyntaxKind.AnyKeyword,this.ts.SyntaxKind.BigIntKeyword,this.ts.SyntaxKind.BooleanKeyword,this.ts.SyntaxKind.NeverKeyword,this.ts.SyntaxKind.NumberKeyword,this.ts.SyntaxKind.ObjectKeyword,this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.SymbolKeyword,this.ts.SyntaxKind.UndefinedKeyword,this.ts.SyntaxKind.UnknownKeyword,this.ts.SyntaxKind.VoidKeyword]}addJsDoc=(e,t)=>this.ts.addSyntheticLeadingComment(e,this.ts.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0);printNode=(e,t)=>{let n=this.ts.createSourceFile(`print.ts`,``,this.ts.ScriptTarget.Latest,!1,this.ts.ScriptKind.TS);return this.ts.createPrinter(t).printNode(this.ts.EmitHint.Unspecified,e,n)};makeId=e=>this.f.createIdentifier(e);makePropertyIdentifier=t=>typeof t==`string`&&e.#t.test(t)?this.makeId(t):this.literally(t);makeTemplate=(e,...t)=>this.f.createTemplateExpression(this.f.createTemplateHead(e),t.map(([e,n=``],r)=>this.f.createTemplateSpan(typeof e==`string`?this.makeId(e):e,r===t.length-1?this.f.createTemplateTail(n):this.f.createTemplateMiddle(n))));makeParam=(e,{type:t,mod:n,initId:r,optional:i}={})=>this.f.createParameterDeclaration(n,void 0,e,i?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,t?this.ensureTypeNode(t):void 0,r?this.makeId(r):void 0);makeParams=e=>Object.entries(e).map(([e,t])=>this.makeParam(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t));makePublicConstructor=(e,t=[])=>this.f.createConstructorDeclaration(this.accessModifiers.public,e,this.f.createBlock(t));ensureTypeNode=(e,t)=>typeof e==`number`?this.f.createKeywordTypeNode(e):typeof e==`string`||this.ts.isIdentifier(e)?this.f.createTypeReferenceNode(e,t&&r.map(this.ensureTypeNode,t)):e;makeRecordStringAny=()=>this.ensureTypeNode(`Record`,[this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.AnyKeyword]);makeUnion=e=>{let t=new Map;for(let n of e)t.set(this.isPrimitive(n)?n.kind:n,n);return this.f.createUnionTypeNode(Array.from(t.values()))};makeInterfaceProp=(e,t,{isOptional:n,hasUndefined:i=n,isDeprecated:a,comment:o}={})=>{let s=this.ensureTypeNode(t),c=this.f.createPropertySignature(void 0,this.makePropertyIdentifier(e),n?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,i?this.makeUnion([s,this.ensureTypeNode(this.ts.SyntaxKind.UndefinedKeyword)]):s),l=r.reject(r.isNil,[a?`@deprecated`:void 0,o]);return l.length?this.addJsDoc(c,l.join(` `)):c};makeOneLine=e=>this.ts.setEmitFlags(e,this.ts.EmitFlags.SingleLine);makeDeconstruction=(...e)=>this.f.createArrayBindingPattern(e.map(e=>this.f.createBindingElement(void 0,void 0,e)));makeConst=(e,t,{type:n,expose:r}={})=>this.f.createVariableStatement(r&&this.exportModifier,this.f.createVariableDeclarationList([this.f.createVariableDeclaration(e,void 0,n?this.ensureTypeNode(n):void 0,t)],this.ts.NodeFlags.Const));makePublicLiteralType=(e,t)=>this.makeType(e,this.makeUnion(r.map(this.makeLiteralType,t)),{expose:!0});makeType=(e,t,{expose:n,comment:r,params:i}={})=>{let a=this.f.createTypeAliasDeclaration(n?this.exportModifier:void 0,e,i&&this.makeTypeParams(i),t);return r?this.addJsDoc(a,r):a};makePublicProperty=(e,t)=>this.f.createPropertyDeclaration(this.accessModifiers.public,e,void 0,this.ensureTypeNode(t),void 0);makePublicMethod=(e,t,n,{typeParams:r,returns:i,isStatic:a}={})=>this.f.createMethodDeclaration(a?this.accessModifiers.publicStatic:this.accessModifiers.public,void 0,e,void 0,r&&this.makeTypeParams(r),t,i,this.f.createBlock(n));makePublicClass=(e,t,{typeParams:n}={})=>this.f.createClassDeclaration(this.exportModifier,e,n&&this.makeTypeParams(n),void 0,t);makeKeyOf=e=>this.f.createTypeOperatorNode(this.ts.SyntaxKind.KeyOfKeyword,this.ensureTypeNode(e));makePromise=e=>this.ensureTypeNode(Promise.name,[e]);makeInterface=(e,t,{expose:n,comment:r}={})=>{let i=this.f.createInterfaceDeclaration(n?this.exportModifier:void 0,e,void 0,void 0,t);return r?this.addJsDoc(i,r):i};makeTypeParams=e=>(Array.isArray(e)?e.map(e=>r.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return this.f.createTypeParameterDeclaration([],e,n?this.ensureTypeNode(n):void 0,r?this.ensureTypeNode(r):void 0)});makeArrowFn=(e,t,{isAsync:n}={})=>this.f.createArrowFunction(n?this.asyncModifier:void 0,void 0,Array.isArray(e)?r.map(this.makeParam,e):this.makeParams(e),void 0,void 0,t);makeTernary=(...e)=>{let[t,n,r]=e.map(e=>typeof e==`string`?this.makeId(e):e);return this.f.createConditionalExpression(t,this.f.createToken(this.ts.SyntaxKind.QuestionToken),n,this.f.createToken(this.ts.SyntaxKind.ColonToken),r)};makeCall=(e,...t)=>(...n)=>this.f.createCallExpression(t.reduce((e,t)=>typeof t==`string`||this.ts.isIdentifier(t)?this.f.createPropertyAccessExpression(e,t):this.f.createElementAccessExpression(e,t),typeof e==`string`?this.makeId(e):e),void 0,n.map(e=>typeof e==`string`?this.makeId(e):e));makeNew=(e,...t)=>this.f.createNewExpression(this.makeId(e),void 0,t);makeExtract=(e,t)=>this.ensureTypeNode(`Extract`,[e,t]);makeAssignment=(e,t)=>this.f.createExpressionStatement(this.f.createBinaryExpression(typeof e==`string`?this.makeId(e):e,this.f.createToken(this.ts.SyntaxKind.EqualsToken),t));makeIndexed=(e,t)=>this.f.createIndexedAccessTypeNode(this.ensureTypeNode(e),this.ensureTypeNode(t));makeMaybeAsync=e=>this.makeUnion([this.ensureTypeNode(e),this.makePromise(e)]);makeFnType=(e,t)=>this.f.createFunctionTypeNode(void 0,this.makeParams(e),this.ensureTypeNode(t));literally=e=>typeof e==`number`?this.f.createNumericLiteral(e):typeof e==`bigint`?this.f.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?this.f.createTrue():this.f.createFalse():e===null?this.f.createNull():this.f.createStringLiteral(e);makeLiteralType=e=>this.f.createLiteralTypeNode(this.literally(e));isPrimitive=e=>this.#e.includes(e.kind)};const Z=e=>e;var gr=class{serverUrl;api;paths=new Set;tags=new Map;registry=new Map;constructor(e,t){this.serverUrl=t,this.api=new hr(e)}#e={pathType:`Path`,implementationType:`Implementation`,keyParameter:`key`,pathParameter:`path`,paramsArgument:`params`,ctxArgument:`ctx`,methodParameter:`method`,requestParameter:`request`,eventParameter:`event`,dataParameter:`data`,handlerParameter:`handler`,msgParameter:`msg`,parseRequestFn:`parseRequest`,substituteFn:`substitute`,provideMethod:`provide`,onMethod:`on`,implementationArgument:`implementation`,hasBodyConst:`hasBody`,undefinedValue:`undefined`,responseConst:`response`,restConst:`rest`,searchParamsConst:`searchParams`,defaultImplementationConst:`defaultImplementation`,clientConst:`client`,contentTypeConst:`contentType`,isJsonConst:`isJSON`,sourceProp:`source`,methodType:`Method`,someOfType:`SomeOf`,requestType:`Request`,paginationType:`Pagination`};interfaces={input:`Input`,positive:`PositiveResponse`,negative:`NegativeResponse`,encoded:`EncodedResponse`,response:`Response`};makeMethodType=()=>this.api.makePublicLiteralType(this.#e.methodType,le);makeSomeOfType=()=>this.api.makeType(this.#e.someOfType,this.api.makeIndexed(`T`,this.api.makeKeyOf(`T`)),{params:[`T`]});makeRequestType=()=>this.api.makeType(this.#e.requestType,this.api.makeKeyOf(this.interfaces.input),{expose:!0});someOf=({name:e})=>this.api.ensureTypeNode(this.#e.someOfType,[e]);makePathType=()=>this.api.makePublicLiteralType(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>this.api.makeInterface(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>this.api.makeInterfaceProp(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>this.api.makeConst(`endpointTags`,this.api.f.createObjectLiteralExpression(Array.from(this.tags).map(([e,t])=>this.api.f.createPropertyAssignment(this.api.makePropertyIdentifier(e),this.api.f.createArrayLiteralExpression(r.map(this.api.literally,t))))),{expose:!0});makeImplementationType=()=>this.api.makeType(this.#e.implementationType,this.api.makeFnType({[this.#e.methodParameter]:this.#e.methodType,[this.#e.pathParameter]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument]:this.api.makeRecordStringAny(),[this.#e.ctxArgument]:{optional:!0,type:`T`}},this.api.makePromise(this.api.ts.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:this.api.ts.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>this.api.makeConst(this.#e.parseRequestFn,this.api.makeArrowFn({[this.#e.requestParameter]:this.api.ts.SyntaxKind.StringKeyword},this.api.f.createAsExpression(this.api.makeCall(this.#e.requestParameter,Z(`split`))(this.api.f.createRegularExpressionLiteral(`/ (.+)/`),this.api.literally(2)),this.api.f.createTupleTypeNode([this.api.ensureTypeNode(this.#e.methodType),this.api.ensureTypeNode(this.#e.pathType)]))));makeSubstituteFn=()=>this.api.makeConst(this.#e.substituteFn,this.api.makeArrowFn({[this.#e.pathParameter]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument]:this.api.makeRecordStringAny()},this.api.f.createBlock([this.api.makeConst(this.#e.restConst,this.api.f.createObjectLiteralExpression([this.api.f.createSpreadAssignment(this.api.makeId(this.#e.paramsArgument))])),this.api.f.createForInStatement(this.api.f.createVariableDeclarationList([this.api.f.createVariableDeclaration(this.#e.keyParameter)],this.api.ts.NodeFlags.Const),this.api.makeId(this.#e.paramsArgument),this.api.f.createBlock([this.api.makeAssignment(this.#e.pathParameter,this.api.makeCall(this.#e.pathParameter,Z(`replace`))(this.api.makeTemplate(`:`,[this.#e.keyParameter]),this.api.makeArrowFn([],this.api.f.createBlock([this.api.f.createExpressionStatement(this.api.f.createDeleteExpression(this.api.f.createElementAccessExpression(this.api.makeId(this.#e.restConst),this.api.makeId(this.#e.keyParameter)))),this.api.f.createReturnStatement(this.api.f.createElementAccessExpression(this.api.makeId(this.#e.paramsArgument),this.api.makeId(this.#e.keyParameter)))]))))])),this.api.f.createReturnStatement(this.api.f.createAsExpression(this.api.f.createArrayLiteralExpression([this.api.makeId(this.#e.pathParameter),this.api.makeId(this.#e.restConst)]),this.api.ensureTypeNode(`const`)))])));makePaginationType=()=>{let e=Z(`nextCursor`),t=Z(`total`),n=Z(`limit`),r=Z(`offset`),i=this.api.f.createTypeLiteralNode([this.api.makeInterfaceProp(e,this.api.makeUnion([this.api.ensureTypeNode(this.api.ts.SyntaxKind.StringKeyword),this.api.makeLiteralType(null)]))]),a=this.api.f.createTypeLiteralNode([t,n,r].map(e=>this.api.makeInterfaceProp(e,this.api.ts.SyntaxKind.NumberKeyword)));return this.api.makeType(this.#e.paginationType,this.api.makeUnion([i,a]))};#t=()=>{let e=this.api.makeId(this.#e.responseConst),t=Z(`nextCursor`),n=Z(`total`),r=Z(`limit`),i=Z(`offset`),a=this.api.f.createBinaryExpression(this.api.literally(t),this.api.ts.SyntaxKind.InKeyword,e),o=this.api.f.createReturnStatement(this.api.f.createBinaryExpression(this.api.f.createPropertyAccessExpression(e,t),this.api.ts.SyntaxKind.ExclamationEqualsEqualsToken,this.api.literally(null))),s=this.api.f.createBinaryExpression(this.api.f.createPropertyAccessExpression(e,i),this.api.ts.SyntaxKind.PlusToken,this.api.f.createPropertyAccessExpression(e,r)),c=this.api.f.createReturnStatement(this.api.f.createBinaryExpression(s,this.api.ts.SyntaxKind.LessThanToken,this.api.f.createPropertyAccessExpression(e,n)));return this.api.makePublicMethod(`hasMore`,[this.api.makeParam(e,{type:this.#e.paginationType})],[this.api.f.createIfStatement(a,o),c],{returns:this.api.ensureTypeNode(this.api.ts.SyntaxKind.BooleanKeyword),isStatic:!0})};#n=()=>this.api.makePublicMethod(this.#e.provideMethod,this.api.makeParams({[this.#e.requestParameter]:`K`,[this.#e.paramsArgument]:this.api.makeIndexed(this.interfaces.input,`K`),[this.#e.ctxArgument]:{optional:!0,type:`T`}}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.methodParameter,this.#e.pathParameter),this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter)),this.api.f.createReturnStatement(this.api.makeCall(this.api.f.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,this.api.f.createSpreadElement(this.api.makeCall(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.#e.requestType},returns:this.api.makePromise(this.api.makeIndexed(this.interfaces.response,`K`))});makeClientClass=e=>this.api.makePublicClass(e,[this.api.makePublicConstructor([this.api.makeParam(this.#e.implementationArgument,{type:this.api.ensureTypeNode(this.#e.implementationType,[`T`]),mod:this.api.accessModifiers.protectedReadonly,initId:this.#e.defaultImplementationConst})]),this.#n(),this.#t()],{typeParams:[`T`]});#r=e=>this.api.makeTemplate(`?`,[this.api.makeNew(URLSearchParams.name,this.api.makeId(e))]);#i=()=>this.api.makeNew(URL.name,this.api.makeTemplate(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),this.api.literally(this.serverUrl));makeDefaultImplementation=()=>{let e=this.api.f.createPropertyAssignment(Z(`method`),this.api.makeCall(this.#e.methodParameter,Z(`toUpperCase`))()),t=this.api.f.createPropertyAssignment(Z(`headers`),this.api.makeTernary(this.#e.hasBodyConst,this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(this.api.literally(`Content-Type`),this.api.literally(y.json))]),this.#e.undefinedValue)),n=this.api.f.createPropertyAssignment(Z(`body`),this.api.makeTernary(this.#e.hasBodyConst,this.api.makeCall(JSON[Symbol.toStringTag],Z(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=this.api.makeConst(this.#e.responseConst,this.api.f.createAwaitExpression(this.api.makeCall(fetch.name)(this.#i(),this.api.f.createObjectLiteralExpression([e,t,n])))),i=this.api.makeConst(this.#e.hasBodyConst,this.api.f.createLogicalNot(this.api.makeCall(this.api.f.createArrayLiteralExpression([this.api.literally(`get`),this.api.literally(`head`),this.api.literally(`delete`)]),Z(`includes`))(this.#e.methodParameter))),a=this.api.makeConst(this.#e.searchParamsConst,this.api.makeTernary(this.#e.hasBodyConst,this.api.literally(``),this.#r(this.#e.paramsArgument))),o=this.api.makeConst(this.#e.contentTypeConst,this.api.makeCall(this.#e.responseConst,Z(`headers`),Z(`get`))(this.api.literally(`content-type`))),s=this.api.f.createIfStatement(this.api.f.createPrefixUnaryExpression(this.api.ts.SyntaxKind.ExclamationToken,this.api.makeId(this.#e.contentTypeConst)),this.api.f.createReturnStatement()),c=this.api.makeConst(this.#e.isJsonConst,this.api.makeCall(this.#e.contentTypeConst,Z(`startsWith`))(this.api.literally(y.json))),l=this.api.f.createReturnStatement(this.api.makeCall(this.#e.responseConst,this.api.makeTernary(this.#e.isJsonConst,this.api.literally(Z(`json`)),this.api.literally(Z(`text`))))());return this.api.makeConst(this.#e.defaultImplementationConst,this.api.makeArrowFn([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],this.api.f.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#e.implementationType})};#a=()=>this.api.makePublicConstructor(this.api.makeParams({request:`K`,params:this.api.makeIndexed(this.interfaces.input,`K`)}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.pathParameter,this.#e.restConst),this.api.makeCall(this.#e.substituteFn)(this.api.f.createElementAccessExpression(this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter),this.api.literally(1)),this.#e.paramsArgument)),this.api.makeConst(this.#e.searchParamsConst,this.#r(this.#e.restConst)),this.api.makeAssignment(this.api.f.createPropertyAccessExpression(this.api.f.createThis(),this.#e.sourceProp),this.api.makeNew(`EventSource`,this.#i()))]);#o=e=>this.api.f.createTypeLiteralNode([this.api.makeInterfaceProp(Z(`event`),e)]);#s=()=>this.api.makePublicMethod(this.#e.onMethod,this.api.makeParams({[this.#e.eventParameter]:`E`,[this.#e.handlerParameter]:this.api.makeFnType({[this.#e.dataParameter]:this.api.makeIndexed(this.api.makeExtract(`R`,this.api.makeOneLine(this.#o(`E`))),this.api.makeLiteralType(Z(`data`)))},this.api.makeMaybeAsync(this.api.ts.SyntaxKind.VoidKeyword))}),[this.api.f.createExpressionStatement(this.api.makeCall(this.api.f.createThis(),this.#e.sourceProp,Z(`addEventListener`))(this.#e.eventParameter,this.api.makeArrowFn([this.#e.msgParameter],this.api.makeCall(this.#e.handlerParameter)(this.api.makeCall(JSON[Symbol.toStringTag],Z(`parse`))(this.api.f.createPropertyAccessExpression(this.api.f.createParenthesizedExpression(this.api.f.createAsExpression(this.api.makeId(this.#e.msgParameter),this.api.ensureTypeNode(MessageEvent.name))),Z(`data`))))))),this.api.f.createReturnStatement(this.api.f.createThis())],{typeParams:{E:this.api.makeIndexed(`R`,this.api.makeLiteralType(Z(`event`)))}});makeSubscriptionClass=e=>this.api.makePublicClass(e,[this.api.makePublicProperty(this.#e.sourceProp,`EventSource`),this.#a(),this.#s()],{typeParams:{K:this.api.makeExtract(this.#e.requestType,this.api.f.createTemplateLiteralType(this.api.f.createTemplateHead(`get `),[this.api.f.createTemplateLiteralTypeSpan(this.api.ensureTypeNode(this.api.ts.SyntaxKind.StringKeyword),this.api.f.createTemplateTail(``))])),R:this.api.makeExtract(this.api.makeIndexed(this.interfaces.positive,`K`),this.api.makeOneLine(this.#o(this.api.ts.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[this.api.makeConst(this.#e.clientConst,this.api.makeNew(e)),this.api.makeCall(this.#e.clientConst,this.#e.provideMethod)(this.api.literally(`get /v1/user/retrieve`),this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(`id`,this.api.literally(`10`))])),this.api.makeCall(this.api.makeNew(t,this.api.literally(`get /v1/events/stream`),this.api.f.createObjectLiteralExpression()),this.#e.onMethod)(this.api.literally(`time`),this.api.makeArrowFn([`time`],this.api.f.createBlock([])))]};const _r=(e,{rules:t,onMissing:n,ctx:r={}})=>{let i=O(e),a=i&&i in t?t[i]:t[e._zod.def.type],o=e=>_r(e,{ctx:r,rules:t,onMissing:n});return a?a(e,{...r,next:o}):n(e,r)},vr={name:r.path([`name`,`text`]),type:r.path([`type`]),optional:r.path([`questionToken`])},yr=({_zod:{def:e}},{api:t})=>{let n=e.values.map(e=>e===void 0?t.ensureTypeNode(t.ts.SyntaxKind.UndefinedKeyword):t.makeLiteralType(e));return n.length===1?n[0]:t.makeUnion(n)},br=({_zod:{def:e}},{next:t,api:n})=>{let{parts:r}=e,i=0,a=()=>{let e=``;for(;i<r.length;){let t=r[i];if(C(t))break;i++,e+=t??``}return e},o=n.f.createTemplateHead(a()),s=[];for(;i<r.length;){let e=t(r[i++]),o=a(),c=i<r.length?n.f.createTemplateMiddle:n.f.createTemplateTail;s.push(n.f.createTemplateLiteralTypeSpan(e,c(o)))}return s.length?n.f.createTemplateLiteralType(o,s):n.makeLiteralType(o.text)},xr=(e,{isResponse:r,next:i,makeAlias:a,api:o})=>{let s=()=>{let a=Object.entries(e._zod.def.shape).map(([e,a])=>{let{description:s,deprecated:c}=t.get(a)||{},l=(r?a._zod.optout:a._zod.optin)===`optional`,u=l&&!(a instanceof n.core.$ZodExactOptional);return o.makeInterfaceProp(e,i(a),{comment:s,isDeprecated:c,isOptional:l,hasUndefined:u})});return o.f.createTypeLiteralNode(a)};return ze(e,{io:r?`output`:`input`})?a(e,s):s()},Sr=({_zod:{def:e}},{next:t,api:n})=>n.f.createArrayTypeNode(t(e.element)),Cr=({_zod:{def:e}},{api:t})=>t.makeUnion(r.map(t.makeLiteralType,Object.values(e.entries))),wr=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion(e.options.map(t)),Tr=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion([t(e.innerType),n.makeLiteralType(null)]),Er=({_zod:{def:e}},{next:t,api:n})=>n.f.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:n.f.createRestTypeNode(t(e.rest)))),Dr=({_zod:{def:e}},{next:t,api:n})=>{let[r,i]=[e.keyType,e.valueType].map(t),a=n.ensureTypeNode(`Record`,[r,i]);return e.mode===`loose`?n.f.createIntersectionTypeNode([a,n.ensureTypeNode(`Record`,[`PropertyKey`,i])]):a},Or=r.tryCatch((e,t)=>{if(!t.every(e.ts.isTypeLiteralNode))throw Error(`Not objects`);let n=r.chain(r.prop(`members`),t),i=r.uniqWith((...e)=>{if(!r.eqBy(vr.name,...e))return!1;if(r.both(r.eqBy(vr.type),r.eqBy(vr.optional))(...e))return!0;throw Error(`Has conflicting prop`)},n);return e.f.createTypeLiteralNode(i)},(e,t,n)=>t.f.createIntersectionTypeNode(n)),kr=({_zod:{def:e}},{next:t,api:n})=>Or(n,[e.left,e.right].map(t)),Q=e=>({},{api:t})=>t.ensureTypeNode(t.ts.SyntaxKind[e]),$=({_zod:{def:e}},{next:t})=>t(e.innerType),Ar=(e,t)=>e.ensureTypeNode(t?e.ts.SyntaxKind.UnknownKeyword:e.ts.SyntaxKind.AnyKeyword),jr=({_zod:{def:e}},{next:t,isResponse:n,api:r})=>{let i=e[n?`out`:`in`],a=e[n?`in`:`out`];if(!C(i,`transform`))return t(i);let o=t(a),s={[r.ts.SyntaxKind.AnyKeyword]:``,[r.ts.SyntaxKind.BigIntKeyword]:BigInt(0),[r.ts.SyntaxKind.BooleanKeyword]:!1,[r.ts.SyntaxKind.NumberKeyword]:0,[r.ts.SyntaxKind.ObjectKeyword]:{},[r.ts.SyntaxKind.StringKeyword]:``,[r.ts.SyntaxKind.UndefinedKeyword]:void 0}[o.kind],c=be(i,s),l={number:r.ts.SyntaxKind.NumberKeyword,bigint:r.ts.SyntaxKind.BigIntKeyword,boolean:r.ts.SyntaxKind.BooleanKeyword,string:r.ts.SyntaxKind.StringKeyword,undefined:r.ts.SyntaxKind.UndefinedKeyword,object:r.ts.SyntaxKind.ObjectKeyword};return r.ensureTypeNode(c&&l[c]||Ar(r,n))},Mr=({},{api:e})=>e.makeLiteralType(null),Nr=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),Pr=({},{api:e})=>e.ensureTypeNode(`Buffer`),Fr=(e,{next:t})=>t(e._zod.def.shape.raw),Ir={string:Q(`StringKeyword`),number:Q(`NumberKeyword`),bigint:Q(`BigIntKeyword`),boolean:Q(`BooleanKeyword`),any:Q(`AnyKeyword`),undefined:Q(`UndefinedKeyword`),[j]:Q(`StringKeyword`),[M]:Q(`StringKeyword`),never:Q(`NeverKeyword`),void:Q(`UndefinedKeyword`),unknown:Q(`UnknownKeyword`),null:Mr,array:Sr,tuple:Er,record:Dr,object:xr,literal:yr,template_literal:br,intersection:kr,union:wr,default:$,enum:Cr,optional:$,nonoptional:$,nullable:Tr,catch:$,pipe:jr,lazy:Nr,readonly:$,[A]:Pr,[L]:Fr},Lr=(e,{brandHandling:t,ctx:n})=>_r(e,{rules:{...t,...Ir},onMissing:({},{isResponse:e,api:t})=>Ar(t,e),ctx:n});var Rr=class extends gr{#e=[this.makeSomeOfType()];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=this.api.makeLiteralType(null);this.#t.set(e,this.api.makeType(n,r)),this.#t.set(e,this.api.makeType(n,t()))}return this.api.ensureTypeNode(n)}constructor({typescript:e=W(`typescript`),routing:t,config:i,brandHandling:a,variant:o=`client`,clientClassName:s=`Client`,subscriptionClassName:c=`Subscription`,serverUrl:l=`https://example.com`,noBodySchema:u=n.undefined(),hasHeadMethod:d=!0}){super(e,l);let f={makeAlias:this.#r.bind(this),api:this.api},p={brandHandling:a,ctx:{...f,isResponse:!1}},m={brandHandling:a,ctx:{...f,isResponse:!0}},h=(e,t,n)=>{let i=T.bind(null,e,t),{isDeprecated:a,inputSchema:o,tags:s}=n,c=`${e} ${t}`,l=this.api.makeType(i(`input`),Lr(o,p),{comment:c});this.#e.push(l);let d=Qe.reduce((t,a)=>{let o=n.getResponses(a),s=r.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=Se(e,r),l=this.api.makeType(i(a,`variant`,`${t+1}`),Lr(s?n:u,m),{comment:c});return this.#e.push(l),o.map(e=>this.api.makeInterfaceProp(e,l.name))},Array.from(o.entries())),l=this.api.makeInterface(i(a,`response`,`variants`),s,{comment:c});return this.#e.push(l),Object.assign(t,{[a]:l})},{});this.paths.add(t);let f=this.api.makeLiteralType(c),h={input:this.api.ensureTypeNode(l.name),positive:this.someOf(d.positive),negative:this.someOf(d.negative),response:this.api.makeUnion([this.api.makeIndexed(this.interfaces.positive,f),this.api.makeIndexed(this.interfaces.negative,f)]),encoded:this.api.f.createIntersectionTypeNode([this.api.ensureTypeNode(d.positive.name),this.api.ensureTypeNode(d.negative.name)])};this.registry.set(c,{isDeprecated:a,store:h}),this.tags.set(c,s)};Rt({routing:t,config:i,onEndpoint:d?jt(h):h}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.makeMethodType(),...this.makePublicInterfaces(),this.makeRequestType()),o!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makePaginationType(),this.makeDefaultImplementation(),this.makeClientClass(s),this.makeSubscriptionClass(c)),this.#n.push(...this.makeUsageStatements(s,c)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:this.api.printNode(t,e)).join(`
7
- `):void 0}print(e){let t=this.#i(e),n=t&&this.api.ts.addSyntheticLeadingComment(this.api.ts.addSyntheticLeadingComment(this.api.f.createEmptyStatement(),this.api.ts.SyntaxKind.SingleLineCommentTrivia,` Usage example:`),this.api.ts.SyntaxKind.MultiLineCommentTrivia,`\n${t}`);return this.#e.concat(n||[]).map((t,n)=>this.api.printNode(t,n<this.#e.length?e:{...e,omitTrailingSemicolon:!0})).join(`
8
-
9
- `)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=W(`prettier`).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#i(e);this.#n=r&&n?[await n(r)]:this.#n;let i=this.print(e);return n?n(i):i}};const zr=(e,t)=>n.object({data:t,event:n.literal(e),id:n.string().optional(),retry:n.int().positive().optional()}),Br=(e,t,n)=>zr(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
10
- `)).parse({event:t,data:n}),Vr=e=>e.headersSent||e.writeHead(200,{connection:`keep-alive`,"content-type":y.sse,"cache-control":`no-cache`}),Hr=e=>new R({handler:async({request:t,response:n})=>{let r=new AbortController,i=setTimeout(()=>Vr(n),1e4);return t.once(`close`,()=>{clearTimeout(i),r.abort()}),{isClosed:()=>n.writableEnded||n.closed,signal:r.signal,emit:(t,r)=>{Vr(n),n.write(Br(e,t,r),`utf-8`),n.flush?.()}}}}),Ur=e=>new H({positive:()=>{let[t,...r]=Object.entries(e).map(([e,t])=>zr(e,t));if(!t)throw new ke(Error(`At least one SSE event is required.`));return{mimeType:y.sse,schema:r.length?n.discriminatedUnion(`event`,[t,...r]):t}},negative:{mimeType:`text/plain`,schema:n.string()},handler:async({response:e,error:t,logger:n,request:r,input:i})=>{if(t){let a=z(t);Ke(a,n,r,i),e.headersSent||e.status(a.statusCode).type(`text/plain`).write(B(a),`utf-8`)}e.end()}});var Wr=class extends G{constructor(e){super(Ur(e)),this.middlewares=[Hr(e)]}};const Gr=[`total`,`limit`,`offset`],Kr=[`nextCursor`,`limit`];function qr({style:e,itemSchema:t,itemsName:r=`items`,maxLimit:i=100,defaultLimit:a=20}){if(!Number.isInteger(i)||i<1)throw Error(`ez.paginated: maxLimit must be a positive integer`);if(!Number.isInteger(a)||a<1)throw Error(`ez.paginated: defaultLimit must be a positive integer`);if(a>i)throw Error(`ez.paginated: defaultLimit must not be greater than maxLimit`);if(e===`offset`&&Gr.includes(r))throw Error(`ez.paginated: itemsName must not match reserved keys for offset output (${Gr.join(`, `)})`);if(e===`cursor`&&Kr.includes(r))throw Error(`ez.paginated: itemsName must not match reserved keys for cursor output (${Kr.join(`, `)})`);let o=n.coerce.number().int().min(1).max(i).default(a).describe(`Page size (number of ${r} per page)`);if(e===`offset`){let e=n.coerce.number().int().min(0).default(0).describe(`Number of ${r} to skip`);return{input:n.object({limit:o,offset:e}),output:n.object({[r]:n.array(t).describe(`Page of ${r}`),total:n.number().int().min(0).describe(`Total number of ${r}`),limit:n.number().int().min(1).describe(`Page size used`),offset:n.number().int().min(0).describe(`Offset used`)})}}let s=n.string().optional().describe(`Cursor for the next page; omit for first page`);return{input:n.object({cursor:s,limit:o}),output:n.object({[r]:n.array(t).describe(`Page of ${r}`),nextCursor:n.string().nullable().describe(`Cursor for the next page, or null if no more pages`),limit:n.number().int().min(1).describe(`Page size used`)})}}const Jr={dateIn:we,dateOut:Te,form:Me,upload:Pe,raw:Le,buffer:Ce,paginated:qr};export{vt as BuiltinLogger,cr as Documentation,P as DocumentationError,G as EndpointsFactory,Wr as EventStreamFactory,F as InputValidationError,Rr as Integration,R as Middleware,Ae as MissingPeerError,Oe as OutputValidationError,H as ResultHandler,N as RoutingError,yt as ServeStatic,ft as arrayEndpointsFactory,nt as arrayResultHandler,mn as attachRouting,st as createCacheMiddleware,se as createConfig,ct as createCookieMiddleware,ut as createRateLimitMiddleware,gn as createServer,dt as defaultEndpointsFactory,U as defaultResultHandler,z as ensureHttpError,Jr as ez,S as getMessageFromError,pr as testEndpoint,mr as testMiddleware};
6
+ `)},Q=e=>{e.startupLogo!==!1&&st(process.stdout);let t=e.errorHandler||M,n=Le(e.logger)?e.logger:new U(e.logger);n.debug(`Running`,{build:`v29.0.0-beta.4`,env:process.env.NODE_ENV||`development`}),at(n);let r=rt({logger:n,config:e}),i={getLogger:it(n),errorHandler:t},a=Ze(i),o=Xe(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},ct=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=Q(e),o=e.app.use(a);return e.cors&&o.use(q(e.cors)),G({app:o,routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},lt=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=Q(e),s=k().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.beforeParsers?.({app:s,getLogger:r}),e.compression){let t=S(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}return e.cookies&&s.use($e({config:e})),e.cors&&s.use(q(e.cors)),s.use(e.jsonParser||k.json()).use(e.formParser||k.urlencoded()).use(e.rawParser||k.raw(),nt),e.upload&&s.use(...tt({config:e,getLogger:r})),e.beforeRouting?.({app:s,getLogger:r}),G({app:s,routing:t,getLogger:r,config:e}),e.afterRouting?.({app:s,getLogger:r}),s.use(a,i),{app:s,logger:n}},ut=(e,t)=>{let{app:n,logger:r}=lt(e,t),i=[],a=(e,t)=>()=>e.listen(t,()=>r.info(`Listening`,t)),o=[];if(e.http){let t=Ce.createServer(n);i.push(t),o.push(a(t,e.http.listen))}if(e.https){let t=we.createServer(e.https.options,n);i.push(t),o.push(a(t,e.https.listen))}return i.length||r.warn(`No servers configured.`),e.gracefulShutdown&&ot({logger:r,servers:i,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:n,logger:r,servers:o.map(e=>e())}},dt=e=>Ee({...e,headers:{"content-type":s.json,...e?.headers}}),ft=e=>De(e),pt=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:Re(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},mt=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=dt(e),a=ft({req:i,...t});a.req=t?.req||i,i.res=a;let o=pt(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},ht=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=mt(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},gt=async({middleware:e,ctx:t={},...n})=>{let{configMock:{inputSources:r,errorHandler:i=M},...o}=mt(n),s=c(o.requestMock,r),l={request:o.requestMock,response:o.responseMock,logger:o.loggerMock,input:s,ctx:t};try{let t=await e.execute(l);return{...o,output:t}}catch(e){return await i.execute({...l,error:a(e),output:null}),{...o,output:{}}}},_t=(e,t)=>w.object({data:t,event:w.literal(e),id:w.string().optional(),retry:w.int().positive().optional()}),vt=(e,t,n)=>_t(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
7
+ `)).parse({event:t,data:n}),yt=e=>e.headersSent||e.writeHead(200,{connection:`keep-alive`,"content-type":s.sse,"cache-control":`no-cache`}),bt=e=>new b({handler:async({request:t,response:n})=>{let r=new AbortController,i=setTimeout(()=>yt(n),1e4);return t.once(`close`,()=>{clearTimeout(i),r.abort()}),{isClosed:()=>n.writableEnded||n.closed,signal:r.signal,emit:(t,r)=>{yt(n),n.write(vt(e,t,r),`utf-8`),n.flush?.()}}}}),xt=e=>new A({positive:()=>{let[t,...n]=Object.entries(e).map(([e,t])=>_t(e,t));if(!t)throw new u(Error(`At least one SSE event is required.`));return{mimeType:s.sse,schema:n.length?w.discriminatedUnion(`event`,[t,...n]):t}},negative:{mimeType:`text/plain`,schema:w.string()},handler:async({response:e,error:t,logger:n,request:r,input:i})=>{if(t){let a=h(t);x(a,n,r,i),e.headersSent||e.status(a.statusCode).type(`text/plain`).write(v(a),`utf-8`)}e.end()}});var St=class extends z{constructor(e){super(xt(e)),this.middlewares=[bt(e)]}};const Ct=[`total`,`limit`,`offset`],$=[`nextCursor`,`limit`];function wt({style:e,itemSchema:t,itemsName:n=`items`,maxLimit:r=100,defaultLimit:i=20}){if(!Number.isInteger(r)||r<1)throw Error(`ez.paginated: maxLimit must be a positive integer`);if(!Number.isInteger(i)||i<1)throw Error(`ez.paginated: defaultLimit must be a positive integer`);if(i>r)throw Error(`ez.paginated: defaultLimit must not be greater than maxLimit`);if(e===`offset`&&Ct.includes(n))throw Error(`ez.paginated: itemsName must not match reserved keys for offset output (${Ct.join(`, `)})`);if(e===`cursor`&&$.includes(n))throw Error(`ez.paginated: itemsName must not match reserved keys for cursor output (${$.join(`, `)})`);let a=w.coerce.number().int().min(1).max(r).default(i).describe(`Page size (number of ${n} per page)`);if(e===`offset`){let e=w.coerce.number().int().min(0).default(0).describe(`Number of ${n} to skip`);return{input:w.object({limit:a,offset:e}),output:w.object({[n]:w.array(t).describe(`Page of ${n}`),total:w.number().int().min(0).describe(`Total number of ${n}`),limit:w.number().int().min(1).describe(`Page size used`),offset:w.number().int().min(0).describe(`Offset used`)})}}let o=w.string().optional().describe(`Cursor for the next page; omit for first page`);return{input:w.object({cursor:o,limit:a}),output:w.object({[n]:w.array(t).describe(`Page of ${n}`),nextCursor:w.string().nullable().describe(`Cursor for the next page, or null if no more pages`),limit:w.number().int().min(1).describe(`Page size used`)})}}const Tt={dateIn:ae,dateOut:n,form:ne,upload:fe,raw:te,buffer:ie,paginated:wt};export{U as BuiltinLogger,de as DocumentationError,z as EndpointsFactory,St as EventStreamFactory,l as InputValidationError,b as Middleware,t as MissingPeerError,ue as OutputValidationError,A as ResultHandler,r as RoutingError,se as ServeStatic,Ie as arrayEndpointsFactory,P as arrayResultHandler,ct as attachRouting,re as createApiResponse,I as createCacheMiddleware,Oe as createConfig,L as createCookieMiddleware,R as createRateLimitMiddleware,ut as createServer,Fe as defaultEndpointsFactory,M as defaultResultHandler,h as ensureHttpError,Tt as ez,e as getMessageFromError,ht as testEndpoint,gt as testMiddleware};
@@ -0,0 +1,85 @@
1
+ import { d as FlatObject, g as CommonConfig, l as EmptyObject, t as Routing } from "./routing-xQnwfH2D.js";
2
+ import { z } from "zod";
3
+ import ts, { default as ts$1 } from "typescript";
4
+ interface NextHandlerInc<U> {
5
+ next: (schema: z.core.$ZodType) => U;
6
+ }
7
+ type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "last" = "regular"> = (
8
+ schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignment compatibility
9
+ ctx: Context & (Variant extends "regular" ? NextHandlerInc<U> : Context),
10
+ ) => U;
11
+ type HandlingRules<U, Context extends FlatObject = EmptyObject, K extends string | symbol = string | symbol> = Partial<
12
+ Record<K, SchemaHandler<U, Context>>
13
+ >;
14
+ interface ZTSContext extends FlatObject {
15
+ isResponse: boolean;
16
+ makeAlias: (key: object, produce: () => ts.TypeNode) => ts.TypeNode;
17
+ }
18
+ type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
19
+ declare abstract class IntegrationBase {
20
+ protected readonly serverUrl: string;
21
+ protected constructor(serverUrl: string);
22
+ }
23
+ interface IntegrationParams {
24
+ routing: Routing;
25
+ config: CommonConfig;
26
+ /**
27
+ * @desc What should be generated
28
+ * @example "types" — types of your endpoint requests and responses (for a DIY solution)
29
+ * @example "client" — an entity for performing typed requests and receiving typed responses
30
+ * @default "client"
31
+ * */
32
+ variant?: "types" | "client";
33
+ /** @default Client */
34
+ clientClassName?: string;
35
+ /** @default Subscription */
36
+ subscriptionClassName?: string;
37
+ /**
38
+ * @desc The API URL to use in the generated code
39
+ * @default https://example.com
40
+ * */
41
+ serverUrl?: string;
42
+ /**
43
+ * @desc The schema to use for responses without body such as 204
44
+ * @default z.undefined()
45
+ * */
46
+ noBodySchema?: z.ZodType;
47
+ /**
48
+ * @desc Depict the HEAD method for each Endpoint supporting the GET method (feature of Express)
49
+ * @default true
50
+ * */
51
+ hasHeadMethod?: boolean;
52
+ /**
53
+ * @desc Handling rules for your own schemas branded with `x-brand` metadata.
54
+ * @desc Keys: brands (recommended to use unique symbols).
55
+ * @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
56
+ * @example { MyBrand: (schema: typeof myBrandSchema, { next }) => createKeywordTypeNode(SyntaxKind.AnyKeyword)
57
+ * @link https://www.npmjs.com/package/@express-zod-api/zod-plugin
58
+ */
59
+ brandHandling?: HandlingRules<ts$1.TypeNode, ZTSContext>;
60
+ }
61
+ interface FormattedPrintingOptions {
62
+ /** @desc Typescript printer options */
63
+ printerOptions?: ts$1.PrinterOptions;
64
+ /**
65
+ * @desc Typescript code formatter
66
+ * @default prettier.format
67
+ * */
68
+ format?: (program: string) => Promise<string>;
69
+ }
70
+ declare class Integration extends IntegrationBase {
71
+ constructor({
72
+ routing,
73
+ config,
74
+ brandHandling,
75
+ variant,
76
+ clientClassName,
77
+ subscriptionClassName,
78
+ serverUrl,
79
+ noBodySchema,
80
+ hasHeadMethod,
81
+ }: IntegrationParams);
82
+ print(printerOptions?: ts$1.PrinterOptions): string;
83
+ printFormatted({ printerOptions, format: userDefined }?: FormattedPrintingOptions): Promise<string>;
84
+ }
85
+ export { Integration, type Producer };
@@ -0,0 +1,4 @@
1
+ import{A as e,G as t,H as n,J as r,K as i,M as a,N as o,O as s,Q as c,X as l,g as u,h as d,n as f,o as ee,t as p}from"./routing-walker-Uax31V_v.js";import{t as m}from"./peer-helpers-BFaGRU7x.js";import{globalRegistry as h,z as g}from"zod";import*as _ from"ramda";import v from"typescript";const y=v.factory,b=[y.createModifier(v.SyntaxKind.ExportKeyword)],te=[y.createModifier(v.SyntaxKind.AsyncKeyword)],x={public:[y.createModifier(v.SyntaxKind.PublicKeyword)],publicStatic:[y.createModifier(v.SyntaxKind.PublicKeyword),y.createModifier(v.SyntaxKind.StaticKeyword)],protectedReadonly:[y.createModifier(v.SyntaxKind.ProtectedKeyword),y.createModifier(v.SyntaxKind.ReadonlyKeyword)]},ne=/^[A-Za-z_$][A-Za-z0-9_$]*$/,re=[v.SyntaxKind.AnyKeyword,v.SyntaxKind.BigIntKeyword,v.SyntaxKind.BooleanKeyword,v.SyntaxKind.NeverKeyword,v.SyntaxKind.NumberKeyword,v.SyntaxKind.ObjectKeyword,v.SyntaxKind.StringKeyword,v.SyntaxKind.SymbolKeyword,v.SyntaxKind.UndefinedKeyword,v.SyntaxKind.UnknownKeyword,v.SyntaxKind.VoidKeyword],S=e=>e,C=e=>typeof e==`number`?y.createNumericLiteral(e):typeof e==`bigint`?y.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?y.createTrue():y.createFalse():e===null?y.createNull():y.createStringLiteral(e),w=e=>y.createIdentifier(e),T=e=>typeof e==`string`&&ne.test(e)?w(e):C(e),E=(e,t)=>typeof e==`number`?y.createKeywordTypeNode(e):typeof e==`string`||v.isIdentifier(e)?y.createTypeReferenceNode(e,t&&_.map(E,t)):e,ie=()=>E(`Record`,[v.SyntaxKind.StringKeyword,v.SyntaxKind.AnyKeyword]),D=e=>{let t=new Map;for(let n of e)t.set(ae(n)?n.kind:n,n);return y.createUnionTypeNode(Array.from(t.values()))},ae=e=>re.includes(e.kind),O=(e,t)=>v.addSyntheticLeadingComment(e,v.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),oe=(e,t)=>{let n=v.createSourceFile(`print.ts`,``,v.ScriptTarget.Latest,!1,v.ScriptKind.TS);return v.createPrinter(t).printNode(v.EmitHint.Unspecified,e,n)},k=(e,...t)=>y.createTemplateExpression(y.createTemplateHead(e),t.map(([e,n=``],r)=>y.createTemplateSpan(typeof e==`string`?w(e):e,r===t.length-1?y.createTemplateTail(n):y.createTemplateMiddle(n)))),A=(e,{type:t,mod:n,initId:r,optional:i}={})=>y.createParameterDeclaration(n,void 0,e,i?y.createToken(v.SyntaxKind.QuestionToken):void 0,t?E(t):void 0,r?w(r):void 0),j=e=>Object.entries(e).map(([e,t])=>A(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t)),se=(e,t=[])=>y.createConstructorDeclaration(x.public,e,y.createBlock(t)),M=(e,t,{isOptional:n,hasUndefined:r=n,isDeprecated:i,comment:a}={})=>{let o=E(t),s=y.createPropertySignature(void 0,T(e),n?y.createToken(v.SyntaxKind.QuestionToken):void 0,r?D([o,E(v.SyntaxKind.UndefinedKeyword)]):o),c=_.reject(_.isNil,[i?`@deprecated`:void 0,a]);return c.length?O(s,c.join(` `)):s},N=e=>v.setEmitFlags(e,v.EmitFlags.SingleLine),ce=(...e)=>y.createArrayBindingPattern(e.map(e=>y.createBindingElement(void 0,void 0,e))),P=(e,t,{type:n,expose:r}={})=>y.createVariableStatement(r&&b,y.createVariableDeclarationList([y.createVariableDeclaration(e,void 0,n?E(n):void 0,t)],v.NodeFlags.Const)),F=(e,t,{expose:n,comment:r,params:i}={})=>{let a=y.createTypeAliasDeclaration(n?b:void 0,e,i&&I(i),t);return r?O(a,r):a},le=(e,t)=>F(e,D(_.map(J,t)),{expose:!0}),I=e=>(Array.isArray(e)?e.map(e=>_.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return y.createTypeParameterDeclaration([],e,n?E(n):void 0,r?E(r):void 0)}),ue=(e,t)=>y.createPropertyDeclaration(x.public,e,void 0,E(t),void 0),L=(e,t,n,{typeParams:r,returns:i,isStatic:a}={})=>y.createMethodDeclaration(a?x.publicStatic:x.public,void 0,e,void 0,r&&I(r),t,i,y.createBlock(n)),R=(e,t,{typeParams:n}={})=>y.createClassDeclaration(b,e,n&&I(n),void 0,t),z=e=>y.createTypeOperatorNode(v.SyntaxKind.KeyOfKeyword,E(e)),B=e=>E(Promise.name,[e]),V=(e,t,{expose:n,comment:r}={})=>{let i=y.createInterfaceDeclaration(n?b:void 0,e,void 0,void 0,t);return r?O(i,r):i},H=(e,t,{isAsync:n}={})=>y.createArrowFunction(n?te:void 0,void 0,Array.isArray(e)?_.map(A,e):j(e),void 0,void 0,t),U=(...e)=>{let[t,n,r]=e.map(e=>typeof e==`string`?w(e):e);return y.createConditionalExpression(t,y.createToken(v.SyntaxKind.QuestionToken),n,y.createToken(v.SyntaxKind.ColonToken),r)},W=(e,...t)=>(...n)=>y.createCallExpression(t.reduce((e,t)=>typeof t==`string`||v.isIdentifier(t)?y.createPropertyAccessExpression(e,t):y.createElementAccessExpression(e,t),typeof e==`string`?w(e):e),void 0,n.map(e=>typeof e==`string`?w(e):e)),G=(e,...t)=>y.createNewExpression(w(e),void 0,t),K=(e,t)=>E(`Extract`,[e,t]),de=(e,t)=>y.createExpressionStatement(y.createBinaryExpression(typeof e==`string`?w(e):e,y.createToken(v.SyntaxKind.EqualsToken),t)),q=(e,t)=>y.createIndexedAccessTypeNode(E(e),E(t)),fe=e=>D([E(e),B(e)]),pe=(e,t)=>y.createFunctionTypeNode(void 0,j(e),E(t)),J=e=>y.createLiteralTypeNode(C(e));var me=class{serverUrl;paths=new Set;tags=new Map;registry=new Map;constructor(e){this.serverUrl=e}#e={pathType:`Path`,implementationType:`Implementation`,keyParameter:`key`,pathParameter:`path`,paramsArgument:`params`,ctxArgument:`ctx`,methodParameter:`method`,requestParameter:`request`,eventParameter:`event`,dataParameter:`data`,handlerParameter:`handler`,msgParameter:`msg`,parseRequestFn:`parseRequest`,substituteFn:`substitute`,provideMethod:`provide`,onMethod:`on`,implementationArgument:`implementation`,hasBodyConst:`hasBody`,undefinedValue:`undefined`,responseConst:`response`,restConst:`rest`,searchParamsConst:`searchParams`,defaultImplementationConst:`defaultImplementation`,clientConst:`client`,contentTypeConst:`contentType`,isJsonConst:`isJSON`,sourceProp:`source`,methodType:`Method`,someOfType:`SomeOf`,requestType:`Request`,paginationType:`Pagination`};interfaces={input:`Input`,positive:`PositiveResponse`,negative:`NegativeResponse`,encoded:`EncodedResponse`,response:`Response`};makeMethodType=()=>le(this.#e.methodType,l);makeSomeOfType=()=>F(this.#e.someOfType,q(`T`,z(`T`)),{params:[`T`]});makeRequestType=()=>F(this.#e.requestType,z(this.interfaces.input),{expose:!0});someOf=({name:e})=>E(this.#e.someOfType,[e]);makePathType=()=>le(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>V(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>M(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>P(`endpointTags`,y.createObjectLiteralExpression(Array.from(this.tags).map(([e,t])=>y.createPropertyAssignment(T(e),y.createArrayLiteralExpression(_.map(C,t))))),{expose:!0});makeImplementationType=()=>F(this.#e.implementationType,pe({[this.#e.methodParameter]:this.#e.methodType,[this.#e.pathParameter]:v.SyntaxKind.StringKeyword,[this.#e.paramsArgument]:ie(),[this.#e.ctxArgument]:{optional:!0,type:`T`}},B(v.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:v.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>P(this.#e.parseRequestFn,H({[this.#e.requestParameter]:v.SyntaxKind.StringKeyword},y.createAsExpression(W(this.#e.requestParameter,S(`split`))(y.createRegularExpressionLiteral(`/ (.+)/`),C(2)),y.createTupleTypeNode([E(this.#e.methodType),E(this.#e.pathType)]))));makeSubstituteFn=()=>P(this.#e.substituteFn,H({[this.#e.pathParameter]:v.SyntaxKind.StringKeyword,[this.#e.paramsArgument]:ie()},y.createBlock([P(this.#e.restConst,y.createObjectLiteralExpression([y.createSpreadAssignment(w(this.#e.paramsArgument))])),y.createForInStatement(y.createVariableDeclarationList([y.createVariableDeclaration(this.#e.keyParameter)],v.NodeFlags.Const),w(this.#e.paramsArgument),y.createBlock([de(this.#e.pathParameter,W(this.#e.pathParameter,S(`replace`))(k(`:`,[this.#e.keyParameter]),H([],y.createBlock([y.createExpressionStatement(y.createDeleteExpression(y.createElementAccessExpression(w(this.#e.restConst),w(this.#e.keyParameter)))),y.createReturnStatement(y.createElementAccessExpression(w(this.#e.paramsArgument),w(this.#e.keyParameter)))]))))])),y.createReturnStatement(y.createAsExpression(y.createArrayLiteralExpression([w(this.#e.pathParameter),w(this.#e.restConst)]),E(`const`)))])));makePaginationType=()=>{let e=S(`nextCursor`),t=S(`total`),n=S(`limit`),r=S(`offset`),i=y.createTypeLiteralNode([M(e,D([E(v.SyntaxKind.StringKeyword),J(null)]))]),a=y.createTypeLiteralNode([t,n,r].map(e=>M(e,v.SyntaxKind.NumberKeyword)));return F(this.#e.paginationType,D([i,a]))};#t=()=>{let e=w(this.#e.responseConst),t=S(`nextCursor`),n=S(`total`),r=S(`limit`),i=S(`offset`),a=y.createBinaryExpression(C(t),v.SyntaxKind.InKeyword,e),o=y.createReturnStatement(y.createBinaryExpression(y.createPropertyAccessExpression(e,t),v.SyntaxKind.ExclamationEqualsEqualsToken,C(null))),s=y.createBinaryExpression(y.createPropertyAccessExpression(e,i),v.SyntaxKind.PlusToken,y.createPropertyAccessExpression(e,r)),c=y.createReturnStatement(y.createBinaryExpression(s,v.SyntaxKind.LessThanToken,y.createPropertyAccessExpression(e,n)));return L(`hasMore`,[A(e,{type:this.#e.paginationType})],[y.createIfStatement(a,o),c],{returns:E(v.SyntaxKind.BooleanKeyword),isStatic:!0})};#n=()=>L(this.#e.provideMethod,j({[this.#e.requestParameter]:`K`,[this.#e.paramsArgument]:q(this.interfaces.input,`K`),[this.#e.ctxArgument]:{optional:!0,type:`T`}}),[P(ce(this.#e.methodParameter,this.#e.pathParameter),W(this.#e.parseRequestFn)(this.#e.requestParameter)),y.createReturnStatement(W(y.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,y.createSpreadElement(W(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.#e.requestType},returns:B(q(this.interfaces.response,`K`))});makeClientClass=e=>R(e,[se([A(this.#e.implementationArgument,{type:E(this.#e.implementationType,[`T`]),mod:x.protectedReadonly,initId:this.#e.defaultImplementationConst})]),this.#n(),this.#t()],{typeParams:[`T`]});#r=e=>k(`?`,[G(URLSearchParams.name,w(e))]);#i=()=>G(URL.name,k(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),C(this.serverUrl));makeDefaultImplementation=()=>{let e=y.createPropertyAssignment(S(`method`),W(this.#e.methodParameter,S(`toUpperCase`))()),t=y.createPropertyAssignment(S(`headers`),U(this.#e.hasBodyConst,y.createObjectLiteralExpression([y.createPropertyAssignment(C(`Content-Type`),C(c.json))]),this.#e.undefinedValue)),n=y.createPropertyAssignment(S(`body`),U(this.#e.hasBodyConst,W(JSON[Symbol.toStringTag],S(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=P(this.#e.responseConst,y.createAwaitExpression(W(fetch.name)(this.#i(),y.createObjectLiteralExpression([e,t,n])))),i=P(this.#e.hasBodyConst,y.createLogicalNot(W(y.createArrayLiteralExpression([C(`get`),C(`head`),C(`delete`)]),S(`includes`))(this.#e.methodParameter))),a=P(this.#e.searchParamsConst,U(this.#e.hasBodyConst,C(``),this.#r(this.#e.paramsArgument))),o=P(this.#e.contentTypeConst,W(this.#e.responseConst,S(`headers`),S(`get`))(C(`content-type`))),s=y.createIfStatement(y.createPrefixUnaryExpression(v.SyntaxKind.ExclamationToken,w(this.#e.contentTypeConst)),y.createReturnStatement()),l=P(this.#e.isJsonConst,W(this.#e.contentTypeConst,S(`startsWith`))(C(c.json))),u=y.createReturnStatement(W(this.#e.responseConst,U(this.#e.isJsonConst,C(S(`json`)),C(S(`text`))))());return P(this.#e.defaultImplementationConst,H([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],y.createBlock([i,a,r,o,s,l,u]),{isAsync:!0}),{type:this.#e.implementationType})};#a=()=>se(j({request:`K`,params:q(this.interfaces.input,`K`)}),[P(ce(this.#e.pathParameter,this.#e.restConst),W(this.#e.substituteFn)(y.createElementAccessExpression(W(this.#e.parseRequestFn)(this.#e.requestParameter),C(1)),this.#e.paramsArgument)),P(this.#e.searchParamsConst,this.#r(this.#e.restConst)),de(y.createPropertyAccessExpression(y.createThis(),this.#e.sourceProp),G(`EventSource`,this.#i()))]);#o=e=>y.createTypeLiteralNode([M(S(`event`),e)]);#s=()=>L(this.#e.onMethod,j({[this.#e.eventParameter]:`E`,[this.#e.handlerParameter]:pe({[this.#e.dataParameter]:q(K(`R`,N(this.#o(`E`))),J(S(`data`)))},fe(v.SyntaxKind.VoidKeyword))}),[y.createExpressionStatement(W(y.createThis(),this.#e.sourceProp,S(`addEventListener`))(this.#e.eventParameter,H([this.#e.msgParameter],W(this.#e.handlerParameter)(W(JSON[Symbol.toStringTag],S(`parse`))(y.createPropertyAccessExpression(y.createParenthesizedExpression(y.createAsExpression(w(this.#e.msgParameter),E(MessageEvent.name))),S(`data`))))))),y.createReturnStatement(y.createThis())],{typeParams:{E:q(`R`,J(S(`event`)))}});makeSubscriptionClass=e=>R(e,[ue(this.#e.sourceProp,`EventSource`),this.#a(),this.#s()],{typeParams:{K:K(this.#e.requestType,y.createTemplateLiteralType(y.createTemplateHead(`get `),[y.createTemplateLiteralTypeSpan(E(v.SyntaxKind.StringKeyword),y.createTemplateTail(``))])),R:K(q(this.interfaces.positive,`K`),N(this.#o(v.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[P(this.#e.clientConst,G(e)),W(this.#e.clientConst,this.#e.provideMethod)(C(`get /v1/user/retrieve`),y.createObjectLiteralExpression([y.createPropertyAssignment(`id`,C(`10`))])),W(G(t,C(`get /v1/events/stream`),y.createObjectLiteralExpression()),this.#e.onMethod)(C(`time`),H([`time`],y.createBlock([])))]};const he=(e,{rules:t,onMissing:n,ctx:r={}})=>{let i=o(e),a=i&&i in t?t[i]:t[e._zod.def.type],s=e=>he(e,{ctx:r,rules:t,onMissing:n});return a?a(e,{...r,next:s}):n(e,r)},Y={name:_.path([`name`,`text`]),type:_.path([`type`]),optional:_.path([`questionToken`])},ge=({_zod:{def:e}})=>{let t=e.values.map(e=>e===void 0?E(v.SyntaxKind.UndefinedKeyword):J(e));return t.length===1?t[0]:D(t)},_e=({_zod:{def:e}},{next:n})=>{let{parts:r}=e,i=0,a=()=>{let e=``;for(;i<r.length;){let n=r[i];if(t(n))break;i++,e+=n??``}return e},o=y.createTemplateHead(a()),s=[];for(;i<r.length;){let e=n(r[i++]),t=a(),o=i<r.length?y.createTemplateMiddle:y.createTemplateTail;s.push(y.createTemplateLiteralTypeSpan(e,o(t)))}return s.length?y.createTemplateLiteralType(o,s):J(o.text)},ve=(e,{isResponse:t,next:n,makeAlias:r})=>{let i=()=>{let r=Object.entries(e._zod.def.shape).map(([e,r])=>{let{description:i,deprecated:a}=h.get(r)||{},o=(t?r._zod.optout:r._zod.optin)===`optional`,s=o&&!(r instanceof g.core.$ZodExactOptional);return M(e,n(r),{comment:i,isDeprecated:a,isOptional:o,hasUndefined:s})});return y.createTypeLiteralNode(r)};return d(e,{io:t?`output`:`input`})?r(e,i):i()},ye=({_zod:{def:e}},{next:t})=>y.createArrayTypeNode(t(e.element)),be=({_zod:{def:e}})=>D(_.map(J,Object.values(e.entries))),xe=({_zod:{def:e}},{next:t})=>D(e.options.map(t)),Se=({_zod:{def:e}},{next:t})=>D([t(e.innerType),J(null)]),Ce=({_zod:{def:e}},{next:t})=>y.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:y.createRestTypeNode(t(e.rest)))),we=({_zod:{def:e}},{next:t})=>{let[n,r]=[e.keyType,e.valueType].map(t),i=E(`Record`,[n,r]);return e.mode===`loose`?y.createIntersectionTypeNode([i,E(`Record`,[`PropertyKey`,r])]):i},Te=_.tryCatch(e=>{if(!e.every(v.isTypeLiteralNode))throw Error(`Not objects`);let t=_.chain(_.prop(`members`),e),n=_.uniqWith((...e)=>{if(!_.eqBy(Y.name,...e))return!1;if(_.both(_.eqBy(Y.type),_.eqBy(Y.optional))(...e))return!0;throw Error(`Has conflicting prop`)},t);return y.createTypeLiteralNode(n)},(e,t)=>y.createIntersectionTypeNode(t)),Ee=({_zod:{def:e}},{next:t})=>Te([e.left,e.right].map(t)),X=e=>()=>E(e),Z=({_zod:{def:e}},{next:t})=>t(e.innerType),Q=e=>E(e?v.SyntaxKind.UnknownKeyword:v.SyntaxKind.AnyKeyword),De=({_zod:{def:e}},{next:r,isResponse:i})=>{let a=e[i?`out`:`in`],o=e[i?`in`:`out`];if(!t(a,`transform`))return r(a);let s=r(o),c={[v.SyntaxKind.AnyKeyword]:``,[v.SyntaxKind.BigIntKeyword]:BigInt(0),[v.SyntaxKind.BooleanKeyword]:!1,[v.SyntaxKind.NumberKeyword]:0,[v.SyntaxKind.ObjectKeyword]:{},[v.SyntaxKind.StringKeyword]:``,[v.SyntaxKind.UndefinedKeyword]:void 0}[s.kind],l=n(a,c),u={number:v.SyntaxKind.NumberKeyword,bigint:v.SyntaxKind.BigIntKeyword,boolean:v.SyntaxKind.BooleanKeyword,string:v.SyntaxKind.StringKeyword,undefined:v.SyntaxKind.UndefinedKeyword,object:v.SyntaxKind.ObjectKeyword};return E(l&&u[l]||Q(i))},Oe=()=>J(null),ke=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),Ae=()=>E(`Buffer`),je=(e,{next:t})=>t(e._zod.def.shape.raw),Me={string:X(v.SyntaxKind.StringKeyword),number:X(v.SyntaxKind.NumberKeyword),bigint:X(v.SyntaxKind.BigIntKeyword),boolean:X(v.SyntaxKind.BooleanKeyword),any:X(v.SyntaxKind.AnyKeyword),undefined:X(v.SyntaxKind.UndefinedKeyword),[e]:X(v.SyntaxKind.StringKeyword),[s]:X(v.SyntaxKind.StringKeyword),never:X(v.SyntaxKind.NeverKeyword),void:X(v.SyntaxKind.UndefinedKeyword),unknown:X(v.SyntaxKind.UnknownKeyword),null:Oe,array:ye,tuple:Ce,record:we,object:ve,literal:ge,template_literal:_e,intersection:Ee,union:xe,default:Z,enum:be,optional:Z,nonoptional:Z,nullable:Se,catch:Z,pipe:De,lazy:ke,readonly:Z,[a]:Ae,[u]:je},$=(e,{brandHandling:t,ctx:n})=>he(e,{rules:{...t,...Me},onMissing:({},{isResponse:e})=>Q(e),ctx:n});var Ne=class extends me{#e=[this.makeSomeOfType()];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=J(null);this.#t.set(e,F(n,r)),this.#t.set(e,F(n,t()))}return E(n)}constructor({routing:e,config:t,brandHandling:n,variant:a=`client`,clientClassName:o=`Client`,subscriptionClassName:s=`Subscription`,serverUrl:c=`https://example.com`,noBodySchema:l=g.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this)},m={brandHandling:n,ctx:{...d,isResponse:!1}},h={brandHandling:n,ctx:{...d,isResponse:!0}},v=(e,t,n)=>{let a=i.bind(null,e,t),{isDeprecated:o,inputSchema:s,tags:c}=n,u=`${e} ${t}`,d=F(a(`input`),$(s,m),{comment:u});this.#e.push(d);let f=ee.reduce((t,i)=>{let o=n.getResponses(i),s=_.chain(([t,{schema:n,mimeTypes:o,statusCodes:s}])=>{let c=r(e,o),d=F(a(i,`variant`,`${t+1}`),$(c?n:l,h),{comment:u});return this.#e.push(d),s.map(e=>M(e,d.name))},Array.from(o.entries())),c=V(a(i,`response`,`variants`),s,{comment:u});return this.#e.push(c),Object.assign(t,{[i]:c})},{});this.paths.add(t);let p=J(u),g={input:E(d.name),positive:this.someOf(f.positive),negative:this.someOf(f.negative),response:D([q(this.interfaces.positive,p),q(this.interfaces.negative,p)]),encoded:y.createIntersectionTypeNode([E(f.positive.name),E(f.negative.name)])};this.registry.set(u,{isDeprecated:o,store:g}),this.tags.set(u,c)};p({routing:e,config:t,onEndpoint:u?f(v):v}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.makeMethodType(),...this.makePublicInterfaces(),this.makeRequestType()),a!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makePaginationType(),this.makeDefaultImplementation(),this.makeClientClass(o),this.makeSubscriptionClass(s)),this.#n.push(...this.makeUsageStatements(o,s)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:oe(t,e)).join(`
2
+ `):void 0}print(e){let t=this.#i(e),n=t&&v.addSyntheticLeadingComment(v.addSyntheticLeadingComment(y.createEmptyStatement(),v.SyntaxKind.SingleLineCommentTrivia,` Usage example:`),v.SyntaxKind.MultiLineCommentTrivia,`\n${t}`);return this.#e.concat(n||[]).map((t,n)=>oe(t,n<this.#e.length?e:{...e,omitTrailingSemicolon:!0})).join(`
3
+
4
+ `)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=m(`prettier`).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#i(e);this.#n=r&&n?[await n(r)]:this.#n;let i=this.print(e);return n?n(i):i}};export{Ne as Integration};
@@ -0,0 +1 @@
1
+ import{F as e,U as t}from"./routing-walker-Uax31V_v.js";import*as n from"ramda";const r=e=>e.type===`object`,i=n.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return n.concat(e,t);if(e===t)return t;throw Error(`Can not flatten properties`,{cause:{a:e,b:t}})}),a=new Set([`type`,`properties`,`required`,`examples`,`description`,`additionalProperties`]),o=e=>{for(let t of Object.keys(e))if(!a.has(t))return!1;return!0},s=n.pair(!0),c=(e,t,r)=>!(`allOf`in e)||!e.allOf?[]:e.allOf.map(e=>{if(t===`throw`&&!(e.type===`object`&&o(e)))throw Error(`Can not merge`);return n.pair(r,e)}),l=e=>{let t=[];return e.anyOf&&t.push(...n.map(s,e.anyOf)),e.oneOf&&t.push(...n.map(s,e.oneOf)),t},u=(e,n,r,i)=>{if(!t(e.propertyNames))return;let a=[];typeof e.propertyNames.const==`string`&&a.push(e.propertyNames.const),e.propertyNames.enum&&a.push(...e.propertyNames.enum.filter(e=>typeof e==`string`));let o={...Object(e.additionalProperties)};for(let e of a)n.properties[e]??=o;i||r.push(...a)},d=(r,i,a)=>{i.examples?.length&&(a?r.examples=n.concat(r.examples||[],i.examples):r.examples=e(r.examples?.filter(t)||[],i.examples.filter(t),([e,t])=>n.mergeDeepRight(e,t)))},f=(e,t=`coerce`)=>{let a=[n.pair(!1,e)],o={type:`object`,properties:{}},s=[];for(let[e,f]of a)f.description&&(o.description??=f.description),a.push(...c(f,t,e)),a.push(...l(f)),d(o,f,e),r(f)&&(a.push([e,{examples:p(f)}]),f.properties&&(o.properties=(t===`throw`?i:n.mergeDeepRight)(o.properties,f.properties),!e&&f.required&&s.push(...f.required)),u(f,o,s,e));return s.length&&(o.required=[...new Set(s)]),o},p=r=>Object.entries(r.properties||{}).reduce((r,[i,a])=>{let{examples:o=[]}=t(a)?a:{};return e(r,o.map(n.objOf(i)),([e,t])=>({...e,...t}))},[]);export{f as t};
@@ -0,0 +1 @@
1
+ import{C as e}from"./routing-walker-Uax31V_v.js";import{createRequire as t}from"node:module";let n;const r=(r,i=`default`)=>{try{let e=(n??=t(import.meta.url))(r);return i==="default"?e.default===void 0?e:e.default:e[i]}catch{throw new e(r)}};export{r as t};
@@ -0,0 +1 @@
1
+ import{globalRegistry as e,z as t}from"zod";import*as n from"ramda";import{isPromise as r}from"node:util/types";import i,{isHttpError as a}from"http-errors";import o from"express";const s={json:`application/json`,upload:`multipart/form-data`,raw:`application/octet-stream`,sse:`text/event-stream`,form:`application/x-www-form-urlencoded`},c=[`get`,`post`,`put`,`delete`,`patch`,`query`],l=[...c,`head`],u=e=>c.includes(e),d=t.object({}),f=/:([A-Za-z0-9_]+)/g,ee=e=>e.match(f)?.map(e=>e.slice(1))||[],te=e=>{let t=(e.header(`content-type`)||``).toLowerCase().startsWith(s.upload);return`files`in e&&t},ne={get:[`query`,`params`],post:[`body`,`params`,`files`],put:[`body`,`params`],patch:[`body`,`params`],delete:[`query`,`params`],query:[`query`,`body`,`params`]},p=[`body`,`query`,`params`],m=e=>e.method.toLowerCase(),h=(e,t={})=>{if(e===`options`)return[];let n=e===`head`?`get`:u(e)?e:void 0;return(n?t[n]||ne[n]:void 0)||p},g=(e,t={})=>{let n=m(e);return h(n,t).filter(t=>t!==`files`||te(e)).reduce((t,n)=>Object.assign(t,e[n]),{})},_=e=>e instanceof Error?e:e instanceof t.ZodError?new t.ZodRealError(e.issues):Error(String(e)),v=e=>e instanceof t.ZodError?e.issues.map(({path:e,message:n})=>`${e.length?`${t.core.toDotPath(e)}: `:``}${n}`).join(`; `):e.message,y=(e,t)=>C(e)&&`_zod`in e&&(!t||n.path([`_zod`,`def`,`type`],e)===t),b=(e,t,r)=>e.length&&t.length?n.xprod(e,t).map(r):e.concat(t),x=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),S=(...e)=>{let t=n.chain(e=>e.split(/[^A-Z0-9]/gi),e);return n.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),t).map(x).join(``)},re=n.tryCatch((e,n)=>typeof t.parse(e,n),n.always(void 0)),C=e=>typeof e==`object`&&!!e,w=n.memoizeWith(()=>`static`,()=>process.env.NODE_ENV===`production`),ie=(e,t)=>!!t&&e!==`head`,T=`x-brand`,E=t=>{let{[T]:n}=e.get(t)||{};if(typeof n==`symbol`||typeof n==`string`||typeof n==`number`)return n},D=t=>{let{examples:n}=e.get(t)||{};return Array.isArray(n)?n:[]},O=Symbol(`Buffer`),k=()=>t.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).meta({[T]:O}),A=Symbol(`DateIn`),ae=({examples:e,...n}={})=>t.union([t.iso.date(),t.iso.datetime({local:!0,offset:!0})]).meta({examples:e}).transform(e=>new Date(e)).pipe(t.date()).meta({...n,[T]:A}),j=Symbol(`DateOut`),M=(e={})=>t.date().transform(e=>e.toISOString()).pipe(t.iso.datetime()).meta({...e,[T]:j});var N=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},oe=class extends Error{name=`DocumentationError`;cause;constructor(e,{method:t,path:n,isResponse:r}){super(e),this.cause=`${r?`Response`:`Input`} schema of an Endpoint assigned to ${t.toUpperCase()} method of ${n} path.`}},P=class extends Error{name=`IOSchemaError`},se=class extends P{cause;name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},F=class extends P{cause;name=`OutputValidationError`;constructor(e){let n=new t.ZodError(e.issues.map(({path:e,...t})=>({...t,path:[`output`,...e]})));super(v(n),{cause:e}),this.cause=e}},I=class extends P{cause;name=`InputValidationError`;constructor(e){super(v(e),{cause:e}),this.cause=e}},L=class extends Error{cause;handled;name=`ResultHandlerError`;constructor(e,t){super(v(e),{cause:e}),this.cause=e,this.handled=t}},ce=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const R=Symbol(`Form`),le=e=>(e instanceof t.ZodObject?e:t.object(e)).meta({[T]:R}),z=Symbol(`Upload`),B=e=>C(e)&&`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,V=()=>t.custom(e=>B(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}`})}).meta({[T]:z}),H=Symbol(`Raw`),U=t.object({raw:k()}),W=e=>U.extend(e).meta({[T]:H});function ue(e){return e?W(e):U.meta({[T]:H})}const G=(e,{io:r,condition:i})=>n.tryCatch(()=>void t.toJSONSchema(e,{io:r,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new se(e)}}),e=>e.cause)(),de=(e,{io:r})=>{let i=[t.toJSONSchema(e,{io:r,unrepresentable:`any`})];for(let e=0;e<i.length;e++){let t=i[e];if(n.is(Object,t)){if(t.$ref===`#`)return!0;i.push(...n.values(t))}n.is(Array,t)&&i.push(...n.values(t))}return!1},fe=e=>G(e,{condition:e=>{let t=E(e);return typeof t==`symbol`&&[z,H,R].includes(t)},io:`input`}),pe=[`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`,`function`],me=(e,t)=>G(e,{io:t,condition:e=>{let n=E(e),{type:r}=e._zod.def;return!!(pe.includes(r)||n===O||t===`input`&&(r===`date`||n===j)||t===`output`&&(n===A||n===H||n===z))}});var he=class{},K=class extends he{#e;#t;#n;constructor({input:e,security:t,handler:n}){super(),this.#e=e,this.#t=t,this.#n=n}get security(){return this.#t}get schema(){return this.#e}async execute({input:e,...n}){try{let t=await(this.#e||d).parseAsync(e);return this.#n({...n,input:t})}catch(e){throw e instanceof t.ZodError?new I(e):e}}},q=class extends K{constructor(e,{provider:t=()=>({}),transformer:n=e=>e}={}){super({handler:async({request:i,response:a})=>{let{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=e=>{if(e&&e instanceof Error)return c(n(e));s(t(i,a))},u=e(i,a,l);return r(u)&&u.catch(l),o}})}};const ge=(e,{variant:n,args:r,...i})=>{if(typeof e==`function`&&(e=e(...r)),e instanceof t.ZodType)return[{schema:e,...i}];if(Array.isArray(e)&&!e.length)throw new L(Error(`At least one ${n} response schema required.`));return(Array.isArray(e)?e:[e]).map(({schema:e,statusCode:t,mimeType:n})=>({schema:e,statusCodes:typeof t==`number`?[t]:t||i.statusCodes,mimeTypes:typeof n==`string`?[n]:n===void 0?i.mimeTypes:n}))},_e=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),ve=e=>a(e)?e:i(e instanceof I?400:500,v(e),{cause:e.cause||e}),ye=e=>w()&&!e.expose?i(e.statusCode).message:e.message,be=e=>Object.entries(e._zod.def.shape).reduce((e,[t,r])=>b(e,D(r).map(n.objOf(t)),([e,t])=>({...e,...t})),[]);var J=class{nest(e){return{...e,"":this}}},xe=class r extends J{#e;#t;#n=n.once(()=>{if(D(this.#e.outputSchema).length||!y(this.#e.outputSchema,`object`))return;let t=be(this.#e.outputSchema);if(!t.length)return;let n=this.#e.outputSchema.meta();e.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...n,examples:t})});constructor(e){super(),this.#e=e}#r(e){return new r({...this.#e,...e})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get summary(){return this.#e.summary}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}getProbableRequestType(e){return e===`query`?`form`:this.#t??=(()=>{let e=fe(this.#e.inputSchema);if(e){let t=E(e);if(t===z)return`upload`;if(t===H)return`raw`;if(t===R)return`form`}return`json`})()}getResponses(e){return e===`positive`&&this.#n(),Object.freeze(e===`negative`?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let e=n.pluck(`security`,this.#e.middlewares||[]);return n.reject(n.isNil,e)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(e){return this.#e.getOperationId?.(e)}async#i(e){try{return await this.#e.outputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new F(e):e}}async#a({method:e,logger:t,ctx:n,response:r,...i}){for(let a of this.#e.middlewares||[])if(!(e===`options`&&!(a instanceof q))&&(Object.assign(n,await a.execute({...i,ctx:n,response:r,logger:t})),r.writableEnded)){t.warn(`A middleware has closed the stream. Accumulated context:`,n);break}}async#o({input:e,...n}){let r;try{r=await this.#e.inputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new I(e):e}return this.#e.handler({...n,input:r})}async#s(e){await this.#e.resultHandler.execute(e)}async execute({request:e,response:t,logger:n,config:r}){let i=m(e),a={},o,s=g(e,r.inputSources);try{if(await this.#a({method:i,input:s,request:e,response:t,logger:n,ctx:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();let r=await this.#o({input:s,logger:n,ctx:a});if(t.writableEnded)return;o={output:await this.#i(r),error:null}}catch(e){o={output:null,error:_(e)}}await this.#s({...o,input:s,request:e,response:t,logger:n,ctx:a})}};const Y={positive:200,negative:400},Se=Object.keys(Y);function Ce(e){return e instanceof t.ZodType?{schema:e}:e}var X=class{#e;constructor(...e){this.#e=e}apply(e,t){return t(e,o.static(...this.#e))}};const we=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},Z=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&u(t)?[n,t]:[e]},Te=e=>e.trim().split(`/`).filter(Boolean).join(`/`),Q=({recognizeMethodDependentRoutes:e=!0},t,n)=>Object.entries(t).map(([t,r])=>{let[i,a]=e&&u(t)&&r instanceof J?[`/`,t]:Z(t);return[[n||``].concat(Te(i)||[]).join(`/`),r,a]}),Ee=(e,t)=>{throw new N(`Route with explicit method can only be assigned with Endpoint`,e,t)},De=(e,t,n)=>{if(!(!n||n.includes(e)))throw new N(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},$=(e,t,n)=>{let r=`${e} ${t}`;if(n.has(r))throw new N(`Route has a duplicate`,e,t);n.add(r)},Oe=({routing:e,config:t,onEndpoint:n,onStatic:r})=>{let i=Q(t,e),a=new Set;for(let e=0;e<i.length;e++){let[o,s,c]=i[e];if(s instanceof J)if(c)$(c,o,a),De(c,o,s.methods),n(c,o,s);else{let{methods:e=[`get`]}=s;for(let t of e)$(t,o,a),n(t,o,s)}else c&&Ee(c,o),s instanceof X?r&&s.apply(o,r):i.splice(e+1,0,...Q(t,s,o))}};export{A,v as B,ce as C,M as D,N as E,b as F,y as G,re as H,d as I,ie as J,S as K,_ as L,O as M,E as N,j as O,D as P,s as Q,g as R,I as S,L as T,C as U,ee as V,w as W,l as X,x as Y,u as Z,ue as _,Y as a,le as b,ve as c,ge as d,q as f,H as g,de as h,Ce as i,k as j,ae as k,ye as l,me as m,we as n,Se as o,K as p,f as q,X as r,xe as s,Oe as t,_e as u,z as v,F as w,oe as x,V as y,h as z};