@universal-middleware/express 0.0.2 → 0.1.0

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/dist/index.d.ts CHANGED
@@ -1,16 +1,87 @@
1
- import { ServerResponse } from 'node:http';
2
- import { DecoratedRequest } from './native-fetch.js';
3
- export { NodeAdapterOptions, createMiddleware, createServer } from './native-fetch.js';
4
- export { createRequestAdapter } from './request.js';
5
- import '@hattip/core';
6
- import 'node:net';
7
- import 'node:buffer';
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { Socket } from 'node:net';
8
3
 
4
+ /** Adapter options */
5
+ interface NodeRequestAdapterOptions {
6
+ /**
7
+ * Set the origin part of the URL to a constant value.
8
+ * It defaults to `process.env.ORIGIN`. If neither is set,
9
+ * the origin is computed from the protocol and hostname.
10
+ * To determine the protocol, `req.protocol` is tried first.
11
+ * If `trustProxy` is set, `X-Forwarded-Proto` header is used.
12
+ * Otherwise, `req.socket.encrypted` is used.
13
+ * To determine the hostname, `X-Forwarded-Host`
14
+ * (if `trustProxy` is set) or `Host` header is used.
15
+ */
16
+ origin?: string;
17
+ /**
18
+ * Whether to trust `X-Forwarded-*` headers. `X-Forwarded-Proto`
19
+ * and `X-Forwarded-Host` are used to determine the origin when
20
+ * `origin` and `process.env.ORIGIN` are not set. `X-Forwarded-For`
21
+ * is used to determine the IP address. The leftmost values are used
22
+ * if multiple values are set. Defaults to true if `process.env.TRUST_PROXY`
23
+ * is set to `1`, otherwise false.
24
+ */
25
+ trustProxy?: boolean;
26
+ }
27
+ /** Create a function that converts a Node HTTP request into a fetch API `Request` object */
28
+ declare function createRequestAdapter(options?: NodeRequestAdapterOptions): (req: DecoratedRequest) => Request;
29
+
30
+ type Awaitable<T> = T | Promise<T>;
31
+ interface UniversalMiddleware {
32
+ (request: Request, context: Universal.Context): Awaitable<Response> | Awaitable<void> | ((response: Response) => Awaitable<Response>);
33
+ }
34
+ interface UniversalHandler {
35
+ (request: Request, context: Universal.Context): Awaitable<Response>;
36
+ }
37
+
38
+ declare const contextSymbol: unique symbol;
39
+ declare const requestSymbol: unique symbol;
40
+ declare const pendingMiddlewaresSymbol: unique symbol;
41
+ declare const wrappedResponseSymbol: unique symbol;
42
+ interface PossiblyEncryptedSocket extends Socket {
43
+ encrypted?: boolean;
44
+ }
45
+ /**
46
+ * `IncomingMessage` possibly augmented by Express-specific
47
+ * `ip` and `protocol` properties.
48
+ */
49
+ interface DecoratedRequest extends Omit<IncomingMessage, "socket"> {
50
+ ip?: string;
51
+ protocol?: string;
52
+ socket?: PossiblyEncryptedSocket;
53
+ rawBody?: Buffer | null;
54
+ [contextSymbol]?: Universal.Context;
55
+ [requestSymbol]?: Request;
56
+ }
57
+ interface DecoratedServerResponse extends ServerResponse {
58
+ [pendingMiddlewaresSymbol]?: ((response: Response) => Awaitable<Response>)[];
59
+ [wrappedResponseSymbol]?: boolean;
60
+ }
9
61
  /** Connect/Express style request listener/middleware */
10
- type NodeMiddleware = (req: DecoratedRequest, res: ServerResponse, next?: () => void) => void;
11
- interface NodePlatformInfo {
12
- request: DecoratedRequest;
13
- response: ServerResponse;
62
+ type NodeMiddleware$1 = (req: DecoratedRequest, res: DecoratedServerResponse, next?: (err?: unknown) => void) => void;
63
+ /** Adapter options */
64
+ interface NodeAdapterHandlerOptions extends NodeRequestAdapterOptions {
65
+ }
66
+ interface NodeAdapterMiddlewareOptions extends NodeRequestAdapterOptions {
14
67
  }
68
+ /**
69
+ * Creates a request handler to be passed to http.createServer() or used as a
70
+ * middleware in Connect-style frameworks like Express.
71
+ */
72
+ declare function createHandler(handler: UniversalHandler, options?: NodeAdapterHandlerOptions): NodeMiddleware$1;
73
+ /**
74
+ * Creates a middleware to be passed to Connect-style frameworks like Express
75
+ */
76
+ declare function createMiddleware(middleware: UniversalMiddleware, options?: NodeAdapterMiddlewareOptions): NodeMiddleware$1;
77
+ declare function getContext(req: DecoratedRequest): Universal.Context | undefined;
78
+
79
+ /**
80
+ * Send a fetch API Response into a Node.js HTTP response stream.
81
+ */
82
+ declare function sendResponse(fetchResponse: Response, nodeResponse: DecoratedServerResponse): Promise<void>;
83
+
84
+ /** Connect/Express style request listener/middleware */
85
+ type NodeMiddleware = (req: DecoratedRequest, res: DecoratedServerResponse, next?: () => void) => void;
15
86
 
16
- export { DecoratedRequest, type NodeMiddleware, type NodePlatformInfo };
87
+ export { type DecoratedRequest, type DecoratedServerResponse, type NodeMiddleware, createHandler, createMiddleware, createRequestAdapter, getContext, sendResponse };
package/dist/index.js CHANGED
@@ -1,22 +1,255 @@
1
- import {
2
- createMiddleware,
3
- createServer
4
- } from "./chunk-5VGN5WIU.js";
5
- import {
6
- createRequestAdapter
7
- } from "./chunk-NPSKJAQI.js";
8
- import "./chunk-VWRNJC72.js";
9
- import "./chunk-CDXJFGTO.js";
1
+ // src/request.ts
2
+ var deno = typeof Deno !== "undefined";
3
+ var bun = typeof Bun !== "undefined";
4
+ function createRequestAdapter(options = {}) {
5
+ const { origin = env.ORIGIN, trustProxy = env.TRUST_PROXY === "1" } = options;
6
+ let { protocol: protocolOverride, host: hostOverride } = origin ? new URL(origin) : {};
7
+ if (protocolOverride) {
8
+ protocolOverride = protocolOverride.slice(0, -1);
9
+ }
10
+ let warned = false;
11
+ return function requestAdapter(req) {
12
+ if (req[requestSymbol]) {
13
+ return req[requestSymbol];
14
+ }
15
+ function parseForwardedHeader(name) {
16
+ return (headers["x-forwarded-" + name] || "").split(",", 1)[0].trim();
17
+ }
18
+ let headers = req.headers;
19
+ if (headers[":method"]) {
20
+ headers = Object.fromEntries(
21
+ Object.entries(headers).filter(([key]) => !key.startsWith(":"))
22
+ );
23
+ }
24
+ const protocol = protocolOverride || req.protocol || trustProxy && parseForwardedHeader("proto") || req.socket?.encrypted && "https" || "http";
25
+ let host = hostOverride || trustProxy && parseForwardedHeader("host") || headers.host;
26
+ if (!host && !warned) {
27
+ console.warn(
28
+ "Could not automatically determine the origin host, using 'localhost'. Use the 'origin' option or the 'ORIGIN' environment variable to set the origin explicitly."
29
+ );
30
+ warned = true;
31
+ host = "localhost";
32
+ }
33
+ const request = new Request(protocol + "://" + host + req.url, {
34
+ method: req.method,
35
+ headers,
36
+ body: convertBody(req),
37
+ // @ts-ignore
38
+ duplex: "half"
39
+ });
40
+ req[requestSymbol] = request;
41
+ return request;
42
+ };
43
+ }
44
+ function convertBody(req) {
45
+ if (req.method === "GET" || req.method === "HEAD") {
46
+ return;
47
+ }
48
+ if (req.rawBody !== void 0) {
49
+ return req.rawBody;
50
+ }
51
+ if (!bun && !deno) {
52
+ return req;
53
+ }
54
+ return new ReadableStream({
55
+ start(controller) {
56
+ req.on("data", (chunk) => controller.enqueue(chunk));
57
+ req.on("end", () => controller.close());
58
+ req.on("error", (err) => controller.error(err));
59
+ }
60
+ });
61
+ }
62
+
63
+ // src/response.ts
64
+ import { Readable } from "node:stream";
65
+ var deno2 = typeof Deno !== "undefined";
66
+ async function sendResponse(fetchResponse, nodeResponse) {
67
+ const fetchBody = fetchResponse.body;
68
+ let body = null;
69
+ if (typeof fetchBody.pipe === "function") {
70
+ body = fetchBody;
71
+ } else if (typeof fetchBody.pipeTo === "function") {
72
+ if (!deno2 && Readable.fromWeb) {
73
+ body = Readable.fromWeb(fetchBody);
74
+ } else {
75
+ const reader = fetchBody.getReader();
76
+ body = new Readable({
77
+ async read() {
78
+ const { done, value } = await reader.read();
79
+ this.push(done ? null : value);
80
+ }
81
+ });
82
+ }
83
+ } else if (fetchBody) {
84
+ body = Readable.from(fetchBody);
85
+ }
86
+ setHeaders(fetchResponse, nodeResponse);
87
+ if (body) {
88
+ body.pipe(nodeResponse);
89
+ await new Promise((resolve, reject) => {
90
+ body.on("error", reject);
91
+ nodeResponse.on("finish", resolve);
92
+ nodeResponse.on("error", reject);
93
+ });
94
+ } else {
95
+ nodeResponse.setHeader("content-length", "0");
96
+ nodeResponse.end();
97
+ }
98
+ }
99
+ function override(nodeResponse, key, callback) {
100
+ const original = nodeResponse[key];
101
+ nodeResponse[key] = async (...args) => {
102
+ await callback();
103
+ return original.apply(nodeResponse, args);
104
+ };
105
+ return function restore() {
106
+ nodeResponse[key] = original;
107
+ };
108
+ }
109
+ function wrapResponse(nodeResponse) {
110
+ if (nodeResponse[wrappedResponseSymbol]) return;
111
+ nodeResponse[wrappedResponseSymbol] = true;
112
+ const restore = [
113
+ override(nodeResponse, "write", triggerPendingMiddlewares),
114
+ override(nodeResponse, "end", triggerPendingMiddlewares),
115
+ override(nodeResponse, "writeHead", triggerPendingMiddlewares)
116
+ ];
117
+ let resolve;
118
+ const pendingResponse = new Promise((r) => resolve = r);
119
+ async function triggerPendingMiddlewares() {
120
+ if (nodeResponse[pendingMiddlewaresSymbol]) {
121
+ const middlewares = nodeResponse[pendingMiddlewaresSymbol];
122
+ delete nodeResponse[pendingMiddlewaresSymbol];
123
+ const response = await middlewares.reduce(
124
+ async (prev, curr) => curr(await prev),
125
+ Promise.resolve(
126
+ new Response(null, {
127
+ status: nodeResponse.statusCode,
128
+ statusText: nodeResponse.statusMessage,
129
+ headers: adaptHeaders(nodeResponse.getHeaders())
130
+ })
131
+ )
132
+ );
133
+ if (response.body) {
134
+ throw new Error(
135
+ "Replacing the Response body is currently not supported for connect-like servers"
136
+ );
137
+ }
138
+ setHeaders(response, nodeResponse, true);
139
+ resolve();
140
+ restore.forEach((r) => r());
141
+ } else {
142
+ await pendingResponse;
143
+ }
144
+ }
145
+ }
146
+ function setHeaders(fetchResponse, nodeResponse, mirror = false) {
147
+ nodeResponse.statusCode = fetchResponse.status;
148
+ if (fetchResponse.statusText) {
149
+ nodeResponse.statusMessage = fetchResponse.statusText;
150
+ }
151
+ const nodeResponseHeaders = new Set(Object.keys(nodeResponse.getHeaders()));
152
+ const setCookie = fetchResponse.headers.getSetCookie();
153
+ for (const cookie of setCookie) {
154
+ nodeResponse.appendHeader("set-cookie", cookie);
155
+ }
156
+ fetchResponse.headers.forEach((value, key) => {
157
+ nodeResponseHeaders.delete(key);
158
+ if (key === "set-cookie") return;
159
+ nodeResponse.setHeader(key, value);
160
+ });
161
+ if (mirror) {
162
+ nodeResponseHeaders.forEach((key) => nodeResponse.removeHeader(key));
163
+ }
164
+ }
165
+ function adaptHeaders(nodeHeaders) {
166
+ const headers = [];
167
+ const keys = Object.keys(nodeHeaders);
168
+ for (const key of keys) {
169
+ headers.push([key, normalizeHttpHeader(nodeHeaders[key])]);
170
+ }
171
+ return headers;
172
+ }
173
+ function normalizeHttpHeader(value) {
174
+ if (Array.isArray(value)) {
175
+ return value.join(", ");
176
+ }
177
+ return value || "";
178
+ }
10
179
 
11
- // src/index.ts
12
- import installNodeFetch from "@hattip/polyfills/node-fetch";
13
- import installGetSetCookie from "@hattip/polyfills/get-set-cookie";
14
- import installCrypto from "@hattip/polyfills/crypto";
15
- installNodeFetch();
16
- installGetSetCookie();
17
- installCrypto();
180
+ // src/common.ts
181
+ var contextSymbol = Symbol("unContext");
182
+ var requestSymbol = Symbol("unRequest");
183
+ var pendingMiddlewaresSymbol = Symbol("unPendingMiddlewares");
184
+ var wrappedResponseSymbol = Symbol("unWrappedResponse");
185
+ var env = typeof globalThis.process?.env !== "undefined" ? globalThis.process.env : typeof import.meta?.env !== "undefined" ? import.meta.env : {};
186
+ function createHandler(handler, options = {}) {
187
+ const requestAdapter = createRequestAdapter(options);
188
+ return async (req, res, next) => {
189
+ try {
190
+ req[contextSymbol] ??= {};
191
+ const request = requestAdapter(req);
192
+ const response = await handler(request, req[contextSymbol]);
193
+ await sendResponse(response, res);
194
+ } catch (error) {
195
+ if (next) {
196
+ next(error);
197
+ } else {
198
+ console.error(error);
199
+ if (!res.headersSent) {
200
+ res.statusCode = 500;
201
+ }
202
+ if (!res.writableEnded) {
203
+ res.end();
204
+ }
205
+ }
206
+ }
207
+ };
208
+ }
209
+ function createMiddleware(middleware, options = {}) {
210
+ const requestAdapter = createRequestAdapter(options);
211
+ return async (req, res, next) => {
212
+ try {
213
+ req[contextSymbol] ??= {};
214
+ const request = requestAdapter(req);
215
+ const response = await middleware(request, req[contextSymbol]);
216
+ if (!response) {
217
+ return next?.();
218
+ } else if (typeof response === "function") {
219
+ if (res.headersSent) {
220
+ throw new Error(
221
+ "Universal Middleware called after headers have been sent. Please open an issue at https://github.com/magne4000/universal-handler"
222
+ );
223
+ }
224
+ wrapResponse(res);
225
+ res[pendingMiddlewaresSymbol] ??= [];
226
+ res[pendingMiddlewaresSymbol].push(response);
227
+ return next?.();
228
+ } else {
229
+ await sendResponse(response, res);
230
+ }
231
+ } catch (error) {
232
+ if (next) {
233
+ next(error);
234
+ } else {
235
+ console.error(error);
236
+ if (!res.headersSent) {
237
+ res.statusCode = 500;
238
+ }
239
+ if (!res.writableEnded) {
240
+ res.end();
241
+ }
242
+ }
243
+ }
244
+ };
245
+ }
246
+ function getContext(req) {
247
+ return req[contextSymbol];
248
+ }
18
249
  export {
250
+ createHandler,
19
251
  createMiddleware,
20
252
  createRequestAdapter,
21
- createServer
253
+ getContext,
254
+ sendResponse
22
255
  };
package/package.json CHANGED
@@ -1,47 +1,47 @@
1
1
  {
2
2
  "name": "@universal-middleware/express",
3
- "version": "0.0.2",
3
+ "version": "0.1.0",
4
4
  "type": "module",
5
5
  "description": "Express adapter for universal middlewares",
6
6
  "files": [
7
7
  "dist"
8
8
  ],
9
+ "types": "./config.d.ts",
9
10
  "exports": {
10
- ".": "./dist/index.js",
11
- "./native-fetch": "./dist/native-fetch.js",
12
- "./whatwg-node": "./dist/whatwg-node.js",
13
- "./request": "./dist/request.js",
14
- "./response": "./dist/response.js",
15
- "./fast-fetch": "./dist/fast-fetch.js"
16
- },
17
- "typesVersions": {
18
- "*": {
19
- "*": [
20
- "dist/*.d.ts"
21
- ]
22
- }
11
+ ".": "./dist/index.js"
23
12
  },
24
13
  "author": "Joël Charles <joel.charles91@gmail.com>",
25
14
  "contributors": [
26
15
  "Fatih Aygün <cyco130@gmail.com>"
27
16
  ],
28
- "repository": "https://github.com/hattipjs/hattip",
17
+ "repository": "https://github.com/magne4000/universal-handler",
29
18
  "license": "MIT",
30
- "devDependencies": {
31
- "@types/node": "^20.12.12",
32
- "rimraf": "^5.0.7",
33
- "tsup": "^8.0.2",
34
- "typescript": "^5.4.5"
35
- },
36
- "dependencies": {
37
- "@hattip/core": "^0.0.45",
38
- "@hattip/polyfills": "^0.0.45",
39
- "@hattip/walk": "^0.0.45"
40
- },
41
19
  "scripts": {
42
20
  "build": "rimraf dist && tsup",
43
21
  "dev": "tsup --watch",
44
- "test": "pnpm test:typecheck",
45
- "test:typecheck": "tsc -p tsconfig.json --noEmit"
22
+ "prepack": "pnpm build",
23
+ "test": "vitest run",
24
+ "test:run-express:node": "tsx tests/entry-express.ts",
25
+ "test:run-express:bun": "bun tests/entry-express.ts",
26
+ "test:run-express:deno": "deno run --unstable-sloppy-imports -A tests/entry-express.ts",
27
+ "test:typecheck": "tsc -p tsconfig.json --noEmit",
28
+ "release": "LANG=en_US release-me patch",
29
+ "release:minor": "LANG=en_US release-me minor",
30
+ "release:commit": "LANG=en_US release-me commit"
31
+ },
32
+ "devDependencies": {
33
+ "@brillout/release-me": "^0.3.9",
34
+ "@types/node": "^20.14.10",
35
+ "express": "^4.19.2",
36
+ "helmet": "^7.1.0",
37
+ "mri": "^1.2.0",
38
+ "readable-stream": "^4.5.2",
39
+ "rimraf": "^6.0.0",
40
+ "tsup": "^8.1.0",
41
+ "tsx": "^4.16.2",
42
+ "typescript": "^5.5.3",
43
+ "vitest": "^2.0.2",
44
+ "wait-port": "^1.1.0",
45
+ "zx": "^8.1.4"
46
46
  }
47
- }
47
+ }
package/readme.md CHANGED
@@ -1,5 +1,3 @@
1
1
  # `@universal-middleware/express`
