Skip to content

Latest commit

 

History

History
326 lines (284 loc) · 8.11 KB

File metadata and controls

326 lines (284 loc) · 8.11 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)
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') {
Jan 15, 2018
Jan 15, 2018
104
if (capability.arraybuffer) {
105
body = toArrayBuffer(Buffer.concat(self._body))
106
} else if (capability.blobConstructor) {
Sep 15, 2015
Sep 15, 2015
107
body = new global.Blob(self._body.map(function (buffer) {
Jan 13, 2016
Jan 13, 2016
108
return toArrayBuffer(buffer)
Jul 8, 2015
Jul 8, 2015
109
}), {
110
type: (headersObj['content-type'] || {}).value || ''
111
})
Jul 1, 2015
Jul 1, 2015
112
} else {
113
// get utf8 string
114
body = Buffer.concat(self._body).toString()
115
}
Jun 24, 2015
Jun 24, 2015
116
}
117
Apr 4, 2017
Apr 4, 2017
118
// create flattened list of headers
119
var headersList = []
120
Object.keys(headersObj).forEach(function (keyName) {
121
var name = headersObj[keyName].name
122
var value = headersObj[keyName].value
123
if (Array.isArray(value)) {
124
value.forEach(function (v) {
125
headersList.push([name, v])
126
})
127
} else {
128
headersList.push([name, value])
129
}
130
})
Jun 24, 2015
Jun 24, 2015
131
Apr 4, 2017
Apr 4, 2017
132
if (self._mode === 'fetch') {
Jan 15, 2018
Jan 15, 2018
133
var signal = null
May 8, 2018
May 8, 2018
134
var fetchTimer = null
Jan 15, 2018
Jan 15, 2018
135
if (capability.abortController) {
136
var controller = new AbortController()
137
signal = controller.signal
138
self._fetchAbortController = controller
139
Jan 15, 2018
Jan 15, 2018
140
if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
May 8, 2018
May 8, 2018
141
fetchTimer = global.setTimeout(function () {
Jan 15, 2018
Jan 15, 2018
142
self.emit('requestTimeout')
Jan 15, 2018
Jan 15, 2018
143
if (self._fetchAbortController)
144
self._fetchAbortController.abort()
Jan 15, 2018
Jan 15, 2018
145
}, opts.requestTimeout)
Jan 15, 2018
Jan 15, 2018
146
}
147
}
148
Sep 15, 2015
Sep 15, 2015
149
global.fetch(self._opts.url, {
Jun 24, 2015
Jun 24, 2015
150
method: self._opts.method,
Apr 4, 2017
Apr 4, 2017
151
headers: headersList,
Jan 18, 2017
Jan 18, 2017
152
body: body || undefined,
Jun 24, 2015
Jun 24, 2015
153
mode: 'cors',
Jan 15, 2018
Jan 15, 2018
154
credentials: opts.withCredentials ? 'include' : 'same-origin',
155
signal: signal
Jun 24, 2015
Jun 24, 2015
156
}).then(function (response) {
May 8, 2018
May 8, 2018
157
global.clearTimeout(fetchTimer)
Jun 24, 2015
Jun 24, 2015
158
self._fetchResponse = response
159
self._connect()
Oct 2, 2015
Oct 2, 2015
160
}, function (reason) {
May 8, 2018
May 8, 2018
161
global.clearTimeout(fetchTimer)
Jul 8, 2015
Jul 8, 2015
162
self.emit('error', reason)
Jun 24, 2015
Jun 24, 2015
163
})
164
} else {
Sep 15, 2015
Sep 15, 2015
165
var xhr = self._xhr = new global.XMLHttpRequest()
Jul 8, 2015
Jul 8, 2015
166
try {
Sep 12, 2015
Sep 12, 2015
167
xhr.open(self._opts.method, self._opts.url, true)
Jul 8, 2015
Jul 8, 2015
168
} catch (err) {
169
process.nextTick(function () {
170
self.emit('error', err)
171
})
172
return
173
}
Jun 24, 2015
Jun 24, 2015
174
175
// Can't set responseType on really old browsers
176
if ('responseType' in xhr)
Jul 3, 2015
Jul 3, 2015
177
xhr.responseType = self._mode.split(':')[0]
Jun 24, 2015
Jun 24, 2015
178
179
if ('withCredentials' in xhr)
Jul 7, 2015
Jul 7, 2015
180
xhr.withCredentials = !!opts.withCredentials
Jun 24, 2015
Jun 24, 2015
181
182
if (self._mode === 'text' && 'overrideMimeType' in xhr)
183
xhr.overrideMimeType('text/plain; charset=x-user-defined')
184
Jan 15, 2018
Jan 15, 2018
185
if ('requestTimeout' in opts) {
186
xhr.timeout = opts.requestTimeout
Oct 18, 2016
Oct 18, 2016
187
xhr.ontimeout = function () {
Jan 15, 2018
Jan 15, 2018
188
self.emit('requestTimeout')
Oct 18, 2016
Oct 18, 2016
189
}
190
}
191
Apr 4, 2017
Apr 4, 2017
192
headersList.forEach(function (header) {
193
xhr.setRequestHeader(header[0], header[1])
Jun 24, 2015
Jun 24, 2015
194
})
195
Jul 3, 2015
Jul 3, 2015
196
self._response = null
Jun 24, 2015
Jun 24, 2015
197
xhr.onreadystatechange = function () {
198
switch (xhr.readyState) {
199
case rStates.LOADING:
200
case rStates.DONE:
Jul 8, 2015
Jul 8, 2015
201
self._onXHRProgress()
Jun 24, 2015
Jun 24, 2015
202
break
203
}
204
}
Jul 2, 2015
Jul 2, 2015
205
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
206
// in onprogress, not in onreadystatechange with xhr.readyState = 3
207
if (self._mode === 'moz-chunked-arraybuffer') {
208
xhr.onprogress = function () {
Jul 8, 2015
Jul 8, 2015
209
self._onXHRProgress()
Jul 2, 2015
Jul 2, 2015
210
}
211
}
Jun 24, 2015
Jun 24, 2015
212
Jul 8, 2015
Jul 8, 2015
213
xhr.onerror = function () {
Jul 13, 2015
Jul 13, 2015
214
if (self._destroyed)
215
return
Jul 8, 2015
Jul 8, 2015
216
self.emit('error', new Error('XHR error'))
217
}
218
219
try {
220
xhr.send(body)
221
} catch (err) {
222
process.nextTick(function () {
223
self.emit('error', err)
224
})
225
return
226
}
Jun 24, 2015
Jun 24, 2015
227
}
228
}
229
Jul 3, 2015
Jul 3, 2015
230
/**
Oct 13, 2015
Oct 13, 2015
231
* Checks if xhr.status is readable and non-zero, indicating no error.
232
* Even though the spec says it should be available in readyState 3,
233
* accessing it throws an exception in IE8
Jul 3, 2015
Jul 3, 2015
234
*/
235
function statusValid (xhr) {
236
try {
Oct 13, 2015
Oct 13, 2015
237
var status = xhr.status
238
return (status !== null && status !== 0)
Jul 3, 2015
Jul 3, 2015
239
} catch (e) {
240
return false
241
}
242
}
243
Jul 8, 2015
Jul 8, 2015
244
ClientRequest.prototype._onXHRProgress = function () {
245
var self = this
246
Jul 13, 2015
Jul 13, 2015
247
if (!statusValid(self._xhr) || self._destroyed)
Jul 8, 2015
Jul 8, 2015
248
return
249
250
if (!self._response)
251
self._connect()
252
253
self._response._onXHRProgress()
254
}
255
Jun 24, 2015
Jun 24, 2015
256
ClientRequest.prototype._connect = function () {
257
var self = this
258
Jul 13, 2015
Jul 13, 2015
259
if (self._destroyed)
260
return
261
Jun 24, 2015
Jun 24, 2015
262
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
Jan 4, 2017
Jan 4, 2017
263
self._response.on('error', function(err) {
264
self.emit('error', err)
265
})
266
Jun 24, 2015
Jun 24, 2015
267
self.emit('response', self._response)
268
}
269
270
ClientRequest.prototype._write = function (chunk, encoding, cb) {
271
var self = this
272
273
self._body.push(chunk)
274
cb()
275
}
276
Jul 13, 2015
Jul 13, 2015
277
ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
Jun 24, 2015
Jun 24, 2015
278
var self = this
Jul 13, 2015
Jul 13, 2015
279
self._destroyed = true
Jul 13, 2015
Jul 13, 2015
280
if (self._response)
281
self._response._destroyed = true
Jun 24, 2015
Jun 24, 2015
282
if (self._xhr)
283
self._xhr.abort()
Jan 15, 2018
Jan 15, 2018
284
else if (self._fetchAbortController)
285
self._fetchAbortController.abort()
Jun 24, 2015
Jun 24, 2015
286
}
287
288
ClientRequest.prototype.end = function (data, encoding, cb) {
289
var self = this
290
if (typeof data === 'function') {
291
cb = data
292
data = undefined
293
}
294
Aug 8, 2015
Aug 8, 2015
295
stream.Writable.prototype.end.call(self, data, encoding, cb)
Jun 24, 2015
Jun 24, 2015
296
}
297
298
ClientRequest.prototype.flushHeaders = function () {}
299
ClientRequest.prototype.setTimeout = function () {}
300
ClientRequest.prototype.setNoDelay = function () {}
301
ClientRequest.prototype.setSocketKeepAlive = function () {}
Jul 13, 2015
Jul 13, 2015
302
303
// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
304
var unsafeHeaders = [
305
'accept-charset',
306
'accept-encoding',
307
'access-control-request-headers',
308
'access-control-request-method',
309
'connection',
310
'content-length',
311
'cookie',
312
'cookie2',
313
'date',
314
'dnt',
315
'expect',
316
'host',
317
'keep-alive',
318
'origin',
319
'referer',
320
'te',
321
'trailer',
322
'transfer-encoding',
323
'upgrade',
324
'user-agent',
325
'via'
Jul 13, 2015
Jul 13, 2015
326
]