Skip to content

Latest commit

 

History

History
285 lines (247 loc) · 7.03 KB

File metadata and controls

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