itty-router 4.0.10 → 4.0.11-next.1

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 (69) hide show
  1. package/Router.js +39 -1
  2. package/Router.mjs +37 -0
  3. package/StatusError.js +12 -1
  4. package/StatusError.mjs +10 -0
  5. package/createCors.js +68 -1
  6. package/createCors.mjs +66 -0
  7. package/createResponse.js +16 -1
  8. package/createResponse.mjs +14 -0
  9. package/error.js +44 -1
  10. package/error.mjs +42 -0
  11. package/html.js +18 -1
  12. package/html.mjs +16 -0
  13. package/index.js +205 -1
  14. package/index.mjs +189 -0
  15. package/jpeg.js +18 -1
  16. package/jpeg.mjs +16 -0
  17. package/json.js +18 -1
  18. package/json.mjs +16 -0
  19. package/package.json +8 -84
  20. package/png.js +18 -1
  21. package/png.mjs +16 -0
  22. package/status.js +5 -1
  23. package/status.mjs +3 -0
  24. package/text.js +5 -1
  25. package/text.mjs +3 -0
  26. package/webp.js +18 -1
  27. package/webp.mjs +16 -0
  28. package/websocket.js +22 -1
  29. package/websocket.mjs +20 -0
  30. package/withContent.js +9 -1
  31. package/withContent.mjs +7 -0
  32. package/withCookies.js +11 -1
  33. package/withCookies.mjs +9 -0
  34. package/withParams.js +14 -1
  35. package/withParams.mjs +12 -0
  36. package/cjs/Router.d.ts +0 -49
  37. package/cjs/Router.js +0 -1
  38. package/cjs/StatusError.d.ts +0 -10
  39. package/cjs/StatusError.js +0 -1
  40. package/cjs/createCors.d.ts +0 -12
  41. package/cjs/createCors.js +0 -1
  42. package/cjs/createResponse.d.ts +0 -7
  43. package/cjs/createResponse.js +0 -1
  44. package/cjs/error.d.ts +0 -11
  45. package/cjs/error.js +0 -1
  46. package/cjs/html.d.ts +0 -1
  47. package/cjs/html.js +0 -1
  48. package/cjs/index.d.ts +0 -15
  49. package/cjs/index.js +0 -1
  50. package/cjs/jpeg.d.ts +0 -1
  51. package/cjs/jpeg.js +0 -1
  52. package/cjs/json.d.ts +0 -1
  53. package/cjs/json.js +0 -1
  54. package/cjs/png.d.ts +0 -1
  55. package/cjs/png.js +0 -1
  56. package/cjs/status.d.ts +0 -1
  57. package/cjs/status.js +0 -1
  58. package/cjs/text.d.ts +0 -1
  59. package/cjs/text.js +0 -1
  60. package/cjs/webp.d.ts +0 -1
  61. package/cjs/webp.js +0 -1
  62. package/cjs/websocket.d.ts +0 -1
  63. package/cjs/websocket.js +0 -1
  64. package/cjs/withContent.d.ts +0 -2
  65. package/cjs/withContent.js +0 -1
  66. package/cjs/withCookies.d.ts +0 -2
  67. package/cjs/withCookies.js +0 -1
  68. package/cjs/withParams.d.ts +0 -2
  69. package/cjs/withParams.js +0 -1
