Skip to content

Latest commit

 

History

History
326 lines (283 loc) · 8.08 KB

File metadata and controls

326 lines (283 loc) · 8.08 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
May 3, 2018
May 3, 2018
10
var requestTimer = null;
11
Sep 1, 2016
Sep 1, 2016
12
function decideMode (preferBinary, useFetch) {
13
if (capability.fetch && useFetch) {
Jul 2, 2015
Jul 2, 2015
14
return 'fetch'
15
} else if (capability.mozchunkedarraybuffer) {
16
return 'moz-chunked-arraybuffer'
17
} else if (capability.msstream) {
18
return 'ms-stream'
19
} else if (capability.arraybuffer && preferBinary) {
20
return 'arraybuffer'
Jul 3, 2015
Jul 3, 2015
21
} else if (capability.vbArray && preferBinary) {
22
return 'text:vbarray'
Jul 2, 2015
Jul 2, 2015
23
} else {
24
return 'text'
25
}
26
}
27
Jun 24, 2015
Jun 24, 2015
28
var ClientRequest = module.exports = function (opts) {
29
var self = this
30
stream.Writable.call(self)
31
32
self._opts = opts
33
self._body = []
Jul 7, 2015
Jul 7, 2015
34
self._headers = {}
Jul 7, 2015
Jul 7, 2015
35
if (opts.auth)
36
self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
Sep 15, 2015
Sep 15, 2015
37
Object.keys(opts.headers).forEach(function (name) {
Jun 24, 2015
Jun 24, 2015
38
self.setHeader(name, opts.headers[name])
39
})
40
Jul 2, 2015
Jul 2, 2015
41
var preferBinary
Sep 1, 2016
Sep 1, 2016
42
var useFetch = true
Jan 15, 2018
Jan 15, 2018
43
if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
Jan 15, 2018
Jan 15, 2018
44
// If the use of XHR should be preferred. Not typically needed.
Sep 1, 2016
Sep 1, 2016
45
useFetch = false
46
preferBinary = true
47
} else if (opts.mode === 'prefer-streaming') {
Aug 20, 2015
Aug 20, 2015
48
// If streaming is a high priority but binary compatibility and
49
// the accuracy of the 'content-type' header aren't
Jul 2, 2015
Jul 2, 2015
50
preferBinary = false
Aug 20, 2015
Aug 20, 2015
51
} else if (opts.mode === 'allow-wrong-content-type') {
52
// If streaming is more important than preserving the 'content-type' header
Jul 2, 2015
Jul 2, 2015
53
preferBinary = !capability.overrideMimeType
Aug 20, 2015
Aug 20, 2015
54
} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
55
// Use binary if text streaming may corrupt data or the content-type header, or for speed
56
preferBinary = true
Jul 2, 2015
Jul 2, 2015
57
} else {
58
throw new Error('Invalid value for opts.mode')
59
}
Sep 1, 2016
Sep 1, 2016
60
self._mode = decideMode(preferBinary, useFetch)
Jun 24, 2015
Jun 24, 2015
61
Jul 2, 2015
Jul 2, 2015
62
self.on('finish', function () {
63
self._onFinish()
64
})
Jun 24, 2015
Jun 24, 2015
65
}
66
Jul 3, 2015
Jul 3, 2015
67
inherits(ClientRequest, stream.Writable)
Jun 24, 2015
Jun 24, 2015
68
69
ClientRequest.prototype.setHeader = function (name, value) {
70
var self = this
Jul 13, 2015
Jul 13, 2015
71
var lowerName = name.toLowerCase()
72
// This check is not necessary, but it prevents warnings from browsers about setting unsafe
73
// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
74
// http-browserify did it, so I will too.
Sep 15, 2015
Sep 15, 2015
75
if (unsafeHeaders.indexOf(lowerName) !== -1)
Jul 13, 2015
Jul 13, 2015
76
return
77
78
self._headers[lowerName] = {
Jul 7, 2015
Jul 7, 2015
79
name: name,
80
value: value
81
}
Jun 24, 2015
Jun 24, 2015
82
}
83
84
ClientRequest.prototype.getHeader = function (name) {
Apr 26, 2017
Apr 26, 2017
85
var header = this._headers[name.toLowerCase()]
86
if (header)
87
return header.value
88
return null
Jun 24, 2015
Jun 24, 2015
89
}
90
91
ClientRequest.prototype.removeHeader = function (name) {
92
var self = this
Jul 7, 2015
Jul 7, 2015
93
delete self._headers[name.toLowerCase()]
Jun 24, 2015
Jun 24, 2015
94
}
95
96
ClientRequest.prototype._onFinish = function () {
97
var self = this
98
Jul 13, 2015
Jul 13, 2015
99
if (self._destroyed)
100
return
Jun 24, 2015
Jun 24, 2015
101
var opts = self._opts
102
Jul 7, 2015
Jul 7, 2015
103
var headersObj = self._headers
Jan 16, 2017
Jan 16, 2017
104
var body = null
Apr 4, 2017
Apr 4, 2017
105
if (opts.method !== 'GET' && opts.method !== 'HEAD') {
Jan 15, 2018
Jan 15, 2018
106
if (capability.arraybuffer) {
107
body = toArrayBuffer(Buffer.concat(self._body))
108
} else if (capability.blobConstructor) {
Sep 15, 2015
Sep 15, 2015
109
body = new global.Blob(self._body.map(function (buffer) {
Jan 13, 2016
Jan 13, 2016
110
return toArrayBuffer(buffer)
Jul 8, 2015
Jul 8, 2015
111
}), {
112
type: (headersObj['content-type'] || {}).value || ''
113
})
Jul 1, 2015
Jul 1, 2015
114
} else {
115
// get utf8 string
116
body = Buffer.concat(self._body).toString()
117
}
Jun 24, 2015
Jun 24, 2015
118
}
119
Apr 4, 2017
Apr 4, 2017
120
// create flattened list of headers
121
var headersList = []
122
Object.keys(headersObj).forEach(function (keyName) {
123
var name = headersObj[keyName].name
124
var value = headersObj[keyName].value
125
if (Array.isArray(value)) {
126
value.forEach(function (v) {
127
headersList.push([name, v])
128
})
129
} else {
130
headersList.push([name, value])
131
}
132
})
Jun 24, 2015
Jun 24, 2015
133
Apr 4, 2017
Apr 4, 2017
134
if (self._mode === 'fetch') {
Jan 15, 2018
Jan 15, 2018
135
var signal = null
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 3, 2018
May 3, 2018
142
requestTimer = 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) {
May 3, 2018
May 3, 2018
158
global.clearTimeout(requestTimer)
Jun 24, 2015
Jun 24, 2015
159
self._fetchResponse = response
160
self._connect()
Oct 2, 2015
Oct 2, 2015
161
}, function (reason) {
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
]