@feathersjs/client 5.0.0-pre.0 → 5.0.0-pre.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +229 -0
  2. package/README.md +2 -2
  3. package/dist/core.d.ts +1 -0
  4. package/dist/core.js +1861 -3627
  5. package/dist/core.js.map +1 -1
  6. package/dist/core.min.js +1 -1
  7. package/dist/feathers.d.ts +8 -0
  8. package/dist/feathers.js +5106 -5755
  9. package/dist/feathers.js.map +1 -1
  10. package/dist/feathers.min.js +1 -1
  11. package/package.json +44 -38
  12. package/src/core.ts +1 -0
  13. package/src/feathers.ts +13 -0
  14. package/.babelrc +0 -8
  15. package/.cache/lasso/default/6a3076a5/dependencyFingerprints/cache +0 -0
  16. package/.cache/lasso/default/6a3076a5/key +0 -1
  17. package/.cache/lasso/default/6a3076a5/lasso-require/inspect-/5d47a286cdceb98f64bf9128488dd355fde40e81/cache +0 -0
  18. package/.cache/lasso/default/7be4a25c/dependencyFingerprints/cache +0 -0
  19. package/.cache/lasso/default/7be4a25c/key +0 -1
  20. package/.cache/lasso/default/7be4a25c/lasso-require/inspect/cache +0 -0
  21. package/.mocha-puppeteer/test-page/@feathersjs/adapter-commons$4.5.0/lib/filter-query.js +0 -1998
  22. package/.mocha-puppeteer/test-page/@feathersjs/adapter-commons$4.5.0/lib/index.js +0 -694
  23. package/.mocha-puppeteer/test-page/@feathersjs/adapter-commons$4.5.0/lib/service.js +0 -1636
  24. package/.mocha-puppeteer/test-page/@feathersjs/adapter-commons$4.5.0/lib/sort.js +0 -2259
  25. package/.mocha-puppeteer/test-page/@feathersjs/adapter-commons$4.5.1/lib/filter-query.js +0 -98
  26. package/.mocha-puppeteer/test-page/@feathersjs/adapter-commons$4.5.1/lib/index.js +0 -37
  27. package/.mocha-puppeteer/test-page/@feathersjs/adapter-commons$4.5.1/lib/service.js +0 -94
  28. package/.mocha-puppeteer/test-page/@feathersjs/adapter-commons$4.5.1/lib/sort.js +0 -112
  29. package/.mocha-puppeteer/test-page/@feathersjs/client$4.5.0/browser/test-run.js +0 -1
  30. package/.mocha-puppeteer/test-page/@feathersjs/client$4.5.0/browser/test.js +0 -1037
  31. package/.mocha-puppeteer/test-page/@feathersjs/client$4.5.0/dist/feathers.js +0 -78377
  32. package/.mocha-puppeteer/test-page/@feathersjs/client$4.5.1/browser/test-run.js +0 -1
  33. package/.mocha-puppeteer/test-page/@feathersjs/client$4.5.1/browser/test.js +0 -102
  34. package/.mocha-puppeteer/test-page/@feathersjs/client$4.5.1/dist/feathers.js +0 -5231
  35. package/.mocha-puppeteer/test-page/@feathersjs/commons$4.5.0/lib/hooks.js +0 -2626
  36. package/.mocha-puppeteer/test-page/@feathersjs/commons$4.5.0/lib/index.js +0 -540
  37. package/.mocha-puppeteer/test-page/@feathersjs/commons$4.5.0/lib/utils.js +0 -1991
  38. package/.mocha-puppeteer/test-page/@feathersjs/commons$4.5.1/lib/hooks.js +0 -170
  39. package/.mocha-puppeteer/test-page/@feathersjs/commons$4.5.1/lib/index.js +0 -17
  40. package/.mocha-puppeteer/test-page/@feathersjs/commons$4.5.1/lib/utils.js +0 -102
  41. package/.mocha-puppeteer/test-page/@feathersjs/errors$4.5.0/lib/index.js +0 -2262
  42. package/.mocha-puppeteer/test-page/@feathersjs/errors$4.5.1/lib/index.js +0 -251
  43. package/.mocha-puppeteer/test-page/@feathersjs/tests$4.5.0/lib/client.js +0 -1506
  44. package/.mocha-puppeteer/test-page/@feathersjs/tests$4.5.1/lib/client.js +0 -83
  45. package/.mocha-puppeteer/test-page/assert$1.5.0/assert.js +0 -508
  46. package/.mocha-puppeteer/test-page/debug$4.1.1/src/browser.js +0 -266
  47. package/.mocha-puppeteer/test-page/debug$4.1.1/src/common.js +0 -268
  48. package/.mocha-puppeteer/test-page/feathers-memory$4.1.0/lib/index.js +0 -143
  49. package/.mocha-puppeteer/test-page/inherits$2.0.1/inherits_browser.js +0 -25
  50. package/.mocha-puppeteer/test-page/lasso-modules-client$2.0.5/src/index.js +0 -592
  51. package/.mocha-puppeteer/test-page/lasso-modules-meta.js +0 -28
  52. package/.mocha-puppeteer/test-page/marko$4.18.35/src/runtime/components/boot-run.js +0 -1
  53. package/.mocha-puppeteer/test-page/marko$4.18.35/src/runtime/components/boot.js +0 -95
  54. package/.mocha-puppeteer/test-page/marko$4.18.42/src/runtime/components/boot-run.js +0 -1
  55. package/.mocha-puppeteer/test-page/marko$4.18.42/src/runtime/components/boot.js +0 -95
  56. package/.mocha-puppeteer/test-page/marko$4.19.0/src/runtime/components/boot-run.js +0 -1
  57. package/.mocha-puppeteer/test-page/marko$4.19.0/src/runtime/components/boot.js +0 -3
  58. package/.mocha-puppeteer/test-page/mocha$3.5.3/mocha.css +0 -326
  59. package/.mocha-puppeteer/test-page/mocha$3.5.3/mocha.js +0 -16590
  60. package/.mocha-puppeteer/test-page/mocha-puppeteer$0.14.0/lib/pages/test-page/run-tests-run.js +0 -1
  61. package/.mocha-puppeteer/test-page/mocha-puppeteer$0.14.0/lib/pages/test-page/run-tests.js +0 -53
  62. package/.mocha-puppeteer/test-page/mocha-puppeteer$0.14.0/lib/pages/test-page/setup-run.js +0 -1
  63. package/.mocha-puppeteer/test-page/mocha-puppeteer$0.14.0/lib/pages/test-page/setup.js +0 -10
  64. package/.mocha-puppeteer/test-page/ms$2.1.2/index.js +0 -164
  65. package/.mocha-puppeteer/test-page/object-assign$4.1.1/index.js +0 -92
  66. package/.mocha-puppeteer/test-page/process$0.11.10/browser.js +0 -186
  67. package/.mocha-puppeteer/test-page/sift$8.5.1/lib/index.js +0 -738
  68. package/.mocha-puppeteer/test-page/superagent$3.8.3/superagent.js +0 -2035
  69. package/.mocha-puppeteer/test-page/util$0.10.3/support/isBufferBrowser.js +0 -7
  70. package/.mocha-puppeteer/test-page/util$0.10.3/util.js +0 -588
  71. package/.nyc_output/coverage.json +0 -1
  72. package/authentication.js +0 -1
  73. package/dist/authentication.js +0 -2242
  74. package/dist/authentication.js.map +0 -1
  75. package/dist/authentication.min.js +0 -1
  76. package/dist/rest.js +0 -3287
  77. package/dist/rest.js.map +0 -1
  78. package/dist/rest.min.js +0 -1
  79. package/dist/socketio.js +0 -2384
  80. package/dist/socketio.js.map +0 -1
  81. package/dist/socketio.min.js +0 -1
  82. package/index.d.ts +0 -23
  83. package/index.js +0 -1
  84. package/rest.js +0 -1
  85. package/socketio.js +0 -1
  86. package/webpack.config.js +0 -69
