@universal-middleware/express 0.6.1 → 0.6.2

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,13 +1,10 @@
1
- import { createRequestAdapter } from "./request.js";
2
1
  import { Awaitable, EnhancedMiddleware, Get, RuntimeAdapter, RuntimeAdapterTarget, UniversalFn, UniversalHandler, UniversalMiddleware, UniversalRouter, UniversalRouterInterface } from "@universal-middleware/core";
3
- import { DecoratedRequest, NodeRequestAdapterOptions, sendResponse } from "@universal-middleware/node";
4
2
  import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
3
+ import { DecoratedRequest, NodeRequestAdapterOptions, sendResponse } from "@universal-middleware/node";
4
+ import { createRequestAdapter } from "./request.js";
5
5
  import { Readable } from "node:stream";
6
- //#region src/const.d.ts
7
6
  declare const pendingMiddlewaresSymbol: unique symbol;
8
7
  declare const wrappedResponseSymbol: unique symbol;
9
- //#endregion
10
- //#region src/types.d.ts
11
8
  interface DecoratedServerResponse extends ServerResponse {
12
9
  [pendingMiddlewaresSymbol]?: ((response: Response) => Awaitable<Response | undefined>)[];
13
10
  [wrappedResponseSymbol]?: boolean;
@@ -17,8 +14,6 @@ type NodeMiddleware<In extends Universal.Context, Out extends Universal.Context>
17
14
  type NodeHandler<In extends Universal.Context> = UniversalFn<UniversalHandler<In>, <R>(req: DecoratedRequest<In>, res: DecoratedServerResponse, next?: (err?: unknown) => void) => R>;
18
15
  interface NodeAdapterHandlerOptions extends NodeRequestAdapterOptions {}
19
16
  interface NodeAdapterMiddlewareOptions extends NodeRequestAdapterOptions {}
20
- //#endregion
21
- //#region src/common.d.ts
22
17
  /**
23
18
  * Creates a request handler to be passed to http.createServer() or used as a
24
19
  * middleware in Connect-style frameworks like Express.
@@ -30,8 +25,6 @@ export declare function createHandler<T extends unknown[], InContext extends Uni
30
25
  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>>;
31
26
  export declare function getContext<InContext extends Universal.Context = Universal.Context>(req: DecoratedRequest): InContext;
32
27
  export declare function getRuntime(request: DecoratedRequest, response: DecoratedServerResponse): RuntimeAdapter;
33
- //#endregion
34
- //#region src/utils.d.ts
35
28
  type ExpressRequestHandler = (req: DecoratedRequest, res: DecoratedServerResponse, next: (err?: unknown) => void) => unknown;
36
29
  /**
37
30
  * The parts of an Express 4 or 5 application the adapter uses.
@@ -57,7 +50,7 @@ export declare function connectToWeb(handler: ConnectMiddleware | ConnectMiddlew
57
50
  export declare function createIncomingMessage(request: Request): IncomingMessage;
58
51
  /**
59
52
  * Creates a `ServerResponse` whose output is captured. `onReadable`'s callback gets the output stream, the headers and
60
- * the status once the response starts.
53
+ * the status once the response starts. Its `onError` gets the error of a response destroyed before it started.
61
54
  * @beta
62
55
  */
63
56
  export declare function createServerResponse(incomingMessage: IncomingMessage): {
@@ -67,10 +60,8 @@ export declare function createServerResponse(incomingMessage: IncomingMessage):
67
60
  headers: OutgoingHttpHeaders;
68
61
  statusCode: number;
69
62
  statusMessage: string | undefined;
70
- }) => void) => void;
63
+ }) => void, onError?: (error: Error) => void) => void;
71
64
  };
72
- //#endregion
73
- //#region src/router.d.ts
74
65
  type App = Express;
75
66
  /** The options `apply` passes to every middleware and handler it adapts */
76
67
  type ApplyOptions = NodeAdapterHandlerOptions & NodeAdapterMiddlewareOptions;
@@ -82,5 +73,4 @@ declare class UniversalExpressRouter<T extends App> extends UniversalRouter impl
82
73
  applyCatchAll(): this;
83
74
  }
84
75
  export declare function apply(app: Express, middlewares: EnhancedMiddlewareExpress[], options?: ApplyOptions): void;
85
- //#endregion
86
76
  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,15 +1,15 @@
