express-zod-api 25.3.0-beta.1 → 25.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ ${i}888${n}
|
|
|
14
14
|
${r}
|
|
15
15
|
`;e.write(c.split(`
|
|
16
16
|
`).map((e,t)=>s[t]?s[t](e):e).join(`
|
|
17
|
-
`))},sn=e=>{e.startupLogo!==!1&&on(process.stdout);let t=e.errorHandler||ot,n=pt(e.logger)?e.logger:new vt(e.logger);n.debug(`Running`,{build:`v25.3.0-beta.1`,env:process.env.NODE_ENV||`development`}),rn(n);let r=tn({logger:n,config:e}),i=nn(n),a={getLogger:i,errorHandler:t},o=Xt(a),s=Yt(a);return{...a,logger:n,notFoundHandler:o,catcher:s,loggingMiddleware:r}},cn=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=sn(e);return Bt({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},ln=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=sn(e),s=g().disable(`x-powered-by`).use(o);if(e.compression){let t=await xt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r});let c={json:[e.jsonParser||g.json()],raw:[e.rawParser||g.raw(),en],form:[e.formParser||g.urlencoded()],upload:e.upload?await $t({config:e,getLogger:r}):[]};Bt({app:s,routing:t,getLogger:r,config:e,parsers:c}),s.use(a,i);let l=[],u=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),d=[];if(e.http){let t=te.createServer(s);l.push(t),d.push(u(t,e.http.listen))}if(e.https){let t=ne.createServer(e.https.options,s);l.push(t),d.push(u(t,e.https.listen))}return l.length||n.warn(`No servers configured.`),e.gracefulShutdown&&an({logger:n,servers:l,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:d.map(e=>e())}},un=e=>w(e)&&`or`in e,dn=e=>w(e)&&`and`in e,fn=e=>!dn(e)&&!un(e),pn=e=>{let n=t.filter(fn,e),r=t.chain(t.prop(`and`),t.filter(dn,e)),[i,a]=t.partition(fn,r),o=t.concat(n,i),s=t.filter(un,e),c=t.map(t.prop(`or`),t.concat(s,a));return c.reduce((e,n)=>xe(e,t.map(e=>fn(e)?[e]:e.and,n),([e,n])=>t.concat(e,n)),t.reject(t.isEmpty,[o]))};var mn=`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`.split(`.`);const hn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,gn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},_n=e=>e.replace(pe,e=>`{${e.slice(1)}}`),vn=({},e)=>{if(e.isResponse)throw new A(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},yn=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),bn=({zodSchema:e,jsonSchema:t})=>{if(!S(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},xn=t.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return Et(e,`throw`)},(e,{jsonSchema:t})=>t),Sn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:On(t.type)})},L=e=>e,Cn=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new A(`Please use ez.dateOut() for output.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:hn}};return e?.length&&(r.examples=e),r},wn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new A(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:hn}};return e?.length&&(r.examples=e),r},Tn=()=>({type:`string`,format:`bigint`,pattern:/^-?\d+$/.source}),En=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,Dn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return gn?.[t]},On=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],kn=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!S(r,`transform`))return t;let a=L(In(i,{ctx:n}));if(_(a))if(n.isResponse){let e=Ce(r,Dn(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},An=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!w(t.properties.raw)?e:t.properties.raw},jn=e=>e.length?t.fromPairs(t.zip(t.times(e=>`example${e+1}`,e.length),t.map(t.objOf(`value`),e))):void 0,Mn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||mn.includes(e),Nn=({path:e,method:n,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${n.toUpperCase()} ${e} Parameter`})=>{let u=Et(r),d=me(e),f=i.includes(`query`),p=i.includes(`params`),m=i.includes(`headers`),ee=e=>p&&d.includes(e),h=t.chain(t.filter(e=>e.type===`header`),c??[]).map(({name:e})=>e),g=t=>m&&(s?.(t,n,e)??Mn(t,h));return Object.entries(u.properties).reduce((e,[n,r])=>{if(!w(r))return e;let i=ee(n)?`path`:g(n)?`header`:f?`query`:void 0;if(!i)return e;let s=L(r),c=o===`components`?a(r.id||JSON.stringify(r),s,C(l,n)):s;return e.concat({name:n,in:i,deprecated:r.deprecated,required:u.required?.includes(n)||!1,description:s.description||l,schema:c,examples:jn(_(s)&&s.examples?.length?s.examples:t.pluck(n,u.examples?.filter(t.both(w,t.has(n)))||[]))})},[])},Pn={nullable:Sn,union:bn,bigint:Tn,intersection:xn,tuple:En,pipe:kn,[D]:Cn,[O]:wn,[M]:vn,[N]:An,[E]:yn},Fn=(e,n,r)=>{let i=[e,n];for(;i.length;){let e=i.shift();if(t.is(Object,e)){if(ae(e)&&!e.$ref.startsWith(`#/components`)){let t=e.$ref.split(`/`).pop(),i=n[t];i&&(e.$ref=r.makeRef(i.id||i,L(i)).$ref);continue}i.push(...t.values(e))}t.is(Array,e)&&i.push(...t.values(e))}return e},In=(t,{ctx:n,rules:i=Pn})=>{let{$defs:a={},properties:o={}}=r.toJSONSchema(r.object({subject:t}),{unrepresentable:`any`,io:n.isResponse?`output`:`input`,override:t=>{let r=e(t.zodSchema),a=i[r&&r in i?r:t.zodSchema._zod.def.type];if(a){let e={...a(t,n)};for(let e in t.jsonSchema)delete t.jsonSchema[e];Object.assign(t.jsonSchema,e)}}});return Fn(w(o.subject)?o.subject:{},a,n)},Ln=(e,n)=>{if(ae(e))return[e,!1];let r=!1,i=t.map(e=>{let[t,i]=Ln(e,n);return r=r||i,t}),a=t.omit(n),o={properties:a,examples:t.map(a),required:t.without(n),allOf:i,oneOf:i,anyOf:i},s=t.evolve(o,e);return[s,r||!!s.required?.length]},Rn=({method:e,path:n,schema:r,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${n} ${Se(a)} response ${c?l:``}`.trim()})=>{if(!we(e,i))return{description:d};let f=L(In(r,{rules:{...u,...Pn},ctx:{isResponse:!0,makeRef:o,path:n,method:e}})),p=[];_(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(r,f,C(d)):f,examples:jn(p)};return{description:d,content:t.fromPairs(t.xprod(i,[m]))}},zn=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Bn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},Vn=({name:e})=>({type:`apiKey`,in:`header`,name:e}),Hn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),Un=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),Wn=({flows:e={}})=>({type:`oauth2`,flows:t.map(e=>({...e,scopes:e.scopes||{}}),t.reject(t.isNil,e))}),Gn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?zn(e):e.type===`input`?Bn(e,t):e.type===`header`?Vn(e):e.type===`cookie`?Hn(e):e.type===`openid`?Un(e):Wn(e);return e.map(e=>e.map(n))},Kn=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),qn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>In(e,{rules:{...t,...Pn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Jn=({method:e,path:n,schema:r,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${n} Request body`})=>{let[u,d]=Ln(L(i),c),f=[];_(u)&&u.examples&&(f.push(...u.examples),delete u.examples);let p={schema:s===`components`?o(r,u,C(l)):u,examples:jn(f.length?f:Et(i).examples?.filter(e=>w(e)&&!Array.isArray(e)).map(t.omit(c))||[])},m={description:l,content:{[a]:p}};return(d||a===y.raw)&&(m.required=!0),m},Yn=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;let r={name:t,description:typeof n==`string`?n:n.description};return typeof n==`object`&&n.url&&(r.externalDocs={url:n.url}),e.concat(r)},[]),Xn=e=>e.length<=50?e:e.slice(0,49)+`…`,Zn=e=>e.length?e.slice():void 0;var Qn=class extends ie{#lastSecuritySchemaIds=new Map;#lastOperationIdSuffixes=new Map;#references=new Map;#makeRef(e,t,n=this.#references.get(e)){return n||(n=`Schema${this.#references.size+1}`,this.#references.set(e,n)),this.addSchema(n,t),{$ref:`#/components/schemas/${n}`}}#ensureUniqOperationId(e,t,n){let r=n||C(t,e),i=this.#lastOperationIdSuffixes.get(r);if(i===void 0)return this.#lastOperationIdSuffixes.set(r,1),r;if(n)throw new A(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#lastOperationIdSuffixes.set(r,i),`${r}${i}`}#ensureUniqSecuritySchemaName(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#lastSecuritySchemaIds.get(e.type)||0)+1;return this.#lastSecuritySchemaIds.set(e.type,n),`${e.type.toUpperCase()}_${n}`}constructor({routing:e,config:n,title:r,version:i,serverUrl:a,descriptions:o,brandHandling:s,tags:c,isHeader:l,hasSummaryFromDescription:u=!0,hasHeadMethod:d=!0,composition:f=`inline`}){super(),this.addInfo({title:r,version:i});for(let e of typeof a==`string`?[a]:a)this.addServer({url:e});let p=(e,r,i)=>{let a={path:r,method:e,endpoint:i,composition:f,brandHandling:s,makeRef:this.#makeRef.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,ee=d?Xn(d):u&&c?Xn(c):void 0,h=ye(e,n.inputSources),g=this.#ensureUniqOperationId(r,e,i.getOperationId(e)),te=qn({...a,schema:m}),ne=pn(i.security),re=Nn({...a,inputSources:h,isHeader:l,security:ne,request:te,description:o?.requestParameter?.call(null,{method:e,path:r,operationId:g})}),ie={};for(let t of rt){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)ie[l]=Rn({...a,variant:t,schema:s,mimeTypes:i,statusCode:l,hasMultipleStatusCodes:n.length>1||c.length>1,description:o?.[`${t}Response`]?.call(null,{method:e,path:r,operationId:g,statusCode:l})})}let ae=h.includes(`body`)?Jn({...a,request:te,paramNames:t.pluck(`name`,re),schema:m,mimeType:y[i.requestType],description:o?.requestBody?.call(null,{method:e,path:r,operationId:g})}):void 0,_=Kn(Gn(ne,h),p,e=>{let t=this.#ensureUniqSecuritySchemaName(e);return this.addSecurityScheme(t,e),t}),oe={operationId:g,summary:ee,description:c,deprecated:i.isDeprecated||void 0,tags:Zn(i.tags),parameters:Zn(re),requestBody:ae,security:Zn(_),responses:ie};this.addPath(_n(r),{[e]:oe})};It({routing:e,onEndpoint:d?kt(p):p}),c&&(this.rootDoc.tags=Yn(c))}};const $n=e=>oe({...e,headers:{"content-type":y.json,...e?.headers}}),er=e=>se(e),tr=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:mt(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},nr=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=$n(e),a=er({req:i,...t});a.req=t?.req||i,i.res=a;let o=tr(r),s={cors:!1,logger:o,...n};return{requestMock:i,responseMock:a,loggerMock:o,configMock:s}},rr=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=nr(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},ir=async({middleware:e,options:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=ot}}=nr(n),c=be(r,o),l={request:r,response:i,logger:a,input:c,options:t};try{let t=await e.execute(l);return{requestMock:r,responseMock:i,loggerMock:a,output:t}}catch(e){return await s.execute({...l,error:b(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}},R=v.factory,ar=[R.createModifier(v.SyntaxKind.ExportKeyword)],or=[R.createModifier(v.SyntaxKind.AsyncKeyword)],sr={public:[R.createModifier(v.SyntaxKind.PublicKeyword)],protectedReadonly:[R.createModifier(v.SyntaxKind.ProtectedKeyword),R.createModifier(v.SyntaxKind.ReadonlyKeyword)]},cr=(e,t)=>v.addSyntheticLeadingComment(e,v.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),lr=(e,t)=>{let n=v.createSourceFile(`print.ts`,``,v.ScriptTarget.Latest,!1,v.ScriptKind.TS),r=v.createPrinter(t);return r.printNode(v.EmitHint.Unspecified,e,n)},ur=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=e=>typeof e==`string`&&ur.test(e)?R.createIdentifier(e):Y(e),fr=(e,...t)=>R.createTemplateExpression(R.createTemplateHead(e),t.map(([e,n=``],r)=>R.createTemplateSpan(e,r===t.length-1?R.createTemplateTail(n):R.createTemplateMiddle(n)))),pr=(e,{type:t,mod:n,init:r,optional:i}={})=>R.createParameterDeclaration(n,void 0,e,i?R.createToken(v.SyntaxKind.QuestionToken):void 0,t?B(t):void 0,r),z=e=>Object.entries(e).map(([e,t])=>pr(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t)),mr=(e,t=[])=>R.createConstructorDeclaration(sr.public,e,R.createBlock(t)),B=(e,n)=>typeof e==`number`?R.createKeywordTypeNode(e):typeof e==`string`||v.isIdentifier(e)?R.createTypeReferenceNode(e,n&&t.map(B,n)):e,hr=B(`Record`,[v.SyntaxKind.StringKeyword,v.SyntaxKind.AnyKeyword]),V=e=>{let t=new Map;for(let n of e)t.set(Nr(n)?n.kind:n,n);return R.createUnionTypeNode(Array.from(t.values()))},gr=(e,n,{isOptional:r,isDeprecated:i,comment:a}={})=>{let o=B(n),s=R.createPropertySignature(void 0,dr(e),r?R.createToken(v.SyntaxKind.QuestionToken):void 0,r?V([o,B(v.SyntaxKind.UndefinedKeyword)]):o),c=t.reject(t.isNil,[i?`@deprecated`:void 0,a]);return c.length?cr(s,c.join(` `)):s},_r=e=>v.setEmitFlags(e,v.EmitFlags.SingleLine),vr=(...e)=>R.createArrayBindingPattern(e.map(e=>R.createBindingElement(void 0,void 0,e))),H=(e,t,{type:n,expose:r}={})=>R.createVariableStatement(r&&ar,R.createVariableDeclarationList([R.createVariableDeclaration(e,void 0,n?B(n):void 0,t)],v.NodeFlags.Const)),yr=(e,n)=>U(e,V(t.map(X,n)),{expose:!0}),U=(e,t,{expose:n,comment:r,params:i}={})=>{let a=R.createTypeAliasDeclaration(n?ar:void 0,e,i&&Er(i),t);return r?cr(a,r):a},br=(e,t)=>R.createPropertyDeclaration(sr.public,e,void 0,B(t),void 0),xr=(e,t,n,{typeParams:r,returns:i}={})=>R.createMethodDeclaration(sr.public,void 0,e,void 0,r&&Er(r),t,i,R.createBlock(n)),Sr=(e,t,{typeParams:n}={})=>R.createClassDeclaration(ar,e,n&&Er(n),void 0,t),Cr=e=>R.createTypeOperatorNode(v.SyntaxKind.KeyOfKeyword,B(e)),wr=e=>B(Promise.name,[e]),Tr=(e,t,{expose:n,comment:r}={})=>{let i=R.createInterfaceDeclaration(n?ar:void 0,e,void 0,void 0,t);return r?cr(i,r):i},Er=e=>(Array.isArray(e)?e.map(e=>t.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return R.createTypeParameterDeclaration([],e,n?B(n):void 0,r?B(r):void 0)}),W=(e,n,{isAsync:r}={})=>R.createArrowFunction(r?or:void 0,void 0,Array.isArray(e)?t.map(pr,e):z(e),void 0,void 0,n),G=e=>e,Dr=(e,t,n)=>R.createConditionalExpression(e,R.createToken(v.SyntaxKind.QuestionToken),t,R.createToken(v.SyntaxKind.ColonToken),n),K=(e,...t)=>(...n)=>R.createCallExpression(t.reduce((e,t)=>typeof t==`string`||v.isIdentifier(t)?R.createPropertyAccessExpression(e,t):R.createElementAccessExpression(e,t),typeof e==`string`?R.createIdentifier(e):e),void 0,n),q=(e,...t)=>R.createNewExpression(R.createIdentifier(e),void 0,t),Or=(e,t)=>B(`Extract`,[e,t]),kr=(e,t)=>R.createExpressionStatement(R.createBinaryExpression(e,R.createToken(v.SyntaxKind.EqualsToken),t)),J=(e,t)=>R.createIndexedAccessTypeNode(B(e),B(t)),Ar=e=>V([B(e),wr(e)]),jr=(e,t)=>R.createFunctionTypeNode(void 0,z(e),B(t)),Y=e=>typeof e==`number`?R.createNumericLiteral(e):typeof e==`bigint`?R.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?R.createTrue():R.createFalse():e===null?R.createNull():R.createStringLiteral(e),X=e=>R.createLiteralTypeNode(Y(e)),Mr=[v.SyntaxKind.AnyKeyword,v.SyntaxKind.BigIntKeyword,v.SyntaxKind.BooleanKeyword,v.SyntaxKind.NeverKeyword,v.SyntaxKind.NumberKeyword,v.SyntaxKind.ObjectKeyword,v.SyntaxKind.StringKeyword,v.SyntaxKind.SymbolKeyword,v.SyntaxKind.UndefinedKeyword,v.SyntaxKind.UnknownKeyword,v.SyntaxKind.VoidKeyword],Nr=e=>Mr.includes(e.kind);var Pr=class{paths=new Set;tags=new Map;registry=new Map;#ids={pathType:R.createIdentifier(`Path`),implementationType:R.createIdentifier(`Implementation`),keyParameter:R.createIdentifier(`key`),pathParameter:R.createIdentifier(`path`),paramsArgument:R.createIdentifier(`params`),ctxArgument:R.createIdentifier(`ctx`),methodParameter:R.createIdentifier(`method`),requestParameter:R.createIdentifier(`request`),eventParameter:R.createIdentifier(`event`),dataParameter:R.createIdentifier(`data`),handlerParameter:R.createIdentifier(`handler`),msgParameter:R.createIdentifier(`msg`),parseRequestFn:R.createIdentifier(`parseRequest`),substituteFn:R.createIdentifier(`substitute`),provideMethod:R.createIdentifier(`provide`),onMethod:R.createIdentifier(`on`),implementationArgument:R.createIdentifier(`implementation`),hasBodyConst:R.createIdentifier(`hasBody`),undefinedValue:R.createIdentifier(`undefined`),responseConst:R.createIdentifier(`response`),restConst:R.createIdentifier(`rest`),searchParamsConst:R.createIdentifier(`searchParams`),defaultImplementationConst:R.createIdentifier(`defaultImplementation`),clientConst:R.createIdentifier(`client`),contentTypeConst:R.createIdentifier(`contentType`),isJsonConst:R.createIdentifier(`isJSON`),sourceProp:R.createIdentifier(`source`)};interfaces={input:R.createIdentifier(`Input`),positive:R.createIdentifier(`PositiveResponse`),negative:R.createIdentifier(`NegativeResponse`),encoded:R.createIdentifier(`EncodedResponse`),response:R.createIdentifier(`Response`)};methodType=yr(`Method`,ue);someOfType=U(`SomeOf`,J(`T`,Cr(`T`)),{params:[`T`]});requestType=U(`Request`,Cr(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>B(this.someOfType.name,[e]);makePathType=()=>yr(this.#ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>Tr(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>gr(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>H(`endpointTags`,R.createObjectLiteralExpression(Array.from(this.tags).map(([e,n])=>R.createPropertyAssignment(dr(e),R.createArrayLiteralExpression(t.map(Y,n))))),{expose:!0});makeImplementationType=()=>U(this.#ids.implementationType,jr({[this.#ids.methodParameter.text]:this.methodType.name,[this.#ids.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#ids.paramsArgument.text]:hr,[this.#ids.ctxArgument.text]:{optional:!0,type:`T`}},wr(v.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:v.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>H(this.#ids.parseRequestFn,W({[this.#ids.requestParameter.text]:v.SyntaxKind.StringKeyword},R.createAsExpression(K(this.#ids.requestParameter,G(`split`))(R.createRegularExpressionLiteral(`/ (.+)/`),Y(2)),R.createTupleTypeNode([B(this.methodType.name),B(this.#ids.pathType)]))));makeSubstituteFn=()=>H(this.#ids.substituteFn,W({[this.#ids.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#ids.paramsArgument.text]:hr},R.createBlock([H(this.#ids.restConst,R.createObjectLiteralExpression([R.createSpreadAssignment(this.#ids.paramsArgument)])),R.createForInStatement(R.createVariableDeclarationList([R.createVariableDeclaration(this.#ids.keyParameter)],v.NodeFlags.Const),this.#ids.paramsArgument,R.createBlock([kr(this.#ids.pathParameter,K(this.#ids.pathParameter,G(`replace`))(fr(`:`,[this.#ids.keyParameter]),W([],R.createBlock([R.createExpressionStatement(R.createDeleteExpression(R.createElementAccessExpression(this.#ids.restConst,this.#ids.keyParameter))),R.createReturnStatement(R.createElementAccessExpression(this.#ids.paramsArgument,this.#ids.keyParameter))]))))])),R.createReturnStatement(R.createAsExpression(R.createArrayLiteralExpression([this.#ids.pathParameter,this.#ids.restConst]),B(`const`)))])));#makeProvider=()=>xr(this.#ids.provideMethod,z({[this.#ids.requestParameter.text]:`K`,[this.#ids.paramsArgument.text]:J(this.interfaces.input,`K`),[this.#ids.ctxArgument.text]:{optional:!0,type:`T`}}),[H(vr(this.#ids.methodParameter,this.#ids.pathParameter),K(this.#ids.parseRequestFn)(this.#ids.requestParameter)),R.createReturnStatement(K(R.createThis(),this.#ids.implementationArgument)(this.#ids.methodParameter,R.createSpreadElement(K(this.#ids.substituteFn)(this.#ids.pathParameter,this.#ids.paramsArgument)),this.#ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:wr(J(this.interfaces.response,`K`))});makeClientClass=e=>Sr(e,[mr([pr(this.#ids.implementationArgument,{type:B(this.#ids.implementationType,[`T`]),mod:sr.protectedReadonly,init:this.#ids.defaultImplementationConst})]),this.#makeProvider()],{typeParams:[`T`]});#makeSearchParams=e=>fr(`?`,[q(URLSearchParams.name,e)]);#makeFetchURL=()=>q(URL.name,fr(``,[this.#ids.pathParameter],[this.#ids.searchParamsConst]),Y(this.serverUrl));makeDefaultImplementation=()=>{let e=R.createPropertyAssignment(G(`method`),K(this.#ids.methodParameter,G(`toUpperCase`))()),t=R.createPropertyAssignment(G(`headers`),Dr(this.#ids.hasBodyConst,R.createObjectLiteralExpression([R.createPropertyAssignment(Y(`Content-Type`),Y(y.json))]),this.#ids.undefinedValue)),n=R.createPropertyAssignment(G(`body`),Dr(this.#ids.hasBodyConst,K(JSON[Symbol.toStringTag],G(`stringify`))(this.#ids.paramsArgument),this.#ids.undefinedValue)),r=H(this.#ids.responseConst,R.createAwaitExpression(K(fetch.name)(this.#makeFetchURL(),R.createObjectLiteralExpression([e,t,n])))),i=H(this.#ids.hasBodyConst,R.createLogicalNot(K(R.createArrayLiteralExpression([Y(`get`),Y(`head`),Y(`delete`)]),G(`includes`))(this.#ids.methodParameter))),a=H(this.#ids.searchParamsConst,Dr(this.#ids.hasBodyConst,Y(``),this.#makeSearchParams(this.#ids.paramsArgument))),o=H(this.#ids.contentTypeConst,K(this.#ids.responseConst,G(`headers`),G(`get`))(Y(`content-type`))),s=R.createIfStatement(R.createPrefixUnaryExpression(v.SyntaxKind.ExclamationToken,this.#ids.contentTypeConst),R.createReturnStatement()),c=H(this.#ids.isJsonConst,K(this.#ids.contentTypeConst,G(`startsWith`))(Y(y.json))),l=R.createReturnStatement(K(this.#ids.responseConst,Dr(this.#ids.isJsonConst,Y(G(`json`)),Y(G(`text`))))());return H(this.#ids.defaultImplementationConst,W([this.#ids.methodParameter,this.#ids.pathParameter,this.#ids.paramsArgument],R.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#ids.implementationType})};#makeSubscriptionConstructor=()=>mr(z({request:`K`,params:J(this.interfaces.input,`K`)}),[H(vr(this.#ids.pathParameter,this.#ids.restConst),K(this.#ids.substituteFn)(R.createElementAccessExpression(K(this.#ids.parseRequestFn)(this.#ids.requestParameter),Y(1)),this.#ids.paramsArgument)),H(this.#ids.searchParamsConst,this.#makeSearchParams(this.#ids.restConst)),kr(R.createPropertyAccessExpression(R.createThis(),this.#ids.sourceProp),q(`EventSource`,this.#makeFetchURL()))]);#makeEventNarrow=e=>R.createTypeLiteralNode([gr(G(`event`),e)]);#makeOnMethod=()=>xr(this.#ids.onMethod,z({[this.#ids.eventParameter.text]:`E`,[this.#ids.handlerParameter.text]:jr({[this.#ids.dataParameter.text]:J(Or(`R`,_r(this.#makeEventNarrow(`E`))),X(G(`data`)))},Ar(v.SyntaxKind.VoidKeyword))}),[R.createExpressionStatement(K(R.createThis(),this.#ids.sourceProp,G(`addEventListener`))(this.#ids.eventParameter,W([this.#ids.msgParameter],K(this.#ids.handlerParameter)(K(JSON[Symbol.toStringTag],G(`parse`))(R.createPropertyAccessExpression(R.createParenthesizedExpression(R.createAsExpression(this.#ids.msgParameter,B(MessageEvent.name))),G(`data`))))))),R.createReturnStatement(R.createThis())],{typeParams:{E:J(`R`,X(G(`event`)))}});makeSubscriptionClass=e=>Sr(e,[br(this.#ids.sourceProp,`EventSource`),this.#makeSubscriptionConstructor(),this.#makeOnMethod()],{typeParams:{K:Or(this.requestType.name,R.createTemplateLiteralType(R.createTemplateHead(`get `),[R.createTemplateLiteralTypeSpan(B(v.SyntaxKind.StringKeyword),R.createTemplateTail(``))])),R:Or(J(this.interfaces.positive,`K`),_r(this.#makeEventNarrow(v.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[H(this.#ids.clientConst,q(e)),K(this.#ids.clientConst,this.#ids.provideMethod)(Y(`get /v1/user/retrieve`),R.createObjectLiteralExpression([R.createPropertyAssignment(`id`,Y(`10`))])),K(q(t,Y(`get /v1/events/stream`),R.createObjectLiteralExpression()),this.#ids.onMethod)(Y(`time`),W([`time`],R.createBlock([])))]};const Fr=(t,{onEach:n,rules:r,onMissing:i,ctx:a={}})=>{let o=e(t),s=o&&o in r?r[o]:r[t._zod.def.type],c=e=>Fr(e,{ctx:a,onEach:n,rules:r,onMissing:i}),l=s?s(t,{...a,next:c}):i(t,a),u=n&&n(t,{prev:l,...a});return u?{...l,...u}:l},{factory:Z}=v,Ir={[v.SyntaxKind.AnyKeyword]:``,[v.SyntaxKind.BigIntKeyword]:BigInt(0),[v.SyntaxKind.BooleanKeyword]:!1,[v.SyntaxKind.NumberKeyword]:0,[v.SyntaxKind.ObjectKeyword]:{},[v.SyntaxKind.StringKeyword]:``,[v.SyntaxKind.UndefinedKeyword]:void 0},Lr={name:t.path([`name`,`text`]),type:t.path([`type`]),optional:t.path([`questionToken`])},Rr=({_zod:{def:e}})=>{let t=e.values.map(e=>e===void 0?B(v.SyntaxKind.UndefinedKeyword):X(e));return t.length===1?t[0]:V(t)},zr=({_zod:{def:e}},{next:t})=>{let n=[...e.parts],r=()=>{let e=``;for(;n.length;){let t=n.shift();if(S(t)){n.unshift(t);break}e+=t??``}return e},i=Z.createTemplateHead(r()),a=[];for(;n.length;){let e=t(n.shift()),i=r(),o=n.length?Z.createTemplateMiddle:Z.createTemplateTail;a.push(Z.createTemplateLiteralTypeSpan(e,o(i)))}return a.length?Z.createTemplateLiteralType(i,a):X(i.text)},Br=(e,{isResponse:t,next:r,makeAlias:i})=>{let a=()=>{let i=Object.entries(e._zod.def.shape).map(([e,i])=>{let{description:a,deprecated:o}=n.get(i)||{};return gr(e,r(i),{comment:a,isDeprecated:o,isOptional:(t?i._zod.optout:i._zod.optin)===`optional`})});return Z.createTypeLiteralNode(i)};return Be(e,{io:t?`output`:`input`})?i(e,a):a()},Vr=({_zod:{def:e}},{next:t})=>Z.createArrayTypeNode(t(e.element)),Hr=({_zod:{def:e}})=>V(Object.values(e.entries).map(X)),Ur=({_zod:{def:e}},{next:t})=>V(e.options.map(t)),Wr=e=>Ir?.[e.kind],Gr=({_zod:{def:e}},{next:t})=>V([t(e.innerType),X(null)]),Kr=({_zod:{def:e}},{next:t})=>Z.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:Z.createRestTypeNode(t(e.rest)))),qr=({_zod:{def:e}},{next:t})=>B(`Record`,[e.keyType,e.valueType].map(t)),Jr=t.tryCatch(e=>{if(!e.every(v.isTypeLiteralNode))throw Error(`Not objects`);let n=t.chain(t.prop(`members`),e),r=t.uniqWith((...e)=>{if(!t.eqBy(Lr.name,...e))return!1;if(t.both(t.eqBy(Lr.type),t.eqBy(Lr.optional))(...e))return!0;throw Error(`Has conflicting prop`)},n);return Z.createTypeLiteralNode(r)},(e,t)=>Z.createIntersectionTypeNode(t)),Yr=({_zod:{def:e}},{next:t})=>Jr([e.left,e.right].map(t)),Q=e=>()=>B(e),$=({_zod:{def:e}},{next:t})=>t(e.innerType),Xr=e=>B(e?v.SyntaxKind.UnknownKeyword:v.SyntaxKind.AnyKeyword),Zr=({_zod:{def:e}},{next:t,isResponse:n})=>{let r=e[n?`out`:`in`],i=e[n?`in`:`out`];if(!S(r,`transform`))return t(r);let a=t(i),o=Ce(r,Wr(a)),s={number:v.SyntaxKind.NumberKeyword,bigint:v.SyntaxKind.BigIntKeyword,boolean:v.SyntaxKind.BooleanKeyword,string:v.SyntaxKind.StringKeyword,undefined:v.SyntaxKind.UndefinedKeyword,object:v.SyntaxKind.ObjectKeyword};return B(o&&s[o]||Xr(n))},Qr=()=>X(null),$r=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ei=()=>B(`Buffer`),ti=(e,{next:t})=>t(e._zod.def.shape.raw),ni={string:Q(v.SyntaxKind.StringKeyword),number:Q(v.SyntaxKind.NumberKeyword),bigint:Q(v.SyntaxKind.BigIntKeyword),boolean:Q(v.SyntaxKind.BooleanKeyword),any:Q(v.SyntaxKind.AnyKeyword),undefined:Q(v.SyntaxKind.UndefinedKeyword),[D]:Q(v.SyntaxKind.StringKeyword),[O]:Q(v.SyntaxKind.StringKeyword),never:Q(v.SyntaxKind.NeverKeyword),void:Q(v.SyntaxKind.UndefinedKeyword),unknown:Q(v.SyntaxKind.UnknownKeyword),null:Qr,array:Vr,tuple:Kr,record:qr,object:Br,literal:Rr,template_literal:zr,intersection:Yr,union:Ur,default:$,enum:Hr,optional:$,nonoptional:$,nullable:Gr,catch:$,pipe:Zr,lazy:$r,readonly:$,[E]:ei,[N]:ti},ri=(e,{brandHandling:t,ctx:n})=>Fr(e,{rules:{...t,...ni},onMissing:({},{isResponse:e})=>Xr(e),ctx:n});var ii=class extends Pr{#program=[this.someOfType];#aliases=new Map;#usage=[];#makeAlias(e,t){let n=this.#aliases.get(e)?.name?.text;if(!n){n=`Type${this.#aliases.size+1}`;let r=X(null);this.#aliases.set(e,U(n,r)),this.#aliases.set(e,U(n,t()))}return B(n)}constructor({routing:e,brandHandling:n,variant:i=`client`,clientClassName:a=`Client`,subscriptionClassName:o=`Subscription`,serverUrl:s=`https://example.com`,noContent:c=r.undefined(),hasHeadMethod:l=!0}){super(s);let u={makeAlias:this.#makeAlias.bind(this)},d={brandHandling:n,ctx:{...u,isResponse:!1}},f={brandHandling:n,ctx:{...u,isResponse:!0}},p=(e,n,r)=>{let i=C.bind(null,e,n),{isDeprecated:a,inputSchema:o,tags:s}=r,l=`${e} ${n}`,u=U(i(`input`),ri(o,d),{comment:l});this.#program.push(u);let p=rt.reduce((n,a)=>{let o=r.getResponses(a),s=t.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=we(e,r),u=U(i(a,`variant`,`${t+1}`),ri(s?n:c,f),{comment:l});return this.#program.push(u),o.map(e=>gr(e,u.name))},Array.from(o.entries())),u=Tr(i(a,`response`,`variants`),s,{comment:l});return this.#program.push(u),Object.assign(n,{[a]:u})},{});this.paths.add(n);let m=X(l),ee={input:B(u.name),positive:this.someOf(p.positive),negative:this.someOf(p.negative),response:V([J(this.interfaces.positive,m),J(this.interfaces.negative,m)]),encoded:R.createIntersectionTypeNode([B(p.positive.name),B(p.negative.name)])};this.registry.set(l,{isDeprecated:a,store:ee}),this.tags.set(l,s)};It({routing:e,onEndpoint:l?kt(p):p}),this.#program.unshift(...this.#aliases.values()),this.#program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),i!==`types`&&(this.#program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(a),this.makeSubscriptionClass(o)),this.#usage.push(...this.makeUsageStatements(a,o)))}#printUsage(e){return this.#usage.length?this.#usage.map(t=>typeof t==`string`?t:lr(t,e)).join(`
|
|
17
|
+
`))},sn=e=>{e.startupLogo!==!1&&on(process.stdout);let t=e.errorHandler||ot,n=pt(e.logger)?e.logger:new vt(e.logger);n.debug(`Running`,{build:`v25.3.0`,env:process.env.NODE_ENV||`development`}),rn(n);let r=tn({logger:n,config:e}),i=nn(n),a={getLogger:i,errorHandler:t},o=Xt(a),s=Yt(a);return{...a,logger:n,notFoundHandler:o,catcher:s,loggingMiddleware:r}},cn=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=sn(e);return Bt({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},ln=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=sn(e),s=g().disable(`x-powered-by`).use(o);if(e.compression){let t=await xt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r});let c={json:[e.jsonParser||g.json()],raw:[e.rawParser||g.raw(),en],form:[e.formParser||g.urlencoded()],upload:e.upload?await $t({config:e,getLogger:r}):[]};Bt({app:s,routing:t,getLogger:r,config:e,parsers:c}),s.use(a,i);let l=[],u=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),d=[];if(e.http){let t=te.createServer(s);l.push(t),d.push(u(t,e.http.listen))}if(e.https){let t=ne.createServer(e.https.options,s);l.push(t),d.push(u(t,e.https.listen))}return l.length||n.warn(`No servers configured.`),e.gracefulShutdown&&an({logger:n,servers:l,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:d.map(e=>e())}},un=e=>w(e)&&`or`in e,dn=e=>w(e)&&`and`in e,fn=e=>!dn(e)&&!un(e),pn=e=>{let n=t.filter(fn,e),r=t.chain(t.prop(`and`),t.filter(dn,e)),[i,a]=t.partition(fn,r),o=t.concat(n,i),s=t.filter(un,e),c=t.map(t.prop(`or`),t.concat(s,a));return c.reduce((e,n)=>xe(e,t.map(e=>fn(e)?[e]:e.and,n),([e,n])=>t.concat(e,n)),t.reject(t.isEmpty,[o]))};var mn=`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`.split(`.`);const hn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,gn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},_n=e=>e.replace(pe,e=>`{${e.slice(1)}}`),vn=({},e)=>{if(e.isResponse)throw new A(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},yn=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),bn=({zodSchema:e,jsonSchema:t})=>{if(!S(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},xn=t.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return Et(e,`throw`)},(e,{jsonSchema:t})=>t),Sn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:On(t.type)})},L=e=>e,Cn=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new A(`Please use ez.dateOut() for output.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:hn}};return e?.length&&(r.examples=e),r},wn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new A(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:hn}};return e?.length&&(r.examples=e),r},Tn=()=>({type:`string`,format:`bigint`,pattern:/^-?\d+$/.source}),En=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,Dn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return gn?.[t]},On=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],kn=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!S(r,`transform`))return t;let a=L(In(i,{ctx:n}));if(_(a))if(n.isResponse){let e=Ce(r,Dn(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},An=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!w(t.properties.raw)?e:t.properties.raw},jn=e=>e.length?t.fromPairs(t.zip(t.times(e=>`example${e+1}`,e.length),t.map(t.objOf(`value`),e))):void 0,Mn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||mn.includes(e),Nn=({path:e,method:n,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${n.toUpperCase()} ${e} Parameter`})=>{let u=Et(r),d=me(e),f=i.includes(`query`),p=i.includes(`params`),m=i.includes(`headers`),ee=e=>p&&d.includes(e),h=t.chain(t.filter(e=>e.type===`header`),c??[]).map(({name:e})=>e),g=t=>m&&(s?.(t,n,e)??Mn(t,h));return Object.entries(u.properties).reduce((e,[n,r])=>{if(!w(r))return e;let i=ee(n)?`path`:g(n)?`header`:f?`query`:void 0;if(!i)return e;let s=L(r),c=o===`components`?a(r.id||JSON.stringify(r),s,C(l,n)):s;return e.concat({name:n,in:i,deprecated:r.deprecated,required:u.required?.includes(n)||!1,description:s.description||l,schema:c,examples:jn(_(s)&&s.examples?.length?s.examples:t.pluck(n,u.examples?.filter(t.both(w,t.has(n)))||[]))})},[])},Pn={nullable:Sn,union:bn,bigint:Tn,intersection:xn,tuple:En,pipe:kn,[D]:Cn,[O]:wn,[M]:vn,[N]:An,[E]:yn},Fn=(e,n,r)=>{let i=[e,n];for(;i.length;){let e=i.shift();if(t.is(Object,e)){if(ae(e)&&!e.$ref.startsWith(`#/components`)){let t=e.$ref.split(`/`).pop(),i=n[t];i&&(e.$ref=r.makeRef(i.id||i,L(i)).$ref);continue}i.push(...t.values(e))}t.is(Array,e)&&i.push(...t.values(e))}return e},In=(t,{ctx:n,rules:i=Pn})=>{let{$defs:a={},properties:o={}}=r.toJSONSchema(r.object({subject:t}),{unrepresentable:`any`,io:n.isResponse?`output`:`input`,override:t=>{let r=e(t.zodSchema),a=i[r&&r in i?r:t.zodSchema._zod.def.type];if(a){let e={...a(t,n)};for(let e in t.jsonSchema)delete t.jsonSchema[e];Object.assign(t.jsonSchema,e)}}});return Fn(w(o.subject)?o.subject:{},a,n)},Ln=(e,n)=>{if(ae(e))return[e,!1];let r=!1,i=t.map(e=>{let[t,i]=Ln(e,n);return r=r||i,t}),a=t.omit(n),o={properties:a,examples:t.map(a),required:t.without(n),allOf:i,oneOf:i,anyOf:i},s=t.evolve(o,e);return[s,r||!!s.required?.length]},Rn=({method:e,path:n,schema:r,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${n} ${Se(a)} response ${c?l:``}`.trim()})=>{if(!we(e,i))return{description:d};let f=L(In(r,{rules:{...u,...Pn},ctx:{isResponse:!0,makeRef:o,path:n,method:e}})),p=[];_(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(r,f,C(d)):f,examples:jn(p)};return{description:d,content:t.fromPairs(t.xprod(i,[m]))}},zn=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Bn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},Vn=({name:e})=>({type:`apiKey`,in:`header`,name:e}),Hn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),Un=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),Wn=({flows:e={}})=>({type:`oauth2`,flows:t.map(e=>({...e,scopes:e.scopes||{}}),t.reject(t.isNil,e))}),Gn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?zn(e):e.type===`input`?Bn(e,t):e.type===`header`?Vn(e):e.type===`cookie`?Hn(e):e.type===`openid`?Un(e):Wn(e);return e.map(e=>e.map(n))},Kn=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),qn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>In(e,{rules:{...t,...Pn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Jn=({method:e,path:n,schema:r,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${n} Request body`})=>{let[u,d]=Ln(L(i),c),f=[];_(u)&&u.examples&&(f.push(...u.examples),delete u.examples);let p={schema:s===`components`?o(r,u,C(l)):u,examples:jn(f.length?f:Et(i).examples?.filter(e=>w(e)&&!Array.isArray(e)).map(t.omit(c))||[])},m={description:l,content:{[a]:p}};return(d||a===y.raw)&&(m.required=!0),m},Yn=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;let r={name:t,description:typeof n==`string`?n:n.description};return typeof n==`object`&&n.url&&(r.externalDocs={url:n.url}),e.concat(r)},[]),Xn=e=>e.length<=50?e:e.slice(0,49)+`…`,Zn=e=>e.length?e.slice():void 0;var Qn=class extends ie{#lastSecuritySchemaIds=new Map;#lastOperationIdSuffixes=new Map;#references=new Map;#makeRef(e,t,n=this.#references.get(e)){return n||(n=`Schema${this.#references.size+1}`,this.#references.set(e,n)),this.addSchema(n,t),{$ref:`#/components/schemas/${n}`}}#ensureUniqOperationId(e,t,n){let r=n||C(t,e),i=this.#lastOperationIdSuffixes.get(r);if(i===void 0)return this.#lastOperationIdSuffixes.set(r,1),r;if(n)throw new A(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#lastOperationIdSuffixes.set(r,i),`${r}${i}`}#ensureUniqSecuritySchemaName(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#lastSecuritySchemaIds.get(e.type)||0)+1;return this.#lastSecuritySchemaIds.set(e.type,n),`${e.type.toUpperCase()}_${n}`}constructor({routing:e,config:n,title:r,version:i,serverUrl:a,descriptions:o,brandHandling:s,tags:c,isHeader:l,hasSummaryFromDescription:u=!0,hasHeadMethod:d=!0,composition:f=`inline`}){super(),this.addInfo({title:r,version:i});for(let e of typeof a==`string`?[a]:a)this.addServer({url:e});let p=(e,r,i)=>{let a={path:r,method:e,endpoint:i,composition:f,brandHandling:s,makeRef:this.#makeRef.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,ee=d?Xn(d):u&&c?Xn(c):void 0,h=ye(e,n.inputSources),g=this.#ensureUniqOperationId(r,e,i.getOperationId(e)),te=qn({...a,schema:m}),ne=pn(i.security),re=Nn({...a,inputSources:h,isHeader:l,security:ne,request:te,description:o?.requestParameter?.call(null,{method:e,path:r,operationId:g})}),ie={};for(let t of rt){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)ie[l]=Rn({...a,variant:t,schema:s,mimeTypes:i,statusCode:l,hasMultipleStatusCodes:n.length>1||c.length>1,description:o?.[`${t}Response`]?.call(null,{method:e,path:r,operationId:g,statusCode:l})})}let ae=h.includes(`body`)?Jn({...a,request:te,paramNames:t.pluck(`name`,re),schema:m,mimeType:y[i.requestType],description:o?.requestBody?.call(null,{method:e,path:r,operationId:g})}):void 0,_=Kn(Gn(ne,h),p,e=>{let t=this.#ensureUniqSecuritySchemaName(e);return this.addSecurityScheme(t,e),t}),oe={operationId:g,summary:ee,description:c,deprecated:i.isDeprecated||void 0,tags:Zn(i.tags),parameters:Zn(re),requestBody:ae,security:Zn(_),responses:ie};this.addPath(_n(r),{[e]:oe})};It({routing:e,onEndpoint:d?kt(p):p}),c&&(this.rootDoc.tags=Yn(c))}};const $n=e=>oe({...e,headers:{"content-type":y.json,...e?.headers}}),er=e=>se(e),tr=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:mt(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},nr=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=$n(e),a=er({req:i,...t});a.req=t?.req||i,i.res=a;let o=tr(r),s={cors:!1,logger:o,...n};return{requestMock:i,responseMock:a,loggerMock:o,configMock:s}},rr=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=nr(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},ir=async({middleware:e,options:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=ot}}=nr(n),c=be(r,o),l={request:r,response:i,logger:a,input:c,options:t};try{let t=await e.execute(l);return{requestMock:r,responseMock:i,loggerMock:a,output:t}}catch(e){return await s.execute({...l,error:b(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}},R=v.factory,ar=[R.createModifier(v.SyntaxKind.ExportKeyword)],or=[R.createModifier(v.SyntaxKind.AsyncKeyword)],sr={public:[R.createModifier(v.SyntaxKind.PublicKeyword)],protectedReadonly:[R.createModifier(v.SyntaxKind.ProtectedKeyword),R.createModifier(v.SyntaxKind.ReadonlyKeyword)]},cr=(e,t)=>v.addSyntheticLeadingComment(e,v.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),lr=(e,t)=>{let n=v.createSourceFile(`print.ts`,``,v.ScriptTarget.Latest,!1,v.ScriptKind.TS),r=v.createPrinter(t);return r.printNode(v.EmitHint.Unspecified,e,n)},ur=/^[A-Za-z_$][A-Za-z0-9_$]*$/,dr=e=>typeof e==`string`&&ur.test(e)?R.createIdentifier(e):Y(e),fr=(e,...t)=>R.createTemplateExpression(R.createTemplateHead(e),t.map(([e,n=``],r)=>R.createTemplateSpan(e,r===t.length-1?R.createTemplateTail(n):R.createTemplateMiddle(n)))),pr=(e,{type:t,mod:n,init:r,optional:i}={})=>R.createParameterDeclaration(n,void 0,e,i?R.createToken(v.SyntaxKind.QuestionToken):void 0,t?B(t):void 0,r),z=e=>Object.entries(e).map(([e,t])=>pr(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t)),mr=(e,t=[])=>R.createConstructorDeclaration(sr.public,e,R.createBlock(t)),B=(e,n)=>typeof e==`number`?R.createKeywordTypeNode(e):typeof e==`string`||v.isIdentifier(e)?R.createTypeReferenceNode(e,n&&t.map(B,n)):e,hr=B(`Record`,[v.SyntaxKind.StringKeyword,v.SyntaxKind.AnyKeyword]),V=e=>{let t=new Map;for(let n of e)t.set(Nr(n)?n.kind:n,n);return R.createUnionTypeNode(Array.from(t.values()))},gr=(e,n,{isOptional:r,isDeprecated:i,comment:a}={})=>{let o=B(n),s=R.createPropertySignature(void 0,dr(e),r?R.createToken(v.SyntaxKind.QuestionToken):void 0,r?V([o,B(v.SyntaxKind.UndefinedKeyword)]):o),c=t.reject(t.isNil,[i?`@deprecated`:void 0,a]);return c.length?cr(s,c.join(` `)):s},_r=e=>v.setEmitFlags(e,v.EmitFlags.SingleLine),vr=(...e)=>R.createArrayBindingPattern(e.map(e=>R.createBindingElement(void 0,void 0,e))),H=(e,t,{type:n,expose:r}={})=>R.createVariableStatement(r&&ar,R.createVariableDeclarationList([R.createVariableDeclaration(e,void 0,n?B(n):void 0,t)],v.NodeFlags.Const)),yr=(e,n)=>U(e,V(t.map(X,n)),{expose:!0}),U=(e,t,{expose:n,comment:r,params:i}={})=>{let a=R.createTypeAliasDeclaration(n?ar:void 0,e,i&&Er(i),t);return r?cr(a,r):a},br=(e,t)=>R.createPropertyDeclaration(sr.public,e,void 0,B(t),void 0),xr=(e,t,n,{typeParams:r,returns:i}={})=>R.createMethodDeclaration(sr.public,void 0,e,void 0,r&&Er(r),t,i,R.createBlock(n)),Sr=(e,t,{typeParams:n}={})=>R.createClassDeclaration(ar,e,n&&Er(n),void 0,t),Cr=e=>R.createTypeOperatorNode(v.SyntaxKind.KeyOfKeyword,B(e)),wr=e=>B(Promise.name,[e]),Tr=(e,t,{expose:n,comment:r}={})=>{let i=R.createInterfaceDeclaration(n?ar:void 0,e,void 0,void 0,t);return r?cr(i,r):i},Er=e=>(Array.isArray(e)?e.map(e=>t.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return R.createTypeParameterDeclaration([],e,n?B(n):void 0,r?B(r):void 0)}),W=(e,n,{isAsync:r}={})=>R.createArrowFunction(r?or:void 0,void 0,Array.isArray(e)?t.map(pr,e):z(e),void 0,void 0,n),G=e=>e,Dr=(e,t,n)=>R.createConditionalExpression(e,R.createToken(v.SyntaxKind.QuestionToken),t,R.createToken(v.SyntaxKind.ColonToken),n),K=(e,...t)=>(...n)=>R.createCallExpression(t.reduce((e,t)=>typeof t==`string`||v.isIdentifier(t)?R.createPropertyAccessExpression(e,t):R.createElementAccessExpression(e,t),typeof e==`string`?R.createIdentifier(e):e),void 0,n),q=(e,...t)=>R.createNewExpression(R.createIdentifier(e),void 0,t),Or=(e,t)=>B(`Extract`,[e,t]),kr=(e,t)=>R.createExpressionStatement(R.createBinaryExpression(e,R.createToken(v.SyntaxKind.EqualsToken),t)),J=(e,t)=>R.createIndexedAccessTypeNode(B(e),B(t)),Ar=e=>V([B(e),wr(e)]),jr=(e,t)=>R.createFunctionTypeNode(void 0,z(e),B(t)),Y=e=>typeof e==`number`?R.createNumericLiteral(e):typeof e==`bigint`?R.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?R.createTrue():R.createFalse():e===null?R.createNull():R.createStringLiteral(e),X=e=>R.createLiteralTypeNode(Y(e)),Mr=[v.SyntaxKind.AnyKeyword,v.SyntaxKind.BigIntKeyword,v.SyntaxKind.BooleanKeyword,v.SyntaxKind.NeverKeyword,v.SyntaxKind.NumberKeyword,v.SyntaxKind.ObjectKeyword,v.SyntaxKind.StringKeyword,v.SyntaxKind.SymbolKeyword,v.SyntaxKind.UndefinedKeyword,v.SyntaxKind.UnknownKeyword,v.SyntaxKind.VoidKeyword],Nr=e=>Mr.includes(e.kind);var Pr=class{paths=new Set;tags=new Map;registry=new Map;#ids={pathType:R.createIdentifier(`Path`),implementationType:R.createIdentifier(`Implementation`),keyParameter:R.createIdentifier(`key`),pathParameter:R.createIdentifier(`path`),paramsArgument:R.createIdentifier(`params`),ctxArgument:R.createIdentifier(`ctx`),methodParameter:R.createIdentifier(`method`),requestParameter:R.createIdentifier(`request`),eventParameter:R.createIdentifier(`event`),dataParameter:R.createIdentifier(`data`),handlerParameter:R.createIdentifier(`handler`),msgParameter:R.createIdentifier(`msg`),parseRequestFn:R.createIdentifier(`parseRequest`),substituteFn:R.createIdentifier(`substitute`),provideMethod:R.createIdentifier(`provide`),onMethod:R.createIdentifier(`on`),implementationArgument:R.createIdentifier(`implementation`),hasBodyConst:R.createIdentifier(`hasBody`),undefinedValue:R.createIdentifier(`undefined`),responseConst:R.createIdentifier(`response`),restConst:R.createIdentifier(`rest`),searchParamsConst:R.createIdentifier(`searchParams`),defaultImplementationConst:R.createIdentifier(`defaultImplementation`),clientConst:R.createIdentifier(`client`),contentTypeConst:R.createIdentifier(`contentType`),isJsonConst:R.createIdentifier(`isJSON`),sourceProp:R.createIdentifier(`source`)};interfaces={input:R.createIdentifier(`Input`),positive:R.createIdentifier(`PositiveResponse`),negative:R.createIdentifier(`NegativeResponse`),encoded:R.createIdentifier(`EncodedResponse`),response:R.createIdentifier(`Response`)};methodType=yr(`Method`,ue);someOfType=U(`SomeOf`,J(`T`,Cr(`T`)),{params:[`T`]});requestType=U(`Request`,Cr(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>B(this.someOfType.name,[e]);makePathType=()=>yr(this.#ids.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>Tr(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>gr(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>H(`endpointTags`,R.createObjectLiteralExpression(Array.from(this.tags).map(([e,n])=>R.createPropertyAssignment(dr(e),R.createArrayLiteralExpression(t.map(Y,n))))),{expose:!0});makeImplementationType=()=>U(this.#ids.implementationType,jr({[this.#ids.methodParameter.text]:this.methodType.name,[this.#ids.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#ids.paramsArgument.text]:hr,[this.#ids.ctxArgument.text]:{optional:!0,type:`T`}},wr(v.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:v.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>H(this.#ids.parseRequestFn,W({[this.#ids.requestParameter.text]:v.SyntaxKind.StringKeyword},R.createAsExpression(K(this.#ids.requestParameter,G(`split`))(R.createRegularExpressionLiteral(`/ (.+)/`),Y(2)),R.createTupleTypeNode([B(this.methodType.name),B(this.#ids.pathType)]))));makeSubstituteFn=()=>H(this.#ids.substituteFn,W({[this.#ids.pathParameter.text]:v.SyntaxKind.StringKeyword,[this.#ids.paramsArgument.text]:hr},R.createBlock([H(this.#ids.restConst,R.createObjectLiteralExpression([R.createSpreadAssignment(this.#ids.paramsArgument)])),R.createForInStatement(R.createVariableDeclarationList([R.createVariableDeclaration(this.#ids.keyParameter)],v.NodeFlags.Const),this.#ids.paramsArgument,R.createBlock([kr(this.#ids.pathParameter,K(this.#ids.pathParameter,G(`replace`))(fr(`:`,[this.#ids.keyParameter]),W([],R.createBlock([R.createExpressionStatement(R.createDeleteExpression(R.createElementAccessExpression(this.#ids.restConst,this.#ids.keyParameter))),R.createReturnStatement(R.createElementAccessExpression(this.#ids.paramsArgument,this.#ids.keyParameter))]))))])),R.createReturnStatement(R.createAsExpression(R.createArrayLiteralExpression([this.#ids.pathParameter,this.#ids.restConst]),B(`const`)))])));#makeProvider=()=>xr(this.#ids.provideMethod,z({[this.#ids.requestParameter.text]:`K`,[this.#ids.paramsArgument.text]:J(this.interfaces.input,`K`),[this.#ids.ctxArgument.text]:{optional:!0,type:`T`}}),[H(vr(this.#ids.methodParameter,this.#ids.pathParameter),K(this.#ids.parseRequestFn)(this.#ids.requestParameter)),R.createReturnStatement(K(R.createThis(),this.#ids.implementationArgument)(this.#ids.methodParameter,R.createSpreadElement(K(this.#ids.substituteFn)(this.#ids.pathParameter,this.#ids.paramsArgument)),this.#ids.ctxArgument))],{typeParams:{K:this.requestType.name},returns:wr(J(this.interfaces.response,`K`))});makeClientClass=e=>Sr(e,[mr([pr(this.#ids.implementationArgument,{type:B(this.#ids.implementationType,[`T`]),mod:sr.protectedReadonly,init:this.#ids.defaultImplementationConst})]),this.#makeProvider()],{typeParams:[`T`]});#makeSearchParams=e=>fr(`?`,[q(URLSearchParams.name,e)]);#makeFetchURL=()=>q(URL.name,fr(``,[this.#ids.pathParameter],[this.#ids.searchParamsConst]),Y(this.serverUrl));makeDefaultImplementation=()=>{let e=R.createPropertyAssignment(G(`method`),K(this.#ids.methodParameter,G(`toUpperCase`))()),t=R.createPropertyAssignment(G(`headers`),Dr(this.#ids.hasBodyConst,R.createObjectLiteralExpression([R.createPropertyAssignment(Y(`Content-Type`),Y(y.json))]),this.#ids.undefinedValue)),n=R.createPropertyAssignment(G(`body`),Dr(this.#ids.hasBodyConst,K(JSON[Symbol.toStringTag],G(`stringify`))(this.#ids.paramsArgument),this.#ids.undefinedValue)),r=H(this.#ids.responseConst,R.createAwaitExpression(K(fetch.name)(this.#makeFetchURL(),R.createObjectLiteralExpression([e,t,n])))),i=H(this.#ids.hasBodyConst,R.createLogicalNot(K(R.createArrayLiteralExpression([Y(`get`),Y(`head`),Y(`delete`)]),G(`includes`))(this.#ids.methodParameter))),a=H(this.#ids.searchParamsConst,Dr(this.#ids.hasBodyConst,Y(``),this.#makeSearchParams(this.#ids.paramsArgument))),o=H(this.#ids.contentTypeConst,K(this.#ids.responseConst,G(`headers`),G(`get`))(Y(`content-type`))),s=R.createIfStatement(R.createPrefixUnaryExpression(v.SyntaxKind.ExclamationToken,this.#ids.contentTypeConst),R.createReturnStatement()),c=H(this.#ids.isJsonConst,K(this.#ids.contentTypeConst,G(`startsWith`))(Y(y.json))),l=R.createReturnStatement(K(this.#ids.responseConst,Dr(this.#ids.isJsonConst,Y(G(`json`)),Y(G(`text`))))());return H(this.#ids.defaultImplementationConst,W([this.#ids.methodParameter,this.#ids.pathParameter,this.#ids.paramsArgument],R.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#ids.implementationType})};#makeSubscriptionConstructor=()=>mr(z({request:`K`,params:J(this.interfaces.input,`K`)}),[H(vr(this.#ids.pathParameter,this.#ids.restConst),K(this.#ids.substituteFn)(R.createElementAccessExpression(K(this.#ids.parseRequestFn)(this.#ids.requestParameter),Y(1)),this.#ids.paramsArgument)),H(this.#ids.searchParamsConst,this.#makeSearchParams(this.#ids.restConst)),kr(R.createPropertyAccessExpression(R.createThis(),this.#ids.sourceProp),q(`EventSource`,this.#makeFetchURL()))]);#makeEventNarrow=e=>R.createTypeLiteralNode([gr(G(`event`),e)]);#makeOnMethod=()=>xr(this.#ids.onMethod,z({[this.#ids.eventParameter.text]:`E`,[this.#ids.handlerParameter.text]:jr({[this.#ids.dataParameter.text]:J(Or(`R`,_r(this.#makeEventNarrow(`E`))),X(G(`data`)))},Ar(v.SyntaxKind.VoidKeyword))}),[R.createExpressionStatement(K(R.createThis(),this.#ids.sourceProp,G(`addEventListener`))(this.#ids.eventParameter,W([this.#ids.msgParameter],K(this.#ids.handlerParameter)(K(JSON[Symbol.toStringTag],G(`parse`))(R.createPropertyAccessExpression(R.createParenthesizedExpression(R.createAsExpression(this.#ids.msgParameter,B(MessageEvent.name))),G(`data`))))))),R.createReturnStatement(R.createThis())],{typeParams:{E:J(`R`,X(G(`event`)))}});makeSubscriptionClass=e=>Sr(e,[br(this.#ids.sourceProp,`EventSource`),this.#makeSubscriptionConstructor(),this.#makeOnMethod()],{typeParams:{K:Or(this.requestType.name,R.createTemplateLiteralType(R.createTemplateHead(`get `),[R.createTemplateLiteralTypeSpan(B(v.SyntaxKind.StringKeyword),R.createTemplateTail(``))])),R:Or(J(this.interfaces.positive,`K`),_r(this.#makeEventNarrow(v.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[H(this.#ids.clientConst,q(e)),K(this.#ids.clientConst,this.#ids.provideMethod)(Y(`get /v1/user/retrieve`),R.createObjectLiteralExpression([R.createPropertyAssignment(`id`,Y(`10`))])),K(q(t,Y(`get /v1/events/stream`),R.createObjectLiteralExpression()),this.#ids.onMethod)(Y(`time`),W([`time`],R.createBlock([])))]};const Fr=(t,{onEach:n,rules:r,onMissing:i,ctx:a={}})=>{let o=e(t),s=o&&o in r?r[o]:r[t._zod.def.type],c=e=>Fr(e,{ctx:a,onEach:n,rules:r,onMissing:i}),l=s?s(t,{...a,next:c}):i(t,a),u=n&&n(t,{prev:l,...a});return u?{...l,...u}:l},{factory:Z}=v,Ir={[v.SyntaxKind.AnyKeyword]:``,[v.SyntaxKind.BigIntKeyword]:BigInt(0),[v.SyntaxKind.BooleanKeyword]:!1,[v.SyntaxKind.NumberKeyword]:0,[v.SyntaxKind.ObjectKeyword]:{},[v.SyntaxKind.StringKeyword]:``,[v.SyntaxKind.UndefinedKeyword]:void 0},Lr={name:t.path([`name`,`text`]),type:t.path([`type`]),optional:t.path([`questionToken`])},Rr=({_zod:{def:e}})=>{let t=e.values.map(e=>e===void 0?B(v.SyntaxKind.UndefinedKeyword):X(e));return t.length===1?t[0]:V(t)},zr=({_zod:{def:e}},{next:t})=>{let n=[...e.parts],r=()=>{let e=``;for(;n.length;){let t=n.shift();if(S(t)){n.unshift(t);break}e+=t??``}return e},i=Z.createTemplateHead(r()),a=[];for(;n.length;){let e=t(n.shift()),i=r(),o=n.length?Z.createTemplateMiddle:Z.createTemplateTail;a.push(Z.createTemplateLiteralTypeSpan(e,o(i)))}return a.length?Z.createTemplateLiteralType(i,a):X(i.text)},Br=(e,{isResponse:t,next:r,makeAlias:i})=>{let a=()=>{let i=Object.entries(e._zod.def.shape).map(([e,i])=>{let{description:a,deprecated:o}=n.get(i)||{};return gr(e,r(i),{comment:a,isDeprecated:o,isOptional:(t?i._zod.optout:i._zod.optin)===`optional`})});return Z.createTypeLiteralNode(i)};return Be(e,{io:t?`output`:`input`})?i(e,a):a()},Vr=({_zod:{def:e}},{next:t})=>Z.createArrayTypeNode(t(e.element)),Hr=({_zod:{def:e}})=>V(Object.values(e.entries).map(X)),Ur=({_zod:{def:e}},{next:t})=>V(e.options.map(t)),Wr=e=>Ir?.[e.kind],Gr=({_zod:{def:e}},{next:t})=>V([t(e.innerType),X(null)]),Kr=({_zod:{def:e}},{next:t})=>Z.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:Z.createRestTypeNode(t(e.rest)))),qr=({_zod:{def:e}},{next:t})=>B(`Record`,[e.keyType,e.valueType].map(t)),Jr=t.tryCatch(e=>{if(!e.every(v.isTypeLiteralNode))throw Error(`Not objects`);let n=t.chain(t.prop(`members`),e),r=t.uniqWith((...e)=>{if(!t.eqBy(Lr.name,...e))return!1;if(t.both(t.eqBy(Lr.type),t.eqBy(Lr.optional))(...e))return!0;throw Error(`Has conflicting prop`)},n);return Z.createTypeLiteralNode(r)},(e,t)=>Z.createIntersectionTypeNode(t)),Yr=({_zod:{def:e}},{next:t})=>Jr([e.left,e.right].map(t)),Q=e=>()=>B(e),$=({_zod:{def:e}},{next:t})=>t(e.innerType),Xr=e=>B(e?v.SyntaxKind.UnknownKeyword:v.SyntaxKind.AnyKeyword),Zr=({_zod:{def:e}},{next:t,isResponse:n})=>{let r=e[n?`out`:`in`],i=e[n?`in`:`out`];if(!S(r,`transform`))return t(r);let a=t(i),o=Ce(r,Wr(a)),s={number:v.SyntaxKind.NumberKeyword,bigint:v.SyntaxKind.BigIntKeyword,boolean:v.SyntaxKind.BooleanKeyword,string:v.SyntaxKind.StringKeyword,undefined:v.SyntaxKind.UndefinedKeyword,object:v.SyntaxKind.ObjectKeyword};return B(o&&s[o]||Xr(n))},Qr=()=>X(null),$r=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ei=()=>B(`Buffer`),ti=(e,{next:t})=>t(e._zod.def.shape.raw),ni={string:Q(v.SyntaxKind.StringKeyword),number:Q(v.SyntaxKind.NumberKeyword),bigint:Q(v.SyntaxKind.BigIntKeyword),boolean:Q(v.SyntaxKind.BooleanKeyword),any:Q(v.SyntaxKind.AnyKeyword),undefined:Q(v.SyntaxKind.UndefinedKeyword),[D]:Q(v.SyntaxKind.StringKeyword),[O]:Q(v.SyntaxKind.StringKeyword),never:Q(v.SyntaxKind.NeverKeyword),void:Q(v.SyntaxKind.UndefinedKeyword),unknown:Q(v.SyntaxKind.UnknownKeyword),null:Qr,array:Vr,tuple:Kr,record:qr,object:Br,literal:Rr,template_literal:zr,intersection:Yr,union:Ur,default:$,enum:Hr,optional:$,nonoptional:$,nullable:Gr,catch:$,pipe:Zr,lazy:$r,readonly:$,[E]:ei,[N]:ti},ri=(e,{brandHandling:t,ctx:n})=>Fr(e,{rules:{...t,...ni},onMissing:({},{isResponse:e})=>Xr(e),ctx:n});var ii=class extends Pr{#program=[this.someOfType];#aliases=new Map;#usage=[];#makeAlias(e,t){let n=this.#aliases.get(e)?.name?.text;if(!n){n=`Type${this.#aliases.size+1}`;let r=X(null);this.#aliases.set(e,U(n,r)),this.#aliases.set(e,U(n,t()))}return B(n)}constructor({routing:e,brandHandling:n,variant:i=`client`,clientClassName:a=`Client`,subscriptionClassName:o=`Subscription`,serverUrl:s=`https://example.com`,noContent:c=r.undefined(),hasHeadMethod:l=!0}){super(s);let u={makeAlias:this.#makeAlias.bind(this)},d={brandHandling:n,ctx:{...u,isResponse:!1}},f={brandHandling:n,ctx:{...u,isResponse:!0}},p=(e,n,r)=>{let i=C.bind(null,e,n),{isDeprecated:a,inputSchema:o,tags:s}=r,l=`${e} ${n}`,u=U(i(`input`),ri(o,d),{comment:l});this.#program.push(u);let p=rt.reduce((n,a)=>{let o=r.getResponses(a),s=t.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=we(e,r),u=U(i(a,`variant`,`${t+1}`),ri(s?n:c,f),{comment:l});return this.#program.push(u),o.map(e=>gr(e,u.name))},Array.from(o.entries())),u=Tr(i(a,`response`,`variants`),s,{comment:l});return this.#program.push(u),Object.assign(n,{[a]:u})},{});this.paths.add(n);let m=X(l),ee={input:B(u.name),positive:this.someOf(p.positive),negative:this.someOf(p.negative),response:V([J(this.interfaces.positive,m),J(this.interfaces.negative,m)]),encoded:R.createIntersectionTypeNode([B(p.positive.name),B(p.negative.name)])};this.registry.set(l,{isDeprecated:a,store:ee}),this.tags.set(l,s)};It({routing:e,onEndpoint:l?kt(p):p}),this.#program.unshift(...this.#aliases.values()),this.#program.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),i!==`types`&&(this.#program.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(a),this.makeSubscriptionClass(o)),this.#usage.push(...this.makeUsageStatements(a,o)))}#printUsage(e){return this.#usage.length?this.#usage.map(t=>typeof t==`string`?t:lr(t,e)).join(`
|
|
18
18
|
`):void 0}print(e){let t=this.#printUsage(e),n=t&&v.addSyntheticLeadingComment(v.addSyntheticLeadingComment(R.createEmptyStatement(),v.SyntaxKind.SingleLineCommentTrivia,` Usage example:`),v.SyntaxKind.MultiLineCommentTrivia,`\n${t}`);return this.#program.concat(n||[]).map((t,n)=>lr(t,n<this.#program.length?e:{...e,omitTrailingSemicolon:!0})).join(`
|
|
19
19
|
|
|
20
20
|
`)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=(await xt(`prettier`)).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#printUsage(e);this.#usage=r&&n?[await n(r)]:this.#usage;let i=this.print(e);return n?n(i):i}};const ai=(e,t)=>r.object({data:t,event:r.literal(e),id:r.string().optional(),retry:r.int().positive().optional()}),oi=(e,t,n)=>ai(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "25.3.0
|
|
3
|
+
"version": "25.3.0",
|
|
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": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"node-mocks-http": "^1.17.2",
|
|
39
39
|
"openapi3-ts": "^4.5.0",
|
|
40
40
|
"ramda": "^0.31.3",
|
|
41
|
-
"@express-zod-api/zod-plugin": "^1.2.0
|
|
41
|
+
"@express-zod-api/zod-plugin": "^1.2.0"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@types/compression": "^1.7.5",
|