@universal-middleware/express 0.5.1 → 0.5.3
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 +21 -16
- package/dist/index.js +184 -132
- package/dist/request.d.ts +9 -1
- package/dist/request.js +20 -1
- package/package.json +7 -6
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { createRequestAdapter } from "./request.js";
|
|
2
|
-
import { Awaitable, EnhancedMiddleware, Get, RuntimeAdapterTarget, UniversalFn, UniversalHandler, UniversalMiddleware, UniversalRouter, UniversalRouterInterface } from "@universal-middleware/core";
|
|
2
|
+
import { Awaitable, EnhancedMiddleware, Get, RuntimeAdapter, RuntimeAdapterTarget, UniversalFn, UniversalHandler, UniversalMiddleware, UniversalRouter, UniversalRouterInterface } from "@universal-middleware/core";
|
|
3
3
|
import { DecoratedRequest, NodeRequestAdapterOptions, sendResponse } from "@universal-middleware/node";
|
|
4
4
|
import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
|
|
5
5
|
import { Readable } from "node:stream";
|
|
6
|
-
import { Express } from "express";
|
|
7
|
-
import { Express as Express$1 } from "express4";
|
|
8
6
|
//#region src/const.d.ts
|
|
9
7
|
declare const pendingMiddlewaresSymbol: unique symbol;
|
|
10
8
|
declare const wrappedResponseSymbol: unique symbol;
|
|
@@ -17,7 +15,6 @@ interface DecoratedServerResponse extends ServerResponse {
|
|
|
17
15
|
/** Connect/Express style request listener/middleware */
|
|
18
16
|
type NodeMiddleware<In extends Universal.Context, Out extends Universal.Context> = UniversalFn<UniversalMiddleware<In, Out>, <R>(req: DecoratedRequest<In>, res: DecoratedServerResponse, next?: (err?: unknown) => void) => R>;
|
|
19
17
|
type NodeHandler<In extends Universal.Context> = UniversalFn<UniversalHandler<In>, <R>(req: DecoratedRequest<In>, res: DecoratedServerResponse, next?: (err?: unknown) => void) => R>;
|
|
20
|
-
/** Adapter options */
|
|
21
18
|
interface NodeAdapterHandlerOptions extends NodeRequestAdapterOptions {}
|
|
22
19
|
interface NodeAdapterMiddlewareOptions extends NodeRequestAdapterOptions {}
|
|
23
20
|
//#endregion
|
|
@@ -32,9 +29,19 @@ export declare function createHandler<T extends unknown[], InContext extends Uni
|
|
|
32
29
|
*/
|
|
33
30
|
export declare function createMiddleware<T extends unknown[], InContext extends Universal.Context, OutContext extends Universal.Context>(middlewareFactory: Get<T, UniversalMiddleware<InContext, OutContext>>, options?: NodeAdapterMiddlewareOptions): Get<T, NodeMiddleware<InContext, OutContext>>;
|
|
34
31
|
export declare function getContext<InContext extends Universal.Context = Universal.Context>(req: DecoratedRequest): InContext;
|
|
32
|
+
export declare function getRuntime(request: DecoratedRequest, response: DecoratedServerResponse): RuntimeAdapter;
|
|
35
33
|
//#endregion
|
|
36
34
|
//#region src/utils.d.ts
|
|
37
|
-
type
|
|
35
|
+
type ExpressRequestHandler = (req: DecoratedRequest, res: DecoratedServerResponse, next: (err?: unknown) => void) => unknown;
|
|
36
|
+
/**
|
|
37
|
+
* The parts of an Express 4 or 5 application the adapter uses.
|
|
38
|
+
* Declared here so that the published types do not depend on a given `express` or `@types/express` version.
|
|
39
|
+
*/
|
|
40
|
+
interface Express {
|
|
41
|
+
(req: IncomingMessage, res: ServerResponse): void;
|
|
42
|
+
use(...handlers: ExpressRequestHandler[]): unknown;
|
|
43
|
+
all(path: string, ...handlers: ExpressRequestHandler[]): unknown;
|
|
44
|
+
}
|
|
38
45
|
type ConnectMiddleware = (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void | Promise<void>;
|
|
39
46
|
type ConnectMiddlewareBoolean = (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => boolean | Promise<boolean>;
|
|
40
47
|
type WebHandler<InContext extends Universal.Context = Universal.Context, Target = unknown> = (request: Request, context?: InContext, runtime?: RuntimeAdapterTarget<Target>) => Response | undefined | Promise<Response | undefined>;
|
|
@@ -49,14 +56,9 @@ export declare function connectToWeb(handler: ConnectMiddleware | ConnectMiddlew
|
|
|
49
56
|
*/
|
|
50
57
|
export declare function createIncomingMessage(request: Request): IncomingMessage;
|
|
51
58
|
/**
|
|
52
|
-
* Creates a
|
|
53
|
-
*
|
|
59
|
+
* Creates a `ServerResponse` whose output is captured. `onReadable`'s callback gets the output stream, the headers and
|
|
60
|
+
* the status once the response starts.
|
|
54
61
|
* @beta
|
|
55
|
-
* @returns
|
|
56
|
-
* An object containing:
|
|
57
|
-
* - res: The custom ServerResponse object.
|
|
58
|
-
* - onReadable: A function that takes a callback. The callback is invoked when the response is readable,
|
|
59
|
-
* providing an object with the readable stream, headers, and status code.
|
|
60
62
|
*/
|
|
61
63
|
export declare function createServerResponse(incomingMessage: IncomingMessage): {
|
|
62
64
|
res: ServerResponse<IncomingMessage>;
|
|
@@ -64,18 +66,21 @@ export declare function createServerResponse(incomingMessage: IncomingMessage):
|
|
|
64
66
|
readable: Readable;
|
|
65
67
|
headers: OutgoingHttpHeaders;
|
|
66
68
|
statusCode: number;
|
|
69
|
+
statusMessage: string | undefined;
|
|
67
70
|
}) => void) => void;
|
|
68
71
|
};
|
|
69
72
|
//#endregion
|
|
70
73
|
//#region src/router.d.ts
|
|
71
|
-
type App = Express
|
|
74
|
+
type App = Express;
|
|
75
|
+
/** The options `apply` passes to every middleware and handler it adapts */
|
|
76
|
+
type ApplyOptions = NodeAdapterHandlerOptions & NodeAdapterMiddlewareOptions;
|
|
72
77
|
type EnhancedMiddlewareExpress = EnhancedMiddleware | EnhancedMiddleware<Universal.Context, Universal.Context, "express">;
|
|
73
78
|
declare class UniversalExpressRouter<T extends App> extends UniversalRouter implements UniversalRouterInterface {
|
|
74
79
|
#private;
|
|
75
|
-
constructor(app: T);
|
|
80
|
+
constructor(app: T, options?: ApplyOptions);
|
|
76
81
|
use(middleware: EnhancedMiddlewareExpress): this;
|
|
77
82
|
applyCatchAll(): this;
|
|
78
83
|
}
|
|
79
|
-
export declare function apply(app: Express
|
|
84
|
+
export declare function apply(app: Express, middlewares: EnhancedMiddlewareExpress[], options?: ApplyOptions): void;
|
|
80
85
|
//#endregion
|
|
81
|
-
export { type App, type ConnectMiddleware, type ConnectMiddlewareBoolean, type DecoratedRequest, type DecoratedServerResponse, type NodeHandler, type NodeMiddleware, type UniversalExpressRouter, type WebHandler, createRequestAdapter, sendResponse };
|
|
86
|
+
export { type App, type ConnectMiddleware, type ConnectMiddlewareBoolean, type DecoratedRequest, type DecoratedServerResponse, type NodeAdapterHandlerOptions, type NodeAdapterMiddlewareOptions, type NodeHandler, type NodeMiddleware, type UniversalExpressRouter, type WebHandler, createRequestAdapter, sendResponse };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { createRequestAdapter } from "./request.js";
|
|
2
|
-
import { UniversalRouter, apply as apply$1, bindUniversal, contextSymbol, getAdapterRuntime, getUniversal, universalSymbol } from "@universal-middleware/core";
|
|
3
|
-
import { requestSymbol, responseAdapter, sendResponse, setResponseHeaders } from "@universal-middleware/node";
|
|
4
|
-
import { EventEmitter } from "node:events";
|
|
1
|
+
import { createRequestAdapter, expressOrigin } from "./request.js";
|
|
2
|
+
import { UniversalRouter, apply as apply$1, bindUniversal, cancelReplacedBody, contextSymbol, getAdapterRuntime, getUniversal, universalSymbol } from "@universal-middleware/core";
|
|
3
|
+
import { BadRequestError, requestSymbol, responseAdapter, sendResponse, setResponseHeaders } from "@universal-middleware/node";
|
|
4
|
+
import { EventEmitter, once } from "node:events";
|
|
5
5
|
import { ServerResponse } from "node:http";
|
|
6
6
|
import { PassThrough, Readable } from "node:stream";
|
|
7
7
|
//#region src/const.ts
|
|
@@ -12,12 +12,18 @@ const wrappedResponseSymbol = Symbol.for("unWrappedResponse");
|
|
|
12
12
|
const MAX_LENT_BYTES = 1048576;
|
|
13
13
|
const lentSymbol = Symbol("universal-middleware.lentBody");
|
|
14
14
|
/**
|
|
15
|
-
* Create the `Request` for `req
|
|
16
|
-
*
|
|
15
|
+
* Create the `Request` for `req`. Its body reads the Node request lazily and without ending it, so that
|
|
16
|
+
* `handBodyBack` can put what the middleware read back for the next Express handler.
|
|
17
17
|
*/
|
|
18
18
|
function adaptLendingBody(adapt, req, res) {
|
|
19
19
|
if (req.method === "GET" || req.method === "HEAD") return adapt(req, res);
|
|
20
|
-
if (req.rawBody !== void 0 || req.readableEnded)
|
|
20
|
+
if (req.rawBody !== void 0 || req.readableEnded) {
|
|
21
|
+
if (req[lentSymbol]) {
|
|
22
|
+
req[lentSymbol] = void 0;
|
|
23
|
+
delete req[requestSymbol];
|
|
24
|
+
}
|
|
25
|
+
return adapt(req, res);
|
|
26
|
+
}
|
|
21
27
|
if (req[lentSymbol]) return adapt(req, res);
|
|
22
28
|
const lend = new LentBody(req);
|
|
23
29
|
req[lentSymbol] = lend;
|
|
@@ -93,100 +99,155 @@ var LentBody = class {
|
|
|
93
99
|
}
|
|
94
100
|
};
|
|
95
101
|
//#endregion
|
|
96
|
-
//#region src/
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
102
|
+
//#region src/head.ts
|
|
103
|
+
/** Sets on `res` the status, status message and headers a `res.writeHead()` call carries, without sending them */
|
|
104
|
+
function setHead(res, statusCode, statusMessage, headers) {
|
|
105
|
+
res.statusCode = statusCode;
|
|
106
|
+
if (typeof statusMessage === "string") res.statusMessage = statusMessage;
|
|
107
|
+
else headers ??= statusMessage;
|
|
108
|
+
if (Array.isArray(headers)) {
|
|
109
|
+
for (let i = 0; i < headers.length; i += 2) res.removeHeader(String(headers[i]));
|
|
110
|
+
for (let i = 0; i < headers.length; i += 2) {
|
|
111
|
+
const value = headers[i + 1];
|
|
112
|
+
res.appendHeader(String(headers[i]), typeof value === "number" ? String(value) : value);
|
|
113
|
+
}
|
|
114
|
+
} else if (headers) {
|
|
115
|
+
for (const [name, value] of Object.entries(headers)) if (value !== void 0) res.setHeader(name, value);
|
|
116
|
+
}
|
|
104
117
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
118
|
+
//#endregion
|
|
119
|
+
//#region src/response.ts
|
|
120
|
+
/** Routes the app's writes to `writer`. As a socket would, `write()` returns false once `writer` is full, then "drain" follows. */
|
|
121
|
+
function captureOutput(nodeResponse, writer) {
|
|
122
|
+
let draining = false;
|
|
123
|
+
function capture(chunk, encoding) {
|
|
108
124
|
if (!nodeResponse.headersSent) nodeResponse.writeHead(nodeResponse.statusCode);
|
|
109
|
-
|
|
110
|
-
if (
|
|
111
|
-
return
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
125
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk, encoding) : chunk;
|
|
126
|
+
if (!bytes?.byteLength) return Promise.resolve();
|
|
127
|
+
return writer.write(bytes).catch((error) => {
|
|
128
|
+
if (writer.desiredSize !== null) console.error(error);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
nodeResponse.write = (chunk, encoding, callback) => {
|
|
132
|
+
if (typeof encoding === "function") {
|
|
133
|
+
callback = encoding;
|
|
134
|
+
encoding = void 0;
|
|
135
|
+
}
|
|
136
|
+
capture(chunk, encoding).then(() => callback?.());
|
|
137
|
+
const room = writer.desiredSize;
|
|
138
|
+
if (room === null || room > 0) return true;
|
|
139
|
+
if (!draining) {
|
|
140
|
+
draining = true;
|
|
141
|
+
const drain = () => {
|
|
142
|
+
draining = false;
|
|
143
|
+
nodeResponse.emit("drain");
|
|
144
|
+
};
|
|
145
|
+
writer.ready.then(drain, drain);
|
|
119
146
|
}
|
|
147
|
+
return false;
|
|
120
148
|
};
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
if (
|
|
127
|
-
callback
|
|
128
|
-
|
|
149
|
+
nodeResponse.end = (chunk, encoding, callback) => {
|
|
150
|
+
if (typeof chunk === "function") {
|
|
151
|
+
callback = chunk;
|
|
152
|
+
chunk = void 0;
|
|
153
|
+
encoding = void 0;
|
|
154
|
+
} else if (typeof encoding === "function") {
|
|
155
|
+
callback = encoding;
|
|
156
|
+
encoding = void 0;
|
|
129
157
|
}
|
|
158
|
+
capture(chunk, encoding);
|
|
159
|
+
writer.close().catch(() => {});
|
|
160
|
+
if (callback) nodeResponse.once("finish", callback);
|
|
130
161
|
return nodeResponse;
|
|
131
162
|
};
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
163
|
+
}
|
|
164
|
+
/** Holds the head back: the first call runs `onHead`, later ones no-op while the pending middlewares run */
|
|
165
|
+
function holdHead(nodeResponse, onHead) {
|
|
166
|
+
let held = false;
|
|
167
|
+
nodeResponse.writeHead = (statusCode, statusMessage, headers) => {
|
|
168
|
+
if (held) return nodeResponse;
|
|
169
|
+
held = true;
|
|
170
|
+
setHead(nodeResponse, statusCode, statusMessage, headers);
|
|
171
|
+
onHead();
|
|
172
|
+
return nodeResponse;
|
|
139
173
|
};
|
|
140
174
|
}
|
|
141
175
|
function wrapResponse(nodeResponse, next) {
|
|
142
176
|
if (nodeResponse[wrappedResponseSymbol]) return;
|
|
143
177
|
nodeResponse[wrappedResponseSymbol] = true;
|
|
144
|
-
const body = createTransformStream();
|
|
145
|
-
const writer = body.writable.getWriter();
|
|
146
|
-
const [reader1, reader2] = body.readable.tee();
|
|
147
178
|
const original = {
|
|
148
|
-
write:
|
|
149
|
-
end:
|
|
150
|
-
writeHead:
|
|
179
|
+
write: nodeResponse.write,
|
|
180
|
+
end: nodeResponse.end,
|
|
181
|
+
writeHead: nodeResponse.writeHead
|
|
182
|
+
};
|
|
183
|
+
const send = {
|
|
184
|
+
write: original.write.bind(nodeResponse),
|
|
185
|
+
end: original.end.bind(nodeResponse)
|
|
151
186
|
};
|
|
187
|
+
let capture;
|
|
188
|
+
const captured = new TransformStream({ start(controller) {
|
|
189
|
+
capture = controller;
|
|
190
|
+
} }, new ByteLengthQueuingStrategy({ highWaterMark: nodeResponse.writableHighWaterMark || 16384 }));
|
|
191
|
+
captureOutput(nodeResponse, captured.writable.getWriter());
|
|
192
|
+
holdHead(nodeResponse, () => {
|
|
193
|
+
triggerPendingMiddlewares().catch(console.error);
|
|
194
|
+
});
|
|
152
195
|
async function triggerPendingMiddlewares() {
|
|
153
|
-
if (!nodeResponse[pendingMiddlewaresSymbol]) return;
|
|
154
196
|
const middlewares = nodeResponse[pendingMiddlewaresSymbol];
|
|
197
|
+
if (!middlewares) return;
|
|
155
198
|
delete nodeResponse[pendingMiddlewaresSymbol];
|
|
156
199
|
let response;
|
|
157
200
|
try {
|
|
158
|
-
response = responseAdapter(nodeResponse,
|
|
201
|
+
response = responseAdapter(nodeResponse, captured.readable);
|
|
159
202
|
for (const middleware of middlewares) {
|
|
160
203
|
const tmp = await middleware(response);
|
|
204
|
+
cancelReplacedBody(response, tmp);
|
|
161
205
|
if (tmp) response = tmp;
|
|
162
206
|
}
|
|
163
207
|
} catch (e) {
|
|
164
|
-
|
|
165
|
-
await
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
208
|
+
capture.error(e);
|
|
209
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
210
|
+
Object.assign(nodeResponse, original);
|
|
211
|
+
if (next) {
|
|
212
|
+
next(e);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
throw e;
|
|
171
216
|
}
|
|
172
|
-
if (!response) return;
|
|
173
|
-
const readableToOriginal = response.body ?? reader2;
|
|
174
217
|
setResponseHeaders(response, nodeResponse, true);
|
|
175
|
-
original.writeHead
|
|
218
|
+
nodeResponse.writeHead = original.writeHead;
|
|
176
219
|
nodeResponse.flushHeaders();
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
220
|
+
const body = nodeResponse.req?.method === "HEAD" ? null : response.body;
|
|
221
|
+
if (!body) {
|
|
222
|
+
response.body?.cancel().catch(() => {});
|
|
223
|
+
if (!captured.readable.locked) captured.readable.cancel().catch(() => {});
|
|
224
|
+
send.end();
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const gone = new AbortController();
|
|
228
|
+
const onClose = () => gone.abort();
|
|
229
|
+
nodeResponse.once("close", onClose);
|
|
230
|
+
if (nodeResponse.destroyed) gone.abort();
|
|
231
|
+
try {
|
|
232
|
+
await body.pipeTo(new WritableStream({
|
|
233
|
+
async write(chunk) {
|
|
234
|
+
if (!send.write(chunk)) await once(nodeResponse, "drain", { signal: gone.signal }).catch(() => {});
|
|
235
|
+
},
|
|
236
|
+
close() {
|
|
237
|
+
send.end();
|
|
238
|
+
},
|
|
239
|
+
abort() {
|
|
240
|
+
send.end();
|
|
241
|
+
}
|
|
242
|
+
}), { signal: gone.signal });
|
|
243
|
+
} catch (error) {
|
|
244
|
+
if (gone.signal.aborted) return;
|
|
245
|
+
throw error;
|
|
246
|
+
} finally {
|
|
247
|
+
nodeResponse.off("close", onClose);
|
|
248
|
+
}
|
|
249
|
+
nodeResponse.write = original.write;
|
|
250
|
+
nodeResponse.end = original.end;
|
|
190
251
|
}
|
|
191
252
|
}
|
|
192
253
|
//#endregion
|
|
@@ -204,12 +265,13 @@ function nextOr404(res, next) {
|
|
|
204
265
|
*/
|
|
205
266
|
function createHandler(handlerFactory, options = {}) {
|
|
206
267
|
const requestAdapter = createRequestAdapter(options);
|
|
268
|
+
const adapt = (req, res) => requestAdapter(req, res, expressOrigin(req));
|
|
207
269
|
return (...args) => {
|
|
208
270
|
const handler = handlerFactory(...args);
|
|
209
271
|
return bindUniversal(handler, async function universalHandlerExpress(req, res, next) {
|
|
210
272
|
try {
|
|
211
273
|
req[contextSymbol] ??= {};
|
|
212
|
-
const request = adaptLendingBody(
|
|
274
|
+
const request = adaptLendingBody(adapt, req, res);
|
|
213
275
|
const response = await this[universalSymbol](request, req[contextSymbol], getRuntime(req, res));
|
|
214
276
|
if (!response) {
|
|
215
277
|
handBodyBack(req);
|
|
@@ -220,8 +282,9 @@ function createHandler(handlerFactory, options = {}) {
|
|
|
220
282
|
handBodyBack(req);
|
|
221
283
|
next(error);
|
|
222
284
|
} else {
|
|
223
|
-
|
|
224
|
-
if (!
|
|
285
|
+
const badRequest = error instanceof BadRequestError;
|
|
286
|
+
if (!badRequest) console.error(error);
|
|
287
|
+
if (!res.headersSent) res.statusCode = badRequest ? error.status : 500;
|
|
225
288
|
if (!res.writableEnded) res.end();
|
|
226
289
|
}
|
|
227
290
|
}
|
|
@@ -233,12 +296,13 @@ function createHandler(handlerFactory, options = {}) {
|
|
|
233
296
|
*/
|
|
234
297
|
function createMiddleware(middlewareFactory, options = {}) {
|
|
235
298
|
const requestAdapter = createRequestAdapter(options);
|
|
299
|
+
const adapt = (req, res) => requestAdapter(req, res, expressOrigin(req));
|
|
236
300
|
return (...args) => {
|
|
237
301
|
const middleware = middlewareFactory(...args);
|
|
238
302
|
return bindUniversal(middleware, async function universalMiddlewareExpress(req, res, next) {
|
|
239
303
|
try {
|
|
240
304
|
req[contextSymbol] ??= {};
|
|
241
|
-
const request = adaptLendingBody(
|
|
305
|
+
const request = adaptLendingBody(adapt, req, res);
|
|
242
306
|
const response = await this[universalSymbol](request, getContext(req), getRuntime(req, res));
|
|
243
307
|
if (!(response instanceof Response)) handBodyBack(req);
|
|
244
308
|
if (!response) return nextOr404(res, next);
|
|
@@ -260,8 +324,9 @@ function createMiddleware(middlewareFactory, options = {}) {
|
|
|
260
324
|
handBodyBack(req);
|
|
261
325
|
next(error);
|
|
262
326
|
} else {
|
|
263
|
-
|
|
264
|
-
if (!
|
|
327
|
+
const badRequest = error instanceof BadRequestError;
|
|
328
|
+
if (!badRequest) console.error(error);
|
|
329
|
+
if (!res.headersSent) res.statusCode = badRequest ? error.status : 500;
|
|
265
330
|
if (!res.writableEnded) res.end();
|
|
266
331
|
}
|
|
267
332
|
}
|
|
@@ -283,6 +348,31 @@ function getRuntime(request, response) {
|
|
|
283
348
|
});
|
|
284
349
|
}
|
|
285
350
|
//#endregion
|
|
351
|
+
//#region src/router.ts
|
|
352
|
+
var UniversalExpressRouter = class extends UniversalRouter {
|
|
353
|
+
#app;
|
|
354
|
+
#options;
|
|
355
|
+
constructor(app, options = {}) {
|
|
356
|
+
super(false);
|
|
357
|
+
this.#app = app;
|
|
358
|
+
this.#options = options;
|
|
359
|
+
}
|
|
360
|
+
use(middleware) {
|
|
361
|
+
this.#app.use(createMiddleware(() => getUniversal(middleware), this.#options)());
|
|
362
|
+
return this;
|
|
363
|
+
}
|
|
364
|
+
applyCatchAll() {
|
|
365
|
+
const handler = createHandler(() => this[universalSymbol], this.#options)();
|
|
366
|
+
this.#app.all("del" in this.#app ? "/**" : "/{*catchAll}", handler);
|
|
367
|
+
return this;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
function apply(app, middlewares, options) {
|
|
371
|
+
const router = new UniversalExpressRouter(app, options);
|
|
372
|
+
apply$1(router, middlewares, true);
|
|
373
|
+
Promise.resolve().then(() => router.applyCatchAll());
|
|
374
|
+
}
|
|
375
|
+
//#endregion
|
|
286
376
|
//#region src/utils.ts
|
|
287
377
|
const statusCodesWithoutBody = [
|
|
288
378
|
100,
|
|
@@ -306,7 +396,7 @@ function connectToWeb(handler) {
|
|
|
306
396
|
const { res, onReadable } = createServerResponse(req);
|
|
307
397
|
const stopForwardingAbort = realReq ? void 0 : forwardAbort(request.signal, req, res);
|
|
308
398
|
return new Promise(async (resolve, reject) => {
|
|
309
|
-
onReadable(({ readable, headers, statusCode }) => {
|
|
399
|
+
onReadable(({ readable, headers, statusCode, statusMessage }) => {
|
|
310
400
|
const hasBody = !statusCodesWithoutBody.includes(statusCode);
|
|
311
401
|
if (stopForwardingAbort) {
|
|
312
402
|
if (hasBody) readable.once("close", stopForwardingAbort);
|
|
@@ -314,6 +404,7 @@ function connectToWeb(handler) {
|
|
|
314
404
|
}
|
|
315
405
|
resolve(new Response(hasBody ? toWebStream(readable) : null, {
|
|
316
406
|
status: statusCode,
|
|
407
|
+
statusText: statusMessage,
|
|
317
408
|
headers: flattenHeaders(headers)
|
|
318
409
|
}));
|
|
319
410
|
});
|
|
@@ -341,7 +432,10 @@ function connectToWeb(handler) {
|
|
|
341
432
|
function createIncomingMessage(request) {
|
|
342
433
|
const url = new URL(request.url, "http://localhost");
|
|
343
434
|
const body = request.body ? Readable.fromWeb(request.body) : Readable.from([]);
|
|
344
|
-
const headers =
|
|
435
|
+
const headers = {
|
|
436
|
+
host: url.host,
|
|
437
|
+
...Object.fromEntries(request.headers)
|
|
438
|
+
};
|
|
345
439
|
if (request.body && headers["content-length"] === void 0) headers["transfer-encoding"] = "chunked";
|
|
346
440
|
const message = Object.assign(body, {
|
|
347
441
|
url: url.pathname + url.search,
|
|
@@ -363,14 +457,9 @@ function createIncomingMessage(request) {
|
|
|
363
457
|
return message;
|
|
364
458
|
}
|
|
365
459
|
/**
|
|
366
|
-
* Creates a
|
|
367
|
-
*
|
|
460
|
+
* Creates a `ServerResponse` whose output is captured. `onReadable`'s callback gets the output stream, the headers and
|
|
461
|
+
* the status once the response starts.
|
|
368
462
|
* @beta
|
|
369
|
-
* @returns
|
|
370
|
-
* An object containing:
|
|
371
|
-
* - res: The custom ServerResponse object.
|
|
372
|
-
* - onReadable: A function that takes a callback. The callback is invoked when the response is readable,
|
|
373
|
-
* providing an object with the readable stream, headers, and status code.
|
|
374
463
|
*/
|
|
375
464
|
function createServerResponse(incomingMessage) {
|
|
376
465
|
const res = new ServerResponse(incomingMessage);
|
|
@@ -383,7 +472,8 @@ function createServerResponse(incomingMessage) {
|
|
|
383
472
|
cb({
|
|
384
473
|
readable: Readable.from(passThrough),
|
|
385
474
|
headers: res.getHeaders(),
|
|
386
|
-
statusCode: res.statusCode
|
|
475
|
+
statusCode: res.statusCode,
|
|
476
|
+
statusMessage: res.statusMessage
|
|
387
477
|
});
|
|
388
478
|
};
|
|
389
479
|
passThrough.once("readable", handleReadable);
|
|
@@ -402,14 +492,7 @@ function createServerResponse(incomingMessage) {
|
|
|
402
492
|
res.write = passThrough.write.bind(passThrough);
|
|
403
493
|
res.end = passThrough.end.bind(passThrough);
|
|
404
494
|
res.writeHead = function writeHead(statusCode, statusMessage, headers) {
|
|
405
|
-
res
|
|
406
|
-
if (typeof statusMessage === "object") {
|
|
407
|
-
headers = statusMessage;
|
|
408
|
-
statusMessage = void 0;
|
|
409
|
-
}
|
|
410
|
-
if (headers) {
|
|
411
|
-
for (const [key, value] of Object.entries(headers)) if (value !== void 0) res.setHeader(key, value);
|
|
412
|
-
}
|
|
495
|
+
setHead(res, statusCode, statusMessage, headers);
|
|
413
496
|
return res;
|
|
414
497
|
};
|
|
415
498
|
return {
|
|
@@ -418,10 +501,8 @@ function createServerResponse(incomingMessage) {
|
|
|
418
501
|
};
|
|
419
502
|
}
|
|
420
503
|
/**
|
|
421
|
-
* Bridges a
|
|
422
|
-
*
|
|
423
|
-
* `createRequestAdapter` derives the handler's `request.signal` from `res`'s "close" event,
|
|
424
|
-
* which a socketless `ServerResponse` never emits on its own — so emit it explicitly.
|
|
504
|
+
* Bridges a Web `AbortSignal` to a synthetic `req`/`res`, and returns a function that stops it.
|
|
505
|
+
* The request adapter aborts `request.signal` on `res`'s "close", which a socketless `ServerResponse` never emits.
|
|
425
506
|
*/
|
|
426
507
|
function forwardAbort(signal, req, res) {
|
|
427
508
|
let active = true;
|
|
@@ -465,34 +546,5 @@ function flattenHeaders(headers) {
|
|
|
465
546
|
}
|
|
466
547
|
return flatHeaders;
|
|
467
548
|
}
|
|
468
|
-
function isExpressV4(app) {
|
|
469
|
-
return "del" in app;
|
|
470
|
-
}
|
|
471
|
-
function isExpressV5(app) {
|
|
472
|
-
return !isExpressV4(app);
|
|
473
|
-
}
|
|
474
|
-
//#endregion
|
|
475
|
-
//#region src/router.ts
|
|
476
|
-
var UniversalExpressRouter = class extends UniversalRouter {
|
|
477
|
-
#app;
|
|
478
|
-
constructor(app) {
|
|
479
|
-
super(false);
|
|
480
|
-
this.#app = app;
|
|
481
|
-
}
|
|
482
|
-
use(middleware) {
|
|
483
|
-
this.#app.use(createMiddleware(() => getUniversal(middleware))());
|
|
484
|
-
return this;
|
|
485
|
-
}
|
|
486
|
-
applyCatchAll() {
|
|
487
|
-
if (isExpressV5(this.#app)) this.#app.all("/{*catchAll}", createHandler(() => this[universalSymbol])());
|
|
488
|
-
if (isExpressV4(this.#app)) this.#app.all("/**", createHandler(() => this[universalSymbol])());
|
|
489
|
-
return this;
|
|
490
|
-
}
|
|
491
|
-
};
|
|
492
|
-
function apply(app, middlewares) {
|
|
493
|
-
const router = new UniversalExpressRouter(app);
|
|
494
|
-
apply$1(router, middlewares, true);
|
|
495
|
-
Promise.resolve().then(() => router.applyCatchAll());
|
|
496
|
-
}
|
|
497
549
|
//#endregion
|
|
498
|
-
export { apply, connectToWeb, createHandler, createIncomingMessage, createMiddleware, createRequestAdapter, createServerResponse, getContext, sendResponse };
|
|
550
|
+
export { apply, connectToWeb, createHandler, createIncomingMessage, createMiddleware, createRequestAdapter, createServerResponse, getContext, getRuntime, sendResponse };
|
package/dist/request.d.ts
CHANGED
|
@@ -1,2 +1,10 @@
|
|
|
1
|
-
import { DecoratedRequest, NodeRequestAdapterOptions, PossiblyEncryptedSocket, createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
|
|
1
|
+
import { DecoratedRequest, DecoratedRequest as DecoratedRequest$1, NodeRequestAdapterOptions, PossiblyEncryptedSocket, RequestOrigin, createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
|
|
2
|
+
//#region src/request.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The host Express gives `req` under its `trust proxy` setting: the first `X-Forwarded-Host`, when the setting
|
|
5
|
+
* trusts the peer, as Express 5's `req.host` reads it. Express 4 has no such getter: its `req.host` drops the port.
|
|
6
|
+
* The protocol needs nothing: `req.protocol` follows `trust proxy` in both, and the request adapter reads it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function expressOrigin(req: DecoratedRequest$1): RequestOrigin | undefined;
|
|
9
|
+
//#endregion
|
|
2
10
|
export { type DecoratedRequest, type NodeRequestAdapterOptions, type PossiblyEncryptedSocket, createRequestAdapter, env, requestSymbol };
|
package/dist/request.js
CHANGED
|
@@ -1,2 +1,21 @@
|
|
|
1
1
|
import { createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
|
|
2
|
-
|
|
2
|
+
//#region src/request.ts
|
|
3
|
+
/**
|
|
4
|
+
* The host Express gives `req` under its `trust proxy` setting: the first `X-Forwarded-Host`, when the setting
|
|
5
|
+
* trusts the peer, as Express 5's `req.host` reads it. Express 4 has no such getter: its `req.host` drops the port.
|
|
6
|
+
* The protocol needs nothing: `req.protocol` follows `trust proxy` in both, and the request adapter reads it.
|
|
7
|
+
*/
|
|
8
|
+
function expressOrigin(req) {
|
|
9
|
+
const forwarded = req.headers["x-forwarded-host"];
|
|
10
|
+
if (!forwarded || !trustsPeer(req)) return;
|
|
11
|
+
return { host: String(forwarded).split(",", 1)[0].trim() };
|
|
12
|
+
}
|
|
13
|
+
/** Whether the app's `trust proxy` setting trusts the peer that sent `req` */
|
|
14
|
+
function trustsPeer(req) {
|
|
15
|
+
const app = "app" in req ? req.app : void 0;
|
|
16
|
+
if (typeof app !== "function" || !("get" in app) || typeof app.get !== "function") return false;
|
|
17
|
+
const trust = app.get("trust proxy fn");
|
|
18
|
+
return typeof trust === "function" && trust(req.socket?.remoteAddress, 0) === true;
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
export { createRequestAdapter, env, expressOrigin, requestSymbol };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@universal-middleware/express",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Express adapter for universal middlewares",
|
|
6
6
|
"files": [
|
|
@@ -16,19 +16,20 @@
|
|
|
16
16
|
"url": "https://github.com/magne4000/universal-middleware"
|
|
17
17
|
},
|
|
18
18
|
"license": "MIT",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22"
|
|
21
|
+
},
|
|
19
22
|
"dependencies": {
|
|
20
|
-
"@universal-middleware/core": "^0.6.
|
|
21
|
-
"@universal-middleware/node": "^0.2.
|
|
23
|
+
"@universal-middleware/core": "^0.6.2",
|
|
24
|
+
"@universal-middleware/node": "^0.2.8"
|
|
22
25
|
},
|
|
23
26
|
"devDependencies": {
|
|
24
|
-
"@swc/core": "^1.16.13",
|
|
25
27
|
"@types/express": "^5.0.6",
|
|
26
28
|
"@types/express4": "npm:@types/express@^4.17.25",
|
|
27
|
-
"@types/node": "^
|
|
29
|
+
"@types/node": "^22.18.0",
|
|
28
30
|
"express": "^5.2.1",
|
|
29
31
|
"express4": "npm:express@^4.22.3",
|
|
30
32
|
"helmet": "^8.3.0",
|
|
31
|
-
"rimraf": "^6.1.3",
|
|
32
33
|
"tsdown": "^0.23.0",
|
|
33
34
|
"tsx": "^4.23.15",
|
|
34
35
|
"typescript": "^7.0.2",
|