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.
- package/Router.js +39 -1
- package/Router.mjs +37 -0
- package/StatusError.js +12 -1
- package/StatusError.mjs +10 -0
- package/createCors.js +68 -1
- package/createCors.mjs +66 -0
- package/createResponse.js +16 -1
- package/createResponse.mjs +14 -0
- package/error.js +44 -1
- package/error.mjs +42 -0
- package/html.js +18 -1
- package/html.mjs +16 -0
- package/index.js +205 -1
- package/index.mjs +189 -0
- package/jpeg.js +18 -1
- package/jpeg.mjs +16 -0
- package/json.js +18 -1
- package/json.mjs +16 -0
- package/package.json +8 -84
- package/png.js +18 -1
- package/png.mjs +16 -0
- package/status.js +5 -1
- package/status.mjs +3 -0
- package/text.js +5 -1
- package/text.mjs +3 -0
- package/webp.js +18 -1
- package/webp.mjs +16 -0
- package/websocket.js +22 -1
- package/websocket.mjs +20 -0
- package/withContent.js +9 -1
- package/withContent.mjs +7 -0
- package/withCookies.js +11 -1
- package/withCookies.mjs +9 -0
- package/withParams.js +14 -1
- package/withParams.mjs +12 -0
- package/cjs/Router.d.ts +0 -49
- package/cjs/Router.js +0 -1
- package/cjs/StatusError.d.ts +0 -10
- package/cjs/StatusError.js +0 -1
- package/cjs/createCors.d.ts +0 -12
- package/cjs/createCors.js +0 -1
- package/cjs/createResponse.d.ts +0 -7
- package/cjs/createResponse.js +0 -1
- package/cjs/error.d.ts +0 -11
- package/cjs/error.js +0 -1
- package/cjs/html.d.ts +0 -1
- package/cjs/html.js +0 -1
- package/cjs/index.d.ts +0 -15
- package/cjs/index.js +0 -1
- package/cjs/jpeg.d.ts +0 -1
- package/cjs/jpeg.js +0 -1
- package/cjs/json.d.ts +0 -1
- package/cjs/json.js +0 -1
- package/cjs/png.d.ts +0 -1
- package/cjs/png.js +0 -1
- package/cjs/status.d.ts +0 -1
- package/cjs/status.js +0 -1
- package/cjs/text.d.ts +0 -1
- package/cjs/text.js +0 -1
- package/cjs/webp.d.ts +0 -1
- package/cjs/webp.js +0 -1
- package/cjs/websocket.d.ts +0 -1
- package/cjs/websocket.js +0 -1
- package/cjs/withContent.d.ts +0 -2
- package/cjs/withContent.js +0 -1
- package/cjs/withCookies.d.ts +0 -2
- package/cjs/withCookies.js +0 -1
- package/cjs/withParams.d.ts +0 -2
- package/cjs/withParams.js +0 -1
package/Router.js
CHANGED
|
@@ -1 +1,39 @@
|
|
|
1
|
-
|
|
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
|
-
|
|
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;
|
package/StatusError.mjs
ADDED
package/createCors.js
CHANGED
|
@@ -1 +1,68 @@
|
|
|
1
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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;
|