http2-express 1.1.0 → 1.1.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/README.md CHANGED
@@ -1,12 +1,15 @@
1
1
  # http2-express
2
2
  This package adds HTTP/2 support to express.js applications.
3
3
 
4
- **Version 1.1.0** adds support for **EXPRESS 5**. [grainrigi](https://github.com/grainrigi) was able to make the changes necessary to support **EXPRESS 5**.
5
- This version is also backward compatible with Express 4.
4
+ **NOTICE**: Replacement for old `http2-express-bridge`: you only change the package name in the import.
6
5
 
7
- **NOTICE**: This package is fully compatible with the old [http2-express-bridge](https://www.npmjs.com/package/http2-express-bridge). You should be able to replace the old package [http2-express-bridge](https://www.npmjs.com/package/http2-express-bridge) with this new one ("**http2-express**") without changing anything in your code, except the package name in the import (see usage below).
6
+ **http2-express** is a small package that lets an Express app run on Node's built-in `http2` server. Express is built on the HTTP/1.1 request and response classes and doesn't work with `http2` directly. This package makes the two compatible: you pass it the `express` module, get back a normal Express app, and hand that app to `http2.createSecureServer()` (or `http2.createServer()` for plain h2c).
8
7
 
9
- **Version 1.0.1** fixes an issue with h2c (running HTTP/2 without TLS) as reported by rickardkarlsson. You should now be able to create a non https server (http2.createServer.....) without any issues.
8
+ ```javascript
9
+ const app = http2Express(express);
10
+ http2.createSecureServer(options, app).listen(443);
11
+ ```
12
+ **Limitation**: server push is not supported, because browsers have dropped it (Chrome removed it in version 106).
10
13
 
11
14
  ## Installation
12
15
  ```bash
@@ -15,8 +18,37 @@ npm i http2-express
15
18
 
16
19
  **Notice**: It is recommended to use Node.js **version 19** or higher.
17
20
 
18
-
19
21
  ## Usage
22
+ - [CommonJS (CJS) usage](#common-js-cjs-usage).
23
+ - [ES Modules (ESM) usage](#es-modules-esm-usage).
24
+ - [TypeScript usage](#typescript-usage).
25
+
26
+ ## Version History
27
+ **Version 1.1.2** includes **TypeScript** type definitions (no separate `@types` package needed for http2-express). The package works with both JavaScript and TypeScript, and with Express 4 and Express 5.
28
+ <br>
29
+ <br>
30
+
31
+ **Version 1.1.1** Fixes the following bugs:
32
+ 1. Fixed the crash issue when a stream is already destroyed.
33
+ 2. Removed the side-effecting hostname getter that mutated this.headers['host']. The host header is now initialized once, upfront, in middleware.
34
+ 3. Wrapped Object.setPrototypeOf calls in try/catch so errors go to next(err) instead of hanging the request.
35
+ 4. Express5 detection now uses parseInt(express.version, 10) >= 5 with the old heuristic as fallback. No longer breaks if lazyrouter is monkey-patched.
36
+ 5. Removed response.push = () => {} which mutated the shared Express prototype; push no-ops are now set only on app._response and app.http2Response.
37
+ 6. Added headers['host'] initialization in the Express 5 router middleware.
38
+ 7. If Express is not installed in your project, or your installed Express version is below version 4.0.0, you'll get a warning.
39
+ <br>
40
+ <br>
41
+
42
+ **Version 1.1.0** adds support for **EXPRESS 5**. [grainrigi](https://github.com/grainrigi) was able to make the changes necessary to support **EXPRESS 5**.
43
+ This version is also backward compatible with Express 4.
44
+ <br>
45
+ <br>
46
+
47
+ **Version 1.0.1** fixes an issue with h2c (running HTTP/2 without TLS) as reported by rickardkarlsson. You should now be able to create a non https server (http2.createServer.....) without any issues.
48
+ <br>
49
+ <br>
50
+
51
+ ## Common JS (CJS) usage
20
52
  ```javascript
21
53
  const express = require('express');
22
54
  const http2 = require('http2');
@@ -47,7 +79,114 @@ The code above creates an HTTP/2 server. An HTTP/2 server performs better than t
47
79
 
48
80
  **Notice**: If option property "allowHTTP1" is set to true, then your server will be backward compatible with HTTP/1.1. If false, then only the new HTTP/2 is supported. Browsers and HTTP Clients that don't support HTTP/2 will error out if "allowHTTP1" is false.
49
81
 
50
- ESModule "import" syntax is also supported.
51
82
 
52
- **NOTICE**: While the old [http2-express-bridge](https://www.npmjs.com/package/http2-express-bridge) provided support for Server Push, this package does not support Server Push because all major browsers and HTTP/2 Clients no longer support it. For example, Server Push has been disable in Chrome since version 106. The reason behind it is that Server Push did not provide significant performance gains, and in many cases, the performance actually decreased.
83
+ ## ES Modules (ESM) usage
84
+ The package works in both CommonJS (`require`) and ES module (`import`) projects, with Express 4 and Express 5. In an ESM project (`"type": "module"` in your `package.json`, or `.mjs` files), use a default import:
85
+ ```javascript
86
+ import express from 'express';
87
+ import http2 from 'http2';
88
+ import fs from 'fs';
89
+ import http2Express from 'http2-express';
90
+
91
+ const app = http2Express(express);
92
+
93
+ app.get('/', (req, res) => {
94
+ res.send('Hello World!');
95
+ });
96
+
97
+ // ES modules have no __dirname; resolve files relative to this module with import.meta.url.
98
+ const options = {
99
+ key: fs.readFileSync(new URL('./certs/server-key.pem', import.meta.url)),
100
+ cert: fs.readFileSync(new URL('./certs/server-cert.pem', import.meta.url)),
101
+ passphrase: 'your certificate passphrase',
102
+ allowHTTP1: false
103
+ };
104
+
105
+ const server = http2.createSecureServer(options, app);
106
+
107
+ server.listen(44320, () => {
108
+ console.info('Listening on port 44320...');
109
+ });
110
+ ```
111
+
112
+ ## TypeScript usage
113
+ Type definitions ship with the package. Install the Express and Node.js types alongside it (use the `@types/express` major version that matches your Express version):
114
+ ```bash
115
+ npm i -D typescript @types/node @types/express
116
+ ```
117
+
118
+ ```typescript
119
+ import express from 'express';
120
+ import http2 from 'http2';
121
+ import fs from 'fs';
122
+ import http2Express from 'http2-express';
123
+
124
+ const app = http2Express(express);
125
+
126
+ app.get('/', (req, res) => {
127
+ res.send('Hello World!');
128
+ });
129
+
130
+ const options: http2.SecureServerOptions = {
131
+ key: fs.readFileSync('path to your certificate key'),
132
+ cert: fs.readFileSync('path to your certificate'),
133
+ passphrase: 'your certificate passphrase',
134
+ allowHTTP1: false
135
+ };
136
+
137
+ const server = http2.createSecureServer(options, app);
138
+
139
+ server.listen(44320, () => {
140
+ console.info('Listening on port 44320...');
141
+ });
142
+ ```
143
+ `http2Express(express)` returns your regular, fully typed Express application (typed by whichever `@types/express` version you have installed) that can also be passed straight to `http2.createServer()` / `http2.createSecureServer()`. `esModuleInterop` must be enabled for the default `import` form above (it is on by default in current TypeScript); otherwise use `import http2Express = require('http2-express');`.
144
+ <br>
145
+ <br>
146
+
147
+ ## JSDoc type checking in JavaScript (no build step)
148
+ In plain JavaScript ESM or CJS, add `// @ts-check` at the top of a file (or `"checkJs": true` in a `jsconfig.json`) and your editor (VS Code, WebStorm, ...) or `tsc --noEmit` will check your code against the bundled type definitions. Nothing is compiled; the JavaScript runs as-is. This works the same in CommonJS (`require`) and ES module (`import`) files.
149
+ ```javascript
150
+ // @ts-check
151
+ const express = require('express');
152
+ const http2 = require('http2');
153
+ const http2Express = require('http2-express');
154
+
155
+ // The type is inferred automatically: your Express app, plus the HTTP/2 request listener signature.
156
+ const app = http2Express(express);
157
+
158
+ app.get('/', (req, res) => {
159
+ res.send('Hello World!'); // req and res are fully typed; a typo like res.sendd() is flagged
160
+ });
161
+
162
+ const server = http2.createServer(app);
163
+ ```
164
+ You normally don't need to write any type annotations, because the types are inferred as shown above.
165
+
166
+ Optional: if you pass the app to a function in another place, TypeScript can't infer the parameter's type, so describe it with a JSDoc `@param`. This continues the example above and uses the same `app`:
167
+ ```javascript
168
+ /**
169
+ * The import(...) below is only a JSDoc type reference (it is not a runtime import),
170
+ * so it also works in CommonJS files that use require().
171
+ * @param {import('http2-express').Http2ExpressApplication<import('express').Express>} application
172
+ */
173
+ function registerHealthRoute(application) {
174
+ application.get('/health', (req, res) => {
175
+ res.send('ok'); // req and res are typed here too
176
+ });
177
+ }
178
+
179
+ registerHealthRoute(app); // `app` from the example above
180
+ ```
181
+ The same `@types/express` / `@types/node` dev dependencies listed above are needed for editor/`tsc` checking. If you use TypeScript 7 and your project contains the npm `punycode` package, add `"maxNodeModuleJsDepth": 0` to your `jsconfig.json` to stop it from checking JavaScript inside `node_modules`.
182
+
183
+ The package's own source is annotated with JSDoc too, and `npm run typecheck` checks it, together with the type tests in `test/`.
184
+
185
+ ## Examples
186
+ Complete working examples are in these [github](https://github.com/markjovis/http2-express) folders (each is a standalone project; run it with `npm start`, or check its types with `npm run typecheck`):
53
187
 
188
+ | Folder | Language | Module system |
189
+ | --- | --- | --- |
190
+ | `example-express4-cjs`, `example-express5-cjs` | JavaScript (with `// @ts-check` and a `jsconfig.json`) | CommonJS (`require`) |
191
+ | `example-express4-esm`, `example-express5-esm` | JavaScript (with `// @ts-check` and a `jsconfig.json`) | ES modules (`import`) |
192
+ | `example-express4-ts`, `example-express5-ts` | TypeScript | compiled/run as CommonJS |
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "http2-express",
3
+ "type": "commonjs",
4
+ "sideEffects": false,
3
5
  "description": "HTTP/2 support for Express",
4
- "version": "1.1.0",
6
+ "version": "1.1.2",
5
7
  "author": "Mark Jovis",
6
8
  "contributors": [
7
- "Mark Jovis <mark.jovis@hotmail.com>"
9
+ "grainrigi"
8
10
  ],
9
11
  "license": "MIT",
10
12
  "keywords": [
@@ -17,21 +19,25 @@
17
19
  "api",
18
20
  "server"
19
21
  ],
20
- "main": "dist/index.js",
21
- "module": "dist/index.js",
22
+ "main": "src/index.js",
23
+ "types": "src/index.d.ts",
24
+ "files": [
25
+ "src/"
26
+ ],
22
27
  "scripts": {
23
- "build": "babel src -d dist",
24
- "prepublishOnly": "npm run build",
25
- "createTypeFiles": "npx -p typescript tsc src/*.js --declaration --allowJs --emitDeclarationOnly --outDir types",
26
- "test": "echo \"Error: no test specified\" && exit 1"
28
+ "typecheck": "tsc -p tsconfig.json"
29
+ },
30
+ "peerDependencies": {
31
+ "express": ">=4.0.0"
27
32
  },
28
33
  "devDependencies": {
29
- "@babel/cli": "^7.23.9",
30
- "@babel/eslint-parser": "^7.23.10",
31
- "@babel/preset-env": "^7.23.9",
32
- "eslint": "^8.57.0",
33
- "eslint-config-airbnb-base": "^15.0.0",
34
- "eslint-plugin-import": "^2.29.1"
34
+ "@eslint/js": "^10.0.1",
35
+ "@types/express": "^5.0.6",
36
+ "@types/node": "^20.19.43",
37
+ "eslint": "^10.5.0",
38
+ "express": "^5.3.0",
39
+ "globals": "^17.6.0",
40
+ "typescript": "^7.0.2"
35
41
  },
36
42
  "engines": {
37
43
  "node": ">= 20.0.0"
package/src/core.js CHANGED
@@ -1,12 +1,19 @@
1
- /* eslint-disable func-names */
2
- /* eslint-disable no-underscore-dangle */
1
+ // @ts-nocheck
2
+ 'use strict';
3
+
3
4
  const EventEmitter = require('events');
4
5
 
5
- const createHttp2Request = require('./http2Request');
6
- const createHttp2Response = require('./http2Response');
7
- const initHttp2Express = require('./initHttp2Express');
6
+ const createHttp2Request = require('./http2-request');
7
+ const createHttp2Response = require('./http2-response');
8
+ const initHttp2Express = require('./init-http2-express');
8
9
  const { setPoweredBy, isHttp2Request } = require('./util');
9
10
 
11
+ /**
12
+ * Creates an Express application (v4 or v5) with HTTP/2 support.
13
+ * The public, strongly typed signature lives in `index.d.ts`.
14
+ * @param {Record<string, any>} express The `express` module.
15
+ * @returns {any} The HTTP/2-enabled Express application.
16
+ */
10
17
  const createHttp2Express = (express) => {
11
18
  const {
12
19
  application,
@@ -16,18 +23,28 @@ const createHttp2Express = (express) => {
16
23
  query
17
24
  } = express;
18
25
 
19
- const isExpress5 = !application.lazyrouter;
26
+ // Detect Express 5 via the version string (positive-space check) with a
27
+ // fallback to the absence-of-lazyrouter heuristic for edge cases where
28
+ // express.version is unavailable.
29
+ const isExpress5 = express.version
30
+ ? parseInt(express.version, 10) >= 5
31
+ : typeof application.lazyrouter !== 'function';
20
32
 
21
33
  if (isExpress5) {
22
34
  const originalInit = application.init;
23
35
  application.init = function init() {
24
36
  originalInit.call(this);
25
- // at this point we can use the router
26
- this.router.use((req, res, next) => {
37
+ this.router.use((/** @type {any} */ req, /** @type {any} */ res, /** @type {() => void} */ next) => {
27
38
  setPoweredBy(this, res);
39
+ // HTTP/2 carries the host in :authority. Populate headers['host'] once,
40
+ // upfront, so Express's req.hostname getter and any header-inspection
41
+ // middleware see a consistent value from the start.
42
+ if (isHttp2Request(req) && !req.headers['host'] && req.authority) {
43
+ req.headers['host'] = req.authority;
44
+ }
28
45
  next();
29
46
  });
30
- }
47
+ };
31
48
  } else {
32
49
  application.lazyrouter = function lazyrouter() {
33
50
  if (!this._router) {
@@ -41,13 +58,30 @@ const createHttp2Express = (express) => {
41
58
  };
42
59
  }
43
60
 
61
+ // For Express 5: intercept the app.request/app.response reads that happen
62
+ // synchronously at the top of app.handle, so H2 connections get the HTTP/2
63
+ // prototype set immediately — before any stream machinery can run _read().
64
+ // This must happen at the getter level, not in a middleware, because by the
65
+ // time middleware runs the wrong prototype is already set on the request.
66
+ //
67
+ // Safe under Node.js's single-threaded event loop: the overrides are set and
68
+ // consumed within the same synchronous call stack (no await between them and
69
+ // Express 5's prototype reads inside app.handle).
70
+ /** @type {any} */
44
71
  let oneshotRequestOverride = null;
72
+ /** @type {any} */
45
73
  let oneshotResponseOverride = null;
46
74
 
75
+ /**
76
+ * The request listener returned to the caller. Typed as `any` because it is
77
+ * built dynamically by copying Express's application members onto it.
78
+ * @param {any} req
79
+ * @param {any} res
80
+ * @param {(err?: unknown) => void} [next]
81
+ * @type {any}
82
+ */
47
83
  const app = function (req, res, next) {
48
84
  if (isExpress5 && isHttp2Request(req)) {
49
- // In Express 5, setting the prototype of req/res is done synchronously in the app.handle function,
50
- // so this is the right place to change the value of app.request/app.response.
51
85
  oneshotRequestOverride = app.http2Request;
52
86
  oneshotResponseOverride = app.http2Response;
53
87
  }
@@ -86,8 +120,6 @@ const createHttp2Express = (express) => {
86
120
  }
87
121
  });
88
122
 
89
- response.push = () => {};
90
-
91
123
  app._request = Object.create(request, {
92
124
  app: {
93
125
  configurable: true,
@@ -106,6 +138,9 @@ const createHttp2Express = (express) => {
106
138
  }
107
139
  });
108
140
 
141
+ // No-op push on the per-app HTTP/1 response object only.
142
+ app._response.push = () => { };
143
+
109
144
  const http2Request = createHttp2Request(request);
110
145
  const http2Response = createHttp2Response(response);
111
146
 
@@ -127,38 +162,35 @@ const createHttp2Express = (express) => {
127
162
  }
128
163
  });
129
164
 
130
- // Expose the prototype that will get set on requests.
165
+ // No-op push on the per-app HTTP/2 response object only.
166
+ app.http2Response.push = () => { };
167
+
131
168
  Object.defineProperty(app, 'request', {
132
169
  configurable: true,
133
170
  enumerable: true,
134
171
  get() {
135
172
  if (oneshotRequestOverride) {
136
- const req = oneshotRequestOverride;
173
+ const val = oneshotRequestOverride;
137
174
  oneshotRequestOverride = null;
138
- return req;
175
+ return val;
139
176
  }
140
177
  return app._request;
141
178
  },
142
- set: (val) => {
143
- app._request = val;
144
- }
179
+ set(val) { app._request = val; }
145
180
  });
146
181
 
147
- // Expose the prototype that will get set on responses.
148
182
  Object.defineProperty(app, 'response', {
149
183
  configurable: true,
150
184
  enumerable: true,
151
185
  get() {
152
186
  if (oneshotResponseOverride) {
153
- const res = oneshotResponseOverride;
187
+ const val = oneshotResponseOverride;
154
188
  oneshotResponseOverride = null;
155
- return res;
189
+ return val;
156
190
  }
157
191
  return app._response;
158
192
  },
159
- set: (val) => {
160
- app._response = val;
161
- }
193
+ set(val) { app._response = val; }
162
194
  });
163
195
 
164
196
  app.init();
@@ -1,7 +1,14 @@
1
- /* eslint-disable dot-notation */
1
+ 'use strict';
2
+
2
3
  const { Http2ServerRequest } = require('http2');
3
4
 
5
+ /**
6
+ * Builds an HTTP/2 flavoured copy of Express's `request` prototype.
7
+ * @param {object} request Express's `request` prototype object.
8
+ * @returns {import('http2').Http2ServerRequest} The HTTP/2 request prototype.
9
+ */
4
10
  const createHttp2Request = (request) => {
11
+ /** @type {any} */
5
12
  const http2Request = Object.create(Http2ServerRequest.prototype);
6
13
 
7
14
  // Copying properties and descriptors from request to http2Request.
@@ -20,19 +27,10 @@ const createHttp2Request = (request) => {
20
27
  }
21
28
  });
22
29
 
23
- const requestHostName = Object.getOwnPropertyDescriptor(http2Request, 'hostname')?.get;
24
-
25
- // Redefine hostname property with custom getter.
26
- if (requestHostName) {
27
- Object.defineProperty(http2Request, 'hostname', {
28
- get() {
29
- if (!this.headers['host'] && this.authority) {
30
- this.headers['host'] = this.authority;
31
- }
32
- return requestHostName.call(this);
33
- }
34
- });
35
- }
30
+ // The hostname getter from Express reads this.headers['host'].
31
+ // HTTP/2 requests carry the host via the :authority pseudo-header instead,
32
+ // so initHttp2Express populates headers['host'] from req.authority before
33
+ // any route handlers run. No getter override needed here.
36
34
 
37
35
  return http2Request;
38
36
  };
@@ -1,6 +1,14 @@
1
+ 'use strict';
2
+
1
3
  const { Http2ServerResponse } = require('http2');
2
4
 
5
+ /**
6
+ * Builds an HTTP/2 flavoured copy of Express's `response` prototype.
7
+ * @param {object} response Express's `response` prototype object.
8
+ * @returns {import('http2').Http2ServerResponse} The HTTP/2 response prototype.
9
+ */
3
10
  const createHttp2Response = (response) => {
11
+ /** @type {any} */
4
12
  const http2Response = Object.create(Http2ServerResponse.prototype);
5
13
 
6
14
  // Copying properties and descriptors from response to http2Response.
package/src/index.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { Http2ServerRequest, Http2ServerResponse } from 'http2';
2
+
3
+ /**
4
+ * Request listener signature used by `http2.createServer()` and
5
+ * `http2.createSecureServer()`.
6
+ */
7
+ type Http2RequestListener = (req: Http2ServerRequest, res: Http2ServerResponse) => void;
8
+
9
+ /**
10
+ * An Express application (as created by `express()`) that can also be passed
11
+ * directly to `http2.createServer()` / `http2.createSecureServer()` as the
12
+ * request listener. All the usual Express members (`get`, `use`, `listen`,
13
+ * `set`, ...) remain available.
14
+ */
15
+ type Http2ExpressApplication<App> = App & Http2RequestListener;
16
+
17
+ /**
18
+ * Creates an Express application with HTTP/2 support.
19
+ *
20
+ * Works with both Express 4 and Express 5. The returned application type comes
21
+ * from the `express` module you pass in, so it follows whichever
22
+ * `@types/express` version your project uses.
23
+ *
24
+ * @param express The `express` module itself (not the result of calling it).
25
+ * @returns An Express application usable as an `http2` server request listener.
26
+ *
27
+ * @example
28
+ * import express from 'express';
29
+ * import http2 from 'http2';
30
+ * import http2Express from 'http2-express';
31
+ *
32
+ * const app = http2Express(express);
33
+ * const server = http2.createSecureServer({ key, cert }, app);
34
+ */
35
+ declare function http2Express<App>(express: () => App): Http2ExpressApplication<App>;
36
+
37
+ declare namespace http2Express {
38
+ export { http2Express as default, Http2ExpressApplication, Http2RequestListener };
39
+ }
40
+
41
+ export = http2Express;
package/src/index.js CHANGED
@@ -1,4 +1,9 @@
1
+ 'use strict';
2
+
1
3
  const createHttp2Express = require('./core');
2
4
 
3
5
  module.exports = createHttp2Express;
4
- exports.default = createHttp2Express;
6
+ // Fix: attach .default to module.exports (not to the detached `exports` binding).
7
+ // After `module.exports = X`, the `exports` variable no longer refers to module.exports,
8
+ // so `exports.default = X` would write to an orphaned object with no effect.
9
+ module.exports.default = createHttp2Express;
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+
3
+ const { isHttp2Request, setPoweredBy } = require('./util');
4
+
5
+ /**
6
+ * Creates the Express middleware that swaps the request/response prototypes to
7
+ * the HTTP/2 or HTTP/1 variants.
8
+ * @param {any} app The HTTP/2-enabled Express application.
9
+ * @returns {(req: any, res: any, next: (err?: unknown) => void) => void}
10
+ */
11
+ const initHttp2Express = (app) => (req, res, next) => {
12
+ setPoweredBy(app, res);
13
+ req.res = res;
14
+ res.req = req;
15
+ req.next = next;
16
+
17
+ try {
18
+ if (isHttp2Request(req)) {
19
+ // HTTP/2 uses :authority instead of the Host header. Populate headers['host']
20
+ // once, upfront, so that Express's req.hostname getter and any middleware
21
+ // that reads req.headers directly see a consistent value from the start.
22
+ if (!req.headers['host'] && req.authority) {
23
+ req.headers['host'] = req.authority;
24
+ }
25
+ Object.setPrototypeOf(req, app.http2Request);
26
+ Object.setPrototypeOf(res, app.http2Response);
27
+ } else {
28
+ Object.setPrototypeOf(req, app.request);
29
+ Object.setPrototypeOf(res, app.response);
30
+ }
31
+ } catch (err) {
32
+ return next(err);
33
+ }
34
+
35
+ res.locals = res.locals || Object.create(null);
36
+ next();
37
+ };
38
+
39
+ module.exports = initHttp2Express;
package/src/util.js CHANGED
@@ -1,10 +1,34 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Minimal shape of an incoming request that is needed to detect HTTP/2.
5
+ * Satisfied by `http.IncomingMessage` and `http2.Http2ServerRequest`.
6
+ * @typedef {object} RequestLike
7
+ * @property {string} httpVersion
8
+ * @property {{ session?: { alpnProtocol?: string } }} [stream]
9
+ */
10
+
11
+ /**
12
+ * Sets the `X-Powered-By` header when the app has `x-powered-by` enabled.
13
+ * @param {{ enabled(name: string): boolean }} app An Express application.
14
+ * @param {{ setHeader(name: string, value: string): unknown }} res The response.
15
+ * @returns {void}
16
+ */
1
17
  exports.setPoweredBy = (app, res) => {
2
18
  if (app.enabled('x-powered-by')) {
3
19
  res.setHeader('X-Powered-By', 'HTTP/2 Express (http2-express)');
4
20
  }
5
- }
21
+ };
6
22
 
23
+ // Using optional chaining so a destroyed/reset stream never throws TypeError.
24
+ // req.stream?.session?.alpnProtocol returns undefined (not a crash) when the
25
+ // stream or session has already been closed.
26
+ /**
27
+ * @param {RequestLike} req
28
+ * @returns {boolean} `true` when the request arrived over HTTP/2 (h2 or h2c).
29
+ */
7
30
  exports.isHttp2Request = (req) => {
8
- const alpnProtocol = req.httpVersion === '2.0' ? req.stream.session.alpnProtocol : 'h1';
9
- return alpnProtocol && (alpnProtocol === 'h2' || alpnProtocol === 'h2c');
10
- }
31
+ if (req.httpVersion !== '2.0') return false;
32
+ const alpnProtocol = req.stream?.session?.alpnProtocol;
33
+ return alpnProtocol === 'h2' || alpnProtocol === 'h2c';
34
+ };
package/.babelrc DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "presets": ["@babel/preset-env"]
3
- }
package/.eslintrc DELETED
@@ -1,35 +0,0 @@
1
- {
2
- "env": {
3
- "browser": true,
4
- "commonjs": true,
5
- "es2023": true
6
- },
7
- "extends": ["airbnb-base", "eslint:recommended"],
8
- "parserOptions": {
9
- "ecmaVersion": 14
10
- },
11
- "ignorePatterns":[
12
- "dist"
13
- ],
14
- "rules": {
15
- "no-console": "off",
16
- "comma-dangle": "off",
17
- "no-plusplus":"off",
18
- "no-case-declarations":"off",
19
- "no-restricted-syntax":"off",
20
- "no-await-in-loop":"off",
21
- "no-unused-vars":"warn",
22
- "max-len": [2, 250, 4, {"ignoreUrls": true}],
23
- "array-callback-return": "warn",
24
- "prefer-template": "warn",
25
- "prefer-const": "warn",
26
- "no-trailing-spaces": "warn",
27
- "no-multiple-empty-lines": "warn",
28
- "indent": "warn",
29
- "spaced-comment": "warn",
30
- "padded-blocks": "warn",
31
- "no-param-reassign": "warn",
32
- "no-path-concat": "warn",
33
- "arrow-body-style": "warn"
34
- }
35
- }
package/dist/core.js DELETED
@@ -1,157 +0,0 @@
1
- "use strict";
2
-
3
- /* eslint-disable func-names */
4
- /* eslint-disable no-underscore-dangle */
5
- var EventEmitter = require('events');
6
- var createHttp2Request = require('./http2Request');
7
- var createHttp2Response = require('./http2Response');
8
- var initHttp2Express = require('./initHttp2Express');
9
- var _require = require('./util'),
10
- setPoweredBy = _require.setPoweredBy,
11
- isHttp2Request = _require.isHttp2Request;
12
- var createHttp2Express = function createHttp2Express(express) {
13
- var application = express.application,
14
- request = express.request,
15
- response = express.response,
16
- Router = express.Router,
17
- query = express.query;
18
- var isExpress5 = !application.lazyrouter;
19
- if (isExpress5) {
20
- var originalInit = application.init;
21
- application.init = function init() {
22
- var _this = this;
23
- originalInit.call(this);
24
- // at this point we can use the router
25
- this.router.use(function (req, res, next) {
26
- setPoweredBy(_this, res);
27
- next();
28
- });
29
- };
30
- } else {
31
- application.lazyrouter = function lazyrouter() {
32
- if (!this._router) {
33
- this._router = new Router({
34
- caseSensitive: this.enabled('case sensitive routing'),
35
- strict: this.enabled('strict routing')
36
- });
37
- this._router.use(query(this.get('query parser fn')));
38
- this._router.use(initHttp2Express(this));
39
- }
40
- };
41
- }
42
- var oneshotRequestOverride = null;
43
- var oneshotResponseOverride = null;
44
- var _app = function app(req, res, next) {
45
- if (isExpress5 && isHttp2Request(req)) {
46
- // In Express 5, setting the prototype of req/res is done synchronously in the app.handle function,
47
- // so this is the right place to change the value of app.request/app.response.
48
- oneshotRequestOverride = _app.http2Request;
49
- oneshotResponseOverride = _app.http2Response;
50
- }
51
- _app.handle(req, res, next);
52
- };
53
-
54
- // Copying properties and descriptors from EventEmitter.prototype to app.
55
- Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (key) {
56
- var descriptor = Object.getOwnPropertyDescriptor(EventEmitter.prototype, key);
57
- if (descriptor) {
58
- Object.defineProperty(_app, key, descriptor);
59
- }
60
- });
61
-
62
- // Copy symbols from EventEmitter.prototype to app.
63
- Object.getOwnPropertySymbols(EventEmitter.prototype).forEach(function (symbol) {
64
- var descriptor = Object.getOwnPropertyDescriptor(EventEmitter.prototype, symbol);
65
- if (descriptor) {
66
- Object.defineProperty(_app, symbol, descriptor);
67
- }
68
- });
69
-
70
- // Copying properties from application to app.
71
- Object.getOwnPropertyNames(application).forEach(function (key) {
72
- var descriptor = Object.getOwnPropertyDescriptor(application, key);
73
- if (descriptor) {
74
- Object.defineProperty(_app, key, descriptor);
75
- }
76
- });
77
-
78
- // Copy symbols from application to app.
79
- Object.getOwnPropertySymbols(application).forEach(function (symbol) {
80
- var descriptor = Object.getOwnPropertyDescriptor(application, symbol);
81
- if (descriptor) {
82
- Object.defineProperty(_app, symbol, descriptor);
83
- }
84
- });
85
- response.push = function () {};
86
- _app._request = Object.create(request, {
87
- app: {
88
- configurable: true,
89
- enumerable: true,
90
- writable: true,
91
- value: _app
92
- }
93
- });
94
- _app._response = Object.create(response, {
95
- app: {
96
- configurable: true,
97
- enumerable: true,
98
- writable: true,
99
- value: _app
100
- }
101
- });
102
- var http2Request = createHttp2Request(request);
103
- var http2Response = createHttp2Response(response);
104
- _app.http2Request = Object.create(http2Request, {
105
- app: {
106
- configurable: true,
107
- enumerable: true,
108
- writable: true,
109
- value: _app
110
- }
111
- });
112
- _app.http2Response = Object.create(http2Response, {
113
- app: {
114
- configurable: true,
115
- enumerable: true,
116
- writable: true,
117
- value: _app
118
- }
119
- });
120
-
121
- // Expose the prototype that will get set on requests.
122
- Object.defineProperty(_app, 'request', {
123
- configurable: true,
124
- enumerable: true,
125
- get: function get() {
126
- if (oneshotRequestOverride) {
127
- var req = oneshotRequestOverride;
128
- oneshotRequestOverride = null;
129
- return req;
130
- }
131
- return _app._request;
132
- },
133
- set: function set(val) {
134
- _app._request = val;
135
- }
136
- });
137
-
138
- // Expose the prototype that will get set on responses.
139
- Object.defineProperty(_app, 'response', {
140
- configurable: true,
141
- enumerable: true,
142
- get: function get() {
143
- if (oneshotResponseOverride) {
144
- var res = oneshotResponseOverride;
145
- oneshotResponseOverride = null;
146
- return res;
147
- }
148
- return _app._response;
149
- },
150
- set: function set(val) {
151
- _app._response = val;
152
- }
153
- });
154
- _app.init();
155
- return _app;
156
- };
157
- module.exports = createHttp2Express;
@@ -1,40 +0,0 @@
1
- "use strict";
2
-
3
- /* eslint-disable dot-notation */
4
- var _require = require('http2'),
5
- Http2ServerRequest = _require.Http2ServerRequest;
6
- var createHttp2Request = function createHttp2Request(request) {
7
- var _Object$getOwnPropert;
8
- var http2Request = Object.create(Http2ServerRequest.prototype);
9
-
10
- // Copying properties and descriptors from request to http2Request.
11
- Object.getOwnPropertyNames(request).forEach(function (key) {
12
- var descriptor = Object.getOwnPropertyDescriptor(request, key);
13
- if (descriptor) {
14
- Object.defineProperty(http2Request, key, descriptor);
15
- }
16
- });
17
-
18
- // Retain symbols, if any, from request.
19
- Object.getOwnPropertySymbols(request).forEach(function (symbol) {
20
- var descriptor = Object.getOwnPropertyDescriptor(request, symbol);
21
- if (descriptor) {
22
- Object.defineProperty(http2Request, symbol, descriptor);
23
- }
24
- });
25
- var requestHostName = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(http2Request, 'hostname')) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.get;
26
-
27
- // Redefine hostname property with custom getter.
28
- if (requestHostName) {
29
- Object.defineProperty(http2Request, 'hostname', {
30
- get: function get() {
31
- if (!this.headers['host'] && this.authority) {
32
- this.headers['host'] = this.authority;
33
- }
34
- return requestHostName.call(this);
35
- }
36
- });
37
- }
38
- return http2Request;
39
- };
40
- module.exports = createHttp2Request;
@@ -1,25 +0,0 @@
1
- "use strict";
2
-
3
- var _require = require('http2'),
4
- Http2ServerResponse = _require.Http2ServerResponse;
5
- var createHttp2Response = function createHttp2Response(response) {
6
- var http2Response = Object.create(Http2ServerResponse.prototype);
7
-
8
- // Copying properties and descriptors from response to http2Response.
9
- Object.getOwnPropertyNames(response).forEach(function (key) {
10
- var descriptor = Object.getOwnPropertyDescriptor(response, key);
11
- if (descriptor) {
12
- Object.defineProperty(http2Response, key, descriptor);
13
- }
14
- });
15
-
16
- // Copy symbols from response to http2Response.
17
- Object.getOwnPropertySymbols(response).forEach(function (symbol) {
18
- var descriptor = Object.getOwnPropertyDescriptor(response, symbol);
19
- if (descriptor) {
20
- Object.defineProperty(http2Response, symbol, descriptor);
21
- }
22
- });
23
- return http2Response;
24
- };
25
- module.exports = createHttp2Response;
package/dist/index.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";
2
-
3
- var createHttp2Express = require('./core');
4
- module.exports = createHttp2Express;
5
- exports["default"] = createHttp2Express;
@@ -1,23 +0,0 @@
1
- "use strict";
2
-
3
- var _require = require("./util"),
4
- isHttp2Request = _require.isHttp2Request,
5
- setPoweredBy = _require.setPoweredBy;
6
- var initHttp2Express = function initHttp2Express(app) {
7
- return function (req, res, next) {
8
- setPoweredBy(app, res);
9
- req.res = res;
10
- res.req = req;
11
- req.next = next;
12
- if (isHttp2Request(req)) {
13
- Object.setPrototypeOf(req, app.http2Request);
14
- Object.setPrototypeOf(res, app.http2Response);
15
- } else {
16
- Object.setPrototypeOf(req, app.request);
17
- Object.setPrototypeOf(res, app.response);
18
- }
19
- res.locals = res.locals || Object.create(null);
20
- next();
21
- };
22
- };
23
- module.exports = initHttp2Express;
package/dist/util.js DELETED
@@ -1,11 +0,0 @@
1
- "use strict";
2
-
3
- exports.setPoweredBy = function (app, res) {
4
- if (app.enabled('x-powered-by')) {
5
- res.setHeader('X-Powered-By', 'HTTP/2 Express (http2-express)');
6
- }
7
- };
8
- exports.isHttp2Request = function (req) {
9
- var alpnProtocol = req.httpVersion === '2.0' ? req.stream.session.alpnProtocol : 'h1';
10
- return alpnProtocol && (alpnProtocol === 'h2' || alpnProtocol === 'h2c');
11
- };
@@ -1,21 +0,0 @@
1
- const { isHttp2Request, setPoweredBy } = require("./util");
2
-
3
- const initHttp2Express = (app) => (req, res, next) => {
4
- setPoweredBy(app, res);
5
- req.res = res;
6
- res.req = req;
7
- req.next = next;
8
-
9
- if (isHttp2Request(req)) {
10
- Object.setPrototypeOf(req, app.http2Request);
11
- Object.setPrototypeOf(res, app.http2Response);
12
- } else {
13
- Object.setPrototypeOf(req, app.request);
14
- Object.setPrototypeOf(res, app.response);
15
- }
16
-
17
- res.locals = res.locals || Object.create(null);
18
- next();
19
- };
20
-
21
- module.exports = initHttp2Express;