@vafast/cors 0.0.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/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2022 saltyAom
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # @huyooo/elysia-cors
2
+ Plugin for [elysia](https://github.com/elysiajs/elysia) that for Cross Origin Requests (CORs)
3
+
4
+ ## Installation
5
+ ```bash
6
+ bun add @huyooo/elysia-cors
7
+ ```
8
+
9
+ ## Example
10
+ ```typescript
11
+ import { Elysia } from '@huyooo/elysia'
12
+ import { cors } from '@huyooo/elysia-cors'
13
+
14
+ const app = new Elysia()
15
+ .use(cors())
16
+ .listen(8080)
17
+ ```
18
+
19
+ ## Config
20
+ ### origin
21
+ @default `true`
22
+
23
+ Assign the **Access-Control-Allow-Origin** header.
24
+
25
+ Value can be one of the following:
26
+ - `string` - String of origin which will directly assign to `Access-Control-Allow-Origin`
27
+
28
+ - `boolean` - If set to true, `Access-Control-Allow-Origin` will be set to `*` (accept all origin)
29
+
30
+ - `RegExp` - Pattern to use to test with request's url, will accept origin if matched.
31
+
32
+ - `Function` - Custom logic to validate origin acceptance or not. will accept origin if `true` is returned.
33
+ - Function will accepts `Context` just like `Handler`
34
+ ```typescript
35
+ // Example usage
36
+ app.use(cors, {
37
+ origin: ({ request, headers }) => true
38
+ })
39
+
40
+ // Type Definition
41
+ type CORSOriginFn = (context: Context) => boolean | void
42
+ ```
43
+
44
+ - `Array<string | RegExp | Function>` - Will try to find truthy value of all options above. Will accept Request if one is `true`.
45
+
46
+ ### methods
47
+ @default `*`
48
+
49
+ Assign **Access-Control-Allow-Methods** header.
50
+
51
+ Value can be one of the following:
52
+ Accept:
53
+ - `undefined | null | ''` - Ignore all methods.
54
+
55
+ - `*` - Accept all methods.
56
+
57
+ - `HTTPMethod` - Will be directly set to **Access-Control-Allow-Methods**.
58
+ - Expects either a single method or a comma-delimited string (eg: 'GET, PUT, POST')
59
+
60
+ - `HTTPMethod[]` - Allow multiple HTTP methods.
61
+ - eg: ['GET', 'PUT', 'POST']
62
+
63
+ ### allowedHeaders
64
+ @default `*`
65
+
66
+ Assign **Access-Control-Allow-Headers** header.
67
+
68
+ Allow incoming request with the specified headers.
69
+
70
+ Value can be one of the following:
71
+ - `string`
72
+ - Expects either a single method or a comma-delimited string (eg: 'Content-Type, Authorization').
73
+
74
+ - `string[]` - Allow multiple HTTP methods.
75
+ - eg: ['Content-Type', 'Authorization']
76
+
77
+ ### exposedHeaders
78
+ @default `*`
79
+
80
+ Assign **Access-Control-Exposed-Headers** header.
81
+
82
+ Return the specified headers to request in CORS mode.
83
+
84
+ Value can be one of the following:
85
+ - `string`
86
+ - Expects either a single method or a comma-delimited string (eg: 'Content-Type, 'X-Powered-By').
87
+
88
+ - `string[]` - Allow multiple HTTP methods.
89
+ - eg: ['Content-Type', 'X-Powered-By']
90
+
91
+ ### credentials
92
+ @default `true`
93
+
94
+ Assign **Access-Control-Allow-Credentials** header.
95
+
96
+ Allow incoming requests to send `credentials` header.
97
+
98
+ - `boolean` - Available if set to `true`.
99
+
100
+ ### maxAge
101
+ @default `5`
102
+
103
+ Assign **Access-Control-Max-Age** header.
104
+
105
+ Allow incoming requests to send `credentials` header.
106
+
107
+ - `number` - Duration in seconds to indicates how long the results of a preflight request can be cached.
108
+
109
+ ### preflight
110
+ @default `true`
111
+
112
+ Add `[OPTIONS] /*` handler to handle preflight request which response with `HTTP 204` and CORS hints.
113
+
114
+ - `boolean` - Available if set to `true`.
@@ -0,0 +1,114 @@
1
+ import { Middleware } from 'vafast';
2
+
3
+ type Origin = string | RegExp | ((request: Request) => boolean | void);
4
+ type HTTPMethod = 'ACL' | 'BIND' | 'CHECKOUT' | 'CONNECT' | 'COPY' | 'DELETE' | 'GET' | 'HEAD' | 'LINK' | 'LOCK' | 'M-SEARCH' | 'MERGE' | 'MKACTIVITY' | 'MKCALENDAR' | 'MKCOL' | 'MOVE' | 'NOTIFY' | 'OPTIONS' | 'PATCH' | 'POST' | 'PROPFIND' | 'PROPPATCH' | 'PURGE' | 'PUT' | 'REBIND' | 'REPORT' | 'SEARCH' | 'SOURCE' | 'SUBSCRIBE' | 'TRACE' | 'UNBIND' | 'UNLINK' | 'UNLOCK' | 'UNSUBSCRIBE';
5
+ type MaybeArray<T> = T | T[];
6
+ interface CORSConfig {
7
+ /**
8
+ * @default `true`
9
+ *
10
+ * Assign the **Access-Control-Allow-Origin** header.
11
+ *
12
+ * Value can be one of the following:
13
+ * - `string` - String of origin which will be directly assign to `Access-Control-Allow-Origin`
14
+ *
15
+ * - `boolean` - If set to true, `Access-Control-Allow-Origin` will be set to `*` (accept all origin)
16
+ *
17
+ * - `RegExp` - Pattern to use to test with request's url, will accept origin if matched.
18
+ *
19
+ * - `Function` - Custom logic to validate origin acceptance or not. will accept origin if `true` is returned.
20
+ * - Function will accepts `Request` as parameter
21
+ *
22
+ * ```typescript
23
+ * // ? Example usage
24
+ * const corsMiddleware = cors({
25
+ * origin: (request) => true
26
+ * })
27
+ *
28
+ * // Type Definition
29
+ * type CORSOriginFn = (request: Request) => boolean | void
30
+ * ```
31
+ *
32
+ * - `Array<string | RegExp | Function>` - Will try to find truthy value of all options above. Will accept request if one is `true`.
33
+ */
34
+ origin?: Origin | boolean | Origin[];
35
+ /**
36
+ * @default `*`
37
+ *
38
+ * Assign **Access-Control-Allow-Methods** header.
39
+ *
40
+ * Value can be one of the following:
41
+ * Accept:
42
+ * - `undefined | null | ''` - Ignore all methods.
43
+ *
44
+ * - `*` - Accept all methods.
45
+ *
46
+ * - `HTTPMethod` - Will be directly set to **Access-Control-Allow-Methods**.
47
+ * - Expects either a single method or a comma-delimited string (eg: 'GET, PUT, POST')
48
+ *
49
+ * - `HTTPMethod[]` - Allow multiple HTTP methods.
50
+ * - eg: ['GET', 'PUT', 'POST']
51
+ */
52
+ methods?: boolean | undefined | null | '' | '*' | MaybeArray<HTTPMethod | (string & {})>;
53
+ /**
54
+ * @default `*`
55
+ *
56
+ * Assign **Access-Control-Allow-Headers** header.
57
+ *
58
+ * Allow incoming request with the specified headers.
59
+ *
60
+ * Value can be one of the following:
61
+ * - `string`
62
+ * - Expects either a single method or a comma-delimited string (eg: 'Content-Type, Authorization').
63
+ *
64
+ * - `string[]` - Allow multiple HTTP methods.
65
+ * - eg: ['Content-Type', 'Authorization']
66
+ */
67
+ allowedHeaders?: true | string | string[];
68
+ /**
69
+ * @default `*`
70
+ *
71
+ * Assign **Access-Control-Expose-Headers** header.
72
+ *
73
+ * Return the specified headers to request in CORS mode.
74
+ *
75
+ * Value can be one of the following:
76
+ * - `string`
77
+ * - Expects either a single method or a comma-delimited string (eg: 'Content-Type, 'X-Powered-By').
78
+ *
79
+ * - `string[]` - Allow multiple HTTP methods.
80
+ * - eg: ['Content-Type', 'X-Powered-By']
81
+ */
82
+ exposeHeaders?: true | string | string[];
83
+ /**
84
+ * @default `true`
85
+ *
86
+ * Assign **Access-Control-Allow-Credentials** header.
87
+ *
88
+ * Allow incoming requests to send `credentials` header.
89
+ *
90
+ * - `boolean` - Available if set to `true`.
91
+ */
92
+ credentials?: boolean;
93
+ /**
94
+ * @default `5`
95
+ *
96
+ * Assign **Access-Control-Max-Age** header.
97
+ *
98
+ * Allow incoming requests to send `credentials` header.
99
+ *
100
+ * - `number` - Duration in seconds to indicates how long the results of a preflight request can be cached.
101
+ */
102
+ maxAge?: number;
103
+ /**
104
+ * @default `true`
105
+ *
106
+ * Add `[OPTIONS] /*` handler to handle preflight request which response with `HTTP 204` and CORS hints.
107
+ *
108
+ * - `boolean` - Available if set to `true`.
109
+ */
110
+ preflight?: boolean;
111
+ }
112
+ declare const cors: (config?: CORSConfig) => Middleware;
113
+
114
+ export { type HTTPMethod, cors, cors as default };
package/dist/index.js ADDED
@@ -0,0 +1,180 @@
1
+ // src/index.ts
2
+ var isBun = typeof new Headers()?.toJSON === "function";
3
+ var processHeaders = (headers) => {
4
+ if ("toJSON" in headers && typeof headers.toJSON === "function") {
5
+ return Object.keys(headers.toJSON()).join(", ");
6
+ }
7
+ let keys = "";
8
+ let i = 0;
9
+ headers.forEach((_, key) => {
10
+ if (i) keys = keys + ", " + key;
11
+ else keys = key;
12
+ i++;
13
+ });
14
+ return keys;
15
+ };
16
+ var cors = (config) => {
17
+ let {
18
+ origin = true,
19
+ methods = true,
20
+ allowedHeaders = true,
21
+ exposeHeaders = true,
22
+ credentials = true,
23
+ maxAge = 5,
24
+ preflight = true
25
+ } = config ?? {};
26
+ if (Array.isArray(allowedHeaders))
27
+ allowedHeaders = allowedHeaders.join(", ");
28
+ if (Array.isArray(exposeHeaders)) exposeHeaders = exposeHeaders.join(", ");
29
+ const origins = typeof origin === "boolean" ? void 0 : Array.isArray(origin) ? origin : [origin];
30
+ const anyOrigin = origins?.some((o) => o === "*");
31
+ const originMap = {};
32
+ if (origins) {
33
+ for (const origin2 of origins)
34
+ if (typeof origin2 === "string") originMap[origin2] = true;
35
+ }
36
+ const processOrigin = (origin2, request, from) => {
37
+ if (Array.isArray(origin2))
38
+ return origin2.some((o) => processOrigin(o, request, from));
39
+ switch (typeof origin2) {
40
+ case "string":
41
+ if (from in originMap) return true;
42
+ const fromProtocol = from.indexOf("://");
43
+ if (fromProtocol !== -1) from = from.slice(fromProtocol + 3);
44
+ return origin2 === from;
45
+ case "function":
46
+ return origin2(request) === true;
47
+ case "object":
48
+ if (origin2 instanceof RegExp) return origin2.test(from);
49
+ }
50
+ return false;
51
+ };
52
+ const handleOrigin = (response, request) => {
53
+ if (origin === true) {
54
+ response.headers.set("vary", "*");
55
+ response.headers.set(
56
+ "access-control-allow-origin",
57
+ request.headers.get("Origin") || "*"
58
+ );
59
+ return;
60
+ }
61
+ if (anyOrigin) {
62
+ response.headers.set("vary", "*");
63
+ response.headers.set("access-control-allow-origin", "*");
64
+ return;
65
+ }
66
+ if (!origins?.length) return;
67
+ const headers = [];
68
+ if (origins.length) {
69
+ const from = request.headers.get("Origin") ?? "";
70
+ for (let i = 0; i < origins.length; i++) {
71
+ const value = processOrigin(origins[i], request, from);
72
+ if (value === true) {
73
+ response.headers.set("vary", origin ? "Origin" : "*");
74
+ response.headers.set(
75
+ "access-control-allow-origin",
76
+ from || "*"
77
+ );
78
+ return;
79
+ }
80
+ }
81
+ }
82
+ response.headers.set("vary", "Origin");
83
+ if (headers.length)
84
+ response.headers.set(
85
+ "access-control-allow-origin",
86
+ headers.join(", ")
87
+ );
88
+ };
89
+ const handleMethod = (response, method) => {
90
+ if (!method) return;
91
+ if (methods === true)
92
+ return response.headers.set(
93
+ "access-control-allow-methods",
94
+ method ?? "*"
95
+ );
96
+ if (methods === false || !methods?.length) return;
97
+ if (methods === "*")
98
+ return response.headers.set("access-control-allow-methods", "*");
99
+ if (!Array.isArray(methods))
100
+ return response.headers.set("access-control-allow-methods", methods);
101
+ response.headers.set("access-control-allow-methods", methods.join(", "));
102
+ };
103
+ const setDefaultHeaders = (response) => {
104
+ if (typeof exposeHeaders === "string")
105
+ response.headers.set("access-control-expose-headers", exposeHeaders);
106
+ if (typeof allowedHeaders === "string")
107
+ response.headers.set("access-control-allow-headers", allowedHeaders);
108
+ if (credentials === true)
109
+ response.headers.set("access-control-allow-credentials", "true");
110
+ };
111
+ const handlePreflight = async (request) => {
112
+ const response = new Response(null, { status: 204 });
113
+ handleOrigin(response, request);
114
+ handleMethod(
115
+ response,
116
+ request.headers.get("access-control-request-method")
117
+ );
118
+ if (allowedHeaders === true || exposeHeaders === true) {
119
+ if (allowedHeaders === true)
120
+ response.headers.set(
121
+ "access-control-allow-headers",
122
+ request.headers.get("access-control-request-headers") || ""
123
+ );
124
+ if (exposeHeaders === true)
125
+ response.headers.set(
126
+ "access-control-expose-headers",
127
+ processHeaders(request.headers)
128
+ );
129
+ }
130
+ if (maxAge)
131
+ response.headers.set("access-control-max-age", maxAge.toString());
132
+ return response;
133
+ };
134
+ return async (request, next) => {
135
+ if (preflight && request.method === "OPTIONS") {
136
+ const response2 = new Response(null, { status: 204 });
137
+ handleOrigin(response2, request);
138
+ handleMethod(
139
+ response2,
140
+ request.headers.get("access-control-request-method")
141
+ );
142
+ if (allowedHeaders === true || exposeHeaders === true) {
143
+ if (allowedHeaders === true)
144
+ response2.headers.set(
145
+ "access-control-allow-headers",
146
+ request.headers.get("access-control-request-headers") || ""
147
+ );
148
+ if (exposeHeaders === true)
149
+ response2.headers.set(
150
+ "access-control-expose-headers",
151
+ processHeaders(request.headers)
152
+ );
153
+ }
154
+ if (maxAge)
155
+ response2.headers.set(
156
+ "access-control-max-age",
157
+ maxAge.toString()
158
+ );
159
+ return response2;
160
+ }
161
+ const response = await next();
162
+ handleOrigin(response, request);
163
+ handleMethod(response, request.method);
164
+ setDefaultHeaders(response);
165
+ if (allowedHeaders === true || exposeHeaders === true) {
166
+ const headers = processHeaders(request.headers);
167
+ if (allowedHeaders === true)
168
+ response.headers.set("access-control-allow-headers", headers);
169
+ if (exposeHeaders === true)
170
+ response.headers.set("access-control-expose-headers", headers);
171
+ }
172
+ return response;
173
+ };
174
+ };
175
+ var index_default = cors;
176
+ export {
177
+ cors,
178
+ index_default as default
179
+ };
180
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/* eslint-disable no-case-declarations */\nimport type { Middleware } from 'vafast'\n\ntype Origin = string | RegExp | ((request: Request) => boolean | void)\n\nexport type HTTPMethod =\n\t| 'ACL'\n\t| 'BIND'\n\t| 'CHECKOUT'\n\t| 'CONNECT'\n\t| 'COPY'\n\t| 'DELETE'\n\t| 'GET'\n\t| 'HEAD'\n\t| 'LINK'\n\t| 'LOCK'\n\t| 'M-SEARCH'\n\t| 'MERGE'\n\t| 'MKACTIVITY'\n\t| 'MKCALENDAR'\n\t| 'MKCOL'\n\t| 'MOVE'\n\t| 'NOTIFY'\n\t| 'OPTIONS'\n\t| 'PATCH'\n\t| 'POST'\n\t| 'PROPFIND'\n\t| 'PROPPATCH'\n\t| 'PURGE'\n\t| 'PUT'\n\t| 'REBIND'\n\t| 'REPORT'\n\t| 'SEARCH'\n\t| 'SOURCE'\n\t| 'SUBSCRIBE'\n\t| 'TRACE'\n\t| 'UNBIND'\n\t| 'UNLINK'\n\t| 'UNLOCK'\n\t| 'UNSUBSCRIBE'\n\ntype MaybeArray<T> = T | T[]\n\ninterface CORSConfig {\n\t/**\n\t * @default `true`\n\t *\n\t * Assign the **Access-Control-Allow-Origin** header.\n\t *\n\t * Value can be one of the following:\n\t * - `string` - String of origin which will be directly assign to `Access-Control-Allow-Origin`\n\t *\n\t * - `boolean` - If set to true, `Access-Control-Allow-Origin` will be set to `*` (accept all origin)\n\t *\n\t * - `RegExp` - Pattern to use to test with request's url, will accept origin if matched.\n\t *\n\t * - `Function` - Custom logic to validate origin acceptance or not. will accept origin if `true` is returned.\n\t * - Function will accepts `Request` as parameter\n\t *\n\t * ```typescript\n\t * // ? Example usage\n\t * const corsMiddleware = cors({\n\t * origin: (request) => true\n\t * })\n\t *\n\t * // Type Definition\n\t * type CORSOriginFn = (request: Request) => boolean | void\n\t * ```\n\t *\n\t * - `Array<string | RegExp | Function>` - Will try to find truthy value of all options above. Will accept request if one is `true`.\n\t */\n\torigin?: Origin | boolean | Origin[]\n\t/**\n\t * @default `*`\n\t *\n\t * Assign **Access-Control-Allow-Methods** header.\n\t *\n\t * Value can be one of the following:\n\t * Accept:\n\t * - `undefined | null | ''` - Ignore all methods.\n\t *\n\t * - `*` - Accept all methods.\n\t *\n\t * - `HTTPMethod` - Will be directly set to **Access-Control-Allow-Methods**.\n\t * - Expects either a single method or a comma-delimited string (eg: 'GET, PUT, POST')\n\t *\n\t * - `HTTPMethod[]` - Allow multiple HTTP methods.\n\t * - eg: ['GET', 'PUT', 'POST']\n\t */\n\tmethods?:\n\t\t| boolean\n\t\t| undefined\n\t\t| null\n\t\t| ''\n\t\t| '*'\n\t\t| MaybeArray<HTTPMethod | (string & {})>\n\t/**\n\t * @default `*`\n\t *\n\t * Assign **Access-Control-Allow-Headers** header.\n\t *\n\t * Allow incoming request with the specified headers.\n\t *\n\t * Value can be one of the following:\n\t * - `string`\n\t * - Expects either a single method or a comma-delimited string (eg: 'Content-Type, Authorization').\n\t *\n\t * - `string[]` - Allow multiple HTTP methods.\n\t * - eg: ['Content-Type', 'Authorization']\n\t */\n\tallowedHeaders?: true | string | string[]\n\t/**\n\t * @default `*`\n\t *\n\t * Assign **Access-Control-Expose-Headers** header.\n\t *\n\t * Return the specified headers to request in CORS mode.\n\t *\n\t * Value can be one of the following:\n\t * - `string`\n\t * - Expects either a single method or a comma-delimited string (eg: 'Content-Type, 'X-Powered-By').\n\t *\n\t * - `string[]` - Allow multiple HTTP methods.\n\t * - eg: ['Content-Type', 'X-Powered-By']\n\t */\n\texposeHeaders?: true | string | string[]\n\t/**\n\t * @default `true`\n\t *\n\t * Assign **Access-Control-Allow-Credentials** header.\n\t *\n\t * Allow incoming requests to send `credentials` header.\n\t *\n\t * - `boolean` - Available if set to `true`.\n\t */\n\tcredentials?: boolean\n\t/**\n\t * @default `5`\n\t *\n\t * Assign **Access-Control-Max-Age** header.\n\t *\n\t * Allow incoming requests to send `credentials` header.\n\t *\n\t * - `number` - Duration in seconds to indicates how long the results of a preflight request can be cached.\n\t */\n\tmaxAge?: number\n\t/**\n\t * @default `true`\n\t *\n\t * Add `[OPTIONS] /*` handler to handle preflight request which response with `HTTP 204` and CORS hints.\n\t *\n\t * - `boolean` - Available if set to `true`.\n\t */\n\tpreflight?: boolean\n}\n\n// @ts-ignore\nconst isBun = typeof new Headers()?.toJSON === 'function'\n\n/**\n * This function is use when headers config is true.\n * Attempts to process headers based on request headers.\n */\nconst processHeaders = (headers: any) => {\n\t// Check if toJSON method exists (Bun specific)\n\tif ('toJSON' in headers && typeof headers.toJSON === 'function') {\n\t\treturn Object.keys(headers.toJSON()).join(', ')\n\t}\n\n\tlet keys = ''\n\n\tlet i = 0\n\theaders.forEach((_: any, key: string) => {\n\t\tif (i) keys = keys + ', ' + key\n\t\telse keys = key\n\n\t\ti++\n\t})\n\n\treturn keys\n}\n\nexport const cors = (config?: CORSConfig): Middleware => {\n\tlet {\n\t\torigin = true,\n\t\tmethods = true,\n\t\tallowedHeaders = true,\n\t\texposeHeaders = true,\n\t\tcredentials = true,\n\t\tmaxAge = 5,\n\t\tpreflight = true\n\t} = config ?? {}\n\n\tif (Array.isArray(allowedHeaders))\n\t\tallowedHeaders = allowedHeaders.join(', ')\n\n\tif (Array.isArray(exposeHeaders)) exposeHeaders = exposeHeaders.join(', ')\n\n\tconst origins =\n\t\ttypeof origin === 'boolean'\n\t\t\t? undefined\n\t\t\t: Array.isArray(origin)\n\t\t\t? origin\n\t\t\t: [origin]\n\n\tconst anyOrigin = origins?.some((o) => o === '*')\n\n\tconst originMap = <Record<string, true>>{}\n\tif (origins)\n\t\tfor (const origin of origins)\n\t\t\tif (typeof origin === 'string') originMap[origin] = true\n\n\tconst processOrigin = (\n\t\torigin: Origin,\n\t\trequest: Request,\n\t\tfrom: string\n\t): boolean => {\n\t\tif (Array.isArray(origin))\n\t\t\treturn origin.some((o) => processOrigin(o, request, from))\n\n\t\tswitch (typeof origin) {\n\t\t\tcase 'string':\n\t\t\t\tif (from in originMap) return true\n\n\t\t\t\tconst fromProtocol = from.indexOf('://')\n\t\t\t\tif (fromProtocol !== -1) from = from.slice(fromProtocol + 3)\n\n\t\t\t\treturn origin === from\n\n\t\t\tcase 'function':\n\t\t\t\treturn origin(request) === true\n\n\t\t\tcase 'object':\n\t\t\t\tif (origin instanceof RegExp) return origin.test(from)\n\t\t}\n\n\t\treturn false\n\t}\n\n\tconst handleOrigin = (response: Response, request: Request) => {\n\t\t// origin === `true` means any origin\n\t\tif (origin === true) {\n\t\t\tresponse.headers.set('vary', '*')\n\t\t\tresponse.headers.set(\n\t\t\t\t'access-control-allow-origin',\n\t\t\t\trequest.headers.get('Origin') || '*'\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tif (anyOrigin) {\n\t\t\tresponse.headers.set('vary', '*')\n\t\t\tresponse.headers.set('access-control-allow-origin', '*')\n\n\t\t\treturn\n\t\t}\n\n\t\tif (!origins?.length) return\n\n\t\tconst headers: string[] = []\n\n\t\tif (origins.length) {\n\t\t\tconst from = request.headers.get('Origin') ?? ''\n\t\t\tfor (let i = 0; i < origins.length; i++) {\n\t\t\t\tconst value = processOrigin(origins[i]!, request, from)\n\t\t\t\tif (value === true) {\n\t\t\t\t\tresponse.headers.set('vary', origin ? 'Origin' : '*')\n\t\t\t\t\tresponse.headers.set(\n\t\t\t\t\t\t'access-control-allow-origin',\n\t\t\t\t\t\tfrom || '*'\n\t\t\t\t\t)\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tresponse.headers.set('vary', 'Origin')\n\t\tif (headers.length)\n\t\t\tresponse.headers.set(\n\t\t\t\t'access-control-allow-origin',\n\t\t\t\theaders.join(', ')\n\t\t\t)\n\t}\n\n\tconst handleMethod = (response: Response, method?: string | null) => {\n\t\tif (!method) return\n\n\t\tif (methods === true)\n\t\t\treturn response.headers.set(\n\t\t\t\t'access-control-allow-methods',\n\t\t\t\tmethod ?? '*'\n\t\t\t)\n\n\t\tif (methods === false || !methods?.length) return\n\n\t\tif (methods === '*')\n\t\t\treturn response.headers.set('access-control-allow-methods', '*')\n\n\t\tif (!Array.isArray(methods))\n\t\t\treturn response.headers.set('access-control-allow-methods', methods)\n\n\t\tresponse.headers.set('access-control-allow-methods', methods.join(', '))\n\t}\n\n\tconst setDefaultHeaders = (response: Response) => {\n\t\tif (typeof exposeHeaders === 'string')\n\t\t\tresponse.headers.set('access-control-expose-headers', exposeHeaders)\n\n\t\tif (typeof allowedHeaders === 'string')\n\t\t\tresponse.headers.set('access-control-allow-headers', allowedHeaders)\n\n\t\tif (credentials === true)\n\t\t\tresponse.headers.set('access-control-allow-credentials', 'true')\n\t}\n\n\tconst handlePreflight = async (request: Request): Promise<Response> => {\n\t\tconst response = new Response(null, { status: 204 })\n\n\t\thandleOrigin(response, request)\n\t\thandleMethod(\n\t\t\tresponse,\n\t\t\trequest.headers.get('access-control-request-method')\n\t\t)\n\n\t\tif (allowedHeaders === true || exposeHeaders === true) {\n\t\t\tif (allowedHeaders === true)\n\t\t\t\tresponse.headers.set(\n\t\t\t\t\t'access-control-allow-headers',\n\t\t\t\t\trequest.headers.get('access-control-request-headers') || ''\n\t\t\t\t)\n\n\t\t\tif (exposeHeaders === true)\n\t\t\t\tresponse.headers.set(\n\t\t\t\t\t'access-control-expose-headers',\n\t\t\t\t\tprocessHeaders(request.headers)\n\t\t\t\t)\n\t\t}\n\n\t\tif (maxAge)\n\t\t\tresponse.headers.set('access-control-max-age', maxAge.toString())\n\n\t\treturn response\n\t}\n\n\treturn async (request: Request, next: () => Promise<Response>) => {\n\t\t// Handle preflight requests\n\t\tif (preflight && request.method === 'OPTIONS') {\n\t\t\tconst response = new Response(null, { status: 204 })\n\n\t\t\thandleOrigin(response, request)\n\t\t\thandleMethod(\n\t\t\t\tresponse,\n\t\t\t\trequest.headers.get('access-control-request-method')\n\t\t\t)\n\n\t\t\tif (allowedHeaders === true || exposeHeaders === true) {\n\t\t\t\tif (allowedHeaders === true)\n\t\t\t\t\tresponse.headers.set(\n\t\t\t\t\t\t'access-control-allow-headers',\n\t\t\t\t\t\trequest.headers.get('access-control-request-headers') ||\n\t\t\t\t\t\t\t''\n\t\t\t\t\t)\n\n\t\t\t\tif (exposeHeaders === true)\n\t\t\t\t\tresponse.headers.set(\n\t\t\t\t\t\t'access-control-expose-headers',\n\t\t\t\t\t\tprocessHeaders(request.headers)\n\t\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (maxAge)\n\t\t\t\tresponse.headers.set(\n\t\t\t\t\t'access-control-max-age',\n\t\t\t\t\tmaxAge.toString()\n\t\t\t\t)\n\n\t\t\treturn response\n\t\t}\n\n\t\t// Process CORS for actual requests\n\t\tconst response = await next()\n\n\t\thandleOrigin(response, request)\n\t\thandleMethod(response, request.method)\n\t\tsetDefaultHeaders(response)\n\n\t\tif (allowedHeaders === true || exposeHeaders === true) {\n\t\t\tconst headers = processHeaders(request.headers)\n\n\t\t\tif (allowedHeaders === true)\n\t\t\t\tresponse.headers.set('access-control-allow-headers', headers)\n\n\t\t\tif (exposeHeaders === true)\n\t\t\t\tresponse.headers.set('access-control-expose-headers', headers)\n\t\t}\n\n\t\treturn response\n\t}\n}\n\nexport default cors\n"],"mappings":";AA6JA,IAAM,QAAQ,OAAO,IAAI,QAAQ,GAAG,WAAW;AAM/C,IAAM,iBAAiB,CAAC,YAAiB;AAExC,MAAI,YAAY,WAAW,OAAO,QAAQ,WAAW,YAAY;AAChE,WAAO,OAAO,KAAK,QAAQ,OAAO,CAAC,EAAE,KAAK,IAAI;AAAA,EAC/C;AAEA,MAAI,OAAO;AAEX,MAAI,IAAI;AACR,UAAQ,QAAQ,CAAC,GAAQ,QAAgB;AACxC,QAAI,EAAG,QAAO,OAAO,OAAO;AAAA,QACvB,QAAO;AAEZ;AAAA,EACD,CAAC;AAED,SAAO;AACR;AAEO,IAAM,OAAO,CAA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AAA,QACjB;AAED,aAAOA;AAAA,IACR;AAGA,UAAM,WAAW,MAAM,KAAK;AAE5B,iBAAa,UAAU,OAAO;AAC9B,iBAAa,UAAU,QAAQ,MAAM;AACrC,sBAAkB,QAAQ;AAE1B,QAAI,mBAAmB,QAAQ,kBAAkB,MAAM;AACtD,YAAM,UAAU,eAAe,QAAQ,OAAO;AAE9C,UAAI,mBAAmB;AACtB,iBAAS,QAAQ,IAAI,gCAAgC,OAAO;AAE7D,UAAI,kBAAkB;AACrB,iBAAS,QAAQ,IAAI,iCAAiC,OAAO;AAAA,IAC/D;AAEA,WAAO;AAAA,EACR;AACD;AAEA,IAAO,gBAAQ;","names":["origin","response"]}
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@vafast/cors",
3
+ "version": "0.0.1",
4
+ "description": "CORS middleware plugin for Vafast framework",
5
+ "type": "module",
6
+ "author": {
7
+ "name": "Gaurish Sethia",
8
+ "url": "https://github.com/gaurishhs",
9
+ "email": "gaurishh.sethia@gmail.com"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/gaurishhs/@vafast/cors"
14
+ },
15
+ "main": "./dist/index.js",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js",
22
+ "require": "./dist/index.js",
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
26
+ "bugs": "https://github.com/gaurishhs/@vafast/cors/issues",
27
+ "homepage": "https://github.com/gaurishhs/@vafast/cors",
28
+ "keywords": [
29
+ "@vafast",
30
+ "typescript",
31
+ "cors"
32
+ ],
33
+ "scripts": {
34
+ "clean": "rimraf dist",
35
+ "build": "tsup",
36
+ "dev": "NODE_DEBUG=* bun run --hot example/index.ts",
37
+ "test": "bun test",
38
+ "test:types": "tsc --noEmit",
39
+ "lint": "eslint . --ext .ts",
40
+ "lint:fix": "eslint . --ext .ts --fix",
41
+ "type-check": "tsc --noEmit",
42
+ "prepublishOnly": "npm run build && npm run test",
43
+ "release": "npm run build && npm run test && npm publish --access=public",
44
+ "release:patch": "npm version patch && npm run release && git push && git push --tags",
45
+ "release:minor": "npm version minor && npm run release && git push && git push --tags",
46
+ "release:major": "npm version major && npm run release && git push && git push --tags"
47
+ },
48
+ "license": "MIT",
49
+ "files": [
50
+ "dist",
51
+ "README.md",
52
+ "LICENSE"
53
+ ],
54
+ "devDependencies": {
55
+ "@types/bun": "^1.1.2",
56
+ "@types/debug": "^4.1.12",
57
+ "@types/node": "^24.3.0",
58
+ "@typescript-eslint/eslint-plugin": "^7.9.0",
59
+ "@typescript-eslint/parser": "^7.9.0",
60
+ "eslint": "^9.2.0",
61
+ "rimraf": "^6.0.1",
62
+ "tsup": "^8.5.1",
63
+ "typescript": "^5.4.5",
64
+ "vafast": "^0.3.4"
65
+ },
66
+ "peerDependencies": {
67
+ "vafast": ">= 0.1.12"
68
+ }
69
+ }