Skip to content

Latest commit

 

History

History
323 lines (281 loc) · 8.01 KB

File metadata and controls

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