Skip to content

Latest commit

 

History

History
321 lines (279 loc) · 7.92 KB

File metadata and controls

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