Skip to content

Latest commit

 

History

History
348 lines (299 loc) · 8.46 KB

File metadata and controls

348 lines (299 loc) · 8.46 KB
 
Jun 24, 2015
Jun 24, 2015
1
var capability = require('./capability')
Jul 13, 2015
Jul 13, 2015
2
var inherits = require('inherits')
Jun 24, 2015
Jun 24, 2015
3
var response = require('./response')
Apr 27, 2016
Apr 27, 2016
4
var stream = require('readable-stream')
Jun 24, 2015
Jun 24, 2015
5
6
var IncomingMessage = response.IncomingMessage
7
var rStates = response.readyStates
8
Sep 1, 2016
Sep 1, 2016
9
function decideMode (preferBinary, useFetch) {
10
if (capability.fetch && useFetch) {
Jul 2, 2015
Jul 2, 2015
11
return 'fetch'
12
} else if (capability.mozchunkedarraybuffer) {
13
return 'moz-chunked-arraybuffer'
14
} else if (capability.msstream) {
15
return 'ms-stream'
16
} else if (capability.arraybuffer && preferBinary) {
17
return 'arraybuffer'
18
} else {
19
return 'text'
20
}
21
}
22
Jun 24, 2015
Jun 24, 2015
23
var ClientRequest = module.exports = function (opts) {
24
var self = this
25
stream.Writable.call(self)
26
27
self._opts = opts
28
self._body = []
Jul 7, 2015
Jul 7, 2015
29
self._headers = {}
Jul 7, 2015
Jul 7, 2015
30
if (opts.auth)
Sep 24, 2018
Sep 24, 2018
31
self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64'))
Sep 15, 2015
Sep 15, 2015
32
Object.keys(opts.headers).forEach(function (name) {
Jun 24, 2015
Jun 24, 2015
33
self.setHeader(name, opts.headers[name])
34
})
35
Jul 2, 2015
Jul 2, 2015
36
var preferBinary
Sep 1, 2016
Sep 1, 2016
37
var useFetch = true
Jan 15, 2018
Jan 15, 2018
38
if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
Jan 15, 2018
Jan 15, 2018
39
// If the use of XHR should be preferred. Not typically needed.
Sep 1, 2016
Sep 1, 2016
40
useFetch = false
41
preferBinary = true
42
} else if (opts.mode === 'prefer-streaming') {
Aug 20, 2015
Aug 20, 2015
43
// If streaming is a high priority but binary compatibility and
44
// the accuracy of the 'content-type' header aren't
Jul 2, 2015
Jul 2, 2015
45
preferBinary = false
Aug 20, 2015
Aug 20, 2015
46
} else if (opts.mode === 'allow-wrong-content-type') {
47
// If streaming is more important than preserving the 'content-type' header
Jul 2, 2015
Jul 2, 2015
48
preferBinary = !capability.overrideMimeType
Aug 20, 2015
Aug 20, 2015
49
} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
50
// Use binary if text streaming may corrupt data or the content-type header, or for speed
51
preferBinary = true
Jul 2, 2015
Jul 2, 2015
52
} else {
53
throw new Error('Invalid value for opts.mode')
54
}
Sep 1, 2016
Sep 1, 2016
55
self._mode = decideMode(preferBinary, useFetch)
May 9, 2018
May 9, 2018
56
self._fetchTimer = null
Apr 13, 2021
Apr 13, 2021
57
self._socketTimeout = null
58
self._socketTimer = null
Jun 24, 2015
Jun 24, 2015
59
Jul 2, 2015
Jul 2, 2015
60
self.on('finish', function () {
61
self._onFinish()
62
})
Jun 24, 2015
Jun 24, 2015
63
}
64
Jul 3, 2015
Jul 3, 2015
65
inherits(ClientRequest, stream.Writable)
Jun 24, 2015
Jun 24, 2015
66
67
ClientRequest.prototype.setHeader = function (name, value) {
68
var self = this
Jul 13, 2015
Jul 13, 2015
69
var lowerName = name.toLowerCase()
70
// This check is not necessary, but it prevents warnings from browsers about setting unsafe
71
// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
72
// http-browserify did it, so I will too.
Sep 15, 2015
Sep 15, 2015
73
if (unsafeHeaders.indexOf(lowerName) !== -1)
Jul 13, 2015
Jul 13, 2015
74
return
75
76
self._headers[lowerName] = {
Jul 7, 2015
Jul 7, 2015
77
name: name,
78
value: value
79
}
Jun 24, 2015
Jun 24, 2015
80
}
81
82
ClientRequest.prototype.getHeader = function (name) {
Apr 26, 2017
Apr 26, 2017
83
var header = this._headers[name.toLowerCase()]
84
if (header)
85
return header.value
86
return null
Jun 24, 2015
Jun 24, 2015
87
}
88
89
ClientRequest.prototype.removeHeader = function (name) {
90
var self = this
Jul 7, 2015
Jul 7, 2015
91
delete self._headers[name.toLowerCase()]
Jun 24, 2015
Jun 24, 2015
92
}
93
94
ClientRequest.prototype._onFinish = function () {
95
var self = this
96
Jul 13, 2015
Jul 13, 2015
97
if (self._destroyed)
98
return
Jun 24, 2015
Jun 24, 2015
99
var opts = self._opts
100
Jul 7, 2015
Jul 7, 2015
101
var headersObj = self._headers
Jan 16, 2017
Jan 16, 2017
102
var body = null
Apr 4, 2017
Apr 4, 2017
103
if (opts.method !== 'GET' && opts.method !== 'HEAD') {
Sep 24, 2018
Sep 24, 2018
104
body = new Blob(self._body, {
105
type: (headersObj['content-type'] || {}).value || ''
106
});
107
}
Jun 24, 2015
Jun 24, 2015
108
Apr 4, 2017
Apr 4, 2017
109
// create flattened list of headers
110
var headersList = []
111
Object.keys(headersObj).forEach(function (keyName) {
112
var name = headersObj[keyName].name
113
var value = headersObj[keyName].value
114
if (Array.isArray(value)) {
115
value.forEach(function (v) {
116
headersList.push([name, v])
117
})
118
} else {
119
headersList.push([name, value])
120
}
121
})
Jun 24, 2015
Jun 24, 2015
122
Apr 4, 2017
Apr 4, 2017
123
if (self._mode === 'fetch') {
Jan 15, 2018
Jan 15, 2018
124
var signal = null
125
if (capability.abortController) {
126
var controller = new AbortController()
127
signal = controller.signal
128
self._fetchAbortController = controller
129
Jan 15, 2018
Jan 15, 2018
130
if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
May 9, 2018
May 9, 2018
131
self._fetchTimer = global.setTimeout(function () {
Jan 15, 2018
Jan 15, 2018
132
self.emit('requestTimeout')
Jan 15, 2018
Jan 15, 2018
133
if (self._fetchAbortController)
134
self._fetchAbortController.abort()
Jan 15, 2018
Jan 15, 2018
135
}, opts.requestTimeout)
Jan 15, 2018
Jan 15, 2018
136
}
137
}
138
Sep 15, 2015
Sep 15, 2015
139
global.fetch(self._opts.url, {
Jun 24, 2015
Jun 24, 2015
140
method: self._opts.method,
Apr 4, 2017
Apr 4, 2017
141
headers: headersList,
Jan 18, 2017
Jan 18, 2017
142
body: body || undefined,
Jun 24, 2015
Jun 24, 2015
143
mode: 'cors',
Jan 15, 2018
Jan 15, 2018
144
credentials: opts.withCredentials ? 'include' : 'same-origin',
145
signal: signal
Jun 24, 2015
Jun 24, 2015
146
}).then(function (response) {
147
self._fetchResponse = response
Apr 13, 2021
Apr 13, 2021
148
self._resetTimers(false)
Jun 24, 2015
Jun 24, 2015
149
self._connect()
Oct 2, 2015
Oct 2, 2015
150
}, function (reason) {
Apr 13, 2021
Apr 13, 2021
151
self._resetTimers(true)
May 9, 2018
May 9, 2018
152
if (!self._destroyed)
153
self.emit('error', reason)
Jun 24, 2015
Jun 24, 2015
154
})
155
} else {
Sep 15, 2015
Sep 15, 2015
156
var xhr = self._xhr = new global.XMLHttpRequest()
Jul 8, 2015
Jul 8, 2015
157
try {
Sep 12, 2015
Sep 12, 2015
158
xhr.open(self._opts.method, self._opts.url, true)
Jul 8, 2015
Jul 8, 2015
159
} catch (err) {
160
process.nextTick(function () {
161
self.emit('error', err)
162
})
163
return
164
}
Jun 24, 2015
Jun 24, 2015
165
166
// Can't set responseType on really old browsers
167
if ('responseType' in xhr)
Sep 24, 2018
Sep 24, 2018
168
xhr.responseType = self._mode
Jun 24, 2015
Jun 24, 2015
169
170
if ('withCredentials' in xhr)
Jul 7, 2015
Jul 7, 2015
171
xhr.withCredentials = !!opts.withCredentials
Jun 24, 2015
Jun 24, 2015
172
173
if (self._mode === 'text' && 'overrideMimeType' in xhr)
174
xhr.overrideMimeType('text/plain; charset=x-user-defined')
175
Jan 15, 2018
Jan 15, 2018
176
if ('requestTimeout' in opts) {
177
xhr.timeout = opts.requestTimeout
Oct 18, 2016
Oct 18, 2016
178
xhr.ontimeout = function () {
Jan 15, 2018
Jan 15, 2018
179
self.emit('requestTimeout')
Oct 18, 2016
Oct 18, 2016
180
}
181
}
182
Apr 4, 2017
Apr 4, 2017
183
headersList.forEach(function (header) {
184
xhr.setRequestHeader(header[0], header[1])
Jun 24, 2015
Jun 24, 2015
185
})
186
Jul 3, 2015
Jul 3, 2015
187
self._response = null
Jun 24, 2015
Jun 24, 2015
188
xhr.onreadystatechange = function () {
189
switch (xhr.readyState) {
190
case rStates.LOADING:
191
case rStates.DONE:
Jul 8, 2015
Jul 8, 2015
192
self._onXHRProgress()
Jun 24, 2015
Jun 24, 2015
193
break
194
}
195
}
Jul 2, 2015
Jul 2, 2015
196
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
197
// in onprogress, not in onreadystatechange with xhr.readyState = 3
198
if (self._mode === 'moz-chunked-arraybuffer') {
199
xhr.onprogress = function () {
Jul 8, 2015
Jul 8, 2015
200
self._onXHRProgress()
Jul 2, 2015
Jul 2, 2015
201
}
202
}
Jun 24, 2015
Jun 24, 2015
203
Jul 8, 2015
Jul 8, 2015
204
xhr.onerror = function () {
Jul 13, 2015
Jul 13, 2015
205
if (self._destroyed)
206
return
Apr 13, 2021
Apr 13, 2021
207
self._resetTimers(true)
Jul 8, 2015
Jul 8, 2015
208
self.emit('error', new Error('XHR error'))
209
}
210
211
try {
212
xhr.send(body)
213
} catch (err) {
214
process.nextTick(function () {
215
self.emit('error', err)
216
})
217
return
218
}
Jun 24, 2015
Jun 24, 2015
219
}
220
}
221
Jul 3, 2015
Jul 3, 2015
222
/**
Oct 13, 2015
Oct 13, 2015
223
* Checks if xhr.status is readable and non-zero, indicating no error.
224
* Even though the spec says it should be available in readyState 3,
225
* accessing it throws an exception in IE8
Jul 3, 2015
Jul 3, 2015
226
*/
227
function statusValid (xhr) {
228
try {
Oct 13, 2015
Oct 13, 2015
229
var status = xhr.status
230
return (status !== null && status !== 0)
Jul 3, 2015
Jul 3, 2015
231
} catch (e) {
232
return false
233
}
234
}
235
Jul 8, 2015
Jul 8, 2015
236
ClientRequest.prototype._onXHRProgress = function () {
237
var self = this
238
Apr 13, 2021
Apr 13, 2021
239
self._resetTimers(false)
240
Jul 13, 2015
Jul 13, 2015
241
if (!statusValid(self._xhr) || self._destroyed)
Jul 8, 2015
Jul 8, 2015
242
return
243
244
if (!self._response)
245
self._connect()
246
247
self._response._onXHRProgress()
248
}
249
Jun 24, 2015
Jun 24, 2015
250
ClientRequest.prototype._connect = function () {
251
var self = this
252
Jul 13, 2015
Jul 13, 2015
253
if (self._destroyed)
254
return
255
Apr 13, 2021
Apr 13, 2021
256
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._resetTimers.bind(self))
Jan 4, 2017
Jan 4, 2017
257
self._response.on('error', function(err) {
258
self.emit('error', err)
259
})
260
Jun 24, 2015
Jun 24, 2015
261
self.emit('response', self._response)
262
}
263
264
ClientRequest.prototype._write = function (chunk, encoding, cb) {
265
var self = this
266
267
self._body.push(chunk)
268
cb()
269
}
270
Apr 13, 2021
Apr 13, 2021
271
ClientRequest.prototype._resetTimers = function (done) {
272
var self = this
273
274
global.clearTimeout(self._socketTimer)
275
self._socketTimer = null
276
277
if (done) {
278
global.clearTimeout(self._fetchTimer)
279
self._fetchTimer = null
280
} else if (self._socketTimeout != null) {
281
self._socketTimer = global.setTimeout(function () {
282
self.emit('timeout')
283
if (self._fetchAbortController) {
284
self._fetchAbortController.abort()
285
}
286
}, self._socketTimeout)
287
}
288
}
289
Jul 13, 2015
Jul 13, 2015
290
ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
Jun 24, 2015
Jun 24, 2015
291
var self = this
Jul 13, 2015
Jul 13, 2015
292
self._destroyed = true
Apr 13, 2021
Apr 13, 2021
293
self._resetTimers(true)
Jul 13, 2015
Jul 13, 2015
294
if (self._response)
295
self._response._destroyed = true
Jun 24, 2015
Jun 24, 2015
296
if (self._xhr)
297
self._xhr.abort()
Jan 15, 2018
Jan 15, 2018
298
else if (self._fetchAbortController)
299
self._fetchAbortController.abort()
Jun 24, 2015
Jun 24, 2015
300
}
301
302
ClientRequest.prototype.end = function (data, encoding, cb) {
303
var self = this
304
if (typeof data === 'function') {
305
cb = data
306
data = undefined
307
}
308
Aug 8, 2015
Aug 8, 2015
309
stream.Writable.prototype.end.call(self, data, encoding, cb)
Jun 24, 2015
Jun 24, 2015
310
}
311
Apr 13, 2021
Apr 13, 2021
312
ClientRequest.prototype.setTimeout = function (timeout, cb) {
313
var self = this
314
315
if (cb)
316
self.once('timeout', cb)
317
318
self._socketTimeout = timeout
319
self._resetTimers(false)
320
}
321
Jun 24, 2015
Jun 24, 2015
322
ClientRequest.prototype.flushHeaders = function () {}
323
ClientRequest.prototype.setNoDelay = function () {}
324
ClientRequest.prototype.setSocketKeepAlive = function () {}
Jul 13, 2015
Jul 13, 2015
325
326
// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
327
var unsafeHeaders = [
328
'accept-charset',
329
'accept-encoding',
330
'access-control-request-headers',
331
'access-control-request-method',
332
'connection',
333
'content-length',
334
'cookie',
335
'cookie2',
336
'date',
337
'dnt',
338
'expect',
339
'host',
340
'keep-alive',
341
'origin',
342
'referer',
343
'te',
344
'trailer',
345
'transfer-encoding',
346
'upgrade',
347
'via'
Jul 13, 2015
Jul 13, 2015
348
]