UNPKG

express-zod-api

Version:

A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.

1 lines 12.6 kB
import{globalRegistry as e,z as t}from"zod";import*as n from"ramda";import{isPromise as r}from"node:util/types";import i,{isHttpError as a}from"http-errors";import o from"express";const s={json:`application/json`,upload:`multipart/form-data`,raw:`application/octet-stream`,sse:`text/event-stream`,form:`application/x-www-form-urlencoded`},c=[`get`,`post`,`put`,`delete`,`patch`,`query`],l=[...c,`head`],u=Set.prototype.has.bind(new Set(c)),d=t.object({}),f=/:([A-Za-z0-9_]+)/g,ee=e=>e.match(f)?.map(e=>e.slice(1))||[],p=(e,t=1)=>e.replace(f,()=>`:${t++}`),te=e=>{let t=(e.header(`content-type`)||``).toLowerCase().startsWith(s.upload);return`files`in e&&t},ne={get:[`query`,`params`],post:[`body`,`params`,`files`],put:[`body`,`params`],patch:[`body`,`params`],delete:[`query`,`params`],query:[`query`,`body`,`params`]},re=[`body`,`query`,`params`],m=e=>e.method.toLowerCase(),h=(e,t={})=>{if(e===`options`)return[];let n=e===`head`?`get`:u(e)?e:void 0;return(n?t[n]||ne[n]:void 0)||re},g=(e,t={})=>{let n=m(e);return h(n,t).filter(t=>t!==`files`||te(e)).reduce((t,n)=>Object.assign(t,e[n]),{})},_=e=>e instanceof Error?e:e instanceof t.ZodError?new t.ZodRealError(e.issues):Error(String(e)),v=e=>e instanceof t.ZodError?e.issues.map(({path:e,message:n})=>`${e.length?`${t.core.toDotPath(e)}: `:``}${n}`).join(`; `):e.message,y=(e,t)=>S(e)&&`_zod`in e&&(!t||n.path([`_zod`,`def`,`type`],e)===t),b=(e,t,r)=>e.length&&t.length?n.xprod(e,t).map(r):e.concat(t),x=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),ie=(...e)=>{let t=n.chain(e=>e.split(/[^A-Z0-9]/gi),e);return n.chain(e=>e.replaceAll(/[A-Z]+/g,e=>`/${e}`).split(`/`),t).map(x).join(``)},ae=n.tryCatch((e,n)=>typeof t.parse(e,n),n.always(void 0)),S=e=>typeof e==`object`&&!!e,C={_cache:void 0,get env(){return C._cache??=process.env.NODE_ENV??`development`},get isProduction(){return C.env===`production`}},oe=(e,t)=>!!t&&e!==`head`,w=`x-brand`,T=t=>{let{[w]:n}=e.get(t)||{};if(typeof n==`symbol`||typeof n==`string`||typeof n==`number`)return n},E=t=>{let{examples:n}=e.get(t)||{};return Array.isArray(n)?n:[]},D=Symbol(`Buffer`),O=()=>t.custom(e=>Buffer.isBuffer(e),{error:`Expected Buffer`}).meta({[w]:D}),k=Symbol(`DateIn`),se=({examples:e,...n}={})=>t.union([t.iso.date(),t.iso.datetime({local:!0,offset:!0})]).meta({examples:e}).transform(e=>new Date(e)).pipe(t.date()).meta({...n,[w]:k}),A=Symbol(`DateOut`),ce=(e={})=>t.date().transform(e=>e.toISOString()).pipe(t.iso.datetime()).meta({...e,[w]:A});var j=class extends Error{name=`RoutingError`;cause;constructor(e,t,n){super(e),this.cause={method:t,path:n}}},le=class extends Error{name=`DocumentationError`;cause;constructor(e,{method:t,path:n,isResponse:r}){super(e),this.cause=`${r?`Response`:`Input`} schema of an Endpoint assigned to ${t.toUpperCase()} method of ${n} path.`}},M=class extends Error{name=`IOSchemaError`},ue=class extends M{cause;name=`DeepCheckError`;constructor(e){super(`Found`,{cause:e}),this.cause=e}},N=class extends M{cause;name=`OutputValidationError`;constructor(e){let n=new t.ZodError(e.issues.map(({path:e,...t})=>({...t,path:[`output`,...e]})));super(v(n),{cause:e}),this.cause=e}},P=class extends M{cause;name=`InputValidationError`;constructor(e){super(v(e),{cause:e}),this.cause=e}},F=class extends Error{cause;handled;name=`ResultHandlerError`;constructor(e,t){super(v(e),{cause:e}),this.cause=e,this.handled=t}},de=class extends Error{name=`MissingPeerError`;constructor(e){super(`Missing peer dependency: ${e}. Please install it to use the feature.`)}};const I=Symbol(`Form`),fe=e=>(e instanceof t.ZodObject?e:t.object(e)).meta({[w]:I}),L=Symbol(`Upload`),pe=e=>S(e)&&`name`in e&&`encoding`in e&&`mimetype`in e&&`data`in e&&`tempFilePath`in e&&`truncated`in e&&`size`in e&&`md5`in e&&`mv`in e,me=()=>t.custom(e=>pe(e)&&typeof e.name==`string`&&typeof e.encoding==`string`&&typeof e.mimetype==`string`&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath==`string`&&typeof e.truncated==`boolean`&&typeof e.size==`number`&&typeof e.md5==`string`&&typeof e.mv==`function`,{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).meta({[w]:L}),R=Symbol(`Raw`),z=t.object({raw:O()}),he=e=>z.extend(e).meta({[w]:R});function ge(e){return e?he(e):z.meta({[w]:R})}const B=(e,{io:r,condition:i})=>n.tryCatch(()=>void t.toJSONSchema(e,{io:r,unrepresentable:`any`,override:({zodSchema:e})=>{if(i(e))throw new ue(e)}}),e=>e.cause)(),_e=(e,{io:r})=>{let i=[t.toJSONSchema(e,{io:r,unrepresentable:`any`})];for(let e=0;e<i.length;e++){let t=i[e];if(n.is(Object,t)){if(t.$ref===`#`)return!0;i.push(...n.values(t))}n.is(Array,t)&&i.push(...n.values(t))}return!1},ve=Set.prototype.has.bind(new Set([L,R,I])),ye=e=>B(e,{condition:e=>ve(T(e)),io:`input`}),be=new Set([`nan`,`symbol`,`map`,`set`,`bigint`,`void`,`promise`,`never`,`function`]),xe=(e,t)=>B(e,{io:t,condition:e=>{let n=T(e),{type:r}=e._zod.def;return!!(be.has(r)||n===D||t===`input`&&(r===`date`||n===A)||t===`output`&&(n===k||n===R||n===L))}});var V=class e extends Set{constructor(e){if(super(),e)for(let t of e)Set.prototype.add.call(this,t)}add(e){throw TypeError(`Can not add to the read only Set`)}delete(e){throw TypeError(`Can not delete from the read only Set`)}clear(){throw TypeError(`Can not clear the read only Set`)}union(t){return new e(super.union(t))}intersection(t){return new e(super.intersection(t))}difference(t){return new e(super.difference(t))}symmetricDifference(t){return new e(super.symmetricDifference(t))}},Se=class{},H=class extends Se{#e;#t;#n;#r;constructor({input:e,security:t,statusCode:n,handler:r}){super(),this.#e=e,this.#t=t,this.#n=new V(typeof n==`number`?[n]:n),this.#r=r}get security(){return this.#t}get schema(){return this.#e}get statusCodes(){return this.#n}async execute({input:e,...n}){try{let t=await(this.#e||d).parseAsync(e);return this.#r({...n,input:t})}catch(e){throw e instanceof t.ZodError?new P(e):e}}},U=class extends H{constructor(e,{provider:t=()=>({}),transformer:n=e=>e,statusCode:i}={}){super({statusCode:i,handler:async({request:i,response:a})=>{let{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=e=>{if(e&&e instanceof Error)return c(n(e));s(t(i,a))},u=e(i,a,l);return r(u)&&u.catch(l),o}})}};const W={positive:200,negative:400},Ce=Object.keys(W),G=e=>e<400;function we(e){return e instanceof t.ZodType?{schema:e}:e}const Te=(e,{variant:r,args:i})=>{typeof e==`function`&&(e=e(...i));let a={statusCodes:[W[r]],mimeTypes:[s.json]};if(e instanceof t.ZodType)return[{schema:e,...a}];if(Array.isArray(e)&&!e.length)throw new F(Error(`At least one ${r} response schema required.`));let o=(Array.isArray(e)?e:[e]).map(({schema:e,statusCode:t,mimeType:n})=>({schema:e,statusCodes:typeof t==`number`?[t]:t||a.statusCodes,mimeTypes:typeof n==`string`?[n]:n===void 0?a.mimeTypes:n})),c=n.chain(n.prop(`statusCodes`),o),l=c.find(e=>G(e)===(r===`negative`));if(l!==void 0)throw new F(Error(`The status code ${l} is not valid for a ${r} API response.`));if(o.length>1){let e=n.find(e=>c.indexOf(e)!==c.lastIndexOf(e),c);if(e!==void 0)throw new F(Error(`The status code ${e} is used by multiple response schemas.`))}return o},Ee=(e,t,n)=>{let r=new Set(Array.from(t).filter(e=>G(e)===(n===`positive`)));if(!r.size)return e;if(e.length===1)return e.map(e=>({...e,statusCodes:Array.from(r)}));let i=[],a=e.reduce((e,{statusCodes:t,...n})=>{let a=new Set(t).intersection(r);return a.size?(i.push({...n,statusCodes:Array.from(a)}),e.difference(a)):e},new Set(r));if(a.size){let e=Array.from(a).join(`, `),t=a.size>1;throw new F(Error(`The ResultHandler defines multiple ${n} response schemas, but the overriding status code${t?`s`:``} ${e} of the Endpoint ${t?`are`:`is`} not listed for any of them, therefore it is unclear how such override${t?`s`:``} would be handled. Consider adding ${t?`them`:`it`} to ResultHandler.`))}return i},De=(e,t,{url:n},r)=>!e.expose&&t.error(`Server side error`,{error:e,url:n,payload:r}),Oe=e=>a(e)?e:i(e instanceof P?400:500,v(e),{cause:e.cause||e}),ke=e=>C.isProduction&&!e.expose?i(e.statusCode).message:e.message,Ae=e=>Object.entries(e._zod.def.shape).reduce((e,[t,r])=>b(e,E(r).map(n.objOf(t)),([e,t])=>({...e,...t})),[]);var K=class{nest(e){return{...e,"":this}}},je=class r extends K{#e;#t;#n=n.once(()=>{if(E(this.#e.outputSchema).length||!y(this.#e.outputSchema,`object`))return;let t=Ae(this.#e.outputSchema);if(!t.length)return;let n=this.#e.outputSchema.meta();e.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...n,examples:t})});constructor(e){super(),this.#e=e}#r(e){return new r({...this.#e,...e})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get summary(){return this.#e.summary}get methods(){return this.#e.methods}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#e.outputSchema}getProbableRequestType(e){return e===`query`?`form`:this.#t??=(()=>{let e=ye(this.#e.inputSchema);if(e){let t=T(e);if(t===L)return`upload`;if(t===R)return`raw`;if(t===I)return`form`}return`json`})()}getResponses(e){e===`positive`&&this.#n();let t=e===`negative`?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema);return Object.freeze(this.#e.statusCodes.size?Ee(t,this.#e.statusCodes,e):t)}get security(){let e=n.pluck(`security`,this.#e.middlewares||[]);return n.reject(n.isNil,e)}get scopes(){return this.#e.scopes}get tags(){return this.#e.tags}getOperationId(e){return this.#e.getOperationId?.(e)}async#i(e){try{return await this.#e.outputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new N(e):e}}async#a({method:e,logger:t,ctx:n,response:r,...i}){for(let a of this.#e.middlewares||[])if(!(e===`options`&&!(a instanceof U))&&(Object.assign(n,await a.execute({...i,ctx:n,response:r,logger:t})),r.writableEnded)){t.warn(`A middleware has closed the stream. Accumulated context:`,n);break}}async#o({input:e,...n}){let r;try{r=await this.#e.inputSchema.parseAsync(e)}catch(e){throw e instanceof t.ZodError?new P(e):e}return this.#e.handler({...n,input:r})}async#s(e){await this.#e.resultHandler.execute(e)}async execute({request:e,response:t,logger:n,config:r}){let i=m(e),a={},o,s=g(e,r.inputSources);try{if(await this.#a({method:i,input:s,request:e,response:t,logger:n,ctx:a}),t.writableEnded)return;if(i===`options`)return void t.status(200).end();let r=await this.#o({input:s,logger:n,ctx:a});if(t.writableEnded)return;o={output:await this.#i(r),error:null}}catch(e){o={output:null,error:_(e)}}await this.#s({...o,input:s,request:e,response:t,logger:n,ctx:a})}},q=class{#e;constructor(...e){this.#e=e}apply(e,t){return t(e,o.static(...this.#e))}};const J=e=>S(e)&&`or`in e,Y=e=>S(e)&&`and`in e,X=e=>!Y(e)&&!J(e),Me=e=>{let t=n.filter(X,e),r=n.chain(n.prop(`and`),n.filter(Y,e)),[i,a]=n.partition(X,r),o=n.concat(t,i),s=n.filter(J,e);return n.map(n.prop(`or`),n.concat(s,a)).reduce((e,t)=>b(e,n.map(e=>X(e)?[e]:e.and,t),([e,t])=>n.concat(e,t)),n.reject(n.isEmpty,[o]))},Z=(e,t)=>Y(e)?n.chain(e=>Z(e,t),e.and):J(e)?n.chain(e=>Z(e,t),e.or):e.type===t?[e.name]:[],Ne=(e,t)=>new Set(n.chain(e=>Z(e,t),e)),Pe=e=>(t,...n)=>{e(t,...n),t===`get`&&e(`head`,...n)},Fe=e=>{let[t,n]=e.trim().split(/ (.+)/,2);return n&&u(t)?[n,t]:[e]},Ie=e=>e.trim().split(`/`).filter(Boolean).join(`/`),Q=({recognizeMethodDependentRoutes:e=!0},t,n)=>Object.entries(t).map(([t,r])=>{let[i,a]=e&&u(t)&&r instanceof K?[`/`,t]:Fe(t);return[[n||``].concat(Ie(i)||[]).join(`/`)||`/`,r,a]}),Le=(e,t)=>{throw new j(`Route with explicit method can only be assigned with Endpoint`,e,t)},Re=(e,t,n)=>{if(!(!n.size||n.has(e)))throw new j(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},$=(e,t,n)=>{let r=t.includes(`:`)?p(t):t,i=`${e} ${r}`;if(n.has(i))throw new j(`Route has a duplicate: the normalized path "${r}" is already registered`,e,t);n.add(i)},ze=({routing:e,config:t,onEndpoint:n,onStatic:r})=>{let i=Q(t,e),a=new Set;for(let e=0;e<i.length;e++){let[o,s,c]=i[e];if(s instanceof K)if(c)$(c,o,a),Re(c,o,s.methods),n(c,o,s);else{let{methods:e}=s;for(let t of e.size?e:[`get`])$(t,o,a),n(t,o,s)}else c&&Le(c,o),s instanceof q?r&&s.apply(o,r):i.splice(e+1,0,...Q(t,s,o))}};export{x as $,ce as A,_ as B,fe as C,N as D,de as E,D as F,ae as G,h as H,T as I,ie as J,S as K,E as L,se as M,k as N,F as O,O as P,oe as Q,b as R,me as S,P as T,v as U,g as V,ee as W,f as X,p as Y,C as Z,xe as _,q as a,ge as b,ke as c,we as d,l as et,W as f,V as g,H as h,Me as i,A as j,j as k,De as l,U as m,Pe as n,s as nt,je as o,Ce as p,y as q,Ne as r,Oe as s,ze as t,u as tt,Te as u,_e as v,le as w,L as x,R as y,d as z};