@@ -1,2035 +0,0 @@
1
- (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.superagent = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2
- function Agent() {
3
- this._defaults = [];
4
- }
5
-
6
- ["use", "on", "once", "set", "query", "type", "accept", "auth", "withCredentials", "sortQuery", "retry", "ok", "redirects",
7
- "timeout", "buffer", "serialize", "parse", "ca", "key", "pfx", "cert"].forEach(function(fn) {
8
- /** Default setting for all requests from this agent */
9
- Agent.prototype[fn] = function(/*varargs*/) {
10
- this._defaults.push({fn:fn, arguments:arguments});
11
- return this;
12
- }
13
- });
14
-
15
- Agent.prototype._setDefaults = function(req) {
16
- this._defaults.forEach(function(def) {
17
- req[def.fn].apply(req, def.arguments);
18
- });
19
- };
20
-
21
- module.exports = Agent;
22
-
23
- },{}],2:[function(require,module,exports){
24
- 'use strict';
25
-
26
- /**
27
- * Check if `obj` is an object.
28
- *
29
- * @param {Object} obj
30
- * @return {Boolean}
31
- * @api private
32
- */
33
-
34
- function isObject(obj) {
35
- return null !== obj && 'object' === typeof obj;
36
- }
37
-
38
- module.exports = isObject;
39
-
40
- },{}],3:[function(require,module,exports){
41
- 'use strict';
42
-
43
- /**
44
- * Module of mixed-in functions shared between node and client code
45
- */
46
- var isObject = require('./is-object');
47
-
48
- /**
49
- * Expose `RequestBase`.
50
- */
51
-
52
- module.exports = RequestBase;
53
-
54
- /**
55
- * Initialize a new `RequestBase`.
56
- *
57
- * @api public
58
- */
59
-
60
- function RequestBase(obj) {
61
- if (obj) return mixin(obj);
62
- }
63
-
64
- /**
65
- * Mixin the prototype properties.
66
- *
67
- * @param {Object} obj
68
- * @return {Object}
69
- * @api private
70
- */
71
-
72
- function mixin(obj) {
73
- for (var key in RequestBase.prototype) {
74
- obj[key] = RequestBase.prototype[key];
75
- }
76
- return obj;
77
- }
78
-
79
- /**
80
- * Clear previous timeout.
81
- *
82
- * @return {Request} for chaining
83
- * @api public
84
- */
85
-
86
- RequestBase.prototype.clearTimeout = function _clearTimeout(){
87
- clearTimeout(this._timer);
88
- clearTimeout(this._responseTimeoutTimer);
89
- delete this._timer;
90
- delete this._responseTimeoutTimer;
91
- return this;
92
- };
93
-
94
- /**
95
- * Override default response body parser
96
- *
97
- * This function will be called to convert incoming data into request.body
98
- *
99
- * @param {Function}
100
- * @api public
101
- */
102
-
103
- RequestBase.prototype.parse = function parse(fn){
104
- this._parser = fn;
105
- return this;
106
- };
107
-
108
- /**
109
- * Set format of binary response body.
110
- * In browser valid formats are 'blob' and 'arraybuffer',
111
- * which return Blob and ArrayBuffer, respectively.
112
- *
113
- * In Node all values result in Buffer.
114
- *
115
- * Examples:
116
- *
117
- * req.get('/')
118
- * .responseType('blob')
119
- * .end(callback);
120
- *
121
- * @param {String} val
122
- * @return {Request} for chaining
123
- * @api public
124
- */
125
-
126
- RequestBase.prototype.responseType = function(val){
127
- this._responseType = val;
128
- return this;
129
- };
130
-
131
- /**
132
- * Override default request body serializer
133
- *
134
- * This function will be called to convert data set via .send or .attach into payload to send
135
- *
136
- * @param {Function}
137
- * @api public
138
- */
139
-
140
- RequestBase.prototype.serialize = function serialize(fn){
141
- this._serializer = fn;
142
- return this;
143
- };
144
-
145
- /**
146
- * Set timeouts.
147
- *
148
- * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
149
- * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
150
- *
151
- * Value of 0 or false means no timeout.
152
- *
153
- * @param {Number|Object} ms or {response, deadline}
154
- * @return {Request} for chaining
155
- * @api public
156
- */
157
-
158
- RequestBase.prototype.timeout = function timeout(options){
159
- if (!options || 'object' !== typeof options) {
160
- this._timeout = options;
161
- this._responseTimeout = 0;
162
- return this;
163
- }
164
-
165
- for(var option in options) {
166
- switch(option) {
167
- case 'deadline':
168
- this._timeout = options.deadline;
169
- break;
170
- case 'response':
171
- this._responseTimeout = options.response;
172
- break;
173
- default:
174
- console.warn("Unknown timeout option", option);
175
- }
176
- }
177
- return this;
178
- };
179
-
180
- /**
181
- * Set number of retry attempts on error.
182
- *
183
- * Failed requests will be retried 'count' times if timeout or err.code >= 500.
184
- *
185
- * @param {Number} count
186
- * @param {Function} [fn]
187
- * @return {Request} for chaining
188
- * @api public
189
- */
190
-
191
- RequestBase.prototype.retry = function retry(count, fn){
192
- // Default to 1 if no count passed or true
193
- if (arguments.length === 0 || count === true) count = 1;
194
- if (count <= 0) count = 0;
195
- this._maxRetries = count;
196
- this._retries = 0;
197
- this._retryCallback = fn;
198
- return this;
199
- };
200
-
201
- var ERROR_CODES = [
202
- 'ECONNRESET',
203
- 'ETIMEDOUT',
204
- 'EADDRINFO',
205
- 'ESOCKETTIMEDOUT'
206
- ];
207
-
208
- /**
209
- * Determine if a request should be retried.
210
- * (Borrowed from segmentio/superagent-retry)
211
- *
212
- * @param {Error} err
213
- * @param {Response} [res]
214
- * @returns {Boolean}
215
- */
216
- RequestBase.prototype._shouldRetry = function(err, res) {
217
- if (!this._maxRetries || this._retries++ >= this._maxRetries) {
218
- return false;
219
- }
220
- if (this._retryCallback) {
221
- try {
222
- var override = this._retryCallback(err, res);
223
- if (override === true) return true;
224
- if (override === false) return false;
225
- // undefined falls back to defaults
226
- } catch(e) {
227
- console.error(e);
228
- }
229
- }
230
- if (res && res.status && res.status >= 500 && res.status != 501) return true;
231
- if (err) {
232
- if (err.code && ~ERROR_CODES.indexOf(err.code)) return true;
233
- // Superagent timeout
234
- if (err.timeout && err.code == 'ECONNABORTED') return true;
235
- if (err.crossDomain) return true;
236
- }
237
- return false;
238
- };
239
-
240
- /**
241
- * Retry request
242
- *
243
- * @return {Request} for chaining
244
- * @api private
245
- */
246
-
247
- RequestBase.prototype._retry = function() {
248
-
249
- this.clearTimeout();
250
-
251
- // node
252
- if (this.req) {
253
- this.req = null;
254
- this.req = this.request();
255
- }
256
-
257
- this._aborted = false;
258
- this.timedout = false;
259
-
260
- return this._end();
261
- };
262
-
263
- /**
264
- * Promise support
265
- *
266
- * @param {Function} resolve
267
- * @param {Function} [reject]
268
- * @return {Request}
269
- */
270
-
271
- RequestBase.prototype.then = function then(resolve, reject) {
272
- if (!this._fullfilledPromise) {
273
- var self = this;
274
- if (this._endCalled) {
275
- console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises");
276
- }
277
- this._fullfilledPromise = new Promise(function(innerResolve, innerReject) {
278
- self.end(function(err, res) {
279
- if (err) innerReject(err);
280
- else innerResolve(res);
281
- });
282
- });
283
- }
284
- return this._fullfilledPromise.then(resolve, reject);
285
- };
286
-
287
- RequestBase.prototype['catch'] = function(cb) {
288
- return this.then(undefined, cb);
289
- };
290
-
291
- /**
292
- * Allow for extension
293
- */
294
-
295
- RequestBase.prototype.use = function use(fn) {
296
- fn(this);
297
- return this;
298
- };
299
-
300
- RequestBase.prototype.ok = function(cb) {
301
- if ('function' !== typeof cb) throw Error("Callback required");
302
- this._okCallback = cb;
303
- return this;
304
- };
305
-
306
- RequestBase.prototype._isResponseOK = function(res) {
307
- if (!res) {
308
- return false;
309
- }
310
-
311
- if (this._okCallback) {
312
- return this._okCallback(res);
313
- }
314
-
315
- return res.status >= 200 && res.status < 300;
316
- };
317
-
318
- /**
319
- * Get request header `field`.
320
- * Case-insensitive.
321
- *
322
- * @param {String} field
323
- * @return {String}
324
- * @api public
325
- */
326
-
327
- RequestBase.prototype.get = function(field){
328
- return this._header[field.toLowerCase()];
329
- };
330
-
331
- /**
332
- * Get case-insensitive header `field` value.
333
- * This is a deprecated internal API. Use `.get(field)` instead.
334
- *
335
- * (getHeader is no longer used internally by the superagent code base)
336
- *
337
- * @param {String} field
338
- * @return {String}
339
- * @api private
340
- * @deprecated
341
- */
342
-
343
- RequestBase.prototype.getHeader = RequestBase.prototype.get;
344
-
345
- /**
346
- * Set header `field` to `val`, or multiple fields with one object.
347
- * Case-insensitive.
348
- *
349
- * Examples:
350
- *
351
- * req.get('/')
352
- * .set('Accept', 'application/json')
353
- * .set('X-API-Key', 'foobar')
354
- * .end(callback);
355
- *
356
- * req.get('/')
357
- * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
358
- * .end(callback);
359
- *
360
- * @param {String|Object} field
361
- * @param {String} val
362
- * @return {Request} for chaining
363
- * @api public
364
- */
365
-
366
- RequestBase.prototype.set = function(field, val){
367
- if (isObject(field)) {
368
- for (var key in field) {
369
- this.set(key, field[key]);
370
- }
371
- return this;
372
- }
373
- this._header[field.toLowerCase()] = val;
374
- this.header[field] = val;
375
- return this;
376
- };
377
-
378
- /**
379
- * Remove header `field`.
380
- * Case-insensitive.
381
- *
382
- * Example:
383
- *
384
- * req.get('/')
385
- * .unset('User-Agent')
386
- * .end(callback);
387
- *
388
- * @param {String} field
389
- */
390
- RequestBase.prototype.unset = function(field){
391
- delete this._header[field.toLowerCase()];
392
- delete this.header[field];
393
- return this;
394
- };
395
-
396
- /**
397
- * Write the field `name` and `val`, or multiple fields with one object
398
- * for "multipart/form-data" request bodies.
399
- *
400
- * ``` js
401
- * request.post('/upload')
402
- * .field('foo', 'bar')
403
- * .end(callback);
404
- *
405
- * request.post('/upload')
406
- * .field({ foo: 'bar', baz: 'qux' })
407
- * .end(callback);
408
- * ```
409
- *
410
- * @param {String|Object} name
411
- * @param {String|Blob|File|Buffer|fs.ReadStream} val
412
- * @return {Request} for chaining
413
- * @api public
414
- */
415
- RequestBase.prototype.field = function(name, val) {
416
- // name should be either a string or an object.
417
- if (null === name || undefined === name) {
418
- throw new Error('.field(name, val) name can not be empty');
419
- }
420
-
421
- if (this._data) {
422
- console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
423
- }
424
-
425
- if (isObject(name)) {
426
- for (var key in name) {
427
- this.field(key, name[key]);
428
- }
429
- return this;
430
- }
431
-
432
- if (Array.isArray(val)) {
433
- for (var i in val) {
434
- this.field(name, val[i]);
435
- }
436
- return this;
437
- }
438
-
439
- // val should be defined now
440
- if (null === val || undefined === val) {
441
- throw new Error('.field(name, val) val can not be empty');
442
- }
443
- if ('boolean' === typeof val) {
444
- val = '' + val;
445
- }
446
- this._getFormData().append(name, val);
447
- return this;
448
- };
449
-
450
- /**
451
- * Abort the request, and clear potential timeout.
452
- *
453
- * @return {Request}
454
- * @api public
455
- */
456
- RequestBase.prototype.abort = function(){
457
- if (this._aborted) {
458
- return this;
459
- }
460
- this._aborted = true;
461
- this.xhr && this.xhr.abort(); // browser
462
- this.req && this.req.abort(); // node
463
- this.clearTimeout();
464
- this.emit('abort');
465
- return this;
466
- };
467
-
468
- RequestBase.prototype._auth = function(user, pass, options, base64Encoder) {
469
- switch (options.type) {
470
- case 'basic':
471
- this.set('Authorization', 'Basic ' + base64Encoder(user + ':' + pass));
472
- break;
473
-
474
- case 'auto':
475
- this.username = user;
476
- this.password = pass;
477
- break;
478
-
479
- case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
480
- this.set('Authorization', 'Bearer ' + user);
481
- break;
482
- }
483
- return this;
484
- };
485
-
486
- /**
487
- * Enable transmission of cookies with x-domain requests.
488
- *
489
- * Note that for this to work the origin must not be
490
- * using "Access-Control-Allow-Origin" with a wildcard,
491
- * and also must set "Access-Control-Allow-Credentials"
492
- * to "true".
493
- *
494
- * @api public
495
- */
496
-
497
- RequestBase.prototype.withCredentials = function(on) {
498
- // This is browser-only functionality. Node side is no-op.
499
- if (on == undefined) on = true;
500
- this._withCredentials = on;
501
- return this;
502
- };
503
-
504
- /**
505
- * Set the max redirects to `n`. Does noting in browser XHR implementation.
506
- *
507
- * @param {Number} n
508
- * @return {Request} for chaining
509
- * @api public
510
- */
511
-
512
- RequestBase.prototype.redirects = function(n){
513
- this._maxRedirects = n;
514
- return this;
515
- };
516
-
517
- /**
518
- * Maximum size of buffered response body, in bytes. Counts uncompressed size.
519
- * Default 200MB.
520
- *
521
- * @param {Number} n
522
- * @return {Request} for chaining
523
- */
524
- RequestBase.prototype.maxResponseSize = function(n){
525
- if ('number' !== typeof n) {
526
- throw TypeError("Invalid argument");
527
- }
528
- this._maxResponseSize = n;
529
- return this;
530
- };
531
-
532
- /**
533
- * Convert to a plain javascript object (not JSON string) of scalar properties.
534
- * Note as this method is designed to return a useful non-this value,
535
- * it cannot be chained.
536
- *
537
- * @return {Object} describing method, url, and data of this request
538
- * @api public
539
- */
540
-
541
- RequestBase.prototype.toJSON = function() {
542
- return {
543
- method: this.method,
544
- url: this.url,
545
- data: this._data,
546
- headers: this._header,
547
- };
548
- };
549
-
550
- /**
551
- * Send `data` as the request body, defaulting the `.type()` to "json" when
552
- * an object is given.
553
- *
554
- * Examples:
555
- *
556
- * // manual json
557
- * request.post('/user')
558
- * .type('json')
559
- * .send('{"name":"tj"}')
560
- * .end(callback)
561
- *
562
- * // auto json
563
- * request.post('/user')
564
- * .send({ name: 'tj' })
565
- * .end(callback)
566
- *
567
- * // manual x-www-form-urlencoded
568
- * request.post('/user')
569
- * .type('form')
570
- * .send('name=tj')
571
- * .end(callback)
572
- *
573
- * // auto x-www-form-urlencoded
574
- * request.post('/user')
575
- * .type('form')
576
- * .send({ name: 'tj' })
577
- * .end(callback)
578
- *
579
- * // defaults to x-www-form-urlencoded
580
- * request.post('/user')
581
- * .send('name=tobi')
582
- * .send('species=ferret')
583
- * .end(callback)
584
- *
585
- * @param {String|Object} data
586
- * @return {Request} for chaining
587
- * @api public
588
- */
589
-
590
- RequestBase.prototype.send = function(data){
591
- var isObj = isObject(data);
592
- var type = this._header['content-type'];
593
-
594
- if (this._formData) {
595
- console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
596
- }
597
-
598
- if (isObj && !this._data) {
599
- if (Array.isArray(data)) {
600
- this._data = [];
601
- } else if (!this._isHost(data)) {
602
- this._data = {};
603
- }
604
- } else if (data && this._data && this._isHost(this._data)) {
605
- throw Error("Can't merge these send calls");
606
- }
607
-
608
- // merge
609
- if (isObj && isObject(this._data)) {
610
- for (var key in data) {
611
- this._data[key] = data[key];
612
- }
613
- } else if ('string' == typeof data) {
614
- // default to x-www-form-urlencoded
615
- if (!type) this.type('form');
616
- type = this._header['content-type'];
617
- if ('application/x-www-form-urlencoded' == type) {
618
- this._data = this._data
619
- ? this._data + '&' + data
620
- : data;
621
- } else {
622
- this._data = (this._data || '') + data;
623
- }
624
- } else {
625
- this._data = data;
626
- }
627
-
628
- if (!isObj || this._isHost(data)) {
629
- return this;
630
- }
631
-
632
- // default to json
633
- if (!type) this.type('json');
634
- return this;
635
- };
636
-
637
- /**
638
- * Sort `querystring` by the sort function
639
- *
640
- *
641
- * Examples:
642
- *
643
- * // default order
644
- * request.get('/user')
645
- * .query('name=Nick')
646
- * .query('search=Manny')
647
- * .sortQuery()
648
- * .end(callback)
649
- *
650
- * // customized sort function
651
- * request.get('/user')
652
- * .query('name=Nick')
653
- * .query('search=Manny')
654
- * .sortQuery(function(a, b){
655
- * return a.length - b.length;
656
- * })
657
- * .end(callback)
658
- *
659
- *
660
- * @param {Function} sort
661
- * @return {Request} for chaining
662
- * @api public
663
- */
664
-
665
- RequestBase.prototype.sortQuery = function(sort) {
666
- // _sort default to true but otherwise can be a function or boolean
667
- this._sort = typeof sort === 'undefined' ? true : sort;
668
- return this;
669
- };
670
-
671
- /**
672
- * Compose querystring to append to req.url
673
- *
674
- * @api private
675
- */
676
- RequestBase.prototype._finalizeQueryString = function(){
677
- var query = this._query.join('&');
678
- if (query) {
679
- this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;
680
- }
681
- this._query.length = 0; // Makes the call idempotent
682
-
683
- if (this._sort) {
684
- var index = this.url.indexOf('?');
685
- if (index >= 0) {
686
- var queryArr = this.url.substring(index + 1).split('&');
687
- if ('function' === typeof this._sort) {
688
- queryArr.sort(this._sort);
689
- } else {
690
- queryArr.sort();
691
- }
692
- this.url = this.url.substring(0, index) + '?' + queryArr.join('&');
693
- }
694
- }
695
- };
696
-
697
- // For backwards compat only
698
- RequestBase.prototype._appendQueryString = function() {console.trace("Unsupported");}
699
-
700
- /**
701
- * Invoke callback with timeout error.
702
- *
703
- * @api private
704
- */
705
-
706
- RequestBase.prototype._timeoutError = function(reason, timeout, errno){
707
- if (this._aborted) {
708
- return;
709
- }
710
- var err = new Error(reason + timeout + 'ms exceeded');
711
- err.timeout = timeout;
712
- err.code = 'ECONNABORTED';
713
- err.errno = errno;
714
- this.timedout = true;
715
- this.abort();
716
- this.callback(err);
717
- };
718
-
719
- RequestBase.prototype._setTimeouts = function() {
720
- var self = this;
721
-
722
- // deadline
723
- if (this._timeout && !this._timer) {
724
- this._timer = setTimeout(function(){
725
- self._timeoutError('Timeout of ', self._timeout, 'ETIME');
726
- }, this._timeout);
727
- }
728
- // response timeout
729
- if (this._responseTimeout && !this._responseTimeoutTimer) {
730
- this._responseTimeoutTimer = setTimeout(function(){
731
- self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
732
- }, this._responseTimeout);
733
- }
734
- };
735
-
736
- },{"./is-object":2}],4:[function(require,module,exports){
737
- 'use strict';
738
-
739
- /**
740
- * Module dependencies.
741
- */
742
-
743
- var utils = require('./utils');
744
-
745
- /**
746
- * Expose `ResponseBase`.
747
- */
748
-
749
- module.exports = ResponseBase;
750
-
751
- /**
752
- * Initialize a new `ResponseBase`.
753
- *
754
- * @api public
755
- */
756
-
757
- function ResponseBase(obj) {
758
- if (obj) return mixin(obj);
759
- }
760
-
761
- /**
762
- * Mixin the prototype properties.
763
- *
764
- * @param {Object} obj
765
- * @return {Object}
766
- * @api private
767
- */
768
-
769
- function mixin(obj) {
770
- for (var key in ResponseBase.prototype) {
771
- obj[key] = ResponseBase.prototype[key];
772
- }
773
- return obj;
774
- }
775
-
776
- /**
777
- * Get case-insensitive `field` value.
778
- *
779
- * @param {String} field
780
- * @return {String}
781
- * @api public
782
- */
783
-
784
- ResponseBase.prototype.get = function(field) {
785
- return this.header[field.toLowerCase()];
786
- };
787
-
788
- /**
789
- * Set header related properties:
790
- *
791
- * - `.type` the content type without params
792
- *
793
- * A response of "Content-Type: text/plain; charset=utf-8"
794
- * will provide you with a `.type` of "text/plain".
795
- *
796
- * @param {Object} header
797
- * @api private
798
- */
799
-
800
- ResponseBase.prototype._setHeaderProperties = function(header){
801
- // TODO: moar!
802
- // TODO: make this a util
803
-
804
- // content-type
805
- var ct = header['content-type'] || '';
806
- this.type = utils.type(ct);
807
-
808
- // params
809
- var params = utils.params(ct);
810
- for (var key in params) this[key] = params[key];
811
-
812
- this.links = {};
813
-
814
- // links
815
- try {
816
- if (header.link) {
817
- this.links = utils.parseLinks(header.link);
818
- }
819
- } catch (err) {
820
- // ignore
821
- }
822
- };
823
-
824
- /**
825
- * Set flags such as `.ok` based on `status`.
826
- *
827
- * For example a 2xx response will give you a `.ok` of __true__
828
- * whereas 5xx will be __false__ and `.error` will be __true__. The
829
- * `.clientError` and `.serverError` are also available to be more
830
- * specific, and `.statusType` is the class of error ranging from 1..5
831
- * sometimes useful for mapping respond colors etc.
832
- *
833
- * "sugar" properties are also defined for common cases. Currently providing:
834
- *
835
- * - .noContent
836
- * - .badRequest
837
- * - .unauthorized
838
- * - .notAcceptable
839
- * - .notFound
840
- *
841
- * @param {Number} status
842
- * @api private
843
- */
844
-
845
- ResponseBase.prototype._setStatusProperties = function(status){
846
- var type = status / 100 | 0;
847
-
848
- // status / class
849
- this.status = this.statusCode = status;
850
- this.statusType = type;
851
-
852
- // basics
853
- this.info = 1 == type;
854
- this.ok = 2 == type;
855
- this.redirect = 3 == type;
856
- this.clientError = 4 == type;
857
- this.serverError = 5 == type;
858
- this.error = (4 == type || 5 == type)
859
- ? this.toError()
860
- : false;
861
-
862
- // sugar
863
- this.created = 201 == status;
864
- this.accepted = 202 == status;
865
- this.noContent = 204 == status;
866
- this.badRequest = 400 == status;
867
- this.unauthorized = 401 == status;
868
- this.notAcceptable = 406 == status;
869
- this.forbidden = 403 == status;
870
- this.notFound = 404 == status;
871
- this.unprocessableEntity = 422 == status;
872
- };
873
-
874
- },{"./utils":5}],5:[function(require,module,exports){
875
- 'use strict';
876
-
877
- /**
878
- * Return the mime type for the given `str`.
879
- *
880
- * @param {String} str
881
- * @return {String}
882
- * @api private
883
- */
884
-
885
- exports.type = function(str){
886
- return str.split(/ *; */).shift();
887
- };
888
-
889
- /**
890
- * Return header field parameters.
891
- *
892
- * @param {String} str
893
- * @return {Object}
894
- * @api private
895
- */
896
-
897
- exports.params = function(str){
898
- return str.split(/ *; */).reduce(function(obj, str){
899
- var parts = str.split(/ *= */);
900
- var key = parts.shift();
901
- var val = parts.shift();
902
-
903
- if (key && val) obj[key] = val;
904
- return obj;
905
- }, {});
906
- };
907
-
908
- /**
909
- * Parse Link header fields.
910
- *
911
- * @param {String} str
912
- * @return {Object}
913
- * @api private
914
- */
915
-
916
- exports.parseLinks = function(str){
917
- return str.split(/ *, */).reduce(function(obj, str){
918
- var parts = str.split(/ *; */);
919
- var url = parts[0].slice(1, -1);
920
- var rel = parts[1].split(/ *= */)[1].slice(1, -1);
921
- obj[rel] = url;
922
- return obj;
923
- }, {});
924
- };
925
-
926
- /**
927
- * Strip content related fields from `header`.
928
- *
929
- * @param {Object} header
930
- * @return {Object} header
931
- * @api private
932
- */
933
-
934
- exports.cleanHeader = function(header, changesOrigin){
935
- delete header['content-type'];
936
- delete header['content-length'];
937
- delete header['transfer-encoding'];
938
- delete header['host'];
939
- // secuirty
940
- if (changesOrigin) {
941
- delete header['authorization'];
942
- delete header['cookie'];
943
- }
944
- return header;
945
- };
946
-
947
- },{}],6:[function(require,module,exports){
948
-
949
- /**
950
- * Expose `Emitter`.
951
- */
952
-
953
- if (typeof module !== 'undefined') {
954
- module.exports = Emitter;
955
- }
956
-
957
- /**
958
- * Initialize a new `Emitter`.
959
- *
960
- * @api public
961
- */
962
-
963
- function Emitter(obj) {
964
- if (obj) return mixin(obj);
965
- };
966
-
967
- /**
968
- * Mixin the emitter properties.
969
- *
970
- * @param {Object} obj
971
- * @return {Object}
972
- * @api private
973
- */
974
-
975
- function mixin(obj) {
976
- for (var key in Emitter.prototype) {
977
- obj[key] = Emitter.prototype[key];
978
- }
979
- return obj;
980
- }
981
-
982
- /**
983
- * Listen on the given `event` with `fn`.
984
- *
985
- * @param {String} event
986
- * @param {Function} fn
987
- * @return {Emitter}
988
- * @api public
989
- */
990
-
991
- Emitter.prototype.on =
992
- Emitter.prototype.addEventListener = function(event, fn){
993
- this._callbacks = this._callbacks || {};
994
- (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
995
- .push(fn);
996
- return this;
997
- };
998
-
999
- /**
1000
- * Adds an `event` listener that will be invoked a single
1001
- * time then automatically removed.
1002
- *
1003
- * @param {String} event
1004
- * @param {Function} fn
1005
- * @return {Emitter}
1006
- * @api public
1007
- */
1008
-
1009
- Emitter.prototype.once = function(event, fn){
1010
- function on() {
1011
- this.off(event, on);
1012
- fn.apply(this, arguments);
1013
- }
1014
-
1015
- on.fn = fn;
1016
- this.on(event, on);
1017
- return this;
1018
- };
1019
-
1020
- /**
1021
- * Remove the given callback for `event` or all
1022
- * registered callbacks.
1023
- *
1024
- * @param {String} event
1025
- * @param {Function} fn
1026
- * @return {Emitter}
1027
- * @api public
1028
- */
1029
-
1030
- Emitter.prototype.off =
1031
- Emitter.prototype.removeListener =
1032
- Emitter.prototype.removeAllListeners =
1033
- Emitter.prototype.removeEventListener = function(event, fn){
1034
- this._callbacks = this._callbacks || {};
1035
-
1036
- // all
1037
- if (0 == arguments.length) {
1038
- this._callbacks = {};
1039
- return this;
1040
- }
1041
-
1042
- // specific event
1043
- var callbacks = this._callbacks['$' + event];
1044
- if (!callbacks) return this;
1045
-
1046
- // remove all handlers
1047
- if (1 == arguments.length) {
1048
- delete this._callbacks['$' + event];
1049
- return this;
1050
- }
1051
-
1052
- // remove specific handler
1053
- var cb;
1054
- for (var i = 0; i < callbacks.length; i++) {
1055
- cb = callbacks[i];
1056
- if (cb === fn || cb.fn === fn) {
1057
- callbacks.splice(i, 1);
1058
- break;
1059
- }
1060
- }
1061
- return this;
1062
- };
1063
-
1064
- /**
1065
- * Emit `event` with the given args.
1066
- *
1067
- * @param {String} event
1068
- * @param {Mixed} ...
1069
- * @return {Emitter}
1070
- */
1071
-
1072
- Emitter.prototype.emit = function(event){
1073
- this._callbacks = this._callbacks || {};
1074
- var args = [].slice.call(arguments, 1)
1075
- , callbacks = this._callbacks['$' + event];
1076
-
1077
- if (callbacks) {
1078
- callbacks = callbacks.slice(0);
1079
- for (var i = 0, len = callbacks.length; i < len; ++i) {
1080
- callbacks[i].apply(this, args);
1081
- }
1082
- }
1083
-
1084
- return this;
1085
- };
1086
-
1087
- /**
1088
- * Return array of callbacks for `event`.
1089
- *
1090
- * @param {String} event
1091
- * @return {Array}
1092
- * @api public
1093
- */
1094
-
1095
- Emitter.prototype.listeners = function(event){
1096
- this._callbacks = this._callbacks || {};
1097
- return this._callbacks['$' + event] || [];
1098
- };
1099
-
1100
- /**
1101
- * Check if this emitter has `event` handlers.
1102
- *
1103
- * @param {String} event
1104
- * @return {Boolean}
1105
- * @api public
1106
- */
1107
-
1108
- Emitter.prototype.hasListeners = function(event){
1109
- return !! this.listeners(event).length;
1110
- };
1111
-
1112
- },{}],7:[function(require,module,exports){
1113
- /**
1114
- * Root reference for iframes.
1115
- */
1116
-
1117
- var root;
1118
- if (typeof window !== 'undefined') { // Browser window
1119
- root = window;
1120
- } else if (typeof self !== 'undefined') { // Web Worker
1121
- root = self;
1122
- } else { // Other environments
1123
- console.warn("Using browser-only version of superagent in non-browser environment");
1124
- root = this;
1125
- }
1126
-
1127
- var Emitter = require('component-emitter');
1128
- var RequestBase = require('./request-base');
1129
- var isObject = require('./is-object');
1130
- var ResponseBase = require('./response-base');
1131
- var Agent = require('./agent-base');
1132
-
1133
- /**
1134
- * Noop.
1135
- */
1136
-
1137
- function noop(){};
1138
-
1139
- /**
1140
- * Expose `request`.
1141
- */
1142
-
1143
- var request = exports = module.exports = function(method, url) {
1144
- // callback
1145
- if ('function' == typeof url) {
1146
- return new exports.Request('GET', method).end(url);
1147
- }
1148
-
1149
- // url first
1150
- if (1 == arguments.length) {
1151
- return new exports.Request('GET', method);
1152
- }
1153
-
1154
- return new exports.Request(method, url);
1155
- }
1156
-
1157
- exports.Request = Request;
1158
-
1159
- /**
1160
- * Determine XHR.
1161
- */
1162
-
1163
- request.getXHR = function () {
1164
- if (root.XMLHttpRequest
1165
- && (!root.location || 'file:' != root.location.protocol
1166
- || !root.ActiveXObject)) {
1167
- return new XMLHttpRequest;
1168
- } else {
1169
- try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
1170
- try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
1171
- try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
1172
- try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
1173
- }
1174
- throw Error("Browser-only version of superagent could not find XHR");
1175
- };
1176
-
1177
- /**
1178
- * Removes leading and trailing whitespace, added to support IE.
1179
- *
1180
- * @param {String} s
1181
- * @return {String}
1182
- * @api private
1183
- */
1184
-
1185
- var trim = ''.trim
1186
- ? function(s) { return s.trim(); }
1187
- : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
1188
-
1189
- /**
1190
- * Serialize the given `obj`.
1191
- *
1192
- * @param {Object} obj
1193
- * @return {String}
1194
- * @api private
1195
- */
1196
-
1197
- function serialize(obj) {
1198
- if (!isObject(obj)) return obj;
1199
- var pairs = [];
1200
- for (var key in obj) {
1201
- pushEncodedKeyValuePair(pairs, key, obj[key]);
1202
- }
1203
- return pairs.join('&');
1204
- }
1205
-
1206
- /**
1207
- * Helps 'serialize' with serializing arrays.
1208
- * Mutates the pairs array.
1209
- *
1210
- * @param {Array} pairs
1211
- * @param {String} key
1212
- * @param {Mixed} val
1213
- */
1214
-
1215
- function pushEncodedKeyValuePair(pairs, key, val) {
1216
- if (val != null) {
1217
- if (Array.isArray(val)) {
1218
- val.forEach(function(v) {
1219
- pushEncodedKeyValuePair(pairs, key, v);
1220
- });
1221
- } else if (isObject(val)) {
1222
- for(var subkey in val) {
1223
- pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);
1224
- }
1225
- } else {
1226
- pairs.push(encodeURIComponent(key)
1227
- + '=' + encodeURIComponent(val));
1228
- }
1229
- } else if (val === null) {
1230
- pairs.push(encodeURIComponent(key));
1231
- }
1232
- }
1233
-
1234
- /**
1235
- * Expose serialization method.
1236
- */
1237
-
1238
- request.serializeObject = serialize;
1239
-
1240
- /**
1241
- * Parse the given x-www-form-urlencoded `str`.
1242
- *
1243
- * @param {String} str
1244
- * @return {Object}
1245
- * @api private
1246
- */
1247
-
1248
- function parseString(str) {
1249
- var obj = {};
1250
- var pairs = str.split('&');
1251
- var pair;
1252
- var pos;
1253
-
1254
- for (var i = 0, len = pairs.length; i < len; ++i) {
1255
- pair = pairs[i];
1256
- pos = pair.indexOf('=');
1257
- if (pos == -1) {
1258
- obj[decodeURIComponent(pair)] = '';
1259
- } else {
1260
- obj[decodeURIComponent(pair.slice(0, pos))] =
1261
- decodeURIComponent(pair.slice(pos + 1));
1262
- }
1263
- }
1264
-
1265
- return obj;
1266
- }
1267
-
1268
- /**
1269
- * Expose parser.
1270
- */
1271
-
1272
- request.parseString = parseString;
1273
-
1274
- /**
1275
- * Default MIME type map.
1276
- *
1277
- * superagent.types.xml = 'application/xml';
1278
- *
1279
- */
1280
-
1281
- request.types = {
1282
- html: 'text/html',
1283
- json: 'application/json',
1284
- xml: 'text/xml',
1285
- urlencoded: 'application/x-www-form-urlencoded',
1286
- 'form': 'application/x-www-form-urlencoded',
1287
- 'form-data': 'application/x-www-form-urlencoded'
1288
- };
1289
-
1290
- /**
1291
- * Default serialization map.
1292
- *
1293
- * superagent.serialize['application/xml'] = function(obj){
1294
- * return 'generated xml here';
1295
- * };
1296
- *
1297
- */
1298
-
1299
- request.serialize = {
1300
- 'application/x-www-form-urlencoded': serialize,
1301
- 'application/json': JSON.stringify
1302
- };
1303
-
1304
- /**
1305
- * Default parsers.
1306
- *
1307
- * superagent.parse['application/xml'] = function(str){
1308
- * return { object parsed from str };
1309
- * };
1310
- *
1311
- */
1312
-
1313
- request.parse = {
1314
- 'application/x-www-form-urlencoded': parseString,
1315
- 'application/json': JSON.parse
1316
- };
1317
-
1318
- /**
1319
- * Parse the given header `str` into
1320
- * an object containing the mapped fields.
1321
- *
1322
- * @param {String} str
1323
- * @return {Object}
1324
- * @api private
1325
- */
1326
-
1327
- function parseHeader(str) {
1328
- var lines = str.split(/\r?\n/);
1329
- var fields = {};
1330
- var index;
1331
- var line;
1332
- var field;
1333
- var val;
1334
-
1335
- for (var i = 0, len = lines.length; i < len; ++i) {
1336
- line = lines[i];
1337
- index = line.indexOf(':');
1338
- if (index === -1) { // could be empty line, just skip it
1339
- continue;
1340
- }
1341
- field = line.slice(0, index).toLowerCase();
1342
- val = trim(line.slice(index + 1));
1343
- fields[field] = val;
1344
- }
1345
-
1346
- return fields;
1347
- }
1348
-
1349
- /**
1350
- * Check if `mime` is json or has +json structured syntax suffix.
1351
- *
1352
- * @param {String} mime
1353
- * @return {Boolean}
1354
- * @api private
1355
- */
1356
-
1357
- function isJSON(mime) {
1358
- // should match /json or +json
1359
- // but not /json-seq
1360
- return /[\/+]json($|[^-\w])/.test(mime);
1361
- }
1362
-
1363
- /**
1364
- * Initialize a new `Response` with the given `xhr`.
1365
- *
1366
- * - set flags (.ok, .error, etc)
1367
- * - parse header
1368
- *
1369
- * Examples:
1370
- *
1371
- * Aliasing `superagent` as `request` is nice:
1372
- *
1373
- * request = superagent;
1374
- *
1375
- * We can use the promise-like API, or pass callbacks:
1376
- *
1377
- * request.get('/').end(function(res){});
1378
- * request.get('/', function(res){});
1379
- *
1380
- * Sending data can be chained:
1381
- *
1382
- * request
1383
- * .post('/user')
1384
- * .send({ name: 'tj' })
1385
- * .end(function(res){});
1386
- *
1387
- * Or passed to `.send()`:
1388
- *
1389
- * request
1390
- * .post('/user')
1391
- * .send({ name: 'tj' }, function(res){});
1392
- *
1393
- * Or passed to `.post()`:
1394
- *
1395
- * request
1396
- * .post('/user', { name: 'tj' })
1397
- * .end(function(res){});
1398
- *
1399
- * Or further reduced to a single call for simple cases:
1400
- *
1401
- * request
1402
- * .post('/user', { name: 'tj' }, function(res){});
1403
- *
1404
- * @param {XMLHTTPRequest} xhr
1405
- * @param {Object} options
1406
- * @api private
1407
- */
1408
-
1409
- function Response(req) {
1410
- this.req = req;
1411
- this.xhr = this.req.xhr;
1412
- // responseText is accessible only if responseType is '' or 'text' and on older browsers
1413
- this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')
1414
- ? this.xhr.responseText
1415
- : null;
1416
- this.statusText = this.req.xhr.statusText;
1417
- var status = this.xhr.status;
1418
- // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
1419
- if (status === 1223) {
1420
- status = 204;
1421
- }
1422
- this._setStatusProperties(status);
1423
- this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
1424
- // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
1425
- // getResponseHeader still works. so we get content-type even if getting
1426
- // other headers fails.
1427
- this.header['content-type'] = this.xhr.getResponseHeader('content-type');
1428
- this._setHeaderProperties(this.header);
1429
-
1430
- if (null === this.text && req._responseType) {
1431
- this.body = this.xhr.response;
1432
- } else {
1433
- this.body = this.req.method != 'HEAD'
1434
- ? this._parseBody(this.text ? this.text : this.xhr.response)
1435
- : null;
1436
- }
1437
- }
1438
-
1439
- ResponseBase(Response.prototype);
1440
-
1441
- /**
1442
- * Parse the given body `str`.
1443
- *
1444
- * Used for auto-parsing of bodies. Parsers
1445
- * are defined on the `superagent.parse` object.
1446
- *
1447
- * @param {String} str
1448
- * @return {Mixed}
1449
- * @api private
1450
- */
1451
-
1452
- Response.prototype._parseBody = function(str) {
1453
- var parse = request.parse[this.type];
1454
- if (this.req._parser) {
1455
- return this.req._parser(this, str);
1456
- }
1457
- if (!parse && isJSON(this.type)) {
1458
- parse = request.parse['application/json'];
1459
- }
1460
- return parse && str && (str.length || str instanceof Object)
1461
- ? parse(str)
1462
- : null;
1463
- };
1464
-
1465
- /**
1466
- * Return an `Error` representative of this response.
1467
- *
1468
- * @return {Error}
1469
- * @api public
1470
- */
1471
-
1472
- Response.prototype.toError = function(){
1473
- var req = this.req;
1474
- var method = req.method;
1475
- var url = req.url;
1476
-
1477
- var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
1478
- var err = new Error(msg);
1479
- err.status = this.status;
1480
- err.method = method;
1481
- err.url = url;
1482
-
1483
- return err;
1484
- };
1485
-
1486
- /**
1487
- * Expose `Response`.
1488
- */
1489
-
1490
- request.Response = Response;
1491
-
1492
- /**
1493
- * Initialize a new `Request` with the given `method` and `url`.
1494
- *
1495
- * @param {String} method
1496
- * @param {String} url
1497
- * @api public
1498
- */
1499
-
1500
- function Request(method, url) {
1501
- var self = this;
1502
- this._query = this._query || [];
1503
- this.method = method;
1504
- this.url = url;
1505
- this.header = {}; // preserves header name case
1506
- this._header = {}; // coerces header names to lowercase
1507
- this.on('end', function(){
1508
- var err = null;
1509
- var res = null;
1510
-
1511
- try {
1512
- res = new Response(self);
1513
- } catch(e) {
1514
- err = new Error('Parser is unable to parse the response');
1515
- err.parse = true;
1516
- err.original = e;
1517
- // issue #675: return the raw response if the response parsing fails
1518
- if (self.xhr) {
1519
- // ie9 doesn't have 'response' property
1520
- err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;
1521
- // issue #876: return the http status code if the response parsing fails
1522
- err.status = self.xhr.status ? self.xhr.status : null;
1523
- err.statusCode = err.status; // backwards-compat only
1524
- } else {
1525
- err.rawResponse = null;
1526
- err.status = null;
1527
- }
1528
-
1529
- return self.callback(err);
1530
- }
1531
-
1532
- self.emit('response', res);
1533
-
1534
- var new_err;
1535
- try {
1536
- if (!self._isResponseOK(res)) {
1537
- new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
1538
- }
1539
- } catch(custom_err) {
1540
- new_err = custom_err; // ok() callback can throw
1541
- }
1542
-
1543
- // #1000 don't catch errors from the callback to avoid double calling it
1544
- if (new_err) {
1545
- new_err.original = err;
1546
- new_err.response = res;
1547
- new_err.status = res.status;
1548
- self.callback(new_err, res);
1549
- } else {
1550
- self.callback(null, res);
1551
- }
1552
- });
1553
- }
1554
-
1555
- /**
1556
- * Mixin `Emitter` and `RequestBase`.
1557
- */
1558
-
1559
- Emitter(Request.prototype);
1560
- RequestBase(Request.prototype);
1561
-
1562
- /**
1563
- * Set Content-Type to `type`, mapping values from `request.types`.
1564
- *
1565
- * Examples:
1566
- *
1567
- * superagent.types.xml = 'application/xml';
1568
- *
1569
- * request.post('/')
1570
- * .type('xml')
1571
- * .send(xmlstring)
1572
- * .end(callback);
1573
- *
1574
- * request.post('/')
1575
- * .type('application/xml')
1576
- * .send(xmlstring)
1577
- * .end(callback);
1578
- *
1579
- * @param {String} type
1580
- * @return {Request} for chaining
1581
- * @api public
1582
- */
1583
-
1584
- Request.prototype.type = function(type){
1585
- this.set('Content-Type', request.types[type] || type);
1586
- return this;
1587
- };
1588
-
1589
- /**
1590
- * Set Accept to `type`, mapping values from `request.types`.
1591
- *
1592
- * Examples:
1593
- *
1594
- * superagent.types.json = 'application/json';
1595
- *
1596
- * request.get('/agent')
1597
- * .accept('json')
1598
- * .end(callback);
1599
- *
1600
- * request.get('/agent')
1601
- * .accept('application/json')
1602
- * .end(callback);
1603
- *
1604
- * @param {String} accept
1605
- * @return {Request} for chaining
1606
- * @api public
1607
- */
1608
-
1609
- Request.prototype.accept = function(type){
1610
- this.set('Accept', request.types[type] || type);
1611
- return this;
1612
- };
1613
-
1614
- /**
1615
- * Set Authorization field value with `user` and `pass`.
1616
- *
1617
- * @param {String} user
1618
- * @param {String} [pass] optional in case of using 'bearer' as type
1619
- * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
1620
- * @return {Request} for chaining
1621
- * @api public
1622
- */
1623
-
1624
- Request.prototype.auth = function(user, pass, options){
1625
- if (1 === arguments.length) pass = '';
1626
- if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options
1627
- options = pass;
1628
- pass = '';
1629
- }
1630
- if (!options) {
1631
- options = {
1632
- type: 'function' === typeof btoa ? 'basic' : 'auto',
1633
- };
1634
- }
1635
-
1636
- var encoder = function(string) {
1637
- if ('function' === typeof btoa) {
1638
- return btoa(string);
1639
- }
1640
- throw new Error('Cannot use basic auth, btoa is not a function');
1641
- };
1642
-
1643
- return this._auth(user, pass, options, encoder);
1644
- };
1645
-
1646
- /**
1647
- * Add query-string `val`.
1648
- *
1649
- * Examples:
1650
- *
1651
- * request.get('/shoes')
1652
- * .query('size=10')
1653
- * .query({ color: 'blue' })
1654
- *
1655
- * @param {Object|String} val
1656
- * @return {Request} for chaining
1657
- * @api public
1658
- */
1659
-
1660
- Request.prototype.query = function(val){
1661
- if ('string' != typeof val) val = serialize(val);
1662
- if (val) this._query.push(val);
1663
- return this;
1664
- };
1665
-
1666
- /**
1667
- * Queue the given `file` as an attachment to the specified `field`,
1668
- * with optional `options` (or filename).
1669
- *
1670
- * ``` js
1671
- * request.post('/upload')
1672
- * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
1673
- * .end(callback);
1674
- * ```
1675
- *
1676
- * @param {String} field
1677
- * @param {Blob|File} file
1678
- * @param {String|Object} options
1679
- * @return {Request} for chaining
1680
- * @api public
1681
- */
1682
-
1683
- Request.prototype.attach = function(field, file, options){
1684
- if (file) {
1685
- if (this._data) {
1686
- throw Error("superagent can't mix .send() and .attach()");
1687
- }
1688
-
1689
- this._getFormData().append(field, file, options || file.name);
1690
- }
1691
- return this;
1692
- };
1693
-
1694
- Request.prototype._getFormData = function(){
1695
- if (!this._formData) {
1696
- this._formData = new root.FormData();
1697
- }
1698
- return this._formData;
1699
- };
1700
-
1701
- /**
1702
- * Invoke the callback with `err` and `res`
1703
- * and handle arity check.
1704
- *
1705
- * @param {Error} err
1706
- * @param {Response} res
1707
- * @api private
1708
- */
1709
-
1710
- Request.prototype.callback = function(err, res){
1711
- if (this._shouldRetry(err, res)) {
1712
- return this._retry();
1713
- }
1714
-
1715
- var fn = this._callback;
1716
- this.clearTimeout();
1717
-
1718
- if (err) {
1719
- if (this._maxRetries) err.retries = this._retries - 1;
1720
- this.emit('error', err);
1721
- }
1722
-
1723
- fn(err, res);
1724
- };
1725
-
1726
- /**
1727
- * Invoke callback with x-domain error.
1728
- *
1729
- * @api private
1730
- */
1731
-
1732
- Request.prototype.crossDomainError = function(){
1733
- var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
1734
- err.crossDomain = true;
1735
-
1736
- err.status = this.status;
1737
- err.method = this.method;
1738
- err.url = this.url;
1739
-
1740
- this.callback(err);
1741
- };
1742
-
1743
- // This only warns, because the request is still likely to work
1744
- Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){
1745
- console.warn("This is not supported in browser version of superagent");
1746
- return this;
1747
- };
1748
-
1749
- // This throws, because it can't send/receive data as expected
1750
- Request.prototype.pipe = Request.prototype.write = function(){
1751
- throw Error("Streaming is not supported in browser version of superagent");
1752
- };
1753
-
1754
- /**
1755
- * Check if `obj` is a host object,
1756
- * we don't want to serialize these :)
1757
- *
1758
- * @param {Object} obj
1759
- * @return {Boolean}
1760
- * @api private
1761
- */
1762
- Request.prototype._isHost = function _isHost(obj) {
1763
- // Native objects stringify to [object File], [object Blob], [object FormData], etc.
1764
- return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
1765
- }
1766
-
1767
- /**
1768
- * Initiate request, invoking callback `fn(res)`
1769
- * with an instanceof `Response`.
1770
- *
1771
- * @param {Function} fn
1772
- * @return {Request} for chaining
1773
- * @api public
1774
- */
1775
-
1776
- Request.prototype.end = function(fn){
1777
- if (this._endCalled) {
1778
- console.warn("Warning: .end() was called twice. This is not supported in superagent");
1779
- }
1780
- this._endCalled = true;
1781
-
1782
- // store callback
1783
- this._callback = fn || noop;
1784
-
1785
- // querystring
1786
- this._finalizeQueryString();
1787
-
1788
- return this._end();
1789
- };
1790
-
1791
- Request.prototype._end = function() {
1792
- var self = this;
1793
- var xhr = (this.xhr = request.getXHR());
1794
- var data = this._formData || this._data;
1795
-
1796
- this._setTimeouts();
1797
-
1798
- // state change
1799
- xhr.onreadystatechange = function(){
1800
- var readyState = xhr.readyState;
1801
- if (readyState >= 2 && self._responseTimeoutTimer) {
1802
- clearTimeout(self._responseTimeoutTimer);
1803
- }
1804
- if (4 != readyState) {
1805
- return;
1806
- }
1807
-
1808
- // In IE9, reads to any property (e.g. status) off of an aborted XHR will
1809
- // result in the error "Could not complete the operation due to error c00c023f"
1810
- var status;
1811
- try { status = xhr.status } catch(e) { status = 0; }
1812
-
1813
- if (!status) {
1814
- if (self.timedout || self._aborted) return;
1815
- return self.crossDomainError();
1816
- }
1817
- self.emit('end');
1818
- };
1819
-
1820
- // progress
1821
- var handleProgress = function(direction, e) {
1822
- if (e.total > 0) {
1823
- e.percent = e.loaded / e.total * 100;
1824
- }
1825
- e.direction = direction;
1826
- self.emit('progress', e);
1827
- };
1828
- if (this.hasListeners('progress')) {
1829
- try {
1830
- xhr.onprogress = handleProgress.bind(null, 'download');
1831
- if (xhr.upload) {
1832
- xhr.upload.onprogress = handleProgress.bind(null, 'upload');
1833
- }
1834
- } catch(e) {
1835
- // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
1836
- // Reported here:
1837
- // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
1838
- }
1839
- }
1840
-
1841
- // initiate request
1842
- try {
1843
- if (this.username && this.password) {
1844
- xhr.open(this.method, this.url, true, this.username, this.password);
1845
- } else {
1846
- xhr.open(this.method, this.url, true);
1847
- }
1848
- } catch (err) {
1849
- // see #1149
1850
- return this.callback(err);
1851
- }
1852
-
1853
- // CORS
1854
- if (this._withCredentials) xhr.withCredentials = true;
1855
-
1856
- // body
1857
- if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {
1858
- // serialize stuff
1859
- var contentType = this._header['content-type'];
1860
- var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
1861
- if (!serialize && isJSON(contentType)) {
1862
- serialize = request.serialize['application/json'];
1863
- }
1864
- if (serialize) data = serialize(data);
1865
- }
1866
-
1867
- // set header fields
1868
- for (var field in this.header) {
1869
- if (null == this.header[field]) continue;
1870
-
1871
- if (this.header.hasOwnProperty(field))
1872
- xhr.setRequestHeader(field, this.header[field]);
1873
- }
1874
-
1875
- if (this._responseType) {
1876
- xhr.responseType = this._responseType;
1877
- }
1878
-
1879
- // send stuff
1880
- this.emit('request', this);
1881
-
1882
- // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
1883
- // We need null here if data is undefined
1884
- xhr.send(typeof data !== 'undefined' ? data : null);
1885
- return this;
1886
- };
1887
-
1888
- request.agent = function() {
1889
- return new Agent();
1890
- };
1891
-
1892
- ["GET", "POST", "OPTIONS", "PATCH", "PUT", "DELETE"].forEach(function(method) {
1893
- Agent.prototype[method.toLowerCase()] = function(url, fn) {
1894
- var req = new request.Request(method, url);
1895
- this._setDefaults(req);
1896
- if (fn) {
1897
- req.end(fn);
1898
- }
1899
- return req;
1900
- };
1901
- });
1902
-
1903
- Agent.prototype.del = Agent.prototype['delete'];
1904
-
1905
- /**
1906
- * GET `url` with optional callback `fn(res)`.
1907
- *
1908
- * @param {String} url
1909
- * @param {Mixed|Function} [data] or fn
1910
- * @param {Function} [fn]
1911
- * @return {Request}
1912
- * @api public
1913
- */
1914
-
1915
- request.get = function(url, data, fn) {
1916
- var req = request('GET', url);
1917
- if ('function' == typeof data) (fn = data), (data = null);
1918
- if (data) req.query(data);
1919
- if (fn) req.end(fn);
1920
- return req;
1921
- };
1922
-
1923
- /**
1924
- * HEAD `url` with optional callback `fn(res)`.
1925
- *
1926
- * @param {String} url
1927
- * @param {Mixed|Function} [data] or fn
1928
- * @param {Function} [fn]
1929
- * @return {Request}
1930
- * @api public
1931
- */
1932
-
1933
- request.head = function(url, data, fn) {
1934
- var req = request('HEAD', url);
1935
- if ('function' == typeof data) (fn = data), (data = null);
1936
- if (data) req.query(data);
1937
- if (fn) req.end(fn);
1938
- return req;
1939
- };
1940
-
1941
- /**
1942
- * OPTIONS query to `url` with optional callback `fn(res)`.
1943
- *
1944
- * @param {String} url
1945
- * @param {Mixed|Function} [data] or fn
1946
- * @param {Function} [fn]
1947
- * @return {Request}
1948
- * @api public
1949
- */
1950
-
1951
- request.options = function(url, data, fn) {
1952
- var req = request('OPTIONS', url);
1953
- if ('function' == typeof data) (fn = data), (data = null);
1954
- if (data) req.send(data);
1955
- if (fn) req.end(fn);
1956
- return req;
1957
- };
1958
-
1959
- /**
1960
- * DELETE `url` with optional `data` and callback `fn(res)`.
1961
- *
1962
- * @param {String} url
1963
- * @param {Mixed} [data]
1964
- * @param {Function} [fn]
1965
- * @return {Request}
1966
- * @api public
1967
- */
1968
-
1969
- function del(url, data, fn) {
1970
- var req = request('DELETE', url);
1971
- if ('function' == typeof data) (fn = data), (data = null);
1972
- if (data) req.send(data);
1973
- if (fn) req.end(fn);
1974
- return req;
1975
- }
1976
-
1977
- request['del'] = del;
1978
- request['delete'] = del;
1979
-
1980
- /**
1981
- * PATCH `url` with optional `data` and callback `fn(res)`.
1982
- *
1983
- * @param {String} url
1984
- * @param {Mixed} [data]
1985
- * @param {Function} [fn]
1986
- * @return {Request}
1987
- * @api public
1988
- */
1989
-
1990
- request.patch = function(url, data, fn) {
1991
- var req = request('PATCH', url);
1992
- if ('function' == typeof data) (fn = data), (data = null);
1993
- if (data) req.send(data);
1994
- if (fn) req.end(fn);
1995
- return req;
1996
- };
1997
-
1998
- /**
1999
- * POST `url` with optional `data` and callback `fn(res)`.
2000
- *
2001
- * @param {String} url
2002
- * @param {Mixed} [data]
2003
- * @param {Function} [fn]
2004
- * @return {Request}
2005
- * @api public
2006
- */
2007
-
2008
- request.post = function(url, data, fn) {
2009
- var req = request('POST', url);
2010
- if ('function' == typeof data) (fn = data), (data = null);
2011
- if (data) req.send(data);
2012
- if (fn) req.end(fn);
2013
- return req;
2014
- };
2015
-
2016
- /**
2017
- * PUT `url` with optional `data` and callback `fn(res)`.
2018
- *
2019
- * @param {String} url
2020
- * @param {Mixed|Function} [data] or fn
2021
- * @param {Function} [fn]
2022
- * @return {Request}
2023
- * @api public
2024
- */
2025
-
2026
- request.put = function(url, data, fn) {
2027
- var req = request('PUT', url);
2028
- if ('function' == typeof data) (fn = data), (data = null);
2029
- if (data) req.send(data);
2030
- if (fn) req.end(fn);
2031
- return req;
2032
- };
2033
-
2034
- },{"./agent-base":1,"./is-object":2,"./request-base":3,"./response-base":4,"component-emitter":6}]},{},[7])(7)
2035
- });