@zuplo/cli 6.73.17 → 6.73.19
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/node_modules/@hono/node-server/README.md +58 -25
- package/node_modules/@hono/node-server/dist/conninfo.cjs +22 -0
- package/node_modules/@hono/node-server/dist/{conninfo.d.ts → conninfo.d.cts} +4 -3
- package/node_modules/@hono/node-server/dist/conninfo.d.mts +4 -3
- package/node_modules/@hono/node-server/dist/conninfo.mjs +19 -16
- package/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs +5 -0
- package/node_modules/@hono/node-server/dist/constants-BXAKTxRC.cjs +11 -0
- package/node_modules/@hono/node-server/dist/index.cjs +1173 -0
- package/node_modules/@hono/node-server/dist/index.d.cts +101 -0
- package/node_modules/@hono/node-server/dist/index.d.mts +101 -8
- package/node_modules/@hono/node-server/dist/index.mjs +1143 -637
- package/node_modules/@hono/node-server/dist/serve-static.cjs +151 -0
- package/node_modules/@hono/node-server/dist/serve-static.d.cts +18 -0
- package/node_modules/@hono/node-server/dist/serve-static.d.mts +14 -13
- package/node_modules/@hono/node-server/dist/serve-static.mjs +143 -145
- package/node_modules/@hono/node-server/dist/utils/response.cjs +8 -0
- package/node_modules/@hono/node-server/dist/utils/response.d.cts +4 -0
- package/node_modules/@hono/node-server/dist/utils/response.d.mts +3 -2
- package/node_modules/@hono/node-server/dist/utils/response.mjs +6 -9
- package/node_modules/@hono/node-server/dist/utils/stream.cjs +65 -0
- package/node_modules/@hono/node-server/dist/utils/stream.d.cts +6 -0
- package/node_modules/@hono/node-server/dist/utils/stream.d.mts +6 -0
- package/node_modules/@hono/node-server/dist/utils/stream.mjs +64 -0
- package/node_modules/@hono/node-server/package.json +65 -54
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js +1 -12
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts +7 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js +9 -3
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js +5 -3
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js +1 -12
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sseKeepAlive.d.ts +5 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sseKeepAlive.d.ts.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sseKeepAlive.js +17 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sseKeepAlive.js.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts +9 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js +10 -4
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts +21 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js +239 -41
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js +25 -6
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/mediaType.d.ts +32 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/mediaType.d.ts.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/mediaType.js +64 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/mediaType.js.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts +5 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js +10 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js +2 -13
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts +7 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js +9 -3
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js +5 -3
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js +2 -13
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.d.ts +5 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.d.ts.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.js +13 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.js.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts +9 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js +10 -4
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts +21 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js +239 -41
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js +25 -6
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.d.ts +32 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.d.ts.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js +57 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts +5 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js +9 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/package.json +4 -3
- package/node_modules/@zuplo/core/package.json +1 -1
- package/node_modules/@zuplo/graphql/package.json +1 -1
- package/node_modules/@zuplo/openapi-tools/package.json +1 -1
- package/node_modules/@zuplo/otel/out/esm/chunk-JYT2Q52R.js +26 -0
- package/node_modules/@zuplo/otel/out/esm/chunk-JYT2Q52R.js.map +1 -0
- package/node_modules/@zuplo/otel/out/esm/index.js +1 -1
- package/node_modules/@zuplo/otel/package.json +1 -1
- package/node_modules/@zuplo/runtime/out/esm/{chunk-OAVAM6CR.js → chunk-JPPAUB3E.js} +3 -3
- package/node_modules/@zuplo/runtime/out/esm/chunk-JPPAUB3E.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/types/index.d.ts +10 -3
- package/node_modules/@zuplo/runtime/package.json +1 -1
- package/node_modules/express-rate-limit/dist/index.d.cts +10 -12
- package/node_modules/express-rate-limit/dist/index.d.mts +10 -12
- package/node_modules/express-rate-limit/dist/index.d.ts +10 -12
- package/node_modules/express-rate-limit/package.json +5 -5
- package/node_modules/express-rate-limit/readme.md +2 -2
- package/node_modules/ip-address/README.md +102 -100
- package/node_modules/ip-address/dist/common.d.ts +23 -0
- package/node_modules/ip-address/dist/common.js +27 -4
- package/node_modules/ip-address/dist/common.js.map +1 -1
- package/node_modules/ip-address/dist/ipv4.d.ts +7 -0
- package/node_modules/ip-address/dist/ipv4.js +19 -7
- package/node_modules/ip-address/dist/ipv4.js.map +1 -1
- package/node_modules/ip-address/dist/ipv6.d.ts +7 -0
- package/node_modules/ip-address/dist/ipv6.js +38 -25
- package/node_modules/ip-address/dist/ipv6.js.map +1 -1
- package/node_modules/ip-address/dist/v4/constants.js +5 -1
- package/node_modules/ip-address/dist/v4/constants.js.map +1 -1
- package/node_modules/ip-address/package.json +2 -2
- package/package.json +6 -6
- package/node_modules/@hono/node-server/dist/conninfo.js +0 -42
- package/node_modules/@hono/node-server/dist/globals.d.mts +0 -2
- package/node_modules/@hono/node-server/dist/globals.d.ts +0 -2
- package/node_modules/@hono/node-server/dist/globals.js +0 -29
- package/node_modules/@hono/node-server/dist/globals.mjs +0 -5
- package/node_modules/@hono/node-server/dist/index.d.ts +0 -8
- package/node_modules/@hono/node-server/dist/index.js +0 -702
- package/node_modules/@hono/node-server/dist/listener.d.mts +0 -13
- package/node_modules/@hono/node-server/dist/listener.d.ts +0 -13
- package/node_modules/@hono/node-server/dist/listener.js +0 -670
- package/node_modules/@hono/node-server/dist/listener.mjs +0 -635
- package/node_modules/@hono/node-server/dist/request.d.mts +0 -25
- package/node_modules/@hono/node-server/dist/request.d.ts +0 -25
- package/node_modules/@hono/node-server/dist/request.js +0 -238
- package/node_modules/@hono/node-server/dist/request.mjs +0 -206
- package/node_modules/@hono/node-server/dist/response.d.mts +0 -26
- package/node_modules/@hono/node-server/dist/response.d.ts +0 -26
- package/node_modules/@hono/node-server/dist/response.js +0 -112
- package/node_modules/@hono/node-server/dist/response.mjs +0 -85
- package/node_modules/@hono/node-server/dist/serve-static.d.ts +0 -17
- package/node_modules/@hono/node-server/dist/serve-static.js +0 -177
- package/node_modules/@hono/node-server/dist/server.d.mts +0 -10
- package/node_modules/@hono/node-server/dist/server.d.ts +0 -10
- package/node_modules/@hono/node-server/dist/server.js +0 -696
- package/node_modules/@hono/node-server/dist/server.mjs +0 -660
- package/node_modules/@hono/node-server/dist/types.d.mts +0 -44
- package/node_modules/@hono/node-server/dist/types.d.ts +0 -44
- package/node_modules/@hono/node-server/dist/types.js +0 -18
- package/node_modules/@hono/node-server/dist/types.mjs +0 -0
- package/node_modules/@hono/node-server/dist/utils/response/constants.d.mts +0 -3
- package/node_modules/@hono/node-server/dist/utils/response/constants.d.ts +0 -3
- package/node_modules/@hono/node-server/dist/utils/response/constants.js +0 -30
- package/node_modules/@hono/node-server/dist/utils/response/constants.mjs +0 -5
- package/node_modules/@hono/node-server/dist/utils/response.d.ts +0 -3
- package/node_modules/@hono/node-server/dist/utils/response.js +0 -37
- package/node_modules/@hono/node-server/dist/utils.d.mts +0 -9
- package/node_modules/@hono/node-server/dist/utils.d.ts +0 -9
- package/node_modules/@hono/node-server/dist/utils.js +0 -99
- package/node_modules/@hono/node-server/dist/utils.mjs +0 -71
- package/node_modules/@hono/node-server/dist/vercel.d.mts +0 -7
- package/node_modules/@hono/node-server/dist/vercel.d.ts +0 -7
- package/node_modules/@hono/node-server/dist/vercel.js +0 -677
- package/node_modules/@hono/node-server/dist/vercel.mjs +0 -640
- package/node_modules/@zuplo/otel/out/esm/chunk-JWNK52ES.js +0 -26
- package/node_modules/@zuplo/otel/out/esm/chunk-JWNK52ES.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-OAVAM6CR.js.map +0 -1
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-OAVAM6CR.js.LEGAL.txt → chunk-JPPAUB3E.js.LEGAL.txt} +0 -0
|
@@ -1,662 +1,1168 @@
|
|
|
1
|
-
|
|
2
|
-
import { createServer
|
|
1
|
+
import { t as X_ALREADY_SENT } from "./constants-BLSFu_RU.mjs";
|
|
2
|
+
import { STATUS_CODES, createServer } from "node:http";
|
|
3
|
+
import { Http2ServerRequest, constants } from "node:http2";
|
|
4
|
+
import { Readable } from "node:stream";
|
|
5
|
+
import { defineWebSocketHelper } from "hono/ws";
|
|
3
6
|
|
|
4
|
-
|
|
5
|
-
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
|
6
|
-
|
|
7
|
-
// src/request.ts
|
|
8
|
-
import { Http2ServerRequest } from "http2";
|
|
9
|
-
import { Readable } from "stream";
|
|
7
|
+
//#region src/error.ts
|
|
10
8
|
var RequestError = class extends Error {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
9
|
+
constructor(message, options) {
|
|
10
|
+
super(message, options);
|
|
11
|
+
this.name = "RequestError";
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/url.ts
|
|
17
|
+
const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
|
|
18
|
+
const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
|
|
19
|
+
const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
|
|
20
|
+
const buildUrl = (scheme, host, incomingUrl) => {
|
|
21
|
+
const url = `${scheme}://${host}${incomingUrl}`;
|
|
22
|
+
if (!reValidHost.test(host)) {
|
|
23
|
+
const urlObj = new URL(url);
|
|
24
|
+
if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
|
|
25
|
+
return urlObj.href;
|
|
26
|
+
} else if (incomingUrl.length === 0) return url + "/";
|
|
27
|
+
else {
|
|
28
|
+
if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
|
|
29
|
+
if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
|
|
30
|
+
return url;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/request.ts
|
|
36
|
+
const toRequestError = (e) => {
|
|
37
|
+
if (e instanceof RequestError) return e;
|
|
38
|
+
return new RequestError(e.message, { cause: e });
|
|
39
|
+
};
|
|
40
|
+
const GlobalRequest = global.Request;
|
|
41
|
+
var Request$1 = class extends GlobalRequest {
|
|
42
|
+
constructor(input, options) {
|
|
43
|
+
if (typeof input === "object" && getRequestCache in input) {
|
|
44
|
+
const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
|
|
45
|
+
if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
|
|
46
|
+
input = input[getRequestCache]();
|
|
47
|
+
}
|
|
48
|
+
if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
|
|
49
|
+
super(input, options);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const newHeadersFromIncoming = (incoming) => {
|
|
53
|
+
const headerRecord = [];
|
|
54
|
+
const rawHeaders = incoming.rawHeaders;
|
|
55
|
+
for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
|
|
56
|
+
const key = rawHeaders[i];
|
|
57
|
+
if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
|
|
58
|
+
}
|
|
59
|
+
return new Headers(headerRecord);
|
|
60
|
+
};
|
|
61
|
+
const wrapBodyStream = Symbol("wrapBodyStream");
|
|
62
|
+
const byteExactEncodings = new Set([
|
|
63
|
+
"latin1",
|
|
64
|
+
"binary",
|
|
65
|
+
"hex",
|
|
66
|
+
"base64",
|
|
67
|
+
"base64url"
|
|
68
|
+
]);
|
|
69
|
+
const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
|
|
70
|
+
const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
|
|
71
|
+
const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
|
|
72
|
+
const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
|
|
73
|
+
const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
|
|
74
|
+
const recordBodyBufferedBeforeDisconnect = (incoming) => {
|
|
75
|
+
if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
|
|
76
|
+
const incomingWithRecovery = incoming;
|
|
77
|
+
incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
|
|
78
|
+
};
|
|
79
|
+
const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
|
|
80
|
+
if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
|
|
81
|
+
const incomingWithRecovery = incoming;
|
|
82
|
+
if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
|
|
83
|
+
let result;
|
|
84
|
+
const errored = incoming.errored;
|
|
85
|
+
if (errored && errored.code !== "ECONNRESET") result = errored;
|
|
86
|
+
else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
|
|
87
|
+
else {
|
|
88
|
+
const bodyChunks = chunks ?? [];
|
|
89
|
+
const chunk = incoming.read();
|
|
90
|
+
if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
|
|
91
|
+
const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
|
|
92
|
+
result = buffer;
|
|
93
|
+
const contentLength = incoming.headers["content-length"];
|
|
94
|
+
if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
|
|
95
|
+
const expectedLength = Number(contentLength);
|
|
96
|
+
if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
|
|
100
|
+
return result;
|
|
101
|
+
};
|
|
102
|
+
const enqueueBufferedBody = (controller, buffered) => {
|
|
103
|
+
if (buffered instanceof Error) {
|
|
104
|
+
controller.error(buffered);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (buffered.length > 0) controller.enqueue(buffered);
|
|
108
|
+
controller.close();
|
|
109
|
+
};
|
|
110
|
+
const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
111
|
+
const init = {
|
|
112
|
+
method,
|
|
113
|
+
headers,
|
|
114
|
+
signal: abortController.signal
|
|
115
|
+
};
|
|
116
|
+
if (method === "TRACE") {
|
|
117
|
+
init.method = "GET";
|
|
118
|
+
const req = new Request$1(url, init);
|
|
119
|
+
Object.defineProperty(req, "method", { get() {
|
|
120
|
+
return "TRACE";
|
|
121
|
+
} });
|
|
122
|
+
return req;
|
|
123
|
+
}
|
|
124
|
+
if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
|
|
125
|
+
controller.enqueue(incoming.rawBody);
|
|
126
|
+
controller.close();
|
|
127
|
+
} });
|
|
128
|
+
else if (incoming[wrapBodyStream]) {
|
|
129
|
+
let reader;
|
|
130
|
+
init.body = new ReadableStream({ async pull(controller) {
|
|
131
|
+
try {
|
|
132
|
+
if (!reader) {
|
|
133
|
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
|
134
|
+
if (buffered !== void 0) {
|
|
135
|
+
enqueueBufferedBody(controller, buffered);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
140
|
+
const { done, value } = await reader.read();
|
|
141
|
+
if (done) controller.close();
|
|
142
|
+
else controller.enqueue(value);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
controller.error(error);
|
|
145
|
+
}
|
|
146
|
+
} });
|
|
147
|
+
} else {
|
|
148
|
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
|
149
|
+
if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
|
|
150
|
+
enqueueBufferedBody(controller, buffered);
|
|
151
|
+
} });
|
|
152
|
+
else init.body = Readable.toWeb(incoming);
|
|
153
|
+
}
|
|
154
|
+
return new Request$1(url, init);
|
|
155
|
+
};
|
|
156
|
+
const getRequestCache = Symbol("getRequestCache");
|
|
157
|
+
const requestCache = Symbol("requestCache");
|
|
158
|
+
const incomingKey = Symbol("incomingKey");
|
|
159
|
+
const urlKey = Symbol("urlKey");
|
|
160
|
+
const methodKey = Symbol("methodKey");
|
|
161
|
+
const headersKey = Symbol("headersKey");
|
|
162
|
+
const abortControllerKey = Symbol("abortControllerKey");
|
|
163
|
+
const getAbortController = Symbol("getAbortController");
|
|
164
|
+
const abortRequest = Symbol("abortRequest");
|
|
165
|
+
const bodyBufferKey = Symbol("bodyBuffer");
|
|
166
|
+
const bodyReadPromiseKey = Symbol("bodyReadPromise");
|
|
167
|
+
const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
|
|
168
|
+
const bodyLockReaderKey = Symbol("bodyLockReader");
|
|
169
|
+
const abortReasonKey = Symbol("abortReason");
|
|
170
|
+
const newBodyUnusableError = () => {
|
|
171
|
+
return /* @__PURE__ */ new TypeError("Body is unusable");
|
|
172
|
+
};
|
|
173
|
+
const rejectBodyUnusable = () => {
|
|
174
|
+
return Promise.reject(newBodyUnusableError());
|
|
126
175
|
};
|
|
176
|
+
const textDecoder = new TextDecoder();
|
|
177
|
+
const consumeBodyDirectOnce = (request) => {
|
|
178
|
+
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
|
179
|
+
request[bodyConsumedDirectlyKey] = true;
|
|
180
|
+
};
|
|
181
|
+
const toArrayBuffer = (buf) => {
|
|
182
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
183
|
+
};
|
|
184
|
+
const contentType = (request) => {
|
|
185
|
+
return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
|
|
186
|
+
};
|
|
187
|
+
const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
188
|
+
const normalizeIncomingMethod = (method) => {
|
|
189
|
+
if (typeof method !== "string" || method.length === 0) return "GET";
|
|
190
|
+
switch (method) {
|
|
191
|
+
case "DELETE":
|
|
192
|
+
case "GET":
|
|
193
|
+
case "HEAD":
|
|
194
|
+
case "OPTIONS":
|
|
195
|
+
case "PATCH":
|
|
196
|
+
case "POST":
|
|
197
|
+
case "PUT":
|
|
198
|
+
case "QUERY": return method;
|
|
199
|
+
}
|
|
200
|
+
const upper = method.toUpperCase();
|
|
201
|
+
switch (upper) {
|
|
202
|
+
case "DELETE":
|
|
203
|
+
case "GET":
|
|
204
|
+
case "HEAD":
|
|
205
|
+
case "OPTIONS":
|
|
206
|
+
case "POST":
|
|
207
|
+
case "PUT": return upper;
|
|
208
|
+
default: return method;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
const validateDirectReadMethod = (method) => {
|
|
212
|
+
if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
|
|
213
|
+
const normalized = method.toUpperCase();
|
|
214
|
+
if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
|
|
215
|
+
};
|
|
216
|
+
const readBodyWithFastPath = (request, method, fromBuffer) => {
|
|
217
|
+
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
|
218
|
+
const methodName = request.method;
|
|
219
|
+
if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
|
|
220
|
+
const methodValidationError = validateDirectReadMethod(methodName);
|
|
221
|
+
if (methodValidationError) return Promise.reject(methodValidationError);
|
|
222
|
+
if (request[requestCache]) {
|
|
223
|
+
if (methodName !== "TRACE") return request[requestCache][method]();
|
|
224
|
+
}
|
|
225
|
+
const alreadyUsedError = consumeBodyDirectOnce(request);
|
|
226
|
+
if (alreadyUsedError) return alreadyUsedError;
|
|
227
|
+
const raw = readRawBodyIfAvailable(request);
|
|
228
|
+
if (raw) {
|
|
229
|
+
const result = Promise.resolve(fromBuffer(raw, request));
|
|
230
|
+
request[bodyBufferKey] = void 0;
|
|
231
|
+
return result;
|
|
232
|
+
}
|
|
233
|
+
return readBodyDirect(request).then((buf) => {
|
|
234
|
+
const result = fromBuffer(buf, request);
|
|
235
|
+
request[bodyBufferKey] = void 0;
|
|
236
|
+
return result;
|
|
237
|
+
});
|
|
238
|
+
};
|
|
239
|
+
const readRawBodyIfAvailable = (request) => {
|
|
240
|
+
const incoming = request[incomingKey];
|
|
241
|
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
|
|
242
|
+
};
|
|
243
|
+
const normalizeAbortError = (request, incoming) => {
|
|
244
|
+
if (incoming.errored) return incoming.errored;
|
|
245
|
+
const reason = request[abortReasonKey];
|
|
246
|
+
if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
|
|
247
|
+
return /* @__PURE__ */ new Error("Client connection prematurely closed.");
|
|
248
|
+
};
|
|
249
|
+
const readBodyDirect = (request) => {
|
|
250
|
+
if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
|
|
251
|
+
if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
|
|
252
|
+
const incoming = request[incomingKey];
|
|
253
|
+
if (incoming.readableDidRead) return rejectBodyUnusable();
|
|
254
|
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
|
255
|
+
if (buffered !== void 0) {
|
|
256
|
+
if (buffered instanceof Error) return Promise.reject(buffered);
|
|
257
|
+
request[bodyBufferKey] = buffered;
|
|
258
|
+
return Promise.resolve(buffered);
|
|
259
|
+
}
|
|
260
|
+
const promise = new Promise((resolve, reject) => {
|
|
261
|
+
const chunks = [];
|
|
262
|
+
let settled = false;
|
|
263
|
+
const finish = (callback) => {
|
|
264
|
+
if (settled) return;
|
|
265
|
+
settled = true;
|
|
266
|
+
cleanup();
|
|
267
|
+
callback();
|
|
268
|
+
};
|
|
269
|
+
const recoverCompleteBodyAfterDisconnect = (error) => {
|
|
270
|
+
const streamError = incoming.errored ?? error;
|
|
271
|
+
if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
|
|
272
|
+
finish(() => {
|
|
273
|
+
const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
|
|
274
|
+
if (recovered instanceof Error) reject(recovered);
|
|
275
|
+
else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
|
|
276
|
+
else {
|
|
277
|
+
request[bodyBufferKey] = recovered;
|
|
278
|
+
resolve(recovered);
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
return true;
|
|
282
|
+
};
|
|
283
|
+
const onData = (chunk) => {
|
|
284
|
+
chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
|
|
285
|
+
};
|
|
286
|
+
const onEnd = () => {
|
|
287
|
+
finish(() => {
|
|
288
|
+
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
|
|
289
|
+
request[bodyBufferKey] = buffer;
|
|
290
|
+
resolve(buffer);
|
|
291
|
+
});
|
|
292
|
+
};
|
|
293
|
+
const onError = (error) => {
|
|
294
|
+
if (recoverCompleteBodyAfterDisconnect(error)) return;
|
|
295
|
+
finish(() => {
|
|
296
|
+
reject(error);
|
|
297
|
+
});
|
|
298
|
+
};
|
|
299
|
+
const onClose = () => {
|
|
300
|
+
if (incoming.readableEnded) {
|
|
301
|
+
onEnd();
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
if (recoverCompleteBodyAfterDisconnect()) return;
|
|
305
|
+
finish(() => {
|
|
306
|
+
reject(normalizeAbortError(request, incoming));
|
|
307
|
+
});
|
|
308
|
+
};
|
|
309
|
+
const cleanup = () => {
|
|
310
|
+
incoming.off("data", onData);
|
|
311
|
+
incoming.off("end", onEnd);
|
|
312
|
+
incoming.off("error", onError);
|
|
313
|
+
incoming.off("close", onClose);
|
|
314
|
+
request[bodyReadPromiseKey] = void 0;
|
|
315
|
+
};
|
|
316
|
+
incoming.on("data", onData);
|
|
317
|
+
incoming.on("end", onEnd);
|
|
318
|
+
incoming.on("error", onError);
|
|
319
|
+
incoming.on("close", onClose);
|
|
320
|
+
queueMicrotask(() => {
|
|
321
|
+
if (settled) return;
|
|
322
|
+
if (incoming.readableEnded) onEnd();
|
|
323
|
+
else if (incoming.errored) onError(incoming.errored);
|
|
324
|
+
else if (incoming.destroyed) onClose();
|
|
325
|
+
});
|
|
326
|
+
});
|
|
327
|
+
request[bodyReadPromiseKey] = promise;
|
|
328
|
+
return promise;
|
|
329
|
+
};
|
|
330
|
+
const requestPrototype = {
|
|
331
|
+
get method() {
|
|
332
|
+
return this[methodKey];
|
|
333
|
+
},
|
|
334
|
+
get url() {
|
|
335
|
+
return this[urlKey];
|
|
336
|
+
},
|
|
337
|
+
get headers() {
|
|
338
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
339
|
+
},
|
|
340
|
+
[abortRequest](reason) {
|
|
341
|
+
if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
|
|
342
|
+
const abortController = this[abortControllerKey];
|
|
343
|
+
if (abortController && !abortController.signal.aborted) abortController.abort(reason);
|
|
344
|
+
},
|
|
345
|
+
[getAbortController]() {
|
|
346
|
+
this[abortControllerKey] ||= new AbortController();
|
|
347
|
+
if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
|
|
348
|
+
return this[abortControllerKey];
|
|
349
|
+
},
|
|
350
|
+
[getRequestCache]() {
|
|
351
|
+
const abortController = this[getAbortController]();
|
|
352
|
+
if (this[requestCache]) return this[requestCache];
|
|
353
|
+
const method = this.method;
|
|
354
|
+
if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
|
|
355
|
+
this[bodyBufferKey] = void 0;
|
|
356
|
+
const init = {
|
|
357
|
+
method: method === "TRACE" ? "GET" : method,
|
|
358
|
+
headers: this.headers,
|
|
359
|
+
signal: abortController.signal
|
|
360
|
+
};
|
|
361
|
+
if (method !== "TRACE") {
|
|
362
|
+
init.body = new ReadableStream({ start(c) {
|
|
363
|
+
c.close();
|
|
364
|
+
} });
|
|
365
|
+
init.duplex = "half";
|
|
366
|
+
}
|
|
367
|
+
const req = new Request$1(this[urlKey], init);
|
|
368
|
+
if (method === "TRACE") Object.defineProperty(req, "method", { get() {
|
|
369
|
+
return "TRACE";
|
|
370
|
+
} });
|
|
371
|
+
return this[requestCache] = req;
|
|
372
|
+
}
|
|
373
|
+
return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
|
|
374
|
+
},
|
|
375
|
+
get body() {
|
|
376
|
+
if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
|
|
377
|
+
const request = this[getRequestCache]();
|
|
378
|
+
if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
|
|
379
|
+
return request.body;
|
|
380
|
+
},
|
|
381
|
+
get bodyUsed() {
|
|
382
|
+
if (this[bodyConsumedDirectlyKey]) return true;
|
|
383
|
+
if (this[requestCache]) return this[requestCache].bodyUsed;
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
Object.defineProperty(requestPrototype, "signal", { get() {
|
|
388
|
+
return this[getAbortController]().signal;
|
|
389
|
+
} });
|
|
127
390
|
[
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
"referrerPolicy",
|
|
138
|
-
"signal",
|
|
139
|
-
"keepalive"
|
|
391
|
+
"cache",
|
|
392
|
+
"credentials",
|
|
393
|
+
"destination",
|
|
394
|
+
"integrity",
|
|
395
|
+
"mode",
|
|
396
|
+
"redirect",
|
|
397
|
+
"referrer",
|
|
398
|
+
"referrerPolicy",
|
|
399
|
+
"keepalive"
|
|
140
400
|
].forEach((k) => {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
}
|
|
145
|
-
});
|
|
401
|
+
Object.defineProperty(requestPrototype, k, { get() {
|
|
402
|
+
return this[getRequestCache]()[k];
|
|
403
|
+
} });
|
|
146
404
|
});
|
|
147
|
-
["
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
405
|
+
["clone", "formData"].forEach((k) => {
|
|
406
|
+
Object.defineProperty(requestPrototype, k, { value: function() {
|
|
407
|
+
if (this[bodyConsumedDirectlyKey]) {
|
|
408
|
+
if (k === "clone") throw newBodyUnusableError();
|
|
409
|
+
return rejectBodyUnusable();
|
|
410
|
+
}
|
|
411
|
+
return this[getRequestCache]()[k]();
|
|
412
|
+
} });
|
|
153
413
|
});
|
|
154
|
-
Object.defineProperty(requestPrototype,
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
414
|
+
Object.defineProperty(requestPrototype, "text", { value: function() {
|
|
415
|
+
return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
|
|
416
|
+
} });
|
|
417
|
+
Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
|
|
418
|
+
return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
|
|
419
|
+
} });
|
|
420
|
+
Object.defineProperty(requestPrototype, "blob", { value: function() {
|
|
421
|
+
return readBodyWithFastPath(this, "blob", (buf, request) => {
|
|
422
|
+
const type = contentType(request);
|
|
423
|
+
const init = type ? { headers: { "content-type": type } } : void 0;
|
|
424
|
+
return new Response(buf, init).blob();
|
|
425
|
+
});
|
|
426
|
+
} });
|
|
427
|
+
Object.defineProperty(requestPrototype, "json", { value: function() {
|
|
428
|
+
if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
|
429
|
+
return this.text().then(JSON.parse);
|
|
430
|
+
} });
|
|
431
|
+
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
432
|
+
return `Request (lightweight) ${inspectFn({
|
|
433
|
+
method: this.method,
|
|
434
|
+
url: this.url,
|
|
435
|
+
headers: this.headers,
|
|
436
|
+
nativeRequest: this[requestCache]
|
|
437
|
+
}, {
|
|
438
|
+
...options,
|
|
439
|
+
depth: depth == null ? null : depth - 1
|
|
440
|
+
})}`;
|
|
441
|
+
} });
|
|
442
|
+
Object.setPrototypeOf(requestPrototype, Request$1.prototype);
|
|
443
|
+
const newRequest = (incoming, defaultHostname) => {
|
|
444
|
+
const req = Object.create(requestPrototype);
|
|
445
|
+
req[incomingKey] = incoming;
|
|
446
|
+
req[methodKey] = normalizeIncomingMethod(incoming.method);
|
|
447
|
+
const incomingUrl = incoming.url || "";
|
|
448
|
+
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
449
|
+
if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
450
|
+
try {
|
|
451
|
+
req[urlKey] = new URL(incomingUrl).href;
|
|
452
|
+
} catch (e) {
|
|
453
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
454
|
+
}
|
|
455
|
+
return req;
|
|
456
|
+
}
|
|
457
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
458
|
+
if (!host) throw new RequestError("Missing host header");
|
|
459
|
+
let scheme;
|
|
460
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
461
|
+
scheme = incoming.scheme;
|
|
462
|
+
if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
|
|
463
|
+
} else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
464
|
+
try {
|
|
465
|
+
req[urlKey] = buildUrl(scheme, host, incomingUrl);
|
|
466
|
+
} catch (e) {
|
|
467
|
+
if (e instanceof RequestError) throw e;
|
|
468
|
+
else throw new RequestError("Invalid URL", { cause: e });
|
|
469
|
+
}
|
|
470
|
+
return req;
|
|
202
471
|
};
|
|
203
472
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
473
|
+
//#endregion
|
|
474
|
+
//#region src/response.ts
|
|
475
|
+
const defaultContentType = "text/plain; charset=UTF-8";
|
|
476
|
+
const responseCache = Symbol("responseCache");
|
|
477
|
+
const getResponseCache = Symbol("getResponseCache");
|
|
478
|
+
const cacheKey = Symbol("cache");
|
|
479
|
+
const GlobalResponse = global.Response;
|
|
480
|
+
var Response$1 = class Response$1 {
|
|
481
|
+
#body;
|
|
482
|
+
#init;
|
|
483
|
+
[getResponseCache]() {
|
|
484
|
+
const cache = this[cacheKey];
|
|
485
|
+
const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
|
|
486
|
+
delete this[cacheKey];
|
|
487
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
|
|
488
|
+
status: this.#init?.status,
|
|
489
|
+
statusText: this.#init?.statusText,
|
|
490
|
+
headers: liveHeaders
|
|
491
|
+
} : this.#init);
|
|
492
|
+
}
|
|
493
|
+
constructor(body, init) {
|
|
494
|
+
let headers;
|
|
495
|
+
this.#body = body;
|
|
496
|
+
if (init instanceof GlobalResponse) {
|
|
497
|
+
const cachedGlobalResponse = init[responseCache];
|
|
498
|
+
if (cachedGlobalResponse) {
|
|
499
|
+
this.#init = cachedGlobalResponse;
|
|
500
|
+
this[getResponseCache]();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
this.#init = init instanceof Response$1 ? init.#init : init;
|
|
504
|
+
headers = new Headers(init.headers);
|
|
505
|
+
} else this.#init = init;
|
|
506
|
+
if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
|
|
507
|
+
init?.status || 200,
|
|
508
|
+
body ?? null,
|
|
509
|
+
headers || init?.headers
|
|
510
|
+
];
|
|
511
|
+
}
|
|
512
|
+
get headers() {
|
|
513
|
+
const cache = this[cacheKey];
|
|
514
|
+
if (cache) {
|
|
515
|
+
if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
|
|
516
|
+
return cache[2];
|
|
517
|
+
}
|
|
518
|
+
return this[getResponseCache]().headers;
|
|
519
|
+
}
|
|
520
|
+
get status() {
|
|
521
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
522
|
+
}
|
|
523
|
+
get ok() {
|
|
524
|
+
const status = this.status;
|
|
525
|
+
return status >= 200 && status < 300;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
[
|
|
529
|
+
"body",
|
|
530
|
+
"bodyUsed",
|
|
531
|
+
"redirected",
|
|
532
|
+
"statusText",
|
|
533
|
+
"trailers",
|
|
534
|
+
"type",
|
|
535
|
+
"url"
|
|
536
|
+
].forEach((k) => {
|
|
537
|
+
Object.defineProperty(Response$1.prototype, k, { get() {
|
|
538
|
+
return this[getResponseCache]()[k];
|
|
539
|
+
} });
|
|
263
540
|
});
|
|
264
|
-
[
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
541
|
+
[
|
|
542
|
+
"arrayBuffer",
|
|
543
|
+
"blob",
|
|
544
|
+
"clone",
|
|
545
|
+
"formData",
|
|
546
|
+
"json",
|
|
547
|
+
"text"
|
|
548
|
+
].forEach((k) => {
|
|
549
|
+
Object.defineProperty(Response$1.prototype, k, { value: function() {
|
|
550
|
+
return this[getResponseCache]()[k]();
|
|
551
|
+
} });
|
|
270
552
|
});
|
|
271
|
-
Object.defineProperty(
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
553
|
+
Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
554
|
+
return `Response (lightweight) ${inspectFn({
|
|
555
|
+
status: this.status,
|
|
556
|
+
headers: this.headers,
|
|
557
|
+
ok: this.ok,
|
|
558
|
+
nativeResponse: this[responseCache]
|
|
559
|
+
}, {
|
|
560
|
+
...options,
|
|
561
|
+
depth: depth == null ? null : depth - 1
|
|
562
|
+
})}`;
|
|
563
|
+
} });
|
|
564
|
+
Object.setPrototypeOf(Response$1, GlobalResponse);
|
|
565
|
+
Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
|
|
566
|
+
const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
|
|
567
|
+
const parseRedirectUrl = (url) => {
|
|
568
|
+
if (url instanceof URL) return url.href;
|
|
569
|
+
if (validRedirectUrl.test(url)) return url;
|
|
570
|
+
return new URL(url).href;
|
|
571
|
+
};
|
|
572
|
+
const validRedirectStatuses = new Set([
|
|
573
|
+
301,
|
|
574
|
+
302,
|
|
575
|
+
303,
|
|
576
|
+
307,
|
|
577
|
+
308
|
|
578
|
+
]);
|
|
579
|
+
Object.defineProperty(Response$1, "redirect", {
|
|
580
|
+
value: function redirect(url, status = 302) {
|
|
581
|
+
if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
|
|
582
|
+
return new Response$1(null, {
|
|
583
|
+
status,
|
|
584
|
+
headers: { location: parseRedirectUrl(url) }
|
|
585
|
+
});
|
|
586
|
+
},
|
|
587
|
+
writable: true,
|
|
588
|
+
configurable: true
|
|
589
|
+
});
|
|
590
|
+
Object.defineProperty(Response$1, "json", {
|
|
591
|
+
value: function json(data, init) {
|
|
592
|
+
const body = JSON.stringify(data);
|
|
593
|
+
if (body === void 0) throw new TypeError("The data is not JSON serializable");
|
|
594
|
+
const initHeaders = init?.headers;
|
|
595
|
+
let headers;
|
|
596
|
+
if (initHeaders) {
|
|
597
|
+
headers = new Headers(initHeaders);
|
|
598
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
599
|
+
} else headers = { "content-type": "application/json" };
|
|
600
|
+
return new Response$1(body, {
|
|
601
|
+
status: init?.status ?? 200,
|
|
602
|
+
statusText: init?.statusText,
|
|
603
|
+
headers
|
|
604
|
+
});
|
|
605
|
+
},
|
|
606
|
+
writable: true,
|
|
607
|
+
configurable: true
|
|
281
608
|
});
|
|
282
|
-
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
283
|
-
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
284
609
|
|
|
285
|
-
|
|
610
|
+
//#endregion
|
|
611
|
+
//#region src/utils.ts
|
|
286
612
|
async function readWithoutBlocking(readPromise) {
|
|
287
|
-
|
|
613
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
288
614
|
}
|
|
289
615
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
} else {
|
|
316
|
-
return reader.read().then(flow, handleStreamError);
|
|
317
|
-
}
|
|
318
|
-
} catch (e) {
|
|
319
|
-
handleStreamError(e);
|
|
320
|
-
}
|
|
321
|
-
}
|
|
616
|
+
const cancel = (error) => {
|
|
617
|
+
reader.cancel(error).catch(() => {});
|
|
618
|
+
};
|
|
619
|
+
writable.on("close", cancel);
|
|
620
|
+
writable.on("error", cancel);
|
|
621
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
622
|
+
return reader.closed.finally(() => {
|
|
623
|
+
writable.off("close", cancel);
|
|
624
|
+
writable.off("error", cancel);
|
|
625
|
+
});
|
|
626
|
+
function handleStreamError(error) {
|
|
627
|
+
if (error) writable.destroy(error);
|
|
628
|
+
}
|
|
629
|
+
function onDrain() {
|
|
630
|
+
reader.read().then(flow, handleStreamError);
|
|
631
|
+
}
|
|
632
|
+
function flow({ done, value }) {
|
|
633
|
+
try {
|
|
634
|
+
if (done) writable.end();
|
|
635
|
+
else if (!writable.write(value)) writable.once("drain", onDrain);
|
|
636
|
+
else return reader.read().then(flow, handleStreamError);
|
|
637
|
+
} catch (e) {
|
|
638
|
+
handleStreamError(e);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
322
641
|
}
|
|
323
642
|
function writeFromReadableStream(stream, writable) {
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
return;
|
|
328
|
-
}
|
|
329
|
-
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
643
|
+
if (stream.locked) throw new TypeError("ReadableStream is locked.");
|
|
644
|
+
else if (writable.destroyed) return;
|
|
645
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
330
646
|
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
if (cookies.length > 0) {
|
|
345
|
-
res["set-cookie"] = cookies;
|
|
346
|
-
}
|
|
347
|
-
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
348
|
-
return res;
|
|
647
|
+
const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
|
|
648
|
+
const res = {};
|
|
649
|
+
if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
|
|
650
|
+
if (headers.has("set-cookie")) {
|
|
651
|
+
const cookies = [];
|
|
652
|
+
for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
|
|
653
|
+
else res[k] = v;
|
|
654
|
+
if (cookies.length > 0) res["set-cookie"] = cookies;
|
|
655
|
+
} else for (const [k, v] of headers) res[k] = v;
|
|
656
|
+
if (defaultContentType) res["content-type"] ??= defaultContentType;
|
|
657
|
+
return res;
|
|
349
658
|
};
|
|
350
659
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
660
|
+
//#endregion
|
|
661
|
+
//#region src/listener.ts
|
|
662
|
+
const outgoingEnded = Symbol("outgoingEnded");
|
|
663
|
+
const incomingDraining = Symbol("incomingDraining");
|
|
664
|
+
const DRAIN_TIMEOUT_MS = 500;
|
|
665
|
+
const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
|
666
|
+
const drainIncoming = (incoming) => {
|
|
667
|
+
const incomingWithDrainState = incoming;
|
|
668
|
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
|
|
669
|
+
incomingWithDrainState[incomingDraining] = true;
|
|
670
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
671
|
+
try {
|
|
672
|
+
incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
|
|
673
|
+
} catch {}
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
let bytesRead = 0;
|
|
677
|
+
const cleanup = () => {
|
|
678
|
+
clearTimeout(timer);
|
|
679
|
+
incoming.off("data", onData);
|
|
680
|
+
incoming.off("end", cleanup);
|
|
681
|
+
incoming.off("error", cleanup);
|
|
682
|
+
};
|
|
683
|
+
const forceClose = () => {
|
|
684
|
+
cleanup();
|
|
685
|
+
const socket = incoming.socket;
|
|
686
|
+
if (socket && !socket.destroyed) socket.destroySoon();
|
|
687
|
+
};
|
|
688
|
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
689
|
+
timer.unref?.();
|
|
690
|
+
const onData = (chunk) => {
|
|
691
|
+
bytesRead += chunk.length;
|
|
692
|
+
if (bytesRead > MAX_DRAIN_BYTES) forceClose();
|
|
693
|
+
};
|
|
694
|
+
incoming.on("data", onData);
|
|
695
|
+
incoming.on("end", cleanup);
|
|
696
|
+
incoming.on("error", cleanup);
|
|
697
|
+
incoming.resume();
|
|
698
|
+
};
|
|
699
|
+
const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
|
|
700
|
+
if (incoming.errored) {
|
|
701
|
+
recordBodyBufferedBeforeDisconnect(incoming);
|
|
702
|
+
req[abortRequest](incoming.errored.toString());
|
|
703
|
+
} else if (!outgoing.writableFinished) {
|
|
704
|
+
recordBodyBufferedBeforeDisconnect(incoming);
|
|
705
|
+
req[abortRequest]("Client connection prematurely closed.");
|
|
706
|
+
}
|
|
707
|
+
if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
|
|
708
|
+
if (!incoming.readableEnded) setTimeout(() => {
|
|
709
|
+
drainIncoming(incoming);
|
|
710
|
+
});
|
|
711
|
+
});
|
|
712
|
+
};
|
|
713
|
+
const isImmediateCacheableResponse = (res) => {
|
|
714
|
+
if (!(cacheKey in res)) return false;
|
|
715
|
+
const body = res[cacheKey][1];
|
|
716
|
+
return body === null || typeof body === "string" || body instanceof Uint8Array;
|
|
717
|
+
};
|
|
718
|
+
const handleRequestError = () => new Response(null, { status: 400 });
|
|
719
|
+
const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
|
|
720
|
+
const handleResponseError = (e, outgoing) => {
|
|
721
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
722
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
|
|
723
|
+
else {
|
|
724
|
+
console.error(e);
|
|
725
|
+
if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
726
|
+
outgoing.end(`Error: ${err.message}`);
|
|
727
|
+
outgoing.destroy(err);
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
const flushHeaders = (outgoing) => {
|
|
731
|
+
if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
|
|
732
|
+
};
|
|
733
|
+
const responseViaCache = async (res, outgoing) => {
|
|
734
|
+
let [status, body, header] = res[cacheKey];
|
|
735
|
+
if (!header) {
|
|
736
|
+
if (body === null) {
|
|
737
|
+
outgoing.writeHead(status);
|
|
738
|
+
outgoing.end();
|
|
739
|
+
} else if (typeof body === "string") {
|
|
740
|
+
outgoing.writeHead(status, {
|
|
741
|
+
"Content-Type": defaultContentType,
|
|
742
|
+
"Content-Length": Buffer.byteLength(body)
|
|
743
|
+
});
|
|
744
|
+
outgoing.end(body);
|
|
745
|
+
} else if (body instanceof Uint8Array) {
|
|
746
|
+
outgoing.writeHead(status, {
|
|
747
|
+
"Content-Type": defaultContentType,
|
|
748
|
+
"Content-Length": body.byteLength
|
|
749
|
+
});
|
|
750
|
+
outgoing.end(body);
|
|
751
|
+
} else if (body instanceof Blob) {
|
|
752
|
+
outgoing.writeHead(status, {
|
|
753
|
+
"Content-Type": defaultContentType,
|
|
754
|
+
"Content-Length": body.size
|
|
755
|
+
});
|
|
756
|
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
757
|
+
} else {
|
|
758
|
+
outgoing.writeHead(status, { "Content-Type": defaultContentType });
|
|
759
|
+
flushHeaders(outgoing);
|
|
760
|
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
|
761
|
+
}
|
|
762
|
+
outgoing[outgoingEnded]?.();
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
let hasContentLength = false;
|
|
766
|
+
if (header instanceof Headers) {
|
|
767
|
+
hasContentLength = header.has("content-length");
|
|
768
|
+
header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
|
|
769
|
+
} else if (Array.isArray(header)) {
|
|
770
|
+
const headerObj = new Headers(header);
|
|
771
|
+
hasContentLength = headerObj.has("content-length");
|
|
772
|
+
header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
|
|
773
|
+
} else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
774
|
+
hasContentLength = true;
|
|
775
|
+
break;
|
|
776
|
+
}
|
|
777
|
+
if (!hasContentLength) {
|
|
778
|
+
if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
|
|
779
|
+
else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
|
|
780
|
+
else if (body instanceof Blob) header["Content-Length"] = body.size;
|
|
781
|
+
}
|
|
782
|
+
outgoing.writeHead(status, header);
|
|
783
|
+
if (body == null) outgoing.end();
|
|
784
|
+
else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
|
|
785
|
+
else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
786
|
+
else {
|
|
787
|
+
flushHeaders(outgoing);
|
|
788
|
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
|
789
|
+
}
|
|
790
|
+
outgoing[outgoingEnded]?.();
|
|
791
|
+
};
|
|
792
|
+
const isPromise = (res) => typeof res.then === "function";
|
|
793
|
+
const responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
794
|
+
if (isPromise(res)) if (options.errorHandler) try {
|
|
795
|
+
res = await res;
|
|
796
|
+
} catch (err) {
|
|
797
|
+
const errRes = await options.errorHandler(err);
|
|
798
|
+
if (!errRes) return;
|
|
799
|
+
res = errRes;
|
|
800
|
+
}
|
|
801
|
+
else res = await res.catch(handleFetchError);
|
|
802
|
+
if (cacheKey in res) return responseViaCache(res, outgoing);
|
|
803
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
|
|
804
|
+
if (res.body) {
|
|
805
|
+
const reader = res.body.getReader();
|
|
806
|
+
const values = [];
|
|
807
|
+
let done = false;
|
|
808
|
+
let currentReadPromise = void 0;
|
|
809
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
810
|
+
let maxReadCount = 2;
|
|
811
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
812
|
+
currentReadPromise ||= reader.read();
|
|
813
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
814
|
+
console.error(e);
|
|
815
|
+
done = true;
|
|
816
|
+
});
|
|
817
|
+
if (!chunk) {
|
|
818
|
+
if (i === 1) {
|
|
819
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
820
|
+
maxReadCount = 3;
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
break;
|
|
824
|
+
}
|
|
825
|
+
currentReadPromise = void 0;
|
|
826
|
+
if (chunk.value) values.push(chunk.value);
|
|
827
|
+
if (chunk.done) {
|
|
828
|
+
done = true;
|
|
829
|
+
break;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
833
|
+
}
|
|
834
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
835
|
+
values.forEach((value) => {
|
|
836
|
+
outgoing.write(value);
|
|
837
|
+
});
|
|
838
|
+
if (done) outgoing.end();
|
|
839
|
+
else {
|
|
840
|
+
if (values.length === 0) flushHeaders(outgoing);
|
|
841
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
842
|
+
}
|
|
843
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
|
|
844
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
845
|
+
outgoing.end();
|
|
846
|
+
}
|
|
847
|
+
outgoing[outgoingEnded]?.();
|
|
848
|
+
};
|
|
849
|
+
const getRequestListener = (fetchCallback, options = {}) => {
|
|
850
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
851
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
|
|
852
|
+
Object.defineProperty(global, "Request", { value: Request$1 });
|
|
853
|
+
Object.defineProperty(global, "Response", { value: Response$1 });
|
|
854
|
+
}
|
|
855
|
+
return async (incoming, outgoing) => {
|
|
856
|
+
let res, req;
|
|
857
|
+
let needsBodyCleanup = false;
|
|
858
|
+
let closeHandlerAttached = false;
|
|
859
|
+
const ensureCloseHandler = () => {
|
|
860
|
+
if (!req || closeHandlerAttached) return;
|
|
861
|
+
closeHandlerAttached = true;
|
|
862
|
+
outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
|
|
863
|
+
};
|
|
864
|
+
try {
|
|
865
|
+
req = newRequest(incoming, options.hostname);
|
|
866
|
+
needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
|
|
867
|
+
if (needsBodyCleanup) {
|
|
868
|
+
incoming[wrapBodyStream] = true;
|
|
869
|
+
if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
|
|
870
|
+
if (!incoming.readableEnded) setTimeout(() => {
|
|
871
|
+
if (!incoming.readableEnded) setTimeout(() => {
|
|
872
|
+
incoming.destroy();
|
|
873
|
+
outgoing.destroy();
|
|
874
|
+
});
|
|
875
|
+
});
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
res = fetchCallback(req, {
|
|
879
|
+
incoming,
|
|
880
|
+
outgoing
|
|
881
|
+
});
|
|
882
|
+
if (!isPromise(res) && isImmediateCacheableResponse(res)) {
|
|
883
|
+
if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
|
|
884
|
+
if (!incoming.readableEnded) drainIncoming(incoming);
|
|
885
|
+
});
|
|
886
|
+
return responseViaCache(res, outgoing);
|
|
887
|
+
}
|
|
888
|
+
ensureCloseHandler();
|
|
889
|
+
} catch (e) {
|
|
890
|
+
if (!res) if (options.errorHandler) {
|
|
891
|
+
ensureCloseHandler();
|
|
892
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
893
|
+
if (!res) return;
|
|
894
|
+
} else if (!req) res = handleRequestError();
|
|
895
|
+
else res = handleFetchError(e);
|
|
896
|
+
else return handleResponseError(e, outgoing);
|
|
897
|
+
}
|
|
898
|
+
try {
|
|
899
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
900
|
+
} catch (e) {
|
|
901
|
+
return handleResponseError(e, outgoing);
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
};
|
|
359
905
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
};
|
|
430
|
-
var responseViaCache = async (res, outgoing) => {
|
|
431
|
-
let [status, body, header] = res[cacheKey];
|
|
432
|
-
let hasContentLength = false;
|
|
433
|
-
if (!header) {
|
|
434
|
-
header = { "content-type": "text/plain; charset=UTF-8" };
|
|
435
|
-
} else if (header instanceof Headers) {
|
|
436
|
-
hasContentLength = header.has("content-length");
|
|
437
|
-
header = buildOutgoingHttpHeaders(header);
|
|
438
|
-
} else if (Array.isArray(header)) {
|
|
439
|
-
const headerObj = new Headers(header);
|
|
440
|
-
hasContentLength = headerObj.has("content-length");
|
|
441
|
-
header = buildOutgoingHttpHeaders(headerObj);
|
|
442
|
-
} else {
|
|
443
|
-
for (const key in header) {
|
|
444
|
-
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
445
|
-
hasContentLength = true;
|
|
446
|
-
break;
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
if (!hasContentLength) {
|
|
451
|
-
if (typeof body === "string") {
|
|
452
|
-
header["Content-Length"] = Buffer.byteLength(body);
|
|
453
|
-
} else if (body instanceof Uint8Array) {
|
|
454
|
-
header["Content-Length"] = body.byteLength;
|
|
455
|
-
} else if (body instanceof Blob) {
|
|
456
|
-
header["Content-Length"] = body.size;
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
outgoing.writeHead(status, header);
|
|
460
|
-
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
461
|
-
outgoing.end(body);
|
|
462
|
-
} else if (body instanceof Blob) {
|
|
463
|
-
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
464
|
-
} else {
|
|
465
|
-
flushHeaders(outgoing);
|
|
466
|
-
await writeFromReadableStream(body, outgoing)?.catch(
|
|
467
|
-
(e) => handleResponseError(e, outgoing)
|
|
468
|
-
);
|
|
469
|
-
}
|
|
470
|
-
;
|
|
471
|
-
outgoing[outgoingEnded]?.();
|
|
472
|
-
};
|
|
473
|
-
var isPromise = (res) => typeof res.then === "function";
|
|
474
|
-
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
475
|
-
if (isPromise(res)) {
|
|
476
|
-
if (options.errorHandler) {
|
|
477
|
-
try {
|
|
478
|
-
res = await res;
|
|
479
|
-
} catch (err) {
|
|
480
|
-
const errRes = await options.errorHandler(err);
|
|
481
|
-
if (!errRes) {
|
|
482
|
-
return;
|
|
483
|
-
}
|
|
484
|
-
res = errRes;
|
|
485
|
-
}
|
|
486
|
-
} else {
|
|
487
|
-
res = await res.catch(handleFetchError);
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
if (cacheKey in res) {
|
|
491
|
-
return responseViaCache(res, outgoing);
|
|
492
|
-
}
|
|
493
|
-
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
494
|
-
if (res.body) {
|
|
495
|
-
const reader = res.body.getReader();
|
|
496
|
-
const values = [];
|
|
497
|
-
let done = false;
|
|
498
|
-
let currentReadPromise = void 0;
|
|
499
|
-
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
500
|
-
let maxReadCount = 2;
|
|
501
|
-
for (let i = 0; i < maxReadCount; i++) {
|
|
502
|
-
currentReadPromise ||= reader.read();
|
|
503
|
-
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
504
|
-
console.error(e);
|
|
505
|
-
done = true;
|
|
506
|
-
});
|
|
507
|
-
if (!chunk) {
|
|
508
|
-
if (i === 1) {
|
|
509
|
-
await new Promise((resolve) => setTimeout(resolve));
|
|
510
|
-
maxReadCount = 3;
|
|
511
|
-
continue;
|
|
512
|
-
}
|
|
513
|
-
break;
|
|
514
|
-
}
|
|
515
|
-
currentReadPromise = void 0;
|
|
516
|
-
if (chunk.value) {
|
|
517
|
-
values.push(chunk.value);
|
|
518
|
-
}
|
|
519
|
-
if (chunk.done) {
|
|
520
|
-
done = true;
|
|
521
|
-
break;
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
if (done && !("content-length" in resHeaderRecord)) {
|
|
525
|
-
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
outgoing.writeHead(res.status, resHeaderRecord);
|
|
529
|
-
values.forEach((value) => {
|
|
530
|
-
;
|
|
531
|
-
outgoing.write(value);
|
|
532
|
-
});
|
|
533
|
-
if (done) {
|
|
534
|
-
outgoing.end();
|
|
535
|
-
} else {
|
|
536
|
-
if (values.length === 0) {
|
|
537
|
-
flushHeaders(outgoing);
|
|
538
|
-
}
|
|
539
|
-
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
540
|
-
}
|
|
541
|
-
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
|
542
|
-
} else {
|
|
543
|
-
outgoing.writeHead(res.status, resHeaderRecord);
|
|
544
|
-
outgoing.end();
|
|
545
|
-
}
|
|
546
|
-
;
|
|
547
|
-
outgoing[outgoingEnded]?.();
|
|
548
|
-
};
|
|
549
|
-
var getRequestListener = (fetchCallback, options = {}) => {
|
|
550
|
-
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
551
|
-
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
|
552
|
-
Object.defineProperty(global, "Request", {
|
|
553
|
-
value: Request
|
|
554
|
-
});
|
|
555
|
-
Object.defineProperty(global, "Response", {
|
|
556
|
-
value: Response2
|
|
557
|
-
});
|
|
558
|
-
}
|
|
559
|
-
return async (incoming, outgoing) => {
|
|
560
|
-
let res, req;
|
|
561
|
-
try {
|
|
562
|
-
req = newRequest(incoming, options.hostname);
|
|
563
|
-
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
564
|
-
if (!incomingEnded) {
|
|
565
|
-
;
|
|
566
|
-
incoming[wrapBodyStream] = true;
|
|
567
|
-
incoming.on("end", () => {
|
|
568
|
-
incomingEnded = true;
|
|
569
|
-
});
|
|
570
|
-
if (incoming instanceof Http2ServerRequest2) {
|
|
571
|
-
;
|
|
572
|
-
outgoing[outgoingEnded] = () => {
|
|
573
|
-
if (!incomingEnded) {
|
|
574
|
-
setTimeout(() => {
|
|
575
|
-
if (!incomingEnded) {
|
|
576
|
-
setTimeout(() => {
|
|
577
|
-
drainIncoming(incoming);
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
});
|
|
581
|
-
}
|
|
582
|
-
};
|
|
583
|
-
}
|
|
584
|
-
outgoing.on("finish", () => {
|
|
585
|
-
if (!incomingEnded) {
|
|
586
|
-
drainIncoming(incoming);
|
|
587
|
-
}
|
|
588
|
-
});
|
|
589
|
-
}
|
|
590
|
-
outgoing.on("close", () => {
|
|
591
|
-
const abortController = req[abortControllerKey];
|
|
592
|
-
if (abortController) {
|
|
593
|
-
if (incoming.errored) {
|
|
594
|
-
req[abortControllerKey].abort(incoming.errored.toString());
|
|
595
|
-
} else if (!outgoing.writableFinished) {
|
|
596
|
-
req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
if (!incomingEnded) {
|
|
600
|
-
setTimeout(() => {
|
|
601
|
-
if (!incomingEnded) {
|
|
602
|
-
setTimeout(() => {
|
|
603
|
-
drainIncoming(incoming);
|
|
604
|
-
});
|
|
605
|
-
}
|
|
606
|
-
});
|
|
607
|
-
}
|
|
608
|
-
});
|
|
609
|
-
res = fetchCallback(req, { incoming, outgoing });
|
|
610
|
-
if (cacheKey in res) {
|
|
611
|
-
return responseViaCache(res, outgoing);
|
|
612
|
-
}
|
|
613
|
-
} catch (e) {
|
|
614
|
-
if (!res) {
|
|
615
|
-
if (options.errorHandler) {
|
|
616
|
-
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
617
|
-
if (!res) {
|
|
618
|
-
return;
|
|
619
|
-
}
|
|
620
|
-
} else if (!req) {
|
|
621
|
-
res = handleRequestError();
|
|
622
|
-
} else {
|
|
623
|
-
res = handleFetchError(e);
|
|
624
|
-
}
|
|
625
|
-
} else {
|
|
626
|
-
return handleResponseError(e, outgoing);
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
try {
|
|
630
|
-
return await responseViaResponseObject(res, outgoing, options);
|
|
631
|
-
} catch (e) {
|
|
632
|
-
return handleResponseError(e, outgoing);
|
|
633
|
-
}
|
|
634
|
-
};
|
|
906
|
+
//#endregion
|
|
907
|
+
//#region src/websocket.ts
|
|
908
|
+
/**
|
|
909
|
+
* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
|
|
910
|
+
*/
|
|
911
|
+
const CloseEvent = globalThis.CloseEvent ?? class extends Event {
|
|
912
|
+
#eventInitDict;
|
|
913
|
+
constructor(type, eventInitDict = {}) {
|
|
914
|
+
super(type, eventInitDict);
|
|
915
|
+
this.#eventInitDict = eventInitDict;
|
|
916
|
+
}
|
|
917
|
+
get wasClean() {
|
|
918
|
+
return this.#eventInitDict.wasClean ?? false;
|
|
919
|
+
}
|
|
920
|
+
get code() {
|
|
921
|
+
return this.#eventInitDict.code ?? 0;
|
|
922
|
+
}
|
|
923
|
+
get reason() {
|
|
924
|
+
return this.#eventInitDict.reason ?? "";
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
/**
|
|
928
|
+
* Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.
|
|
929
|
+
* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
|
|
930
|
+
*/
|
|
931
|
+
const ErrorEvent = globalThis.ErrorEvent ?? class extends Event {
|
|
932
|
+
#eventInitDict;
|
|
933
|
+
constructor(type, eventInitDict = {}) {
|
|
934
|
+
super(type, eventInitDict);
|
|
935
|
+
this.#eventInitDict = eventInitDict;
|
|
936
|
+
}
|
|
937
|
+
get message() {
|
|
938
|
+
return this.#eventInitDict.message ?? "";
|
|
939
|
+
}
|
|
940
|
+
get filename() {
|
|
941
|
+
return this.#eventInitDict.filename ?? "";
|
|
942
|
+
}
|
|
943
|
+
get lineno() {
|
|
944
|
+
return this.#eventInitDict.lineno ?? 0;
|
|
945
|
+
}
|
|
946
|
+
get colno() {
|
|
947
|
+
return this.#eventInitDict.colno ?? 0;
|
|
948
|
+
}
|
|
949
|
+
get error() {
|
|
950
|
+
return this.#eventInitDict.error ?? null;
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
const generateConnectionSymbol = () => Symbol("connection");
|
|
954
|
+
const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
|
|
955
|
+
const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
|
|
956
|
+
const responseHeadersToSkip = new Set([
|
|
957
|
+
"connection",
|
|
958
|
+
"content-length",
|
|
959
|
+
"keep-alive",
|
|
960
|
+
"proxy-authenticate",
|
|
961
|
+
"proxy-authorization",
|
|
962
|
+
"te",
|
|
963
|
+
"trailer",
|
|
964
|
+
"transfer-encoding",
|
|
965
|
+
"upgrade",
|
|
966
|
+
"sec-websocket-accept",
|
|
967
|
+
"sec-websocket-extensions",
|
|
968
|
+
"sec-websocket-protocol"
|
|
969
|
+
]);
|
|
970
|
+
const appendResponseHeaders = (headers, responseHeaders) => {
|
|
971
|
+
if (!responseHeaders) return;
|
|
972
|
+
responseHeaders.forEach((value, key) => {
|
|
973
|
+
if (responseHeadersToSkip.has(key.toLowerCase())) return;
|
|
974
|
+
headers.push(`${key}: ${value}`);
|
|
975
|
+
});
|
|
635
976
|
};
|
|
977
|
+
const rejectUpgradeRequest = (socket, status, responseHeaders) => {
|
|
978
|
+
const responseLines = ["Connection: close", "Content-Length: 0"];
|
|
979
|
+
appendResponseHeaders(responseLines, responseHeaders);
|
|
980
|
+
socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
|
|
981
|
+
`);
|
|
982
|
+
};
|
|
983
|
+
const createUpgradeRequest = (request) => {
|
|
984
|
+
const protocol = request.socket.encrypted ? "https" : "http";
|
|
985
|
+
const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
|
|
986
|
+
const headers = new Headers();
|
|
987
|
+
for (const key in request.headers) {
|
|
988
|
+
const value = request.headers[key];
|
|
989
|
+
if (!value) continue;
|
|
990
|
+
headers.append(key, Array.isArray(value) ? value[0] : value);
|
|
991
|
+
}
|
|
992
|
+
return new Request(url, { headers });
|
|
993
|
+
};
|
|
994
|
+
const setupWebSocket = (options) => {
|
|
995
|
+
const { server, fetchCallback, wss } = options;
|
|
996
|
+
const waiterMap = /* @__PURE__ */ new Map();
|
|
997
|
+
wss.on("connection", (ws, request) => {
|
|
998
|
+
const waiter = waiterMap.get(request);
|
|
999
|
+
if (waiter) {
|
|
1000
|
+
waiter.resolve(ws);
|
|
1001
|
+
waiterMap.delete(request);
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
const rejectWaiter = (request) => {
|
|
1005
|
+
const waiter = waiterMap.get(request);
|
|
1006
|
+
if (waiter) {
|
|
1007
|
+
waiterMap.delete(request);
|
|
1008
|
+
waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted"));
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
const waitForWebSocket = (request, connectionSymbol) => {
|
|
1012
|
+
return new Promise((resolve, reject) => {
|
|
1013
|
+
waiterMap.set(request, {
|
|
1014
|
+
resolve,
|
|
1015
|
+
reject,
|
|
1016
|
+
connectionSymbol
|
|
1017
|
+
});
|
|
1018
|
+
});
|
|
1019
|
+
};
|
|
1020
|
+
server.on("upgrade", async (request, socket, head) => {
|
|
1021
|
+
if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
|
|
1022
|
+
const env = {
|
|
1023
|
+
incoming: request,
|
|
1024
|
+
outgoing: void 0,
|
|
1025
|
+
wss,
|
|
1026
|
+
[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
|
|
1027
|
+
};
|
|
1028
|
+
let status = 400;
|
|
1029
|
+
let responseHeaders;
|
|
1030
|
+
try {
|
|
1031
|
+
const response = await fetchCallback(createUpgradeRequest(request), env);
|
|
1032
|
+
if (response instanceof Response) {
|
|
1033
|
+
status = response.status;
|
|
1034
|
+
responseHeaders = response.headers;
|
|
1035
|
+
}
|
|
1036
|
+
} catch {
|
|
1037
|
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
const waiter = waiterMap.get(request);
|
|
1041
|
+
if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
|
|
1042
|
+
rejectWaiter(request);
|
|
1043
|
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
const addResponseHeaders = (headers) => {
|
|
1047
|
+
appendResponseHeaders(headers, responseHeaders);
|
|
1048
|
+
};
|
|
1049
|
+
const reclaimWaiterOnClose = () => rejectWaiter(request);
|
|
1050
|
+
socket.once("close", reclaimWaiterOnClose);
|
|
1051
|
+
wss.on("headers", addResponseHeaders);
|
|
1052
|
+
try {
|
|
1053
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
1054
|
+
socket.off("close", reclaimWaiterOnClose);
|
|
1055
|
+
wss.emit("connection", ws, request);
|
|
1056
|
+
});
|
|
1057
|
+
} finally {
|
|
1058
|
+
wss.off("headers", addResponseHeaders);
|
|
1059
|
+
}
|
|
1060
|
+
});
|
|
1061
|
+
server.on("close", () => {
|
|
1062
|
+
wss.close();
|
|
1063
|
+
});
|
|
1064
|
+
};
|
|
1065
|
+
const upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {
|
|
1066
|
+
if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
|
|
1067
|
+
const env = c.env;
|
|
1068
|
+
const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
|
|
1069
|
+
if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
|
|
1070
|
+
const connectionSymbol = generateConnectionSymbol();
|
|
1071
|
+
env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
|
|
1072
|
+
(async () => {
|
|
1073
|
+
let ws;
|
|
1074
|
+
try {
|
|
1075
|
+
ws = await waitForWebSocket(env.incoming, connectionSymbol);
|
|
1076
|
+
} catch {
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
const messagesReceivedInStarting = [];
|
|
1080
|
+
const bufferMessage = (data, isBinary) => {
|
|
1081
|
+
messagesReceivedInStarting.push([data, isBinary]);
|
|
1082
|
+
};
|
|
1083
|
+
ws.on("message", bufferMessage);
|
|
1084
|
+
const ctx = {
|
|
1085
|
+
binaryType: "arraybuffer",
|
|
1086
|
+
close(code, reason) {
|
|
1087
|
+
ws.close(code, reason);
|
|
1088
|
+
},
|
|
1089
|
+
protocol: ws.protocol,
|
|
1090
|
+
raw: ws,
|
|
1091
|
+
get readyState() {
|
|
1092
|
+
return ws.readyState;
|
|
1093
|
+
},
|
|
1094
|
+
send(source, opts) {
|
|
1095
|
+
ws.send(source, { compress: opts?.compress });
|
|
1096
|
+
},
|
|
1097
|
+
url: new URL(c.req.url)
|
|
1098
|
+
};
|
|
1099
|
+
try {
|
|
1100
|
+
events?.onOpen?.(new Event("open"), ctx);
|
|
1101
|
+
} catch (e) {
|
|
1102
|
+
(options?.onError ?? console.error)(e);
|
|
1103
|
+
}
|
|
1104
|
+
const handleMessage = (data, isBinary) => {
|
|
1105
|
+
const datas = Array.isArray(data) ? data : [data];
|
|
1106
|
+
for (const data of datas) try {
|
|
1107
|
+
events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === "string" ? data : Buffer.from(data).toString("utf-8") }), ctx);
|
|
1108
|
+
} catch (e) {
|
|
1109
|
+
(options?.onError ?? console.error)(e);
|
|
1110
|
+
}
|
|
1111
|
+
};
|
|
1112
|
+
ws.off("message", bufferMessage);
|
|
1113
|
+
for (const message of messagesReceivedInStarting) handleMessage(...message);
|
|
1114
|
+
ws.on("message", (data, isBinary) => {
|
|
1115
|
+
handleMessage(data, isBinary);
|
|
1116
|
+
});
|
|
1117
|
+
ws.on("close", (code, reason) => {
|
|
1118
|
+
try {
|
|
1119
|
+
events?.onClose?.(new CloseEvent("close", {
|
|
1120
|
+
code,
|
|
1121
|
+
reason: reason.toString()
|
|
1122
|
+
}), ctx);
|
|
1123
|
+
} catch (e) {
|
|
1124
|
+
(options?.onError ?? console.error)(e);
|
|
1125
|
+
}
|
|
1126
|
+
});
|
|
1127
|
+
ws.on("error", (error) => {
|
|
1128
|
+
try {
|
|
1129
|
+
events?.onError?.(new ErrorEvent("error", { error }), ctx);
|
|
1130
|
+
} catch (e) {
|
|
1131
|
+
(options?.onError ?? console.error)(e);
|
|
1132
|
+
}
|
|
1133
|
+
});
|
|
1134
|
+
})();
|
|
1135
|
+
return new Response();
|
|
1136
|
+
});
|
|
636
1137
|
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
};
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
};
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
1138
|
+
//#endregion
|
|
1139
|
+
//#region src/server.ts
|
|
1140
|
+
const createAdaptorServer = (options) => {
|
|
1141
|
+
const fetchCallback = options.fetch;
|
|
1142
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
1143
|
+
hostname: options.hostname,
|
|
1144
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
1145
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
1146
|
+
});
|
|
1147
|
+
const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
|
|
1148
|
+
if (options.websocket && options.websocket.server) {
|
|
1149
|
+
if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
|
|
1150
|
+
setupWebSocket({
|
|
1151
|
+
server,
|
|
1152
|
+
fetchCallback,
|
|
1153
|
+
wss: options.websocket.server
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
return server;
|
|
1157
|
+
};
|
|
1158
|
+
const serve = (options, listeningListener) => {
|
|
1159
|
+
const server = createAdaptorServer(options);
|
|
1160
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
1161
|
+
const serverInfo = server.address();
|
|
1162
|
+
listeningListener && listeningListener(serverInfo);
|
|
1163
|
+
});
|
|
1164
|
+
return server;
|
|
662
1165
|
};
|
|
1166
|
+
|
|
1167
|
+
//#endregion
|
|
1168
|
+
export { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };
|