mirror of
https://github.com/nodejs/node.git
synced 2026-11-25 23:01:06 -05:00
deps: update undici to 5.0.0
PR-URL: https://github.com/nodejs/node/pull/42583 Backport-PR-URL: https://github.com/nodejs/node/pull/42727 Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com> Reviewed-By: Mestery <mestery@protonmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Darshan Sen <raisinten@gmail.com>
This commit is contained in:
1 parent
a670c1fb5f
commit
c64b0381ee
20 files changed
+1597
-1559
No files matched your search
+9
-45
@@ -72,11 +72,7 @@ const mockAgent = new MockAgent()
|
||||
setGlobalDispatcher(mockAgent)
|
||||
|
||||
const mockPool = mockAgent.get('http://localhost:3000')
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET'
|
||||
}).reply(200, 'foo')
|
||||
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const { statusCode, body } = await request('http://localhost:3000/foo')
|
||||
|
||||
@@ -95,11 +91,7 @@ import { MockAgent, request } from 'undici'
|
||||
const mockAgent = new MockAgent()
|
||||
|
||||
const mockPool = mockAgent.get('http://localhost:3000')
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET'
|
||||
}).reply(200, 'foo')
|
||||
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const {
|
||||
statusCode,
|
||||
@@ -121,11 +113,7 @@ import { MockAgent, request } from 'undici'
|
||||
const mockAgent = new MockAgent()
|
||||
|
||||
const mockPool = mockAgent.get('http://localhost:3000')
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET'
|
||||
}).reply(200, 'foo')
|
||||
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const {
|
||||
statusCode,
|
||||
@@ -147,11 +135,7 @@ import { MockAgent, request } from 'undici'
|
||||
const mockAgent = new MockAgent({ connections: 1 })
|
||||
|
||||
const mockClient = mockAgent.get('http://localhost:3000')
|
||||
|
||||
mockClient.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET'
|
||||
}).reply(200, 'foo')
|
||||
mockClient.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const {
|
||||
statusCode,
|
||||
@@ -174,16 +158,8 @@ const mockAgent = new MockAgent()
|
||||
setGlobalDispatcher(mockAgent)
|
||||
|
||||
const mockPool = mockAgent.get('http://localhost:3000')
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET'
|
||||
}).reply(200, 'foo')
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/hello',
|
||||
method: 'GET'
|
||||
}).reply(200, 'hello')
|
||||
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
mockPool.intercept({ path: '/hello'}).reply(200, 'hello')
|
||||
|
||||
const result1 = await request('http://localhost:3000/foo')
|
||||
|
||||
@@ -250,11 +226,7 @@ const mockAgent = new MockAgent()
|
||||
setGlobalDispatcher(mockAgent)
|
||||
|
||||
const mockPool = mockAgent.get(new RegExp('http://localhost:3000'))
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET',
|
||||
}).reply(200, 'foo')
|
||||
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const {
|
||||
statusCode,
|
||||
@@ -277,11 +249,7 @@ const mockAgent = new MockAgent()
|
||||
setGlobalDispatcher(mockAgent)
|
||||
|
||||
const mockPool = mockAgent.get((origin) => origin === 'http://localhost:3000')
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET'
|
||||
}).reply(200, 'foo')
|
||||
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const {
|
||||
statusCode,
|
||||
@@ -328,11 +296,7 @@ import { MockAgent } from 'undici'
|
||||
const mockAgent = new MockAgent()
|
||||
|
||||
const mockPool = mockAgent.get('http://localhost:3000')
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET'
|
||||
}).reply(200, 'foo')
|
||||
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const {
|
||||
statusCode,
|
||||
|
||||
+1
-4
@@ -58,10 +58,7 @@ import { MockAgent } from 'undici'
|
||||
const mockAgent = new MockAgent({ connections: 1 })
|
||||
|
||||
const mockClient = mockAgent.get('http://localhost:3000')
|
||||
mockClient.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET',
|
||||
}).reply(200, 'foo')
|
||||
mockClient.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const {
|
||||
statusCode,
|
||||
|
||||
Vendored
+1
-5
@@ -95,11 +95,7 @@ setGlobalDispatcher(mockAgent)
|
||||
|
||||
// MockPool
|
||||
const mockPool = mockAgent.get('http://localhost:3000')
|
||||
|
||||
mockPool.intercept({
|
||||
path: '/foo',
|
||||
method: 'GET',
|
||||
}).reply(200, 'foo')
|
||||
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
||||
|
||||
const {
|
||||
statusCode,
|
||||
|
||||
Vendored
+32
-100
@@ -1,20 +1,14 @@
|
||||
'use strict'
|
||||
|
||||
const {
|
||||
ClientClosedError,
|
||||
InvalidArgumentError,
|
||||
ClientDestroyedError
|
||||
} = require('./core/errors')
|
||||
const { kClients, kRunning } = require('./core/symbols')
|
||||
const Dispatcher = require('./dispatcher')
|
||||
const { InvalidArgumentError } = require('./core/errors')
|
||||
const { kClients, kRunning, kClose, kDestroy, kDispatch } = require('./core/symbols')
|
||||
const DispatcherBase = require('./dispatcher-base')
|
||||
const Pool = require('./pool')
|
||||
const Client = require('./client')
|
||||
const util = require('./core/util')
|
||||
const RedirectHandler = require('./handler/redirect')
|
||||
const { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')()
|
||||
|
||||
const kDestroyed = Symbol('destroyed')
|
||||
const kClosed = Symbol('closed')
|
||||
const kOnConnect = Symbol('onConnect')
|
||||
const kOnDisconnect = Symbol('onDisconnect')
|
||||
const kOnConnectionError = Symbol('onConnectionError')
|
||||
@@ -30,7 +24,7 @@ function defaultFactory (origin, opts) {
|
||||
: new Pool(origin, opts)
|
||||
}
|
||||
|
||||
class Agent extends Dispatcher {
|
||||
class Agent extends DispatcherBase {
|
||||
constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
|
||||
super()
|
||||
|
||||
@@ -60,8 +54,6 @@ class Agent extends Dispatcher {
|
||||
this[kClients].delete(key)
|
||||
}
|
||||
})
|
||||
this[kClosed] = false
|
||||
this[kDestroyed] = false
|
||||
|
||||
const agent = this
|
||||
|
||||
@@ -94,76 +86,38 @@ class Agent extends Dispatcher {
|
||||
return ret
|
||||
}
|
||||
|
||||
dispatch (opts, handler) {
|
||||
if (!handler || typeof handler !== 'object') {
|
||||
throw new InvalidArgumentError('handler must be an object.')
|
||||
[kDispatch] (opts, handler) {
|
||||
let key
|
||||
if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
|
||||
key = String(opts.origin)
|
||||
} else {
|
||||
throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
|
||||
}
|
||||
|
||||
try {
|
||||
if (!opts || typeof opts !== 'object') {
|
||||
throw new InvalidArgumentError('opts must be an object.')
|
||||
}
|
||||
const ref = this[kClients].get(key)
|
||||
|
||||
let key
|
||||
if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
|
||||
key = String(opts.origin)
|
||||
} else {
|
||||
throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
|
||||
}
|
||||
let dispatcher = ref ? ref.deref() : null
|
||||
if (!dispatcher) {
|
||||
dispatcher = this[kFactory](opts.origin, this[kOptions])
|
||||
.on('drain', this[kOnDrain])
|
||||
.on('connect', this[kOnConnect])
|
||||
.on('disconnect', this[kOnDisconnect])
|
||||
.on('connectionError', this[kOnConnectionError])
|
||||
|
||||
if (this[kDestroyed]) {
|
||||
throw new ClientDestroyedError()
|
||||
}
|
||||
|
||||
if (this[kClosed]) {
|
||||
throw new ClientClosedError()
|
||||
}
|
||||
|
||||
const ref = this[kClients].get(key)
|
||||
|
||||
let dispatcher = ref ? ref.deref() : null
|
||||
if (!dispatcher) {
|
||||
dispatcher = this[kFactory](opts.origin, this[kOptions])
|
||||
.on('drain', this[kOnDrain])
|
||||
.on('connect', this[kOnConnect])
|
||||
.on('disconnect', this[kOnDisconnect])
|
||||
.on('connectionError', this[kOnConnectionError])
|
||||
|
||||
this[kClients].set(key, new WeakRef(dispatcher))
|
||||
this[kFinalizer].register(dispatcher, key)
|
||||
}
|
||||
|
||||
const { maxRedirections = this[kMaxRedirections] } = opts
|
||||
if (maxRedirections != null && maxRedirections !== 0) {
|
||||
opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
|
||||
handler = new RedirectHandler(this, maxRedirections, opts, handler)
|
||||
}
|
||||
|
||||
return dispatcher.dispatch(opts, handler)
|
||||
} catch (err) {
|
||||
if (typeof handler.onError !== 'function') {
|
||||
throw new InvalidArgumentError('invalid onError method')
|
||||
}
|
||||
|
||||
handler.onError(err)
|
||||
}
|
||||
}
|
||||
|
||||
get closed () {
|
||||
return this[kClosed]
|
||||
}
|
||||
|
||||
get destroyed () {
|
||||
return this[kDestroyed]
|
||||
}
|
||||
|
||||
close (callback) {
|
||||
if (callback != null && typeof callback !== 'function') {
|
||||
throw new InvalidArgumentError('callback must be a function')
|
||||
this[kClients].set(key, new WeakRef(dispatcher))
|
||||
this[kFinalizer].register(dispatcher, key)
|
||||
}
|
||||
|
||||
this[kClosed] = true
|
||||
const { maxRedirections = this[kMaxRedirections] } = opts
|
||||
if (maxRedirections != null && maxRedirections !== 0) {
|
||||
opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
|
||||
handler = new RedirectHandler(this, maxRedirections, opts, handler)
|
||||
}
|
||||
|
||||
return dispatcher.dispatch(opts, handler)
|
||||
}
|
||||
|
||||
async [kClose] () {
|
||||
const closePromises = []
|
||||
for (const ref of this[kClients].values()) {
|
||||
const client = ref.deref()
|
||||
@@ -173,27 +127,10 @@ class Agent extends Dispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
if (!callback) {
|
||||
return Promise.all(closePromises)
|
||||
}
|
||||
|
||||
// Should never error.
|
||||
Promise.all(closePromises).then(() => process.nextTick(callback))
|
||||
await Promise.all(closePromises)
|
||||
}
|
||||
|
||||
destroy (err, callback) {
|
||||
if (typeof err === 'function') {
|
||||
callback = err
|
||||
err = null
|
||||
}
|
||||
|
||||
if (callback != null && typeof callback !== 'function') {
|
||||
throw new InvalidArgumentError('callback must be a function')
|
||||
}
|
||||
|
||||
this[kClosed] = true
|
||||
this[kDestroyed] = true
|
||||
|
||||
async [kDestroy] (err) {
|
||||
const destroyPromises = []
|
||||
for (const ref of this[kClients].values()) {
|
||||
const client = ref.deref()
|
||||
@@ -203,12 +140,7 @@ class Agent extends Dispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
if (!callback) {
|
||||
return Promise.all(destroyPromises)
|
||||
}
|
||||
|
||||
// Should never error.
|
||||
Promise.all(destroyPromises).then(() => process.nextTick(callback))
|
||||
await Promise.all(destroyPromises)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+59
-159
@@ -6,7 +6,7 @@ const assert = require('assert')
|
||||
const net = require('net')
|
||||
const util = require('./core/util')
|
||||
const Request = require('./core/request')
|
||||
const Dispatcher = require('./dispatcher')
|
||||
const DispatcherBase = require('./dispatcher-base')
|
||||
const RedirectHandler = require('./handler/redirect')
|
||||
const {
|
||||
RequestContentLengthMismatchError,
|
||||
@@ -16,8 +16,6 @@ const {
|
||||
RequestAbortedError,
|
||||
HeadersTimeoutError,
|
||||
HeadersOverflowError,
|
||||
ClientDestroyedError,
|
||||
ClientClosedError,
|
||||
SocketError,
|
||||
InformationalError,
|
||||
BodyTimeoutError,
|
||||
@@ -45,12 +43,9 @@ const {
|
||||
kNoRef,
|
||||
kKeepAliveDefaultTimeout,
|
||||
kHostHeader,
|
||||
kClosed,
|
||||
kDestroyed,
|
||||
kPendingIdx,
|
||||
kRunningIdx,
|
||||
kError,
|
||||
kOnDestroyed,
|
||||
kPipelining,
|
||||
kSocket,
|
||||
kKeepAliveTimeoutValue,
|
||||
@@ -63,9 +58,14 @@ const {
|
||||
kConnector,
|
||||
kMaxRedirections,
|
||||
kMaxRequests,
|
||||
kCounter
|
||||
kCounter,
|
||||
kClose,
|
||||
kDestroy,
|
||||
kDispatch
|
||||
} = require('./core/symbols')
|
||||
|
||||
const kClosedResolve = Symbol('kClosedResolve')
|
||||
|
||||
const channels = {}
|
||||
|
||||
try {
|
||||
@@ -81,7 +81,7 @@ try {
|
||||
channels.connected = { hasSubscribers: false }
|
||||
}
|
||||
|
||||
class Client extends Dispatcher {
|
||||
class Client extends DispatcherBase {
|
||||
constructor (url, {
|
||||
maxHeaderSize,
|
||||
headersTimeout,
|
||||
@@ -189,10 +189,7 @@ class Client extends Dispatcher {
|
||||
this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
|
||||
this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold
|
||||
this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
|
||||
this[kClosed] = false
|
||||
this[kDestroyed] = false
|
||||
this[kServerName] = null
|
||||
this[kOnDestroyed] = []
|
||||
this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
|
||||
this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
|
||||
this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
|
||||
@@ -201,6 +198,7 @@ class Client extends Dispatcher {
|
||||
this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
|
||||
this[kMaxRedirections] = maxRedirections
|
||||
this[kMaxRequests] = maxRequestsPerClient
|
||||
this[kClosedResolve] = null
|
||||
|
||||
// kQueue is built up of 3 sections separated by
|
||||
// the kRunningIdx and kPendingIdx indices.
|
||||
@@ -216,25 +214,15 @@ class Client extends Dispatcher {
|
||||
this[kPendingIdx] = 0
|
||||
}
|
||||
|
||||
// TODO: Make private?
|
||||
get pipelining () {
|
||||
return this[kPipelining]
|
||||
}
|
||||
|
||||
// TODO: Make private?
|
||||
set pipelining (value) {
|
||||
this[kPipelining] = value
|
||||
resume(this, true)
|
||||
}
|
||||
|
||||
get destroyed () {
|
||||
return this[kDestroyed]
|
||||
}
|
||||
|
||||
get closed () {
|
||||
return this[kClosed]
|
||||
}
|
||||
|
||||
get [kPending] () {
|
||||
return this[kQueue].length - this[kPendingIdx]
|
||||
}
|
||||
@@ -266,141 +254,68 @@ class Client extends Dispatcher {
|
||||
this.once('connect', cb)
|
||||
}
|
||||
|
||||
dispatch (opts, handler) {
|
||||
if (!handler || typeof handler !== 'object') {
|
||||
throw new InvalidArgumentError('handler must be an object')
|
||||
[kDispatch] (opts, handler) {
|
||||
const { maxRedirections = this[kMaxRedirections] } = opts
|
||||
if (maxRedirections) {
|
||||
handler = new RedirectHandler(this, maxRedirections, opts, handler)
|
||||
}
|
||||
|
||||
try {
|
||||
if (!opts || typeof opts !== 'object') {
|
||||
throw new InvalidArgumentError('opts must be an object.')
|
||||
}
|
||||
const origin = opts.origin || this[kUrl].origin
|
||||
|
||||
if (this[kDestroyed]) {
|
||||
throw new ClientDestroyedError()
|
||||
}
|
||||
const request = new Request(origin, opts, handler)
|
||||
|
||||
if (this[kClosed]) {
|
||||
throw new ClientClosedError()
|
||||
}
|
||||
this[kQueue].push(request)
|
||||
if (this[kResuming]) {
|
||||
// Do nothing.
|
||||
} else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
|
||||
// Wait a tick in case stream/iterator is ended in the same tick.
|
||||
this[kResuming] = 1
|
||||
process.nextTick(resume, this)
|
||||
} else {
|
||||
resume(this, true)
|
||||
}
|
||||
|
||||
const { maxRedirections = this[kMaxRedirections] } = opts
|
||||
if (maxRedirections) {
|
||||
handler = new RedirectHandler(this, maxRedirections, opts, handler)
|
||||
}
|
||||
|
||||
const origin = opts.origin || this[kUrl].origin
|
||||
|
||||
const request = new Request(origin, opts, handler)
|
||||
|
||||
this[kQueue].push(request)
|
||||
if (this[kResuming]) {
|
||||
// Do nothing.
|
||||
} else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
|
||||
// Wait a tick in case stream/iterator is ended in the same tick.
|
||||
this[kResuming] = 1
|
||||
process.nextTick(resume, this)
|
||||
} else {
|
||||
resume(this, true)
|
||||
}
|
||||
|
||||
if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
|
||||
this[kNeedDrain] = 2
|
||||
}
|
||||
} catch (err) {
|
||||
if (typeof handler.onError !== 'function') {
|
||||
throw new InvalidArgumentError('invalid onError method')
|
||||
}
|
||||
|
||||
handler.onError(err)
|
||||
if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
|
||||
this[kNeedDrain] = 2
|
||||
}
|
||||
|
||||
return this[kNeedDrain] < 2
|
||||
}
|
||||
|
||||
close (callback) {
|
||||
if (callback === undefined) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.close((err, data) => {
|
||||
return err ? reject(err) : resolve(data)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (typeof callback !== 'function') {
|
||||
throw new InvalidArgumentError('invalid callback')
|
||||
}
|
||||
|
||||
if (this[kDestroyed]) {
|
||||
queueMicrotask(() => callback(new ClientDestroyedError(), null))
|
||||
return
|
||||
}
|
||||
|
||||
this[kClosed] = true
|
||||
|
||||
if (!this[kSize]) {
|
||||
this.destroy(callback)
|
||||
} else {
|
||||
this[kOnDestroyed].push(callback)
|
||||
}
|
||||
async [kClose] () {
|
||||
return new Promise((resolve) => {
|
||||
if (!this[kSize]) {
|
||||
this.destroy(resolve)
|
||||
} else {
|
||||
this[kClosedResolve] = resolve
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
destroy (err, callback) {
|
||||
if (typeof err === 'function') {
|
||||
callback = err
|
||||
err = null
|
||||
}
|
||||
async [kDestroy] (err) {
|
||||
return new Promise((resolve) => {
|
||||
const requests = this[kQueue].splice(this[kPendingIdx])
|
||||
for (let i = 0; i < requests.length; i++) {
|
||||
const request = requests[i]
|
||||
errorRequest(this, request, err)
|
||||
}
|
||||
|
||||
if (callback === undefined) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.destroy(err, (err, data) => {
|
||||
return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
|
||||
})
|
||||
})
|
||||
}
|
||||
const callback = () => {
|
||||
if (this[kClosedResolve]) {
|
||||
this[kClosedResolve]()
|
||||
this[kClosedResolve] = null
|
||||
}
|
||||
resolve()
|
||||
}
|
||||
|
||||
if (typeof callback !== 'function') {
|
||||
throw new InvalidArgumentError('invalid callback')
|
||||
}
|
||||
|
||||
if (this[kDestroyed]) {
|
||||
if (this[kOnDestroyed]) {
|
||||
this[kOnDestroyed].push(callback)
|
||||
if (!this[kSocket]) {
|
||||
queueMicrotask(callback)
|
||||
} else {
|
||||
queueMicrotask(() => callback(null, null))
|
||||
util.destroy(this[kSocket].on('close', callback), err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!err) {
|
||||
err = new ClientDestroyedError()
|
||||
}
|
||||
|
||||
const requests = this[kQueue].splice(this[kPendingIdx])
|
||||
for (let i = 0; i < requests.length; i++) {
|
||||
const request = requests[i]
|
||||
errorRequest(this, request, err)
|
||||
}
|
||||
|
||||
this[kClosed] = true
|
||||
this[kDestroyed] = true
|
||||
this[kOnDestroyed].push(callback)
|
||||
|
||||
const onDestroyed = () => {
|
||||
const callbacks = this[kOnDestroyed]
|
||||
this[kOnDestroyed] = null
|
||||
for (let i = 0; i < callbacks.length; i++) {
|
||||
callbacks[i](null, null)
|
||||
}
|
||||
}
|
||||
|
||||
if (!this[kSocket]) {
|
||||
queueMicrotask(onDestroyed)
|
||||
} else {
|
||||
util.destroy(this[kSocket].on('close', onDestroyed), err)
|
||||
}
|
||||
|
||||
resume(this)
|
||||
resume(this)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,7 +391,6 @@ async function lazyllhttp () {
|
||||
let llhttpInstance = null
|
||||
let llhttpPromise = lazyllhttp()
|
||||
.catch(() => {
|
||||
// TODO: Emit warning?
|
||||
})
|
||||
|
||||
let currentParser = null
|
||||
@@ -586,7 +500,6 @@ class Parser {
|
||||
currentBufferPtr = llhttp.malloc(currentBufferSize)
|
||||
}
|
||||
|
||||
// TODO (perf): Can we avoid this copy somehow?
|
||||
new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
|
||||
|
||||
// Call `execute` on the wasm parser.
|
||||
@@ -635,12 +548,10 @@ class Parser {
|
||||
try {
|
||||
try {
|
||||
currentParser = this
|
||||
this.llhttp.llhttp_finish(this.ptr) // TODO (fix): Check ret?
|
||||
} finally {
|
||||
currentParser = null
|
||||
}
|
||||
} catch (err) {
|
||||
// TODO (fix): What if socket is already destroyed? Error will be swallowed.
|
||||
/* istanbul ignore next: difficult to make a test case for */
|
||||
util.destroy(this.socket, err)
|
||||
}
|
||||
@@ -782,13 +693,9 @@ class Parser {
|
||||
return -1
|
||||
}
|
||||
|
||||
// TODO: Check for content-length mismatch from server?
|
||||
|
||||
assert(!this.upgrade)
|
||||
assert(this.statusCode < 200)
|
||||
|
||||
// TODO: More statusCode validation?
|
||||
|
||||
if (statusCode === 100) {
|
||||
util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
|
||||
return -1
|
||||
@@ -979,7 +886,6 @@ class Parser {
|
||||
util.destroy(socket, new InformationalError('reset'))
|
||||
return constants.ERROR.PAUSED
|
||||
} else if (!shouldKeepAlive) {
|
||||
// TODO: What if running > 0?
|
||||
util.destroy(socket, new InformationalError('reset'))
|
||||
return constants.ERROR.PAUSED
|
||||
} else if (socket[kReset] && client[kRunning] === 0) {
|
||||
@@ -1079,7 +985,7 @@ function onSocketClose () {
|
||||
|
||||
client[kSocket] = null
|
||||
|
||||
if (client[kDestroyed]) {
|
||||
if (client.destroyed) {
|
||||
assert(client[kPending] === 0)
|
||||
|
||||
// Fail entire queue.
|
||||
@@ -1251,14 +1157,14 @@ function resume (client, sync) {
|
||||
|
||||
function _resume (client, sync) {
|
||||
while (true) {
|
||||
if (client[kDestroyed]) {
|
||||
if (client.destroyed) {
|
||||
assert(client[kPending] === 0)
|
||||
return
|
||||
}
|
||||
|
||||
if (client[kClosed] && !client[kSize]) {
|
||||
client.destroy(util.nop)
|
||||
continue
|
||||
if (client.closed && !client[kSize]) {
|
||||
client.destroy()
|
||||
return
|
||||
}
|
||||
|
||||
const socket = client[kSocket]
|
||||
@@ -1479,8 +1385,6 @@ function write (client, request) {
|
||||
socket[kBlocking] = true
|
||||
}
|
||||
|
||||
// TODO: Expect: 100-continue
|
||||
|
||||
let header = `${method} ${path} HTTP/1.1\r\n`
|
||||
|
||||
if (typeof host === 'string') {
|
||||
@@ -1600,7 +1504,6 @@ function writeStream ({ body, client, request, socket, contentLength, header, ex
|
||||
|
||||
writer.destroy(err)
|
||||
|
||||
// TODO (fix): Avoid using err.message for logic.
|
||||
if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
|
||||
util.destroy(body, err)
|
||||
} else {
|
||||
@@ -1679,7 +1582,6 @@ async function writeIterable ({ body, client, request, socket, contentLength, he
|
||||
|
||||
const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
|
||||
try {
|
||||
// TODO (fix): What if socket errors while waiting for body?
|
||||
// It's up to the user to somehow abort the async iterable.
|
||||
for await (const chunk of body) {
|
||||
if (socket[kError]) {
|
||||
@@ -1730,7 +1632,6 @@ class AsyncWriter {
|
||||
return true
|
||||
}
|
||||
|
||||
// TODO: What if not ended and bytesWritten === contentLength?
|
||||
// We should defer writing chunks.
|
||||
if (contentLength !== null && bytesWritten + len > contentLength) {
|
||||
if (client[kStrictContentLength]) {
|
||||
@@ -1800,7 +1701,6 @@ class AsyncWriter {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO (fix): Add comment clarifying what this does?
|
||||
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
|
||||
// istanbul ignore else: only for jest
|
||||
if (socket[kParser].timeout.refresh) {
|
||||
|
||||
Vendored
+3
@@ -1,4 +1,7 @@
|
||||
module.exports = {
|
||||
kClose: Symbol('close'),
|
||||
kDestroy: Symbol('destroy'),
|
||||
kDispatch: Symbol('dispatch'),
|
||||
kUrl: Symbol('url'),
|
||||
kWriting: Symbol('writing'),
|
||||
kResuming: Symbol('resuming'),
|
||||
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
'use strict'
|
||||
|
||||
const Dispatcher = require('./dispatcher')
|
||||
const {
|
||||
ClientDestroyedError,
|
||||
ClientClosedError,
|
||||
InvalidArgumentError
|
||||
} = require('./core/errors')
|
||||
const { kDestroy, kClose, kDispatch } = require('./core/symbols')
|
||||
|
||||
const kDestroyed = Symbol('destroyed')
|
||||
const kClosed = Symbol('closed')
|
||||
const kOnDestroyed = Symbol('onDestroyed')
|
||||
const kOnClosed = Symbol('onClosed')
|
||||
|
||||
class DispatcherBase extends Dispatcher {
|
||||
constructor () {
|
||||
super()
|
||||
|
||||
this[kDestroyed] = false
|
||||
this[kOnDestroyed] = []
|
||||
this[kClosed] = false
|
||||
this[kOnClosed] = []
|
||||
}
|
||||
|
||||
get destroyed () {
|
||||
return this[kDestroyed]
|
||||
}
|
||||
|
||||
get closed () {
|
||||
return this[kClosed]
|
||||
}
|
||||
|
||||
close (callback) {
|
||||
if (callback === undefined) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.close((err, data) => {
|
||||
return err ? reject(err) : resolve(data)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (typeof callback !== 'function') {
|
||||
throw new InvalidArgumentError('invalid callback')
|
||||
}
|
||||
|
||||
if (this[kDestroyed]) {
|
||||
queueMicrotask(() => callback(new ClientDestroyedError(), null))
|
||||
return
|
||||
}
|
||||
|
||||
if (this[kClosed]) {
|
||||
if (this[kOnClosed]) {
|
||||
this[kOnClosed].push(callback)
|
||||
} else {
|
||||
queueMicrotask(() => callback(null, null))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
this[kClosed] = true
|
||||
this[kOnClosed].push(callback)
|
||||
|
||||
const onClosed = () => {
|
||||
const callbacks = this[kOnClosed]
|
||||
this[kOnClosed] = null
|
||||
for (let i = 0; i < callbacks.length; i++) {
|
||||
callbacks[i](null, null)
|
||||
}
|
||||
}
|
||||
|
||||
// Should not error.
|
||||
this[kClose]()
|
||||
.then(() => this.destroy())
|
||||
.then(() => {
|
||||
queueMicrotask(onClosed)
|
||||
})
|
||||
}
|
||||
|
||||
destroy (err, callback) {
|
||||
if (typeof err === 'function') {
|
||||
callback = err
|
||||
err = null
|
||||
}
|
||||
|
||||
if (callback === undefined) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.destroy(err, (err, data) => {
|
||||
return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (typeof callback !== 'function') {
|
||||
throw new InvalidArgumentError('invalid callback')
|
||||
}
|
||||
|
||||
if (this[kDestroyed]) {
|
||||
if (this[kOnDestroyed]) {
|
||||
this[kOnDestroyed].push(callback)
|
||||
} else {
|
||||
queueMicrotask(() => callback(null, null))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!err) {
|
||||
err = new ClientDestroyedError()
|
||||
}
|
||||
|
||||
this[kDestroyed] = true
|
||||
this[kOnDestroyed].push(callback)
|
||||
|
||||
const onDestroyed = () => {
|
||||
const callbacks = this[kOnDestroyed]
|
||||
this[kOnDestroyed] = null
|
||||
for (let i = 0; i < callbacks.length; i++) {
|
||||
callbacks[i](null, null)
|
||||
}
|
||||
}
|
||||
|
||||
// Should not error.
|
||||
this[kDestroy](err).then(() => {
|
||||
queueMicrotask(onDestroyed)
|
||||
})
|
||||
}
|
||||
|
||||
dispatch (opts, handler) {
|
||||
if (!handler || typeof handler !== 'object') {
|
||||
throw new InvalidArgumentError('handler must be an object')
|
||||
}
|
||||
|
||||
try {
|
||||
if (!opts || typeof opts !== 'object') {
|
||||
throw new InvalidArgumentError('opts must be an object.')
|
||||
}
|
||||
|
||||
if (this[kDestroyed]) {
|
||||
throw new ClientDestroyedError()
|
||||
}
|
||||
|
||||
if (this[kClosed]) {
|
||||
throw new ClientClosedError()
|
||||
}
|
||||
|
||||
return this[kDispatch](opts, handler)
|
||||
} catch (err) {
|
||||
if (typeof handler.onError !== 'function') {
|
||||
throw new InvalidArgumentError('invalid onError method')
|
||||
}
|
||||
|
||||
handler.onError(err)
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DispatcherBase
|
||||
+3
@@ -86,9 +86,12 @@ const subresource = [
|
||||
''
|
||||
]
|
||||
|
||||
const corsSafeListedResponseHeaderNames = [] // TODO
|
||||
|
||||
module.exports = {
|
||||
subresource,
|
||||
forbiddenResponseHeaderNames,
|
||||
corsSafeListedResponseHeaderNames,
|
||||
forbiddenMethods,
|
||||
requestBodyHeader,
|
||||
referrerPolicy,
|
||||
|
||||
Vendored
+4
-3
@@ -346,11 +346,12 @@ class Headers {
|
||||
const callback = args[0]
|
||||
const thisArg = args[1]
|
||||
|
||||
for (let index = 0; index < this[kHeadersList].length; index += 2) {
|
||||
const clone = this[kHeadersList].slice()
|
||||
for (let index = 0; index < clone.length; index += 2) {
|
||||
callback.call(
|
||||
thisArg,
|
||||
this[kHeadersList][index + 1],
|
||||
this[kHeadersList][index],
|
||||
clone[index + 1],
|
||||
clone[index],
|
||||
this
|
||||
)
|
||||
}
|
||||
|
||||
Vendored
+554
-508
File diff suppressed because it is too large.
Load diff
Vendored
+9
-17
@@ -7,9 +7,9 @@ const { Headers, fill: fillHeaders, HeadersList } = require('./headers')
|
||||
const util = require('../core/util')
|
||||
const {
|
||||
isValidHTTPToken,
|
||||
EnvironmentSettingsObject,
|
||||
sameOrigin,
|
||||
toUSVString
|
||||
toUSVString,
|
||||
normalizeMethod
|
||||
} = require('./util')
|
||||
const {
|
||||
forbiddenMethods,
|
||||
@@ -81,9 +81,7 @@ class Request {
|
||||
try {
|
||||
parsedURL = new URL(input, baseUrl)
|
||||
} catch (err) {
|
||||
const error = new TypeError('Failed to parse URL from ' + input)
|
||||
error.cause = err
|
||||
throw error
|
||||
throw new TypeError('Failed to parse URL from ' + input, { cause: err })
|
||||
}
|
||||
|
||||
// 3. If parsedURL includes credentials, then throw a TypeError.
|
||||
@@ -121,7 +119,7 @@ class Request {
|
||||
// 9. If request’s window is an environment settings object and its origin
|
||||
// is same origin with origin, then set window to request’s window.
|
||||
if (
|
||||
request.window instanceof EnvironmentSettingsObject &&
|
||||
request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
|
||||
sameOrigin(request.window, origin)
|
||||
) {
|
||||
window = request.window
|
||||
@@ -149,7 +147,7 @@ class Request {
|
||||
// unsafe-request flag Set.
|
||||
unsafeRequest: request.unsafeRequest,
|
||||
// client This’s relevant settings object.
|
||||
client: request.client,
|
||||
client: this[kRealm].settingsObject,
|
||||
// window window.
|
||||
window,
|
||||
// priority request’s priority.
|
||||
@@ -179,8 +177,7 @@ class Request {
|
||||
// history-navigation flag request’s history-navigation flag.
|
||||
historyNavigation: request.historyNavigation,
|
||||
// URL list A clone of request’s URL list.
|
||||
// undici implementation note: urlList is cloned in makeRequest
|
||||
urlList: request.urlList
|
||||
urlList: [...request.urlList]
|
||||
})
|
||||
|
||||
// 13. If init is not empty, then:
|
||||
@@ -228,11 +225,7 @@ class Request {
|
||||
try {
|
||||
parsedReferrer = new URL(referrer, baseUrl)
|
||||
} catch (err) {
|
||||
const error = new TypeError(
|
||||
`Referrer "${referrer}" is not a valid URL.`
|
||||
)
|
||||
error.cause = err
|
||||
throw error
|
||||
throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
|
||||
}
|
||||
|
||||
// 3. If one of the following is true
|
||||
@@ -346,8 +339,7 @@ class Request {
|
||||
}
|
||||
|
||||
// 3. Normalize method.
|
||||
// https://fetch.spec.whatwg.org/#concept-method-normalize
|
||||
method = init.method.toUpperCase()
|
||||
method = normalizeMethod(init.method)
|
||||
|
||||
// 4. Set request’s method to method.
|
||||
request.method = method
|
||||
@@ -722,7 +714,7 @@ class Request {
|
||||
}
|
||||
|
||||
// 1. If this is unusable, then throw a TypeError.
|
||||
if (this.bodyUsed || (this.body && this.body.locked)) {
|
||||
if (this.bodyUsed || this.body?.locked) {
|
||||
throw new TypeError('unusable')
|
||||
}
|
||||
|
||||
|
||||
+79
-30
@@ -1,14 +1,16 @@
|
||||
'use strict'
|
||||
|
||||
const { Headers, HeadersList, fill } = require('./headers')
|
||||
const { AbortError } = require('../core/errors')
|
||||
const { extractBody, cloneBody, mixinBody } = require('./body')
|
||||
const util = require('../core/util')
|
||||
const { kEnumerableProperty } = util
|
||||
const { responseURL, isValidReasonPhrase, toUSVString } = require('./util')
|
||||
const { responseURL, isValidReasonPhrase, toUSVString, isCancelled, isAborted } = require('./util')
|
||||
const {
|
||||
redirectStatus,
|
||||
nullBodyStatus,
|
||||
forbiddenResponseHeaderNames
|
||||
forbiddenResponseHeaderNames,
|
||||
corsSafeListedResponseHeaderNames
|
||||
} = require('./constants')
|
||||
const { kState, kHeaders, kGuard, kRealm } = require('./symbols')
|
||||
const { kHeadersList } = require('../core/symbols')
|
||||
@@ -337,10 +339,10 @@ function cloneResponse (response) {
|
||||
|
||||
function makeResponse (init) {
|
||||
return {
|
||||
internalResponse: null,
|
||||
aborted: false,
|
||||
rangeRequested: false,
|
||||
timingAllowPassed: false,
|
||||
requestIncludesCredentials: false,
|
||||
type: 'default',
|
||||
status: 200,
|
||||
timingInfo: null,
|
||||
@@ -361,11 +363,55 @@ function makeNetworkError (reason) {
|
||||
error:
|
||||
reason instanceof Error
|
||||
? reason
|
||||
: new Error(reason ? String(reason) : reason),
|
||||
: new Error(reason ? String(reason) : reason, {
|
||||
cause: reason instanceof Error ? reason : undefined
|
||||
}),
|
||||
aborted: reason && reason.name === 'AbortError'
|
||||
})
|
||||
}
|
||||
|
||||
function makeFilteredResponse (response, state) {
|
||||
state = {
|
||||
internalResponse: response,
|
||||
...state
|
||||
}
|
||||
|
||||
return new Proxy(response, {
|
||||
get (target, p) {
|
||||
return p in state ? state[p] : target[p]
|
||||
},
|
||||
set (target, p, value) {
|
||||
assert(!(p in state))
|
||||
target[p] = value
|
||||
return true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function makeFilteredHeadersList (headersList, filter) {
|
||||
return new Proxy(headersList, {
|
||||
get (target, prop) {
|
||||
// Override methods used by Headers class.
|
||||
if (prop === 'get' || prop === 'has') {
|
||||
return (name) => filter(name) ? target[prop](name) : undefined
|
||||
} else if (prop === 'slice') {
|
||||
return (...args) => {
|
||||
assert(args.length === 0)
|
||||
const arr = []
|
||||
for (let index = 0; index < target.length; index += 2) {
|
||||
if (filter(target[index])) {
|
||||
arr.push(target[index], target[index + 1])
|
||||
}
|
||||
}
|
||||
return arr
|
||||
}
|
||||
} else {
|
||||
return target[prop]
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// https://fetch.spec.whatwg.org/#concept-filtered-response
|
||||
function filterResponse (response, type) {
|
||||
// Set response to the following filtered response with response as its
|
||||
@@ -375,18 +421,9 @@ function filterResponse (response, type) {
|
||||
// and header list excludes any headers in internal response’s header list
|
||||
// whose name is a forbidden response-header name.
|
||||
|
||||
const headers = []
|
||||
for (let n = 0; n < response.headersList.length; n += 2) {
|
||||
if (!forbiddenResponseHeaderNames.includes(response.headersList[n])) {
|
||||
headers.push(response.headersList[n + 0], response.headersList[n + 1])
|
||||
}
|
||||
}
|
||||
|
||||
return makeResponse({
|
||||
...response,
|
||||
internalResponse: response,
|
||||
headersList: new HeadersList(...headers),
|
||||
type: 'basic'
|
||||
return makeFilteredResponse(response, {
|
||||
type: 'basic',
|
||||
headersList: makeFilteredHeadersList(response.headersList, (name) => !forbiddenResponseHeaderNames.includes(name))
|
||||
})
|
||||
} else if (type === 'cors') {
|
||||
// A CORS filtered response is a filtered response whose type is "cors"
|
||||
@@ -394,22 +431,18 @@ function filterResponse (response, type) {
|
||||
// list whose name is not a CORS-safelisted response-header name, given
|
||||
// internal response’s CORS-exposed header-name list.
|
||||
|
||||
// TODO: This is not correct...
|
||||
return makeResponse({
|
||||
...response,
|
||||
internalResponse: response,
|
||||
type: 'cors'
|
||||
return makeFilteredResponse(response, {
|
||||
type: 'cors',
|
||||
headersList: makeFilteredHeadersList(response.headersList, (name) => !corsSafeListedResponseHeaderNames.includes(name))
|
||||
})
|
||||
} else if (type === 'opaque') {
|
||||
// An opaque filtered response is a filtered response whose type is
|
||||
// "opaque", URL list is the empty list, status is 0, status message
|
||||
// is the empty byte sequence, header list is empty, and body is null.
|
||||
|
||||
return makeResponse({
|
||||
...response,
|
||||
internalResponse: response,
|
||||
return makeFilteredResponse(response, {
|
||||
type: 'opaque',
|
||||
urlList: [],
|
||||
urlList: Object.freeze([]),
|
||||
status: 0,
|
||||
statusText: '',
|
||||
body: null
|
||||
@@ -419,13 +452,11 @@ function filterResponse (response, type) {
|
||||
// is "opaqueredirect", status is 0, status message is the empty byte
|
||||
// sequence, header list is empty, and body is null.
|
||||
|
||||
return makeResponse({
|
||||
...response,
|
||||
internalResponse: response,
|
||||
return makeFilteredResponse(response, {
|
||||
type: 'opaqueredirect',
|
||||
status: 0,
|
||||
statusText: '',
|
||||
headersList: new HeadersList(),
|
||||
headersList: makeFilteredHeadersList(response.headersList, () => false),
|
||||
body: null
|
||||
})
|
||||
} else {
|
||||
@@ -433,4 +464,22 @@ function filterResponse (response, type) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { makeNetworkError, makeResponse, filterResponse, Response }
|
||||
// https://fetch.spec.whatwg.org/#appropriate-network-error
|
||||
function makeAppropriateNetworkError (fetchParams) {
|
||||
// 1. Assert: fetchParams is canceled.
|
||||
assert(isCancelled(fetchParams))
|
||||
|
||||
// 2. Return an aborted network error if fetchParams is aborted;
|
||||
// otherwise return a network error.
|
||||
return isAborted(fetchParams)
|
||||
? makeNetworkError(new AbortError())
|
||||
: makeNetworkError(fetchParams.controller.terminated.reason)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
makeNetworkError,
|
||||
makeResponse,
|
||||
makeAppropriateNetworkError,
|
||||
filterResponse,
|
||||
Response
|
||||
}
|
||||
Vendored
+20
-8
@@ -195,7 +195,7 @@ function appendFetchMetadata (httpRequest) {
|
||||
header = httpRequest.mode
|
||||
|
||||
// 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
|
||||
httpRequest.headersList.append('sec-fetch-mode', header)
|
||||
httpRequest.headersList.set('sec-fetch-mode', header)
|
||||
|
||||
// https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
|
||||
// TODO
|
||||
@@ -333,14 +333,25 @@ function createDeferredPromise () {
|
||||
return { promise, resolve: res, reject: rej }
|
||||
}
|
||||
|
||||
class ServiceWorkerGlobalScope {} // dummy
|
||||
class Window {} // dummy
|
||||
class EnvironmentSettingsObject {} // dummy
|
||||
function isAborted (fetchParams) {
|
||||
return fetchParams.controller.state === 'aborted'
|
||||
}
|
||||
|
||||
function isCancelled (fetchParams) {
|
||||
return fetchParams.controller.state === 'aborted' ||
|
||||
fetchParams.controller.state === 'terminated'
|
||||
}
|
||||
|
||||
// https://fetch.spec.whatwg.org/#concept-method-normalize
|
||||
function normalizeMethod (method) {
|
||||
return /^(DELETE|GET|HEAD|OPTIONS|POST|PUT)$/i.test(method)
|
||||
? method.toUpperCase()
|
||||
: method
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ServiceWorkerGlobalScope,
|
||||
Window,
|
||||
EnvironmentSettingsObject,
|
||||
isAborted,
|
||||
isCancelled,
|
||||
createDeferredPromise,
|
||||
ReadableStreamFrom,
|
||||
toUSVString,
|
||||
@@ -366,5 +377,6 @@ module.exports = {
|
||||
isFileLike,
|
||||
isValidReasonPhrase,
|
||||
sameOrigin,
|
||||
CORBCheck
|
||||
CORBCheck,
|
||||
normalizeMethod
|
||||
}
|
||||
+1
-1
@@ -64,7 +64,7 @@ class MockInterceptor {
|
||||
throw new InvalidArgumentError('opts.path must be defined')
|
||||
}
|
||||
if (typeof opts.method === 'undefined') {
|
||||
throw new InvalidArgumentError('opts.method must be defined')
|
||||
opts.method = 'GET'
|
||||
}
|
||||
// See https://github.com/nodejs/undici/issues/1245
|
||||
// As per RFC 3986, clients are not supposed to send URI
|
||||
|
||||
+8
@@ -33,6 +33,14 @@ function lowerCaseEntries (headers) {
|
||||
|
||||
function matchHeaders (mockDispatch, headers) {
|
||||
if (typeof mockDispatch.headers === 'function') {
|
||||
if (Array.isArray(headers)) { // fetch HeadersList
|
||||
const clone = headers.slice()
|
||||
const entries = []
|
||||
for (let index = 0; index < clone.length; index += 2) {
|
||||
entries.push([clone[index], clone[index + 1]])
|
||||
}
|
||||
headers = Object.fromEntries(entries)
|
||||
}
|
||||
return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
|
||||
}
|
||||
if (typeof mockDispatch.headers === 'undefined') {
|
||||
|
||||
Vendored
+21
-99
@@ -1,20 +1,13 @@
|
||||
'use strict'
|
||||
|
||||
const Dispatcher = require('./dispatcher')
|
||||
const {
|
||||
ClientDestroyedError,
|
||||
ClientClosedError,
|
||||
InvalidArgumentError
|
||||
} = require('./core/errors')
|
||||
const DispatcherBase = require('./dispatcher-base')
|
||||
const FixedQueue = require('./node/fixed-queue')
|
||||
const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl } = require('./core/symbols')
|
||||
const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('./core/symbols')
|
||||
const PoolStats = require('./pool-stats')
|
||||
|
||||
const kClients = Symbol('clients')
|
||||
const kNeedDrain = Symbol('needDrain')
|
||||
const kQueue = Symbol('queue')
|
||||
const kDestroyed = Symbol('destroyed')
|
||||
const kClosedPromise = Symbol('closed promise')
|
||||
const kClosedResolve = Symbol('closed resolve')
|
||||
const kOnDrain = Symbol('onDrain')
|
||||
const kOnConnect = Symbol('onConnect')
|
||||
@@ -25,16 +18,12 @@ const kAddClient = Symbol('add client')
|
||||
const kRemoveClient = Symbol('remove client')
|
||||
const kStats = Symbol('stats')
|
||||
|
||||
class PoolBase extends Dispatcher {
|
||||
class PoolBase extends DispatcherBase {
|
||||
constructor () {
|
||||
super()
|
||||
|
||||
this[kQueue] = new FixedQueue()
|
||||
this[kClosedPromise] = null
|
||||
this[kClosedResolve] = null
|
||||
this[kDestroyed] = false
|
||||
this[kClients] = []
|
||||
this[kNeedDrain] = false
|
||||
this[kQueued] = 0
|
||||
|
||||
const pool = this
|
||||
@@ -122,59 +111,17 @@ class PoolBase extends Dispatcher {
|
||||
return this[kStats]
|
||||
}
|
||||
|
||||
get destroyed () {
|
||||
return this[kDestroyed]
|
||||
}
|
||||
|
||||
get closed () {
|
||||
return this[kClosedPromise] != null
|
||||
}
|
||||
|
||||
close (cb) {
|
||||
try {
|
||||
if (this[kDestroyed]) {
|
||||
throw new ClientDestroyedError()
|
||||
}
|
||||
|
||||
if (!this[kClosedPromise]) {
|
||||
if (this[kQueue].isEmpty()) {
|
||||
this[kClosedPromise] = Promise.all(this[kClients].map(c => c.close()))
|
||||
} else {
|
||||
this[kClosedPromise] = new Promise((resolve) => {
|
||||
this[kClosedResolve] = resolve
|
||||
})
|
||||
}
|
||||
this[kClosedPromise] = this[kClosedPromise].then(() => {
|
||||
this[kDestroyed] = true
|
||||
})
|
||||
}
|
||||
|
||||
if (cb) {
|
||||
this[kClosedPromise].then(() => cb(null, null))
|
||||
} else {
|
||||
return this[kClosedPromise]
|
||||
}
|
||||
} catch (err) {
|
||||
if (cb) {
|
||||
cb(err)
|
||||
} else {
|
||||
return Promise.reject(err)
|
||||
}
|
||||
async [kClose] () {
|
||||
if (this[kQueue].isEmpty()) {
|
||||
return Promise.all(this[kClients].map(c => c.close()))
|
||||
} else {
|
||||
return new Promise((resolve) => {
|
||||
this[kClosedResolve] = resolve
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
destroy (err, cb) {
|
||||
this[kDestroyed] = true
|
||||
|
||||
if (typeof err === 'function') {
|
||||
cb = err
|
||||
err = null
|
||||
}
|
||||
|
||||
if (!err) {
|
||||
err = new ClientDestroyedError()
|
||||
}
|
||||
|
||||
async [kDestroy] (err) {
|
||||
while (true) {
|
||||
const item = this[kQueue].shift()
|
||||
if (!item) {
|
||||
@@ -183,44 +130,19 @@ class PoolBase extends Dispatcher {
|
||||
item.handler.onError(err)
|
||||
}
|
||||
|
||||
const promise = Promise.all(this[kClients].map(c => c.destroy(err)))
|
||||
if (cb) {
|
||||
promise.then(() => cb(null, null))
|
||||
} else {
|
||||
return promise
|
||||
}
|
||||
return Promise.all(this[kClients].map(c => c.destroy(err)))
|
||||
}
|
||||
|
||||
dispatch (opts, handler) {
|
||||
if (!handler || typeof handler !== 'object') {
|
||||
throw new InvalidArgumentError('handler must be an object')
|
||||
}
|
||||
[kDispatch] (opts, handler) {
|
||||
const dispatcher = this[kGetDispatcher]()
|
||||
|
||||
try {
|
||||
if (this[kDestroyed]) {
|
||||
throw new ClientDestroyedError()
|
||||
}
|
||||
|
||||
if (this[kClosedPromise]) {
|
||||
throw new ClientClosedError()
|
||||
}
|
||||
|
||||
const dispatcher = this[kGetDispatcher]()
|
||||
|
||||
if (!dispatcher) {
|
||||
this[kNeedDrain] = true
|
||||
this[kQueue].push({ opts, handler })
|
||||
this[kQueued]++
|
||||
} else if (!dispatcher.dispatch(opts, handler)) {
|
||||
dispatcher[kNeedDrain] = true
|
||||
this[kNeedDrain] = !this[kGetDispatcher]()
|
||||
}
|
||||
} catch (err) {
|
||||
if (typeof handler.onError !== 'function') {
|
||||
throw new InvalidArgumentError('invalid onError method')
|
||||
}
|
||||
|
||||
handler.onError(err)
|
||||
if (!dispatcher) {
|
||||
this[kNeedDrain] = true
|
||||
this[kQueue].push({ opts, handler })
|
||||
this[kQueued]++
|
||||
} else if (!dispatcher.dispatch(opts, handler)) {
|
||||
dispatcher[kNeedDrain] = true
|
||||
this[kNeedDrain] = !this[kGetDispatcher]()
|
||||
}
|
||||
|
||||
return !this[kNeedDrain]
|
||||
|
||||
Vendored
+8
-4
@@ -1,14 +1,14 @@
|
||||
'use strict'
|
||||
|
||||
const { kProxy } = require('./core/symbols')
|
||||
const { kProxy, kClose, kDestroy } = require('./core/symbols')
|
||||
const { URL } = require('url')
|
||||
const Agent = require('./agent')
|
||||
const Dispatcher = require('./dispatcher')
|
||||
const DispatcherBase = require('./dispatcher-base')
|
||||
const { InvalidArgumentError } = require('./core/errors')
|
||||
|
||||
const kAgent = Symbol('proxy agent')
|
||||
|
||||
class ProxyAgent extends Dispatcher {
|
||||
class ProxyAgent extends DispatcherBase {
|
||||
constructor (opts) {
|
||||
super(opts)
|
||||
this[kProxy] = buildProxyOptions(opts)
|
||||
@@ -31,9 +31,13 @@ class ProxyAgent extends Dispatcher {
|
||||
)
|
||||
}
|
||||
|
||||
async close () {
|
||||
async [kClose] () {
|
||||
await this[kAgent].close()
|
||||
}
|
||||
|
||||
async [kDestroy] () {
|
||||
await this[kAgent].destroy()
|
||||
}
|
||||
}
|
||||
|
||||
function buildProxyOptions (opts) {
|
||||
|
||||
Vendored
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "undici",
|
||||
"version": "4.16.0",
|
||||
"version": "5.0.0",
|
||||
"description": "An HTTP/1.1 client, written from scratch for Node.js",
|
||||
"homepage": "https://undici.nodejs.org",
|
||||
"bugs": {
|
||||
@@ -54,10 +54,10 @@
|
||||
"test:typescript": "tsd",
|
||||
"coverage": "nyc --reporter=text --reporter=html npm run test",
|
||||
"coverage:ci": "nyc --reporter=lcov npm run test",
|
||||
"bench": "concurrently -k -s first npm:bench:server npm:bench:run",
|
||||
"bench": "PORT=3042 concurrently -k -s first npm:bench:server npm:bench:run",
|
||||
"bench:server": "node benchmarks/server.js",
|
||||
"prebench:run": "node benchmarks/wait.js",
|
||||
"bench:run": "CONNECTIONS=1 node --experimental-wasm-simd benchmarks/benchmark.js && CONNECTIONS=50 node --experimental-wasm-simd benchmarks/benchmark.js",
|
||||
"bench:run": "CONNECTIONS=1 node --experimental-wasm-simd benchmarks/benchmark.js; CONNECTIONS=50 node --experimental-wasm-simd benchmarks/benchmark.js",
|
||||
"serve:website": "docsify serve .",
|
||||
"prepare": "husky install",
|
||||
"fuzz": "jsfuzz test/fuzzing/fuzz.js corpus"
|
||||
|
||||
+2
-2
@@ -44,8 +44,8 @@ declare namespace MockInterceptor {
|
||||
export interface Options {
|
||||
/** Path to intercept on. */
|
||||
path: string | RegExp | ((path: string) => boolean);
|
||||
/** Method to intercept on. */
|
||||
method: string | RegExp | ((method: string) => boolean);
|
||||
/** Method to intercept on. Defaults to GET. */
|
||||
method?: string | RegExp | ((method: string) => boolean);
|
||||
/** Body to intercept on. */
|
||||
body?: string | RegExp | ((body: string) => boolean);
|
||||
/** Headers to intercept on. */
|
||||
|
||||
Vendored
+621
-571
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user