express-zod-api 23.6.0 → 23.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  ## Version 23
4
4
 
5
+ ### v23.6.1
6
+
7
+ - `createServer()` displays a warning when no server is configured.
8
+
5
9
  ### v23.6.0
6
10
 
7
11
  - Featuring `gracefulShutdown.beforeExit()` hook:
package/dist/index.cjs CHANGED
@@ -15,7 +15,7 @@ ${n}888${r}
15
15
  ${o}
16
16
  `;e.write(m.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var Co=e=>{e.startupLogo!==!1&&Io(process.stdout);let t=e.errorHandler||ge,r=Qr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v23.6.0 (CJS)",env:process.env.NODE_ENV||"development"}),zo(r);let o=Ao({logger:r,config:e}),s={getLogger:Eo(r),errorHandler:t},a=Oo(s),c=To(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},jo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Co(e);return ir({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},No=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Co(e),c=(0,tt.default)().disable("x-powered-by").use(a);if(e.compression){let y=await $e("compression");c.use(y(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||tt.default.json()],raw:[e.rawParser||tt.default.raw(),wo],form:[e.formParser||tt.default.urlencoded()],upload:e.upload?await Po({config:e,getLogger:o}):[]};ir({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(y,T)=>()=>y.listen(T,()=>r.info("Listening",T)),h=[];if(e.http){let y=vo.default.createServer(c);p.push(y),h.push(l(y,e.http.listen))}if(e.https){let y=ko.default.createServer(e.https.options,c);p.push(y),h.push(l(y,e.https.listen))}return e.gracefulShutdown&&Zo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:h.map(y=>y())}};var nn=require("openapi3-ts/oas31"),sn=b(require("ramda"),1);var P=b(require("ramda"),1);var Mo=e=>Te(e)&&"or"in e,Lo=e=>Te(e)&&"and"in e,ar=e=>!Lo(e)&&!Mo(e),Uo=e=>{let t=P.filter(ar,e),r=P.chain(P.prop("and"),P.filter(Lo,e)),[o,n]=P.partition(ar,r),s=P.concat(t,o),a=P.filter(Mo,e);return P.map(P.prop("or"),P.concat(a,n)).reduce((m,p)=>Re(m,P.map(l=>ar(l)?[l]:l.and,p),([l,h])=>P.concat(l,h)),P.reject(P.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=b(require("ramda"),1),D=require("zod");var Ze=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ze(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var Ho=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var Do=50,Fo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",qo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},_n=/^\d{4}-\d{2}-\d{2}$/,Vn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Gn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Bo=e=>e.replace($t,t=>`{${t.slice(1)}}`),Jn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Wn=({_def:{innerType:e}},{next:t})=>t(e),Yn=()=>({format:"any"}),Qn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Xn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof D.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},es=({options:e},{next:t})=>({oneOf:e.map(t)}),ts=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),rs=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},$o={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(rs,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>Re(e,t,([r,o])=>d.mergeDeepRight(r,o))},os=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys($o)),d.isEmpty)),ns=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(os);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,$o);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),ss=({_def:{left:e,right:t}},{next:r})=>ns([e,t].map(r)),is=(e,{next:t})=>t(e.unwrap()),as=(e,{next:t})=>t(e.unwrap()),ps=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Vo(r)),r},cs=e=>e in qo,_o=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":cs(t)?t:void 0},Ko=e=>({type:_o(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ds=({value:e})=>({type:_o(e),const:e}),ms=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof D.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=At(e,r)),s.length&&(a.required=s),a},ls=()=>({type:"null"}),us=({},e)=>{if(e.isResponse)throw new B("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Fo}}},fs=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Fo}}},ys=({},e)=>{throw new B(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},gs=()=>({type:"boolean"}),hs=()=>({type:"integer",format:"bigint"}),bs=e=>e.every(t=>t instanceof D.z.ZodLiteral),xs=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof D.z.ZodEnum||e instanceof D.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=At(D.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof D.z.ZodLiteral)return{type:"object",properties:At(D.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof D.z.ZodUnion&&bs(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:At(D.z.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},Ss=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},Rs=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Ts=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:h,isDate:y,isTime:T,isBase64:S,isNANOID:w,isBase64url:R,isDuration:F,_def:{checks:j}})=>{let O=j.find(C=>C.kind==="regex"),v=j.find(C=>C.kind==="datetime"),q=j.some(C=>C.kind==="jwt"),L=j.find(C=>C.kind==="length"),A={type:"string"},V={"date-time":l,byte:S,base64url:R,date:y,time:T,duration:F,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:w,jwt:q,ip:m,cidr:h,emoji:p};for(let C in V)if(V[C]){A.format=C;break}return L&&([A.minLength,A.maxLength]=[L.value,L.value]),r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),y&&(A.pattern=_n.source),T&&(A.pattern=Vn.source),l&&(A.pattern=Gn(v?.offset).source),O&&(A.pattern=O.regex.source),A},Os=2**32-1,Ps=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(R=>R.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(R=>R.kind==="max"),h=t===null?e?s?.[1]:a?.[1]:t,y=l?l.inclusive:!0,T=s?s[1]-s[0]<=Os?"int32":"int64":void 0,w={type:e?"integer":"number",format:e?T:"double"};return p?w.minimum=m:w.exclusiveMinimum=m,y?w.maximum=h:w.exclusiveMaximum=h,w},At=({shape:e},t)=>d.map(t,e),ws=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},Vo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",As=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=ut(e,ws(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(D.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Es=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),zs=(e,{next:t})=>t(e.unwrap()),Zs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Is=(e,{next:t})=>t(e.unwrap().shape.raw),Go=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,Jo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Go)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),vs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Go)({schema:e,variant:"original",validate:!0,pullProps:!0}),ks=(e,t)=>t?.includes(e)||e.startsWith("x-")||Ho.includes(e),Wo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let h=J(r),y=mt(e),T=o.includes("query"),S=o.includes("params"),w=o.includes("headers"),R=O=>S&&y.includes(O),F=d.chain(d.filter(O=>O.type==="header"),m??[]).map(({name:O})=>O),j=O=>w&&(c?.(O,t,e)??ks(O,F));return Object.entries(h.shape).reduce((O,[v,q])=>{let L=R(v)?"path":j(v)?"header":T?"query":void 0;if(!L)return O;let A=Ze(q,{rules:{...a,...pr},onEach:cr,onMissing:dr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),V=s==="components"?n(q,A,le(l,v)):A,{_def:C}=q;return O.concat({name:v,in:L,deprecated:C[g]?.isDeprecated,required:!q.isOptional(),description:A.description||l,schema:V,examples:vs(h,v)})},[])},pr={ZodString:Ts,ZodNumber:Ps,ZodBigInt:hs,ZodBoolean:gs,ZodNull:ls,ZodArray:Ss,ZodTuple:Rs,ZodRecord:xs,ZodObject:ms,ZodLiteral:ds,ZodIntersection:ss,ZodUnion:es,ZodAny:Yn,ZodDefault:Jn,ZodEnum:Ko,ZodNativeEnum:Ko,ZodEffects:As,ZodOptional:is,ZodNullable:ps,ZodDiscriminatedUnion:ts,ZodBranded:zs,ZodDate:ys,ZodCatch:Wn,ZodPipeline:Es,ZodLazy:Zs,ZodReadonly:as,[ee]:Xn,[Ne]:Qn,[Ae]:fs,[we]:us,[ue]:Is},cr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof D.z.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[g]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=Vo(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},dr=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Yo=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Yo(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},Qo=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Xo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:h=`${e.toUpperCase()} ${t} ${Gt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:h};let y=Qo(Ze(r,{rules:{...p,...pr},onEach:cr,onMissing:dr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),T={schema:a==="components"?s(r,y,le(h)):y,examples:Jo(r,!0)};return{description:h,content:d.fromPairs(d.xprod(o,[T]))}},Cs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},js=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Ns=({name:e})=>({type:"apiKey",in:"header",name:e}),Ms=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ls=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Us=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),en=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Cs(o):o.type==="input"?js(o,t):o.type==="header"?Ns(o):o.type==="cookie"?Ms(o):o.type==="openid"?Ls(o):Us(o);return e.map(o=>o.map(r))},tn=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),rn=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,h]=Yo(Ze(r,{rules:{...a,...pr},onEach:cr,onMissing:dr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),y=Qo(l),T={schema:s==="components"?n(r,y,le(p)):y,examples:Jo(J(r),!1,c)},S={description:p,content:{[o]:T}};return(h||o===I.raw)&&(S.required=!0),S},on=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),mr=e=>e.length<=Do?e:e.slice(0,Do-1)+"\u2026",Et=e=>e.length?e.slice():void 0;var zt=class extends nn.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||le(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new B(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:h=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let S of typeof s=="string"?[s]:s)this.addServer({url:S});_e({routing:t,onEndpoint:(S,w,R)=>{let F={path:w,method:R,endpoint:S,composition:y,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:j,shortDescription:O,scopes:v,inputSchema:q}=S,L=O?mr(O):h&&j?mr(j):void 0,A=r.inputSources?.[R]||_t[R],V=this.#n(w,R,S.getOperationId(R)),C=Uo(S.security),xe=Wo({...F,inputSources:A,isHeader:p,security:C,schema:q,description:a?.requestParameter?.call(null,{method:R,path:w,operationId:V})}),st={};for(let ie of De){let Se=S.getResponses(ie);for(let{mimeTypes:Ft,schema:at,statusCodes:pt}of Se)for(let qt of pt)st[qt]=Xo({...F,variant:ie,schema:at,mimeTypes:Ft,statusCode:qt,hasMultipleStatusCodes:Se.length>1||pt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:R,path:w,operationId:V,statusCode:qt})})}let Dt=A.includes("body")?rn({...F,paramNames:sn.pluck("name",xe),schema:q,mimeType:I[S.requestType],description:a?.requestBody?.call(null,{method:R,path:w,operationId:V})}):void 0,it=tn(en(C,A),v,ie=>{let Se=this.#s(ie);return this.addSecurityScheme(Se,ie),Se}),Kt={operationId:V,summary:L,description:j,deprecated:S.isDeprecated||void 0,tags:Et(S.tags),parameters:Et(xe),requestBody:Dt,security:Et(it),responses:st};this.addPath(Bo(w),{[R]:Kt})}}),m&&(this.rootDoc.tags=on(m))}};var Zt=require("node-mocks-http");var Hs=e=>(0,Zt.createRequest)({...e,headers:{"content-type":I.json,...e?.headers}}),Ds=e=>(0,Zt.createResponse)(e),Ks=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},an=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Hs(e),s=Ds({req:n,...t});s.req=t?.req||n,n.res=s;let a=Ks(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},pn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=an(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},cn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=ge}}=an(r),m=lt(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:me(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var yn=b(require("ramda"),1),nt=b(require("typescript"),1),gn=require("zod");var un=b(require("ramda"),1),Q=b(require("typescript"),1);var re=b(require("ramda"),1),u=b(require("typescript"),1),i=u.default.factory,It=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Fs=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],rt={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},lr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),ur=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},qs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fr=e=>typeof e=="string"&&qs.test(e)?i.createIdentifier(e):Z(e),vt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),kt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ve=e=>Object.entries(e).map(([t,r])=>kt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),yr=(e,t=[])=>i.createConstructorDeclaration(rt.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&re.map(f,t)):e,gr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ie=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,fr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?lr(s,a.join(" ")):s},hr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),br=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&It,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),xr=(e,t)=>oe(e,i.createUnionTypeNode(re.map(K,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?It:void 0,e,n&&Or(n),t);return o?lr(s,o):s},dn=(e,t)=>i.createPropertyDeclaration(rt.public,e,void 0,f(t),void 0),Sr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(rt.public,void 0,e,void 0,o&&Or(o),t,n,i.createBlock(r)),Rr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(It,e,r&&Or(r),void 0,t),Tr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Ct=e=>f(Promise.name,[e]),jt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?It:void 0,e,void 0,void 0,t);return o?lr(n,o):n},Or=e=>(Array.isArray(e)?e.map(t=>re.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Fs:void 0,void 0,Array.isArray(e)?re.map(kt,e):Ve(e),void 0,void 0,t),E=e=>e,ot=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),z=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ge=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Nt=(e,t)=>f("Extract",[e,t]),Pr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),Y=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),mn=e=>i.createUnionTypeNode([f(e),Ct(e)]),wr=(e,t)=>i.createFunctionTypeNode(void 0,Ve(e),f(t)),Z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),K=e=>i.createLiteralTypeNode(Z(e)),Bs=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],ln=e=>Bs.includes(e.kind);var Mt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=xr("Method",nr);someOfType=oe("SomeOf",Y("T",Tr("T")),{params:["T"]});requestType=oe("Request",Tr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>xr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>jt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ie(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(fr(t),i.createArrayLiteralExpression(un.map(Z,r))))),{expose:!0});makeImplementationType=()=>oe(this.#e.implementationType,wr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:Q.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:gr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Ct(Q.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Q.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:Q.default.SyntaxKind.StringKeyword},i.createAsExpression(z(this.#e.requestParameter,E("split"))(i.createRegularExpressionLiteral("/ (.+)/"),Z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>M(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:Q.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:gr},i.createBlock([M(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],Q.default.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([Pr(this.#e.pathParameter,z(this.#e.pathParameter,E("replace"))(vt(":",[this.#e.keyParameter]),ve([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>Sr(this.#e.provideMethod,Ve({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:Y(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[M(br(this.#e.methodParameter,this.#e.pathParameter),z(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(z(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(z(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Ct(Y(this.interfaces.response,"K"))});makeClientClass=t=>Rr(t,[yr([kt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:rt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>vt("?",[Ge(URLSearchParams.name,t)]);#o=()=>Ge(URL.name,vt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),Z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(E("method"),z(this.#e.methodParameter,E("toUpperCase"))()),r=i.createPropertyAssignment(E("headers"),ot(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(Z("Content-Type"),Z(I.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(E("body"),ot(this.#e.hasBodyConst,z(JSON[Symbol.toStringTag],E("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=M(this.#e.responseConst,i.createAwaitExpression(z(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=M(this.#e.hasBodyConst,i.createLogicalNot(z(i.createArrayLiteralExpression([Z("get"),Z("delete")]),E("includes"))(this.#e.methodParameter))),a=M(this.#e.searchParamsConst,ot(this.#e.hasBodyConst,Z(""),this.#r(this.#e.paramsArgument))),c=M(this.#e.contentTypeConst,z(this.#e.responseConst,E("headers"),E("get"))(Z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Q.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=M(this.#e.isJsonConst,z(this.#e.contentTypeConst,E("startsWith"))(Z(I.json))),l=i.createReturnStatement(z(this.#e.responseConst,ot(this.#e.isJsonConst,Z(E("json")),Z(E("text"))))());return M(this.#e.defaultImplementationConst,ve([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>yr(Ve({request:"K",params:Y(this.interfaces.input,"K")}),[M(br(this.#e.pathParameter,this.#e.restConst),z(this.#e.substituteFn)(i.createElementAccessExpression(z(this.#e.parseRequestFn)(this.#e.requestParameter),Z(1)),this.#e.paramsArgument)),M(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Pr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Ge("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Ie(E("event"),t)]);#i=()=>Sr(this.#e.onMethod,Ve({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:wr({[this.#e.dataParameter.text]:Y(Nt("R",hr(this.#s("E"))),K(E("data")))},mn(Q.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(z(i.createThis(),this.#e.sourceProp,E("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],z(this.#e.handlerParameter)(z(JSON[Symbol.toStringTag],E("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),E("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:Y("R",K(E("event")))}});makeSubscriptionClass=t=>Rr(t,[dn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Nt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Q.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Nt(Y(this.interfaces.positive,"K"),hr(this.#s(Q.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.#e.clientConst,Ge(t)),z(this.#e.clientConst,this.#e.provideMethod)(Z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",Z("10"))])),z(Ge(r,Z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(Z("time"),ve(["time"],i.createBlock([])))]};var k=b(require("ramda"),1),x=b(require("typescript"),1),Lt=require("zod");var{factory:_}=x.default,$s={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Ar={name:k.path(["name","text"]),type:k.path(["type"]),optional:k.path(["questionToken"])},_s=({value:e})=>K(e),Vs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof Lt.z.ZodOptional:a.isOptional();return Ie(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return _.createTypeLiteralNode(n)},Gs=({element:e},{next:t})=>_.createArrayTypeNode(t(e)),Js=({options:e})=>_.createUnionTypeNode(e.map(K)),fn=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(ln(n)?n.kind:n,n)}return _.createUnionTypeNode(Array.from(r.values()))},Ws=e=>$s?.[e.kind],Ys=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ut(e,Ws(o)),s={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Qs=e=>_.createUnionTypeNode(Object.values(e.enum).map(K)),Xs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?_.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},ei=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),K(null)]),ti=({items:e,_def:{rest:t}},{next:r})=>_.createTupleTypeNode(e.map(r).concat(t===null?[]:_.createRestTypeNode(r(t)))),ri=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),oi=k.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=k.chain(k.prop("members"),e),r=k.uniqWith((...o)=>{if(!k.eqBy(Ar.name,...o))return!1;if(k.both(k.eqBy(Ar.type),k.eqBy(Ar.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),ni=({_def:{left:e,right:t}},{next:r})=>oi([e,t].map(r)),si=({_def:e},{next:t})=>t(e.innerType),be=e=>()=>f(e),ii=(e,{next:t})=>t(e.unwrap()),ai=(e,{next:t})=>t(e.unwrap()),pi=({_def:e},{next:t})=>t(e.innerType),ci=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),di=()=>K(null),mi=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),li=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=_.createUnionTypeNode([r,o]);return t instanceof Lt.z.ZodString?r:t instanceof Lt.z.ZodUnion?n:o},ui=(e,{next:t})=>t(e.unwrap().shape.raw),fi={ZodString:be(x.default.SyntaxKind.StringKeyword),ZodNumber:be(x.default.SyntaxKind.NumberKeyword),ZodBigInt:be(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:be(x.default.SyntaxKind.BooleanKeyword),ZodAny:be(x.default.SyntaxKind.AnyKeyword),ZodUndefined:be(x.default.SyntaxKind.UndefinedKeyword),[we]:be(x.default.SyntaxKind.StringKeyword),[Ae]:be(x.default.SyntaxKind.StringKeyword),ZodNull:di,ZodArray:Gs,ZodTuple:ti,ZodRecord:ri,ZodObject:Vs,ZodLiteral:_s,ZodIntersection:ni,ZodUnion:fn,ZodDefault:si,ZodEnum:Js,ZodNativeEnum:Qs,ZodEffects:Ys,ZodOptional:Xs,ZodNullable:ei,ZodDiscriminatedUnion:fn,ZodBranded:ii,ZodCatch:pi,ZodPipeline:ci,ZodLazy:mi,ZodReadonly:ai,[ee]:li,[ue]:ui},Er=(e,{brandHandling:t,ctx:r})=>Ze(e,{rules:{...t,...fi},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Ut=class extends Mt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=K(null);this.#t.set(t,oe(o,n)),this.#t.set(t,oe(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=gn.z.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},h={brandHandling:r,ctx:{...p,isResponse:!0}};_e({routing:t,onEndpoint:(T,S,w)=>{let R=le.bind(null,w,S),{isDeprecated:F,inputSchema:j,tags:O}=T,v=`${w} ${S}`,q=oe(R("input"),Er(j,l),{comment:v});this.#e.push(q);let L=De.reduce((C,xe)=>{let st=T.getResponses(xe),Dt=yn.chain(([Kt,{schema:ie,mimeTypes:Se,statusCodes:Ft}])=>{let at=oe(R(xe,"variant",`${Kt+1}`),Er(Se?ie:m,h),{comment:v});return this.#e.push(at),Ft.map(pt=>Ie(pt,at.name))},Array.from(st.entries())),it=jt(R(xe,"response","variants"),Dt,{comment:v});return this.#e.push(it),Object.assign(C,{[xe]:it})},{});this.paths.add(S);let A=K(v),V={input:f(q.name),positive:this.someOf(L.positive),negative:this.someOf(L.negative),response:i.createUnionTypeNode([Y(this.interfaces.positive,A),Y(this.interfaces.negative,A)]),encoded:i.createIntersectionTypeNode([f(L.positive.name),f(L.negative.name)])};this.registry.set(v,{isDeprecated:F,store:V}),this.tags.set(v,O)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:ur(r,t)).join(`
18
+ `))};var Co=e=>{e.startupLogo!==!1&&Io(process.stdout);let t=e.errorHandler||ge,r=Qr(e.logger)?e.logger:new Fe(e.logger);r.debug("Running",{build:"v23.6.1 (CJS)",env:process.env.NODE_ENV||"development"}),zo(r);let o=Ao({logger:r,config:e}),s={getLogger:Eo(r),errorHandler:t},a=Oo(s),c=To(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},jo=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=Co(e);return ir({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},No=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=Co(e),c=(0,tt.default)().disable("x-powered-by").use(a);if(e.compression){let y=await $e("compression");c.use(y(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||tt.default.json()],raw:[e.rawParser||tt.default.raw(),wo],form:[e.formParser||tt.default.urlencoded()],upload:e.upload?await Po({config:e,getLogger:o}):[]};ir({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(y,T)=>()=>y.listen(T,()=>r.info("Listening",T)),h=[];if(e.http){let y=vo.default.createServer(c);p.push(y),h.push(l(y,e.http.listen))}if(e.https){let y=ko.default.createServer(e.https.options,c);p.push(y),h.push(l(y,e.https.listen))}return p.length||r.warn("No servers configured."),e.gracefulShutdown&&Zo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:h.map(y=>y())}};var nn=require("openapi3-ts/oas31"),sn=b(require("ramda"),1);var P=b(require("ramda"),1);var Mo=e=>Te(e)&&"or"in e,Lo=e=>Te(e)&&"and"in e,ar=e=>!Lo(e)&&!Mo(e),Uo=e=>{let t=P.filter(ar,e),r=P.chain(P.prop("and"),P.filter(Lo,e)),[o,n]=P.partition(ar,r),s=P.concat(t,o),a=P.filter(Mo,e);return P.map(P.prop("or"),P.concat(a,n)).reduce((m,p)=>Re(m,P.map(l=>ar(l)?[l]:l.and,p),([l,h])=>P.concat(l,h)),P.reject(P.isEmpty,[s]))};var se=require("openapi3-ts/oas31"),d=b(require("ramda"),1),D=require("zod");var Ze=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Ze(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var Ho=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var Do=50,Fo="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",qo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},_n=/^\d{4}-\d{2}-\d{2}$/,Vn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Gn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Bo=e=>e.replace($t,t=>`{${t.slice(1)}}`),Jn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Wn=({_def:{innerType:e}},{next:t})=>t(e),Yn=()=>({format:"any"}),Qn=({},e)=>{if(e.isResponse)throw new B("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Xn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof D.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},es=({options:e},{next:t})=>({oneOf:e.map(t)}),ts=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),rs=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},$o={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(rs,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>Re(e,t,([r,o])=>d.mergeDeepRight(r,o))},os=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys($o)),d.isEmpty)),ns=d.tryCatch(e=>{let[t,r]=e.filter(se.isSchemaObject).filter(os);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,$o);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),ss=({_def:{left:e,right:t}},{next:r})=>ns([e,t].map(r)),is=(e,{next:t})=>t(e.unwrap()),as=(e,{next:t})=>t(e.unwrap()),ps=(e,{next:t})=>{let r=t(e.unwrap());return(0,se.isSchemaObject)(r)&&(r.type=Vo(r)),r},cs=e=>e in qo,_o=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":cs(t)?t:void 0},Ko=e=>({type:_o(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ds=({value:e})=>({type:_o(e),const:e}),ms=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof D.z.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=At(e,r)),s.length&&(a.required=s),a},ls=()=>({type:"null"}),us=({},e)=>{if(e.isResponse)throw new B("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Fo}}},fs=({},e)=>{if(!e.isResponse)throw new B("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Fo}}},ys=({},e)=>{throw new B(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},gs=()=>({type:"boolean"}),hs=()=>({type:"integer",format:"bigint"}),bs=e=>e.every(t=>t instanceof D.z.ZodLiteral),xs=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof D.z.ZodEnum||e instanceof D.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=At(D.z.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof D.z.ZodLiteral)return{type:"object",properties:At(D.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof D.z.ZodUnion&&bs(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:At(D.z.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},Ss=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},Rs=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Ts=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:h,isDate:y,isTime:T,isBase64:S,isNANOID:w,isBase64url:R,isDuration:F,_def:{checks:j}})=>{let O=j.find(C=>C.kind==="regex"),v=j.find(C=>C.kind==="datetime"),q=j.some(C=>C.kind==="jwt"),L=j.find(C=>C.kind==="length"),A={type:"string"},V={"date-time":l,byte:S,base64url:R,date:y,time:T,duration:F,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:w,jwt:q,ip:m,cidr:h,emoji:p};for(let C in V)if(V[C]){A.format=C;break}return L&&([A.minLength,A.maxLength]=[L.value,L.value]),r!==null&&(A.minLength=r),o!==null&&(A.maxLength=o),y&&(A.pattern=_n.source),T&&(A.pattern=Vn.source),l&&(A.pattern=Gn(v?.offset).source),O&&(A.pattern=O.regex.source),A},Os=2**32-1,Ps=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(R=>R.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(R=>R.kind==="max"),h=t===null?e?s?.[1]:a?.[1]:t,y=l?l.inclusive:!0,T=s?s[1]-s[0]<=Os?"int32":"int64":void 0,w={type:e?"integer":"number",format:e?T:"double"};return p?w.minimum=m:w.exclusiveMinimum=m,y?w.maximum=h:w.exclusiveMaximum=h,w},At=({shape:e},t)=>d.map(t,e),ws=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return qo?.[t]},Vo=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",As=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,se.isSchemaObject)(o)){let s=ut(e,ws(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(D.z.any())}if(!t&&n.type==="preprocess"&&(0,se.isSchemaObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Es=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),zs=(e,{next:t})=>t(e.unwrap()),Zs=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Is=(e,{next:t})=>t(e.unwrap().shape.raw),Go=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,Jo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Go)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),vs=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Go)({schema:e,variant:"original",validate:!0,pullProps:!0}),ks=(e,t)=>t?.includes(e)||e.startsWith("x-")||Ho.includes(e),Wo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let h=J(r),y=mt(e),T=o.includes("query"),S=o.includes("params"),w=o.includes("headers"),R=O=>S&&y.includes(O),F=d.chain(d.filter(O=>O.type==="header"),m??[]).map(({name:O})=>O),j=O=>w&&(c?.(O,t,e)??ks(O,F));return Object.entries(h.shape).reduce((O,[v,q])=>{let L=R(v)?"path":j(v)?"header":T?"query":void 0;if(!L)return O;let A=Ze(q,{rules:{...a,...pr},onEach:cr,onMissing:dr,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),V=s==="components"?n(q,A,le(l,v)):A,{_def:C}=q;return O.concat({name:v,in:L,deprecated:C[g]?.isDeprecated,required:!q.isOptional(),description:A.description||l,schema:V,examples:vs(h,v)})},[])},pr={ZodString:Ts,ZodNumber:Ps,ZodBigInt:hs,ZodBoolean:gs,ZodNull:ls,ZodArray:Ss,ZodTuple:Rs,ZodRecord:xs,ZodObject:ms,ZodLiteral:ds,ZodIntersection:ss,ZodUnion:es,ZodAny:Yn,ZodDefault:Jn,ZodEnum:Ko,ZodNativeEnum:Ko,ZodEffects:As,ZodOptional:is,ZodNullable:ps,ZodDiscriminatedUnion:ts,ZodBranded:zs,ZodDate:ys,ZodCatch:Wn,ZodPipeline:Es,ZodLazy:Zs,ZodReadonly:as,[ee]:Xn,[Ne]:Qn,[Ae]:fs,[we]:us,[ue]:Is},cr=(e,{isResponse:t,prev:r})=>{if((0,se.isReferenceObject)(r))return{};let{description:o,_def:n}=e,s=e instanceof D.z.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[g]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=Vo(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},dr=(e,t)=>{throw new B(`Zod type ${e.constructor.name} is unsupported.`,t)},Yo=(e,t)=>{if((0,se.isReferenceObject)(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Yo(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},Qo=e=>(0,se.isReferenceObject)(e)?e:d.omit(["examples"],e),Xo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:h=`${e.toUpperCase()} ${t} ${Gt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:h};let y=Qo(Ze(r,{rules:{...p,...pr},onEach:cr,onMissing:dr,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),T={schema:a==="components"?s(r,y,le(h)):y,examples:Jo(r,!0)};return{description:h,content:d.fromPairs(d.xprod(o,[T]))}},Cs=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},js=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Ns=({name:e})=>({type:"apiKey",in:"header",name:e}),Ms=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Ls=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Us=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),en=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Cs(o):o.type==="input"?js(o,t):o.type==="header"?Ns(o):o.type==="cookie"?Ms(o):o.type==="openid"?Ls(o):Us(o);return e.map(o=>o.map(r))},tn=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),rn=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,h]=Yo(Ze(r,{rules:{...a,...pr},onEach:cr,onMissing:dr,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),y=Qo(l),T={schema:s==="components"?n(r,y,le(p)):y,examples:Jo(J(r),!1,c)},S={description:p,content:{[o]:T}};return(h||o===I.raw)&&(S.required=!0),S},on=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),mr=e=>e.length<=Do?e:e.slice(0,Do-1)+"\u2026",Et=e=>e.length?e.slice():void 0;var zt=class extends nn.OpenApiBuilder{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||le(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new B(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:h=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let S of typeof s=="string"?[s]:s)this.addServer({url:S});_e({routing:t,onEndpoint:(S,w,R)=>{let F={path:w,method:R,endpoint:S,composition:y,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:j,shortDescription:O,scopes:v,inputSchema:q}=S,L=O?mr(O):h&&j?mr(j):void 0,A=r.inputSources?.[R]||_t[R],V=this.#n(w,R,S.getOperationId(R)),C=Uo(S.security),xe=Wo({...F,inputSources:A,isHeader:p,security:C,schema:q,description:a?.requestParameter?.call(null,{method:R,path:w,operationId:V})}),st={};for(let ie of De){let Se=S.getResponses(ie);for(let{mimeTypes:Ft,schema:at,statusCodes:pt}of Se)for(let qt of pt)st[qt]=Xo({...F,variant:ie,schema:at,mimeTypes:Ft,statusCode:qt,hasMultipleStatusCodes:Se.length>1||pt.length>1,description:a?.[`${ie}Response`]?.call(null,{method:R,path:w,operationId:V,statusCode:qt})})}let Dt=A.includes("body")?rn({...F,paramNames:sn.pluck("name",xe),schema:q,mimeType:I[S.requestType],description:a?.requestBody?.call(null,{method:R,path:w,operationId:V})}):void 0,it=tn(en(C,A),v,ie=>{let Se=this.#s(ie);return this.addSecurityScheme(Se,ie),Se}),Kt={operationId:V,summary:L,description:j,deprecated:S.isDeprecated||void 0,tags:Et(S.tags),parameters:Et(xe),requestBody:Dt,security:Et(it),responses:st};this.addPath(Bo(w),{[R]:Kt})}}),m&&(this.rootDoc.tags=on(m))}};var Zt=require("node-mocks-http");var Hs=e=>(0,Zt.createRequest)({...e,headers:{"content-type":I.json,...e?.headers}}),Ds=e=>(0,Zt.createResponse)(e),Ks=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Xr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},an=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Hs(e),s=Ds({req:n,...t});s.req=t?.req||n,n.res=s;let a=Ks(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},pn=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=an(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},cn=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=ge}}=an(r),m=lt(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:me(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};var yn=b(require("ramda"),1),nt=b(require("typescript"),1),gn=require("zod");var un=b(require("ramda"),1),Q=b(require("typescript"),1);var re=b(require("ramda"),1),u=b(require("typescript"),1),i=u.default.factory,It=[i.createModifier(u.default.SyntaxKind.ExportKeyword)],Fs=[i.createModifier(u.default.SyntaxKind.AsyncKeyword)],rt={public:[i.createModifier(u.default.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.default.SyntaxKind.ProtectedKeyword),i.createModifier(u.default.SyntaxKind.ReadonlyKeyword)]},lr=(e,t)=>u.default.addSyntheticLeadingComment(e,u.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),ur=(e,t)=>{let r=u.default.createSourceFile("print.ts","",u.default.ScriptTarget.Latest,!1,u.default.ScriptKind.TS);return u.default.createPrinter(t).printNode(u.default.EmitHint.Unspecified,e,r)},qs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,fr=e=>typeof e=="string"&&qs.test(e)?i.createIdentifier(e):Z(e),vt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),kt=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Ve=e=>Object.entries(e).map(([t,r])=>kt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),yr=(e,t=[])=>i.createConstructorDeclaration(rt.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.default.isIdentifier(e)?i.createTypeReferenceNode(e,t&&re.map(f,t)):e,gr=f("Record",[u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.AnyKeyword]),Ie=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,fr(e),r?i.createToken(u.default.SyntaxKind.QuestionToken):void 0,f(t)),a=re.reject(re.isNil,[o?"@deprecated":void 0,n]);return a.length?lr(s,a.join(" ")):s},hr=e=>u.default.setEmitFlags(e,u.default.EmitFlags.SingleLine),br=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),M=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&It,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.default.NodeFlags.Const)),xr=(e,t)=>oe(e,i.createUnionTypeNode(re.map(K,t)),{expose:!0}),oe=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?It:void 0,e,n&&Or(n),t);return o?lr(s,o):s},dn=(e,t)=>i.createPropertyDeclaration(rt.public,e,void 0,f(t),void 0),Sr=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(rt.public,void 0,e,void 0,o&&Or(o),t,n,i.createBlock(r)),Rr=(e,t,{typeParams:r}={})=>i.createClassDeclaration(It,e,r&&Or(r),void 0,t),Tr=e=>i.createTypeOperatorNode(u.default.SyntaxKind.KeyOfKeyword,f(e)),Ct=e=>f(Promise.name,[e]),jt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?It:void 0,e,void 0,void 0,t);return o?lr(n,o):n},Or=e=>(Array.isArray(e)?e.map(t=>re.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),ve=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Fs:void 0,void 0,Array.isArray(e)?re.map(kt,e):Ve(e),void 0,void 0,t),E=e=>e,ot=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.default.SyntaxKind.QuestionToken),t,i.createToken(u.default.SyntaxKind.ColonToken),r),z=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.default.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ge=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),Nt=(e,t)=>f("Extract",[e,t]),Pr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.default.SyntaxKind.EqualsToken),t)),Y=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),mn=e=>i.createUnionTypeNode([f(e),Ct(e)]),wr=(e,t)=>i.createFunctionTypeNode(void 0,Ve(e),f(t)),Z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),K=e=>i.createLiteralTypeNode(Z(e)),Bs=[u.default.SyntaxKind.AnyKeyword,u.default.SyntaxKind.BigIntKeyword,u.default.SyntaxKind.BooleanKeyword,u.default.SyntaxKind.NeverKeyword,u.default.SyntaxKind.NumberKeyword,u.default.SyntaxKind.ObjectKeyword,u.default.SyntaxKind.StringKeyword,u.default.SyntaxKind.SymbolKeyword,u.default.SyntaxKind.UndefinedKeyword,u.default.SyntaxKind.UnknownKeyword,u.default.SyntaxKind.VoidKeyword],ln=e=>Bs.includes(e.kind);var Mt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=xr("Method",nr);someOfType=oe("SomeOf",Y("T",Tr("T")),{params:["T"]});requestType=oe("Request",Tr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>xr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>jt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Ie(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>M("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(fr(t),i.createArrayLiteralExpression(un.map(Z,r))))),{expose:!0});makeImplementationType=()=>oe(this.#e.implementationType,wr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:Q.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:gr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Ct(Q.default.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:Q.default.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>M(this.#e.parseRequestFn,ve({[this.#e.requestParameter.text]:Q.default.SyntaxKind.StringKeyword},i.createAsExpression(z(this.#e.requestParameter,E("split"))(i.createRegularExpressionLiteral("/ (.+)/"),Z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>M(this.#e.substituteFn,ve({[this.#e.pathParameter.text]:Q.default.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:gr},i.createBlock([M(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],Q.default.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([Pr(this.#e.pathParameter,z(this.#e.pathParameter,E("replace"))(vt(":",[this.#e.keyParameter]),ve([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>Sr(this.#e.provideMethod,Ve({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:Y(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[M(br(this.#e.methodParameter,this.#e.pathParameter),z(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(z(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(z(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Ct(Y(this.interfaces.response,"K"))});makeClientClass=t=>Rr(t,[yr([kt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:rt.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>vt("?",[Ge(URLSearchParams.name,t)]);#o=()=>Ge(URL.name,vt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),Z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(E("method"),z(this.#e.methodParameter,E("toUpperCase"))()),r=i.createPropertyAssignment(E("headers"),ot(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(Z("Content-Type"),Z(I.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(E("body"),ot(this.#e.hasBodyConst,z(JSON[Symbol.toStringTag],E("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=M(this.#e.responseConst,i.createAwaitExpression(z(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=M(this.#e.hasBodyConst,i.createLogicalNot(z(i.createArrayLiteralExpression([Z("get"),Z("delete")]),E("includes"))(this.#e.methodParameter))),a=M(this.#e.searchParamsConst,ot(this.#e.hasBodyConst,Z(""),this.#r(this.#e.paramsArgument))),c=M(this.#e.contentTypeConst,z(this.#e.responseConst,E("headers"),E("get"))(Z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(Q.default.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=M(this.#e.isJsonConst,z(this.#e.contentTypeConst,E("startsWith"))(Z(I.json))),l=i.createReturnStatement(z(this.#e.responseConst,ot(this.#e.isJsonConst,Z(E("json")),Z(E("text"))))());return M(this.#e.defaultImplementationConst,ve([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>yr(Ve({request:"K",params:Y(this.interfaces.input,"K")}),[M(br(this.#e.pathParameter,this.#e.restConst),z(this.#e.substituteFn)(i.createElementAccessExpression(z(this.#e.parseRequestFn)(this.#e.requestParameter),Z(1)),this.#e.paramsArgument)),M(this.#e.searchParamsConst,this.#r(this.#e.restConst)),Pr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Ge("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Ie(E("event"),t)]);#i=()=>Sr(this.#e.onMethod,Ve({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:wr({[this.#e.dataParameter.text]:Y(Nt("R",hr(this.#s("E"))),K(E("data")))},mn(Q.default.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(z(i.createThis(),this.#e.sourceProp,E("addEventListener"))(this.#e.eventParameter,ve([this.#e.msgParameter],z(this.#e.handlerParameter)(z(JSON[Symbol.toStringTag],E("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),E("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:Y("R",K(E("event")))}});makeSubscriptionClass=t=>Rr(t,[dn(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Nt(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(Q.default.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:Nt(Y(this.interfaces.positive,"K"),hr(this.#s(Q.default.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[M(this.#e.clientConst,Ge(t)),z(this.#e.clientConst,this.#e.provideMethod)(Z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",Z("10"))])),z(Ge(r,Z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(Z("time"),ve(["time"],i.createBlock([])))]};var k=b(require("ramda"),1),x=b(require("typescript"),1),Lt=require("zod");var{factory:_}=x.default,$s={[x.default.SyntaxKind.AnyKeyword]:"",[x.default.SyntaxKind.BigIntKeyword]:BigInt(0),[x.default.SyntaxKind.BooleanKeyword]:!1,[x.default.SyntaxKind.NumberKeyword]:0,[x.default.SyntaxKind.ObjectKeyword]:{},[x.default.SyntaxKind.StringKeyword]:"",[x.default.SyntaxKind.UndefinedKeyword]:void 0},Ar={name:k.path(["name","text"]),type:k.path(["type"]),optional:k.path(["questionToken"])},_s=({value:e})=>K(e),Vs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof Lt.z.ZodOptional:a.isOptional();return Ie(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return _.createTypeLiteralNode(n)},Gs=({element:e},{next:t})=>_.createArrayTypeNode(t(e)),Js=({options:e})=>_.createUnionTypeNode(e.map(K)),fn=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(ln(n)?n.kind:n,n)}return _.createUnionTypeNode(Array.from(r.values()))},Ws=e=>$s?.[e.kind],Ys=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=ut(e,Ws(o)),s={number:x.default.SyntaxKind.NumberKeyword,bigint:x.default.SyntaxKind.BigIntKeyword,boolean:x.default.SyntaxKind.BooleanKeyword,string:x.default.SyntaxKind.StringKeyword,undefined:x.default.SyntaxKind.UndefinedKeyword,object:x.default.SyntaxKind.ObjectKeyword};return f(n&&s[n]||x.default.SyntaxKind.AnyKeyword)}return o},Qs=e=>_.createUnionTypeNode(Object.values(e.enum).map(K)),Xs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?_.createUnionTypeNode([o,f(x.default.SyntaxKind.UndefinedKeyword)]):o},ei=(e,{next:t})=>_.createUnionTypeNode([t(e.unwrap()),K(null)]),ti=({items:e,_def:{rest:t}},{next:r})=>_.createTupleTypeNode(e.map(r).concat(t===null?[]:_.createRestTypeNode(r(t)))),ri=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),oi=k.tryCatch(e=>{if(!e.every(x.default.isTypeLiteralNode))throw new Error("Not objects");let t=k.chain(k.prop("members"),e),r=k.uniqWith((...o)=>{if(!k.eqBy(Ar.name,...o))return!1;if(k.both(k.eqBy(Ar.type),k.eqBy(Ar.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return _.createTypeLiteralNode(r)},(e,t)=>_.createIntersectionTypeNode(t)),ni=({_def:{left:e,right:t}},{next:r})=>oi([e,t].map(r)),si=({_def:e},{next:t})=>t(e.innerType),be=e=>()=>f(e),ii=(e,{next:t})=>t(e.unwrap()),ai=(e,{next:t})=>t(e.unwrap()),pi=({_def:e},{next:t})=>t(e.innerType),ci=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),di=()=>K(null),mi=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),li=e=>{let t=e.unwrap(),r=f(x.default.SyntaxKind.StringKeyword),o=f("Buffer"),n=_.createUnionTypeNode([r,o]);return t instanceof Lt.z.ZodString?r:t instanceof Lt.z.ZodUnion?n:o},ui=(e,{next:t})=>t(e.unwrap().shape.raw),fi={ZodString:be(x.default.SyntaxKind.StringKeyword),ZodNumber:be(x.default.SyntaxKind.NumberKeyword),ZodBigInt:be(x.default.SyntaxKind.BigIntKeyword),ZodBoolean:be(x.default.SyntaxKind.BooleanKeyword),ZodAny:be(x.default.SyntaxKind.AnyKeyword),ZodUndefined:be(x.default.SyntaxKind.UndefinedKeyword),[we]:be(x.default.SyntaxKind.StringKeyword),[Ae]:be(x.default.SyntaxKind.StringKeyword),ZodNull:di,ZodArray:Gs,ZodTuple:ti,ZodRecord:ri,ZodObject:Vs,ZodLiteral:_s,ZodIntersection:ni,ZodUnion:fn,ZodDefault:si,ZodEnum:Js,ZodNativeEnum:Qs,ZodEffects:Ys,ZodOptional:Xs,ZodNullable:ei,ZodDiscriminatedUnion:fn,ZodBranded:ii,ZodCatch:pi,ZodPipeline:ci,ZodLazy:mi,ZodReadonly:ai,[ee]:li,[ue]:ui},Er=(e,{brandHandling:t,ctx:r})=>Ze(e,{rules:{...t,...fi},onMissing:()=>f(x.default.SyntaxKind.AnyKeyword),ctx:r});var Ut=class extends Mt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=K(null);this.#t.set(t,oe(o,n)),this.#t.set(t,oe(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=gn.z.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},h={brandHandling:r,ctx:{...p,isResponse:!0}};_e({routing:t,onEndpoint:(T,S,w)=>{let R=le.bind(null,w,S),{isDeprecated:F,inputSchema:j,tags:O}=T,v=`${w} ${S}`,q=oe(R("input"),Er(j,l),{comment:v});this.#e.push(q);let L=De.reduce((C,xe)=>{let st=T.getResponses(xe),Dt=yn.chain(([Kt,{schema:ie,mimeTypes:Se,statusCodes:Ft}])=>{let at=oe(R(xe,"variant",`${Kt+1}`),Er(Se?ie:m,h),{comment:v});return this.#e.push(at),Ft.map(pt=>Ie(pt,at.name))},Array.from(st.entries())),it=jt(R(xe,"response","variants"),Dt,{comment:v});return this.#e.push(it),Object.assign(C,{[xe]:it})},{});this.paths.add(S);let A=K(v),V={input:f(q.name),positive:this.someOf(L.positive),negative:this.someOf(L.negative),response:i.createUnionTypeNode([Y(this.interfaces.positive,A),Y(this.interfaces.negative,A)]),encoded:i.createIntersectionTypeNode([f(L.positive.name),f(L.negative.name)])};this.registry.set(v,{isDeprecated:F,store:V}),this.tags.set(v,O)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:ur(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&nt.default.addSyntheticLeadingComment(nt.default.addSyntheticLeadingComment(i.createEmptyStatement(),nt.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),nt.default.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>ur(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
package/dist/index.d.cts CHANGED
@@ -232,7 +232,6 @@ declare const base: z.ZodObject<{
232
232
  }, {
233
233
  raw: Buffer<ArrayBufferLike>;
234
234
  }>;
235
- /** Shorthand for z.object({ raw: ez.file("buffer") }) */
236
235
  declare function raw(): z.ZodBranded<typeof base, symbol>;
237
236
  declare function raw<S extends z.ZodRawShape>(extra: S): z.ZodBranded<ReturnType<typeof base.extend<S>>, symbol>;
238
237
  type RawSchema = ReturnType<typeof raw>;
package/dist/index.d.ts CHANGED
@@ -232,7 +232,6 @@ declare const base: z.ZodObject<{
232
232
  }, {
233
233
  raw: Buffer<ArrayBufferLike>;
234
234
  }>;
235
- /** Shorthand for z.object({ raw: ez.file("buffer") }) */
236
235
  declare function raw(): z.ZodBranded<typeof base, symbol>;
237
236
  declare function raw<S extends z.ZodRawShape>(extra: S): z.ZodBranded<ReturnType<typeof base.extend<S>>, symbol>;
238
237
  type RawSchema = ReturnType<typeof raw>;
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ ${n}888${r}
15
15
  ${o}
16
16
  `;e.write(m.split(`
17
17
  `).map((p,l)=>c[l]?c[l](p):p).join(`
18
- `))};var fo=e=>{e.startupLogo!==!1&&uo(process.stdout);let t=e.errorHandler||Re,r=Hr(e.logger)?e.logger:new _e(e.logger);r.debug("Running",{build:"v23.6.0 (ESM)",env:process.env.NODE_ENV||"development"}),co(r);let o=ao({logger:r,config:e}),s={getLogger:po(r),errorHandler:t},a=no(s),c=oo(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Ln=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=fo(e);return Bt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Un=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=fo(e),c=ht().disable("x-powered-by").use(a);if(e.compression){let y=await Ne("compression");c.use(y(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||ht.json()],raw:[e.rawParser||ht.raw(),io],form:[e.formParser||ht.urlencoded()],upload:e.upload?await so({config:e,getLogger:o}):[]};Bt({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(y,R)=>()=>y.listen(R,()=>r.info("Listening",R)),h=[];if(e.http){let y=Nn.createServer(c);p.push(y),h.push(l(y,e.http.listen))}if(e.https){let y=Mn.createServer(e.https.options,c);p.push(y),h.push(l(y,e.https.listen))}return e.gracefulShutdown&&mo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:h.map(y=>y())}};import{OpenApiBuilder as Cs}from"openapi3-ts/oas31";import*as Lo from"ramda";import*as O from"ramda";var yo=e=>fe(e)&&"or"in e,go=e=>fe(e)&&"and"in e,$t=e=>!go(e)&&!yo(e),ho=e=>{let t=O.filter($t,e),r=O.chain(O.prop("and"),O.filter(go,e)),[o,n]=O.partition($t,r),s=O.concat(t,o),a=O.filter(yo,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>ue(m,O.map(l=>$t(l)?[l]:l.and,p),([l,h])=>O.concat(l,h)),O.reject(O.isEmpty,[s]))};import{isReferenceObject as _t,isSchemaObject as xt}from"openapi3-ts/oas31";import*as d from"ramda";import{z as F}from"zod";var Oe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Oe(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var bo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var xo=50,Ro="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",To={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Dn=/^\d{4}-\d{2}-\d{2}$/,Kn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Fn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Oo=e=>e.replace(Ct,t=>`{${t.slice(1)}}`),qn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Bn=({_def:{innerType:e}},{next:t})=>t(e),$n=()=>({format:"any"}),_n=({},e)=>{if(e.isResponse)throw new $("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Vn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof F.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Gn=({options:e},{next:t})=>({oneOf:e.map(t)}),Jn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Wn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Po={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Wn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>ue(e,t,([r,o])=>d.mergeDeepRight(r,o))},Yn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Po)),d.isEmpty)),Qn=d.tryCatch(e=>{let[t,r]=e.filter(xt).filter(Yn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Po);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Xn=({_def:{left:e,right:t}},{next:r})=>Qn([e,t].map(r)),es=(e,{next:t})=>t(e.unwrap()),ts=(e,{next:t})=>t(e.unwrap()),rs=(e,{next:t})=>{let r=t(e.unwrap());return xt(r)&&(r.type=Ao(r)),r},os=e=>e in To,wo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":os(t)?t:void 0},So=e=>({type:wo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ns=({value:e})=>({type:wo(e),const:e}),ss=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof F.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=bt(e,r)),s.length&&(a.required=s),a},is=()=>({type:"null"}),as=({},e)=>{if(e.isResponse)throw new $("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ro}}},ps=({},e)=>{if(!e.isResponse)throw new $("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ro}}},cs=({},e)=>{throw new $(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},ds=()=>({type:"boolean"}),ms=()=>({type:"integer",format:"bigint"}),ls=e=>e.every(t=>t instanceof F.ZodLiteral),us=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof F.ZodEnum||e instanceof F.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=bt(F.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof F.ZodLiteral)return{type:"object",properties:bt(F.object({[e.value]:t}),r),required:[e.value]};if(e instanceof F.ZodUnion&&ls(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:bt(F.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},fs=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},ys=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),gs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:h,isDate:y,isTime:R,isBase64:x,isNANOID:P,isBase64url:S,isDuration:D,_def:{checks:C}})=>{let T=C.find(k=>k.kind==="regex"),I=C.find(k=>k.kind==="datetime"),K=C.some(k=>k.kind==="jwt"),M=C.find(k=>k.kind==="length"),w={type:"string"},B={"date-time":l,byte:x,base64url:S,date:y,time:R,duration:D,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:P,jwt:K,ip:m,cidr:h,emoji:p};for(let k in B)if(B[k]){w.format=k;break}return M&&([w.minLength,w.maxLength]=[M.value,M.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),y&&(w.pattern=Dn.source),R&&(w.pattern=Kn.source),l&&(w.pattern=Fn(I?.offset).source),T&&(w.pattern=T.regex.source),w},hs=2**32-1,bs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(S=>S.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(S=>S.kind==="max"),h=t===null?e?s?.[1]:a?.[1]:t,y=l?l.inclusive:!0,R=s?s[1]-s[0]<=hs?"int32":"int64":void 0,P={type:e?"integer":"number",format:e?R:"double"};return p?P.minimum=m:P.exclusiveMinimum=m,y?P.maximum=h:P.exclusiveMaximum=h,P},bt=({shape:e},t)=>d.map(t,e),xs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},Ao=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Ss=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&xt(o)){let s=nt(e,xs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(F.any())}if(!t&&n.type==="preprocess"&&xt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Rs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Ts=(e,{next:t})=>t(e.unwrap()),Os=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ps=(e,{next:t})=>t(e.unwrap().shape.raw),Eo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,zo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Eo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ws=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Eo)({schema:e,variant:"original",validate:!0,pullProps:!0}),As=(e,t)=>t?.includes(e)||e.startsWith("x-")||bo.includes(e),Zo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let h=_(r),y=rt(e),R=o.includes("query"),x=o.includes("params"),P=o.includes("headers"),S=T=>x&&y.includes(T),D=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),C=T=>P&&(c?.(T,t,e)??As(T,D));return Object.entries(h.shape).reduce((T,[I,K])=>{let M=S(I)?"path":C(I)?"header":R?"query":void 0;if(!M)return T;let w=Oe(K,{rules:{...a,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),B=s==="components"?n(K,w,se(l,I)):w,{_def:k}=K;return T.concat({name:I,in:M,deprecated:k[g]?.isDeprecated,required:!K.isOptional(),description:w.description||l,schema:B,examples:ws(h,I)})},[])},Vt={ZodString:gs,ZodNumber:bs,ZodBigInt:ms,ZodBoolean:ds,ZodNull:is,ZodArray:fs,ZodTuple:ys,ZodRecord:us,ZodObject:ss,ZodLiteral:ns,ZodIntersection:Xn,ZodUnion:Gn,ZodAny:$n,ZodDefault:qn,ZodEnum:So,ZodNativeEnum:So,ZodEffects:Ss,ZodOptional:es,ZodNullable:rs,ZodDiscriminatedUnion:Jn,ZodBranded:Ts,ZodDate:cs,ZodCatch:Bn,ZodPipeline:Rs,ZodLazy:Os,ZodReadonly:ts,[G]:Vn,[Ee]:_n,[he]:ps,[ge]:as,[ie]:Ps},Gt=(e,{isResponse:t,prev:r})=>{if(_t(r))return{};let{description:o,_def:n}=e,s=e instanceof F.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[g]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=Ao(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},Jt=(e,t)=>{throw new $(`Zod type ${e.constructor.name} is unsupported.`,t)},Io=(e,t)=>{if(_t(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Io(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},vo=e=>_t(e)?e:d.omit(["examples"],e),ko=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:h=`${e.toUpperCase()} ${t} ${Mt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:h};let y=vo(Oe(r,{rules:{...p,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,y,se(h)):y,examples:zo(r,!0)};return{description:h,content:d.fromPairs(d.xprod(o,[R]))}},Es=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},zs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Zs=({name:e})=>({type:"apiKey",in:"header",name:e}),Is=({name:e})=>({type:"apiKey",in:"cookie",name:e}),vs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ks=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Co=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Es(o):o.type==="input"?zs(o,t):o.type==="header"?Zs(o):o.type==="cookie"?Is(o):o.type==="openid"?vs(o):ks(o);return e.map(o=>o.map(r))},jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),No=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,h]=Io(Oe(r,{rules:{...a,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),y=vo(l),R={schema:s==="components"?n(r,y,se(p)):y,examples:zo(_(r),!1,c)},x={description:p,content:{[o]:R}};return(h||o===Z.raw)&&(x.required=!0),x},Mo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Wt=e=>e.length<=xo?e:e.slice(0,xo-1)+"\u2026",St=e=>e.length?e.slice():void 0;var Yt=class extends Cs{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||se(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new $(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:h=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let x of typeof s=="string"?[s]:s)this.addServer({url:x});Me({routing:t,onEndpoint:(x,P,S)=>{let D={path:P,method:S,endpoint:x,composition:y,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:C,shortDescription:T,scopes:I,inputSchema:K}=x,M=T?Wt(T):h&&C?Wt(C):void 0,w=r.inputSources?.[S]||jt[S],B=this.#n(P,S,x.getOperationId(S)),k=ho(x.security),pe=Zo({...D,inputSources:w,isHeader:p,security:k,schema:K,description:a?.requestParameter?.call(null,{method:S,path:P,operationId:B})}),Ye={};for(let te of Ce){let ce=x.getResponses(te);for(let{mimeTypes:vt,schema:Xe,statusCodes:et}of ce)for(let kt of et)Ye[kt]=ko({...D,variant:te,schema:Xe,mimeTypes:vt,statusCode:kt,hasMultipleStatusCodes:ce.length>1||et.length>1,description:a?.[`${te}Response`]?.call(null,{method:S,path:P,operationId:B,statusCode:kt})})}let Zt=w.includes("body")?No({...D,paramNames:Lo.pluck("name",pe),schema:K,mimeType:Z[x.requestType],description:a?.requestBody?.call(null,{method:S,path:P,operationId:B})}):void 0,Qe=jo(Co(k,w),I,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),It={operationId:B,summary:M,description:C,deprecated:x.isDeprecated||void 0,tags:St(x.tags),parameters:St(pe),requestBody:Zt,security:St(Qe),responses:Ye};this.addPath(Oo(P),{[S]:It})}}),m&&(this.rootDoc.tags=Mo(m))}};import{createRequest as js,createResponse as Ns}from"node-mocks-http";var Ms=e=>js({...e,headers:{"content-type":Z.json,...e?.headers}}),Ls=e=>Ns(e),Us=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Uo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ms(e),s=Ls({req:n,...t});s.req=t?.req||n,n.res=s;let a=Us(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Hs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Uo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Ds=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Re}}=Uo(r),m=ot(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Bo from"ramda";import zt from"typescript";import{z as fi}from"zod";import*as Fo from"ramda";import X from"typescript";import*as Y from"ramda";import u from"typescript";var i=u.factory,Rt=[i.createModifier(u.SyntaxKind.ExportKeyword)],Ks=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Je={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Qt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Xt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},Fs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,er=e=>typeof e=="string"&&Fs.test(e)?i.createIdentifier(e):z(e),Tt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Ot=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Le=e=>Object.entries(e).map(([t,r])=>Ot(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),tr=(e,t=[])=>i.createConstructorDeclaration(Je.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,rr=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Pe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,er(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Qt(s,a.join(" ")):s},or=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),nr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Rt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),sr=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(H,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Rt:void 0,e,n&&cr(n),t);return o?Qt(s,o):s},Ho=(e,t)=>i.createPropertyDeclaration(Je.public,e,void 0,f(t),void 0),ir=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Je.public,void 0,e,void 0,o&&cr(o),t,n,i.createBlock(r)),ar=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Rt,e,r&&cr(r),void 0,t),pr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Pt=e=>f(Promise.name,[e]),wt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Rt:void 0,e,void 0,void 0,t);return o?Qt(n,o):n},cr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),we=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Ks:void 0,void 0,Array.isArray(e)?Y.map(Ot,e):Le(e),void 0,void 0,t),A=e=>e,We=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ue=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),At=(e,t)=>f("Extract",[e,t]),dr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),V=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Do=e=>i.createUnionTypeNode([f(e),Pt(e)]),mr=(e,t)=>i.createFunctionTypeNode(void 0,Le(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),H=e=>i.createLiteralTypeNode(z(e)),qs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Ko=e=>qs.includes(e.kind);var Et=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=sr("Method",Ft);someOfType=Q("SomeOf",V("T",pr("T")),{params:["T"]});requestType=Q("Request",pr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>wt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Pe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(er(t),i.createArrayLiteralExpression(Fo.map(z,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,mr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Pt(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,we({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,we({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([dr(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(Tt(":",[this.#e.keyParameter]),we([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ir(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:V(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(nr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Pt(V(this.interfaces.response,"K"))});makeClientClass=t=>ar(t,[tr([Ot(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Je.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Tt("?",[Ue(URLSearchParams.name,t)]);#o=()=>Ue(URL.name,Tt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),We(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(Z.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),We(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,We(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(Z.json))),l=i.createReturnStatement(E(this.#e.responseConst,We(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return j(this.#e.defaultImplementationConst,we([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>tr(Le({request:"K",params:V(this.interfaces.input,"K")}),[j(nr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),dr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Ue("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Pe(A("event"),t)]);#i=()=>ir(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:mr({[this.#e.dataParameter.text]:V(At("R",or(this.#s("E"))),H(A("data")))},Do(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,we([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:V("R",H(A("event")))}});makeSubscriptionClass=t=>ar(t,[Ho(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:At(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:At(V(this.interfaces.positive,"K"),or(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,Ue(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Ue(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),we(["time"],i.createBlock([])))]};import*as v from"ramda";import b from"typescript";import{z as ur}from"zod";var{factory:q}=b,Bs={[b.SyntaxKind.AnyKeyword]:"",[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:"",[b.SyntaxKind.UndefinedKeyword]:void 0},lr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},$s=({value:e})=>H(e),_s=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof ur.ZodOptional:a.isOptional();return Pe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return q.createTypeLiteralNode(n)},Vs=({element:e},{next:t})=>q.createArrayTypeNode(t(e)),Gs=({options:e})=>q.createUnionTypeNode(e.map(H)),qo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Ko(n)?n.kind:n,n)}return q.createUnionTypeNode(Array.from(r.values()))},Js=e=>Bs?.[e.kind],Ws=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=nt(e,Js(o)),s={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return f(n&&s[n]||b.SyntaxKind.AnyKeyword)}return o},Ys=e=>q.createUnionTypeNode(Object.values(e.enum).map(H)),Qs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?q.createUnionTypeNode([o,f(b.SyntaxKind.UndefinedKeyword)]):o},Xs=(e,{next:t})=>q.createUnionTypeNode([t(e.unwrap()),H(null)]),ei=({items:e,_def:{rest:t}},{next:r})=>q.createTupleTypeNode(e.map(r).concat(t===null?[]:q.createRestTypeNode(r(t)))),ti=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),ri=v.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(lr.name,...o))return!1;if(v.both(v.eqBy(lr.type),v.eqBy(lr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return q.createTypeLiteralNode(r)},(e,t)=>q.createIntersectionTypeNode(t)),oi=({_def:{left:e,right:t}},{next:r})=>ri([e,t].map(r)),ni=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),si=(e,{next:t})=>t(e.unwrap()),ii=(e,{next:t})=>t(e.unwrap()),ai=({_def:e},{next:t})=>t(e.innerType),pi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ci=()=>H(null),di=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),mi=e=>{let t=e.unwrap(),r=f(b.SyntaxKind.StringKeyword),o=f("Buffer"),n=q.createUnionTypeNode([r,o]);return t instanceof ur.ZodString?r:t instanceof ur.ZodUnion?n:o},li=(e,{next:t})=>t(e.unwrap().shape.raw),ui={ZodString:ae(b.SyntaxKind.StringKeyword),ZodNumber:ae(b.SyntaxKind.NumberKeyword),ZodBigInt:ae(b.SyntaxKind.BigIntKeyword),ZodBoolean:ae(b.SyntaxKind.BooleanKeyword),ZodAny:ae(b.SyntaxKind.AnyKeyword),ZodUndefined:ae(b.SyntaxKind.UndefinedKeyword),[ge]:ae(b.SyntaxKind.StringKeyword),[he]:ae(b.SyntaxKind.StringKeyword),ZodNull:ci,ZodArray:Vs,ZodTuple:ei,ZodRecord:ti,ZodObject:_s,ZodLiteral:$s,ZodIntersection:oi,ZodUnion:qo,ZodDefault:ni,ZodEnum:Gs,ZodNativeEnum:Ys,ZodEffects:Ws,ZodOptional:Qs,ZodNullable:Xs,ZodDiscriminatedUnion:qo,ZodBranded:si,ZodCatch:ai,ZodPipeline:pi,ZodLazy:di,ZodReadonly:ii,[G]:mi,[ie]:li},fr=(e,{brandHandling:t,ctx:r})=>Oe(e,{rules:{...t,...ui},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var yr=class extends Et{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=H(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=fi.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},h={brandHandling:r,ctx:{...p,isResponse:!0}};Me({routing:t,onEndpoint:(R,x,P)=>{let S=se.bind(null,P,x),{isDeprecated:D,inputSchema:C,tags:T}=R,I=`${P} ${x}`,K=Q(S("input"),fr(C,l),{comment:I});this.#e.push(K);let M=Ce.reduce((k,pe)=>{let Ye=R.getResponses(pe),Zt=Bo.chain(([It,{schema:te,mimeTypes:ce,statusCodes:vt}])=>{let Xe=Q(S(pe,"variant",`${It+1}`),fr(ce?te:m,h),{comment:I});return this.#e.push(Xe),vt.map(et=>Pe(et,Xe.name))},Array.from(Ye.entries())),Qe=wt(S(pe,"response","variants"),Zt,{comment:I});return this.#e.push(Qe),Object.assign(k,{[pe]:Qe})},{});this.paths.add(x);let w=H(I),B={input:f(K.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:i.createUnionTypeNode([V(this.interfaces.positive,w),V(this.interfaces.negative,w)]),encoded:i.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(I,{isDeprecated:D,store:B}),this.tags.set(I,T)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Xt(r,t)).join(`
18
+ `))};var fo=e=>{e.startupLogo!==!1&&uo(process.stdout);let t=e.errorHandler||Re,r=Hr(e.logger)?e.logger:new _e(e.logger);r.debug("Running",{build:"v23.6.1 (ESM)",env:process.env.NODE_ENV||"development"}),co(r);let o=ao({logger:r,config:e}),s={getLogger:po(r),errorHandler:t},a=no(s),c=oo(s);return{...s,logger:r,notFoundHandler:a,catcher:c,loggingMiddleware:o}},Ln=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=fo(e);return Bt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Un=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:a}=fo(e),c=ht().disable("x-powered-by").use(a);if(e.compression){let y=await Ne("compression");c.use(y(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:c,getLogger:o});let m={json:[e.jsonParser||ht.json()],raw:[e.rawParser||ht.raw(),io],form:[e.formParser||ht.urlencoded()],upload:e.upload?await so({config:e,getLogger:o}):[]};Bt({app:c,routing:t,getLogger:o,config:e,parsers:m}),c.use(s,n);let p=[],l=(y,R)=>()=>y.listen(R,()=>r.info("Listening",R)),h=[];if(e.http){let y=Nn.createServer(c);p.push(y),h.push(l(y,e.http.listen))}if(e.https){let y=Mn.createServer(e.https.options,c);p.push(y),h.push(l(y,e.https.listen))}return p.length||r.warn("No servers configured."),e.gracefulShutdown&&mo({logger:r,servers:p,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:c,logger:r,servers:h.map(y=>y())}};import{OpenApiBuilder as Cs}from"openapi3-ts/oas31";import*as Lo from"ramda";import*as O from"ramda";var yo=e=>fe(e)&&"or"in e,go=e=>fe(e)&&"and"in e,$t=e=>!go(e)&&!yo(e),ho=e=>{let t=O.filter($t,e),r=O.chain(O.prop("and"),O.filter(go,e)),[o,n]=O.partition($t,r),s=O.concat(t,o),a=O.filter(yo,e);return O.map(O.prop("or"),O.concat(a,n)).reduce((m,p)=>ue(m,O.map(l=>$t(l)?[l]:l.and,p),([l,h])=>O.concat(l,h)),O.reject(O.isEmpty,[s]))};import{isReferenceObject as _t,isSchemaObject as xt}from"openapi3-ts/oas31";import*as d from"ramda";import{z as F}from"zod";var Oe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=r[e._def[g]?.brand]||"typeName"in e._def&&r[e._def.typeName],c=s?s(e,{...n,next:p=>Oe(p,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),m=t&&t(e,{prev:c,...n});return m?{...c,...m}:c};var bo=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var xo=50,Ro="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",To={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Dn=/^\d{4}-\d{2}-\d{2}$/,Kn=/^\d{2}:\d{2}:\d{2}(\.\d+)?$/,Fn=e=>e?/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(([+-]\d{2}:\d{2})|Z)$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,Oo=e=>e.replace(Ct,t=>`{${t.slice(1)}}`),qn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Bn=({_def:{innerType:e}},{next:t})=>t(e),$n=()=>({format:"any"}),_n=({},e)=>{if(e.isResponse)throw new $("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Vn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof F.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Gn=({options:e},{next:t})=>({oneOf:e.map(t)}),Jn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Wn=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return d.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties")},Po={type:d.always("object"),properties:({properties:e={}},{properties:t={}})=>d.mergeDeepWith(Wn,e,t),required:({required:e=[]},{required:t=[]})=>d.union(e,t),examples:({examples:e=[]},{examples:t=[]})=>ue(e,t,([r,o])=>d.mergeDeepRight(r,o))},Yn=d.both(({type:e})=>e==="object",d.pipe(Object.keys,d.without(Object.keys(Po)),d.isEmpty)),Qn=d.tryCatch(e=>{let[t,r]=e.filter(xt).filter(Yn);if(!t||!r)throw new Error("Can not flatten objects");let o=d.pickBy((n,s)=>(t[s]||r[s])!==void 0,Po);return d.map(n=>n(t,r),o)},(e,t)=>({allOf:t})),Xn=({_def:{left:e,right:t}},{next:r})=>Qn([e,t].map(r)),es=(e,{next:t})=>t(e.unwrap()),ts=(e,{next:t})=>t(e.unwrap()),rs=(e,{next:t})=>{let r=t(e.unwrap());return xt(r)&&(r.type=Ao(r)),r},os=e=>e in To,wo=e=>{let t=d.toLower(d.type(e));return typeof e=="bigint"?"integer":os(t)?t:void 0},So=e=>({type:wo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),ns=({value:e})=>({type:wo(e),const:e}),ss=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=c=>t?c instanceof F.ZodOptional:c.isOptional(),s=o.filter(c=>!n(e.shape[c])),a={type:"object"};return o.length&&(a.properties=bt(e,r)),s.length&&(a.required=s),a},is=()=>({type:"null"}),as=({},e)=>{if(e.isResponse)throw new $("Please use ez.dateOut() for output.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ro}}},ps=({},e)=>{if(!e.isResponse)throw new $("Please use ez.dateIn() for input.",e);return{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ro}}},cs=({},e)=>{throw new $(`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,e)},ds=()=>({type:"boolean"}),ms=()=>({type:"integer",format:"bigint"}),ls=e=>e.every(t=>t instanceof F.ZodLiteral),us=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof F.ZodEnum||e instanceof F.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=bt(F.object(d.fromPairs(d.xprod(o,[t]))),r),n.required=o),n}if(e instanceof F.ZodLiteral)return{type:"object",properties:bt(F.object({[e.value]:t}),r),required:[e.value]};if(e instanceof F.ZodUnion&&ls(e.options)){let o=d.map(s=>`${s.value}`,e.options),n=d.fromPairs(d.xprod(o,[t]));return{type:"object",properties:bt(F.object(n),r),required:o}}return{type:"object",propertyNames:r(e),additionalProperties:r(t)}},fs=({_def:{minLength:e,maxLength:t,exactLength:r},element:o},{next:n})=>{let s={type:"array",items:n(o)};return r&&([s.minItems,s.maxItems]=Array(2).fill(r.value)),e&&(s.minItems=e.value),t&&(s.maxItems=t.value),s},ys=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),gs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:s,isCUID2:a,isULID:c,isIP:m,isEmoji:p,isDatetime:l,isCIDR:h,isDate:y,isTime:R,isBase64:x,isNANOID:P,isBase64url:S,isDuration:D,_def:{checks:C}})=>{let T=C.find(k=>k.kind==="regex"),I=C.find(k=>k.kind==="datetime"),K=C.some(k=>k.kind==="jwt"),M=C.find(k=>k.kind==="length"),w={type:"string"},B={"date-time":l,byte:x,base64url:S,date:y,time:R,duration:D,email:e,url:t,uuid:n,cuid:s,cuid2:a,ulid:c,nanoid:P,jwt:K,ip:m,cidr:h,emoji:p};for(let k in B)if(B[k]){w.format=k;break}return M&&([w.minLength,w.maxLength]=[M.value,M.value]),r!==null&&(w.minLength=r),o!==null&&(w.maxLength=o),y&&(w.pattern=Dn.source),R&&(w.pattern=Kn.source),l&&(w.pattern=Fn(I?.offset).source),T&&(w.pattern=T.regex.source),w},hs=2**32-1,bs=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}},{numericRange:n={integer:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],float:[-Number.MAX_VALUE,Number.MAX_VALUE]}})=>{let{integer:s,float:a}=n||{integer:null,float:null},c=o.find(S=>S.kind==="min"),m=r===null?e?s?.[0]:a?.[0]:r,p=c?c.inclusive:!0,l=o.find(S=>S.kind==="max"),h=t===null?e?s?.[1]:a?.[1]:t,y=l?l.inclusive:!0,R=s?s[1]-s[0]<=hs?"int32":"int64":void 0,P={type:e?"integer":"number",format:e?R:"double"};return p?P.minimum=m:P.exclusiveMinimum=m,y?P.maximum=h:P.exclusiveMaximum=h,P},bt=({shape:e},t)=>d.map(t,e),xs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return To?.[t]},Ao=({type:e})=>e==="null"?e:typeof e=="string"?[e,"null"]:e?[...new Set(e).add("null")]:"null",Ss=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&xt(o)){let s=nt(e,xs(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(F.any())}if(!t&&n.type==="preprocess"&&xt(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Rs=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Ts=(e,{next:t})=>t(e.unwrap()),Os=(e,{next:t,makeRef:r})=>r(e,()=>t(e.schema)),Ps=(e,{next:t})=>t(e.unwrap().shape.raw),Eo=e=>e.length?d.fromPairs(d.zip(d.times(t=>`example${t+1}`,e.length),d.map(d.objOf("value"),e))):void 0,zo=(e,t,r=[])=>d.pipe(ne,d.map(d.when(o=>d.type(o)==="Object",d.omit(r))),Eo)({schema:e,variant:t?"parsed":"original",validate:!0,pullProps:!0}),ws=(e,t)=>d.pipe(ne,d.filter(d.has(t)),d.pluck(t),Eo)({schema:e,variant:"original",validate:!0,pullProps:!0}),As=(e,t)=>t?.includes(e)||e.startsWith("x-")||bo.includes(e),Zo=({path:e,method:t,schema:r,inputSources:o,makeRef:n,composition:s,brandHandling:a,isHeader:c,security:m,numericRange:p,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let h=_(r),y=rt(e),R=o.includes("query"),x=o.includes("params"),P=o.includes("headers"),S=T=>x&&y.includes(T),D=d.chain(d.filter(T=>T.type==="header"),m??[]).map(({name:T})=>T),C=T=>P&&(c?.(T,t,e)??As(T,D));return Object.entries(h.shape).reduce((T,[I,K])=>{let M=S(I)?"path":C(I)?"header":R?"query":void 0;if(!M)return T;let w=Oe(K,{rules:{...a,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!1,makeRef:n,path:e,method:t,numericRange:p}}),B=s==="components"?n(K,w,se(l,I)):w,{_def:k}=K;return T.concat({name:I,in:M,deprecated:k[g]?.isDeprecated,required:!K.isOptional(),description:w.description||l,schema:B,examples:ws(h,I)})},[])},Vt={ZodString:gs,ZodNumber:bs,ZodBigInt:ms,ZodBoolean:ds,ZodNull:is,ZodArray:fs,ZodTuple:ys,ZodRecord:us,ZodObject:ss,ZodLiteral:ns,ZodIntersection:Xn,ZodUnion:Gn,ZodAny:$n,ZodDefault:qn,ZodEnum:So,ZodNativeEnum:So,ZodEffects:Ss,ZodOptional:es,ZodNullable:rs,ZodDiscriminatedUnion:Jn,ZodBranded:Ts,ZodDate:cs,ZodCatch:Bn,ZodPipeline:Rs,ZodLazy:Os,ZodReadonly:ts,[G]:Vn,[Ee]:_n,[he]:ps,[ge]:as,[ie]:Ps},Gt=(e,{isResponse:t,prev:r})=>{if(_t(r))return{};let{description:o,_def:n}=e,s=e instanceof F.ZodLazy,a=r.type!==void 0,c=!t&&!s&&a&&e.isNullable(),m={};if(o&&(m.description=o),n[g]?.isDeprecated&&(m.deprecated=!0),c&&(m.type=Ao(r)),!s){let p=ne({schema:e,variant:t?"parsed":"original",validate:!0});p.length&&(m.examples=p.slice())}return m},Jt=(e,t)=>{throw new $(`Zod type ${e.constructor.name} is unsupported.`,t)},Io=(e,t)=>{if(_t(e))return[e,!1];let r=!1,o=d.map(c=>{let[m,p]=Io(c,t);return r=r||p,m}),n=d.omit(t),s={properties:n,examples:d.map(n),required:d.without(t),allOf:o,oneOf:o},a=d.evolve(s,e);return[a,r||!!a.required?.length]},vo=e=>_t(e)?e:d.omit(["examples"],e),ko=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:a,hasMultipleStatusCodes:c,statusCode:m,brandHandling:p,numericRange:l,description:h=`${e.toUpperCase()} ${t} ${Mt(n)} response ${c?m:""}`.trim()})=>{if(!o)return{description:h};let y=vo(Oe(r,{rules:{...p,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!0,makeRef:s,path:t,method:e,numericRange:l}})),R={schema:a==="components"?s(r,y,se(h)):y,examples:zo(r,!0)};return{description:h,content:d.fromPairs(d.xprod(o,[R]))}},Es=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},zs=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Zs=({name:e})=>({type:"apiKey",in:"header",name:e}),Is=({name:e})=>({type:"apiKey",in:"cookie",name:e}),vs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ks=({flows:e={}})=>({type:"oauth2",flows:d.map(t=>({...t,scopes:t.scopes||{}}),d.reject(d.isNil,e))}),Co=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?Es(o):o.type==="input"?zs(o,t):o.type==="header"?Zs(o):o.type==="cookie"?Is(o):o.type==="openid"?vs(o):ks(o);return e.map(o=>o.map(r))},jo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let a=r(s),c=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[a]:c?t:[]})},{})),No=({method:e,path:t,schema:r,mimeType:o,makeRef:n,composition:s,brandHandling:a,paramNames:c,numericRange:m,description:p=`${e.toUpperCase()} ${t} Request body`})=>{let[l,h]=Io(Oe(r,{rules:{...a,...Vt},onEach:Gt,onMissing:Jt,ctx:{isResponse:!1,makeRef:n,path:t,method:e,numericRange:m}}),c),y=vo(l),R={schema:s==="components"?n(r,y,se(p)):y,examples:zo(_(r),!1,c)},x={description:p,content:{[o]:R}};return(h||o===Z.raw)&&(x.required=!0),x},Mo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Wt=e=>e.length<=xo?e:e.slice(0,xo-1)+"\u2026",St=e=>e.length?e.slice():void 0;var Yt=class extends Cs{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o),typeof r=="function"&&(r=r())),typeof r=="object"&&this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||se(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new $(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:a,brandHandling:c,tags:m,isHeader:p,numericRange:l,hasSummaryFromDescription:h=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let x of typeof s=="string"?[s]:s)this.addServer({url:x});Me({routing:t,onEndpoint:(x,P,S)=>{let D={path:P,method:S,endpoint:x,composition:y,brandHandling:c,numericRange:l,makeRef:this.#o.bind(this)},{description:C,shortDescription:T,scopes:I,inputSchema:K}=x,M=T?Wt(T):h&&C?Wt(C):void 0,w=r.inputSources?.[S]||jt[S],B=this.#n(P,S,x.getOperationId(S)),k=ho(x.security),pe=Zo({...D,inputSources:w,isHeader:p,security:k,schema:K,description:a?.requestParameter?.call(null,{method:S,path:P,operationId:B})}),Ye={};for(let te of Ce){let ce=x.getResponses(te);for(let{mimeTypes:vt,schema:Xe,statusCodes:et}of ce)for(let kt of et)Ye[kt]=ko({...D,variant:te,schema:Xe,mimeTypes:vt,statusCode:kt,hasMultipleStatusCodes:ce.length>1||et.length>1,description:a?.[`${te}Response`]?.call(null,{method:S,path:P,operationId:B,statusCode:kt})})}let Zt=w.includes("body")?No({...D,paramNames:Lo.pluck("name",pe),schema:K,mimeType:Z[x.requestType],description:a?.requestBody?.call(null,{method:S,path:P,operationId:B})}):void 0,Qe=jo(Co(k,w),I,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),It={operationId:B,summary:M,description:C,deprecated:x.isDeprecated||void 0,tags:St(x.tags),parameters:St(pe),requestBody:Zt,security:St(Qe),responses:Ye};this.addPath(Oo(P),{[S]:It})}}),m&&(this.rootDoc.tags=Mo(m))}};import{createRequest as js,createResponse as Ns}from"node-mocks-http";var Ms=e=>js({...e,headers:{"content-type":Z.json,...e?.headers}}),Ls=e=>Ns(e),Us=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Dr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},Uo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ms(e),s=Ls({req:n,...t});s.req=t?.req||n,n.res=s;let a=Us(o),c={cors:!1,logger:a,...r};return{requestMock:n,responseMock:s,loggerMock:a,configMock:c}},Hs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=Uo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},Ds=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:a,errorHandler:c=Re}}=Uo(r),m=ot(o,a),p={request:o,response:n,logger:s,input:m,options:t};try{let l=await e.execute(p);return{requestMock:o,responseMock:n,loggerMock:s,output:l}}catch(l){return await c.execute({...p,error:oe(l),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Bo from"ramda";import zt from"typescript";import{z as fi}from"zod";import*as Fo from"ramda";import X from"typescript";import*as Y from"ramda";import u from"typescript";var i=u.factory,Rt=[i.createModifier(u.SyntaxKind.ExportKeyword)],Ks=[i.createModifier(u.SyntaxKind.AsyncKeyword)],Je={public:[i.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[i.createModifier(u.SyntaxKind.ProtectedKeyword),i.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Qt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Xt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},Fs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,er=e=>typeof e=="string"&&Fs.test(e)?i.createIdentifier(e):z(e),Tt=(e,...t)=>i.createTemplateExpression(i.createTemplateHead(e),t.map(([r,o=""],n)=>i.createTemplateSpan(r,n===t.length-1?i.createTemplateTail(o):i.createTemplateMiddle(o)))),Ot=(e,{type:t,mod:r,init:o,optional:n}={})=>i.createParameterDeclaration(r,void 0,e,n?i.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Le=e=>Object.entries(e).map(([t,r])=>Ot(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),tr=(e,t=[])=>i.createConstructorDeclaration(Je.public,e,i.createBlock(t)),f=(e,t)=>typeof e=="number"?i.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?i.createTypeReferenceNode(e,t&&Y.map(f,t)):e,rr=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),Pe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=i.createPropertySignature(void 0,er(e),r?i.createToken(u.SyntaxKind.QuestionToken):void 0,f(t)),a=Y.reject(Y.isNil,[o?"@deprecated":void 0,n]);return a.length?Qt(s,a.join(" ")):s},or=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),nr=(...e)=>i.createArrayBindingPattern(e.map(t=>i.createBindingElement(void 0,void 0,t))),j=(e,t,{type:r,expose:o}={})=>i.createVariableStatement(o&&Rt,i.createVariableDeclarationList([i.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),sr=(e,t)=>Q(e,i.createUnionTypeNode(Y.map(H,t)),{expose:!0}),Q=(e,t,{expose:r,comment:o,params:n}={})=>{let s=i.createTypeAliasDeclaration(r?Rt:void 0,e,n&&cr(n),t);return o?Qt(s,o):s},Ho=(e,t)=>i.createPropertyDeclaration(Je.public,e,void 0,f(t),void 0),ir=(e,t,r,{typeParams:o,returns:n}={})=>i.createMethodDeclaration(Je.public,void 0,e,void 0,o&&cr(o),t,n,i.createBlock(r)),ar=(e,t,{typeParams:r}={})=>i.createClassDeclaration(Rt,e,r&&cr(r),void 0,t),pr=e=>i.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),Pt=e=>f(Promise.name,[e]),wt=(e,t,{expose:r,comment:o}={})=>{let n=i.createInterfaceDeclaration(r?Rt:void 0,e,void 0,void 0,t);return o?Qt(n,o):n},cr=e=>(Array.isArray(e)?e.map(t=>Y.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return i.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),we=(e,t,{isAsync:r}={})=>i.createArrowFunction(r?Ks:void 0,void 0,Array.isArray(e)?Y.map(Ot,e):Le(e),void 0,void 0,t),A=e=>e,We=(e,t,r)=>i.createConditionalExpression(e,i.createToken(u.SyntaxKind.QuestionToken),t,i.createToken(u.SyntaxKind.ColonToken),r),E=(e,...t)=>(...r)=>i.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?i.createPropertyAccessExpression(o,n):i.createElementAccessExpression(o,n),typeof e=="string"?i.createIdentifier(e):e),void 0,r),Ue=(e,...t)=>i.createNewExpression(i.createIdentifier(e),void 0,t),At=(e,t)=>f("Extract",[e,t]),dr=(e,t)=>i.createExpressionStatement(i.createBinaryExpression(e,i.createToken(u.SyntaxKind.EqualsToken),t)),V=(e,t)=>i.createIndexedAccessTypeNode(f(e),f(t)),Do=e=>i.createUnionTypeNode([f(e),Pt(e)]),mr=(e,t)=>i.createFunctionTypeNode(void 0,Le(e),f(t)),z=e=>typeof e=="number"?i.createNumericLiteral(e):typeof e=="boolean"?e?i.createTrue():i.createFalse():e===null?i.createNull():i.createStringLiteral(e),H=e=>i.createLiteralTypeNode(z(e)),qs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Ko=e=>qs.includes(e.kind);var Et=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:i.createIdentifier("Path"),implementationType:i.createIdentifier("Implementation"),keyParameter:i.createIdentifier("key"),pathParameter:i.createIdentifier("path"),paramsArgument:i.createIdentifier("params"),ctxArgument:i.createIdentifier("ctx"),methodParameter:i.createIdentifier("method"),requestParameter:i.createIdentifier("request"),eventParameter:i.createIdentifier("event"),dataParameter:i.createIdentifier("data"),handlerParameter:i.createIdentifier("handler"),msgParameter:i.createIdentifier("msg"),parseRequestFn:i.createIdentifier("parseRequest"),substituteFn:i.createIdentifier("substitute"),provideMethod:i.createIdentifier("provide"),onMethod:i.createIdentifier("on"),implementationArgument:i.createIdentifier("implementation"),hasBodyConst:i.createIdentifier("hasBody"),undefinedValue:i.createIdentifier("undefined"),responseConst:i.createIdentifier("response"),restConst:i.createIdentifier("rest"),searchParamsConst:i.createIdentifier("searchParams"),defaultImplementationConst:i.createIdentifier("defaultImplementation"),clientConst:i.createIdentifier("client"),contentTypeConst:i.createIdentifier("contentType"),isJsonConst:i.createIdentifier("isJSON"),sourceProp:i.createIdentifier("source")};interfaces={input:i.createIdentifier("Input"),positive:i.createIdentifier("PositiveResponse"),negative:i.createIdentifier("NegativeResponse"),encoded:i.createIdentifier("EncodedResponse"),response:i.createIdentifier("Response")};methodType=sr("Method",Ft);someOfType=Q("SomeOf",V("T",pr("T")),{params:["T"]});requestType=Q("Request",pr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>wt(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Pe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>j("endpointTags",i.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>i.createPropertyAssignment(er(t),i.createArrayLiteralExpression(Fo.map(z,r))))),{expose:!0});makeImplementationType=()=>Q(this.#e.implementationType,mr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},Pt(X.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:X.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>j(this.#e.parseRequestFn,we({[this.#e.requestParameter.text]:X.SyntaxKind.StringKeyword},i.createAsExpression(E(this.#e.requestParameter,A("split"))(i.createRegularExpressionLiteral("/ (.+)/"),z(2)),i.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>j(this.#e.substituteFn,we({[this.#e.pathParameter.text]:X.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr},i.createBlock([j(this.#e.restConst,i.createObjectLiteralExpression([i.createSpreadAssignment(this.#e.paramsArgument)])),i.createForInStatement(i.createVariableDeclarationList([i.createVariableDeclaration(this.#e.keyParameter)],X.NodeFlags.Const),this.#e.paramsArgument,i.createBlock([dr(this.#e.pathParameter,E(this.#e.pathParameter,A("replace"))(Tt(":",[this.#e.keyParameter]),we([],i.createBlock([i.createExpressionStatement(i.createDeleteExpression(i.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),i.createReturnStatement(i.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),i.createReturnStatement(i.createAsExpression(i.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ir(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:V(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[j(nr(this.#e.methodParameter,this.#e.pathParameter),E(this.#e.parseRequestFn)(this.#e.requestParameter)),i.createReturnStatement(E(i.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,i.createSpreadElement(E(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:Pt(V(this.interfaces.response,"K"))});makeClientClass=t=>ar(t,[tr([Ot(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Je.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Tt("?",[Ue(URLSearchParams.name,t)]);#o=()=>Ue(URL.name,Tt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),z(this.serverUrl));makeDefaultImplementation=()=>{let t=i.createPropertyAssignment(A("method"),E(this.#e.methodParameter,A("toUpperCase"))()),r=i.createPropertyAssignment(A("headers"),We(this.#e.hasBodyConst,i.createObjectLiteralExpression([i.createPropertyAssignment(z("Content-Type"),z(Z.json))]),this.#e.undefinedValue)),o=i.createPropertyAssignment(A("body"),We(this.#e.hasBodyConst,E(JSON[Symbol.toStringTag],A("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=j(this.#e.responseConst,i.createAwaitExpression(E(fetch.name)(this.#o(),i.createObjectLiteralExpression([t,r,o])))),s=j(this.#e.hasBodyConst,i.createLogicalNot(E(i.createArrayLiteralExpression([z("get"),z("delete")]),A("includes"))(this.#e.methodParameter))),a=j(this.#e.searchParamsConst,We(this.#e.hasBodyConst,z(""),this.#r(this.#e.paramsArgument))),c=j(this.#e.contentTypeConst,E(this.#e.responseConst,A("headers"),A("get"))(z("content-type"))),m=i.createIfStatement(i.createPrefixUnaryExpression(X.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),i.createReturnStatement()),p=j(this.#e.isJsonConst,E(this.#e.contentTypeConst,A("startsWith"))(z(Z.json))),l=i.createReturnStatement(E(this.#e.responseConst,We(this.#e.isJsonConst,z(A("json")),z(A("text"))))());return j(this.#e.defaultImplementationConst,we([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],i.createBlock([s,a,n,c,m,p,l]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>tr(Le({request:"K",params:V(this.interfaces.input,"K")}),[j(nr(this.#e.pathParameter,this.#e.restConst),E(this.#e.substituteFn)(i.createElementAccessExpression(E(this.#e.parseRequestFn)(this.#e.requestParameter),z(1)),this.#e.paramsArgument)),j(this.#e.searchParamsConst,this.#r(this.#e.restConst)),dr(i.createPropertyAccessExpression(i.createThis(),this.#e.sourceProp),Ue("EventSource",this.#o()))]);#s=t=>i.createTypeLiteralNode([Pe(A("event"),t)]);#i=()=>ir(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:mr({[this.#e.dataParameter.text]:V(At("R",or(this.#s("E"))),H(A("data")))},Do(X.SyntaxKind.VoidKeyword))}),[i.createExpressionStatement(E(i.createThis(),this.#e.sourceProp,A("addEventListener"))(this.#e.eventParameter,we([this.#e.msgParameter],E(this.#e.handlerParameter)(E(JSON[Symbol.toStringTag],A("parse"))(i.createPropertyAccessExpression(i.createParenthesizedExpression(i.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),A("data"))))))),i.createReturnStatement(i.createThis())],{typeParams:{E:V("R",H(A("event")))}});makeSubscriptionClass=t=>ar(t,[Ho(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:At(this.requestType.name,i.createTemplateLiteralType(i.createTemplateHead("get "),[i.createTemplateLiteralTypeSpan(f(X.SyntaxKind.StringKeyword),i.createTemplateTail(""))])),R:At(V(this.interfaces.positive,"K"),or(this.#s(X.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[j(this.#e.clientConst,Ue(t)),E(this.#e.clientConst,this.#e.provideMethod)(z("get /v1/user/retrieve"),i.createObjectLiteralExpression([i.createPropertyAssignment("id",z("10"))])),E(Ue(r,z("get /v1/events/stream"),i.createObjectLiteralExpression()),this.#e.onMethod)(z("time"),we(["time"],i.createBlock([])))]};import*as v from"ramda";import b from"typescript";import{z as ur}from"zod";var{factory:q}=b,Bs={[b.SyntaxKind.AnyKeyword]:"",[b.SyntaxKind.BigIntKeyword]:BigInt(0),[b.SyntaxKind.BooleanKeyword]:!1,[b.SyntaxKind.NumberKeyword]:0,[b.SyntaxKind.ObjectKeyword]:{},[b.SyntaxKind.StringKeyword]:"",[b.SyntaxKind.UndefinedKeyword]:void 0},lr={name:v.path(["name","text"]),type:v.path(["type"]),optional:v.path(["questionToken"])},$s=({value:e})=>H(e),_s=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([s,a])=>{let{description:c,_def:m}=a,p=t?a instanceof ur.ZodOptional:a.isOptional();return Pe(s,r(a),{comment:c,isOptional:p&&o,isDeprecated:m[g]?.isDeprecated})});return q.createTypeLiteralNode(n)},Vs=({element:e},{next:t})=>q.createArrayTypeNode(t(e)),Gs=({options:e})=>q.createUnionTypeNode(e.map(H)),qo=({options:e},{next:t})=>{let r=new Map;for(let o of e){let n=t(o);r.set(Ko(n)?n.kind:n,n)}return q.createUnionTypeNode(Array.from(r.values()))},Js=e=>Bs?.[e.kind],Ws=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=nt(e,Js(o)),s={number:b.SyntaxKind.NumberKeyword,bigint:b.SyntaxKind.BigIntKeyword,boolean:b.SyntaxKind.BooleanKeyword,string:b.SyntaxKind.StringKeyword,undefined:b.SyntaxKind.UndefinedKeyword,object:b.SyntaxKind.ObjectKeyword};return f(n&&s[n]||b.SyntaxKind.AnyKeyword)}return o},Ys=e=>q.createUnionTypeNode(Object.values(e.enum).map(H)),Qs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?q.createUnionTypeNode([o,f(b.SyntaxKind.UndefinedKeyword)]):o},Xs=(e,{next:t})=>q.createUnionTypeNode([t(e.unwrap()),H(null)]),ei=({items:e,_def:{rest:t}},{next:r})=>q.createTupleTypeNode(e.map(r).concat(t===null?[]:q.createRestTypeNode(r(t)))),ti=({keySchema:e,valueSchema:t},{next:r})=>f("Record",[e,t].map(r)),ri=v.tryCatch(e=>{if(!e.every(b.isTypeLiteralNode))throw new Error("Not objects");let t=v.chain(v.prop("members"),e),r=v.uniqWith((...o)=>{if(!v.eqBy(lr.name,...o))return!1;if(v.both(v.eqBy(lr.type),v.eqBy(lr.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return q.createTypeLiteralNode(r)},(e,t)=>q.createIntersectionTypeNode(t)),oi=({_def:{left:e,right:t}},{next:r})=>ri([e,t].map(r)),ni=({_def:e},{next:t})=>t(e.innerType),ae=e=>()=>f(e),si=(e,{next:t})=>t(e.unwrap()),ii=(e,{next:t})=>t(e.unwrap()),ai=({_def:e},{next:t})=>t(e.innerType),pi=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ci=()=>H(null),di=(e,{makeAlias:t,next:r})=>t(e,()=>r(e.schema)),mi=e=>{let t=e.unwrap(),r=f(b.SyntaxKind.StringKeyword),o=f("Buffer"),n=q.createUnionTypeNode([r,o]);return t instanceof ur.ZodString?r:t instanceof ur.ZodUnion?n:o},li=(e,{next:t})=>t(e.unwrap().shape.raw),ui={ZodString:ae(b.SyntaxKind.StringKeyword),ZodNumber:ae(b.SyntaxKind.NumberKeyword),ZodBigInt:ae(b.SyntaxKind.BigIntKeyword),ZodBoolean:ae(b.SyntaxKind.BooleanKeyword),ZodAny:ae(b.SyntaxKind.AnyKeyword),ZodUndefined:ae(b.SyntaxKind.UndefinedKeyword),[ge]:ae(b.SyntaxKind.StringKeyword),[he]:ae(b.SyntaxKind.StringKeyword),ZodNull:ci,ZodArray:Vs,ZodTuple:ei,ZodRecord:ti,ZodObject:_s,ZodLiteral:$s,ZodIntersection:oi,ZodUnion:qo,ZodDefault:ni,ZodEnum:Gs,ZodNativeEnum:Ys,ZodEffects:Ws,ZodOptional:Qs,ZodNullable:Xs,ZodDiscriminatedUnion:qo,ZodBranded:si,ZodCatch:ai,ZodPipeline:pi,ZodLazy:di,ZodReadonly:ii,[G]:mi,[ie]:li},fr=(e,{brandHandling:t,ctx:r})=>Oe(e,{rules:{...t,...ui},onMissing:()=>f(b.SyntaxKind.AnyKeyword),ctx:r});var yr=class extends Et{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=H(null);this.#t.set(t,Q(o,n)),this.#t.set(t,Q(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:a="https://example.com",optionalPropStyle:c={withQuestionMark:!0,withUndefined:!0},noContent:m=fi.undefined()}){super(a);let p={makeAlias:this.#o.bind(this),optionalPropStyle:c},l={brandHandling:r,ctx:{...p,isResponse:!1}},h={brandHandling:r,ctx:{...p,isResponse:!0}};Me({routing:t,onEndpoint:(R,x,P)=>{let S=se.bind(null,P,x),{isDeprecated:D,inputSchema:C,tags:T}=R,I=`${P} ${x}`,K=Q(S("input"),fr(C,l),{comment:I});this.#e.push(K);let M=Ce.reduce((k,pe)=>{let Ye=R.getResponses(pe),Zt=Bo.chain(([It,{schema:te,mimeTypes:ce,statusCodes:vt}])=>{let Xe=Q(S(pe,"variant",`${It+1}`),fr(ce?te:m,h),{comment:I});return this.#e.push(Xe),vt.map(et=>Pe(et,Xe.name))},Array.from(Ye.entries())),Qe=wt(S(pe,"response","variants"),Zt,{comment:I});return this.#e.push(Qe),Object.assign(k,{[pe]:Qe})},{});this.paths.add(x);let w=H(I),B={input:f(K.name),positive:this.someOf(M.positive),negative:this.someOf(M.negative),response:i.createUnionTypeNode([V(this.interfaces.positive,w),V(this.interfaces.negative,w)]),encoded:i.createIntersectionTypeNode([f(M.positive.name),f(M.negative.name)])};this.registry.set(I,{isDeprecated:D,store:B}),this.tags.set(I,T)}}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Xt(r,t)).join(`
19
19
  `):void 0}print(t){let r=this.#n(t),o=r&&zt.addSyntheticLeadingComment(zt.addSyntheticLeadingComment(i.createEmptyStatement(),zt.SyntaxKind.SingleLineCommentTrivia," Usage example:"),zt.SyntaxKind.MultiLineCommentTrivia,`
20
20
  ${r}`);return this.#e.concat(o||[]).map((n,s)=>Xt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
21
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "23.6.0",
3
+ "version": "23.6.1",
4
4
  "description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {