@universal-middleware/express 0.5.2 → 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 +7 -10
- package/dist/index.js +158 -107
- package/dist/request.d.ts +9 -1
- package/dist/request.js +20 -1
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -15,7 +15,6 @@ interface DecoratedServerResponse extends ServerResponse {
|
|
|
15
15
|
/** Connect/Express style request listener/middleware */
|
|
16
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>;
|
|
17
17
|
type NodeHandler<In extends Universal.Context> = UniversalFn<UniversalHandler<In>, <R>(req: DecoratedRequest<In>, res: DecoratedServerResponse, next?: (err?: unknown) => void) => R>;
|
|
18
|
-
/** Adapter options */
|
|
19
18
|
interface NodeAdapterHandlerOptions extends NodeRequestAdapterOptions {}
|
|
20
19
|
interface NodeAdapterMiddlewareOptions extends NodeRequestAdapterOptions {}
|
|
21
20
|
//#endregion
|
|
@@ -57,14 +56,9 @@ export declare function connectToWeb(handler: ConnectMiddleware | ConnectMiddlew
|
|
|
57
56
|
*/
|
|
58
57
|
export declare function createIncomingMessage(request: Request): IncomingMessage;
|
|
59
58
|
/**
|
|
60
|
-
* Creates a
|
|
61
|
-
*
|
|
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.
|
|
62
61
|
* @beta
|
|
63
|
-
* @returns
|
|
64
|
-
* An object containing:
|
|
65
|
-
* - res: The custom ServerResponse object.
|
|
66
|
-
* - onReadable: A function that takes a callback. The callback is invoked when the response is readable,
|
|
67
|
-
* providing an object with the readable stream, headers, and status code.
|
|
68
62
|
*/
|
|
69
63
|
export declare function createServerResponse(incomingMessage: IncomingMessage): {
|
|
70
64
|
res: ServerResponse<IncomingMessage>;
|
|
@@ -72,18 +66,21 @@ export declare function createServerResponse(incomingMessage: IncomingMessage):
|
|
|
72
66
|
readable: Readable;
|
|
73
67
|
headers: OutgoingHttpHeaders;
|
|
74
68
|
statusCode: number;
|
|
69
|
+
statusMessage: string | undefined;
|
|
75
70
|
}) => void) => void;
|
|
76
71
|
};
|
|
77
72
|
//#endregion
|
|
78
73
|
//#region src/router.d.ts
|
|
79
74
|
type App = Express;
|
|
75
|
+
/** The options `apply` passes to every middleware and handler it adapts */
|
|
76
|
+
type ApplyOptions = NodeAdapterHandlerOptions & NodeAdapterMiddlewareOptions;
|
|
80
77
|
type EnhancedMiddlewareExpress = EnhancedMiddleware | EnhancedMiddleware<Universal.Context, Universal.Context, "express">;
|
|
81
78
|
declare class UniversalExpressRouter<T extends App> extends UniversalRouter implements UniversalRouterInterface {
|
|
82
79
|
#private;
|
|
83
|
-
constructor(app: T);
|
|
80
|
+
constructor(app: T, options?: ApplyOptions);
|
|
84
81
|
use(middleware: EnhancedMiddlewareExpress): this;
|
|
85
82
|
applyCatchAll(): this;
|
|
86
83
|
}
|
|
87
|
-
export declare function apply(app: Express, middlewares: EnhancedMiddlewareExpress[]): void;
|
|
84
|
+
export declare function apply(app: Express, middlewares: EnhancedMiddlewareExpress[], options?: ApplyOptions): void;
|
|
88
85
|
//#endregion
|
|
89
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";
|
|
1
|
+
import { createRequestAdapter, expressOrigin } from "./request.js";
|
|
2
2
|
import { UniversalRouter, apply as apply$1, bindUniversal, cancelReplacedBody, contextSymbol, getAdapterRuntime, getUniversal, universalSymbol } from "@universal-middleware/core";
|
|
3
|
-
import { requestSymbol, responseAdapter, sendResponse, setResponseHeaders } from "@universal-middleware/node";
|
|
4
|
-
import { EventEmitter } from "node:events";
|
|
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,104 +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
|
-
|
|
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);
|
|
111
129
|
});
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
original.apply(nodeResponse, args);
|
|
118
|
-
},
|
|
119
|
-
restore() {
|
|
120
|
-
nodeResponse[key] = original;
|
|
130
|
+
}
|
|
131
|
+
nodeResponse.write = (chunk, encoding, callback) => {
|
|
132
|
+
if (typeof encoding === "function") {
|
|
133
|
+
callback = encoding;
|
|
134
|
+
encoding = void 0;
|
|
121
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);
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
122
148
|
};
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
if (
|
|
129
|
-
callback
|
|
130
|
-
|
|
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;
|
|
131
157
|
}
|
|
158
|
+
capture(chunk, encoding);
|
|
159
|
+
writer.close().catch(() => {});
|
|
160
|
+
if (callback) nodeResponse.once("finish", callback);
|
|
132
161
|
return nodeResponse;
|
|
133
162
|
};
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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;
|
|
141
173
|
};
|
|
142
174
|
}
|
|
143
175
|
function wrapResponse(nodeResponse, next) {
|
|
144
176
|
if (nodeResponse[wrappedResponseSymbol]) return;
|
|
145
177
|
nodeResponse[wrappedResponseSymbol] = true;
|
|
146
|
-
const body = createTransformStream();
|
|
147
|
-
const writer = body.writable.getWriter();
|
|
148
|
-
const [reader1, reader2] = body.readable.tee();
|
|
149
178
|
const original = {
|
|
150
|
-
write:
|
|
151
|
-
end:
|
|
152
|
-
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)
|
|
153
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
|
+
});
|
|
154
195
|
async function triggerPendingMiddlewares() {
|
|
155
|
-
if (!nodeResponse[pendingMiddlewaresSymbol]) return;
|
|
156
196
|
const middlewares = nodeResponse[pendingMiddlewaresSymbol];
|
|
197
|
+
if (!middlewares) return;
|
|
157
198
|
delete nodeResponse[pendingMiddlewaresSymbol];
|
|
158
199
|
let response;
|
|
159
200
|
try {
|
|
160
|
-
response = responseAdapter(nodeResponse,
|
|
201
|
+
response = responseAdapter(nodeResponse, captured.readable);
|
|
161
202
|
for (const middleware of middlewares) {
|
|
162
203
|
const tmp = await middleware(response);
|
|
163
204
|
cancelReplacedBody(response, tmp);
|
|
164
205
|
if (tmp) response = tmp;
|
|
165
206
|
}
|
|
166
207
|
} catch (e) {
|
|
167
|
-
|
|
168
|
-
await
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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;
|
|
174
216
|
}
|
|
175
|
-
if (!response) return;
|
|
176
|
-
const readableToOriginal = response.body ?? reader2;
|
|
177
|
-
if (readableToOriginal !== reader2) reader2.cancel().catch(() => {});
|
|
178
217
|
setResponseHeaders(response, nodeResponse, true);
|
|
179
|
-
original.writeHead
|
|
218
|
+
nodeResponse.writeHead = original.writeHead;
|
|
180
219
|
nodeResponse.flushHeaders();
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
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;
|
|
194
251
|
}
|
|
195
252
|
}
|
|
196
253
|
//#endregion
|
|
@@ -208,12 +265,13 @@ function nextOr404(res, next) {
|
|
|
208
265
|
*/
|
|
209
266
|
function createHandler(handlerFactory, options = {}) {
|
|
210
267
|
const requestAdapter = createRequestAdapter(options);
|
|
268
|
+
const adapt = (req, res) => requestAdapter(req, res, expressOrigin(req));
|
|
211
269
|
return (...args) => {
|
|
212
270
|
const handler = handlerFactory(...args);
|
|
213
271
|
return bindUniversal(handler, async function universalHandlerExpress(req, res, next) {
|
|
214
272
|
try {
|
|
215
273
|
req[contextSymbol] ??= {};
|
|
216
|
-
const request = adaptLendingBody(
|
|
274
|
+
const request = adaptLendingBody(adapt, req, res);
|
|
217
275
|
const response = await this[universalSymbol](request, req[contextSymbol], getRuntime(req, res));
|
|
218
276
|
if (!response) {
|
|
219
277
|
handBodyBack(req);
|
|
@@ -224,8 +282,9 @@ function createHandler(handlerFactory, options = {}) {
|
|
|
224
282
|
handBodyBack(req);
|
|
225
283
|
next(error);
|
|
226
284
|
} else {
|
|
227
|
-
|
|
228
|
-
if (!
|
|
285
|
+
const badRequest = error instanceof BadRequestError;
|
|
286
|
+
if (!badRequest) console.error(error);
|
|
287
|
+
if (!res.headersSent) res.statusCode = badRequest ? error.status : 500;
|
|
229
288
|
if (!res.writableEnded) res.end();
|
|
230
289
|
}
|
|
231
290
|
}
|
|
@@ -237,12 +296,13 @@ function createHandler(handlerFactory, options = {}) {
|
|
|
237
296
|
*/
|
|
238
297
|
function createMiddleware(middlewareFactory, options = {}) {
|
|
239
298
|
const requestAdapter = createRequestAdapter(options);
|
|
299
|
+
const adapt = (req, res) => requestAdapter(req, res, expressOrigin(req));
|
|
240
300
|
return (...args) => {
|
|
241
301
|
const middleware = middlewareFactory(...args);
|
|
242
302
|
return bindUniversal(middleware, async function universalMiddlewareExpress(req, res, next) {
|
|
243
303
|
try {
|
|
244
304
|
req[contextSymbol] ??= {};
|
|
245
|
-
const request = adaptLendingBody(
|
|
305
|
+
const request = adaptLendingBody(adapt, req, res);
|
|
246
306
|
const response = await this[universalSymbol](request, getContext(req), getRuntime(req, res));
|
|
247
307
|
if (!(response instanceof Response)) handBodyBack(req);
|
|
248
308
|
if (!response) return nextOr404(res, next);
|
|
@@ -264,8 +324,9 @@ function createMiddleware(middlewareFactory, options = {}) {
|
|
|
264
324
|
handBodyBack(req);
|
|
265
325
|
next(error);
|
|
266
326
|
} else {
|
|
267
|
-
|
|
268
|
-
if (!
|
|
327
|
+
const badRequest = error instanceof BadRequestError;
|
|
328
|
+
if (!badRequest) console.error(error);
|
|
329
|
+
if (!res.headersSent) res.statusCode = badRequest ? error.status : 500;
|
|
269
330
|
if (!res.writableEnded) res.end();
|
|
270
331
|
}
|
|
271
332
|
}
|
|
@@ -290,22 +351,24 @@ function getRuntime(request, response) {
|
|
|
290
351
|
//#region src/router.ts
|
|
291
352
|
var UniversalExpressRouter = class extends UniversalRouter {
|
|
292
353
|
#app;
|
|
293
|
-
|
|
354
|
+
#options;
|
|
355
|
+
constructor(app, options = {}) {
|
|
294
356
|
super(false);
|
|
295
357
|
this.#app = app;
|
|
358
|
+
this.#options = options;
|
|
296
359
|
}
|
|
297
360
|
use(middleware) {
|
|
298
|
-
this.#app.use(createMiddleware(() => getUniversal(middleware))());
|
|
361
|
+
this.#app.use(createMiddleware(() => getUniversal(middleware), this.#options)());
|
|
299
362
|
return this;
|
|
300
363
|
}
|
|
301
364
|
applyCatchAll() {
|
|
302
|
-
const handler = createHandler(() => this[universalSymbol])();
|
|
365
|
+
const handler = createHandler(() => this[universalSymbol], this.#options)();
|
|
303
366
|
this.#app.all("del" in this.#app ? "/**" : "/{*catchAll}", handler);
|
|
304
367
|
return this;
|
|
305
368
|
}
|
|
306
369
|
};
|
|
307
|
-
function apply(app, middlewares) {
|
|
308
|
-
const router = new UniversalExpressRouter(app);
|
|
370
|
+
function apply(app, middlewares, options) {
|
|
371
|
+
const router = new UniversalExpressRouter(app, options);
|
|
309
372
|
apply$1(router, middlewares, true);
|
|
310
373
|
Promise.resolve().then(() => router.applyCatchAll());
|
|
311
374
|
}
|
|
@@ -333,7 +396,7 @@ function connectToWeb(handler) {
|
|
|
333
396
|
const { res, onReadable } = createServerResponse(req);
|
|
334
397
|
const stopForwardingAbort = realReq ? void 0 : forwardAbort(request.signal, req, res);
|
|
335
398
|
return new Promise(async (resolve, reject) => {
|
|
336
|
-
onReadable(({ readable, headers, statusCode }) => {
|
|
399
|
+
onReadable(({ readable, headers, statusCode, statusMessage }) => {
|
|
337
400
|
const hasBody = !statusCodesWithoutBody.includes(statusCode);
|
|
338
401
|
if (stopForwardingAbort) {
|
|
339
402
|
if (hasBody) readable.once("close", stopForwardingAbort);
|
|
@@ -341,6 +404,7 @@ function connectToWeb(handler) {
|
|
|
341
404
|
}
|
|
342
405
|
resolve(new Response(hasBody ? toWebStream(readable) : null, {
|
|
343
406
|
status: statusCode,
|
|
407
|
+
statusText: statusMessage,
|
|
344
408
|
headers: flattenHeaders(headers)
|
|
345
409
|
}));
|
|
346
410
|
});
|
|
@@ -393,14 +457,9 @@ function createIncomingMessage(request) {
|
|
|
393
457
|
return message;
|
|
394
458
|
}
|
|
395
459
|
/**
|
|
396
|
-
* Creates a
|
|
397
|
-
*
|
|
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.
|
|
398
462
|
* @beta
|
|
399
|
-
* @returns
|
|
400
|
-
* An object containing:
|
|
401
|
-
* - res: The custom ServerResponse object.
|
|
402
|
-
* - onReadable: A function that takes a callback. The callback is invoked when the response is readable,
|
|
403
|
-
* providing an object with the readable stream, headers, and status code.
|
|
404
463
|
*/
|
|
405
464
|
function createServerResponse(incomingMessage) {
|
|
406
465
|
const res = new ServerResponse(incomingMessage);
|
|
@@ -413,7 +472,8 @@ function createServerResponse(incomingMessage) {
|
|
|
413
472
|
cb({
|
|
414
473
|
readable: Readable.from(passThrough),
|
|
415
474
|
headers: res.getHeaders(),
|
|
416
|
-
statusCode: res.statusCode
|
|
475
|
+
statusCode: res.statusCode,
|
|
476
|
+
statusMessage: res.statusMessage
|
|
417
477
|
});
|
|
418
478
|
};
|
|
419
479
|
passThrough.once("readable", handleReadable);
|
|
@@ -432,14 +492,7 @@ function createServerResponse(incomingMessage) {
|
|
|
432
492
|
res.write = passThrough.write.bind(passThrough);
|
|
433
493
|
res.end = passThrough.end.bind(passThrough);
|
|
434
494
|
res.writeHead = function writeHead(statusCode, statusMessage, headers) {
|
|
435
|
-
res
|
|
436
|
-
if (typeof statusMessage === "object") {
|
|
437
|
-
headers = statusMessage;
|
|
438
|
-
statusMessage = void 0;
|
|
439
|
-
}
|
|
440
|
-
if (headers) {
|
|
441
|
-
for (const [key, value] of Object.entries(headers)) if (value !== void 0) res.setHeader(key, value);
|
|
442
|
-
}
|
|
495
|
+
setHead(res, statusCode, statusMessage, headers);
|
|
443
496
|
return res;
|
|
444
497
|
};
|
|
445
498
|
return {
|
|
@@ -448,10 +501,8 @@ function createServerResponse(incomingMessage) {
|
|
|
448
501
|
};
|
|
449
502
|
}
|
|
450
503
|
/**
|
|
451
|
-
* Bridges a
|
|
452
|
-
*
|
|
453
|
-
* `createRequestAdapter` derives the handler's `request.signal` from `res`'s "close" event,
|
|
454
|
-
* 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.
|
|
455
506
|
*/
|
|
456
507
|
function forwardAbort(signal, req, res) {
|
|
457
508
|
let active = true;
|
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": [
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
"node": ">=22"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@universal-middleware/core": "^0.6.
|
|
24
|
-
"@universal-middleware/node": "^0.2.
|
|
23
|
+
"@universal-middleware/core": "^0.6.2",
|
|
24
|
+
"@universal-middleware/node": "^0.2.8"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/express": "^5.0.6",
|