diff --git a/src/HttpAgent.ts b/src/HttpAgent.ts index 0fff0886..54feaa46 100644 --- a/src/HttpAgent.ts +++ b/src/HttpAgent.ts @@ -12,6 +12,7 @@ export type HttpAgentOptions = { lookup?: LookupFunction; checkAddress?: CheckAddressFunction; connect?: buildConnector.BuildOptions, + allowH2?: boolean; }; class IllegalAddressError extends Error { @@ -62,7 +63,7 @@ export class HttpAgent extends Agent { }); }; super({ - connect: { ...options.connect, lookup }, + connect: { ...options.connect, lookup, allowH2: options.allowH2 }, }); this.#checkAddress = options.checkAddress; } diff --git a/src/HttpClient.ts b/src/HttpClient.ts index 5bf5e7d2..f7120a80 100644 --- a/src/HttpClient.ts +++ b/src/HttpClient.ts @@ -70,6 +70,8 @@ const isNode14Or16 = /v1[46]\./.test(process.version); export type ClientOptions = { defaultArgs?: RequestOptions; + /** Allow to use HTTP2 first. Default is `false` */ + allowH2?: boolean; /** * Custom DNS lookup function, default is `dns.lookup`. */ @@ -187,10 +189,17 @@ export class HttpClient extends EventEmitter { lookup: clientOptions.lookup, checkAddress: clientOptions.checkAddress, connect: clientOptions.connect, + allowH2: clientOptions.allowH2, }); } else if (clientOptions?.connect) { this.#dispatcher = new Agent({ connect: clientOptions.connect, + allowH2: clientOptions.allowH2, + }); + } else if (clientOptions?.allowH2) { + // Support HTTP2 + this.#dispatcher = new Agent({ + allowH2: clientOptions.allowH2, }); } initDiagnosticsChannel(); diff --git a/test/HttpClient.test.ts b/test/HttpClient.test.ts index 07ecdacc..8648c3af 100644 --- a/test/HttpClient.test.ts +++ b/test/HttpClient.test.ts @@ -1,7 +1,8 @@ import { strict as assert } from 'node:assert'; import dns from 'node:dns'; +import { sensitiveHeaders } from 'node:http2'; import { describe, it, beforeAll, afterAll } from 'vitest'; -import { HttpClient } from '../src'; +import { HttpClient, getGlobalDispatcher } from '../src'; import { RawResponseWithMeta } from '../src/Response'; import { startServer } from './fixtures/server'; @@ -28,6 +29,20 @@ describe('HttpClient.test.ts', () => { }); }); + describe('clientOptions.allowH2', () => { + it('should work with allowH2 = true', async () => { + const httpclient = new HttpClient({ + allowH2: true, + }); + assert(httpclient); + const response = await httpclient.request('https://registry.npmmirror.com/urllib'); + assert.equal(response.status, 200); + assert(sensitiveHeaders in response.headers); + assert.equal(response.headers['content-type'], 'application/json; charset=utf-8'); + assert.notEqual(httpclient.getDispatcher(), getGlobalDispatcher()); + }); + }); + describe('clientOptions.defaultArgs', () => { it('should work with custom defaultArgs', async () => { const httpclient = new HttpClient({ defaultArgs: { timeout: 1000 } });