1
- import { createRequestAdapter, expressOrigin } from "./request.js";
2
1
  import { UniversalRouter, apply as apply$1, bindUniversal, cancelReplacedBody, contextSymbol, getAdapterRuntime, getUniversal, universalSymbol, withMutableHeaders } from "@universal-middleware/core";
3
2
  import { BadRequestError, requestSymbol, responseAdapter, sendResponse, setResponseHeaders } from "@universal-middleware/node";
3
+ import { createRequestAdapter, expressOrigin } from "./request.js";
4
4
  import { EventEmitter, once } from "node:events";
5
5
  import { ServerResponse } from "node:http";
6
6
  import { PassThrough, Readable } from "node:stream";
7
- //#region src/const.ts
7
+ // src/const.ts
8
8
  const pendingMiddlewaresSymbol = Symbol.for("unPendingMiddlewares");
9
9
  const wrappedResponseSymbol = Symbol.for("unWrappedResponse");
10
- //#endregion
11
- //#region src/body.ts
10
+ // src/body.ts
12
11
  const MAX_LENT_BYTES = 1048576;
12
+ let warned = false;
13
13
  const lentSymbol = Symbol("universal-middleware.lentBody");
14
14
  /**
15
15
  * Create the `Request` for `req`. Its body reads the Node request lazily and without ending it, so that
@@ -95,11 +95,14 @@ var LentBody = class {
95
95
  }
96
96
  delete req[requestSymbol];
97
97
  if (this.held.length > 0) req.unshift(Buffer.concat(this.held));
98
+ else if (this.heldBytes > MAX_LENT_BYTES && !warned) {
99
+ console.warn("A universal middleware read more than 1 MiB of the request body, so the next Express handler gets it empty or cut short. See https://github.com/magne4000/universal-middleware/issues/463");
100
+ warned = true;
101
+ }
98
102
  this.controller.error(/* @__PURE__ */ new Error("The request body must be read before the middleware returns."));
99
103
  }
100
104
  };
101
- //#endregion
102
- //#region src/head.ts
105
+ // src/head.ts
103
106
  /** Sets on `res` the status, status message and headers a `res.writeHead()` call carries, without sending them */
104
107
  function setHead(res, statusCode, statusMessage, headers) {
105
108
  res.statusCode = statusCode;
@@ -115,8 +118,7 @@ function setHead(res, statusCode, statusMessage, headers) {
115
118
  for (const [name, value] of Object.entries(headers)) if (value !== void 0) res.setHeader(name, value);
116
119
  }
117
120
  }
118
- //#endregion
119
- //#region src/response.ts
121
+ // src/response.ts
120
122
  /** Routes the app's writes to `writer`. As a socket would, `write()` returns false once `writer` is full, then "drain" follows. */
121
123
  function captureOutput(nodeResponse, writer) {
122
124
  let draining = false;
@@ -251,8 +253,7 @@ function wrapResponse(nodeResponse, next) {
251
253
  nodeResponse.end = original.end;
252
254
  }
253
255
  }
254
- //#endregion
255
- //#region src/common.ts
256
+ // src/common.ts
256
257
  function nextOr404(res, next) {
257
258
  if (next) next();
258
259
  else {
@@ -348,8 +349,7 @@ function getRuntime(request, response) {
348
349
  })
349
350
  });
350
351
  }
