@remix-run/fetch-proxy 0.6.0 → 0.7.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 +1 -1
- package/README.md +7 -5
- package/dist/index.js +1 -200
- package/dist/lib/fetch-proxy.d.ts +17 -2
- package/dist/lib/fetch-proxy.d.ts.map +1 -1
- package/dist/lib/fetch-proxy.js +76 -0
- package/package.json +7 -9
- package/src/lib/fetch-proxy.ts +17 -2
- package/dist/index.js.map +0 -7
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -2,16 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
`fetch-proxy` is an HTTP proxy for the [JavaScript Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
|
|
4
4
|
|
|
5
|
+
HTTP proxies are essential for many web architectures: load balancing, API gateways, development servers that forward to backend services, and middleware that needs to intercept and modify traffic. Traditional proxy implementations often require platform-specific APIs or complex server setups.
|
|
6
|
+
|
|
5
7
|
In the context of servers, an HTTP proxy server is a server that forwards all requests it receives to another server and returns the responses it receives. When you think about it this way, a [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) is like a mini proxy server sitting right there in your code. You send it requests, it goes and talks to some other server, and it gives you back the response it received.
|
|
6
8
|
|
|
7
|
-
`fetch-proxy` allows you to easily create `fetch` functions that act as proxies to "target" servers.
|
|
9
|
+
`fetch-proxy` allows you to easily create `fetch` functions that act as proxies to "target" servers using the familiar web-standard Fetch API.
|
|
8
10
|
|
|
9
11
|
## Features
|
|
10
12
|
|
|
11
|
-
- Built on the standard [JavaScript Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
|
|
12
|
-
- Supports rewriting `Set-Cookie` headers received from target server
|
|
13
|
-
- Supports `X-Forwarded-Proto` and `X-Forwarded-Host` headers
|
|
14
|
-
- Supports custom `fetch` implementations
|
|
13
|
+
- **Web Standards** - Built on the standard [JavaScript Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
|
|
14
|
+
- **Cookie Rewriting** - Supports rewriting `Set-Cookie` headers received from target server
|
|
15
|
+
- **Forwarding Headers** - Supports `X-Forwarded-Proto` and `X-Forwarded-Host` headers
|
|
16
|
+
- **Custom Fetch** - Supports custom `fetch` implementations
|
|
15
17
|
|
|
16
18
|
## Installation
|
|
17
19
|
|
package/dist/index.js
CHANGED
|
@@ -1,200 +1 @@
|
|
|
1
|
-
|
|
2
|
-
function parseParams(input, delimiter = ";") {
|
|
3
|
-
let parser = delimiter === ";" ? /(?:^|;)\s*([^=;\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^;]|\\\;)+))?)?/g : /(?:^|,)\s*([^=,\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^,]|\\\,)+))?)?/g;
|
|
4
|
-
let params = [];
|
|
5
|
-
let match;
|
|
6
|
-
while ((match = parser.exec(input)) !== null) {
|
|
7
|
-
let key = match[1].trim();
|
|
8
|
-
let value;
|
|
9
|
-
if (match[2]) {
|
|
10
|
-
value = (match[3] || match[4] || "").replace(/\\(.)/g, "$1").trim();
|
|
11
|
-
}
|
|
12
|
-
params.push([key, value]);
|
|
13
|
-
}
|
|
14
|
-
return params;
|
|
15
|
-
}
|
|
16
|
-
function quote(value) {
|
|
17
|
-
if (value.includes('"') || value.includes(";") || value.includes(" ")) {
|
|
18
|
-
return `"${value.replace(/"/g, '\\"')}"`;
|
|
19
|
-
}
|
|
20
|
-
return value;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
// ../headers/src/lib/utils.ts
|
|
24
|
-
function capitalize(str) {
|
|
25
|
-
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
|
|
26
|
-
}
|
|
27
|
-
function isValidDate(date) {
|
|
28
|
-
return date instanceof Date && !isNaN(date.getTime());
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// ../headers/src/lib/set-cookie.ts
|
|
32
|
-
var SetCookie = class {
|
|
33
|
-
domain;
|
|
34
|
-
expires;
|
|
35
|
-
httpOnly;
|
|
36
|
-
maxAge;
|
|
37
|
-
name;
|
|
38
|
-
path;
|
|
39
|
-
sameSite;
|
|
40
|
-
secure;
|
|
41
|
-
value;
|
|
42
|
-
constructor(init) {
|
|
43
|
-
if (init) {
|
|
44
|
-
if (typeof init === "string") {
|
|
45
|
-
let params = parseParams(init);
|
|
46
|
-
if (params.length > 0) {
|
|
47
|
-
this.name = params[0][0];
|
|
48
|
-
this.value = params[0][1];
|
|
49
|
-
for (let [key, value] of params.slice(1)) {
|
|
50
|
-
switch (key.toLowerCase()) {
|
|
51
|
-
case "domain":
|
|
52
|
-
this.domain = value;
|
|
53
|
-
break;
|
|
54
|
-
case "expires": {
|
|
55
|
-
if (typeof value === "string") {
|
|
56
|
-
let date = new Date(value);
|
|
57
|
-
if (isValidDate(date)) {
|
|
58
|
-
this.expires = date;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
break;
|
|
62
|
-
}
|
|
63
|
-
case "httponly":
|
|
64
|
-
this.httpOnly = true;
|
|
65
|
-
break;
|
|
66
|
-
case "max-age": {
|
|
67
|
-
if (typeof value === "string") {
|
|
68
|
-
let v = parseInt(value, 10);
|
|
69
|
-
if (!isNaN(v)) this.maxAge = v;
|
|
70
|
-
}
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
|
-
case "path":
|
|
74
|
-
this.path = value;
|
|
75
|
-
break;
|
|
76
|
-
case "samesite":
|
|
77
|
-
if (typeof value === "string" && /strict|lax|none/i.test(value)) {
|
|
78
|
-
this.sameSite = capitalize(value);
|
|
79
|
-
}
|
|
80
|
-
break;
|
|
81
|
-
case "secure":
|
|
82
|
-
this.secure = true;
|
|
83
|
-
break;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
} else {
|
|
88
|
-
this.domain = init.domain;
|
|
89
|
-
this.expires = init.expires;
|
|
90
|
-
this.httpOnly = init.httpOnly;
|
|
91
|
-
this.maxAge = init.maxAge;
|
|
92
|
-
this.name = init.name;
|
|
93
|
-
this.path = init.path;
|
|
94
|
-
this.sameSite = init.sameSite;
|
|
95
|
-
this.secure = init.secure;
|
|
96
|
-
this.value = init.value;
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
toString() {
|
|
101
|
-
if (!this.name) {
|
|
102
|
-
return "";
|
|
103
|
-
}
|
|
104
|
-
let parts = [`${this.name}=${quote(this.value || "")}`];
|
|
105
|
-
if (this.domain) {
|
|
106
|
-
parts.push(`Domain=${this.domain}`);
|
|
107
|
-
}
|
|
108
|
-
if (this.path) {
|
|
109
|
-
parts.push(`Path=${this.path}`);
|
|
110
|
-
}
|
|
111
|
-
if (this.expires) {
|
|
112
|
-
parts.push(`Expires=${this.expires.toUTCString()}`);
|
|
113
|
-
}
|
|
114
|
-
if (this.maxAge) {
|
|
115
|
-
parts.push(`Max-Age=${this.maxAge}`);
|
|
116
|
-
}
|
|
117
|
-
if (this.secure) {
|
|
118
|
-
parts.push("Secure");
|
|
119
|
-
}
|
|
120
|
-
if (this.httpOnly) {
|
|
121
|
-
parts.push("HttpOnly");
|
|
122
|
-
}
|
|
123
|
-
if (this.sameSite) {
|
|
124
|
-
parts.push(`SameSite=${this.sameSite}`);
|
|
125
|
-
}
|
|
126
|
-
return parts.join("; ");
|
|
127
|
-
}
|
|
128
|
-
};
|
|
129
|
-
|
|
130
|
-
// src/lib/fetch-proxy.ts
|
|
131
|
-
function createFetchProxy(target, options) {
|
|
132
|
-
let localFetch = options?.fetch ?? globalThis.fetch;
|
|
133
|
-
let rewriteCookieDomain = options?.rewriteCookieDomain ?? true;
|
|
134
|
-
let rewriteCookiePath = options?.rewriteCookiePath ?? true;
|
|
135
|
-
let xForwardedHeaders = options?.xForwardedHeaders ?? false;
|
|
136
|
-
let targetUrl = new URL(target);
|
|
137
|
-
if (targetUrl.pathname.endsWith("/")) {
|
|
138
|
-
targetUrl.pathname = targetUrl.pathname.replace(/\/+$/, "");
|
|
139
|
-
}
|
|
140
|
-
return async (input, init) => {
|
|
141
|
-
let request = new Request(input, init);
|
|
142
|
-
let url = new URL(request.url);
|
|
143
|
-
let proxyUrl = new URL(url.search, targetUrl);
|
|
144
|
-
if (url.pathname !== "/") {
|
|
145
|
-
proxyUrl.pathname = proxyUrl.pathname === "/" ? url.pathname : proxyUrl.pathname + url.pathname;
|
|
146
|
-
}
|
|
147
|
-
let proxyHeaders = new Headers(request.headers);
|
|
148
|
-
if (xForwardedHeaders) {
|
|
149
|
-
proxyHeaders.append("X-Forwarded-Proto", url.protocol.replace(/:$/, ""));
|
|
150
|
-
proxyHeaders.append("X-Forwarded-Host", url.host);
|
|
151
|
-
}
|
|
152
|
-
let proxyInit = {
|
|
153
|
-
method: request.method,
|
|
154
|
-
headers: proxyHeaders,
|
|
155
|
-
cache: request.cache,
|
|
156
|
-
credentials: request.credentials,
|
|
157
|
-
integrity: request.integrity,
|
|
158
|
-
keepalive: request.keepalive,
|
|
159
|
-
mode: request.mode,
|
|
160
|
-
redirect: request.redirect,
|
|
161
|
-
referrer: request.referrer,
|
|
162
|
-
referrerPolicy: request.referrerPolicy,
|
|
163
|
-
signal: request.signal,
|
|
164
|
-
...init
|
|
165
|
-
};
|
|
166
|
-
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
167
|
-
proxyInit.body = request.body;
|
|
168
|
-
proxyInit.duplex = "half";
|
|
169
|
-
}
|
|
170
|
-
let response = await localFetch(proxyUrl, proxyInit);
|
|
171
|
-
let responseHeaders = new Headers(response.headers);
|
|
172
|
-
if (responseHeaders.has("Set-Cookie")) {
|
|
173
|
-
let setCookie = responseHeaders.getSetCookie();
|
|
174
|
-
responseHeaders.delete("Set-Cookie");
|
|
175
|
-
for (let cookie of setCookie) {
|
|
176
|
-
let header = new SetCookie(cookie);
|
|
177
|
-
if (rewriteCookieDomain && header.domain) {
|
|
178
|
-
header.domain = url.host;
|
|
179
|
-
}
|
|
180
|
-
if (rewriteCookiePath && header.path) {
|
|
181
|
-
if (header.path.startsWith(targetUrl.pathname + "/")) {
|
|
182
|
-
header.path = header.path.slice(targetUrl.pathname.length);
|
|
183
|
-
} else if (header.path === targetUrl.pathname) {
|
|
184
|
-
header.path = "/";
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
responseHeaders.append("Set-Cookie", header.toString());
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
return new Response(response.body, {
|
|
191
|
-
status: response.status,
|
|
192
|
-
statusText: response.statusText,
|
|
193
|
-
headers: responseHeaders
|
|
194
|
-
});
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
export {
|
|
198
|
-
createFetchProxy
|
|
199
|
-
};
|
|
200
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
export { createFetchProxy } from "./lib/fetch-proxy.js";
|
|
@@ -1,33 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for `createFetchProxy`.
|
|
3
|
+
*/
|
|
1
4
|
export interface FetchProxyOptions {
|
|
2
5
|
/**
|
|
3
|
-
* The `fetch` function to use for the actual fetch.
|
|
6
|
+
* The `fetch` function to use for the actual fetch.
|
|
7
|
+
*
|
|
8
|
+
* @default globalThis.fetch
|
|
4
9
|
*/
|
|
5
10
|
fetch?: typeof globalThis.fetch;
|
|
6
11
|
/**
|
|
7
12
|
* Set `false` to prevent the `Domain` attribute of `Set-Cookie` headers from being rewritten. By
|
|
8
13
|
* default the domain will be rewritten to the domain of the incoming request.
|
|
14
|
+
*
|
|
15
|
+
* @default true
|
|
9
16
|
*/
|
|
10
17
|
rewriteCookieDomain?: boolean;
|
|
11
18
|
/**
|
|
12
19
|
* Set `false` to prevent the `Path` attribute of `Set-Cookie` headers from being rewritten. By
|
|
13
20
|
* default the portion of the pathname that matches the proxy target's pathname will be removed.
|
|
21
|
+
*
|
|
22
|
+
* @default true
|
|
14
23
|
*/
|
|
15
24
|
rewriteCookiePath?: boolean;
|
|
16
25
|
/**
|
|
17
26
|
* Set `true` to add `X-Forwarded-Proto` and `X-Forwarded-Host` headers to the proxied request.
|
|
18
|
-
*
|
|
27
|
+
*
|
|
28
|
+
* @default false
|
|
19
29
|
*/
|
|
20
30
|
xForwardedHeaders?: boolean;
|
|
21
31
|
}
|
|
22
32
|
/**
|
|
23
33
|
* A [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)
|
|
24
34
|
* that forwards requests to another server.
|
|
35
|
+
*
|
|
36
|
+
* @param input The URL or request to forward
|
|
37
|
+
* @param init Optional request init options
|
|
38
|
+
* @returns A promise that resolves to the proxied response
|
|
25
39
|
*/
|
|
26
40
|
export interface FetchProxy {
|
|
27
41
|
(input: URL | RequestInfo, init?: RequestInit): Promise<Response>;
|
|
28
42
|
}
|
|
29
43
|
/**
|
|
30
44
|
* Creates a `fetch` function that forwards requests to another server.
|
|
45
|
+
*
|
|
31
46
|
* @param target The URL of the server to proxy requests to
|
|
32
47
|
* @param options Options to customize the behavior of the proxy
|
|
33
48
|
* @returns A fetch function that forwards requests to the target server
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-proxy.d.ts","sourceRoot":"","sources":["../../src/lib/fetch-proxy.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,iBAAiB;IAChC
|
|
1
|
+
{"version":3,"file":"fetch-proxy.d.ts","sourceRoot":"","sources":["../../src/lib/fetch-proxy.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAA;IAC/B;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAA;CAC5B;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,UAAU;IACzB,CAAC,KAAK,EAAE,GAAG,GAAG,WAAW,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAA;CAClE;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,UAAU,CAoF9F"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { SetCookie } from '@remix-run/headers';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a `fetch` function that forwards requests to another server.
|
|
4
|
+
*
|
|
5
|
+
* @param target The URL of the server to proxy requests to
|
|
6
|
+
* @param options Options to customize the behavior of the proxy
|
|
7
|
+
* @returns A fetch function that forwards requests to the target server
|
|
8
|
+
*/
|
|
9
|
+
export function createFetchProxy(target, options) {
|
|
10
|
+
let localFetch = options?.fetch ?? globalThis.fetch;
|
|
11
|
+
let rewriteCookieDomain = options?.rewriteCookieDomain ?? true;
|
|
12
|
+
let rewriteCookiePath = options?.rewriteCookiePath ?? true;
|
|
13
|
+
let xForwardedHeaders = options?.xForwardedHeaders ?? false;
|
|
14
|
+
let targetUrl = new URL(target);
|
|
15
|
+
if (targetUrl.pathname.endsWith('/')) {
|
|
16
|
+
targetUrl.pathname = targetUrl.pathname.replace(/\/+$/, '');
|
|
17
|
+
}
|
|
18
|
+
return async (input, init) => {
|
|
19
|
+
let request = new Request(input, init);
|
|
20
|
+
let url = new URL(request.url);
|
|
21
|
+
let proxyUrl = new URL(url.search, targetUrl);
|
|
22
|
+
if (url.pathname !== '/') {
|
|
23
|
+
proxyUrl.pathname =
|
|
24
|
+
proxyUrl.pathname === '/' ? url.pathname : proxyUrl.pathname + url.pathname;
|
|
25
|
+
}
|
|
26
|
+
let proxyHeaders = new Headers(request.headers);
|
|
27
|
+
if (xForwardedHeaders) {
|
|
28
|
+
proxyHeaders.append('X-Forwarded-Proto', url.protocol.replace(/:$/, ''));
|
|
29
|
+
proxyHeaders.append('X-Forwarded-Host', url.host);
|
|
30
|
+
}
|
|
31
|
+
let proxyInit = {
|
|
32
|
+
method: request.method,
|
|
33
|
+
headers: proxyHeaders,
|
|
34
|
+
cache: request.cache,
|
|
35
|
+
credentials: request.credentials,
|
|
36
|
+
integrity: request.integrity,
|
|
37
|
+
keepalive: request.keepalive,
|
|
38
|
+
mode: request.mode,
|
|
39
|
+
redirect: request.redirect,
|
|
40
|
+
referrer: request.referrer,
|
|
41
|
+
referrerPolicy: request.referrerPolicy,
|
|
42
|
+
signal: request.signal,
|
|
43
|
+
...init,
|
|
44
|
+
};
|
|
45
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
46
|
+
proxyInit.body = request.body;
|
|
47
|
+
proxyInit.duplex = 'half';
|
|
48
|
+
}
|
|
49
|
+
let response = await localFetch(proxyUrl, proxyInit);
|
|
50
|
+
let responseHeaders = new Headers(response.headers);
|
|
51
|
+
if (responseHeaders.has('Set-Cookie')) {
|
|
52
|
+
let setCookie = responseHeaders.getSetCookie();
|
|
53
|
+
responseHeaders.delete('Set-Cookie');
|
|
54
|
+
for (let cookie of setCookie) {
|
|
55
|
+
let header = new SetCookie(cookie);
|
|
56
|
+
if (rewriteCookieDomain && header.domain) {
|
|
57
|
+
header.domain = url.host;
|
|
58
|
+
}
|
|
59
|
+
if (rewriteCookiePath && header.path) {
|
|
60
|
+
if (header.path.startsWith(targetUrl.pathname + '/')) {
|
|
61
|
+
header.path = header.path.slice(targetUrl.pathname.length);
|
|
62
|
+
}
|
|
63
|
+
else if (header.path === targetUrl.pathname) {
|
|
64
|
+
header.path = '/';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
responseHeaders.append('Set-Cookie', header.toString());
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return new Response(response.body, {
|
|
71
|
+
status: response.status,
|
|
72
|
+
statusText: response.statusText,
|
|
73
|
+
headers: responseHeaders,
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@remix-run/fetch-proxy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "An HTTP proxy for the web Fetch API",
|
|
5
5
|
"author": "Michael Jackson <mjijackson@gmail.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -26,11 +26,11 @@
|
|
|
26
26
|
"./package.json": "./package.json"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@remix-run/headers": "^0.
|
|
29
|
+
"@remix-run/headers": "^0.19.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@types/node": "^24.6.0",
|
|
33
|
-
"
|
|
33
|
+
"@typescript/native-preview": "7.0.0-dev.20251125.1"
|
|
34
34
|
},
|
|
35
35
|
"keywords": [
|
|
36
36
|
"fetch",
|
|
@@ -38,11 +38,9 @@
|
|
|
38
38
|
"proxy"
|
|
39
39
|
],
|
|
40
40
|
"scripts": {
|
|
41
|
-
"build": "
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
"test": "node --disable-warning=ExperimentalWarning --test './src/**/*.test.ts'",
|
|
46
|
-
"typecheck": "tsc --noEmit"
|
|
41
|
+
"build": "tsgo -p tsconfig.build.json",
|
|
42
|
+
"clean": "git clean -fdX",
|
|
43
|
+
"test": "node --disable-warning=ExperimentalWarning --test",
|
|
44
|
+
"typecheck": "tsgo --noEmit"
|
|
47
45
|
}
|
|
48
46
|
}
|
package/src/lib/fetch-proxy.ts
CHANGED
|
@@ -1,23 +1,33 @@
|
|
|
1
1
|
import { SetCookie } from '@remix-run/headers'
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Options for `createFetchProxy`.
|
|
5
|
+
*/
|
|
3
6
|
export interface FetchProxyOptions {
|
|
4
7
|
/**
|
|
5
|
-
* The `fetch` function to use for the actual fetch.
|
|
8
|
+
* The `fetch` function to use for the actual fetch.
|
|
9
|
+
*
|
|
10
|
+
* @default globalThis.fetch
|
|
6
11
|
*/
|
|
7
12
|
fetch?: typeof globalThis.fetch
|
|
8
13
|
/**
|
|
9
14
|
* Set `false` to prevent the `Domain` attribute of `Set-Cookie` headers from being rewritten. By
|
|
10
15
|
* default the domain will be rewritten to the domain of the incoming request.
|
|
16
|
+
*
|
|
17
|
+
* @default true
|
|
11
18
|
*/
|
|
12
19
|
rewriteCookieDomain?: boolean
|
|
13
20
|
/**
|
|
14
21
|
* Set `false` to prevent the `Path` attribute of `Set-Cookie` headers from being rewritten. By
|
|
15
22
|
* default the portion of the pathname that matches the proxy target's pathname will be removed.
|
|
23
|
+
*
|
|
24
|
+
* @default true
|
|
16
25
|
*/
|
|
17
26
|
rewriteCookiePath?: boolean
|
|
18
27
|
/**
|
|
19
28
|
* Set `true` to add `X-Forwarded-Proto` and `X-Forwarded-Host` headers to the proxied request.
|
|
20
|
-
*
|
|
29
|
+
*
|
|
30
|
+
* @default false
|
|
21
31
|
*/
|
|
22
32
|
xForwardedHeaders?: boolean
|
|
23
33
|
}
|
|
@@ -25,6 +35,10 @@ export interface FetchProxyOptions {
|
|
|
25
35
|
/**
|
|
26
36
|
* A [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)
|
|
27
37
|
* that forwards requests to another server.
|
|
38
|
+
*
|
|
39
|
+
* @param input The URL or request to forward
|
|
40
|
+
* @param init Optional request init options
|
|
41
|
+
* @returns A promise that resolves to the proxied response
|
|
28
42
|
*/
|
|
29
43
|
export interface FetchProxy {
|
|
30
44
|
(input: URL | RequestInfo, init?: RequestInit): Promise<Response>
|
|
@@ -32,6 +46,7 @@ export interface FetchProxy {
|
|
|
32
46
|
|
|
33
47
|
/**
|
|
34
48
|
* Creates a `fetch` function that forwards requests to another server.
|
|
49
|
+
*
|
|
35
50
|
* @param target The URL of the server to proxy requests to
|
|
36
51
|
* @param options Options to customize the behavior of the proxy
|
|
37
52
|
* @returns A fetch function that forwards requests to the target server
|
package/dist/index.js.map
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../headers/src/lib/param-values.ts", "../../headers/src/lib/utils.ts", "../../headers/src/lib/set-cookie.ts", "../src/lib/fetch-proxy.ts"],
|
|
4
|
-
"sourcesContent": ["export function parseParams(\n input: string,\n delimiter: ';' | ',' = ';',\n): [string, string | undefined][] {\n // This parser splits on the delimiter and unquotes any quoted values\n // like `filename=\"the\\\\ filename.txt\"`.\n let parser =\n delimiter === ';'\n ? /(?:^|;)\\s*([^=;\\s]+)(\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|((?:[^;]|\\\\\\;)+))?)?/g\n : /(?:^|,)\\s*([^=,\\s]+)(\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|((?:[^,]|\\\\\\,)+))?)?/g\n\n let params: [string, string | undefined][] = []\n\n let match\n while ((match = parser.exec(input)) !== null) {\n let key = match[1].trim()\n\n let value: string | undefined\n if (match[2]) {\n value = (match[3] || match[4] || '').replace(/\\\\(.)/g, '$1').trim()\n }\n\n params.push([key, value])\n }\n\n return params\n}\n\nexport function quote(value: string): string {\n if (value.includes('\"') || value.includes(';') || value.includes(' ')) {\n return `\"${value.replace(/\"/g, '\\\\\"')}\"`\n }\n return value\n}\n", "export function capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()\n}\n\nexport function isIterable<T>(value: any): value is Iterable<T> {\n return value != null && typeof value[Symbol.iterator] === 'function'\n}\n\nexport function isValidDate(date: unknown): boolean {\n return date instanceof Date && !isNaN(date.getTime())\n}\n\nexport function quoteEtag(tag: string): string {\n return tag === '*' ? tag : /^(W\\/)?\".*\"$/.test(tag) ? tag : `\"${tag}\"`\n}\n", "import { type HeaderValue } from './header-value.ts'\nimport { parseParams, quote } from './param-values.ts'\nimport { capitalize, isValidDate } from './utils.ts'\n\ntype SameSiteValue = 'Strict' | 'Lax' | 'None'\n\nexport interface SetCookieInit {\n /**\n * The domain of the cookie. For example, `example.com`.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#domaindomain-value)\n */\n domain?: string\n /**\n * The expiration date of the cookie. If not specified, the cookie is a session cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#expiresdate)\n */\n expires?: Date\n /**\n * Indicates this cookie should not be accessible via JavaScript.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#httponly)\n */\n httpOnly?: true\n /**\n * The maximum age of the cookie in seconds.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#max-age)\n */\n maxAge?: number\n /**\n * The name of the cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie-namecookie-value)\n */\n name?: string\n /**\n * The path of the cookie. For example, `/` or `/admin`.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#pathpath-value)\n */\n path?: string\n /**\n * The `SameSite` attribute of the cookie. This attribute lets servers require that a cookie shouldn't be sent with\n * cross-site requests, which provides some protection against cross-site request forgery attacks.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)\n */\n sameSite?: SameSiteValue\n /**\n * Indicates the cookie should only be sent over HTTPS.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#secure)\n */\n secure?: true\n /**\n * The value of the cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie-namecookie-value)\n */\n value?: string\n}\n\n/**\n * The value of a `Set-Cookie` HTTP header.\n *\n * [MDN `Set-Cookie` Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)\n *\n * [HTTP/1.1 Specification](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1)\n */\nexport class SetCookie implements HeaderValue, SetCookieInit {\n domain?: string\n expires?: Date\n httpOnly?: true\n maxAge?: number\n name?: string\n path?: string\n sameSite?: SameSiteValue\n secure?: true\n value?: string\n\n constructor(init?: string | SetCookieInit) {\n if (init) {\n if (typeof init === 'string') {\n let params = parseParams(init)\n if (params.length > 0) {\n this.name = params[0][0]\n this.value = params[0][1]\n\n for (let [key, value] of params.slice(1)) {\n switch (key.toLowerCase()) {\n case 'domain':\n this.domain = value\n break\n case 'expires': {\n if (typeof value === 'string') {\n let date = new Date(value)\n if (isValidDate(date)) {\n this.expires = date\n }\n }\n break\n }\n case 'httponly':\n this.httpOnly = true\n break\n case 'max-age': {\n if (typeof value === 'string') {\n let v = parseInt(value, 10)\n if (!isNaN(v)) this.maxAge = v\n }\n break\n }\n case 'path':\n this.path = value\n break\n case 'samesite':\n if (typeof value === 'string' && /strict|lax|none/i.test(value)) {\n this.sameSite = capitalize(value) as SameSiteValue\n }\n break\n case 'secure':\n this.secure = true\n break\n }\n }\n }\n } else {\n this.domain = init.domain\n this.expires = init.expires\n this.httpOnly = init.httpOnly\n this.maxAge = init.maxAge\n this.name = init.name\n this.path = init.path\n this.sameSite = init.sameSite\n this.secure = init.secure\n this.value = init.value\n }\n }\n }\n\n toString(): string {\n if (!this.name) {\n return ''\n }\n\n let parts = [`${this.name}=${quote(this.value || '')}`]\n\n if (this.domain) {\n parts.push(`Domain=${this.domain}`)\n }\n if (this.path) {\n parts.push(`Path=${this.path}`)\n }\n if (this.expires) {\n parts.push(`Expires=${this.expires.toUTCString()}`)\n }\n if (this.maxAge) {\n parts.push(`Max-Age=${this.maxAge}`)\n }\n if (this.secure) {\n parts.push('Secure')\n }\n if (this.httpOnly) {\n parts.push('HttpOnly')\n }\n if (this.sameSite) {\n parts.push(`SameSite=${this.sameSite}`)\n }\n\n return parts.join('; ')\n }\n}\n", "import { SetCookie } from '@remix-run/headers'\n\nexport interface FetchProxyOptions {\n /**\n * The `fetch` function to use for the actual fetch. Defaults to the global `fetch` function.\n */\n fetch?: typeof globalThis.fetch\n /**\n * Set `false` to prevent the `Domain` attribute of `Set-Cookie` headers from being rewritten. By\n * default the domain will be rewritten to the domain of the incoming request.\n */\n rewriteCookieDomain?: boolean\n /**\n * Set `false` to prevent the `Path` attribute of `Set-Cookie` headers from being rewritten. By\n * default the portion of the pathname that matches the proxy target's pathname will be removed.\n */\n rewriteCookiePath?: boolean\n /**\n * Set `true` to add `X-Forwarded-Proto` and `X-Forwarded-Host` headers to the proxied request.\n * Defaults to `false`.\n */\n xForwardedHeaders?: boolean\n}\n\n/**\n * A [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)\n * that forwards requests to another server.\n */\nexport interface FetchProxy {\n (input: URL | RequestInfo, init?: RequestInit): Promise<Response>\n}\n\n/**\n * Creates a `fetch` function that forwards requests to another server.\n * @param target The URL of the server to proxy requests to\n * @param options Options to customize the behavior of the proxy\n * @returns A fetch function that forwards requests to the target server\n */\nexport function createFetchProxy(target: string | URL, options?: FetchProxyOptions): FetchProxy {\n let localFetch = options?.fetch ?? globalThis.fetch\n let rewriteCookieDomain = options?.rewriteCookieDomain ?? true\n let rewriteCookiePath = options?.rewriteCookiePath ?? true\n let xForwardedHeaders = options?.xForwardedHeaders ?? false\n\n let targetUrl = new URL(target)\n if (targetUrl.pathname.endsWith('/')) {\n targetUrl.pathname = targetUrl.pathname.replace(/\\/+$/, '')\n }\n\n return async (input: URL | RequestInfo, init?: RequestInit) => {\n let request = new Request(input, init)\n let url = new URL(request.url)\n\n let proxyUrl = new URL(url.search, targetUrl)\n if (url.pathname !== '/') {\n proxyUrl.pathname =\n proxyUrl.pathname === '/' ? url.pathname : proxyUrl.pathname + url.pathname\n }\n\n let proxyHeaders = new Headers(request.headers)\n if (xForwardedHeaders) {\n proxyHeaders.append('X-Forwarded-Proto', url.protocol.replace(/:$/, ''))\n proxyHeaders.append('X-Forwarded-Host', url.host)\n }\n\n let proxyInit: RequestInit = {\n method: request.method,\n headers: proxyHeaders,\n cache: request.cache,\n credentials: request.credentials,\n integrity: request.integrity,\n keepalive: request.keepalive,\n mode: request.mode,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n signal: request.signal,\n ...init,\n }\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n proxyInit.body = request.body\n\n // init.duplex = 'half' must be set when body is a ReadableStream, and Node follows the spec.\n // However, this property is not defined in the TypeScript types for RequestInit, so we have\n // to cast it here in order to set it without a type error.\n // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex\n ;(proxyInit as { duplex: 'half' }).duplex = 'half'\n }\n\n let response = await localFetch(proxyUrl, proxyInit)\n let responseHeaders = new Headers(response.headers)\n\n if (responseHeaders.has('Set-Cookie')) {\n let setCookie = responseHeaders.getSetCookie()\n\n responseHeaders.delete('Set-Cookie')\n\n for (let cookie of setCookie) {\n let header = new SetCookie(cookie)\n\n if (rewriteCookieDomain && header.domain) {\n header.domain = url.host\n }\n\n if (rewriteCookiePath && header.path) {\n if (header.path.startsWith(targetUrl.pathname + '/')) {\n header.path = header.path.slice(targetUrl.pathname.length)\n } else if (header.path === targetUrl.pathname) {\n header.path = '/'\n }\n }\n\n responseHeaders.append('Set-Cookie', header.toString())\n }\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n })\n }\n}\n"],
|
|
5
|
-
"mappings": ";AAAO,SAAS,YACd,OACA,YAAuB,KACS;AAGhC,MAAI,SACF,cAAc,MACV,6EACA;AAEN,MAAI,SAAyC,CAAC;AAE9C,MAAI;AACJ,UAAQ,QAAQ,OAAO,KAAK,KAAK,OAAO,MAAM;AAC5C,QAAI,MAAM,MAAM,CAAC,EAAE,KAAK;AAExB,QAAI;AACJ,QAAI,MAAM,CAAC,GAAG;AACZ,eAAS,MAAM,CAAC,KAAK,MAAM,C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