@webex/http-core 3.0.0-beta.4 → 3.0.0-beta.400

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 (46) hide show
  1. package/README.md +0 -1
  2. package/dist/http-error-subtypes.js +2 -147
  3. package/dist/http-error-subtypes.js.map +1 -1
  4. package/dist/http-error.js +9 -38
  5. package/dist/http-error.js.map +1 -1
  6. package/dist/index.js +54 -30
  7. package/dist/index.js.map +1 -1
  8. package/dist/interceptors/http-status.js +7 -30
  9. package/dist/interceptors/http-status.js.map +1 -1
  10. package/dist/lib/detect.js +28 -48
  11. package/dist/lib/detect.js.map +1 -1
  12. package/dist/lib/interceptor.js +7 -23
  13. package/dist/lib/interceptor.js.map +1 -1
  14. package/dist/lib/xhr.js +49 -93
  15. package/dist/lib/xhr.js.map +1 -1
  16. package/dist/progress-event.js +0 -7
  17. package/dist/progress-event.js.map +1 -1
  18. package/dist/request/index.js +3 -44
  19. package/dist/request/index.js.map +1 -1
  20. package/dist/request/request.js +5 -23
  21. package/dist/request/request.js.map +1 -1
  22. package/dist/request/request.shim.js +40 -92
  23. package/dist/request/request.shim.js.map +1 -1
  24. package/dist/request/utils.js +91 -0
  25. package/dist/request/utils.js.map +1 -0
  26. package/package.json +10 -10
  27. package/src/http-error-subtypes.js +1 -1
  28. package/src/http-error.js +15 -23
  29. package/src/index.js +59 -9
  30. package/src/interceptors/http-status.js +7 -5
  31. package/src/lib/detect.js +0 -1
  32. package/src/lib/interceptor.js +2 -4
  33. package/src/lib/xhr.js +201 -194
  34. package/src/progress-event.js +10 -5
  35. package/src/request/index.js +4 -36
  36. package/src/request/request.js +16 -14
  37. package/src/request/request.shim.js +52 -40
  38. package/src/request/utils.ts +78 -0
  39. package/test/integration/spec/http-error.js +11 -11
  40. package/test/integration/spec/interceptor.js +20 -13
  41. package/test/integration/spec/progress-event.js +8 -8
  42. package/test/integration/spec/request.js +136 -127
  43. package/test/unit/spec/index.js +58 -0
  44. package/test/unit/spec/interceptors/http-status.js +14 -11
  45. package/test/unit/spec/request/request.shim.js +23 -0
  46. package/test/unit/spec/request/utils.js +77 -0
package/src/lib/xhr.js CHANGED
@@ -11,243 +11,250 @@
11
11
  // we're trying to diverge as little as possible.
12
12
  /* eslint-disable */
13
13
 
14
- "use strict";
15
- var window = require("global/window")
16
- var isFunction = require("is-function")
17
- var parseHeaders = require("parse-headers")
18
- var xtend = require("xtend")
19
-
20
- createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
21
- createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
22
-
23
- forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
24
- createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
25
- options = initParams(uri, options, callback)
26
- options.method = method.toUpperCase()
27
- return _createXHR(options)
28
- }
29
- })
14
+ 'use strict';
15
+ var window = require('global/window');
16
+ var isFunction = require('is-function');
17
+ var parseHeaders = require('parse-headers');
18
+ var xtend = require('xtend');
19
+
20
+ createXHR.XMLHttpRequest = window.XMLHttpRequest || noop;
21
+ createXHR.XDomainRequest =
22
+ 'withCredentials' in new createXHR.XMLHttpRequest()
23
+ ? createXHR.XMLHttpRequest
24
+ : window.XDomainRequest;
25
+
26
+ forEachArray(['get', 'put', 'post', 'patch', 'head', 'delete'], function (method) {
27
+ createXHR[method === 'delete' ? 'del' : method] = function (uri, options, callback) {
28
+ options = initParams(uri, options, callback);
29
+ options.method = method.toUpperCase();
30
+ return _createXHR(options);
31
+ };
32
+ });
30
33
 
31
34
  function forEachArray(array, iterator) {
32
- for (var i = 0; i < array.length; i+= 1) {
33
- iterator(array[i])
34
- }
35
+ for (var i = 0; i < array.length; i += 1) {
36
+ iterator(array[i]);
37
+ }
35
38
  }
36
39
 