2
2
 
3
- Loosely adapted from [@hattip/adapter-node](https://github.com/hattipjs/hattip/tree/main/packages/adapter/adapter-node)
4
-
5
- WIP
3
+ [Universal Middleware](https://github.com/magne4000/universal-middleware) adapter for express and other connect-like servers.
package/LICENSE DELETED
@@ -1,7 +0,0 @@
1
- Copyright 2021 Fatih Aygün and contributors
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
-
5
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,69 +0,0 @@
1
- import {
2
- createRequestAdapter
3
- } from "./chunk-NPSKJAQI.js";
4
- import {
5
- sendResponse
6
- } from "./chunk-VWRNJC72.js";
7
-
8
- // src/common.ts
9
- import {
10
- createServer as createHttpServer
11
- } from "node:http";
12
- import process from "node:process";
13
- function createMiddleware(handler, options = {}) {
14
- const { alwaysCallNext = true, ...requestOptions } = options;
15
- const requestAdapter = createRequestAdapter(requestOptions);
16
- return async (req, res, next) => {
17
- try {
18
- const [request, ip] = requestAdapter(req);
19
- let passThroughCalled = false;
20
- const context = {
21
- request,
22
- ip,
23
- env(variable) {
24
- return process.env[variable];
25
- },
26
- waitUntil(promise) {
27
- },
28
- passThrough() {
29
- passThroughCalled = true;
30
- },
31
- platform: {
32
- name: "node",
33
- request: req,
34
- response: res
35
- }
36
- };
37
- const response = await handler(context);
38
- if (passThroughCalled && next) {
39
- next();
40
- return;
41
- }
42
- await sendResponse(response, res);
43
- if (next && alwaysCallNext) {
44
- next();
45
- }
46
- } catch (error) {
47
- if (next) {
48
- next(error);
49
- } else {
50
- console.error(error);
51
- if (!res.headersSent) {
52
- res.statusCode = 500;
53
- }
54
- if (!res.writableEnded) {
55
- res.end();
56
- }
57
- }
58
- }
59
- };
60
- }
61
- function createServer(handler, adapterOptions, serverOptions) {
62
- const listener = createMiddleware(handler, adapterOptions);
63
- return serverOptions ? createHttpServer(serverOptions, listener) : createHttpServer(listener);
64
- }
65
-
66
- export {
67
- createMiddleware,
68
- createServer
69
- };
@@ -1,6 +0,0 @@
1
- // src/raw-body-symbol.ts
2
- var rawBodySymbol = Symbol("rawBody");
3
-
4
- export {
5
- rawBodySymbol
6
- };
@@ -1,70 +0,0 @@
1
- // src/request.ts
2
- import process from "node:process";
3
- var deno = typeof Deno !== "undefined";
4
- var bun = typeof Bun !== "undefined";
5
- function createRequestAdapter(options = {}) {
6
- const {
7
- origin = process.env.ORIGIN,
8
- trustProxy = process.env.TRUST_PROXY === "1"
9
- } = options;
10
- let { protocol: protocolOverride, host: hostOverride } = origin ? new URL(origin) : {};
11
- if (protocolOverride) {
12
- protocolOverride = protocolOverride.slice(0, -1);
13
- }
14
- let warned = false;
15
- return function requestAdapter(req) {
16
- function parseForwardedHeader(name) {
17
- return (headers["x-forwarded-" + name] || "").split(",", 1)[0].trim();
18
- }
19
- let headers = req.headers;
20
- if (headers[":method"]) {
21
- headers = Object.fromEntries(
22
- Object.entries(headers).filter(([key]) => !key.startsWith(":"))
23
- );
24
- }
25
- const ip = req.ip || trustProxy && parseForwardedHeader("for") || req.socket?.remoteAddress || "";
26
- if (req._request) {
27
- return [req._request, ip];
28
- }
29
- const protocol = protocolOverride || req.protocol || trustProxy && parseForwardedHeader("proto") || req.socket?.encrypted && "https" || "http";
30
- let host = hostOverride || trustProxy && parseForwardedHeader("host") || headers.host;
31
- if (!host && !warned) {
32
- console.warn(
33
- "Could not automatically determine the origin host, using 'localhost'. Use the 'origin' option or the 'ORIGIN' environment variable to set the origin explicitly."
34
- );
35
- warned = true;
36
- host = "localhost";
37
- }
38
- const request = new Request(protocol + "://" + host + req.url, {
39
- method: req.method,
40
- headers,
41
- body: convertBody(req),
42
- // @ts-ignore
43
- duplex: "half"
44
- });
45
- req._request = request;
46
- return [request, ip];
47
- };
48
- }
49
- function convertBody(req) {
50
- if (req.method === "GET" || req.method === "HEAD") {
51
- return;
52
- }
53
- if (req.rawBody !== void 0) {
54
- return req.rawBody;
55
- }
56
- if (!bun && !deno) {
57
- return req;
58
- }
59
- return new ReadableStream({
60
- start(controller) {
61
- req.on("data", (chunk) => controller.enqueue(chunk));
62
- req.on("end", () => controller.close());
63
- req.on("error", (err) => controller.error(err));
64
- }
65
- });
66
- }
67
-
68
- export {
69
- createRequestAdapter
70
- };
@@ -1,81 +0,0 @@
1
- import {
2
- rawBodySymbol
3
- } from "./chunk-CDXJFGTO.js";
4
-
5
- // src/response.ts
6
- import { Readable } from "node:stream";
7
- var deno = typeof Deno !== "undefined";
8
- if (deno) {
9
- const oldSet = Headers.prototype.set;
10
- Headers.prototype.set = function set(key, value) {
11
- if (Array.isArray(value)) {
12
- this.delete(key);
13
- value.forEach((v) => this.append(key, v));
14
- } else {
15
- oldSet.call(this, key, value);
16
- }
17
- };
18
- }
19
- async function sendResponse(fetchResponse, nodeResponse) {
20
- if (fetchResponse[rawBodySymbol]) {
21
- writeHead(fetchResponse, nodeResponse);
22
- nodeResponse.end(fetchResponse[rawBodySymbol]);
23
- return;
24
- }
25
- const { body: fetchBody } = fetchResponse;
26
- let body = null;
27
- if (!deno && fetchBody instanceof Readable) {
28
- body = fetchBody;
29
- } else if (fetchBody instanceof ReadableStream) {
30
- if (!deno && Readable.fromWeb) {
31
- body = Readable.fromWeb(fetchBody);
32
- } else {
33
- const reader = fetchBody.getReader();
34
- body = new Readable({
35
- async read() {
36
- const { done, value } = await reader.read();
37
- this.push(done ? null : value);
38
- }
39
- });
40
- }
41
- } else if (fetchBody) {
42
- body = Readable.from(fetchBody);
43
- }
44
- writeHead(fetchResponse, nodeResponse);
45
- if (body) {
46
- body.pipe(nodeResponse);
47
- await new Promise((resolve, reject) => {
48
- body.on("error", reject);
49
- nodeResponse.on("finish", resolve);
50
- nodeResponse.on("error", reject);
51
- });
52
- } else {
53
- nodeResponse.setHeader("content-length", "0");
54
- nodeResponse.end();
55
- }
56
- }
57
- function writeHead(fetchResponse, nodeResponse) {
58
- nodeResponse.statusCode = fetchResponse.status;
59
- if (fetchResponse.statusText) {
60
- nodeResponse.statusMessage = fetchResponse.statusText;
61
- }
62
- const uniqueHeaderNames = new Set(fetchResponse.headers.keys());
63
- for (const key of uniqueHeaderNames) {
64
- if (key === "set-cookie") {
65
- const setCookie = fetchResponse.headers.getSetCookie();
66
- if (nodeResponse.appendHeader) {
67
- for (const cookie of setCookie) {
68
- nodeResponse.appendHeader("set-cookie", cookie);
69
- }
70
- } else {
71
- nodeResponse.setHeader("set-cookie", setCookie);
72
- }
73
- } else {
74
- nodeResponse.setHeader(key, fetchResponse.headers.get(key));
75
- }
76
- }
77
- }
78
-
79
- export {
80
- sendResponse
81
- };
@@ -1,2 +0,0 @@
1
-
2
- export { }
@@ -1,19 +0,0 @@
1
- import {
2
- rawBodySymbol
3
- } from "./chunk-CDXJFGTO.js";
4
-
5
- // src/fast-fetch.ts
6
- import { Readable } from "node:stream";
7
- var OriginalResponse = global.Response;
8
- var Response = class extends OriginalResponse {
9
- [rawBodySymbol];
10
- constructor(body, init) {
11
- super(body, init);
12
- if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer || body instanceof Readable) {
13
- this[rawBodySymbol] = body;
14
- }
15
- }
16
- };
17
- Object.defineProperty(global, "Response", {
18
- value: Response
19
- });
@@ -1,44 +0,0 @@
1
- import { HattipHandler } from '@hattip/core';
2
- import { IncomingMessage, ServerResponse, ServerOptions, Server } from 'node:http';
3
- import { Socket } from 'node:net';
4
- import { NodeRequestAdapterOptions } from './request.js';
5
- import 'node:buffer';
6
-
7
- interface PossiblyEncryptedSocket extends Socket {
8
- encrypted?: boolean;
9
- }
10
- /**
11
- * `IncomingMessage` possibly augmented by Express-specific
12
- * `ip` and `protocol` properties.
13
- */
14
- interface DecoratedRequest extends Omit<IncomingMessage, "socket"> {
15
- ip?: string;
16
- protocol?: string;
17
- socket?: PossiblyEncryptedSocket;
18
- }
19
- /** Connect/Express style request listener/middleware */
20
- type NodeMiddleware = (req: DecoratedRequest, res: ServerResponse, next?: (err?: unknown) => void) => void;
21
- /** Adapter options */
22
- interface NodeAdapterOptions extends NodeRequestAdapterOptions {
23
- /**
24
- * Whether to call the next middleware in the chain even if the request
25
- * was handled.@default true
26
- */
27
- alwaysCallNext?: boolean;
28
- }
29
- interface NodePlatformInfo {
30
- name: "node";
31
- request: DecoratedRequest;
32
- response: ServerResponse;
33
- }
34
- /**
35
- * Creates a request handler to be passed to http.createServer() or used as a
36
- * middleware in Connect-style frameworks like Express.
37
- */
38
- declare function createMiddleware(handler: HattipHandler<NodePlatformInfo>, options?: NodeAdapterOptions): NodeMiddleware;
39
- /**
40
- * Create an HTTP server
41
- */
42
- declare function createServer(handler: HattipHandler<NodePlatformInfo>, adapterOptions?: NodeAdapterOptions, serverOptions?: ServerOptions): Server;
43
-
44
- export { type DecoratedRequest, type NodeAdapterOptions, type NodeMiddleware, type NodePlatformInfo, createMiddleware, createServer };
@@ -1,25 +0,0 @@
1
- import {
2
- createMiddleware,
3
- createServer
4
- } from "./chunk-5VGN5WIU.js";
5
- import "./chunk-NPSKJAQI.js";
6
- import "./chunk-VWRNJC72.js";
7
- import "./chunk-CDXJFGTO.js";
8
-
9
- // src/native-fetch.ts
10
- import * as webStream from "node:stream/web";
11
- import installGetSetCookie from "@hattip/polyfills/get-set-cookie";
12
- import installCrypto from "@hattip/polyfills/crypto";
13
- import installHalfDuplexRequest from "@hattip/polyfills/half-duplex-request";
14
- installGetSetCookie();
15
- installCrypto();
16
- installHalfDuplexRequest();
17
- for (const key of Object.keys(webStream)) {
18
- if (!(key in globalThis)) {
19
- globalThis[key] = webStream[key];
20
- }
21
- }
22
- export {
23
- createMiddleware,
24
- createServer
25
- };
package/dist/request.d.ts DELETED
@@ -1,45 +0,0 @@
1
- import { IncomingMessage } from 'node:http';
2
- import { Socket } from 'node:net';
3
- import { Buffer } from 'node:buffer';
4
-
5
- interface PossiblyEncryptedSocket extends Socket {
6
- encrypted?: boolean;
7
- }
8
- /**
9
- * `IncomingMessage` possibly augmented with some environment-specific
10
- * properties.
11
- */
12
- interface DecoratedRequest extends Omit<IncomingMessage, "socket"> {
13
- ip?: string;
14
- protocol?: string;
15
- socket?: PossiblyEncryptedSocket;
16
- rawBody?: Buffer | null;
17
- _request?: Request;
18
- }
19
- /** Adapter options */
20
- interface NodeRequestAdapterOptions {
21
- /**
22
- * Set the origin part of the URL to a constant value.
23
- * It defaults to `process.env.ORIGIN`. If neither is set,
24
- * the origin is computed from the protocol and hostname.
25
- * To determine the protocol, `req.protocol` is tried first.
26
- * If `trustProxy` is set, `X-Forwarded-Proto` header is used.
27
- * Otherwise, `req.socket.encrypted` is used.
28
- * To determine the hostname, `X-Forwarded-Host`
29
- * (if `trustProxy` is set) or `Host` header is used.
30
- */
31
- origin?: string;
32
- /**
33
- * Whether to trust `X-Forwarded-*` headers. `X-Forwarded-Proto`
34
- * and `X-Forwarded-Host` are used to determine the origin when
35
- * `origin` and `process.env.ORIGIN` are not set. `X-Forwarded-For`
36
- * is used to determine the IP address. The leftmost values are used
37
- * if multiple values are set. Defaults to true if `process.env.TRUST_PROXY`
38
- * is set to `1`, otherwise false.
39
- */
40
- trustProxy?: boolean;
41
- }
42
- /** Create a function that converts a Node HTTP request into a fetch API `Request` object */
43
- declare function createRequestAdapter(options?: NodeRequestAdapterOptions): (req: DecoratedRequest) => [request: Request, ip: string];
44
-
45
- export { type DecoratedRequest, type NodeRequestAdapterOptions, createRequestAdapter };
package/dist/request.js DELETED
@@ -1,6 +0,0 @@
1
- import {
2
- createRequestAdapter
3
- } from "./chunk-NPSKJAQI.js";
4
- export {
5
- createRequestAdapter
6
- };
@@ -1,8 +0,0 @@
1
- import { ServerResponse } from 'node:http';
2
-
3
- /**
4
- * Send a fetch API Response into a Node.js HTTP response stream.
5
- */
6
- declare function sendResponse(fetchResponse: Response, nodeResponse: ServerResponse): Promise<void>;
7
-
8
- export { sendResponse };
package/dist/response.js DELETED
@@ -1,7 +0,0 @@
1
- import {
2
- sendResponse
3
- } from "./chunk-VWRNJC72.js";
4
- import "./chunk-CDXJFGTO.js";
5
- export {
6
- sendResponse
7
- };
@@ -1,16 +0,0 @@
1
- import { ServerResponse } from 'node:http';
2
- import { DecoratedRequest } from './native-fetch.js';
3
- export { NodeAdapterOptions, createMiddleware, createServer } from './native-fetch.js';
4
- import '@hattip/core';
5
- import 'node:net';
6
- import './request.js';
7
- import 'node:buffer';
8
-
9
- /** Connect/Express style request listener/middleware */
10
- type NodeMiddleware = (req: DecoratedRequest, res: ServerResponse, next?: () => void) => void;
11
- interface NodePlatformInfo {
12
- request: DecoratedRequest;
13
- response: ServerResponse;
14
- }
15
-
16
- export { DecoratedRequest, type NodeMiddleware, type NodePlatformInfo };
@@ -1,19 +0,0 @@
1
- import {
2
- createMiddleware,
3
- createServer
4
- } from "./chunk-5VGN5WIU.js";
5
- import "./chunk-NPSKJAQI.js";
6
- import "./chunk-VWRNJC72.js";
7
- import "./chunk-CDXJFGTO.js";
8
-
9
- // src/whatwg-node.ts
10
- import installWhatwgNodeFetch from "@hattip/polyfills/whatwg-node";
11
- import installGetSetCookie from "@hattip/polyfills/get-set-cookie";
12
- import installCrypto from "@hattip/polyfills/crypto";
13
- installWhatwgNodeFetch();
14
- installGetSetCookie();
15
- installCrypto();
16
- export {
17
- createMiddleware,
18
- createServer
19
- };