diff --git a/.eslintrc.js b/.eslintrc.js index 069a0621..636cdceb 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -8,7 +8,6 @@ module.exports = { rules: { 'no-prototype-builtins': 0, 'no-unexpected-multiline': 0, - 'dot-notation': [2, { allowKeywords: false }], }, globals: { Promise: 'readonly', diff --git a/README.md b/README.md index e8d4e0d3..b51e7c6c 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Universal data access layer for web applications. -Typically on the server, you call your API or database directly to fetch some data. However, on the client, you cannot always call your services in the same way (i.e, cross domain policies). Instead, XHR requests need to be made to the server which get forwarded to your service. +Typically on the server, you call your API or database directly to fetch some data. However, on the client, you cannot always call your services in the same way (i.e, cross domain policies). Instead, XHR/fetch requests need to be made to the server which get forwarded to your service. Having to write code differently for both environments is duplicative and error prone. Fetchr provides an abstraction layer over your data service calls so that you can fetch data using the same API on the server and client side. @@ -16,6 +16,8 @@ Having to write code differently for both environments is duplicative and error npm install fetchr --save ``` +_Important:_ when on browser, `Fetchr` relies fully on [`Fetch`](https://fetch.spec.whatwg.org/) API. If you need to support old browsers, you will need to install a polyfill as well (eg. https://github.com/github/fetch). + ## Setup Follow the steps below to setup Fetchr properly. This assumes you are using the [Express](https://www.npmjs.com/package/express) framework. @@ -149,8 +151,8 @@ See the [simple example](https://github.com/yahoo/fetchr/tree/master/examples/si ## Service Metadata -Service calls on the client transparently become xhr requests. -It is a good idea to set cache headers on common xhr calls. +Service calls on the client transparently become fetch requests. +It is a good idea to set cache headers on common fetch calls. You can do so by providing a third parameter in your service's callback. If you want to look at what headers were set by the service you just called, simply inspect the third parameter in the callback. @@ -169,7 +171,7 @@ export default { headers: { 'cache-control': 'public, max-age=3600', }, - statusCode: 200, // You can even provide a custom statusCode for the xhr response + statusCode: 200, // You can even provide a custom statusCode for the fetch response }; callback(null, data, meta); }, @@ -241,9 +243,9 @@ fetcher }); ``` -## XHR Object +## Abort support -The xhr object is returned by the `.end()` method as long as you're _not_ chaining promises. +An object with an `abort` method is returned by the `.end()` method as long as you're _not_ chaining promises. This is useful if you want to abort a request before it is completed. ```js @@ -253,11 +255,11 @@ const req = fetcher .end(function (err, data, meta) { // err.output will be { message: "Not found", more: "meta data" } }); -// req is the xhr object + req.abort(); ``` -However, you can't acces the xhr object if using promise chaining like so: +However, due to the current implementation, you can't access this method if using promise chaining like so: ```js const req = fetcher @@ -268,10 +270,10 @@ const req = fetcher req.then(onResolve, onReject); ``` -## XHR Timeouts +## Timeouts `xhrTimeout` is an optional config property that allows you to set timeout (in ms) for all clientside requests, defaults to `3000`. -On the clientside, xhrPath and xhrTimeout will be used for XHR requests. +On the clientside, xhrPath and xhrTimeout will be used for all requests. On the serverside, xhrPath and xhrTimeout are not needed and are ignored. ```js @@ -294,9 +296,9 @@ fetcher }); ``` -## XHR Params Processing +## Params Processing -For some applications, there may be a situation where you need to process the service params passed in XHR request before params are sent to the actual service. Typically, you would process these params in the service itself. However, if you want to perform processing across many services (i.e. sanitization for security), then you can use the `paramsProcessor` option. +For some applications, there may be a situation where you need to process the service params passed in the request before they are sent to the actual service. Typically, you would process them in the service itself. However, if you neet to perform processing across many services (i.e. sanitization for security), then you can use the `paramsProcessor` option. `paramsProcessor` is a function that is passed into the `Fetcher.middleware` method. It is passed three arguments, the request object, the serviceInfo object, and the service params object. The `paramsProcessor` function can then modify the service params if needed. @@ -318,9 +320,9 @@ app.use( ); ``` -## XHR Response Formatting +## Response Formatting -For some applications, there may be a situation where you need to modify an XHR response before it is passed to the client. Typically, you would apply your modifications in the service itself. However, if you want to modify the XHR responses across many services (i.e. add debug information), then you can use the `responseFormatter` option. +For some applications, there may be a situation where you need to modify the response before it is passed to the client. Typically, you would apply your modifications in the service itself. However, if you need to modify the responses across many services (i.e. add debug information), then you can use the `responseFormatter` option. `responseFormatter` is a function that is passed into the `Fetcher.middleware` method. It is passed three arguments, the request object, response object and the service response object (i.e. the data returned from your service). The `responseFormatter` function can then modify the service response to add additional information. @@ -342,7 +344,7 @@ app.use( ); ``` -Now when an XHR request is performed, your response will contain the `debug` property added above. +Now when an request is performed, your response will contain the `debug` property added above. ## CORS Support @@ -392,31 +394,31 @@ fetcher ## CSRF Protection -You can protect your XHR paths from CSRF attacks by adding a middleware in front of the fetchr middleware: +You can protect your Fetchr middleware paths from CSRF attacks by adding a middleware in front of it: `app.use('/myCustomAPIEndpoint', csrf(), Fetcher.middleware());` You could use https://github.com/expressjs/csurf for this as an example. -Next you need to make sure that the CSRF token is being sent with our XHR requests so that they can be validated. To do this, pass the token in as a key in the `options.context` object on the client: +Next you need to make sure that the CSRF token is being sent with our requests so that they can be validated. To do this, pass the token in as a key in the `options.context` object on the client: ```js const fetcher = new Fetcher({ - xhrPath: '/myCustomAPIEndpoint', //xhrPath is REQUIRED on the clientside fetcher instantiation + xhrPath: '/myCustomAPIEndpoint', // xhrPath is REQUIRED on the clientside fetcher instantiation context: { - // These context values are persisted with XHR calls as query params + // These context values are persisted with client calls as query params _csrf: 'Ax89D94j', }, }); ``` -This `_csrf` will be sent in all XHR requests as a query parameter so that it can be validated on the server. +This `_csrf` will be sent in all client requests as a query parameter so that it can be validated on the server. ## Service Call Config When calling a Fetcher service you can pass an optional config object. -When this call is made from the client, the config object is used to define XHR request options and can be used to override default options: +When this call is made from the client, the config object is used to set some request options and can be used to override default options: ```js //app.js - client @@ -445,7 +447,7 @@ fetcher .end(); ``` -With this configuration, Fetchr will retry all requests that fail with 408 status code or with an XHR 0 status code two more times before returning an error. The interval between each request respects +With this configuration, Fetchr will retry all requests that fail with 408 status code or that failed without even reaching the service (status code 0 means, for example, that the client was not able to reach the server) two more times before returning an error. The interval between each request respects the following formula, based on the exponential backoff and full jitter strategy published in [this AWS architecture blog post](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/): ```js @@ -487,14 +489,14 @@ fetcher ## Context Variables -By Default, fetchr appends all context values to the xhr url as query params. `contextPicker` allows you to greater control over which context variables get sent as query params depending on the xhr method (`GET` or `POST`). This is useful when you want to limit the number of variables in a `GET` url in order not to accidentally [cache bust](http://webassets.readthedocs.org/en/latest/expiring.html). +By Default, fetchr appends all context values to the request url as query params. `contextPicker` allows you to have greater control over which context variables get sent as query params depending on the request method (`GET` or `POST`). This is useful when you want to limit the number of variables in a `GET` url in order not to accidentally [cache bust](http://webassets.readthedocs.org/en/latest/expiring.html). `contextPicker` follows the same format as the `predicate` parameter in [`lodash/pickBy`](https://lodash.com/docs#pickBy) with two arguments: `(value, key)`. ```js const fetcher = new Fetcher({ context: { - // These context values are persisted with XHR calls as query params + // These context values are persisted with client calls as query params _csrf: 'Ax89D94j', device: 'desktop', }, @@ -512,7 +514,7 @@ const fetcher = new Fetcher({ const fetcher = new Fetcher({ context: { - // These context values are persisted with XHR calls as query params + // These context values are persisted with client calls as query params _csrf: 'Ax89D94j', device: 'desktop', }, diff --git a/docs/fetchr.md b/docs/fetchr.md index 35b8ce17..9df7a540 100644 --- a/docs/fetchr.md +++ b/docs/fetchr.md @@ -6,8 +6,8 @@ Creates a new fetchr plugin instance with the following parameters: - `options`: An object containing the plugin settings - `options.req` (required on server): The request object. It can contain per-request/context data. -- `options.xhrPath` (optional): The path for XHR requests. Will be ignored serverside. -- `options.xhrTimeout` (optional): Timeout in milliseconds for all XHR requests +- `options.xhrPath` (optional): The path for all requests. Will be ignored serverside. +- `options.xhrTimeout` (optional): Timeout in milliseconds for all requests - `options.corsPath` (optional): Base CORS path in case CORS is enabled - `options.context` (optional): The context object - `options.contextPicker` (optional): The context predicate functions, it will be applied to lodash/object/pick to pick values from context object diff --git a/libs/fetcher.client.js b/libs/fetcher.client.js index 4135778d..65c474df 100644 --- a/libs/fetcher.client.js +++ b/libs/fetcher.client.js @@ -11,8 +11,8 @@ */ var REST = require('./util/http.client'); var DEFAULT_GUID = 'g0'; -var DEFAULT_XHR_PATH = '/api'; -var DEFAULT_XHR_TIMEOUT = 3000; +var DEFAULT_PATH = '/api'; +var DEFAULT_TIMEOUT = 3000; var MAX_URI_LEN = 2048; var OP_READ = 'read'; var defaultConstructGetUri = require('./util/defaultConstructGetUri'); @@ -91,8 +91,8 @@ function Request(operation, resource, options) { this.resource = resource; this.options = { headers: options.headers, - xhrPath: options.xhrPath || DEFAULT_XHR_PATH, - xhrTimeout: options.xhrTimeout || DEFAULT_XHR_TIMEOUT, + xhrPath: options.xhrPath || DEFAULT_PATH, + xhrTimeout: options.xhrTimeout || DEFAULT_TIMEOUT, corsPath: options.corsPath, context: options.context || {}, contextPicker: options.contextPicker || {}, @@ -374,8 +374,8 @@ Request.prototype._constructGroupUri = function (uri) { * Fetcher class for the client. Provides CRUD methods. * @class FetcherClient * @param {Object} options configuration options for Fetcher - * @param {String} [options.xhrPath="/api"] The path for XHR requests - * @param {Number} [options.xhrTimout=3000] Timeout in milliseconds for all XHR requests + * @param {String} [options.xhrPath="/api"] The path for requests + * @param {Number} [options.xhrTimout=3000] Timeout in milliseconds for all requests * @param {Boolean} [options.corsPath] Base CORS path in case CORS is enabled * @param {Object} [options.context] The context object that is propagated to all outgoing * requests as query params. It can contain current-session/context data that should @@ -550,7 +550,7 @@ Fetcher.prototype = { /** * get the serviceMeta array. - * The array contains all xhr meta returned in this session + * The array contains all requests meta returned in this session * with the 0 index being the first call. * @method getServiceMeta * @return {Array} array of metadata returned by each service call diff --git a/libs/util/defaultConstructGetUri.js b/libs/util/defaultConstructGetUri.js index df6aa02b..8f6bb441 100644 --- a/libs/util/defaultConstructGetUri.js +++ b/libs/util/defaultConstructGetUri.js @@ -19,7 +19,7 @@ function jsonifyComplexType(value) { } /** - * Construct xhr GET URI. + * Construct GET URI. * @method defaultConstructGetUri * @param {String} uri base URI * @param {String} resource Resource name diff --git a/libs/util/http.client.js b/libs/util/http.client.js index 813e239a..fb1dac32 100644 --- a/libs/util/http.client.js +++ b/libs/util/http.client.js @@ -7,7 +7,6 @@ * @module rest-http */ -var xhr = require('xhr'); var forEach = require('./forEach'); /* @@ -127,7 +126,7 @@ function mergeConfig(config) { return cfg; } -function doXhr(method, url, headers, data, config, attempt, callback) { +function doRequest(method, url, headers, data, config, attempt, callback) { headers = normalizeHeaders(headers, method, config.cors); config = mergeConfig(config); @@ -135,16 +134,13 @@ function doXhr(method, url, headers, data, config, attempt, callback) { method: method, timeout: config.timeout, headers: headers, - useXDR: config.useXDR, withCredentials: config.withCredentials, on: { success: function (err, response) { callback(NULL, response); }, failure: function (err, response) { - if ( - !shouldRetry(method, config, response.statusCode, attempt) - ) { + if (!shouldRetry(method, config, response.status, attempt)) { callback(err); } else { // Use exponential backoff and full jitter strategy published in https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ @@ -153,8 +149,8 @@ function doXhr(method, url, headers, data, config, attempt, callback) { config.retry.interval * Math.pow(2, attempt); - setTimeout(function retryXHR() { - doXhr( + setTimeout(function retryRequest() { + doRequest( method, url, headers, @@ -174,62 +170,99 @@ function doXhr(method, url, headers, data, config, attempt, callback) { return io(url, options); } -function io(url, options) { - return xhr( - { - url: url, - method: options.method || METHOD_GET, - timeout: options.timeout, - headers: options.headers, - body: options.data, - useXDR: options.cors, - withCredentials: options.withCredentials, - }, - function (err, resp, body) { - var status = resp.statusCode; - var errMessage, errBody; - - if (!err && (status === 0 || (status >= 400 && status < 600))) { - if (typeof body === 'string') { - try { - errBody = JSON.parse(body); - if (errBody.message) { - errMessage = errBody.message; - } else { - errMessage = body; - } - } catch (e) { - errMessage = body; - } - } else { - errMessage = status - ? 'Error ' + status - : 'Internal Fetchr XMLHttpRequest Error'; - } +function FetchrError(options, request, response, responseBody, originalError) { + var err = originalError; + var status = response ? response.status : 0; + var errMessage, errBody; - err = new Error(errMessage); - err.statusCode = status; - err.body = errBody || body; - if (err.body) { - err.output = err.body.output; - err.meta = err.body.meta; + if (!err && (status === 0 || (status >= 400 && status < 600))) { + if (typeof responseBody === 'string') { + try { + errBody = JSON.parse(responseBody); + if (errBody.message) { + errMessage = errBody.message; + } else { + errMessage = responseBody; } + } catch (e) { + errMessage = responseBody; } + } else { + errMessage = status + ? 'Error ' + status + : 'Internal Fetchr XMLHttpRequest Error'; + } + + err = new Error(errMessage); + err.body = errBody || responseBody; + if (err.body) { + err.output = err.body.output; + err.meta = err.body.meta; + } + } + + err.rawRequest = { + headers: options.headers, + method: request.method, + url: request.url, + }; + err.statusCode = status; + err.timeout = options.timeout; + err.url = request.url; + + return err; +} - resp.responseText = body; +function io(url, options) { + var controller = new AbortController(); + + var request = new Request(url, { + method: options.method, + headers: options.headers, + body: options.data, + credentials: options.withCredentials ? 'include' : 'same-origin', + signal: controller.signal, + }); - if (err) { - // getting detail info from xhr module - err.rawRequest = resp.rawRequest; - err.url = resp.url; - err.timeout = options.timeout; + var timeoutId = setTimeout(function () { + controller.abort(); + }, options.timeout); - options.on.failure.call(null, err, resp); + fetch(request) + .then(function (response) { + clearTimeout(timeoutId); + + if (response.ok) { + response.text().then(function (responseBody) { + options.on.success(null, { + responseText: responseBody, + statusCode: response.status, + }); + }); } else { - options.on.success.call(null, null, resp); + response.text().then(function (responseBody) { + options.on.failure( + new FetchrError( + options, + request, + response, + responseBody + ), + response + ); + }); } - } - ); + }) + .catch(function (err) { + clearTimeout(timeoutId); + + options.on.failure( + new FetchrError(options, request, null, null, err), + { status: 0 } + ); + }); + + return controller; } /** @@ -251,7 +284,7 @@ module.exports = { * @param {Function} callback The callback function, with two params (error, response) */ get: function (url, headers, config, callback) { - return doXhr( + return doRequest( METHOD_GET, url, headers, @@ -277,7 +310,7 @@ module.exports = { * @param {Function} callback The callback function, with two params (error, response) */ post: function (url, headers, data, config, callback) { - return doXhr( + return doRequest( METHOD_POST, url, headers, diff --git a/package-lock.json b/package-lock.json index 3c7087e9..03f5f613 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,15 +7,17 @@ "": { "version": "0.6.2", "dependencies": { - "fumble": "^0.1.0", - "xhr": "^2.4.0" + "fumble": "^0.1.0" }, "devDependencies": { + "abortcontroller-polyfill": "^1.7.3", "chai": "^4.2.0", "eslint": "^7.29.0", "express": "^4.17.1", + "fetch-mock": "^9.11.0", "mocha": "^9.0.0", "mockery": "^2.0.0", + "node-fetch": "^2.6.2", "nyc": "^15.1.0", "pre-commit": "^1.0.0", "prettier": "^2.3.2", @@ -396,6 +398,18 @@ "node": ">=6.0.0" } }, + "node_modules/@babel/runtime": { + "version": "7.15.4", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.15.4.tgz", + "integrity": "sha512-99catp6bHCaxr4sJ/DbTGgHS4+Rs2RVd2g7iOap6SLGPDknRK9ztKNsE/Fg6QhSeh1FGE5f6gHGQmvvn3I3xhw==", + "dev": true, + "dependencies": { + "regenerator-runtime": "^0.13.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.15.4", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.15.4.tgz", @@ -865,6 +879,12 @@ "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", "dev": true }, + "node_modules/abortcontroller-polyfill": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/abortcontroller-polyfill/-/abortcontroller-polyfill-1.7.3.tgz", + "integrity": "sha512-zetDJxd89y3X99Kvo4qFx8GKlt6GsvN3UcRZHwU6iFA/0KiOmhkTVhe8oRoTBiTVPZu09x3vCra47+w8Yz1+2Q==", + "dev": true + }, "node_modules/accepts": { "version": "1.3.7", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", @@ -1616,6 +1636,17 @@ "integrity": "sha512-Mw+adcfzPxcPeI+0WlvRrr/3lGVO0bD75SxX6811cxSh1Wbxx7xZBGK1eVtDf6si8rg2lhnUjsVLMFMfbRIuwA==", "dev": true }, + "node_modules/core-js": { + "version": "3.18.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.18.0.tgz", + "integrity": "sha512-WJeQqq6jOYgVgg4NrXKL0KLQhi0CT4ZOCvFL+3CQ5o7I6J8HkT5wd53EadMfqTDp1so/MT1J+w2ujhWcCJtN7w==", + "dev": true, + "hasInstallScript": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, "node_modules/core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", @@ -1743,11 +1774,6 @@ "node": ">=6.0.0" } }, - "node_modules/dom-walk": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/dom-walk/-/dom-walk-0.1.2.tgz", - "integrity": "sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w==" - }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -2317,6 +2343,71 @@ "pend": "~1.2.0" } }, + "node_modules/fetch-mock": { + "version": "9.11.0", + "resolved": "https://registry.npmjs.org/fetch-mock/-/fetch-mock-9.11.0.tgz", + "integrity": "sha512-PG1XUv+x7iag5p/iNHD4/jdpxL9FtVSqRMUQhPab4hVDt80T1MH5ehzVrL2IdXO9Q2iBggArFvPqjUbHFuI58Q==", + "dev": true, + "dependencies": { + "@babel/core": "^7.0.0", + "@babel/runtime": "^7.0.0", + "core-js": "^3.0.0", + "debug": "^4.1.1", + "glob-to-regexp": "^0.4.0", + "is-subset": "^0.1.1", + "lodash.isequal": "^4.5.0", + "path-to-regexp": "^2.2.1", + "querystring": "^0.2.0", + "whatwg-url": "^6.5.0" + }, + "engines": { + "node": ">=4.0.0" + }, + "funding": { + "type": "charity", + "url": "https://www.justgiving.com/refugee-support-europe" + }, + "peerDependencies": { + "node-fetch": "*" + }, + "peerDependenciesMeta": { + "node-fetch": { + "optional": true + } + } + }, + "node_modules/fetch-mock/node_modules/path-to-regexp": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-2.4.0.tgz", + "integrity": "sha512-G6zHoVqC6GGTQkZwF4lkuEyMbVOjoBKAEybQUypI1WTkqinCOrq2x6U2+phkJ1XsEMTy4LjtwPI7HW+NVrRR2w==", + "dev": true + }, + "node_modules/fetch-mock/node_modules/tr46": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", + "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/fetch-mock/node_modules/webidl-conversions": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", + "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", + "dev": true + }, + "node_modules/fetch-mock/node_modules/whatwg-url": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-6.5.0.tgz", + "integrity": "sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==", + "dev": true, + "dependencies": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + }, "node_modules/file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -2691,15 +2782,6 @@ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", "dev": true }, - "node_modules/global": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/global/-/global-4.4.0.tgz", - "integrity": "sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w==", - "dependencies": { - "min-document": "^2.19.0", - "process": "^0.11.10" - } - }, "node_modules/globals": { "version": "13.10.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.10.0.tgz", @@ -2953,11 +3035,6 @@ "node": ">=0.10.0" } }, - "node_modules/is-function": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-function/-/is-function-1.0.2.tgz", - "integrity": "sha512-lw7DUp0aWXYg+CBCN+JKkcE0Q2RayZnSvnZBlwgxHBQhqt5pZNVy4Ri7H9GmmXkdu7LUthszM+Tor1u/2iBcpQ==" - }, "node_modules/is-glob": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", @@ -3000,6 +3077,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-subset": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-subset/-/is-subset-0.1.1.tgz", + "integrity": "sha1-ilkRfZMt4d4A8kX83TnOQ/HpOaY=", + "dev": true + }, "node_modules/is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", @@ -3343,12 +3426,24 @@ "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=", "dev": true }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha1-QVxEePK8wwEgwizhDtMib30+GOA=", + "dev": true + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "dev": true }, + "node_modules/lodash.sortby": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", + "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", + "dev": true + }, "node_modules/lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", @@ -3468,14 +3563,6 @@ "node": ">= 0.6" } }, - "node_modules/min-document": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/min-document/-/min-document-2.19.0.tgz", - "integrity": "sha1-e9KC4/WELtKVu3SM3Z8f+iyCRoU=", - "dependencies": { - "dom-walk": "^0.1.0" - } - }, "node_modules/minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", @@ -3688,10 +3775,13 @@ } }, "node_modules/node-fetch": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", - "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.4.tgz", + "integrity": "sha512-aD1fO+xtLiSCc9vuD+sYMxpIuQyhHscGSkBEo2o5LTV/3bTEAYvdUii29n8LlO5uLCmWdGP7uVUVXFo5SRdkLA==", "dev": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, "engines": { "node": "4.x || >=6.0.0" } @@ -4061,11 +4151,6 @@ "node": ">=6" } }, - "node_modules/parse-headers": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.3.tgz", - "integrity": "sha512-QhhZ+DCCit2Coi2vmAKbq5RGTRcQUOE2+REgv8vdyu7MnYx2eZztegqtTx99TZ86GTIwqiy3+4nQTWZ2tgmdCA==" - }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -4235,14 +4320,6 @@ "node": ">=10.13.0" } }, - "node_modules/process": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", - "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", - "engines": { - "node": ">= 0.6.0" - } - }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", @@ -4338,6 +4415,15 @@ "node": ">=10.18.1" } }, + "node_modules/puppeteer/node_modules/node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", + "dev": true, + "engines": { + "node": "4.x || >=6.0.0" + } + }, "node_modules/puppeteer/node_modules/progress": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.1.tgz", @@ -4362,6 +4448,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/querystring": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.1.tgz", + "integrity": "sha512-wkvS7mL/JMugcup3/rMitHmd9ecIGd2lhFhK9N3UUQ450h66d1r3Y9nvXzQAW1Lq+wyx61k/1pfKS5KuKiyEbg==", + "deprecated": "The querystring API is considered Legacy. new code should use the URLSearchParams API instead.", + "dev": true, + "engines": { + "node": ">=0.4.x" + } + }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -4421,6 +4517,12 @@ "node": ">=8.10.0" } }, + "node_modules/regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==", + "dev": true + }, "node_modules/regexpp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", @@ -5176,6 +5278,12 @@ "node": ">=0.6" } }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=", + "dev": true + }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -5306,6 +5414,12 @@ "node": ">=10.13.0" } }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=", + "dev": true + }, "node_modules/webpack": { "version": "5.54.0", "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.54.0.tgz", @@ -5386,6 +5500,16 @@ "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "dev": true }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=", + "dev": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/which": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", @@ -5519,25 +5643,6 @@ } } }, - "node_modules/xhr": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/xhr/-/xhr-2.6.0.tgz", - "integrity": "sha512-/eCGLb5rxjx5e3mF1A7s+pLlR6CGyqWN91fv1JgER5mVWg1MZmlhBvy9kjcsOdRk8RrIujotWyJamfyrp+WIcA==", - "dependencies": { - "global": "~4.4.0", - "is-function": "^1.0.1", - "parse-headers": "^2.0.0", - "xtend": "^4.0.0" - } - }, - "node_modules/xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "engines": { - "node": ">=0.4" - } - }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", @@ -5961,6 +6066,15 @@ "integrity": "sha512-rycZXvQ+xS9QyIcJ9HXeDWf1uxqlbVFAUq0Rq0dbc50Zb/+wUe/ehyfzGfm9KZZF0kBejYgxltBXocP+gKdL2g==", "dev": true }, + "@babel/runtime": { + "version": "7.15.4", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.15.4.tgz", + "integrity": "sha512-99catp6bHCaxr4sJ/DbTGgHS4+Rs2RVd2g7iOap6SLGPDknRK9ztKNsE/Fg6QhSeh1FGE5f6gHGQmvvn3I3xhw==", + "dev": true, + "requires": { + "regenerator-runtime": "^0.13.4" + } + }, "@babel/template": { "version": "7.15.4", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.15.4.tgz", @@ -6386,6 +6500,12 @@ "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", "dev": true }, + "abortcontroller-polyfill": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/abortcontroller-polyfill/-/abortcontroller-polyfill-1.7.3.tgz", + "integrity": "sha512-zetDJxd89y3X99Kvo4qFx8GKlt6GsvN3UcRZHwU6iFA/0KiOmhkTVhe8oRoTBiTVPZu09x3vCra47+w8Yz1+2Q==", + "dev": true + }, "accepts": { "version": "1.3.7", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", @@ -6982,6 +7102,12 @@ "integrity": "sha512-Mw+adcfzPxcPeI+0WlvRrr/3lGVO0bD75SxX6811cxSh1Wbxx7xZBGK1eVtDf6si8rg2lhnUjsVLMFMfbRIuwA==", "dev": true }, + "core-js": { + "version": "3.18.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.18.0.tgz", + "integrity": "sha512-WJeQqq6jOYgVgg4NrXKL0KLQhi0CT4ZOCvFL+3CQ5o7I6J8HkT5wd53EadMfqTDp1so/MT1J+w2ujhWcCJtN7w==", + "dev": true + }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", @@ -7077,11 +7203,6 @@ "esutils": "^2.0.2" } }, - "dom-walk": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/dom-walk/-/dom-walk-0.1.2.tgz", - "integrity": "sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w==" - }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -7539,6 +7660,58 @@ "pend": "~1.2.0" } }, + "fetch-mock": { + "version": "9.11.0", + "resolved": "https://registry.npmjs.org/fetch-mock/-/fetch-mock-9.11.0.tgz", + "integrity": "sha512-PG1XUv+x7iag5p/iNHD4/jdpxL9FtVSqRMUQhPab4hVDt80T1MH5ehzVrL2IdXO9Q2iBggArFvPqjUbHFuI58Q==", + "dev": true, + "requires": { + "@babel/core": "^7.0.0", + "@babel/runtime": "^7.0.0", + "core-js": "^3.0.0", + "debug": "^4.1.1", + "glob-to-regexp": "^0.4.0", + "is-subset": "^0.1.1", + "lodash.isequal": "^4.5.0", + "path-to-regexp": "^2.2.1", + "querystring": "^0.2.0", + "whatwg-url": "^6.5.0" + }, + "dependencies": { + "path-to-regexp": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-2.4.0.tgz", + "integrity": "sha512-G6zHoVqC6GGTQkZwF4lkuEyMbVOjoBKAEybQUypI1WTkqinCOrq2x6U2+phkJ1XsEMTy4LjtwPI7HW+NVrRR2w==", + "dev": true + }, + "tr46": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", + "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "webidl-conversions": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", + "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", + "dev": true + }, + "whatwg-url": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-6.5.0.tgz", + "integrity": "sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==", + "dev": true, + "requires": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + } + } + }, "file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -7812,15 +7985,6 @@ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", "dev": true }, - "global": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/global/-/global-4.4.0.tgz", - "integrity": "sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w==", - "requires": { - "min-document": "^2.19.0", - "process": "^0.11.10" - } - }, "globals": { "version": "13.10.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.10.0.tgz", @@ -7996,11 +8160,6 @@ "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", "dev": true }, - "is-function": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-function/-/is-function-1.0.2.tgz", - "integrity": "sha512-lw7DUp0aWXYg+CBCN+JKkcE0Q2RayZnSvnZBlwgxHBQhqt5pZNVy4Ri7H9GmmXkdu7LUthszM+Tor1u/2iBcpQ==" - }, "is-glob": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", @@ -8028,6 +8187,12 @@ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", "dev": true }, + "is-subset": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-subset/-/is-subset-0.1.1.tgz", + "integrity": "sha1-ilkRfZMt4d4A8kX83TnOQ/HpOaY=", + "dev": true + }, "is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", @@ -8295,12 +8460,24 @@ "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=", "dev": true }, + "lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha1-QVxEePK8wwEgwizhDtMib30+GOA=", + "dev": true + }, "lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "dev": true }, + "lodash.sortby": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", + "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", + "dev": true + }, "lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", @@ -8389,14 +8566,6 @@ "mime-db": "1.44.0" } }, - "min-document": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/min-document/-/min-document-2.19.0.tgz", - "integrity": "sha1-e9KC4/WELtKVu3SM3Z8f+iyCRoU=", - "requires": { - "dom-walk": "^0.1.0" - } - }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", @@ -8566,10 +8735,13 @@ } }, "node-fetch": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", - "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", - "dev": true + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.4.tgz", + "integrity": "sha512-aD1fO+xtLiSCc9vuD+sYMxpIuQyhHscGSkBEo2o5LTV/3bTEAYvdUii29n8LlO5uLCmWdGP7uVUVXFo5SRdkLA==", + "dev": true, + "requires": { + "whatwg-url": "^5.0.0" + } }, "node-preload": { "version": "0.2.1", @@ -8851,11 +9023,6 @@ "callsites": "^3.0.0" } }, - "parse-headers": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.3.tgz", - "integrity": "sha512-QhhZ+DCCit2Coi2vmAKbq5RGTRcQUOE2+REgv8vdyu7MnYx2eZztegqtTx99TZ86GTIwqiy3+4nQTWZ2tgmdCA==" - }, "parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -8980,11 +9147,6 @@ "integrity": "sha512-9fbDAXSBcc6Bs1mZrDYb3XKzDLm4EXXL9sC1LqKP5rZkT6KRr/rf9amVUcODVXgguK/isJz0d0hP72WeaKWsvA==", "dev": true }, - "process": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", - "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=" - }, "process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", @@ -9064,6 +9226,12 @@ "ws": "7.4.6" }, "dependencies": { + "node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", + "dev": true + }, "progress": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.1.tgz", @@ -9081,6 +9249,12 @@ "side-channel": "^1.0.4" } }, + "querystring": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.1.tgz", + "integrity": "sha512-wkvS7mL/JMugcup3/rMitHmd9ecIGd2lhFhK9N3UUQ450h66d1r3Y9nvXzQAW1Lq+wyx61k/1pfKS5KuKiyEbg==", + "dev": true + }, "randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -9128,6 +9302,12 @@ "picomatch": "^2.2.1" } }, + "regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==", + "dev": true + }, "regexpp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", @@ -9714,6 +9894,12 @@ "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", "dev": true }, + "tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=", + "dev": true + }, "type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -9816,6 +10002,12 @@ "graceful-fs": "^4.1.2" } }, + "webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=", + "dev": true + }, "webpack": { "version": "5.54.0", "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.54.0.tgz", @@ -9874,6 +10066,16 @@ "integrity": "sha512-fahN08Et7P9trej8xz/Z7eRu8ltyiygEo/hnRi9KqBUs80KeDcnf96ZJo++ewWd84fEf3xSX9bp4ZS9hbw0OBw==", "dev": true }, + "whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=", + "dev": true, + "requires": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "which": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", @@ -9971,22 +10173,6 @@ "dev": true, "requires": {} }, - "xhr": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/xhr/-/xhr-2.6.0.tgz", - "integrity": "sha512-/eCGLb5rxjx5e3mF1A7s+pLlR6CGyqWN91fv1JgER5mVWg1MZmlhBvy9kjcsOdRk8RrIujotWyJamfyrp+WIcA==", - "requires": { - "global": "~4.4.0", - "is-function": "^1.0.1", - "parse-headers": "^2.0.0", - "xtend": "^4.0.0" - } - }, - "xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==" - }, "y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index d399b3c0..281128f9 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,8 @@ "format:check": "prettier --check .", "lint": "eslint . && npm run format:check", "test": "npm run test:unit && npm run test:functional", - "test:coverage": "nyc --reporter=lcov npm run test:unit", - "test:unit": "NODE_ENV=test mocha tests/unit/ --recursive --reporter spec --timeout 20000 --exit", + "test:coverage": "nyc --reporter=lcov npm run test:unit", + "test:unit": "NODE_ENV=test mocha tests/unit/ --recursive --reporter spec --timeout 20000 --exit --require tests/unit/setup.js", "test:functional": "NODE_ENV=test mocha tests/functional/*.test.js --reporter spec --exit" }, "repository": { @@ -25,15 +25,17 @@ } ], "dependencies": { - "fumble": "^0.1.0", - "xhr": "^2.4.0" + "fumble": "^0.1.0" }, "devDependencies": { + "abortcontroller-polyfill": "^1.7.3", "chai": "^4.2.0", "eslint": "^7.29.0", "express": "^4.17.1", + "fetch-mock": "^9.11.0", "mocha": "^9.0.0", "mockery": "^2.0.0", + "node-fetch": "^2.6.2", "nyc": "^15.1.0", "pre-commit": "^1.0.0", "prettier": "^2.3.2", diff --git a/tests/functional/fetchr.test.js b/tests/functional/fetchr.test.js index 073c4a68..8e802c53 100644 --- a/tests/functional/fetchr.test.js +++ b/tests/functional/fetchr.test.js @@ -163,13 +163,13 @@ describe('client/server integration', () => { meta: { foo: 'bar' }, output: { message: 'error' }, rawRequest: { - url: '/api/error?returnMeta=true', + url: 'http://localhost:3000/api/error?returnMeta=true', method: 'GET', headers: { 'X-Requested-With': 'XMLHttpRequest' }, }, statusCode: 400, timeout: 3000, - url: '/api/error?returnMeta=true', + url: 'http://localhost:3000/api/error?returnMeta=true', }); }); @@ -189,13 +189,13 @@ describe('client/server integration', () => { meta: {}, output: { message: 'unexpected' }, rawRequest: { - url: '/api/error;error=unexpected?returnMeta=true', + url: 'http://localhost:3000/api/error;error=unexpected?returnMeta=true', method: 'GET', headers: { 'X-Requested-With': 'XMLHttpRequest' }, }, statusCode: 500, timeout: 3000, - url: '/api/error;error=unexpected?returnMeta=true', + url: 'http://localhost:3000/api/error;error=unexpected?returnMeta=true', }); }); @@ -209,11 +209,11 @@ describe('client/server integration', () => { statusCode: 404, body: { error: 'page not found' }, rawRequest: { - url: '/non-existent/item?returnMeta=true', + url: 'http://localhost:3000/non-existent/item?returnMeta=true', method: 'GET', headers: { 'X-Requested-With': 'XMLHttpRequest' }, }, - url: '/non-existent/item?returnMeta=true', + url: 'http://localhost:3000/non-existent/item?returnMeta=true', timeout: 3000, }); }); @@ -227,14 +227,13 @@ describe('client/server integration', () => { }); expect(response).to.deep.equal({ - code: 'ETIMEDOUT', statusCode: 0, rawRequest: { - url: '/api/error;error=timeout?returnMeta=true', + url: 'http://localhost:3000/api/error;error=timeout?returnMeta=true', method: 'GET', headers: { 'X-Requested-With': 'XMLHttpRequest' }, }, - url: '/api/error;error=timeout?returnMeta=true', + url: 'http://localhost:3000/api/error;error=timeout?returnMeta=true', timeout: 20, }); }); diff --git a/tests/functional/server.js b/tests/functional/server.js new file mode 100644 index 00000000..fa6a7eed --- /dev/null +++ b/tests/functional/server.js @@ -0,0 +1,8 @@ +const app = require('./app'); +const buildClient = require('./buildClient'); + +buildClient().then(() => { + app.listen(3000, () => { + console.log('http://localhost:3000'); + }); +}); diff --git a/tests/mock/mockApp.js b/tests/mock/mockApp.js index 65bfd55d..86b5e7ae 100644 --- a/tests/mock/mockApp.js +++ b/tests/mock/mockApp.js @@ -2,7 +2,7 @@ * Copyright 2016, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ -var DEFAULT_XHR_PATH = '/api'; +var DEFAULT_PATH = '/api'; var express = require('express'); var app = express(); @@ -16,7 +16,7 @@ FetcherServer.registerService(mockErrorService); FetcherServer.registerService(mockNoopService); app.use(express.json()); -app.use(DEFAULT_XHR_PATH, FetcherServer.middleware()); +app.use(DEFAULT_PATH, FetcherServer.middleware()); module.exports = app; -module.exports.DEFAULT_XHR_PATH = DEFAULT_XHR_PATH; +module.exports.DEFAULT_PATH = DEFAULT_PATH; diff --git a/tests/unit/libs/fetcher.client.js b/tests/unit/libs/fetcher.client.js index 279066dc..2d3c458c 100644 --- a/tests/unit/libs/fetcher.client.js +++ b/tests/unit/libs/fetcher.client.js @@ -5,15 +5,11 @@ 'use strict'; +const fetchMock = require('fetch-mock'); var expect = require('chai').expect; var mockery = require('mockery'); var sinon = require('sinon'); var supertest = require('supertest'); -var xhr = require('xhr'); - -var FakeXMLHttpRequest = sinon.FakeXMLHttpRequest; -FakeXMLHttpRequest.onCreate = handleFakeXhr; -xhr.XMLHttpRequest = FakeXMLHttpRequest; var Fetcher = require('../../../libs/fetcher.client'); var defaultConstructGetUri = require('../../../libs/util/defaultConstructGetUri'); @@ -23,18 +19,14 @@ var defaultOptions = require('../../util/defaultOptions'); // APP var defaultApp = require('../../mock/mockApp'); -var DEFAULT_XHR_PATH = defaultApp.DEFAULT_XHR_PATH; +var DEFAULT_PATH = defaultApp.DEFAULT_PATH; // CORS var corsApp = require('../../mock/mockCorsApp'); var corsPath = corsApp.corsPath; -var validateXhr = null; +var validateRequest = null; -function handleFakeXhr(request) { - if (request.readyState === 0) { - setImmediate(handleFakeXhr, request); - return; - } +function handleFakeRequest(a, b, request) { var method = request.method.toLowerCase(); var url = request.url; var app = defaultApp; @@ -46,26 +38,36 @@ function handleFakeXhr(request) { url = '/' + url; } } - supertest(app) + return supertest(app) [method](url) - .set(request.requestHeaders) - .send(request.requestBody) - .end(function (err, res) { - if (err) { - // superagent error - request.respond(500, null, err); - return; - } + .set(request.headers.entries()) + .send(request.body ? JSON.parse(request.body.toString()) : undefined) + .then(function (res) { if (res.error) { // fetcher error - request.respond(res.error.status || 500, null, res.error.text); - return; + return { + status: res.error.status || 500, + body: res.error.text, + }; } - validateXhr && validateXhr(request); - request.respond(res.status, JSON.stringify(res.headers), res.text); + validateRequest && validateRequest(request); + return { + status: res.status, + headers: res.headers, + body: res.text, + }; + }) + .catch((err) => { + // superagent error + return { + status: 500, + throws: err, + }; }); } +fetchMock.mock('*', handleFakeRequest); + var context = { _csrf: 'stuff' }; var resource = defaultOptions.resource; var params = defaultOptions.params; @@ -94,22 +96,24 @@ var callbackWithStats = function (operation, done) { }; describe('Client Fetcher', function () { + after(() => { + fetchMock.reset(); + }); + describe('DEFAULT', function () { before(function () { this.fetcher = new Fetcher({ context: context, statsCollector: statsCollector, }); - validateXhr = function (req) { + validateRequest = function (req) { if (req.method === 'GET') { - expect(req.url).to.contain( - DEFAULT_XHR_PATH + '/' + resource - ); + expect(req.url).to.contain(DEFAULT_PATH + '/' + resource); expect(req.url).to.contain('?_csrf=' + context._csrf); expect(req.url).to.contain('returnMeta=true'); } else if (req.method === 'POST') { expect(req.url).to.equal( - DEFAULT_XHR_PATH + '?_csrf=' + context._csrf + DEFAULT_PATH + '?_csrf=' + context._csrf ); } }; @@ -119,20 +123,20 @@ describe('Client Fetcher', function () { }); testCrud(params, body, config, callbackWithStats, resolve, reject); after(function () { - validateXhr = null; + validateRequest = null; }); }); describe('CORS', function () { before(function () { - validateXhr = function (req) { + validateRequest = function (req) { if (req.method === 'GET') { expect(req.url).to.contain(corsPath); expect(req.url).to.contain('_csrf=' + context._csrf); expect(req.url).to.contain('returnMeta=true'); } else if (req.method === 'POST') { expect(req.url).to.contain( - corsPath + '?_csrf=' + context._csrf + corsPath + '/?_csrf=' + context._csrf ); } }; @@ -151,20 +155,20 @@ describe('Client Fetcher', function () { reject: reject, }); after(function () { - validateXhr = null; + validateRequest = null; }); }); - describe('xhr', function () { + describe('request', function () { before(function () { this.fetcher = new Fetcher({ context: context, }); }); - it('should return xhr object when calling end w/ callback', function (done) { + it('should return request object when calling end w/ callback', function (done) { var operation = 'create'; - var xhr = this.fetcher[operation](resource) + var request = this.fetcher[operation](resource) .params(params) .body(body) .clientConfig(config) @@ -174,17 +178,14 @@ describe('Client Fetcher', function () { done(err); return; } - expect(xhr.readyState).to.exist; - expect(xhr.abort).to.exist; - expect(xhr.open).to.exist; - expect(xhr.send).to.exist; + expect(request.abort).to.exist; done(); }) ); }); - it('should be able to abort xhr when calling end w/ callback', function () { + it('should be able to abort when calling end w/ callback', function () { var operation = 'create'; - var xhr = this.fetcher[operation](resource) + var request = this.fetcher[operation](resource) .params(params) .body(body) .clientConfig(config) @@ -197,12 +198,12 @@ describe('Client Fetcher', function () { } }) ); - expect(xhr.abort).to.exist; - xhr.abort(); + expect(request.abort).to.exist; + request.abort(); }); }); - describe('xhrTimeout', function () { + describe('Timeout', function () { describe('should be configurable globally', function () { before(function () { mockery.registerMock('./util/http.client', { @@ -273,7 +274,7 @@ describe('Client Fetcher', function () { }); }); - describe('should default to DEFAULT_XHR_TIMEOUT of 3000', function () { + describe('should default to DEFAULT_TIMEOUT of 3000', function () { before(function () { mockery.registerMock('./util/http.client', { get: function (url, headers, config, callback) { @@ -305,17 +306,15 @@ describe('Client Fetcher', function () { describe('Context Picker', function () { var ctx = Object.assign({ random: 'randomnumber' }, context); before(function () { - validateXhr = function (req) { + validateRequest = function (req) { if (req.method === 'GET') { - expect(req.url).to.contain( - DEFAULT_XHR_PATH + '/' + resource - ); + expect(req.url).to.contain(DEFAULT_PATH + '/' + resource); expect(req.url).to.contain('?_csrf=' + ctx._csrf); expect(req.url).to.not.contain('random=' + ctx.random); expect(req.url).to.contain('returnMeta=true'); } else if (req.method === 'POST') { expect(req.url).to.equal( - DEFAULT_XHR_PATH + + DEFAULT_PATH + '?_csrf=' + ctx._csrf + '&random=' + @@ -325,7 +324,7 @@ describe('Client Fetcher', function () { }; }); after(function () { - validateXhr = null; + validateRequest = null; }); describe('Function', function () { diff --git a/tests/unit/libs/util/http.client.js b/tests/unit/libs/util/http.client.js index ec1fcc83..d04a869b 100644 --- a/tests/unit/libs/util/http.client.js +++ b/tests/unit/libs/util/http.client.js @@ -5,56 +5,44 @@ 'use strict'; -var expect = require('chai').expect; -var mockery = require('mockery'); -var http; -var xhrOptions; -var mockResponse; -var mockBody = ''; -var mockError = null; +const fetchMock = require('fetch-mock'); +const { expect } = require('chai'); +const sinon = require('sinon'); +const http = require('../../../../libs/util/http.client.js'); describe('Client HTTP', function () { - before(function () { - mockery.enable({ - useCleanCache: true, - warnOnUnregistered: false, - }); - mockery.resetCache(); - mockBody = ''; - mockery.registerMock('xhr', function mockXhr(options, callback) { - xhrOptions.push(options); - callback(mockError, mockResponse, mockBody); - }); - http = require('../../../../libs/util/http.client.js'); - }); + let responseStatus; + let mockBody; after(function () { - mockBody = ''; - mockery.deregisterAll(); + fetchMock.reset(); }); afterEach(function () { - mockError = null; + fetchMock.resetHistory(); + fetchMock.resetBehavior(); }); describe('#Successful requests', function () { beforeEach(function () { - mockResponse = { - statusCode: 200, - }; + responseStatus = 200; mockBody = 'BODY'; - xhrOptions = []; }); it('GET', function (done) { + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get('/url', { 'X-Foo': 'foo' }, {}, function (err, response) { - expect(xhrOptions.length).to.equal(1); - var options = xhrOptions[0]; + expect(fetchMock.calls()).to.have.lengthOf(1); + const options = fetchMock.lastCall().request; expect(options.url).to.equal('/url'); - expect(options.headers['X-Requested-With']).to.equal( + expect(options.headers.get('X-Requested-With')).to.equal( 'XMLHttpRequest' ); - expect(options.headers['X-Foo']).to.equal('foo'); + expect(options.headers.get('X-Foo')).to.equal('foo'); expect(options.method).to.equal('GET'); expect(err).to.equal(null); expect(response.statusCode).to.equal(200); @@ -64,21 +52,26 @@ describe('Client HTTP', function () { }); it('POST', function (done) { + fetchMock.post('/url', { + body: mockBody, + status: responseStatus, + }); + http.post( '/url', { 'X-Foo': 'foo' }, { data: 'data' }, {}, function () { - expect(xhrOptions.length).to.equal(1); - var options = xhrOptions[0]; + expect(fetchMock.calls()).to.have.lengthOf(1); + const options = fetchMock.lastCall().request; expect(options.url).to.equal('/url'); - expect(options.headers['X-Requested-With']).to.equal( + expect(options.headers.get('X-Requested-With')).to.equal( 'XMLHttpRequest' ); - expect(options.headers['X-Foo']).to.equal('foo'); + expect(options.headers.get('X-Foo')).to.equal('foo'); expect(options.method).to.equal('POST'); - expect(options.body).to.eql('{"data":"data"}'); + expect(options.body.toString()).to.eql('{"data":"data"}'); done(); } ); @@ -87,52 +80,77 @@ describe('Client HTTP', function () { describe('#Successful CORS requests', function () { beforeEach(function () { - mockResponse = { - statusCode: 200, - }; + responseStatus = 200; mockBody = 'BODY'; - xhrOptions = []; + sinon.spy(global, 'Request'); + }); + + afterEach(() => { + Request.restore(); }); it('GET', function (done) { + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get( '/url', { 'X-Foo': 'foo' }, { cors: true, withCredentials: true }, function (err, response) { - expect(xhrOptions.length).to.equal(1); - var options = xhrOptions[0]; + expect(fetchMock.calls()).to.have.lengthOf(1); + const options = fetchMock.lastCall().request; expect(options.url).to.equal('/url'); expect(options.headers).to.not.have.property( 'X-Requested-With' ); - expect(options.headers['X-Foo']).to.equal('foo'); + expect(options.headers.get('X-Foo')).to.equal('foo'); expect(options.method).to.equal('GET'); - expect(options.withCredentials).to.equal(true); expect(err).to.equal(null); expect(response.statusCode).to.equal(200); expect(response.responseText).to.equal('BODY'); + + sinon.assert.calledWith( + Request, + sinon.match.string, + sinon.match({ credentials: 'include' }) + ); + done(); } ); }); it('POST', function (done) { + fetchMock.post('/url', { + body: mockBody, + status: responseStatus, + }); + http.post( '/url', { 'X-Foo': 'foo' }, { data: 'data' }, { cors: true }, function () { - expect(xhrOptions.length).to.equal(1); - var options = xhrOptions[0]; + expect(fetchMock.calls()).to.have.lengthOf(1); + const options = fetchMock.lastCall().request; expect(options.url).to.equal('/url'); expect(options.headers).to.not.have.property( 'X-Requested-With' ); - expect(options.headers['X-Foo']).to.equal('foo'); + expect(options.headers.get('X-Foo')).to.equal('foo'); expect(options.method).to.equal('POST'); - expect(options.body).to.eql('{"data":"data"}'); + expect(options.body.toString()).to.eql('{"data":"data"}'); + + sinon.assert.calledWith( + Request, + sinon.match.string, + sinon.match({ credentials: 'same-origin' }) + ); + done(); } ); @@ -141,34 +159,35 @@ describe('Client HTTP', function () { describe('#400 requests', function () { beforeEach(function () { - xhrOptions = []; - mockResponse = { - statusCode: 400, - }; - }); - - it('GET with no response', function (done) { - mockBody = undefined; - http.get('/url', { 'X-Foo': 'foo' }, {}, function (err) { - expect(err.message).to.equal('Error 400'); - expect(err.statusCode).to.equal(400); - expect(err.body).to.equal(undefined); - done(); - }); + responseStatus = 400; }); it('GET with empty response', function (done) { mockBody = ''; + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get('/url', { 'X-Foo': 'foo' }, {}, function (err) { - expect(err.message).to.equal(''); - expect(err.statusCode).to.equal(400); - expect(err.body).to.equal(''); - done(); + try { + expect(err.message).to.equal(''); + expect(err.statusCode).to.equal(400); + expect(err.body).to.equal(''); + done(); + } catch (e) { + done(e); + } }); }); it('GET with JSON response containing message attribute', function (done) { mockBody = '{"message":"some body content"}'; + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get('/url', { 'X-Foo': 'foo' }, {}, function (err) { expect(err.message).to.equal('some body content'); expect(err.statusCode).to.equal(400); @@ -181,6 +200,11 @@ describe('Client HTTP', function () { it('GET with JSON response not containing message attribute', function (done) { mockBody = '{"other":"some body content"}'; + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get('/url', { 'X-Foo': 'foo' }, {}, function (err) { expect(err.message).to.equal(mockBody); expect(err.statusCode).to.equal(400); @@ -198,6 +222,11 @@ describe('Client HTTP', function () { // if not configured to allow content throughput it('GET with plain text', function (done) { mockBody = 'Bad Request'; + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get('/url', { 'X-Foo': 'foo' }, {}, function (err) { expect(err.message).to.equal(mockBody); expect(err.statusCode).to.equal(400); @@ -209,22 +238,34 @@ describe('Client HTTP', function () { describe('#Retry', function () { beforeEach(function () { - xhrOptions = []; mockBody = 'BODY'; - mockResponse = { - statusCode: 408, - }; + + responseStatus = 408; }); + const expectRequestsToBeEqual = (req1, req2) => { + expect(req1.request.url).to.equal(req2.request.url); + expect(req1.request.method).to.equal(req2.request.method); + expect( + Object.fromEntries(req1.request.headers.entries()) + ).to.deep.equal(Object.fromEntries(req2.request.headers.entries())); + expect(req1.request.body).to.equal(req2.request.body); + }; + it('GET with no retry', function (done) { + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get('/url', { 'X-Foo': 'foo' }, {}, function (err) { - var options = xhrOptions[0]; - expect(xhrOptions.length).to.equal(1); + const options = fetchMock.lastCall().request; + expect(fetchMock.calls()).to.have.lengthOf(1); expect(options.url).to.equal('/url'); - expect(options.headers['X-Requested-With']).to.equal( + expect(options.headers.get('X-Requested-With')).to.equal( 'XMLHttpRequest' ); - expect(options.headers['X-Foo']).to.equal('foo'); + expect(options.headers.get('X-Foo')).to.equal('foo'); expect(options.method).to.equal('GET'); expect(err.message).to.equal('BODY'); expect(err.statusCode).to.equal(408); @@ -234,43 +275,52 @@ describe('Client HTTP', function () { }); it('GET with retry', function (done) { + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get( '/url', { 'X-Foo': 'foo' }, { - timeout: 2000, retry: { interval: 200, maxRetries: 1, }, }, function (err) { - expect(xhrOptions.length).to.equal(2); - var options = xhrOptions[0]; + expect(fetchMock.calls()).to.have.lengthOf(2); + const options = fetchMock.lastCall().request; expect(options.url).to.equal('/url'); - expect(options.headers['X-Requested-With']).to.equal( + expect(options.headers.get('X-Requested-With')).to.equal( 'XMLHttpRequest' ); - expect(options.headers['X-Foo']).to.equal('foo'); + expect(options.headers.get('X-Foo')).to.equal('foo'); expect(options.method).to.equal('GET'); - expect(options.timeout).to.equal(2000); expect(err.message).to.equal('BODY'); expect(err.statusCode).to.equal(408); expect(err.body).to.equal('BODY'); - expect(xhrOptions[0]).to.eql(xhrOptions[1]); + + const [req1, req2] = fetchMock.calls(); + expectRequestsToBeEqual(req1, req2); + done(); } ); }); it('GET with retry and custom status code', function (done) { - mockResponse = { statusCode: 502 }; + responseStatus = 502; + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); http.get( '/url', { 'X-Foo': 'foo' }, { - timeout: 2000, retry: { interval: 20, maxRetries: 1, @@ -278,8 +328,11 @@ describe('Client HTTP', function () { }, }, function () { - expect(xhrOptions.length).to.equal(2); - expect(xhrOptions[0]).to.eql(xhrOptions[1]); + expect(fetchMock.calls()).to.have.lengthOf(2); + + const [req1, req2] = fetchMock.calls(); + expectRequestsToBeEqual(req1, req2); + done(); } ); @@ -290,11 +343,14 @@ describe('Client HTTP', function () { var config; beforeEach(function () { - mockResponse = { - statusCode: 200, - }; + sinon.spy(global, 'setTimeout'); + + responseStatus = 200; mockBody = 'BODY'; - xhrOptions = []; + }); + + afterEach(() => { + setTimeout.restore(); }); describe('#No timeout set for individual call', function () { @@ -303,22 +359,34 @@ describe('Client HTTP', function () { }); it('should use xhrTimeout for GET', function (done) { + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get('/url', { 'X-Foo': 'foo' }, config, function () { - var options = xhrOptions[0]; - expect(options.timeout).to.equal(3000); + sinon.assert.calledWith(setTimeout, sinon.match.func, 3000); done(); }); }); it('should use xhrTimeout for POST', function (done) { + fetchMock.post('/url', { + body: mockBody, + status: responseStatus, + }); + http.post( '/url', { 'X-Foo': 'foo' }, { data: 'data' }, config, function () { - var options = xhrOptions[0]; - expect(options.timeout).to.equal(3000); + sinon.assert.calledWith( + setTimeout, + sinon.match.func, + 3000 + ); done(); } ); @@ -331,22 +399,34 @@ describe('Client HTTP', function () { }); it('should override default xhrTimeout for GET', function (done) { + fetchMock.get('/url', { + body: mockBody, + status: responseStatus, + }); + http.get('/url', { 'X-Foo': 'foo' }, config, function () { - var options = xhrOptions[0]; - expect(options.timeout).to.equal(6000); + sinon.assert.calledWith(setTimeout, sinon.match.func, 6000); done(); }); }); it('should override default xhrTimeout for POST', function (done) { + fetchMock.post('/url', { + body: mockBody, + status: responseStatus, + }); + http.post( '/url', { 'X-Foo': 'foo' }, { data: 'data' }, config, function () { - var options = xhrOptions[0]; - expect(options.timeout).to.equal(6000); + sinon.assert.calledWith( + setTimeout, + sinon.match.func, + 6000 + ); done(); } ); @@ -354,11 +434,13 @@ describe('Client HTTP', function () { }); }); - describe('xhr errors', function () { + describe('request errors', function () { it('should pass-through any xhr error', function (done) { - mockError = new Error('AnyError'); - xhrOptions = []; - mockResponse = { statusCode: 0, url: '/url' }; + responseStatus = 0; + fetchMock.get('/url', { + throws: new Error('AnyError'), + status: responseStatus, + }); http.get('/url', {}, { xhrTimeout: 42 }, function (err, response) { expect(response).to.equal(undefined); diff --git a/tests/unit/setup.js b/tests/unit/setup.js new file mode 100644 index 00000000..def88d06 --- /dev/null +++ b/tests/unit/setup.js @@ -0,0 +1,23 @@ +// As seen in isomorphic-fetch fetch polyfill: +// https://github.com/matthew-andrews/isomorphic-fetch/blob/fc5e0d0d0b180e5b4c70b2ae7f738c50a9a51b25/fetch-npm-node.js + +'use strict'; + +const nodeFetch = require('node-fetch'); +const { + AbortController, + abortableFetch, +} = require('abortcontroller-polyfill/dist/cjs-ponyfill'); + +const { fetch, Request } = abortableFetch({ + fetch: nodeFetch, + Request: nodeFetch.Request, +}); + +if (!global.fetch) { + global.AbortController = AbortController; + global.Headers = nodeFetch.Headers; + global.Request = Request; + global.Response = nodeFetch.Response; + global.fetch = fetch; +}