351
- //#endregion
352
- //#region src/router.ts
352
+ // src/router.ts
353
353
  var UniversalExpressRouter = class extends UniversalRouter {
354
354
  #app;
355
355
  #options;
@@ -373,8 +373,7 @@ function apply(app, middlewares, options) {
373
373
  apply$1(router, middlewares, true);
374
374
  Promise.resolve().then(() => router.applyCatchAll());
375
375
  }
376
- //#endregion
377
- //#region src/utils.ts
376
+ // src/utils.ts
378
377
  const statusCodesWithoutBody = [
379
378
  100,
380
379
  101,
@@ -390,13 +389,16 @@ const statusCodesWithoutBody = [
390
389
  */
391
390
  function connectToWeb(handler) {
392
391
  return async (request, context, runtime) => {
393
- const req = (runtime && "req" in runtime && runtime.req || request.runtime?.node?.req) ?? createIncomingMessage(request);
392
+ const realReq = runtime && "req" in runtime && runtime.req || request.runtime?.node?.req;
393
+ const req = realReq ?? createIncomingMessage(request);
394
394
  const callerContext = context ?? request.context;
395
395
  if (callerContext) req[contextSymbol] = callerContext;
396
396
  const { res, onReadable } = createServerResponse(req);
397
- const stopForwardingAbort = forwardAbort(request.signal, req, res);
397
+ const stopForwardingAbort = forwardAbort(request.signal, req, res, !realReq);
398
398
  return new Promise(async (resolve, reject) => {
399
+ let started = false;
399
400
  onReadable(({ readable, headers, statusCode, statusMessage }) => {
401
+ started = true;
400
402
  const hasBody = !statusCodesWithoutBody.includes(statusCode);
401
403
  if (hasBody) readable.once("close", stopForwardingAbort);
402
404
  else stopForwardingAbort();
@@ -405,11 +407,17 @@ function connectToWeb(handler) {
405
407
  statusText: statusMessage,
406
408
  headers: flattenHeaders(headers)
407
409
  }));
410
+ }, (error) => {
411
+ stopForwardingAbort();
412
+ reject(error);
408
413
  });
409
414
  const next = (error) => {
410
415
  stopForwardingAbort();
411
- if (error) reject(error instanceof Error ? error : new Error(String(error)));
412
- else resolve(void 0);
416
+ if (error) {
417
+ const failure = error instanceof Error ? error : new Error(String(error));
418
+ if (started) res.destroy(failure);
419
+ else reject(failure);
420
+ } else resolve(void 0);
413
421
  };
414
422
  try {
415
423
  if (await handler(req, res, next) === false) {
@@ -452,18 +460,20 @@ function createIncomingMessage(request) {
452
460
  message.once("end", () => {
453
461
  message.complete = true;
454
462
  });
463
+ const destroy = message._destroy;
464
+ message._destroy = (error, callback) => destroy.call(message, error, (result) => callback(message.listenerCount("error") > 0 ? result : null));
455
465
  return message;
456
466
  }
457
467
  /**
458
468
  * Creates a `ServerResponse` whose output is captured. `onReadable`'s callback gets the output stream, the headers and
459
- * the status once the response starts.
469
+ * the status once the response starts. Its `onError` gets the error of a response destroyed before it started.
460
470
  * @beta
461
471
  */
462
472
  function createServerResponse(incomingMessage) {
463
473
  const res = new ServerResponse(incomingMessage);
464
474
  const passThrough = new PassThrough();
465
475
  let handled = false;
466
- const onReadable = (cb) => {
476
+ const onReadable = (cb, onError) => {
467
477
  const handleReadable = () => {
468
478
  if (handled) return;
469
479
  handled = true;
@@ -476,6 +486,11 @@ function createServerResponse(incomingMessage) {
476
486
  };
477
487
  passThrough.once("readable", handleReadable);
478
488
  passThrough.once("end", handleReadable);
489
+ passThrough.once("close", () => {
490
+ if (handled) return;
491
+ handled = true;
492
+ onError?.(passThrough.errored ?? /* @__PURE__ */ new Error("The response was destroyed before it started"));
493
+ });
479
494
  };
480
495
  passThrough.once("finish", () => {
481
496
  res.emit("finish");
@@ -484,13 +499,29 @@ function createServerResponse(incomingMessage) {
484
499
  res.destroy();
485
500
  res.emit("close");
486
501
  });
502
+ const destroy = res.destroy;
503
+ res.destroy = (error) => {
504
+ passThrough.destroy(error);
505
+ return destroy.call(res, error);
506
+ };
507
+ passThrough.on("error", () => {});
487
508
  passThrough.on("drain", () => {
488
509
  res.emit("drain");
489
510
  });
490
- res.write = passThrough.write.bind(passThrough);
491
- res.end = passThrough.end.bind(passThrough);
511
+ let headWritten = false;
512
+ res.write = function write(...args) {
513
+ if (!headWritten) res.writeHead(res.statusCode);
514
+ return passThrough.write(...args);
515
+ };
516
+ res.end = function end(...args) {
517
+ if (!headWritten) res.writeHead(res.statusCode);
518
+ passThrough.end(...args);
519
+ return res;
520
+ };
521
+ Object.defineProperty(res, "headersSent", { get: () => headWritten });
492
522
  Object.defineProperty(res, "writableEnded", { get: () => passThrough.writableEnded });
493
523
  res.writeHead = function writeHead(statusCode, statusMessage, headers) {
524
+ headWritten = true;
494
525
  setHead(res, statusCode, statusMessage, headers);
495
526
  return res;
496
527
  };
@@ -502,14 +533,16 @@ function createServerResponse(incomingMessage) {
502
533
  /**
503
534
  * Bridges a Web `AbortSignal` to `connectToWeb`'s `req`/`res`, and returns a function that stops it.
504
535
  * The request adapter aborts `request.signal` on `res`'s "close", which a socketless `ServerResponse` never emits.
536
+ * A synthetic `req` with an unfinished body fails with ECONNRESET, as Node's server fails its own requests.
505
537
  */
506
- function forwardAbort(signal, req, res) {
538
+ function forwardAbort(signal, req, res, synthetic) {
507
539
  let active = true;
508
540
  const abort = () => {
509
541
  if (!active) return;
510
542
  active = false;
511
543
  res.emit("close");
512
- req.destroy();
544
+ const cut = synthetic && !req.complete;
545
+ req.destroy(cut ? Object.assign(/* @__PURE__ */ new Error("aborted"), { code: "ECONNRESET" }) : void 0);
513
546
  };
514
547
  if (signal.aborted) queueMicrotask(abort);
515
548
  else signal.addEventListener("abort", abort, { once: true });
@@ -545,5 +578,4 @@ function flattenHeaders(headers) {
545
578
  }
546
579
  return flatHeaders;
547
580
  }
548
- //#endregion
549
581
  export { apply, connectToWeb, createHandler, createIncomingMessage, createMiddleware, createRequestAdapter, createServerResponse, getContext, getRuntime, sendResponse };
package/dist/request.d.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  import { DecoratedRequest, DecoratedRequest as DecoratedRequest$1, NodeRequestAdapterOptions, PossiblyEncryptedSocket, RequestOrigin, createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
2
- //#region src/request.d.ts
3
2
  /**
4
3
  * The host Express gives `req` under its `trust proxy` setting: the first `X-Forwarded-Host`, when the setting
5
4
  * trusts the peer, as Express 5's `req.host` reads it. Express 4 has no such getter: its `req.host` drops the port.
6
5
  * The protocol needs nothing: `req.protocol` follows `trust proxy` in both, and the request adapter reads it.
7
6
  */
8
7
  export declare function expressOrigin(req: DecoratedRequest$1): RequestOrigin | undefined;
9
- //#endregion
10
8
  export { type DecoratedRequest, type NodeRequestAdapterOptions, type PossiblyEncryptedSocket, createRequestAdapter, env, requestSymbol };
package/dist/request.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
2
- //#region src/request.ts
2
+ // src/request.ts
3
3
  /**
4
4
  * The host Express gives `req` under its `trust proxy` setting: the first `X-Forwarded-Host`, when the setting
5
5
  * trusts the peer, as Express 5's `req.host` reads it. Express 4 has no such getter: its `req.host` drops the port.
@@ -17,5 +17,4 @@ function trustsPeer(req) {
17
17
  const trust = app.get("trust proxy fn");
18
18
  return typeof trust === "function" && trust(req.socket?.remoteAddress, 0) === true;
19
19
  }
20
- //#endregion
21
20
  export { createRequestAdapter, env, expressOrigin, requestSymbol };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@universal-middleware/express",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "type": "module",
5
5
  "description": "Express adapter for universal middlewares",
6
6
  "files": [
@@ -30,11 +30,11 @@
30
30
  "express": "^5.3.0",
31
31
  "express4": "npm:express@^4.22.3",
32
32
  "helmet": "^8.3.0",
33
- "tsdown": "^0.23.1",
33
+ "tsdown": "^0.23.7",
34
34
  "tsx": "^4.23.15",
35
- "typescript": "^7.0.2",
36
- "vite": "^8.3.4",
37
- "vitest": "^5.0.5",
35
+ "typescript": "7.1.0-beta",
36
+ "vite": "^8.3.8",
37
+ "vitest": "^5.1.1",
38
38
  "@universal-middleware/tests": "0.0.2",
39
39
  "@universal-middleware/tsdown-config": "0.0.0"
40
40
  },