Skip to content

Commit a90386b

Browse files
nodejs-github-botdanielleadams
authored andcommitted
deps: update undici to 5.11.0
PR-URL: #44929 Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com> Reviewed-By: Tobias Nießen <tniessen@tnie.de>
1 parent 0db86ee commit a90386b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

72 files changed

+10995
-1374
lines changed

deps/undici/src/README.md

+33-11
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,12 @@ Help us improve the test coverage by following instructions at [nodejs/undici/#9
185185
Basic usage example:
186186

187187
```js
188-
import { fetch } from 'undici';
188+
import { fetch } from 'undici'
189189

190190

191191
const res = await fetch('https://example.com')
192192
const json = await res.json()
193-
console.log(json);
193+
console.log(json)
194194
```
195195

196196
You can pass an optional dispatcher to `fetch` as:
@@ -225,29 +225,29 @@ A body can be of the following types:
225225
In this implementation of fetch, ```request.body``` now accepts ```Async Iterables```. It is not present in the [Fetch Standard.](https://fetch.spec.whatwg.org)
226226

227227
```js
228-
import { fetch } from "undici";
228+
import { fetch } from 'undici'
229229

230230
const data = {
231231
async *[Symbol.asyncIterator]() {
232-
yield "hello";
233-
yield "world";
232+
yield 'hello'
233+
yield 'world'
234234
},
235-
};
235+
}
236236

237-
await fetch("https://example.com", { body: data, method: 'POST' });
237+
await fetch('https://example.com', { body: data, method: 'POST' })
238238
```
239239

240240
#### `response.body`
241241

242242
Nodejs has two kinds of streams: [web streams](https://nodejs.org/dist/latest-v16.x/docs/api/webstreams.html), which follow the API of the WHATWG web standard found in browsers, and an older Node-specific [streams API](https://nodejs.org/api/stream.html). `response.body` returns a readable web stream. If you would prefer to work with a Node stream you can convert a web stream using `.fromWeb()`.
243243

244244
```js
245-
import { fetch } from 'undici';
246-
import { Readable } from 'node:stream';
245+
import { fetch } from 'undici'
246+
import { Readable } from 'node:stream'
247247

248248
const response = await fetch('https://example.com')
249-
const readableWebStream = response.body;
250-
const readableNodeStream = Readable.fromWeb(readableWebStream);
249+
const readableWebStream = response.body
250+
const readableNodeStream = Readable.fromWeb(readableWebStream)
251251
```
252252

253253
#### Specification Compliance
@@ -329,6 +329,28 @@ Gets the global dispatcher used by Common API Methods.
329329

330330
Returns: `Dispatcher`
331331

332+
### `undici.setGlobalOrigin(origin)`
333+
334+
* origin `string | URL | undefined`
335+
336+
Sets the global origin used in `fetch`.
337+
338+
If `undefined` is passed, the global origin will be reset. This will cause `Response.redirect`, `new Request()`, and `fetch` to throw an error when a relative path is passed.
339+
340+
```js
341+
setGlobalOrigin('http://localhost:3000')
342+
343+
const response = await fetch('/api/ping')
344+
345+
console.log(response.url) // http://localhost:3000/api/ping
346+
```
347+
348+
### `undici.getGlobalOrigin()`
349+
350+
Gets the global origin used in `fetch`.
351+
352+
Returns: `URL`
353+
332354
### `UrlObject`
333355

334356
* **port** `string | number` (optional)

deps/undici/src/docs/api/Agent.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@ Returns: `Agent`
1616

1717
### Parameter: `AgentOptions`
1818

19-
Extends: [`ClientOptions`](Pool.md#parameter-pooloptions)
19+
Extends: [`PoolOptions`](Pool.md#parameter-pooloptions)
2020

2121
* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)`
2222
* **maxRedirections** `Integer` - Default: `0`. The number of HTTP redirection to follow unless otherwise specified in `DispatchOptions`.
23+
* **interceptors** `{ Agent: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time.
2324

2425
## Instance Properties
2526

deps/undici/src/docs/api/Client.md

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ Returns: `Client`
2626
* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections.
2727
* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`.
2828
* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body.
29+
* **interceptors** `{ Client: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time.
2930

3031
#### Parameter: `ConnectOptions`
3132

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#Interface: DispatchInterceptor
2+
3+
Extends: `Function`
4+
5+
A function that can be applied to the `Dispatcher.Dispatch` function before it is invoked with a dispatch request.
6+
7+
This allows one to write logic to intercept both the outgoing request, and the incoming response.
8+
9+
### Parameter: `Dispatcher.Dispatch`
10+
11+
The base dispatch function you are decorating.
12+
13+
### ReturnType: `Dispatcher.Dispatch`
14+
15+
A dispatch function that has been altered to provide additional logic
16+
17+
### Basic Example
18+
19+
Here is an example of an interceptor being used to provide a JWT bearer token
20+
21+
```js
22+
'use strict'
23+
24+
const insertHeaderInterceptor = dispatch => {
25+
return function InterceptedDispatch(opts, handler){
26+
opts.headers.push('Authorization', 'Bearer [Some token]')
27+
return dispatch(opts, handler)
28+
}
29+
}
30+
31+
const client = new Client('https://localhost:3000', {
32+
interceptors: { Client: [insertHeaderInterceptor] }
33+
})
34+
35+
```
36+
37+
### Basic Example 2
38+
39+
Here is a contrived example of an interceptor stripping the headers from a response.
40+
41+
```js
42+
'use strict'
43+
44+
const clearHeadersInterceptor = dispatch => {
45+
const { DecoratorHandler } = require('undici')
46+
class ResultInterceptor extends DecoratorHandler {
47+
onHeaders (statusCode, headers, resume) {
48+
return super.onHeaders(statusCode, [], resume)
49+
}
50+
}
51+
return function InterceptedDispatch(opts, handler){
52+
return dispatch(opts, new ResultInterceptor(handler))
53+
}
54+
}
55+
56+
const client = new Client('https://localhost:3000', {
57+
interceptors: { Client: [clearHeadersInterceptor] }
58+
})
59+
60+
```

deps/undici/src/docs/api/MockPool.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ Returns: `MockInterceptor` corresponding to the input options.
5454
### Parameter: `MockPoolInterceptOptions`
5555

5656
* **path** `string | RegExp | (path: string) => boolean` - a matcher for the HTTP request path.
57-
* **method** `string | RegExp | (method: string) => boolean` - a matcher for the HTTP request method.
57+
* **method** `string | RegExp | (method: string) => boolean` - (optional) - a matcher for the HTTP request method. Defaults to `GET`.
5858
* **body** `string | RegExp | (body: string) => boolean` - (optional) - a matcher for the HTTP request body.
5959
* **headers** `Record<string, string | RegExp | (body: string) => boolean`> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way.
6060
* **query** `Record<string, any> | null` - (optional) - a matcher for the HTTP request query string params.

deps/undici/src/docs/api/Pool.md

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Extends: [`ClientOptions`](Client.md#parameter-clientoptions)
1919

2020
* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)`
2121
* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `Pool` instance will create an unlimited amount of `Client` instances.
22+
* **interceptors** `{ Pool: DispatchInterceptor[] } }` - Default: `{ Pool: [] }` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching).
2223

2324
## Instance Properties
2425

deps/undici/src/index-fetch.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
'use strict'
22

33
const { getGlobalDispatcher } = require('./lib/global')
4-
const fetchImpl = require('./lib/fetch')
4+
const fetchImpl = require('./lib/fetch').fetch
55

66
module.exports.fetch = async function fetch (resource) {
77
const dispatcher = (arguments[1] && arguments[1].dispatcher) || getGlobalDispatcher()
8-
return fetchImpl.apply(dispatcher, arguments)
8+
try {
9+
return await fetchImpl.apply(dispatcher, arguments)
10+
} catch (err) {
11+
Error.captureStackTrace(err, this)
12+
throw err
13+
}
914
}
1015
module.exports.FormData = require('./lib/fetch/formdata').FormData
1116
module.exports.Headers = require('./lib/fetch/headers').Headers

deps/undici/src/index.d.ts

+7-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import Dispatcher = require('./types/dispatcher')
22
import { setGlobalDispatcher, getGlobalDispatcher } from './types/global-dispatcher'
3+
import { setGlobalOrigin, getGlobalOrigin } from './types/global-origin'
34
import Pool = require('./types/pool')
5+
import { RedirectHandler, DecoratorHandler } from './types/handlers'
6+
47
import BalancedPool = require('./types/balanced-pool')
58
import Client = require('./types/client')
69
import buildConnector = require('./types/connector')
@@ -19,14 +22,15 @@ export * from './types/formdata'
1922
export * from './types/diagnostics-channel'
2023
export { Interceptable } from './types/mock-interceptor'
2124

22-
export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent }
25+
export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, RedirectHandler, DecoratorHandler }
2326
export default Undici
2427

25-
declare function Undici(url: string, opts: Pool.Options): Pool
26-
2728
declare namespace Undici {
2829
var Dispatcher: typeof import('./types/dispatcher')
2930
var Pool: typeof import('./types/pool');
31+
var RedirectHandler: typeof import ('./types/handlers').RedirectHandler
32+
var DecoratorHandler: typeof import ('./types/handlers').DecoratorHandler
33+
var createRedirectInterceptor: typeof import ('./types/interceptors').createRedirectInterceptor
3034
var BalancedPool: typeof import('./types/balanced-pool');
3135
var Client: typeof import('./types/client');
3236
var buildConnector: typeof import('./types/connector');

deps/undici/src/index.js

+19-2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ const MockPool = require('./lib/mock/mock-pool')
1616
const mockErrors = require('./lib/mock/mock-errors')
1717
const ProxyAgent = require('./lib/proxy-agent')
1818
const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')
19+
const DecoratorHandler = require('./lib/handler/DecoratorHandler')
20+
const RedirectHandler = require('./lib/handler/RedirectHandler')
21+
const createRedirectInterceptor = require('./lib/interceptor/redirectInterceptor')
1922

2023
const nodeVersion = process.versions.node.split('.')
2124
const nodeMajor = Number(nodeVersion[0])
@@ -30,6 +33,10 @@ module.exports.BalancedPool = BalancedPool
3033
module.exports.Agent = Agent
3134
module.exports.ProxyAgent = ProxyAgent
3235

36+
module.exports.DecoratorHandler = DecoratorHandler
37+
module.exports.RedirectHandler = RedirectHandler
38+
module.exports.createRedirectInterceptor = createRedirectInterceptor
39+
3340
module.exports.buildConnector = buildConnector
3441
module.exports.errors = errors
3542

@@ -89,16 +96,26 @@ if (nodeMajor > 16 || (nodeMajor === 16 && nodeMinor >= 8)) {
8996
let fetchImpl = null
9097
module.exports.fetch = async function fetch (resource) {
9198
if (!fetchImpl) {
92-
fetchImpl = require('./lib/fetch')
99+
fetchImpl = require('./lib/fetch').fetch
93100
}
94101
const dispatcher = (arguments[1] && arguments[1].dispatcher) || getGlobalDispatcher()
95-
return fetchImpl.apply(dispatcher, arguments)
102+
try {
103+
return await fetchImpl.apply(dispatcher, arguments)
104+
} catch (err) {
105+
Error.captureStackTrace(err, this)
106+
throw err
107+
}
96108
}
97109
module.exports.Headers = require('./lib/fetch/headers').Headers
98110
module.exports.Response = require('./lib/fetch/response').Response
99111
module.exports.Request = require('./lib/fetch/request').Request
100112
module.exports.FormData = require('./lib/fetch/formdata').FormData
101113
module.exports.File = require('./lib/fetch/file').File
114+
115+
const { setGlobalOrigin, getGlobalOrigin } = require('./lib/fetch/global')
116+
117+
module.exports.setGlobalOrigin = setGlobalOrigin
118+
module.exports.getGlobalOrigin = getGlobalOrigin
102119
}
103120

104121
module.exports.request = makeDispatcher(api.request)

deps/undici/src/lib/agent.js

+9-8
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
'use strict'
22

33
const { InvalidArgumentError } = require('./core/errors')
4-
const { kClients, kRunning, kClose, kDestroy, kDispatch } = require('./core/symbols')
4+
const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('./core/symbols')
55
const DispatcherBase = require('./dispatcher-base')
66
const Pool = require('./pool')
77
const Client = require('./client')
88
const util = require('./core/util')
9-
const RedirectHandler = require('./handler/redirect')
9+
const createRedirectInterceptor = require('./interceptor/redirectInterceptor')
1010
const { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')()
1111

1212
const kOnConnect = Symbol('onConnect')
@@ -44,7 +44,14 @@ class Agent extends DispatcherBase {
4444
connect = { ...connect }
4545
}
4646

47+
this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
48+
? options.interceptors.Agent
49+
: [createRedirectInterceptor({ maxRedirections })]
50+
4751
this[kOptions] = { ...util.deepClone(options), connect }
52+
this[kOptions].interceptors = options.interceptors
53+
? { ...options.interceptors }
54+
: undefined
4855
this[kMaxRedirections] = maxRedirections
4956
this[kFactory] = factory
5057
this[kClients] = new Map()
@@ -108,12 +115,6 @@ class Agent extends DispatcherBase {
108115
this[kFinalizer].register(dispatcher, key)
109116
}
110117

111-
const { maxRedirections = this[kMaxRedirections] } = opts
112-
if (maxRedirections != null && maxRedirections !== 0) {
113-
opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
114-
handler = new RedirectHandler(this, maxRedirections, opts, handler)
115-
}
116-
117118
return dispatcher.dispatch(opts, handler)
118119
}
119120

deps/undici/src/lib/balanced-pool.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const {
1313
kGetDispatcher
1414
} = require('./pool-base')
1515
const Pool = require('./pool')
16-
const { kUrl } = require('./core/symbols')
16+
const { kUrl, kInterceptors } = require('./core/symbols')
1717
const { parseOrigin } = require('./core/util')
1818
const kFactory = Symbol('factory')
1919

@@ -53,6 +53,9 @@ class BalancedPool extends PoolBase {
5353
throw new InvalidArgumentError('factory must be a function.')
5454
}
5555

56+
this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
57+
? opts.interceptors.BalancedPool
58+
: []
5659
this[kFactory] = factory
5760

5861
for (const upstream of upstreams) {

deps/undici/src/lib/client.js

+7-7
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ const net = require('net')
77
const util = require('./core/util')
88
const Request = require('./core/request')
99
const DispatcherBase = require('./dispatcher-base')
10-
const RedirectHandler = require('./handler/redirect')
1110
const {
1211
RequestContentLengthMismatchError,
1312
ResponseContentLengthMismatchError,
@@ -60,7 +59,8 @@ const {
6059
kCounter,
6160
kClose,
6261
kDestroy,
63-
kDispatch
62+
kDispatch,
63+
kInterceptors
6464
} = require('./core/symbols')
6565

6666
const kClosedResolve = Symbol('kClosedResolve')
@@ -82,6 +82,7 @@ try {
8282

8383
class Client extends DispatcherBase {
8484
constructor (url, {
85+
interceptors,
8586
maxHeaderSize,
8687
headersTimeout,
8788
socketTimeout,
@@ -179,6 +180,9 @@ class Client extends DispatcherBase {
179180
})
180181
}
181182

183+
this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
184+
? interceptors.Client
185+
: [createRedirectInterceptor({ maxRedirections })]
182186
this[kUrl] = util.parseOrigin(url)
183187
this[kConnector] = connect
184188
this[kSocket] = null
@@ -254,11 +258,6 @@ class Client extends DispatcherBase {
254258
}
255259

256260
[kDispatch] (opts, handler) {
257-
const { maxRedirections = this[kMaxRedirections] } = opts
258-
if (maxRedirections) {
259-
handler = new RedirectHandler(this, maxRedirections, opts, handler)
260-
}
261-
262261
const origin = opts.origin || this[kUrl].origin
263262

264263
const request = new Request(origin, opts, handler)
@@ -319,6 +318,7 @@ class Client extends DispatcherBase {
319318
}
320319

321320
const constants = require('./llhttp/constants')
321+
const createRedirectInterceptor = require('./interceptor/redirectInterceptor')
322322
const EMPTY_BUF = Buffer.alloc(0)
323323

324324
async function lazyllhttp () {

0 commit comments

Comments
 (0)