37
- function isEmpty(obj){
38
- for(var i in obj){
39
- if(obj.hasOwnProperty(i)) return false
40
- }
41
- return true
40
+ function isEmpty(obj) {
41
+ for (var i in obj) {
42
+ if (obj.hasOwnProperty(i)) return false;
43
+ }
44
+ return true;
42
45
  }
43
46
 
44
47
  function initParams(uri, options, callback) {
45
- var params = uri
48
+ var params = uri;
46
49
 
47
- if (isFunction(options)) {
48
- callback = options
49
- if (typeof uri === "string") {
50
- params = {uri:uri}
51
- }
52
- } else {
53
- params = xtend(options, {uri: uri})
50
+ if (isFunction(options)) {
51
+ callback = options;
52
+ if (typeof uri === 'string') {
53
+ params = {uri: uri};
54
54
  }
55
+ } else {
56
+ params = xtend(options, {uri: uri});
57
+ }
55
58
 
56
- params.callback = callback
57
- return params
59
+ params.callback = callback;
60
+ return params;
58
61
  }
59
62
 
60
63
  function createXHR(uri, options, callback) {
61
- options = initParams(uri, options, callback)
62
- return _createXHR(options)
64
+ options = initParams(uri, options, callback);
65
+ return _createXHR(options);
63
66
  }
64
67
 
65
68
  function _createXHR(options) {
66
- if(typeof options.callback === "undefined"){
67
- throw new Error("callback argument missing")
69
+ if (typeof options.callback === 'undefined') {
70
+ throw new Error('callback argument missing');
71
+ }
72
+
73
+ var called = false;
74
+ var callback = function cbOnce(err, response, body) {
75
+ if (!called) {
76
+ called = true;
77
+ options.callback(err, response, body);
68
78
  }
79
+ };
69
80
 
70
- var called = false
71
- var callback = function cbOnce(err, response, body){
72
- if(!called){
73
- called = true
74
- options.callback(err, response, body)
75
- }
81
+ function readystatechange() {
82
+ if (xhr.readyState === 4) {
83
+ setTimeout(loadFunc, 0);
76
84
  }
85
+ }
77
86
 
78
- function readystatechange() {
79
- if (xhr.readyState === 4) {
80
- setTimeout(loadFunc, 0)
81
- }
82
- }
83
-
84
- function getBody() {
85
- // Chrome with requestType=blob throws errors arround when even testing access to responseText
86
- var body = undefined
87
-
88
- if (xhr.response) {
89
- body = xhr.response
90
- } else {
91
- body = xhr.responseText || getXml(xhr)
92
- }
87
+ function getBody() {
88
+ // Chrome with requestType=blob throws errors arround when even testing access to responseText
89
+ var body = undefined;
93
90
 
94
- if (isJson) {
95
- try {
96
- body = JSON.parse(body)
97
- } catch (e) {}
98
- }
99
-
100
- return body
91
+ if (xhr.response) {
92
+ body = xhr.response;
93
+ } else {
94
+ body = xhr.responseText || getXml(xhr);
101
95
  }
102
96
 
103
- function errorFunc(evt) {
104
- clearTimeout(timeoutTimer)
105
- if(!(evt instanceof Error)){
106
- evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
107
- }
108
- evt.statusCode = 0
109
- return callback(evt, failureResponse)
97
+ if (isJson) {
98
+ try {
99
+ body = JSON.parse(body);
100
+ } catch (e) {}
110
101
  }
111
102
 
112
- // will load the data & process the response in a special response object
113
- function loadFunc() {
114
- if (aborted) return
115
- var status
116
- clearTimeout(timeoutTimer)
117
- if(options.useXDR && xhr.status===undefined) {
118
- //IE8 CORS GET successful response doesn't have a status field, but body is fine
119
- status = 200
120
- } else {
121
- status = (xhr.status === 1223 ? 204 : xhr.status)
122
- }
123
- var response = failureResponse
124
- var err = null
125
-
126
- if (status !== 0){
127
- response = {
128
- body: getBody(),
129
- statusCode: status,
130
- method: method,
131
- headers: {},
132
- url: uri,
133
- rawRequest: xhr
134
- }
135
- if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
136
- response.headers = parseHeaders(xhr.getAllResponseHeaders())
137
- }
138
- } else {
139
- err = new Error("Internal XMLHttpRequest Error")
140
- }
141
- return callback(err, response, response.body)
103
+ return body;
104
+ }
105
+
106
+ function errorFunc(evt) {
107
+ clearTimeout(timeoutTimer);
108
+ if (!(evt instanceof Error)) {
109
+ if (evt instanceof ProgressEvent) {
110
+ evt = new Error(`XMLHttpRequest Error: ProgressEvent: loaded=${evt.loaded}, total=${evt.total}, lengthComputable=${evt.lengthComputable}, target.readyState=${evt.target?.readyState}`)
111
+ } else {
112
+ evt = new Error('' + (evt || 'Unknown XMLHttpRequest Error'));
113
+ }
142
114
  }
143
-
144
- var xhr = options.xhr || null
145
-
146
- if (!xhr) {
147
- if (options.cors || options.useXDR) {
148
- xhr = new createXHR.XDomainRequest()
149
- }else{
150
- xhr = new createXHR.XMLHttpRequest()
151
- }
115
+ evt.statusCode = 0;
116
+ return callback(evt, failureResponse);
117
+ }
118
+
119
+ // will load the data & process the response in a special response object
120
+ function loadFunc() {
121
+ if (aborted) return;
122
+ var status;
123
+ clearTimeout(timeoutTimer);
124
+ if (options.useXDR && xhr.status === undefined) {
125
+ //IE8 CORS GET successful response doesn't have a status field, but body is fine
126
+ status = 200;
127
+ } else {
128
+ status = xhr.status === 1223 ? 204 : xhr.status;
152
129
  }
130
+ var response = failureResponse;
131
+ var err = null;
153
132
 
154
- var key
155
- var aborted
156
- var uri = options.uri || options.url
157
- var method = options.method || "GET"
158
- var body = options.body || options.data
159
- var headers = options.headers || {}
160
- var sync = !!options.sync
161
- var isJson = false
162
- var timeoutTimer
163
- var failureResponse = {
164
- body: undefined,
165
- headers: {},
166
- statusCode: 0,
133
+ if (status !== 0) {
134
+ response = {
135
+ body: getBody(),
136
+ statusCode: status,
167
137
  method: method,
138
+ headers: {},
168
139
  url: uri,
169
- rawRequest: xhr
170
- }
171
-
172
- if ("json" in options && options.json !== false) {
173
- isJson = true
174
- headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
175
- if (method !== "GET" && method !== "HEAD") {
176
- headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
177
- body = JSON.stringify(options.json === true ? body : options.json)
178
- }
140
+ rawRequest: xhr,
141
+ };
142
+ if (xhr.getAllResponseHeaders) {
143
+ //remember xhr can in fact be XDR for CORS in IE
144
+ response.headers = parseHeaders(xhr.getAllResponseHeaders());
145
+ }
146
+ } else {
147
+ err = new Error('Internal XMLHttpRequest Error');
179
148
  }
149
+ return callback(err, response, response.body);
150
+ }
180
151
 
181
- xhr.onreadystatechange = readystatechange
182
- xhr.onload = loadFunc
183
- xhr.onerror = errorFunc
184
- // IE9 must have onprogress be set to a unique function.
185
- xhr.onprogress = function () {
186
- // IE must die
187
- }
188
- xhr.onabort = function(){
189
- aborted = true;
190
- }
191
- xhr.ontimeout = errorFunc
192
- xhr.open(method, uri, !sync, options.username, options.password)
193
- //has to be after open
194
- if(!sync) {
195
- xhr.withCredentials = !!options.withCredentials
196
- }
197
- // Cannot set timeout with sync request
198
- // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
199
- // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
200
- if (!sync && options.timeout > 0 ) {
201
- timeoutTimer = setTimeout(function(){
202
- if (aborted) return
203
- aborted = true//IE9 may still call readystatechange
204
- xhr.abort("timeout")
205
- var e = new Error("XMLHttpRequest timeout")
206
- e.code = "ETIMEDOUT"
207
- errorFunc(e)
208
- }, options.timeout )
209
- }
152
+ var xhr = options.xhr || null;
210
153
 
211
- if (xhr.setRequestHeader) {
212
- for(key in headers){
213
- if(headers.hasOwnProperty(key)){
214
- xhr.setRequestHeader(key, headers[key])
215
- }
216
- }
217
- } else if (options.headers && !isEmpty(options.headers)) {
218
- throw new Error("Headers cannot be set on an XDomainRequest object")
154
+ if (!xhr) {
155
+ if (options.cors || options.useXDR) {
156
+ xhr = new createXHR.XDomainRequest();
157
+ } else {
158
+ xhr = new createXHR.XMLHttpRequest();
219
159
  }
220
-
221
- if ("responseType" in options) {
222
- xhr.responseType = options.responseType
160
+ }
161
+
162
+ var key;
163
+ var aborted;
164
+ var uri = options.uri || options.url;
165
+ var method = options.method || 'GET';
166
+ var body = options.body || options.data;
167
+ var headers = options.headers || {};
168
+ var sync = !!options.sync;
169
+ var isJson = false;
170
+ var timeoutTimer;
171
+ var failureResponse = {
172
+ body: undefined,
173
+ headers: {},
174
+ statusCode: 0,
175
+ method: method,
176
+ url: uri,
177
+ rawRequest: xhr,
178
+ };
179
+
180
+ if ('json' in options && options.json !== false) {
181
+ isJson = true;
182
+ headers['accept'] || headers['Accept'] || (headers['Accept'] = 'application/json'); //Don't override existing accept header declared by user
183
+ if (method !== 'GET' && method !== 'HEAD') {
184
+ headers['content-type'] ||
185
+ headers['Content-Type'] ||
186
+ (headers['Content-Type'] = 'application/json'); //Don't override existing accept header declared by user
187
+ body = JSON.stringify(options.json === true ? body : options.json);
223
188
  }
224
-
225
- if ("beforeSend" in options &&
226
- typeof options.beforeSend === "function"
227
- ) {
228
- options.beforeSend(xhr)
189
+ }
190
+
191
+ xhr.onreadystatechange = readystatechange;
192
+ xhr.onload = loadFunc;
193
+ xhr.onerror = errorFunc;
194
+ // IE9 must have onprogress be set to a unique function.
195
+ xhr.onprogress = function () {
196
+ // IE must die
197
+ };
198
+ xhr.onabort = function () {
199
+ aborted = true;
200
+ };
201
+ xhr.ontimeout = errorFunc;
202
+ xhr.open(method, uri, !sync, options.username, options.password);
203
+ //has to be after open
204
+ if (!sync) {
205
+ xhr.withCredentials = !!options.withCredentials;
206
+ }
207
+ // Cannot set timeout with sync request
208
+ // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
209
+ // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
210
+ if (!sync && options.timeout > 0) {
211
+ timeoutTimer = setTimeout(function () {
212
+ if (aborted) return;
213
+ aborted = true; //IE9 may still call readystatechange
214
+ xhr.abort('timeout');
215
+ var e = new Error('XMLHttpRequest timeout');
216
+ e.code = 'ETIMEDOUT';
217
+ errorFunc(e);
218
+ }, options.timeout);
219
+ }
220
+
221
+ if (xhr.setRequestHeader) {
222
+ for (key in headers) {
223
+ if (headers.hasOwnProperty(key)) {
224
+ xhr.setRequestHeader(key, headers[key]);
225
+ }
229
226
  }
227
+ } else if (options.headers && !isEmpty(options.headers)) {
228
+ throw new Error('Headers cannot be set on an XDomainRequest object');
229
+ }
230
230
 
231
- // Microsoft Edge browser sends "undefined" when send is called with undefined value.
232
- // XMLHttpRequest spec says to pass null as body to indicate no body
233
- // See https://github.com/naugtur/xhr/issues/100.
234
- xhr.send(body || null)
231
+ if ('responseType' in options) {
232
+ xhr.responseType = options.responseType;
233
+ }
235
234
 
236
- return xhr
235
+ if ('beforeSend' in options && typeof options.beforeSend === 'function') {
236
+ options.beforeSend(xhr);
237
+ }
237
238
 
239
+ // Microsoft Edge browser sends "undefined" when send is called with undefined value.
240
+ // XMLHttpRequest spec says to pass null as body to indicate no body
241
+ // See https://github.com/naugtur/xhr/issues/100.
242
+ xhr.send(body || null);
238
243
 
244
+ return xhr;
239
245
  }
240
246
 
241
247
  function getXml(xhr) {
242
- if (xhr.responseType === "document") {
243
- return xhr.responseXML
244
- }
245
- var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
246
- if (xhr.responseType === "" && !firefoxBugTakenEffect) {
247
- return xhr.responseXML
248
- }
249
-
250
- return null
248
+ if (xhr.responseType === 'document') {
249
+ return xhr.responseXML;
250
+ }
251
+ var firefoxBugTakenEffect =
252
+ xhr.responseXML && xhr.responseXML.documentElement.nodeName === 'parsererror';
253
+ if (xhr.responseType === '' && !firefoxBugTakenEffect) {
254
+ return xhr.responseXML;
255
+ }
256
+
257
+ return null;
251
258
  }
252
259
 
253
260
  function noop() {}
@@ -16,17 +16,22 @@ export default function ProgressEvent(loaded, total) {
16
16
  loaded: {
17
17
  enumerable: true,
18
18
  value: loaded,
19
- writable: false
19
+ writable: false,
20
20
  },
21
21
  total: {
22
22
  enumerable: true,
23
23
  value: total,
24
- writable: false
24
+ writable: false,
25
25
  },
26
26
  lengthComputable: {
27
27
  enumerable: true,
28
- value: isNumber(loaded) && !Number.isNaN(loaded) && isNumber(total) && !Number.isNaN(total) && total > 0,
29
- writable: false
30
- }
28
+ value:
29
+ isNumber(loaded) &&
30
+ !Number.isNaN(loaded) &&
31
+ isNumber(total) &&
32
+ !Number.isNaN(total) &&
33
+ total > 0,
34
+ writable: false,
35
+ },
31
36
  });
32
37
  }
@@ -5,6 +5,7 @@
5
5
  import {EventEmitter} from 'events';
6
6
 
7
7
  import _request from './request';
8
+ import {intercept} from './utils';
8
9
 
9
10
  /**
10
11
  * @param {Object} options
@@ -21,42 +22,9 @@ export default function request(options) {
21
22
  options.download = new EventEmitter();
22
23
  options.upload = new EventEmitter();
23
24
 
24
- return intercept(options.interceptors, 'Request')
25
+ return intercept(options, options.interceptors, 'Request')
25
26
  .then((...args) => _request(options, ...args))
26
- .then((...args) => intercept(options.interceptors.slice().reverse(), 'Response', ...args));
27
-
28
- /**
29
- * @param {Array} interceptors
30
- * @param {string} key
31
- * @param {Object} res
32
- * @private
33
- * @returns {Promise}
34
- */
35
- function intercept(interceptors, key, res) {
36
- const successKey = `on${key}`;
37
- const errorKey = `on${key}Error`;
38
-
39
- return interceptors.reduce(
40
- (promise, interceptor) =>
41
- promise.then(
42
- (result) => {
43
- interceptor.logOptions(options);
44
- if (interceptor[successKey]) {
45
- return interceptor[successKey](options, result);
46
- }
47
-
48
- return Promise.resolve(result);
49
- },
50
- (reason) => {
51
- interceptor.logOptions(options);
52
- if (interceptor[errorKey]) {
53
- return interceptor[errorKey](options, reason);
54
- }
55
-
56
- return Promise.reject(reason);
57
- }
58
- ),
59
- Promise.resolve(res)
27
+ .then((...args) =>
28
+ intercept(options, options.interceptors.slice().reverse(), 'Response', ...args)
60
29
  );
61
- }
62
30
  }
@@ -24,12 +24,11 @@ function prepareOptions(options) {
24
24
  }
25
25
 
26
26
  if (isBuffer(options.body)) {
27
- return detect(options.body)
28
- .then((type) => {
29
- options.headers['content-type'] = type;
27
+ return detect(options.body).then((type) => {
28
+ options.headers['content-type'] = type;
30
29
 
31
- return options;
32
- });
30
+ return options;
31
+ });
33
32
  }
34
33
 
35
34
  return Promise.resolve(options);
@@ -54,24 +53,28 @@ function doRequest(options) {
54
53
 
55
54
  // I'm not sure why this line is necessary. request seems to be creating
56
55
  // buffers that aren't Buffers.
57
- if (options.responseType === 'buffer' && response.body.type === 'Buffer' && !isBuffer(response.body)) {
56
+ if (
57
+ options.responseType === 'buffer' &&
58
+ response.body.type === 'Buffer' &&
59
+ !isBuffer(response.body)
60
+ ) {
58
61
  response.body = Buffer.from(response.body);
59
62
  }
60
63
 
61
64
  if (isBuffer(response.body) && !response.body.type) {
62
- resolve(detect(response.body)
63
- .then((type) => {
65
+ resolve(
66
+ detect(response.body).then((type) => {
64
67
  response.body.type = type;
65
68
 
66
69
  return response;
67
- }));
70
+ })
71
+ );
68
72
 
69
73
  return;
70
74
  }
71
75
 
72
76
  resolve(response);
73
- }
74
- else {
77
+ } else {
75
78
  // Make a network error behave like a browser network error.
76
79
  resolve({
77
80
  statusCode: 0,
@@ -79,7 +82,7 @@ function doRequest(options) {
79
82
  headers: options.headers,
80
83
  method: options.method,
81
84
  url: options.url,
82
- body: error
85
+ body: error,
83
86
  });
84
87
  }
85
88
  });
@@ -102,6 +105,5 @@ function doRequest(options) {
102
105
  * @returns {Promise}
103
106
  */
104
107
  export default function _request(options) {
105
- return prepareOptions(options)
106
- .then(doRequest);
108
+ return prepareOptions(options).then(doRequest);
107
109
  }