msw 0.20.5 → 0.21.3

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 (74) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +1 -1
  3. package/lib/esm/fetch-deps.js +26 -23
  4. package/lib/esm/graphql.js +92 -79
  5. package/lib/esm/index.js +90 -44
  6. package/lib/esm/{matchRequest-deps.js → matchRequestUrl-deps.js} +29 -17
  7. package/lib/esm/mockServiceWorker.js +8 -1
  8. package/lib/esm/rest-deps.js +27 -18
  9. package/lib/esm/rest.js +1 -1
  10. package/lib/esm/xml-deps.js +3 -3
  11. package/lib/types/LiveStorage.d.ts +17 -0
  12. package/lib/types/context/body.d.ts +2 -2
  13. package/lib/types/context/errors.d.ts +3 -1
  14. package/lib/types/context/fetch.d.ts +2 -2
  15. package/lib/types/context/json.d.ts +5 -3
  16. package/lib/types/context/text.d.ts +2 -2
  17. package/lib/types/context/xml.d.ts +2 -2
  18. package/lib/types/graphql.d.ts +8 -10
  19. package/lib/types/index.d.ts +3 -3
  20. package/lib/types/native/index.d.ts +7 -1
  21. package/lib/types/node/createSetupServer.d.ts +29 -0
  22. package/lib/types/node/setupServer.d.ts +4 -24
  23. package/lib/types/response.d.ts +10 -7
  24. package/lib/types/rest.d.ts +158 -16
  25. package/lib/types/setupWorker/glossary.d.ts +14 -4
  26. package/lib/types/setupWorker/start/utils/getWorkerByRegistration.d.ts +2 -1
  27. package/lib/types/setupWorker/start/utils/getWorkerInstance.d.ts +2 -2
  28. package/lib/types/sharedOptions.d.ts +1 -1
  29. package/lib/types/utils/getResponse.d.ts +2 -2
  30. package/lib/types/utils/handlers/requestHandler.d.ts +74 -0
  31. package/lib/types/utils/{requestHandlerUtils.d.ts → handlers/requestHandlerUtils.d.ts} +2 -2
  32. package/lib/types/utils/{isNodeProcess.d.ts → internal/isNodeProcess.d.ts} +1 -0
  33. package/lib/types/utils/{isStringEqual.d.ts → internal/isStringEqual.d.ts} +0 -0
  34. package/lib/types/utils/{jsonParse.d.ts → internal/jsonParse.d.ts} +0 -0
  35. package/lib/types/utils/internal/mergeRight.d.ts +5 -0
  36. package/lib/types/utils/{logger → logging}/getStatusCodeColor.d.ts +0 -0
  37. package/lib/types/utils/{logger → logging}/getTimestamp.d.ts +0 -0
  38. package/lib/types/utils/{logger → logging}/prepareRequest.d.ts +3 -3
  39. package/lib/types/utils/{logger → logging}/prepareResponse.d.ts +2 -2
  40. package/lib/types/utils/matching/{matchRequest.d.ts → matchRequestUrl.d.ts} +0 -0
  41. package/lib/types/utils/request/getPublicUrlFromRequest.d.ts +6 -0
  42. package/lib/types/utils/request/getRequestCookies.d.ts +1 -1
  43. package/lib/types/{onUnhandledRequest.d.ts → utils/request/onUnhandledRequest.d.ts} +1 -1
  44. package/lib/types/utils/request/parseBody.d.ts +5 -0
  45. package/lib/types/utils/url/getAbsoluteUrl.d.ts +6 -0
  46. package/lib/types/utils/{getAbsoluteWorkerUrl.d.ts → url/getAbsoluteWorkerUrl.d.ts} +0 -0
  47. package/lib/types/utils/url/getUrlByMask.d.ts +5 -0
  48. package/lib/umd/index.js +696 -613
  49. package/lib/umd/mockServiceWorker.js +8 -1
  50. package/native/index.js +1508 -133
  51. package/node/context/delay.d.ts +11 -0
  52. package/node/context/fetch.d.ts +8 -0
  53. package/node/context/set.d.ts +2 -0
  54. package/node/context/status.d.ts +2 -0
  55. package/node/index.js +1507 -133
  56. package/node/node/createSetupServer.d.ts +29 -0
  57. package/node/node/index.d.ts +5 -0
  58. package/node/node/setupServer.d.ts +7 -0
  59. package/node/response.d.ts +25 -0
  60. package/node/utils/NetworkError.d.ts +3 -0
  61. package/node/utils/getResponse.d.ts +14 -0
  62. package/{lib/types → node/utils}/handlers/requestHandler.d.ts +13 -12
  63. package/node/utils/handlers/requestHandlerUtils.d.ts +4 -0
  64. package/node/utils/internal/compose.d.ts +5 -0
  65. package/node/utils/internal/isNodeProcess.d.ts +5 -0
  66. package/node/utils/internal/jsonParse.d.ts +5 -0
  67. package/node/utils/request/getPublicUrlFromRequest.d.ts +6 -0
  68. package/node/utils/request/onUnhandledRequest.d.ts +5 -0
  69. package/node/utils/request/parseBody.d.ts +5 -0
  70. package/package.json +34 -29
  71. package/lib/types/utils/getJsonBody.d.ts +0 -5
  72. package/lib/types/utils/request/parseRequestBody.d.ts +0 -2
  73. package/lib/types/utils/resolveMask.d.ts +0 -6
  74. package/lib/types/utils/resolveRelativeUrl.d.ts +0 -6
package/native/index.js CHANGED
@@ -2,21 +2,22 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var XMLHttpRequest = require('node-request-interceptor/lib/interceptors/XMLHttpRequest');
5
6
  var nodeRequestInterceptor = require('node-request-interceptor');
6
7
 
7
8
  /*! *****************************************************************************
8
- Copyright (c) Microsoft Corporation. All rights reserved.
9
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
10
- this file except in compliance with the License. You may obtain a copy of the
11
- License at http://www.apache.org/licenses/LICENSE-2.0
9
+ Copyright (c) Microsoft Corporation.
12
10
 
13
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
15
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
16
- MERCHANTABLITY OR NON-INFRINGEMENT.
11
+ Permission to use, copy, modify, and/or distribute this software for any
12
+ purpose with or without fee is hereby granted.
17
13
 
18
- See the Apache Version 2.0 License for specific language governing permissions
19
- and limitations under the License.
14
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
15
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
16
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
17
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
18
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
19
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
20
+ PERFORMANCE OF THIS SOFTWARE.
20
21
  ***************************************************************************** */
21
22
 
22
23
  function __awaiter(thisArg, _arguments, P, generator) {
@@ -115,13 +116,15 @@ function tryDecode(str, decode) {
115
116
  }
116
117
  }
117
118
 
119
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
120
+
118
121
  function createCommonjsModule(fn, basedir, module) {
119
122
  return module = {
120
- path: basedir,
121
- exports: {},
122
- require: function (path, base) {
123
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
124
- }
123
+ path: basedir,
124
+ exports: {},
125
+ require: function (path, base) {
126
+ return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
127
+ }
125
128
  }, fn(module, module.exports), module.exports;
126
129
  }
127
130
 