package/Router.js CHANGED
@@ -1 +1,39 @@
1
- const e=({base:e="",routes:r=[]}={})=>({__proto__:new Proxy({},{get:(o,a,t,p)=>(o,...l)=>r.push([a.toUpperCase(),RegExp(`^${(p=(e+"/"+o).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),l,p])&&t}),routes:r,async handle(e,...o){let a,t,p=new URL(e.url),l=e.query={__proto__:null};for(let[e,r]of p.searchParams)l[e]=void 0===l[e]?r:[l[e],r].flat();for(let[l,s,$,c]of r)if((l===e.method||"ALL"===l)&&(t=p.pathname.match(s))){e.params=t.groups||{},e.route=c;for(let r of $)if(void 0!==(a=await r(e.proxy||e,...o)))return a}}});export{e as Router};
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;
package/Router.mjs ADDED
@@ -0,0 +1,37 @@
1
+ const Router = ({ base = '', routes = [] } = {}) =>
2
+ // @ts-expect-error TypeScript doesn't know that Proxy makes this work
3
+ ({
4
+ __proto__: new Proxy({}, {
5
+ // @ts-expect-error (we're adding an expected prop "path" to the get)
6
+ get: (target, prop, receiver, path) => (route, ...handlers) => routes.push([
7
+ prop.toUpperCase(),
8
+ RegExp(`^${(path = (base + '/' + route).replace(/\/+(\/|$)/g, '$1')) // strip double & trailing splash
9
+ .replace(/(\/?\.?):(\w+)\+/g, '($1(?<$2>*))') // greedy params
10
+ .replace(/(\/?\.?):(\w+)/g, '($1(?<$2>[^$1/]+?))') // named params and image format
11
+ .replace(/\./g, '\\.') // dot in path
12
+ .replace(/(\/?)\*/g, '($1.*)?') // wildcard
13
+ }/*$`),
14
+ handlers,
15
+ path, // embed clean route path
16
+ ]) && receiver
17
+ }),
18
+ routes,
19
+ async handle(request, ...args) {
20
+ let response, match, url = new URL(request.url), query = request.query = { __proto__: null };
21
+ for (let [k, v] of url.searchParams) {
22
+ query[k] = query[k] === undefined ? v : [query[k], v].flat();
23
+ }
24
+ for (let [method, regex, handlers, path] of routes) {
25
+ if ((method === request.method || method === 'ALL') && (match = url.pathname.match(regex))) {
26
+ request.params = match.groups || {}; // embed params in request
27
+ request.route = path; // embed route path in request
28
+ for (let handler of handlers) {
29
+ if ((response = await handler(request.proxy || request, ...args)) !== undefined)
30
+ return response;
31
+ }
32
+ }
33
+ }
34
+ }
35
+ });
36
+
37
+ export { Router };
package/StatusError.js CHANGED
@@ -1 +1,12 @@
1
- class t extends Error{status;constructor(t=500,s){super("object"==typeof s?s.error:s),"object"==typeof s&&Object.assign(this,s),this.status=t}}export{t as StatusError};
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;
@@ -0,0 +1,10 @@
1
+ class StatusError extends Error {
2
+ status;
3
+ constructor(status = 500, body) {
4
+ super(typeof body === 'object' ? body.error : body);
5
+ typeof body === 'object' && Object.assign(this, body);
6
+ this.status = status;
7
+ }
8
+ }
9
+
10
+ export { StatusError };
package/createCors.js CHANGED
@@ -1 +1,68 @@
1
- const e=(e={})=>{const{origins:o=["*"],maxAge:s,methods:t=["GET"],headers:n={}}=e;let r;const c={"content-type":"application/json","Access-Control-Allow-Methods":t.join(", "),...n};s&&(c["Access-Control-Max-Age"]=s);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:o,status:s,body:t}=e;return[101,301,302,308].includes(s)||o.get("access-control-allow-origin")?e:new Response(t,{status:s,headers:{...Object.fromEntries(o),...c,...r,"content-type":o.get("content-type")}})},preflight:e=>{const s=[...new Set(["OPTIONS",...t])],n=e.headers.get("origin")||"";if(r=(o.includes(n)||o.includes("*"))&&{"Access-Control-Allow-Origin":n},"OPTIONS"===e.method){const o={...c,"Access-Control-Allow-Methods":s.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...r};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:s.join(", ")}})}}}};export{e as createCors};
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;
package/createCors.mjs ADDED
@@ -0,0 +1,66 @@
1
+ // Create CORS function with default options.
2
+ const createCors = (options = {}) => {
3
+ // Destructure and set defaults for options.
4
+ const { origins = ['*'], maxAge, methods = ['GET'], headers = {} } = options;
5
+ let allowOrigin;
6
+ // Initial response headers.
7
+ const rHeaders = {
8
+ 'content-type': 'application/json',
9
+ 'Access-Control-Allow-Methods': methods.join(', '),
10
+ ...headers,
11
+ };
12
+ // Set max age if provided.
13
+ if (maxAge)
14
+ rHeaders['Access-Control-Max-Age'] = maxAge;
15
+ // Pre-flight function.
16
+ const preflight = (r) => {
17
+ // Use methods set.
18
+ const useMethods = [...new Set(['OPTIONS', ...methods])];
19
+ const origin = r.headers.get('origin') || '';
20
+ // Set allowOrigin globally.
21
+ allowOrigin = (origins.includes(origin) || origins.includes('*')) && {
22
+ 'Access-Control-Allow-Origin': origin,
23
+ };
24
+ // Check if method is OPTIONS.
25
+ if (r.method === 'OPTIONS') {
26
+ const reqHeaders = {
27
+ ...rHeaders,
28
+ 'Access-Control-Allow-Methods': useMethods.join(', '),
29
+ 'Access-Control-Allow-Headers': r.headers.get('Access-Control-Request-Headers'),
30
+ ...allowOrigin,
31
+ };
32
+ // Handle CORS pre-flight request.
33
+ return new Response(null, {
34
+ headers: r.headers.get('Origin') &&
35
+ r.headers.get('Access-Control-Request-Method') &&
36
+ r.headers.get('Access-Control-Request-Headers')
37
+ ? reqHeaders
38
+ : { Allow: useMethods.join(', ') },
39
+ });
40
+ }
41
+ };
42
+ // Corsify function.
43
+ const corsify = (response) => {
44
+ if (!response)
45
+ throw new Error('No fetch handler responded and no upstream to proxy to specified.');
46
+ const { headers, status, body } = response;
47
+ // Bypass for protocol shifts or redirects, or if CORS is already set.
48
+ if ([101, 301, 302, 308].includes(status) ||
49
+ headers.get('access-control-allow-origin'))
50
+ return response;
51
+ // Return new response with CORS headers.
52
+ return new Response(body, {
53
+ status,
54
+ headers: {
55
+ ...Object.fromEntries(headers),
56
+ ...rHeaders,
57
+ ...allowOrigin,
58
+ 'content-type': headers.get('content-type'),
59
+ },
60
+ });
61
+ };
62
+ // Return corsify and preflight methods.
63
+ return { corsify, preflight };
64
+ };
65
+
66
+ export { createCors };
package/createResponse.js CHANGED
@@ -1 +1,16 @@
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})};export{e as createResponse};
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;
@@ -0,0 +1,14 @@
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
+ export { createResponse };
package/error.js CHANGED
@@ -1 +1,44 @@
1
- const e=((e="text/plain; charset=utf-8",r)=>(t,n={})=>{const{headers:o={},...s}=n;return"Response"===t?.constructor.name?t:new Response(r?r(t):t,{headers:{"content-type":e,...o},...s})})("application/json; charset=utf-8",JSON.stringify),r=e=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[e]||"Unknown Error"),t=(t=500,n)=>{if(t instanceof Error){const{message:e,...o}=t;t=t.status||500,n={error:e||r(t),...o}}return n={status:t,..."object"==typeof n?n:{error:n||r(t)}},e(n,{status:t})};export{t as error};
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/error.mjs ADDED
@@ -0,0 +1,42 @@
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 json = createResponse('application/json; charset=utf-8', JSON.stringify);
15
+
16
+ const getMessage = (code) => {
17
+ return ({
18
+ 400: 'Bad Request',
19
+ 401: 'Unauthorized',
20
+ 403: 'Forbidden',
21
+ 404: 'Not Found',
22
+ 500: 'Internal Server Error',
23
+ }[code] || 'Unknown Error');
24
+ };
25
+ const error = (a = 500, b) => {
26
+ // handle passing an Error | StatusError directly in
27
+ if (a instanceof Error) {
28
+ const { message, ...err } = a;
29
+ a = a.status || 500;
30
+ b = {
31
+ error: message || getMessage(a),
32
+ ...err,
33
+ };
34
+ }
35
+ b = {
36
+ status: a,
37
+ ...(typeof b === 'object' ? b : { error: b || getMessage(a) }),
38
+ };
39
+ return json(b, { status: a });
40
+ };
41
+
42
+ export { error };
package/html.js CHANGED
@@ -1 +1,18 @@
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})})("text/html");export{e as html};
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/html.mjs ADDED
@@ -0,0 +1,16 @@
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 html = createResponse('text/html');
15
+
16
+ export { html };
package/index.js CHANGED
@@ -1 +1,205 @@
1
- const e=({base:e="",routes:t=[]}={})=>({__proto__:new Proxy({},{get:(o,s,r,n)=>(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,async handle(e,...o){let s,r,n=new URL(e.url),a=e.query={__proto__:null};for(let[e,t]of n.searchParams)a[e]=void 0===a[e]?t:[a[e],t].flat();for(let[a,c,l,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 l)if(void 0!==(s=await t(e.proxy||e,...o)))return s}}});class t 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 o=(e="text/plain; charset=utf-8",t)=>(o,s={})=>{const{headers:r={},...n}=s;return"Response"===o?.constructor.name?o:new Response(t?t(o):o,{headers:{"content-type":e,...r},...n})},s=o("application/json; charset=utf-8",JSON.stringify),r=e=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[e]||"Unknown Error"),n=(e=500,t)=>{if(e instanceof Error){const{message:o,...s}=e;e=e.status||500,t={error:o||r(e),...s}}return t={status:e,..."object"==typeof t?t:{error:t||r(e)}},s(t,{status:e})},a=e=>new Response(null,{status:e}),c=(e,t)=>new Response(e,t),l=o("text/html"),i=o("image/jpeg"),p=o("image/png"),d=o("image/webp"),u=async e=>{e.headers.get("content-type")?.includes("json")&&(e.content=await e.json())},g=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[t,o])=>o?(e[t]=o,e):e),{})},h=e=>{e.proxy=new Proxy(e.proxy||e,{get:(t,o)=>{let s;return void 0!==(s=t[o])?s.bind?.(e)||s:t?.params?.[o]}})},f=(e={})=>{const{origins:t=["*"],maxAge:o,methods:s=["GET"],headers:r={}}=e;let n;const a={"content-type":"application/json","Access-Control-Allow-Methods":s.join(", "),...r};o&&(a["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),...a,...n,"content-type":t.get("content-type")}})},preflight:e=>{const o=[...new Set(["OPTIONS",...s])],r=e.headers.get("origin")||"";if(n=(t.includes(r)||t.includes("*"))&&{"Access-Control-Allow-Origin":r},"OPTIONS"===e.method){const t={...a,"Access-Control-Allow-Methods":o.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")?t:{Allow:o.join(", ")}})}}}};export{e as Router,t as StatusError,f as createCors,o as createResponse,n as error,l as html,i as jpeg,s as json,p as png,a as status,c as text,d as webp,u as withContent,g as withCookies,h as withParams};
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
+ class StatusError extends Error {
40
+ status;
41
+ constructor(status = 500, body) {
42
+ super(typeof body === 'object' ? body.error : body);
43
+ typeof body === 'object' && Object.assign(this, body);
44
+ this.status = status;
45
+ }
46
+ }
47
+
48
+ const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
49
+ const { headers = {}, ...rest } = options;
50
+ if (body?.constructor.name === 'Response')
51
+ return body;
52
+ return new Response(transform ? transform(body) : body, {
53
+ headers: {
54
+ 'content-type': format,
55
+ ...headers,
56
+ },
57
+ ...rest,
58
+ });
59
+ };
60
+
61
+ const json = createResponse('application/json; charset=utf-8', JSON.stringify);
62
+
63
+ const getMessage = (code) => {
64
+ return ({
65
+ 400: 'Bad Request',
66
+ 401: 'Unauthorized',
67
+ 403: 'Forbidden',
68
+ 404: 'Not Found',
69
+ 500: 'Internal Server Error',
70
+ }[code] || 'Unknown Error');
71
+ };
72
+ const error = (a = 500, b) => {
73
+ // handle passing an Error | StatusError directly in
74
+ if (a instanceof Error) {
75
+ const { message, ...err } = a;
76
+ a = a.status || 500;
77
+ b = {
78
+ error: message || getMessage(a),
79
+ ...err,
80
+ };
81
+ }
82
+ b = {
83
+ status: a,
84
+ ...(typeof b === 'object' ? b : { error: b || getMessage(a) }),
85
+ };
86
+ return json(b, { status: a });
87
+ };
88
+
89
+ const status = (status) => new Response(null, { status });
90
+
91
+ const text = (message, options) => new Response(message, options);
92
+
93
+ const html = createResponse('text/html');
94
+
95
+ const jpeg = createResponse('image/jpeg');
96
+
97
+ const png = createResponse('image/png');
98
+
99
+ const webp = createResponse('image/webp');
100
+
101
+ // withContent - embeds any request body as request.content
102
+ const withContent = async (request) => {
103
+ if (request.headers.get('content-type')?.includes('json'))
104
+ request.content = await request.json();
105
+ };
106
+
107
+ // withCookies - embeds cookies object into the request
108
+ const withCookies = (r) => {
109
+ r.cookies = (r.headers.get('Cookie') || '')
110
+ .split(/;\s*/)
111
+ .map((p) => p.split(/=(.+)/))
112
+ .reduce((a, [k, v]) => (v ? ((a[k] = v), a) : a), {});
113
+ };
114
+
115
+ const withParams = (request) => {
116
+ request.proxy = new Proxy(request.proxy || request, {
117
+ get: (obj, prop) => {
118
+ let p;
119
+ if ((p = obj[prop]) !== undefined)
120
+ return p.bind?.(request) || p;
121
+ return obj?.params?.[prop];
122
+ },
123
+ });
124
+ };
125
+
126
+ // Create CORS function with default options.
127
+ const createCors = (options = {}) => {
128
+ // Destructure and set defaults for options.
129
+ const { origins = ['*'], maxAge, methods = ['GET'], headers = {} } = options;
130
+ let allowOrigin;
131
+ // Initial response headers.
132
+ const rHeaders = {
133
+ 'content-type': 'application/json',
134
+ 'Access-Control-Allow-Methods': methods.join(', '),
135
+ ...headers,
136
+ };
137
+ // Set max age if provided.
138
+ if (maxAge)
139
+ rHeaders['Access-Control-Max-Age'] = maxAge;
140
+ // Pre-flight function.
141
+ const preflight = (r) => {
142
+ // Use methods set.
143
+ const useMethods = [...new Set(['OPTIONS', ...methods])];
144
+ const origin = r.headers.get('origin') || '';
145
+ // Set allowOrigin globally.
146
+ allowOrigin = (origins.includes(origin) || origins.includes('*')) && {
147
+ 'Access-Control-Allow-Origin': origin,
148
+ };
149
+ // Check if method is OPTIONS.
150
+ if (r.method === 'OPTIONS') {
151
+ const reqHeaders = {
152
+ ...rHeaders,
153
+ 'Access-Control-Allow-Methods': useMethods.join(', '),
154
+ 'Access-Control-Allow-Headers': r.headers.get('Access-Control-Request-Headers'),
155
+ ...allowOrigin,
156
+ };
157
+ // Handle CORS pre-flight request.
158
+ return new Response(null, {
159
+ headers: r.headers.get('Origin') &&
160
+ r.headers.get('Access-Control-Request-Method') &&
161
+ r.headers.get('Access-Control-Request-Headers')
162
+ ? reqHeaders
163
+ : { Allow: useMethods.join(', ') },
164
+ });
165
+ }
166
+ };
167
+ // Corsify function.
168
+ const corsify = (response) => {
169
+ if (!response)
170
+ throw new Error('No fetch handler responded and no upstream to proxy to specified.');
171
+ const { headers, status, body } = response;
172
+ // Bypass for protocol shifts or redirects, or if CORS is already set.
173
+ if ([101, 301, 302, 308].includes(status) ||
174
+ headers.get('access-control-allow-origin'))
175
+ return response;
176
+ // Return new response with CORS headers.
177
+ return new Response(body, {
178
+ status,
179
+ headers: {
180
+ ...Object.fromEntries(headers),
181
+ ...rHeaders,
182
+ ...allowOrigin,
183
+ 'content-type': headers.get('content-type'),
184
+ },
185
+ });
186
+ };
187
+ // Return corsify and preflight methods.
188
+ return { corsify, preflight };
189
+ };
190
+
191
+ exports.Router = Router;
192
+ exports.StatusError = StatusError;
193
+ exports.createCors = createCors;
194
+ exports.createResponse = createResponse;
195
+ exports.error = error;
196
+ exports.html = html;
197
+ exports.jpeg = jpeg;
198
+ exports.json = json;
199
+ exports.png = png;
200
+ exports.status = status;
201
+ exports.text = text;
202
+ exports.webp = webp;
203
+ exports.withContent = withContent;
204
+ exports.withCookies = withCookies;
205
+ exports.withParams = withParams;