UNPKG

itty-router

Version:

A tiny, zero-dependency router, designed to make beautiful APIs in any environment.

2 lines (1 loc) 1.73 kB
"use strict";const r=((r="text/plain; charset=utf-8",e)=>(t,o={})=>{if(void 0===t||t instanceof Response)return t;const a=new Response(e?.(t)??t,o.url?void 0:o);return a.headers.set("content-type",r),a})("application/json; charset=utf-8",JSON.stringify),e=r=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[r]||"Unknown Error"),t=(t=500,o)=>{if(t instanceof Error){const{message:r,...a}=t;t=t.status||500,o={error:r||e(t),...a}}return o={status:t,..."object"==typeof o?o:{error:o||e(t)}},r(o,{status:t})},o=r=>{r.proxy=new Proxy(r.proxy??r,{get:(e,t)=>e[t]?.bind?.(r)??e[t]??e?.params?.[t]})};exports.AutoRouter=({format:e=r,missing:a=(()=>t(404)),finally:n=[],before:s=[],...c}={})=>(({base:r="",routes:e=[],...t}={})=>({__proto__:new Proxy({},{get:(t,o,a,n)=>(t,...s)=>e.push([o.toUpperCase?.(),RegExp(`^${(n=(r+t).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),s,n])&&a}),routes:e,...t,async fetch(r,...o){let a,n,s=new URL(r.url),c=r.query={__proto__:null};for(let[r,e]of s.searchParams)c[r]=c[r]?[].concat(c[r],e):e;r:try{for(let e of t.before||[])if(null!=(a=await e(r.proxy??r,...o)))break r;e:for(let[t,c,f,i]of e)if((t==r.method||"ALL"==t)&&(n=s.pathname.match(c))){r.params=n.groups||{},r.route=i;for(let e of f)if(null!=(a=await e(r.proxy??r,...o)))break e}}catch(e){if(!t.catch)throw e;a=await t.catch(e,r.proxy??r,...o)}try{for(let e of t.finally||[])a=await e(a,r.proxy??r,...o)??a}catch(e){if(!t.catch)throw e;a=await t.catch(e,r.proxy??r,...o)}return a}}))({before:[o,...s],catch:t,finally:[(r,...e)=>r??a(...e),e,...n],...c});