@@ -465,16 +468,16 @@ function set(...args) {
465
468
 
466
469
  /**
467
470
  * Returns a boolean indicating if the current process is running in NodeJS environment.
471
+ * @see https://github.com/mswjs/msw/pull/255
468
472
  */
469
- // Please see https://github.com/mswjs/msw/pull/255
470
473
  function isNodeProcess() {
474
+ // Check browser environment.
471
475
  if (typeof global !== 'object') {
472
- // check browser environment
473
476
  return false;
474
477
  }
478
+ // Check nodejs or React Native environment.
475
479
  if (Object.prototype.toString.call(global.process) === '[object process]' ||
476
480
  navigator.product === 'ReactNative') {
477
- // check nodejs or react native environment
478
481
  return true;
479
482
  }
480
483
  }
@@ -503,20 +506,21 @@ const delay = (durationMs) => {
503
506
  };
504
507
 
505
508
  const useFetch = isNodeProcess() ? require('node-fetch') : window.fetch;
506
- const gracefully = (promise) => {
507
- return promise.then((res) => {
508
- var _a;
509
- if ((_a = res.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json')) {
510
- return res.json();
511
- }
512
- return res.text();
513
- });
514
- };
515
509
  const augmentRequestInit = (requestInit) => {
516
510
  const headers = new lib.Headers(requestInit.headers);
517
511
  headers.set('x-msw-bypass', 'true');
518
512
  return Object.assign(Object.assign({}, requestInit), { headers: headers.getAllHeaders() });
519
513
  };
514
+ const createFetchRequestParameters = (input) => {
515
+ const { body, method } = input;
516
+ const requestParameters = Object.assign(Object.assign({}, input), { body: undefined });
517
+ if (['GET', 'HEAD'].includes(method)) {
518
+ return requestParameters;
519
+ }
520
+ requestParameters.body =
521
+ typeof body === 'object' ? JSON.stringify(body) : body;
522
+ return requestParameters;
523
+ };
520
524
  /**
521
525
  * Wrapper around the native `window.fetch()` function that performs
522
526
  * a request bypassing MSW. Requests performed using
@@ -525,11 +529,11 @@ const augmentRequestInit = (requestInit) => {
525
529
  const fetch = (input, requestInit = {}) => {
526
530
  // Keep the default `window.fetch()` call signature
527
531
  if (typeof input === 'string') {
528
- return gracefully(useFetch(input, augmentRequestInit(requestInit)));
532
+ return useFetch(input, augmentRequestInit(requestInit));
529
533
  }
530
- const { body } = input;
531
- const compliantReq = augmentRequestInit(Object.assign(Object.assign({}, input), { body: typeof body === 'object' ? JSON.stringify(body) : body }));
532
- return gracefully(useFetch(input.url.href, compliantReq));
534
+ const requestParameters = createFetchRequestParameters(input);
535
+ const compliantRequest = augmentRequestInit(requestParameters);
536
+ return useFetch(input.url.href, compliantRequest);
533
537
  };
534
538
 
535
539
  const defaultContext = {
@@ -671,21 +675,16 @@ function jsonParse(str) {
671
675
  }
672
676
 
673
677
  /**
674
- * Returns a parsed JSON from a given valid body string,
675
- * otherwise returns a given body string as-is.
678
+ * Parses a given request/response body based on the `Content-Type` header.
676
679
  */
677
- function getJsonBody(body) {
678
- return jsonParse(body) || body;
679
- }
680
-
681
- function parseRequestBody(body, headers) {
680
+ function parseBody(body, headers) {
682
681
  var _a;
683
682
  if (body) {
684
683
  // If the intercepted request's body has a JSON Content-Type
685
684
  // parse it into an object, otherwise leave as-is.
686
685
  const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json');
687
686
  if (hasJsonContent && typeof body !== 'object') {
688
- return getJsonBody(body);
687
+ return jsonParse(body) || body;
689
688
  }
690
689
  return body;
691
690
  }
@@ -707,12 +706,1374 @@ function resetHandlers(initialHandlers, ...nextHandlers) {
707
706
  return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
708
707
  }
709
708
 
709
+ var punycode = createCommonjsModule(function (module, exports) {
710
+ (function(root) {
711
+
712
+ /** Detect free variables */
713
+ var freeExports = exports &&
714
+ !exports.nodeType && exports;
715
+ var freeModule = module &&
716
+ !module.nodeType && module;
717
+ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
718
+ if (
719
+ freeGlobal.global === freeGlobal ||
720
+ freeGlobal.window === freeGlobal ||
721
+ freeGlobal.self === freeGlobal
722
+ ) {
723
+ root = freeGlobal;
724
+ }
725
+
726
+ /**
727
+ * The `punycode` object.
728
+ * @name punycode
729
+ * @type Object
730
+ */
731
+ var punycode,
732
+
733
+ /** Highest positive signed 32-bit float value */
734
+ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
735
+
736
+ /** Bootstring parameters */
737
+ base = 36,
738
+ tMin = 1,
739
+ tMax = 26,
740
+ skew = 38,
741
+ damp = 700,
742
+ initialBias = 72,
743
+ initialN = 128, // 0x80
744
+ delimiter = '-', // '\x2D'
745
+
746
+ /** Regular expressions */
747
+ regexPunycode = /^xn--/,
748
+ regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
749
+ regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
750
+
751
+ /** Error messages */
752
+ errors = {
753
+ 'overflow': 'Overflow: input needs wider integers to process',
754
+ 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
755
+ 'invalid-input': 'Invalid input'
756
+ },
757
+
758
+ /** Convenience shortcuts */
759
+ baseMinusTMin = base - tMin,
760
+ floor = Math.floor,
761
+ stringFromCharCode = String.fromCharCode,
762
+
763
+ /** Temporary variable */
764
+ key;
765
+
766
+ /*--------------------------------------------------------------------------*/
767
+
768
+ /**
769
+ * A generic error utility function.
770
+ * @private
771
+ * @param {String} type The error type.
772
+ * @returns {Error} Throws a `RangeError` with the applicable error message.
773
+ */
774
+ function error(type) {
775
+ throw RangeError(errors[type]);
776
+ }
777
+
778
+ /**
779
+ * A generic `Array#map` utility function.
780
+ * @private
781
+ * @param {Array} array The array to iterate over.
782
+ * @param {Function} callback The function that gets called for every array
783
+ * item.
784
+ * @returns {Array} A new array of values returned by the callback function.
785
+ */
786
+ function map(array, fn) {
787
+ var length = array.length;
788
+ var result = [];
789
+ while (length--) {
790
+ result[length] = fn(array[length]);
791
+ }
792
+ return result;
793
+ }
794
+
795
+ /**
796
+ * A simple `Array#map`-like wrapper to work with domain name strings or email
797
+ * addresses.
798
+ * @private
799
+ * @param {String} domain The domain name or email address.
800
+ * @param {Function} callback The function that gets called for every
801
+ * character.
802
+ * @returns {Array} A new string of characters returned by the callback
803
+ * function.
804
+ */
805
+ function mapDomain(string, fn) {
806
+ var parts = string.split('@');
807
+ var result = '';
808
+ if (parts.length > 1) {
809
+ // In email addresses, only the domain name should be punycoded. Leave
810
+ // the local part (i.e. everything up to `@`) intact.
811
+ result = parts[0] + '@';
812
+ string = parts[1];
813
+ }
814
+ // Avoid `split(regex)` for IE8 compatibility. See #17.
815
+ string = string.replace(regexSeparators, '\x2E');
816
+ var labels = string.split('.');
817
+ var encoded = map(labels, fn).join('.');
818
+ return result + encoded;
819
+ }
820
+
821
+ /**
822
+ * Creates an array containing the numeric code points of each Unicode
823
+ * character in the string. While JavaScript uses UCS-2 internally,
824
+ * this function will convert a pair of surrogate halves (each of which
825
+ * UCS-2 exposes as separate characters) into a single code point,
826
+ * matching UTF-16.
827
+ * @see `punycode.ucs2.encode`
828
+ * @see <https://mathiasbynens.be/notes/javascript-encoding>
829
+ * @memberOf punycode.ucs2
830
+ * @name decode
831
+ * @param {String} string The Unicode input string (UCS-2).
832
+ * @returns {Array} The new array of code points.
833
+ */
834
+ function ucs2decode(string) {
835
+ var output = [],
836
+ counter = 0,
837
+ length = string.length,
838
+ value,
839
+ extra;
840
+ while (counter < length) {
841
+ value = string.charCodeAt(counter++);
842
+ if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
843
+ // high surrogate, and there is a next character
844
+ extra = string.charCodeAt(counter++);
845
+ if ((extra & 0xFC00) == 0xDC00) { // low surrogate
846
+ output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
847
+ } else {
848
+ // unmatched surrogate; only append this code unit, in case the next
849
+ // code unit is the high surrogate of a surrogate pair
850
+ output.push(value);
851
+ counter--;
852
+ }
853
+ } else {
854
+ output.push(value);
855
+ }
856
+ }
857
+ return output;
858
+ }
859
+
860
+ /**
861
+ * Creates a string based on an array of numeric code points.
862
+ * @see `punycode.ucs2.decode`
863
+ * @memberOf punycode.ucs2
864
+ * @name encode
865
+ * @param {Array} codePoints The array of numeric code points.
866
+ * @returns {String} The new Unicode string (UCS-2).
867
+ */
868
+ function ucs2encode(array) {
869
+ return map(array, function(value) {
870
+ var output = '';
871
+ if (value > 0xFFFF) {
872
+ value -= 0x10000;
873
+ output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
874
+ value = 0xDC00 | value & 0x3FF;
875
+ }
876
+ output += stringFromCharCode(value);
877
+ return output;
878
+ }).join('');
879
+ }
880
+
881
+ /**
882
+ * Converts a basic code point into a digit/integer.
883
+ * @see `digitToBasic()`
884
+ * @private
885
+ * @param {Number} codePoint The basic numeric code point value.
886
+ * @returns {Number} The numeric value of a basic code point (for use in
887
+ * representing integers) in the range `0` to `base - 1`, or `base` if
888
+ * the code point does not represent a value.
889
+ */
890
+ function basicToDigit(codePoint) {
891
+ if (codePoint - 48 < 10) {
892
+ return codePoint - 22;
893
+ }
894
+ if (codePoint - 65 < 26) {
895
+ return codePoint - 65;
896
+ }
897
+ if (codePoint - 97 < 26) {
898
+ return codePoint - 97;
899
+ }
900
+ return base;
901
+ }
902
+
903
+ /**
904
+ * Converts a digit/integer into a basic code point.
905
+ * @see `basicToDigit()`
906
+ * @private
907
+ * @param {Number} digit The numeric value of a basic code point.
908
+ * @returns {Number} The basic code point whose value (when used for
909
+ * representing integers) is `digit`, which needs to be in the range
910
+ * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
911
+ * used; else, the lowercase form is used. The behavior is undefined
912
+ * if `flag` is non-zero and `digit` has no uppercase form.
913
+ */
914
+ function digitToBasic(digit, flag) {
915
+ // 0..25 map to ASCII a..z or A..Z
916
+ // 26..35 map to ASCII 0..9
917
+ return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
918
+ }
919
+
920
+ /**
921
+ * Bias adaptation function as per section 3.4 of RFC 3492.
922
+ * http://tools.ietf.org/html/rfc3492#section-3.4
923
+ * @private
924
+ */
925
+ function adapt(delta, numPoints, firstTime) {
926
+ var k = 0;
927
+ delta = firstTime ? floor(delta / damp) : delta >> 1;
928
+ delta += floor(delta / numPoints);
929
+ for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
930
+ delta = floor(delta / baseMinusTMin);
931
+ }
932
+ return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
933
+ }
934
+
935
+ /**
936
+ * Converts a Punycode string of ASCII-only symbols to a string of Unicode
937
+ * symbols.
938
+ * @memberOf punycode
939
+ * @param {String} input The Punycode string of ASCII-only symbols.
940
+ * @returns {String} The resulting string of Unicode symbols.
941
+ */
942
+ function decode(input) {
943
+ // Don't use UCS-2
944
+ var output = [],
945
+ inputLength = input.length,
946
+ out,
947
+ i = 0,
948
+ n = initialN,
949
+ bias = initialBias,
950
+ basic,
951
+ j,
952
+ index,
953
+ oldi,
954
+ w,
955
+ k,
956
+ digit,
957
+ t,
958
+ /** Cached calculation results */
959
+ baseMinusT;
960
+
961
+ // Handle the basic code points: let `basic` be the number of input code
962
+ // points before the last delimiter, or `0` if there is none, then copy
963
+ // the first basic code points to the output.
964
+
965
+ basic = input.lastIndexOf(delimiter);
966
+ if (basic < 0) {
967
+ basic = 0;
968
+ }
969
+
970
+ for (j = 0; j < basic; ++j) {
971
+ // if it's not a basic code point
972
+ if (input.charCodeAt(j) >= 0x80) {
973
+ error('not-basic');
974
+ }
975
+ output.push(input.charCodeAt(j));
976
+ }
977
+
978
+ // Main decoding loop: start just after the last delimiter if any basic code
979
+ // points were copied; start at the beginning otherwise.
980
+
981
+ for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
982
+
983
+ // `index` is the index of the next character to be consumed.
984
+ // Decode a generalized variable-length integer into `delta`,
985
+ // which gets added to `i`. The overflow checking is easier
986
+ // if we increase `i` as we go, then subtract off its starting
987
+ // value at the end to obtain `delta`.
988
+ for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
989
+
990
+ if (index >= inputLength) {
991
+ error('invalid-input');
992
+ }
993
+
994
+ digit = basicToDigit(input.charCodeAt(index++));
995
+
996
+ if (digit >= base || digit > floor((maxInt - i) / w)) {
997
+ error('overflow');
998
+ }
999
+
1000
+ i += digit * w;
1001
+ t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
1002
+
1003
+ if (digit < t) {
1004
+ break;
1005
+ }
1006
+
1007
+ baseMinusT = base - t;
1008
+ if (w > floor(maxInt / baseMinusT)) {
1009
+ error('overflow');
1010
+ }
1011
+
1012
+ w *= baseMinusT;
1013
+
1014
+ }
1015
+
1016
+ out = output.length + 1;
1017
+ bias = adapt(i - oldi, out, oldi == 0);
1018
+
1019
+ // `i` was supposed to wrap around from `out` to `0`,
1020
+ // incrementing `n` each time, so we'll fix that now:
1021
+ if (floor(i / out) > maxInt - n) {
1022
+ error('overflow');
1023
+ }
1024
+
1025
+ n += floor(i / out);
1026
+ i %= out;
1027
+
1028
+ // Insert `n` at position `i` of the output
1029
+ output.splice(i++, 0, n);
1030
+
1031
+ }
1032
+
1033
+ return ucs2encode(output);
1034
+ }
1035
+
1036
+ /**
1037
+ * Converts a string of Unicode symbols (e.g. a domain name label) to a
1038
+ * Punycode string of ASCII-only symbols.
1039
+ * @memberOf punycode
1040
+ * @param {String} input The string of Unicode symbols.
1041
+ * @returns {String} The resulting Punycode string of ASCII-only symbols.
1042
+ */
1043
+ function encode(input) {
1044
+ var n,
1045
+ delta,
1046
+ handledCPCount,
1047
+ basicLength,
1048
+ bias,
1049
+ j,
1050
+ m,
1051
+ q,
1052
+ k,
1053
+ t,
1054
+ currentValue,
1055
+ output = [],
1056
+ /** `inputLength` will hold the number of code points in `input`. */
1057
+ inputLength,
1058
+ /** Cached calculation results */
1059
+ handledCPCountPlusOne,
1060
+ baseMinusT,
1061
+ qMinusT;
1062
+
1063
+ // Convert the input in UCS-2 to Unicode
1064
+ input = ucs2decode(input);
1065
+
1066
+ // Cache the length
1067
+ inputLength = input.length;
1068
+
1069
+ // Initialize the state
1070
+ n = initialN;
1071
+ delta = 0;
1072
+ bias = initialBias;
1073
+
1074
+ // Handle the basic code points
1075
+ for (j = 0; j < inputLength; ++j) {
1076
+ currentValue = input[j];
1077
+ if (currentValue < 0x80) {
1078
+ output.push(stringFromCharCode(currentValue));
1079
+ }
1080
+ }
1081
+
1082
+ handledCPCount = basicLength = output.length;
1083
+
1084
+ // `handledCPCount` is the number of code points that have been handled;
1085
+ // `basicLength` is the number of basic code points.
1086
+
1087
+ // Finish the basic string - if it is not empty - with a delimiter
1088
+ if (basicLength) {
1089
+ output.push(delimiter);
1090
+ }
1091
+
1092
+ // Main encoding loop:
1093
+ while (handledCPCount < inputLength) {
1094
+
1095
+ // All non-basic code points < n have been handled already. Find the next
1096
+ // larger one:
1097
+ for (m = maxInt, j = 0; j < inputLength; ++j) {
1098
+ currentValue = input[j];
1099
+ if (currentValue >= n && currentValue < m) {
1100
+ m = currentValue;
1101
+ }
1102
+ }
1103
+
1104
+ // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
1105
+ // but guard against overflow
1106
+ handledCPCountPlusOne = handledCPCount + 1;
1107
+ if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
1108
+ error('overflow');
1109
+ }
1110
+
1111
+ delta += (m - n) * handledCPCountPlusOne;
1112
+ n = m;
1113
+
1114
+ for (j = 0; j < inputLength; ++j) {
1115
+ currentValue = input[j];
1116
+
1117
+ if (currentValue < n && ++delta > maxInt) {
1118
+ error('overflow');
1119
+ }
1120
+
1121
+ if (currentValue == n) {
1122
+ // Represent delta as a generalized variable-length integer
1123
+ for (q = delta, k = base; /* no condition */; k += base) {
1124
+ t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
1125
+ if (q < t) {
1126
+ break;
1127
+ }
1128
+ qMinusT = q - t;
1129
+ baseMinusT = base - t;
1130
+ output.push(
1131
+ stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
1132
+ );
1133
+ q = floor(qMinusT / baseMinusT);
1134
+ }
1135
+
1136
+ output.push(stringFromCharCode(digitToBasic(q, 0)));
1137
+ bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
1138
+ delta = 0;
1139
+ ++handledCPCount;
1140
+ }
1141
+ }
1142
+
1143
+ ++delta;
1144
+ ++n;
1145
+
1146
+ }
1147
+ return output.join('');
1148
+ }
1149
+
1150
+ /**
1151
+ * Converts a Punycode string representing a domain name or an email address
1152
+ * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
1153
+ * it doesn't matter if you call it on a string that has already been
1154
+ * converted to Unicode.
1155
+ * @memberOf punycode
1156
+ * @param {String} input The Punycoded domain name or email address to
1157
+ * convert to Unicode.
1158
+ * @returns {String} The Unicode representation of the given Punycode
1159
+ * string.
1160
+ */
1161
+ function toUnicode(input) {
1162
+ return mapDomain(input, function(string) {
1163
+ return regexPunycode.test(string)
1164
+ ? decode(string.slice(4).toLowerCase())
1165
+ : string;
1166
+ });
1167
+ }
1168
+
1169
+ /**
1170
+ * Converts a Unicode string representing a domain name or an email address to
1171
+ * Punycode. Only the non-ASCII parts of the domain name will be converted,
1172
+ * i.e. it doesn't matter if you call it with a domain that's already in
1173
+ * ASCII.
1174
+ * @memberOf punycode
1175
+ * @param {String} input The domain name or email address to convert, as a
1176
+ * Unicode string.
1177
+ * @returns {String} The Punycode representation of the given domain name or
1178
+ * email address.
1179
+ */
1180
+ function toASCII(input) {
1181
+ return mapDomain(input, function(string) {
1182
+ return regexNonASCII.test(string)
1183
+ ? 'xn--' + encode(string)
1184
+ : string;
1185
+ });
1186
+ }
1187
+
1188
+ /*--------------------------------------------------------------------------*/
1189
+
1190
+ /** Define the public API */
1191
+ punycode = {
1192
+ /**
1193
+ * A string representing the current Punycode.js version number.
1194
+ * @memberOf punycode
1195
+ * @type String
1196
+ */
1197
+ 'version': '1.3.2',
1198
+ /**
1199
+ * An object of methods to convert from JavaScript's internal character
1200
+ * representation (UCS-2) to Unicode code points, and back.
1201
+ * @see <https://mathiasbynens.be/notes/javascript-encoding>
1202
+ * @memberOf punycode
1203
+ * @type Object
1204
+ */
1205
+ 'ucs2': {
1206
+ 'decode': ucs2decode,
1207
+ 'encode': ucs2encode
1208
+ },
1209
+ 'decode': decode,
1210
+ 'encode': encode,
1211
+ 'toASCII': toASCII,
1212
+ 'toUnicode': toUnicode
1213
+ };
1214
+
1215
+ /** Expose `punycode` */
1216
+ // Some AMD build optimizers, like r.js, check for specific condition patterns
1217
+ // like the following:
1218
+ if (freeExports && freeModule) {
1219
+ if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+
1220
+ freeModule.exports = punycode;
1221
+ } else { // in Narwhal or RingoJS v0.7.0-
1222
+ for (key in punycode) {
1223
+ punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
1224
+ }
1225
+ }
1226
+ } else { // in Rhino or a web browser
1227
+ root.punycode = punycode;
1228
+ }
1229
+
1230
+ }(commonjsGlobal));
1231
+ });
1232
+
1233
+ var util = {
1234
+ isString: function(arg) {
1235
+ return typeof(arg) === 'string';
1236
+ },
1237
+ isObject: function(arg) {
1238
+ return typeof(arg) === 'object' && arg !== null;
1239
+ },
1240
+ isNull: function(arg) {
1241
+ return arg === null;
1242
+ },
1243
+ isNullOrUndefined: function(arg) {
1244
+ return arg == null;
1245
+ }
1246
+ };
1247
+
1248
+ // Copyright Joyent, Inc. and other Node contributors.
1249
+
1250
+ // If obj.hasOwnProperty has been overridden, then calling
1251
+ // obj.hasOwnProperty(prop) will break.
1252
+ // See: https://github.com/joyent/node/issues/1707
1253
+ function hasOwnProperty(obj, prop) {
1254
+ return Object.prototype.hasOwnProperty.call(obj, prop);
1255
+ }
1256
+
1257
+ var decode$1 = function(qs, sep, eq, options) {
1258
+ sep = sep || '&';
1259
+ eq = eq || '=';
1260
+ var obj = {};
1261
+
1262
+ if (typeof qs !== 'string' || qs.length === 0) {
1263
+ return obj;
1264
+ }
1265
+
1266
+ var regexp = /\+/g;
1267
+ qs = qs.split(sep);
1268
+
1269
+ var maxKeys = 1000;
1270
+ if (options && typeof options.maxKeys === 'number') {
1271
+ maxKeys = options.maxKeys;
1272
+ }
1273
+
1274
+ var len = qs.length;
1275
+ // maxKeys <= 0 means that we should not limit keys count
1276
+ if (maxKeys > 0 && len > maxKeys) {
1277
+ len = maxKeys;
1278
+ }
1279
+
1280
+ for (var i = 0; i < len; ++i) {
1281
+ var x = qs[i].replace(regexp, '%20'),
1282
+ idx = x.indexOf(eq),
1283
+ kstr, vstr, k, v;
1284
+
1285
+ if (idx >= 0) {
1286
+ kstr = x.substr(0, idx);
1287
+ vstr = x.substr(idx + 1);
1288
+ } else {
1289
+ kstr = x;
1290
+ vstr = '';
1291
+ }
1292
+
1293
+ k = decodeURIComponent(kstr);
1294
+ v = decodeURIComponent(vstr);
1295
+
1296
+ if (!hasOwnProperty(obj, k)) {
1297
+ obj[k] = v;
1298
+ } else if (Array.isArray(obj[k])) {
1299
+ obj[k].push(v);
1300
+ } else {
1301
+ obj[k] = [obj[k], v];
1302
+ }
1303
+ }
1304
+
1305
+ return obj;
1306
+ };
1307
+
1308
+ // Copyright Joyent, Inc. and other Node contributors.
1309
+
1310
+ var stringifyPrimitive = function(v) {
1311
+ switch (typeof v) {
1312
+ case 'string':
1313
+ return v;
1314
+
1315
+ case 'boolean':
1316
+ return v ? 'true' : 'false';
1317
+
1318
+ case 'number':
1319
+ return isFinite(v) ? v : '';
1320
+
1321
+ default:
1322
+ return '';
1323
+ }
1324
+ };
1325
+
1326
+ var encode = function(obj, sep, eq, name) {
1327
+ sep = sep || '&';
1328
+ eq = eq || '=';
1329
+ if (obj === null) {
1330
+ obj = undefined;
1331
+ }
1332
+
1333
+ if (typeof obj === 'object') {
1334
+ return Object.keys(obj).map(function(k) {
1335
+ var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
1336
+ if (Array.isArray(obj[k])) {
1337
+ return obj[k].map(function(v) {
1338
+ return ks + encodeURIComponent(stringifyPrimitive(v));
1339
+ }).join(sep);
1340
+ } else {
1341
+ return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
1342
+ }
1343
+ }).join(sep);
1344
+
1345
+ }
1346
+
1347
+ if (!name) return '';
1348
+ return encodeURIComponent(stringifyPrimitive(name)) + eq +
1349
+ encodeURIComponent(stringifyPrimitive(obj));
1350
+ };
1351
+
1352
+ var querystring = createCommonjsModule(function (module, exports) {
1353
+
1354
+ exports.decode = exports.parse = decode$1;
1355
+ exports.encode = exports.stringify = encode;
1356
+ });
1357
+
1358
+ var format = urlFormat;
1359
+
1360
+ function Url() {
1361
+ this.protocol = null;
1362
+ this.slashes = null;
1363
+ this.auth = null;
1364
+ this.host = null;
1365
+ this.port = null;
1366
+ this.hostname = null;
1367
+ this.hash = null;
1368
+ this.search = null;
1369
+ this.query = null;
1370
+ this.pathname = null;
1371
+ this.path = null;
1372
+ this.href = null;
1373
+ }
1374
+
1375
+ // Reference: RFC 3986, RFC 1808, RFC 2396
1376
+
1377
+ // define these here so at least they only have to be
1378
+ // compiled once on the first module load.
1379
+ var protocolPattern = /^([a-z0-9.+-]+:)/i,
1380
+ portPattern = /:[0-9]*$/,
1381
+
1382
+ // Special case for a simple path URL
1383
+ simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
1384
+
1385
+ // RFC 2396: characters reserved for delimiting URLs.
1386
+ // We actually just auto-escape these.
1387
+ delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
1388
+
1389
+ // RFC 2396: characters not allowed for various reasons.
1390
+ unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
1391
+
1392
+ // Allowed by RFCs, but cause of XSS attacks. Always escape these.
1393
+ autoEscape = ['\''].concat(unwise),
1394
+ // Characters that are never ever allowed in a hostname.
1395
+ // Note that any invalid chars are also handled, but these
1396
+ // are the ones that are *expected* to be seen, so we fast-path
1397
+ // them.
1398
+ nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
1399
+ hostEndingChars = ['/', '?', '#'],
1400
+ hostnameMaxLen = 255,
1401
+ hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
1402
+ hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
1403
+ // protocols that can allow "unsafe" and "unwise" chars.
1404
+ unsafeProtocol = {
1405
+ 'javascript': true,
1406
+ 'javascript:': true
1407
+ },
1408
+ // protocols that never have a hostname.
1409
+ hostlessProtocol = {
1410
+ 'javascript': true,
1411
+ 'javascript:': true
1412
+ },
1413
+ // protocols that always contain a // bit.
1414
+ slashedProtocol = {
1415
+ 'http': true,
1416
+ 'https': true,
1417
+ 'ftp': true,
1418
+ 'gopher': true,
1419
+ 'file': true,
1420
+ 'http:': true,
1421
+ 'https:': true,
1422
+ 'ftp:': true,
1423
+ 'gopher:': true,
1424
+ 'file:': true
1425
+ };
1426
+
1427
+ function urlParse(url, parseQueryString, slashesDenoteHost) {
1428
+ if (url && util.isObject(url) && url instanceof Url) return url;
1429
+
1430
+ var u = new Url;
1431
+ u.parse(url, parseQueryString, slashesDenoteHost);
1432
+ return u;
1433
+ }
1434
+
1435
+ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
1436
+ if (!util.isString(url)) {
1437
+ throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
1438
+ }
1439
+
1440
+ // Copy chrome, IE, opera backslash-handling behavior.
1441
+ // Back slashes before the query string get converted to forward slashes
1442
+ // See: https://code.google.com/p/chromium/issues/detail?id=25916
1443
+ var queryIndex = url.indexOf('?'),
1444
+ splitter =
1445
+ (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
1446
+ uSplit = url.split(splitter),
1447
+ slashRegex = /\\/g;
1448
+ uSplit[0] = uSplit[0].replace(slashRegex, '/');
1449
+ url = uSplit.join(splitter);
1450
+
1451
+ var rest = url;
1452
+
1453
+ // trim before proceeding.
1454
+ // This is to support parse stuff like " http://foo.com \n"
1455
+ rest = rest.trim();
1456
+
1457
+ if (!slashesDenoteHost && url.split('#').length === 1) {
1458
+ // Try fast path regexp
1459
+ var simplePath = simplePathPattern.exec(rest);
1460
+ if (simplePath) {
1461
+ this.path = rest;
1462
+ this.href = rest;
1463
+ this.pathname = simplePath[1];
1464
+ if (simplePath[2]) {
1465
+ this.search = simplePath[2];
1466
+ if (parseQueryString) {
1467
+ this.query = querystring.parse(this.search.substr(1));
1468
+ } else {
1469
+ this.query = this.search.substr(1);
1470
+ }
1471
+ } else if (parseQueryString) {
1472
+ this.search = '';
1473
+ this.query = {};
1474
+ }
1475
+ return this;
1476
+ }
1477
+ }
1478
+
1479
+ var proto = protocolPattern.exec(rest);
1480
+ if (proto) {
1481
+ proto = proto[0];
1482
+ var lowerProto = proto.toLowerCase();
1483
+ this.protocol = lowerProto;
1484
+ rest = rest.substr(proto.length);
1485
+ }
1486
+
1487
+ // figure out if it's got a host
1488
+ // user@server is *always* interpreted as a hostname, and url
1489
+ // resolution will treat //foo/bar as host=foo,path=bar because that's
1490
+ // how the browser resolves relative URLs.
1491
+ if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
1492
+ var slashes = rest.substr(0, 2) === '//';
1493
+ if (slashes && !(proto && hostlessProtocol[proto])) {
1494
+ rest = rest.substr(2);
1495
+ this.slashes = true;
1496
+ }
1497
+ }
1498
+
1499
+ if (!hostlessProtocol[proto] &&
1500
+ (slashes || (proto && !slashedProtocol[proto]))) {
1501
+
1502
+ // there's a hostname.
1503
+ // the first instance of /, ?, ;, or # ends the host.
1504
+ //
1505
+ // If there is an @ in the hostname, then non-host chars *are* allowed
1506
+ // to the left of the last @ sign, unless some host-ending character
1507
+ // comes *before* the @-sign.
1508
+ // URLs are obnoxious.
1509
+ //
1510
+ // ex:
1511
+ // http://a@b@c/ => user:a@b host:c
1512
+ // http://a@b?@c => user:a host:c path:/?@c
1513
+
1514
+ // v0.12 TODO(isaacs): This is not quite how Chrome does things.
1515
+ // Review our test case against browsers more comprehensively.
1516
+
1517
+ // find the first instance of any hostEndingChars
1518
+ var hostEnd = -1;
1519
+ for (var i = 0; i < hostEndingChars.length; i++) {
1520
+ var hec = rest.indexOf(hostEndingChars[i]);
1521
+ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
1522
+ hostEnd = hec;
1523
+ }
1524
+
1525
+ // at this point, either we have an explicit point where the
1526
+ // auth portion cannot go past, or the last @ char is the decider.
1527
+ var auth, atSign;
1528
+ if (hostEnd === -1) {
1529
+ // atSign can be anywhere.
1530
+ atSign = rest.lastIndexOf('@');
1531
+ } else {
1532
+ // atSign must be in auth portion.
1533
+ // http://a@b/c@d => host:b auth:a path:/c@d
1534
+ atSign = rest.lastIndexOf('@', hostEnd);
1535
+ }
1536
+
1537
+ // Now we have a portion which is definitely the auth.
1538
+ // Pull that off.
1539
+ if (atSign !== -1) {
1540
+ auth = rest.slice(0, atSign);
1541
+ rest = rest.slice(atSign + 1);
1542
+ this.auth = decodeURIComponent(auth);
1543
+ }
1544
+
1545
+ // the host is the remaining to the left of the first non-host char
1546
+ hostEnd = -1;
1547
+ for (var i = 0; i < nonHostChars.length; i++) {
1548
+ var hec = rest.indexOf(nonHostChars[i]);
1549
+ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
1550
+ hostEnd = hec;
1551
+ }
1552
+ // if we still have not hit it, then the entire thing is a host.
1553
+ if (hostEnd === -1)
1554
+ hostEnd = rest.length;
1555
+
1556
+ this.host = rest.slice(0, hostEnd);
1557
+ rest = rest.slice(hostEnd);
1558
+
1559
+ // pull out port.
1560
+ this.parseHost();
1561
+
1562
+ // we've indicated that there is a hostname,
1563
+ // so even if it's empty, it has to be present.
1564
+ this.hostname = this.hostname || '';
1565
+
1566
+ // if hostname begins with [ and ends with ]
1567
+ // assume that it's an IPv6 address.
1568
+ var ipv6Hostname = this.hostname[0] === '[' &&
1569
+ this.hostname[this.hostname.length - 1] === ']';
1570
+
1571
+ // validate a little.
1572
+ if (!ipv6Hostname) {
1573
+ var hostparts = this.hostname.split(/\./);
1574
+ for (var i = 0, l = hostparts.length; i < l; i++) {
1575
+ var part = hostparts[i];
1576
+ if (!part) continue;
1577
+ if (!part.match(hostnamePartPattern)) {
1578
+ var newpart = '';
1579
+ for (var j = 0, k = part.length; j < k; j++) {
1580
+ if (part.charCodeAt(j) > 127) {
1581
+ // we replace non-ASCII char with a temporary placeholder
1582
+ // we need this to make sure size of hostname is not
1583
+ // broken by replacing non-ASCII by nothing
1584
+ newpart += 'x';
1585
+ } else {
1586
+ newpart += part[j];
1587
+ }
1588
+ }
1589
+ // we test again with ASCII char only
1590
+ if (!newpart.match(hostnamePartPattern)) {
1591
+ var validParts = hostparts.slice(0, i);
1592
+ var notHost = hostparts.slice(i + 1);
1593
+ var bit = part.match(hostnamePartStart);
1594
+ if (bit) {
1595
+ validParts.push(bit[1]);
1596
+ notHost.unshift(bit[2]);
1597
+ }
1598
+ if (notHost.length) {
1599
+ rest = '/' + notHost.join('.') + rest;
1600
+ }
1601
+ this.hostname = validParts.join('.');
1602
+ break;
1603
+ }
1604
+ }
1605
+ }
1606
+ }
1607
+
1608
+ if (this.hostname.length > hostnameMaxLen) {
1609
+ this.hostname = '';
1610
+ } else {
1611
+ // hostnames are always lower case.
1612
+ this.hostname = this.hostname.toLowerCase();
1613
+ }
1614
+
1615
+ if (!ipv6Hostname) {
1616
+ // IDNA Support: Returns a punycoded representation of "domain".
1617
+ // It only converts parts of the domain name that
1618
+ // have non-ASCII characters, i.e. it doesn't matter if
1619
+ // you call it with a domain that already is ASCII-only.
1620
+ this.hostname = punycode.toASCII(this.hostname);
1621
+ }
1622
+
1623
+ var p = this.port ? ':' + this.port : '';
1624
+ var h = this.hostname || '';
1625
+ this.host = h + p;
1626
+ this.href += this.host;
1627
+
1628
+ // strip [ and ] from the hostname
1629
+ // the host field still retains them, though
1630
+ if (ipv6Hostname) {
1631
+ this.hostname = this.hostname.substr(1, this.hostname.length - 2);
1632
+ if (rest[0] !== '/') {
1633
+ rest = '/' + rest;
1634
+ }
1635
+ }
1636
+ }
1637
+
1638
+ // now rest is set to the post-host stuff.
1639
+ // chop off any delim chars.
1640
+ if (!unsafeProtocol[lowerProto]) {
1641
+
1642
+ // First, make 100% sure that any "autoEscape" chars get
1643
+ // escaped, even if encodeURIComponent doesn't think they
1644
+ // need to be.
1645
+ for (var i = 0, l = autoEscape.length; i < l; i++) {
1646
+ var ae = autoEscape[i];
1647
+ if (rest.indexOf(ae) === -1)
1648
+ continue;
1649
+ var esc = encodeURIComponent(ae);
1650
+ if (esc === ae) {
1651
+ esc = escape(ae);
1652
+ }
1653
+ rest = rest.split(ae).join(esc);
1654
+ }
1655
+ }
1656
+
1657
+
1658
+ // chop off from the tail first.
1659
+ var hash = rest.indexOf('#');
1660
+ if (hash !== -1) {
1661
+ // got a fragment string.
1662
+ this.hash = rest.substr(hash);
1663
+ rest = rest.slice(0, hash);
1664
+ }
1665
+ var qm = rest.indexOf('?');
1666
+ if (qm !== -1) {
1667
+ this.search = rest.substr(qm);
1668
+ this.query = rest.substr(qm + 1);
1669
+ if (parseQueryString) {
1670
+ this.query = querystring.parse(this.query);
1671
+ }
1672
+ rest = rest.slice(0, qm);
1673
+ } else if (parseQueryString) {
1674
+ // no query string, but parseQueryString still requested
1675
+ this.search = '';
1676
+ this.query = {};
1677
+ }
1678
+ if (rest) this.pathname = rest;
1679
+ if (slashedProtocol[lowerProto] &&
1680
+ this.hostname && !this.pathname) {
1681
+ this.pathname = '/';
1682
+ }
1683
+
1684
+ //to support http.request
1685
+ if (this.pathname || this.search) {
1686
+ var p = this.pathname || '';
1687
+ var s = this.search || '';
1688
+ this.path = p + s;
1689
+ }
1690
+
1691
+ // finally, reconstruct the href based on what has been validated.
1692
+ this.href = this.format();
1693
+ return this;
1694
+ };
1695
+
1696
+ // format a parsed object into a url string
1697
+ function urlFormat(obj) {
1698
+ // ensure it's an object, and not a string url.
1699
+ // If it's an obj, this is a no-op.
1700
+ // this way, you can call url_format() on strings
1701
+ // to clean up potentially wonky urls.
1702
+ if (util.isString(obj)) obj = urlParse(obj);
1703
+ if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
1704
+ return obj.format();
1705
+ }
1706
+
1707
+ Url.prototype.format = function() {
1708
+ var auth = this.auth || '';
1709
+ if (auth) {
1710
+ auth = encodeURIComponent(auth);
1711
+ auth = auth.replace(/%3A/i, ':');
1712
+ auth += '@';
1713
+ }
1714
+
1715
+ var protocol = this.protocol || '',
1716
+ pathname = this.pathname || '',
1717
+ hash = this.hash || '',
1718
+ host = false,
1719
+ query = '';
1720
+
1721
+ if (this.host) {
1722
+ host = auth + this.host;
1723
+ } else if (this.hostname) {
1724
+ host = auth + (this.hostname.indexOf(':') === -1 ?
1725
+ this.hostname :
1726
+ '[' + this.hostname + ']');
1727
+ if (this.port) {
1728
+ host += ':' + this.port;
1729
+ }
1730
+ }
1731
+
1732
+ if (this.query &&
1733
+ util.isObject(this.query) &&
1734
+ Object.keys(this.query).length) {
1735
+ query = querystring.stringify(this.query);
1736
+ }
1737
+
1738
+ var search = this.search || (query && ('?' + query)) || '';
1739
+
1740
+ if (protocol && protocol.substr(-1) !== ':') protocol += ':';
1741
+
1742
+ // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
1743
+ // unless they had them to begin with.
1744
+ if (this.slashes ||
1745
+ (!protocol || slashedProtocol[protocol]) && host !== false) {
1746
+ host = '//' + (host || '');
1747
+ if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
1748
+ } else if (!host) {
1749
+ host = '';
1750
+ }
1751
+
1752
+ if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
1753
+ if (search && search.charAt(0) !== '?') search = '?' + search;
1754
+
1755
+ pathname = pathname.replace(/[?#]/g, function(match) {
1756
+ return encodeURIComponent(match);
1757
+ });
1758
+ search = search.replace('#', '%23');
1759
+
1760
+ return protocol + host + pathname + search + hash;
1761
+ };
1762
+
1763
+ Url.prototype.resolve = function(relative) {
1764
+ return this.resolveObject(urlParse(relative, false, true)).format();
1765
+ };
1766
+
1767
+ Url.prototype.resolveObject = function(relative) {
1768
+ if (util.isString(relative)) {
1769
+ var rel = new Url();
1770
+ rel.parse(relative, false, true);
1771
+ relative = rel;
1772
+ }
1773
+
1774
+ var result = new Url();
1775
+ var tkeys = Object.keys(this);
1776
+ for (var tk = 0; tk < tkeys.length; tk++) {
1777
+ var tkey = tkeys[tk];
1778
+ result[tkey] = this[tkey];
1779
+ }
1780
+
1781
+ // hash is always overridden, no matter what.
1782
+ // even href="" will remove it.
1783
+ result.hash = relative.hash;
1784
+
1785
+ // if the relative url is empty, then there's nothing left to do here.
1786
+ if (relative.href === '') {
1787
+ result.href = result.format();
1788
+ return result;
1789
+ }
1790
+
1791
+ // hrefs like //foo/bar always cut to the protocol.
1792
+ if (relative.slashes && !relative.protocol) {
1793
+ // take everything except the protocol from relative
1794
+ var rkeys = Object.keys(relative);
1795
+ for (var rk = 0; rk < rkeys.length; rk++) {
1796
+ var rkey = rkeys[rk];
1797
+ if (rkey !== 'protocol')
1798
+ result[rkey] = relative[rkey];
1799
+ }
1800
+
1801
+ //urlParse appends trailing / to urls like http://www.example.com
1802
+ if (slashedProtocol[result.protocol] &&
1803
+ result.hostname && !result.pathname) {
1804
+ result.path = result.pathname = '/';
1805
+ }
1806
+
1807
+ result.href = result.format();
1808
+ return result;
1809
+ }
1810
+
1811
+ if (relative.protocol && relative.protocol !== result.protocol) {
1812
+ // if it's a known url protocol, then changing
1813
+ // the protocol does weird things
1814
+ // first, if it's not file:, then we MUST have a host,
1815
+ // and if there was a path
1816
+ // to begin with, then we MUST have a path.
1817
+ // if it is file:, then the host is dropped,
1818
+ // because that's known to be hostless.
1819
+ // anything else is assumed to be absolute.
1820
+ if (!slashedProtocol[relative.protocol]) {
1821
+ var keys = Object.keys(relative);
1822
+ for (var v = 0; v < keys.length; v++) {
1823
+ var k = keys[v];
1824
+ result[k] = relative[k];
1825
+ }
1826
+ result.href = result.format();
1827
+ return result;
1828
+ }
1829
+
1830
+ result.protocol = relative.protocol;
1831
+ if (!relative.host && !hostlessProtocol[relative.protocol]) {
1832
+ var relPath = (relative.pathname || '').split('/');
1833
+ while (relPath.length && !(relative.host = relPath.shift()));
1834
+ if (!relative.host) relative.host = '';
1835
+ if (!relative.hostname) relative.hostname = '';
1836
+ if (relPath[0] !== '') relPath.unshift('');
1837
+ if (relPath.length < 2) relPath.unshift('');
1838
+ result.pathname = relPath.join('/');
1839
+ } else {
1840
+ result.pathname = relative.pathname;
1841
+ }
1842
+ result.search = relative.search;
1843
+ result.query = relative.query;
1844
+ result.host = relative.host || '';
1845
+ result.auth = relative.auth;
1846
+ result.hostname = relative.hostname || relative.host;
1847
+ result.port = relative.port;
1848
+ // to support http.request
1849
+ if (result.pathname || result.search) {
1850
+ var p = result.pathname || '';
1851
+ var s = result.search || '';
1852
+ result.path = p + s;
1853
+ }
1854
+ result.slashes = result.slashes || relative.slashes;
1855
+ result.href = result.format();
1856
+ return result;
1857
+ }
1858
+
1859
+ var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
1860
+ isRelAbs = (
1861
+ relative.host ||
1862
+ relative.pathname && relative.pathname.charAt(0) === '/'
1863
+ ),
1864
+ mustEndAbs = (isRelAbs || isSourceAbs ||
1865
+ (result.host && relative.pathname)),
1866
+ removeAllDots = mustEndAbs,
1867
+ srcPath = result.pathname && result.pathname.split('/') || [],
1868
+ relPath = relative.pathname && relative.pathname.split('/') || [],
1869
+ psychotic = result.protocol && !slashedProtocol[result.protocol];
1870
+
1871
+ // if the url is a non-slashed url, then relative
1872
+ // links like ../.. should be able
1873
+ // to crawl up to the hostname, as well. This is strange.
1874
+ // result.protocol has already been set by now.
1875
+ // Later on, put the first path part into the host field.
1876
+ if (psychotic) {
1877
+ result.hostname = '';
1878
+ result.port = null;
1879
+ if (result.host) {
1880
+ if (srcPath[0] === '') srcPath[0] = result.host;
1881
+ else srcPath.unshift(result.host);
1882
+ }
1883
+ result.host = '';
1884
+ if (relative.protocol) {
1885
+ relative.hostname = null;
1886
+ relative.port = null;
1887
+ if (relative.host) {
1888
+ if (relPath[0] === '') relPath[0] = relative.host;
1889
+ else relPath.unshift(relative.host);
1890
+ }
1891
+ relative.host = null;
1892
+ }
1893
+ mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
1894
+ }
1895
+
1896
+ if (isRelAbs) {
1897
+ // it's absolute.
1898
+ result.host = (relative.host || relative.host === '') ?
1899
+ relative.host : result.host;
1900
+ result.hostname = (relative.hostname || relative.hostname === '') ?
1901
+ relative.hostname : result.hostname;
1902
+ result.search = relative.search;
1903
+ result.query = relative.query;
1904
+ srcPath = relPath;
1905
+ // fall through to the dot-handling below.
1906
+ } else if (relPath.length) {
1907
+ // it's relative
1908
+ // throw away the existing file, and take the new path instead.
1909
+ if (!srcPath) srcPath = [];
1910
+ srcPath.pop();
1911
+ srcPath = srcPath.concat(relPath);
1912
+ result.search = relative.search;
1913
+ result.query = relative.query;
1914
+ } else if (!util.isNullOrUndefined(relative.search)) {
1915
+ // just pull out the search.
1916
+ // like href='?foo'.
1917
+ // Put this after the other two cases because it simplifies the booleans
1918
+ if (psychotic) {
1919
+ result.hostname = result.host = srcPath.shift();
1920
+ //occationaly the auth can get stuck only in host
1921
+ //this especially happens in cases like
1922
+ //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
1923
+ var authInHost = result.host && result.host.indexOf('@') > 0 ?
1924
+ result.host.split('@') : false;
1925
+ if (authInHost) {
1926
+ result.auth = authInHost.shift();
1927
+ result.host = result.hostname = authInHost.shift();
1928
+ }
1929
+ }
1930
+ result.search = relative.search;
1931
+ result.query = relative.query;
1932
+ //to support http.request
1933
+ if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
1934
+ result.path = (result.pathname ? result.pathname : '') +
1935
+ (result.search ? result.search : '');
1936
+ }
1937
+ result.href = result.format();
1938
+ return result;
1939
+ }
1940
+
1941
+ if (!srcPath.length) {
1942
+ // no path at all. easy.
1943
+ // we've already handled the other stuff above.
1944
+ result.pathname = null;
1945
+ //to support http.request
1946
+ if (result.search) {
1947
+ result.path = '/' + result.search;
1948
+ } else {
1949
+ result.path = null;
1950
+ }
1951
+ result.href = result.format();
1952
+ return result;
1953
+ }
1954
+
1955
+ // if a url ENDs in . or .., then it must get a trailing slash.
1956
+ // however, if it ends in anything else non-slashy,
1957
+ // then it must NOT get a trailing slash.
1958
+ var last = srcPath.slice(-1)[0];
1959
+ var hasTrailingSlash = (
1960
+ (result.host || relative.host || srcPath.length > 1) &&
1961
+ (last === '.' || last === '..') || last === '');
1962
+
1963
+ // strip single dots, resolve double dots to parent dir
1964
+ // if the path tries to go above the root, `up` ends up > 0
1965
+ var up = 0;
1966
+ for (var i = srcPath.length; i >= 0; i--) {
1967
+ last = srcPath[i];
1968
+ if (last === '.') {
1969
+ srcPath.splice(i, 1);
1970
+ } else if (last === '..') {
1971
+ srcPath.splice(i, 1);
1972
+ up++;
1973
+ } else if (up) {
1974
+ srcPath.splice(i, 1);
1975
+ up--;
1976
+ }
1977
+ }
1978
+
1979
+ // if the path is allowed to go above the root, restore leading ..s
1980
+ if (!mustEndAbs && !removeAllDots) {
1981
+ for (; up--; up) {
1982
+ srcPath.unshift('..');
1983
+ }
1984
+ }
1985
+
1986
+ if (mustEndAbs && srcPath[0] !== '' &&
1987
+ (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
1988
+ srcPath.unshift('');
1989
+ }
1990
+
1991
+ if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
1992
+ srcPath.push('');
1993
+ }
1994
+
1995
+ var isAbsolute = srcPath[0] === '' ||
1996
+ (srcPath[0] && srcPath[0].charAt(0) === '/');
1997
+
1998
+ // put the host back
1999
+ if (psychotic) {
2000
+ result.hostname = result.host = isAbsolute ? '' :
2001
+ srcPath.length ? srcPath.shift() : '';
2002
+ //occationaly the auth can get stuck only in host
2003
+ //this especially happens in cases like
2004
+ //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
2005
+ var authInHost = result.host && result.host.indexOf('@') > 0 ?
2006
+ result.host.split('@') : false;
2007
+ if (authInHost) {
2008
+ result.auth = authInHost.shift();
2009
+ result.host = result.hostname = authInHost.shift();
2010
+ }
2011
+ }
2012
+
2013
+ mustEndAbs = mustEndAbs || (result.host && srcPath.length);
2014
+
2015
+ if (mustEndAbs && !isAbsolute) {
2016
+ srcPath.unshift('');
2017
+ }
2018
+
2019
+ if (!srcPath.length) {
2020
+ result.pathname = null;
2021
+ result.path = null;
2022
+ } else {
2023
+ result.pathname = srcPath.join('/');
2024
+ }
2025
+
2026
+ //to support request.http
2027
+ if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
2028
+ result.path = (result.pathname ? result.pathname : '') +
2029
+ (result.search ? result.search : '');
2030
+ }
2031
+ result.auth = relative.auth || result.auth;
2032
+ result.slashes = result.slashes || relative.slashes;
2033
+ result.href = result.format();
2034
+ return result;
2035
+ };
2036
+
2037
+ Url.prototype.parseHost = function() {
2038
+ var host = this.host;
2039
+ var port = portPattern.exec(host);
2040
+ if (port) {
2041
+ port = port[0];
2042
+ if (port !== ':') {
2043
+ this.port = port.substr(1);
2044
+ }
2045
+ host = host.substr(0, host.length - port.length);
2046
+ }
2047
+ if (host) this.hostname = host;
2048
+ };
2049
+
2050
+ /**
2051
+ * Returns a relative URL if the given request URL is relative to the current origin.
2052
+ * Otherwise returns an absolute URL.
2053
+ */
2054
+ const getPublicUrlFromRequest = (request) => {
2055
+ return request.referrer.startsWith(request.url.origin)
2056
+ ? request.url.pathname
2057
+ : format({
2058
+ protocol: request.url.protocol,
2059
+ host: request.url.host,
2060
+ pathname: request.url.pathname,
2061
+ });
2062
+ };
2063
+
710
2064
  function onUnhandledRequest(request, onUnhandledRequest = 'bypass') {
711
2065
  if (typeof onUnhandledRequest === 'function') {
712
2066
  onUnhandledRequest(request);
713
2067
  return;
714
2068
  }
715
- const message = `captured a ${request.method} ${request.url} request without a corresponding request handler.`;
2069
+ const publicUrl = getPublicUrlFromRequest(request);
2070
+ const message = `captured a ${request.method} ${request.url} request without a corresponding request handler.
2071
+
2072
+ If you wish to intercept this request, consider creating a request handler for it:
2073
+
2074
+ rest.${request.method.toLowerCase()}('${publicUrl}', (req, res, ctx) => {
2075
+ return res(ctx.text('body'))
2076
+ })`;
716
2077
  switch (onUnhandledRequest) {
717
2078
  case 'error': {
718
2079
  throw new Error(`[MSW] Error: ${message}`);
@@ -729,100 +2090,114 @@ const DEFAULT_LISTEN_OPTIONS = {
729
2090
  onUnhandledRequest: 'bypass',
730
2091
  };
731
2092
  /**
732
- * Sets up a server-side requests interception with the given mock definition.
2093
+ * Creates a `setupServer` API using given request interceptors.
2094
+ * Useful to generate identical API using different patches to request issuing modules.
733
2095
  */
734
- const setupServer = (...requestHandlers) => {
735
- const interceptor = new nodeRequestInterceptor.RequestInterceptor();
736
- // Error when attempting to run this function in a browser environment.
737
- if (!isNodeProcess()) {
738
- throw new Error('[MSW] Failed to execute `setupServer` in the environment that is not NodeJS (i.e. a browser). Consider using `setupWorker` instead.');
739
- }
740
- // Store the list of request handlers for the current server instance,
741
- // so it could be modified at a runtime.
742
- let currentHandlers = [...requestHandlers];
743
- return {
744
- /**
745
- * Enables requests interception based on the previously provided mock definition.
746
- */
747
- listen(options) {
748
- const resolvedOptions = Object.assign({}, DEFAULT_LISTEN_OPTIONS, options);
749
- interceptor.use((req) => __awaiter(this, void 0, void 0, function* () {
750
- const requestHeaders = new lib.Headers(lib.flattenHeadersObject(req.headers || {}));
751
- const requestCookieString = requestHeaders.get('cookie');
752
- const mockedRequest = {
753
- url: req.url,
754
- method: req.method,
755
- // Parse the request's body based on the "Content-Type" header.
756
- body: parseRequestBody(req.body, requestHeaders),
757
- headers: requestHeaders,
758
- cookies: {},
759
- params: {},
760
- redirect: 'manual',
761
- referrer: '',
762
- keepalive: false,
763
- cache: 'default',
764
- mode: 'cors',
765
- referrerPolicy: 'no-referrer',
766
- integrity: '',
767
- destination: 'document',
768
- bodyUsed: false,
769
- credentials: 'same-origin',
770
- };
771
- if (requestCookieString) {
772
- // Set mocked request cookies from the `cookie` header of the original request.
773
- // No need to take `credentials` into account, because in NodeJS requests are intercepted
774
- // _after_ they happen. Request issuer should have already taken care of sending relevant cookies.
775
- // Unlike browser, where interception is on the worker level, _before_ the request happens.
776
- mockedRequest.cookies = parse_1(requestCookieString);
777
- }
778
- if (mockedRequest.headers.get('x-msw-bypass')) {
779
- return;
780
- }
781
- const { response } = yield getResponse(mockedRequest, currentHandlers);
782
- if (!response) {
783
- onUnhandledRequest(mockedRequest, resolvedOptions.onUnhandledRequest);
784
- return;
785
- }
786
- return new Promise((resolve) => {
787
- var _a;
788
- // the node build will use the timers module to ensure @sinon/fake-timers or jest fake timers
789
- // don't affect this timeout.
790
- setTimeout(() => {
791
- resolve({
792
- status: response.status,
793
- statusText: response.statusText,
794
- headers: response.headers.getAllHeaders(),
795
- body: response.body,
796
- });
797
- }, (_a = response.delay) !== null && _a !== void 0 ? _a : 0);
798
- });
799
- }));
800
- },
801
- /**
802
- * Prepends given request handlers to the list of existing handlers.
803
- */
804
- use(...handlers) {
805
- use(currentHandlers, ...handlers);
806
- },
807
- /**
808
- * Marks all request handlers that respond using `res.once()` as unused.
809
- */
810
- restoreHandlers() {
811
- restoreHandlers(currentHandlers);
812
- },
813
- /**
814
- * Resets request handlers to the initial list given to the `setupServer` call, or to the explicit next request handlers list, if given.
815
- */
816
- resetHandlers(...nextHandlers) {
817
- currentHandlers = resetHandlers(requestHandlers, ...nextHandlers);
818
- },
819
- /**
820
- * Stops requests interception by restoring all augmented modules.
821
- */
822
- close() {
823
- interceptor.restore();
824
- },
2096
+ function createSetupServer(...interceptors) {
2097
+ /**
2098
+ * Sets up a server-side requests interception with the given mock definition.
2099
+ */
2100
+ return function setupServer(...requestHandlers) {
2101
+ requestHandlers.forEach((handler) => {
2102
+ if (Array.isArray(handler))
2103
+ throw new Error(`[MSW] Failed to call "setupServer" given an Array of request handlers (setupServer([a, b])), expected to receive each handler individually: setupServer(a, b).`);
2104
+ });
2105
+ const interceptor = new nodeRequestInterceptor.RequestInterceptor(interceptors);
2106
+ // Error when attempting to run this function in a browser environment.
2107
+ if (!isNodeProcess()) {
2108
+ throw new Error('[MSW] Failed to execute `setupServer` in the environment that is not NodeJS (i.e. a browser). Consider using `setupWorker` instead.');
2109
+ }
2110
+ // Store the list of request handlers for the current server instance,
2111
+ // so it could be modified at a runtime.
2112
+ let currentHandlers = [...requestHandlers];
2113
+ return {
2114
+ /**
2115
+ * Enables requests interception based on the previously provided mock definition.
2116
+ */
2117
+ listen(options) {
2118
+ const resolvedOptions = Object.assign({}, DEFAULT_LISTEN_OPTIONS, options);
2119
+ interceptor.use((req) => __awaiter(this, void 0, void 0, function* () {
2120
+ const requestHeaders = new lib.Headers(lib.flattenHeadersObject(req.headers || {}));
2121
+ const requestCookieString = requestHeaders.get('cookie');
2122
+ const mockedRequest = {
2123
+ url: req.url,
2124
+ method: req.method,
2125
+ // Parse the request's body based on the "Content-Type" header.
2126
+ body: parseBody(req.body, requestHeaders),
2127
+ headers: requestHeaders,
2128
+ cookies: {},
2129
+ params: {},
2130
+ redirect: 'manual',
2131
+ referrer: '',
2132
+ keepalive: false,
2133
+ cache: 'default',
2134
+ mode: 'cors',
2135
+ referrerPolicy: 'no-referrer',
2136
+ integrity: '',
2137
+ destination: 'document',
2138
+ bodyUsed: false,
2139
+ credentials: 'same-origin',
2140
+ };
2141
+ if (requestCookieString) {
2142
+ // Set mocked request cookies from the `cookie` header of the original request.
2143
+ // No need to take `credentials` into account, because in NodeJS requests are intercepted
2144
+ // _after_ they happen. Request issuer should have already taken care of sending relevant cookies.
2145
+ // Unlike browser, where interception is on the worker level, _before_ the request happens.
2146
+ mockedRequest.cookies = parse_1(requestCookieString);
2147
+ }
2148
+ if (mockedRequest.headers.get('x-msw-bypass')) {
2149
+ return;
2150
+ }
2151
+ const { response } = yield getResponse(mockedRequest, currentHandlers);
2152
+ if (!response) {
2153
+ onUnhandledRequest(mockedRequest, resolvedOptions.onUnhandledRequest);
2154
+ return;
2155
+ }
2156
+ return new Promise((resolve) => {
2157
+ var _a;
2158
+ // the node build will use the timers module to ensure @sinon/fake-timers or jest fake timers
2159
+ // don't affect this timeout.
2160
+ setTimeout(() => {
2161
+ resolve({
2162
+ status: response.status,
2163
+ statusText: response.statusText,
2164
+ headers: response.headers.getAllHeaders(),
2165
+ body: response.body,
2166
+ });
2167
+ }, (_a = response.delay) !== null && _a !== void 0 ? _a : 0);
2168
+ });
2169
+ }));
2170
+ },
2171
+ /**
2172
+ * Prepends given request handlers to the list of existing handlers.
2173
+ */
2174
+ use(...handlers) {
2175
+ use(currentHandlers, ...handlers);
2176
+ },
2177
+ /**
2178
+ * Marks all request handlers that respond using `res.once()` as unused.
2179
+ */
2180
+ restoreHandlers() {
2181
+ restoreHandlers(currentHandlers);
2182
+ },
2183
+ /**
2184
+ * Resets request handlers to the initial list given to the `setupServer` call, or to the explicit next request handlers list, if given.
2185
+ */
2186
+ resetHandlers(...nextHandlers) {
2187
+ currentHandlers = resetHandlers(requestHandlers, ...nextHandlers);
2188
+ },
2189
+ /**
2190
+ * Stops requests interception by restoring all augmented modules.
2191
+ */
2192
+ close() {
2193
+ interceptor.restore();
2194
+ },
2195
+ };
825
2196
  };
826
- };
2197
+ }
2198
+
2199
+ // Provision request interception via patching the `XMLHttpRequest` class only
2200
+ // in React Native. There is no `http`/`https` modules in that environment.
2201
+ const setupServer = createSetupServer(XMLHttpRequest.interceptXMLHttpRequest);
827
2202
 
828
2203
  exports.setupServer = setupServer;