Skip to content

Latest commit

 

History

History
327 lines (285 loc) · 8.18 KB

File metadata and controls

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