Skip to content

Latest commit

 

History

History
279 lines (241 loc) · 6.91 KB

File metadata and controls

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