Socket
Socket
Sign inDemoInstall

itty-router

Package Overview
Dependencies
Maintainers
2
Versions
265
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

itty-router - npm Package Compare versions

Comparing version 4.2.2 to 4.3.0-next.0

AutoRouter.d.ts

2

createCors.d.ts

@@ -1,2 +0,2 @@

import { IRequest } from './Router';
import { IRequest } from './IttyRouter';
export type CorsOptions = {

@@ -3,0 +3,0 @@ origins?: string[] | ((origin: string) => boolean);

@@ -0,2 +1,4 @@

export * from './IttyRouter';
export * from './Router';
export * from './AutoRouter';
export * from './StatusError';

@@ -3,0 +5,0 @@ export * from './createResponse';

@@ -1,2 +0,2 @@

"use strict";class e extends Error{status;constructor(e=500,t){super("object"==typeof t?t.error:t),"object"==typeof t&&Object.assign(this,t),this.status=e}}const t=(e="text/plain; charset=utf-8",t)=>(o,{headers:s={},...r}={})=>void 0===o||"Response"===o?.constructor.name?o:new Response(t?t(o):o,{headers:{"content-type":e,...s.entries?Object.fromEntries(s):s},...r}),o=t("application/json; charset=utf-8",JSON.stringify),s=e=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[e]||"Unknown Error"),r=t("text/plain; charset=utf-8",String),n=t("text/html"),a=t("image/jpeg"),c=t("image/png"),p=t("image/webp");exports.Router=({base:e="",routes:t=[],...o}={})=>({__proto__:new Proxy({},{get:(o,s,r,n)=>"handle"==s?r.fetch:(o,...a)=>t.push([s.toUpperCase?.(),RegExp(`^${(n=(e+o).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),a,n])&&r}),routes:t,...o,async fetch(e,...o){let s,r,n=new URL(e.url),a=e.query={__proto__:null};for(let[e,t]of n.searchParams)a[e]=a[e]?[].concat(a[e],t):t;for(let[a,c,p,i]of t)if((a==e.method||"ALL"==a)&&(r=n.pathname.match(c))){e.params=r.groups||{},e.route=i;for(let t of p)if(null!=(s=await t(e.proxy??e,...o)))return s}}}),exports.StatusError=e,exports.createCors=(e={})=>{const{origins:t=["*"],maxAge:o,methods:s=["GET"],headers:r={}}=e;let n;const a="function"==typeof t?t:e=>t.includes(e)||t.includes("*"),c={"content-type":"application/json","Access-Control-Allow-Methods":s.join(", "),...r};o&&(c["Access-Control-Max-Age"]=o);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:t,status:o,body:s}=e;return[101,301,302,308].includes(o)||t.get("access-control-allow-origin")?e:new Response(s,{status:o,headers:{...Object.fromEntries(t),...c,...n,"content-type":t.get("content-type")}})},preflight:e=>{const t=[...new Set(["OPTIONS",...s])],o=e.headers.get("origin")||"";if(n=a(o)&&{"Access-Control-Allow-Origin":o},"OPTIONS"===e.method){const o={...c,"Access-Control-Allow-Methods":t.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...n};return new Response(null,{headers:e.headers.get("Origin")&&e.headers.get("Access-Control-Request-Method")&&e.headers.get("Access-Control-Request-Headers")?o:{Allow:t.join(", ")}})}}}},exports.createResponse=t,exports.error=(e=500,t)=>{if(e instanceof Error){const{message:o,...r}=e;e=e.status||500,t={error:o||s(e),...r}}return t={status:e,..."object"==typeof t?t:{error:t||s(e)}},o(t,{status:e})},exports.html=n,exports.jpeg=a,exports.json=o,exports.png=c,exports.status=(e,t)=>new Response(null,{...t,status:e}),exports.text=r,exports.webp=p,exports.withContent=async e=>{e.content=e.body?await e.clone().json().catch((()=>e.clone().formData())).catch((()=>e.text())):void 0},exports.withCookies=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[t,o])=>o?(e[t]=o,e):e),{})},exports.withParams=e=>{e.proxy=new Proxy(e.proxy||e,{get:(t,o)=>void 0!==t[o]?t[o].bind?.(e)||t[o]:t?.params?.[o]})};
"use strict";const e=({base:e="",routes:t=[],...r}={})=>({__proto__:new Proxy({},{get:(r,o,s,n)=>"handle"==o?s.fetch:(r,...a)=>t.push([o.toUpperCase?.(),RegExp(`^${(n=(e+r).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),a,n])&&s}),routes:t,...r,async fetch(e,...o){let s,n,a=new URL(e.url),c=e.query={__proto__:null};for(let[e,t]of a.searchParams)c[e]=c[e]?[].concat(c[e],t):t;e:try{for(let t of r.before||[])if(null!=(s=await t(e.proxy??e,...o)))break e;t:for(let[r,c,p,l]of t)if((r==e.method||"ALL"==r)&&(n=a.pathname.match(c))){e.params=n.groups||{},e.route=l;for(let t of p)if(null!=(s=await t(e.proxy??e,...o)))break t}}catch(t){if(!r.onError)throw t;for(let n of r.onError)s=await n(s??t,e.proxy??e,...o)??s}for(let t of r.after||[])s=await t(s,e.proxy??e,...o)??s;return s}}),t=(e="text/plain; charset=utf-8",t)=>(r,{headers:o={},...s}={})=>void 0===r||"Response"===r?.constructor.name?r:new Response(t?t(r):r,{headers:{"content-type":e,...o.entries?Object.fromEntries(o):o},...s}),r=t("application/json; charset=utf-8",JSON.stringify),o=e=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[e]||"Unknown Error"),s=(e=500,t)=>{if(e instanceof Error){const{message:r,...s}=e;e=e.status||500,t={error:r||o(e),...s}}return t={status:e,..."object"==typeof t?t:{error:t||o(e)}},r(t,{status:e})},n=e=>{e.proxy=new Proxy(e.proxy||e,{get:(t,r)=>void 0!==t[r]?t[r].bind?.(e)||t[r]:t?.params?.[r]})};class a extends Error{status;constructor(e=500,t){super("object"==typeof t?t.error:t),"object"==typeof t&&Object.assign(this,t),this.status=e}}const c=t("text/plain; charset=utf-8",String),p=t("text/html"),l=t("image/jpeg"),i=t("image/png"),u=t("image/webp");exports.AutoRouter=({format:t=r,missing:o=(()=>s(404)),after:a=[],before:c=[],...p}={})=>e({before:[n,...c],onError:[s],after:[(e,...t)=>e??o(e,...t),t,...a],...p}),exports.IttyRouter=({base:e="",routes:t=[],...r}={})=>({__proto__:new Proxy({},{get:(r,o,s,n)=>(r,...a)=>t.push([o.toUpperCase?.(),RegExp(`^${(n=(e+r).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),a,n])&&s}),routes:t,...r,async fetch(e,...r){let o,s,n=new URL(e.url),a=e.query={__proto__:null};for(let[e,t]of n.searchParams)a[e]=a[e]?[].concat(a[e],t):t;for(let[a,c,p,l]of t)if((a==e.method||"ALL"==a)&&(s=n.pathname.match(c))){e.params=s.groups||{},e.route=l;for(let t of p)if(null!=(o=await t(e.proxy??e,...r)))return o}}}),exports.Router=e,exports.StatusError=a,exports.createCors=(e={})=>{const{origins:t=["*"],maxAge:r,methods:o=["GET"],headers:s={}}=e;let n;const a="function"==typeof t?t:e=>t.includes(e)||t.includes("*"),c={"content-type":"application/json","Access-Control-Allow-Methods":o.join(", "),...s};r&&(c["Access-Control-Max-Age"]=r);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:t,status:r,body:o}=e;return[101,301,302,308].includes(r)||t.get("access-control-allow-origin")?e:new Response(o,{status:r,headers:{...Object.fromEntries(t),...c,...n,"content-type":t.get("content-type")}})},preflight:e=>{const t=[...new Set(["OPTIONS",...o])],r=e.headers.get("origin")||"";if(n=a(r)&&{"Access-Control-Allow-Origin":r},"OPTIONS"===e.method){const r={...c,"Access-Control-Allow-Methods":t.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...n};return new Response(null,{headers:e.headers.get("Origin")&&e.headers.get("Access-Control-Request-Method")&&e.headers.get("Access-Control-Request-Headers")?r:{Allow:t.join(", ")}})}}}},exports.createResponse=t,exports.error=s,exports.html=p,exports.jpeg=l,exports.json=r,exports.png=i,exports.status=(e,t)=>new Response(null,{...t,status:e}),exports.text=c,exports.webp=u,exports.withContent=async e=>{e.content=await e.clone().json().catch((()=>e.clone().formData())).catch((()=>e.text()))},exports.withCookies=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[t,r])=>r?(e[t]=r,e):e),{})},exports.withParams=n;
//# sourceMappingURL=index.js.map
{
"name": "itty-router",
"version": "4.2.2",
"version": "4.3.0-next.0",
"description": "A tiny, zero-dependency router, designed to make beautiful APIs in any environment.",

@@ -14,2 +14,7 @@ "main": "./index.js",

},
"./AutoRouter": {
"import": "./AutoRouter.mjs",
"require": "./AutoRouter.js",
"types": "./AutoRouter.d.ts"
},
"./createCors": {

@@ -35,2 +40,7 @@ "import": "./createCors.mjs",

},
"./IttyRouter": {
"import": "./IttyRouter.mjs",
"require": "./IttyRouter.js",
"types": "./IttyRouter.d.ts"
},
"./jpeg": {

@@ -37,0 +47,0 @@ "import": "./jpeg.mjs",

@@ -1,55 +0,14 @@

export type GenericTraps = {
[key: string]: any;
};
export type RequestLike = {
method: string;
url: string;
} & GenericTraps;
export type IRequestStrict = {
method: string;
url: string;
route: string;
params: {
[key: string]: string;
};
query: {
[key: string]: string | string[] | undefined;
};
proxy?: any;
} & Request;
export type IRequest = IRequestStrict & GenericTraps;
import { Equal, IRequest, IttyRouterOptions, IttyRouterType, Route, RouteHandler, UniversalRoute } from './IttyRouter';
export type ResponseHandler<ResponseType = any, RequestType = IRequest, Args extends any[] = any[]> = (response: ResponseType, request: RequestType, ...args: Args) => any;
export type ErrorHandler<ErrorOrResponse = Error, RequestType = IRequest, Args extends any[] = any[]> = (response: ErrorOrResponse, request: RequestType, ...args: Args) => any;
export type RouterType<R = Route, Args extends any[] = any[]> = {
before?: RouteHandler[];
onError?: ErrorHandler[];
after?: ResponseHandler[];
} & IttyRouterType<R, Args>;
export type RouterOptions = {
base?: string;
routes?: RouteEntry[];
} & Record<string, any>;
export type RouteHandler<I = IRequest, A extends any[] = any[]> = {
(request: I, ...args: A): any;
};
export type RouteEntry = [
httpMethod: string,
match: RegExp,
handlers: RouteHandler[],
path?: string
];
export type Route = <RequestType = IRequest, Args extends any[] = any[], RT = RouterType>(path: string, ...handlers: RouteHandler<RequestType, Args>[]) => RT;
export type UniversalRoute<RequestType = IRequest, Args extends any[] = any[]> = (path: string, ...handlers: RouteHandler<RequestType, Args>[]) => RouterType<UniversalRoute<RequestType, Args>, Args>;
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
export type CustomRoutes<R = Route> = {
[key: string]: R;
};
export type RouterType<R = Route, Args extends any[] = any[]> = {
__proto__: RouterType<R>;
routes: RouteEntry[];
fetch: <A extends any[] = Args>(request: RequestLike, ...extra: Equal<R, Args> extends true ? A : Args) => Promise<any>;
handle: <A extends any[] = Args>(request: RequestLike, ...extra: Equal<R, Args> extends true ? A : Args) => Promise<any>;
all: R;
delete: R;
get: R;
head: R;
options: R;
patch: R;
post: R;
put: R;
} & CustomRoutes<R> & Record<string, any>;
before?: RouteHandler[];
onError?: ErrorHandler[];
after?: ResponseHandler[];
} & IttyRouterOptions;
export declare const Router: <RequestType = IRequest, Args extends any[] = any[], RouteType = Equal<RequestType, IRequest> extends true ? Route : UniversalRoute<RequestType, Args>>({ base, routes, ...other }?: RouterOptions) => RouterType<RouteType, Args>;
export {};

@@ -1,2 +0,2 @@

"use strict";exports.Router=({base:e="",routes:r=[],...t}={})=>({__proto__:new Proxy({},{get:(t,o,a,p)=>"handle"==o?a.fetch:(t,...l)=>r.push([o.toUpperCase?.(),RegExp(`^${(p=(e+t).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),l,p])&&a}),routes:r,...t,async fetch(e,...t){let o,a,p=new URL(e.url),l=e.query={__proto__:null};for(let[e,r]of p.searchParams)l[e]=l[e]?[].concat(l[e],r):r;for(let[l,c,s,u]of r)if((l==e.method||"ALL"==l)&&(a=p.pathname.match(c))){e.params=a.groups||{},e.route=u;for(let r of s)if(null!=(o=await r(e.proxy??e,...t)))return o}}});
"use strict";exports.Router=({base:r="",routes:e=[],...o}={})=>({__proto__:new Proxy({},{get:(o,t,a,f)=>"handle"==t?a.fetch:(o,...l)=>e.push([t.toUpperCase?.(),RegExp(`^${(f=(r+o).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),l,f])&&a}),routes:e,...o,async fetch(r,...t){let a,f,l=new URL(r.url),p=r.query={__proto__:null};for(let[r,e]of l.searchParams)p[r]=p[r]?[].concat(p[r],e):e;r:try{for(let e of o.before||[])if(null!=(a=await e(r.proxy??r,...t)))break r;e:for(let[o,p,c,s]of e)if((o==r.method||"ALL"==o)&&(f=l.pathname.match(p))){r.params=f.groups||{},r.route=s;for(let e of c)if(null!=(a=await e(r.proxy??r,...t)))break e}}catch(e){if(!o.onError)throw e;for(let f of o.onError)a=await f(a??e,r.proxy??r,...t)??a}for(let e of o.after||[])a=await e(a,r.proxy??r,...t)??a;return a}});
//# sourceMappingURL=Router.js.map

@@ -1,2 +0,2 @@

import { IRequest, IRequestStrict } from './Router';
import { IRequest, IRequestStrict } from './IttyRouter';
export type HasContent<ContentType> = {

@@ -3,0 +3,0 @@ content: ContentType;

@@ -1,2 +0,2 @@

"use strict";exports.withContent=async t=>{t.content=t.body?await t.clone().json().catch((()=>t.clone().formData())).catch((()=>t.text())):void 0};
"use strict";exports.withContent=async t=>{t.content=await t.clone().json().catch((()=>t.clone().formData())).catch((()=>t.text()))};
//# sourceMappingURL=withContent.js.map

@@ -1,2 +0,2 @@

import { IRequest } from './Router';
import { IRequest } from './IttyRouter';
export declare const withCookies: (r: IRequest) => void;

@@ -1,2 +0,2 @@

import { IRequest } from './Router';
import { IRequest } from './IttyRouter';
export declare const withParams: (request: IRequest) => void;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc