itty-router 4.0.11 → 4.0.13

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.
Files changed (71) hide show
  1. package/Router.js +1 -37
  2. package/Router.mjs +1 -0
  3. package/StatusError.js +1 -10
  4. package/StatusError.mjs +1 -0
  5. package/createCors.js +1 -66
  6. package/createCors.mjs +1 -0
  7. package/createResponse.d.ts +1 -1
  8. package/createResponse.js +1 -14
  9. package/createResponse.mjs +1 -0
  10. package/error.js +1 -42
  11. package/error.mjs +1 -0
  12. package/html.js +1 -16
  13. package/html.mjs +1 -0
  14. package/index.js +1 -189
  15. package/index.mjs +1 -0
  16. package/jpeg.js +1 -16
  17. package/jpeg.mjs +1 -0
  18. package/json.js +1 -16
  19. package/json.mjs +1 -0
  20. package/package.json +104 -16
  21. package/png.js +1 -16
  22. package/png.mjs +1 -0
  23. package/status.d.ts +1 -1
  24. package/status.js +1 -3
  25. package/status.mjs +1 -0
  26. package/text.js +1 -3
  27. package/text.mjs +1 -0
  28. package/webp.js +1 -16
  29. package/webp.mjs +1 -0
  30. package/websocket.js +1 -20
  31. package/websocket.mjs +1 -0
  32. package/withContent.js +1 -7
  33. package/withContent.mjs +1 -0
  34. package/withCookies.js +1 -9
  35. package/withCookies.mjs +1 -0
  36. package/withParams.js +1 -12
  37. package/withParams.mjs +1 -0
  38. package/cjs/Router.d.ts +0 -49
  39. package/cjs/Router.js +0 -39
  40. package/cjs/StatusError.d.ts +0 -10
  41. package/cjs/StatusError.js +0 -12
  42. package/cjs/createCors.d.ts +0 -12
  43. package/cjs/createCors.js +0 -68
  44. package/cjs/createResponse.d.ts +0 -7
  45. package/cjs/createResponse.js +0 -16
  46. package/cjs/error.d.ts +0 -11
  47. package/cjs/error.js +0 -44
  48. package/cjs/html.d.ts +0 -1
  49. package/cjs/html.js +0 -18
  50. package/cjs/index.d.ts +0 -15
  51. package/cjs/index.js +0 -205
  52. package/cjs/jpeg.d.ts +0 -1
  53. package/cjs/jpeg.js +0 -18
  54. package/cjs/json.d.ts +0 -1
  55. package/cjs/json.js +0 -18
  56. package/cjs/png.d.ts +0 -1
  57. package/cjs/png.js +0 -18
  58. package/cjs/status.d.ts +0 -1
  59. package/cjs/status.js +0 -5
  60. package/cjs/text.d.ts +0 -1
  61. package/cjs/text.js +0 -5
  62. package/cjs/webp.d.ts +0 -1
  63. package/cjs/webp.js +0 -18
  64. package/cjs/websocket.d.ts +0 -1
  65. package/cjs/websocket.js +0 -22
  66. package/cjs/withContent.d.ts +0 -2
  67. package/cjs/withContent.js +0 -9
  68. package/cjs/withCookies.d.ts +0 -2
  69. package/cjs/withCookies.js +0 -11
  70. package/cjs/withParams.d.ts +0 -2
  71. package/cjs/withParams.js +0 -14
package/png.js CHANGED
@@ -1,16 +1 @@
1
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
2
- const { headers = {}, ...rest } = options;
3
- if (body?.constructor.name === 'Response')
4
- return body;
5
- return new Response(transform ? transform(body) : body, {
6
- headers: {
7
- 'content-type': format,
8
- ...headers,
9
- },
10
- ...rest,
11
- });
12
- };
13
-
14
- const png = createResponse('image/png');
15
-
16
- export { png };
1
+ "use strict";const e=((e="text/plain; charset=utf-8",t)=>(n,s)=>{const{headers:r={},...o}=s||{};return"Response"===n?.constructor.name?n:new Response(t?t(n):n,{headers:{"content-type":e,...r},...o})})("image/png");exports.png=e;
package/png.mjs ADDED
@@ -0,0 +1 @@
1
+ const e=((e="text/plain; charset=utf-8",t)=>(n,s)=>{const{headers:o={},...r}=s||{};return"Response"===n?.constructor.name?n:new Response(t?t(n):n,{headers:{"content-type":e,...o},...r})})("image/png");export{e as png};
package/status.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const status: (status: number) => Response;
1
+ export declare const status: (status: number, options?: ResponseInit) => Response;
package/status.js CHANGED
@@ -1,3 +1 @@
1
- const status = (status) => new Response(null, { status });
2
-
3
- export { status };
1
+ "use strict";exports.status=(s,t)=>new Response(null,{...t,status:s});
package/status.mjs ADDED
@@ -0,0 +1 @@
1
+ const s=(s,e)=>new Response(null,{...e,status:s});export{s as status};
package/text.js CHANGED
@@ -1,3 +1 @@
1
- const text = (message, options) => new Response(message, options);
2
-
3
- export { text };
1
+ "use strict";exports.text=(e,s)=>new Response(e,s);
package/text.mjs ADDED
@@ -0,0 +1 @@
1
+ const e=(e,n)=>new Response(e,n);export{e as text};
package/webp.js CHANGED
@@ -1,16 +1 @@
1
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
2
- const { headers = {}, ...rest } = options;
3
- if (body?.constructor.name === 'Response')
4
- return body;
5
- return new Response(transform ? transform(body) : body, {
6
- headers: {
7
- 'content-type': format,
8
- ...headers,
9
- },
10
- ...rest,
11
- });
12
- };
13
-
14
- const webp = createResponse('image/webp');
15
-
16
- export { webp };
1
+ "use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,n)=>{const{headers:r={},...o}=n||{};return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...r},...o})})("image/webp");exports.webp=e;
package/webp.mjs ADDED
@@ -0,0 +1 @@
1
+ const e=((e="text/plain; charset=utf-8",t)=>(n,s)=>{const{headers:o={},...r}=s||{};return"Response"===n?.constructor.name?n:new Response(t?t(n):n,{headers:{"content-type":e,...o},...r})})("image/webp");export{e as webp};
package/websocket.js CHANGED
@@ -1,20 +1 @@
1
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
2
- const { headers = {}, ...rest } = options;
3
- if (body?.constructor.name === 'Response')
4
- return body;
5
- return new Response(transform ? transform(body) : body, {
6
- headers: {
7
- 'content-type': format,
8
- ...headers,
9
- },
10
- ...rest,
11
- });
12
- };
13
-
14
- const websocket = (client, options = {}) => createResponse()(null, {
15
- status: 101,
16
- webSocket: client,
17
- ...options,
18
- });
19
-
20
- export { websocket };
1
+ "use strict";exports.websocket=(e,t={})=>((e="text/plain; charset=utf-8",t)=>(s,n)=>{const{headers:o={},...r}=n||{};return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...o},...r})})()(null,{status:101,webSocket:e,...t});
package/websocket.mjs ADDED
@@ -0,0 +1 @@
1
+ const e=(e,t={})=>((e="text/plain; charset=utf-8",t)=>(n,s)=>{const{headers:o={},...r}=s||{};return"Response"===n?.constructor.name?n:new Response(t?t(n):n,{headers:{"content-type":e,...o},...r})})()(null,{status:101,webSocket:e,...t});export{e as websocket};
package/withContent.js CHANGED
@@ -1,7 +1 @@
1
- // withContent - embeds any request body as request.content
2
- const withContent = async (request) => {
3
- if (request.headers.get('content-type')?.includes('json'))
4
- request.content = await request.json();
5
- };
6
-
7
- export { withContent };
1
+ "use strict";exports.withContent=async t=>{t.headers.get("content-type")?.includes("json")&&(t.content=await t.json())};
@@ -0,0 +1 @@
1
+ const n=async n=>{n.headers.get("content-type")?.includes("json")&&(n.content=await n.json())};export{n as withContent};
package/withCookies.js CHANGED
@@ -1,9 +1 @@
1
- // withCookies - embeds cookies object into the request
2
- const withCookies = (r) => {
3
- r.cookies = (r.headers.get('Cookie') || '')
4
- .split(/;\s*/)
5
- .map((p) => p.split(/=(.+)/))
6
- .reduce((a, [k, v]) => (v ? ((a[k] = v), a) : a), {});
7
- };
8
-
9
- export { withCookies };
1
+ "use strict";exports.withCookies=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[s,i])=>i?(e[s]=i,e):e),{})};
@@ -0,0 +1 @@
1
+ const e=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[o,s])=>s?(e[o]=s,e):e),{})};export{e as withCookies};
package/withParams.js CHANGED
@@ -1,12 +1 @@
1
- const withParams = (request) => {
2
- request.proxy = new Proxy(request.proxy || request, {
3
- get: (obj, prop) => {
4
- let p;
5
- if ((p = obj[prop]) !== undefined)
6
- return p.bind?.(request) || p;
7
- return obj?.params?.[prop];
8
- },
9
- });
10
- };
11
-
12
- export { withParams };
1
+ "use strict";exports.withParams=r=>{r.proxy=new Proxy(r.proxy||r,{get:(t,e)=>{let o;return void 0!==(o=t[e])?o.bind?.(r)||o:t?.params?.[e]}})};
package/withParams.mjs ADDED
@@ -0,0 +1 @@
1
+ const r=r=>{r.proxy=new Proxy(r.proxy||r,{get:(o,e)=>{let t;return void 0!==(t=o[e])?t.bind?.(r)||t:o?.params?.[e]}})};export{r as withParams};
package/cjs/Router.d.ts DELETED
@@ -1,49 +0,0 @@
1
- export type GenericTraps = {
2
- [key: string]: any;
3
- };
4
- export type RequestLike = {
5
- method: string;
6
- url: string;
7
- } & GenericTraps;
8
- export type IRequestStrict = {
9
- method: string;
10
- url: string;
11
- route: string;
12
- params: {
13
- [key: string]: string;
14
- };
15
- query: {
16
- [key: string]: string | string[] | undefined;
17
- };
18
- proxy?: any;
19
- } & Request;
20
- export type IRequest = IRequestStrict & GenericTraps;
21
- export type RouterOptions = {
22
- base?: string;
23
- routes?: RouteEntry[];
24
- };
25
- export type RouteHandler<I = IRequest, A extends any[] = any[]> = {
26
- (request: I, ...args: A): any;
27
- };
28
- export type RouteEntry = [string, RegExp, RouteHandler[], string];
29
- export type Route = <RequestType = IRequest, Args extends any[] = any[], RT = RouterType>(path: string, ...handlers: RouteHandler<RequestType, Args>[]) => RT;
30
- export type UniversalRoute<RequestType = IRequest, Args extends any[] = any[]> = (path: string, ...handlers: RouteHandler<RequestType, Args>[]) => RouterType<UniversalRoute<RequestType, Args>, Args>;
31
- type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
32
- export type CustomRoutes<R = Route> = {
33
- [key: string]: R;
34
- };
35
- export type RouterType<R = Route, Args extends any[] = any[]> = {
36
- __proto__: RouterType<R>;
37
- routes: RouteEntry[];
38
- handle: <A extends any[] = Args>(request: RequestLike, ...extra: Equal<R, Args> extends true ? A : Args) => Promise<any>;
39
- all: R;
40
- delete: R;
41
- get: R;
42
- head: R;
43
- options: R;
44
- patch: R;
45
- post: R;
46
- put: R;
47
- } & CustomRoutes<R>;
48
- export declare const Router: <RequestType = IRequest, Args extends any[] = any[], RouteType = Equal<RequestType, IRequest> extends true ? Route : UniversalRoute<RequestType, Args>>({ base, routes }?: RouterOptions) => RouterType<RouteType, Args>;
49
- export {};
package/cjs/Router.js DELETED
@@ -1,39 +0,0 @@
1
- 'use strict';
2
-
3
- const Router = ({ base = '', routes = [] } = {}) =>
4
- // @ts-expect-error TypeScript doesn't know that Proxy makes this work
5
- ({
6
- __proto__: new Proxy({}, {
7
- // @ts-expect-error (we're adding an expected prop "path" to the get)
8
- get: (target, prop, receiver, path) => (route, ...handlers) => routes.push([
9
- prop.toUpperCase(),
10
- RegExp(`^${(path = (base + '/' + route).replace(/\/+(\/|$)/g, '$1')) // strip double & trailing splash
11
- .replace(/(\/?\.?):(\w+)\+/g, '($1(?<$2>*))') // greedy params
12
- .replace(/(\/?\.?):(\w+)/g, '($1(?<$2>[^$1/]+?))') // named params and image format
13
- .replace(/\./g, '\\.') // dot in path
14
- .replace(/(\/?)\*/g, '($1.*)?') // wildcard
15
- }/*$`),
16
- handlers,
17
- path, // embed clean route path
18
- ]) && receiver
19
- }),
20
- routes,
21
- async handle(request, ...args) {
22
- let response, match, url = new URL(request.url), query = request.query = { __proto__: null };
23
- for (let [k, v] of url.searchParams) {
24
- query[k] = query[k] === undefined ? v : [query[k], v].flat();
25
- }
26
- for (let [method, regex, handlers, path] of routes) {
27
- if ((method === request.method || method === 'ALL') && (match = url.pathname.match(regex))) {
28
- request.params = match.groups || {}; // embed params in request
29
- request.route = path; // embed route path in request
30
- for (let handler of handlers) {
31
- if ((response = await handler(request.proxy || request, ...args)) !== undefined)
32
- return response;
33
- }
34
- }
35
- }
36
- }
37
- });
38
-
39
- exports.Router = Router;
@@ -1,10 +0,0 @@
1
- type StatusErrorObject = {
2
- error?: string;
3
- [key: string]: any;
4
- };
5
- export declare class StatusError extends Error {
6
- status: number;
7
- [key: string]: any;
8
- constructor(status?: number, body?: StatusErrorObject | string);
9
- }
10
- export {};
@@ -1,12 +0,0 @@
1
- 'use strict';
2
-
3
- class StatusError extends Error {
4
- status;
5
- constructor(status = 500, body) {
6
- super(typeof body === 'object' ? body.error : body);
7
- typeof body === 'object' && Object.assign(this, body);
8
- this.status = status;
9
- }
10
- }
11
-
12
- exports.StatusError = StatusError;
@@ -1,12 +0,0 @@
1
- import { IRequest } from './Router';
2
- interface CorsOptions {
3
- origins?: string[];
4
- maxAge?: number;
5
- methods?: string[];
6
- headers?: any;
7
- }
8
- export declare const createCors: (options?: CorsOptions) => {
9
- corsify: (response: Response) => Response;
10
- preflight: (r: IRequest) => Response | undefined;
11
- };
12
- export {};
package/cjs/createCors.js DELETED
@@ -1,68 +0,0 @@
1
- 'use strict';
2
-
3
- // Create CORS function with default options.
4
- const createCors = (options = {}) => {
5
- // Destructure and set defaults for options.
6
- const { origins = ['*'], maxAge, methods = ['GET'], headers = {} } = options;
7
- let allowOrigin;
8
- // Initial response headers.
9
- const rHeaders = {
10
- 'content-type': 'application/json',
11
- 'Access-Control-Allow-Methods': methods.join(', '),
12
- ...headers,
13
- };
14
- // Set max age if provided.
15
- if (maxAge)
16
- rHeaders['Access-Control-Max-Age'] = maxAge;
17
- // Pre-flight function.
18
- const preflight = (r) => {
19
- // Use methods set.
20
- const useMethods = [...new Set(['OPTIONS', ...methods])];
21
- const origin = r.headers.get('origin') || '';
22
- // Set allowOrigin globally.
23
- allowOrigin = (origins.includes(origin) || origins.includes('*')) && {
24
- 'Access-Control-Allow-Origin': origin,
25
- };
26
- // Check if method is OPTIONS.
27
- if (r.method === 'OPTIONS') {
28
- const reqHeaders = {
29
- ...rHeaders,
30
- 'Access-Control-Allow-Methods': useMethods.join(', '),
31
- 'Access-Control-Allow-Headers': r.headers.get('Access-Control-Request-Headers'),
32
- ...allowOrigin,
33
- };
34
- // Handle CORS pre-flight request.
35
- return new Response(null, {
36
- headers: r.headers.get('Origin') &&
37
- r.headers.get('Access-Control-Request-Method') &&
38
- r.headers.get('Access-Control-Request-Headers')
39
- ? reqHeaders
40
- : { Allow: useMethods.join(', ') },
41
- });
42
- }
43
- };
44
- // Corsify function.
45
- const corsify = (response) => {
46
- if (!response)
47
- throw new Error('No fetch handler responded and no upstream to proxy to specified.');
48
- const { headers, status, body } = response;
49
- // Bypass for protocol shifts or redirects, or if CORS is already set.
50
- if ([101, 301, 302, 308].includes(status) ||
51
- headers.get('access-control-allow-origin'))
52
- return response;
53
- // Return new response with CORS headers.
54
- return new Response(body, {
55
- status,
56
- headers: {
57
- ...Object.fromEntries(headers),
58
- ...rHeaders,
59
- ...allowOrigin,
60
- 'content-type': headers.get('content-type'),
61
- },
62
- });
63
- };
64
- // Return corsify and preflight methods.
65
- return { corsify, preflight };
66
- };
67
-
68
- exports.createCors = createCors;
@@ -1,7 +0,0 @@
1
- export interface ResponseFormatter {
2
- (body?: any, options?: object): Response;
3
- }
4
- export interface BodyTransformer {
5
- (body: any): string;
6
- }
7
- export declare const createResponse: (format?: string, transform?: BodyTransformer) => ResponseFormatter;
@@ -1,16 +0,0 @@
1
- 'use strict';
2
-
3
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
4
- const { headers = {}, ...rest } = options;
5
- if (body?.constructor.name === 'Response')
6
- return body;
7
- return new Response(transform ? transform(body) : body, {
8
- headers: {
9
- 'content-type': format,
10
- ...headers,
11
- },
12
- ...rest,
13
- });
14
- };
15
-
16
- exports.createResponse = createResponse;
package/cjs/error.d.ts DELETED
@@ -1,11 +0,0 @@
1
- interface ErrorLike extends Error {
2
- status?: number;
3
- [any: string]: any;
4
- }
5
- export type ErrorBody = string | object;
6
- export interface ErrorFormatter {
7
- (statusCode?: number, body?: ErrorBody): Response;
8
- (error: ErrorLike): Response;
9
- }
10
- export declare const error: ErrorFormatter;
11
- export {};
package/cjs/error.js DELETED
@@ -1,44 +0,0 @@
1
- 'use strict';
2
-
3
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
4
- const { headers = {}, ...rest } = options;
5
- if (body?.constructor.name === 'Response')
6
- return body;
7
- return new Response(transform ? transform(body) : body, {
8
- headers: {
9
- 'content-type': format,
10
- ...headers,
11
- },
12
- ...rest,
13
- });
14
- };
15
-
16
- const json = createResponse('application/json; charset=utf-8', JSON.stringify);
17
-
18
- const getMessage = (code) => {
19
- return ({
20
- 400: 'Bad Request',
21
- 401: 'Unauthorized',
22
- 403: 'Forbidden',
23
- 404: 'Not Found',
24
- 500: 'Internal Server Error',
25
- }[code] || 'Unknown Error');
26
- };
27
- const error = (a = 500, b) => {
28
- // handle passing an Error | StatusError directly in
29
- if (a instanceof Error) {
30
- const { message, ...err } = a;
31
- a = a.status || 500;
32
- b = {
33
- error: message || getMessage(a),
34
- ...err,
35
- };
36
- }
37
- b = {
38
- status: a,
39
- ...(typeof b === 'object' ? b : { error: b || getMessage(a) }),
40
- };
41
- return json(b, { status: a });
42
- };
43
-
44
- exports.error = error;
package/cjs/html.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const html: import("./createResponse").ResponseFormatter;
package/cjs/html.js DELETED
@@ -1,18 +0,0 @@
1
- 'use strict';
2
-
3
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
4
- const { headers = {}, ...rest } = options;
5
- if (body?.constructor.name === 'Response')
6
- return body;
7
- return new Response(transform ? transform(body) : body, {
8
- headers: {
9
- 'content-type': format,
10
- ...headers,
11
- },
12
- ...rest,
13
- });
14
- };
15
-
16
- const html = createResponse('text/html');
17
-
18
- exports.html = html;
package/cjs/index.d.ts DELETED
@@ -1,15 +0,0 @@
1
- export * from './Router';
2
- export * from './StatusError';
3
- export * from './createResponse';
4
- export * from './error';
5
- export * from './status';
6
- export * from './text';
7
- export * from './json';
8
- export * from './html';
9
- export * from './jpeg';
10
- export * from './png';
11
- export * from './webp';
12
- export * from './withContent';
13
- export * from './withCookies';
14
- export * from './withParams';
15
- export * from './createCors';