msw 0.34.0 → 0.36.2

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 (49) hide show
  1. package/lib/esm/RequestHandler-deps.js +391 -66
  2. package/lib/esm/errors-deps.js +15 -1
  3. package/lib/esm/fetch-deps.js +9 -5
  4. package/lib/esm/graphql-deps.js +10 -6
  5. package/lib/esm/graphql.js +1 -0
  6. package/lib/esm/index-deps.js +2 -1
  7. package/lib/esm/index.js +102 -3893
  8. package/lib/esm/index2.js +1 -1
  9. package/lib/esm/mockServiceWorker.js +5 -5
  10. package/lib/esm/rest-deps.js +7 -15
  11. package/lib/esm/rest.js +1 -0
  12. package/lib/iife/index.js +3 -3
  13. package/lib/iife/mockServiceWorker.js +5 -5
  14. package/lib/types/context/data.d.ts +2 -3
  15. package/lib/types/context/extensions.d.ts +8 -0
  16. package/lib/types/context/index.d.ts +1 -0
  17. package/lib/types/graphql.d.ts +2 -1
  18. package/lib/types/handlers/GraphQLHandler.d.ts +7 -6
  19. package/lib/types/handlers/RequestHandler.d.ts +8 -8
  20. package/lib/types/handlers/RestHandler.d.ts +10 -12
  21. package/lib/types/index.d.ts +17 -7
  22. package/lib/types/native/index.d.ts +1 -1
  23. package/lib/types/node/glossary.d.ts +4 -14
  24. package/lib/types/node/index.d.ts +1 -1
  25. package/lib/types/node/setupServer.d.ts +1 -1
  26. package/lib/types/rest.d.ts +10 -9
  27. package/lib/types/setupWorker/glossary.d.ts +16 -26
  28. package/lib/types/setupWorker/start/utils/prepareStartHandler.d.ts +3 -3
  29. package/lib/types/sharedOptions.d.ts +12 -1
  30. package/lib/types/typeUtils.d.ts +5 -3
  31. package/lib/types/utils/getResponse.d.ts +1 -1
  32. package/lib/types/utils/handleRequest.d.ts +4 -4
  33. package/lib/types/utils/internal/getCallFrame.d.ts +1 -1
  34. package/lib/types/utils/internal/jsonParse.d.ts +2 -2
  35. package/lib/types/utils/internal/pipeEvents.d.ts +6 -0
  36. package/lib/types/utils/internal/requestHandlerUtils.d.ts +1 -1
  37. package/lib/types/utils/logging/prepareResponse.d.ts +1 -1
  38. package/lib/types/utils/matching/matchRequestUrl.d.ts +12 -2
  39. package/lib/types/utils/matching/normalizePath.d.ts +1 -1
  40. package/lib/types/utils/request/onUnhandledRequest.d.ts +1 -2
  41. package/lib/types/utils/request/parseBody.d.ts +2 -2
  42. package/lib/types/utils/request/parseWorkerRequest.d.ts +2 -2
  43. package/lib/types/utils/worker/createFallbackRequestListener.d.ts +2 -1
  44. package/lib/types/utils/worker/createRequestListener.d.ts +2 -1
  45. package/lib/umd/index.js +1070 -243
  46. package/lib/umd/mockServiceWorker.js +5 -5
  47. package/native/lib/index.js +501 -501
  48. package/node/lib/index.js +503 -503
  49. package/package.json +19 -19
package/lib/esm/index.js CHANGED
@@ -1,16 +1,20 @@
1
1
  export { i as context } from './index-deps.js';
2
- import { c as commonjsGlobal, p as parse_1, l as lib$4, a as lib$6, j as jsonParse } from './fetch-deps.js';
3
- import { _ as __awaiter$3, d as devUtils, p as parseBody, g as getPublicUrlFromRequest, N as NetworkError, l as lib$5, a as getCleanUrl } from './RequestHandler-deps.js';
4
- export { R as RequestHandler, f as compose, c as createResponseComposition, e as defaultContext, b as defaultResponse, m as matchRequestUrl, r as response } from './RequestHandler-deps.js';
2
+ import { c as commonjsGlobal, p as parse_1, l as lib$2, a as lib$3, j as jsonParse } from './fetch-deps.js';
3
+ import { _ as __awaiter, d as devUtils, p as parseBody, g as getPublicUrlFromRequest, N as NetworkError } from './RequestHandler-deps.js';
4
+ export { R as RequestHandler, f as cleanUrl, e as compose, c as createResponseComposition, b as defaultContext, a as defaultResponse, m as matchRequestUrl, r as response } from './RequestHandler-deps.js';
5
+ import { store } from '@mswjs/cookies';
5
6
  import { i as isStringEqual, R as RestHandler } from './rest-deps.js';
6
7
  export { a as RESTMethods, R as RestHandler, r as rest, b as restContext } from './rest-deps.js';
7
8
  import { t as tryCatch, p as parseGraphQLRequest, G as GraphQLHandler } from './graphql-deps.js';
8
9
  export { G as GraphQLHandler, g as graphql, a as graphqlContext } from './graphql-deps.js';
9
10
  import { m as mergeRight } from './errors-deps.js';
10
- import require$$3 from 'debug';
11
+ import { createInterceptor } from '@mswjs/interceptors';
12
+ import { interceptFetch } from '@mswjs/interceptors/lib/interceptors/fetch';
13
+ import { interceptXMLHttpRequest } from '@mswjs/interceptors/lib/interceptors/XMLHttpRequest';
11
14
  import './xml-deps.js';
15
+ import '@mswjs/interceptors/lib/utils/getCleanUrl';
12
16
 
13
- var lib$3 = {};
17
+ var lib$1 = {};
14
18
 
15
19
  var StrictEventEmitter$1 = {};
16
20
 
@@ -490,7 +494,7 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
490
494
  }
491
495
  }
492
496
 
493
- var __extends$1 = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
497
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
494
498
  var extendStatics = function (d, b) {
495
499
  extendStatics = Object.setPrototypeOf ||
496
500
  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
@@ -514,7 +518,7 @@ StrictEventEmitter$1.__esModule = true;
514
518
  StrictEventEmitter$1.StrictEventEmitter = void 0;
515
519
  var events_1 = events.exports;
516
520
  var StrictEventEmitter = /** @class */ (function (_super) {
517
- __extends$1(StrictEventEmitter, _super);
521
+ __extends(StrictEventEmitter, _super);
518
522
  function StrictEventEmitter() {
519
523
  return _super.call(this) || this;
520
524
  }
@@ -556,9 +560,9 @@ exports.__esModule = true;
556
560
  exports.StrictEventEmitter = void 0;
557
561
  var StrictEventEmitter_1 = StrictEventEmitter$1;
558
562
  __createBinding(exports, StrictEventEmitter_1, "StrictEventEmitter");
559
- }(lib$3));
563
+ }(lib$1));
560
564
 
561
- var lib$2 = {};
565
+ var lib = {};
562
566
 
563
567
  var until$1 = {};
564
568
 
@@ -580,9 +584,9 @@ until$1.until = async (promise) => {
580
584
  }
581
585
  };
582
586
 
583
- Object.defineProperty(lib$2, "__esModule", { value: true });
584
- var until_1$1 = until$1;
585
- var until = lib$2.until = until_1$1.until;
587
+ Object.defineProperty(lib, "__esModule", { value: true });
588
+ var until_1 = until$1;
589
+ var until = lib.until = until_1.until;
586
590
 
587
591
  /**
588
592
  * Attempts to resolve a Service Worker instance from a given registration,
@@ -613,7 +617,7 @@ function getAbsoluteWorkerUrl(relativeUrl) {
613
617
  * Returns an active Service Worker instance.
614
618
  * When not found, registers a new Service Worker.
615
619
  */
616
- const getWorkerInstance = (url, options = {}, findWorker) => __awaiter$3(void 0, void 0, void 0, function* () {
620
+ const getWorkerInstance = (url, options = {}, findWorker) => __awaiter(void 0, void 0, void 0, function* () {
617
621
  // Resolve the absolute Service Worker URL.
618
622
  const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);
619
623
  const mockRegistrations = yield navigator.serviceWorker
@@ -639,7 +643,7 @@ const getWorkerInstance = (url, options = {}, findWorker) => __awaiter$3(void 0,
639
643
  });
640
644
  }
641
645
  // When the Service Worker wasn't found, register it anew and return the reference.
642
- const [error, instance] = yield until(() => __awaiter$3(void 0, void 0, void 0, function* () {
646
+ const [error, instance] = yield until(() => __awaiter(void 0, void 0, void 0, function* () {
643
647
  const registration = yield navigator.serviceWorker.register(url, options);
644
648
  return [
645
649
  // Compare existing worker registration by its worker URL,
@@ -686,7 +690,7 @@ function printStartMessage(args = {}) {
686
690
  * Signals the worker to enable the interception of requests.
687
691
  */
688
692
  function enableMocking(context, options) {
689
- return __awaiter$3(this, void 0, void 0, function* () {
693
+ return __awaiter(this, void 0, void 0, function* () {
690
694
  context.workerChannel.send('MOCK_ACTIVATE');
691
695
  return context.events.once('MOCKING_ENABLED').then(() => {
692
696
  printStartMessage({ quiet: options.quiet });
@@ -712,379 +716,6 @@ const createBroadcastChannel = (event) => {
712
716
  };
713
717
  };
714
718
 
715
- var lib$1 = {};
716
-
717
- var CookieStore = {};
718
-
719
- var setCookie = {exports: {}};
720
-
721
- var defaultParseOptions = {
722
- decodeValues: true,
723
- map: false,
724
- silent: false,
725
- };
726
-
727
- function isNonEmptyString(str) {
728
- return typeof str === "string" && !!str.trim();
729
- }
730
-
731
- function parseString(setCookieValue, options) {
732
- var parts = setCookieValue.split(";").filter(isNonEmptyString);
733
- var nameValue = parts.shift().split("=");
734
- var name = nameValue.shift();
735
- var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part
736
-
737
- options = options
738
- ? Object.assign({}, defaultParseOptions, options)
739
- : defaultParseOptions;
740
-
741
- try {
742
- value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
743
- } catch (e) {
744
- console.error(
745
- "set-cookie-parser encountered an error while decoding a cookie with value '" +
746
- value +
747
- "'. Set options.decodeValues to false to disable this feature.",
748
- e
749
- );
750
- }
751
-
752
- var cookie = {
753
- name: name, // grab everything before the first =
754
- value: value,
755
- };
756
-
757
- parts.forEach(function (part) {
758
- var sides = part.split("=");
759
- var key = sides.shift().trimLeft().toLowerCase();
760
- var value = sides.join("=");
761
- if (key === "expires") {
762
- cookie.expires = new Date(value);
763
- } else if (key === "max-age") {
764
- cookie.maxAge = parseInt(value, 10);
765
- } else if (key === "secure") {
766
- cookie.secure = true;
767
- } else if (key === "httponly") {
768
- cookie.httpOnly = true;
769
- } else if (key === "samesite") {
770
- cookie.sameSite = value;
771
- } else {
772
- cookie[key] = value;
773
- }
774
- });
775
-
776
- return cookie;
777
- }
778
-
779
- function parse$1(input, options) {
780
- options = options
781
- ? Object.assign({}, defaultParseOptions, options)
782
- : defaultParseOptions;
783
-
784
- if (!input) {
785
- if (!options.map) {
786
- return [];
787
- } else {
788
- return {};
789
- }
790
- }
791
-
792
- if (input.headers && input.headers["set-cookie"]) {
793
- // fast-path for node.js (which automatically normalizes header names to lower-case
794
- input = input.headers["set-cookie"];
795
- } else if (input.headers) {
796
- // slow-path for other environments - see #25
797
- var sch =
798
- input.headers[
799
- Object.keys(input.headers).find(function (key) {
800
- return key.toLowerCase() === "set-cookie";
801
- })
802
- ];
803
- // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
804
- if (!sch && input.headers.cookie && !options.silent) {
805
- console.warn(
806
- "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
807
- );
808
- }
809
- input = sch;
810
- }
811
- if (!Array.isArray(input)) {
812
- input = [input];
813
- }
814
-
815
- options = options
816
- ? Object.assign({}, defaultParseOptions, options)
817
- : defaultParseOptions;
818
-
819
- if (!options.map) {
820
- return input.filter(isNonEmptyString).map(function (str) {
821
- return parseString(str, options);
822
- });
823
- } else {
824
- var cookies = {};
825
- return input.filter(isNonEmptyString).reduce(function (cookies, str) {
826
- var cookie = parseString(str, options);
827
- cookies[cookie.name] = cookie;
828
- return cookies;
829
- }, cookies);
830
- }
831
- }
832
-
833
- /*
834
- Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
835
- that are within a single set-cookie field-value, such as in the Expires portion.
836
-
837
- This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
838
- Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
839
- React Native's fetch does this for *every* header, including set-cookie.
840
-
841
- Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
842
- Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
843
- */
844
- function splitCookiesString(cookiesString) {
845
- if (Array.isArray(cookiesString)) {
846
- return cookiesString;
847
- }
848
- if (typeof cookiesString !== "string") {
849
- return [];
850
- }
851
-
852
- var cookiesStrings = [];
853
- var pos = 0;
854
- var start;
855
- var ch;
856
- var lastComma;
857
- var nextStart;
858
- var cookiesSeparatorFound;
859
-
860
- function skipWhitespace() {
861
- while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
862
- pos += 1;
863
- }
864
- return pos < cookiesString.length;
865
- }
866
-
867
- function notSpecialChar() {
868
- ch = cookiesString.charAt(pos);
869
-
870
- return ch !== "=" && ch !== ";" && ch !== ",";
871
- }
872
-
873
- while (pos < cookiesString.length) {
874
- start = pos;
875
- cookiesSeparatorFound = false;
876
-
877
- while (skipWhitespace()) {
878
- ch = cookiesString.charAt(pos);
879
- if (ch === ",") {
880
- // ',' is a cookie separator if we have later first '=', not ';' or ','
881
- lastComma = pos;
882
- pos += 1;
883
-
884
- skipWhitespace();
885
- nextStart = pos;
886
-
887
- while (pos < cookiesString.length && notSpecialChar()) {
888
- pos += 1;
889
- }
890
-
891
- // currently special character
892
- if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
893
- // we found cookies separator
894
- cookiesSeparatorFound = true;
895
- // pos is inside the next cookie, so back up and return it.
896
- pos = nextStart;
897
- cookiesStrings.push(cookiesString.substring(start, lastComma));
898
- start = pos;
899
- } else {
900
- // in param ',' or param separator ';',
901
- // we continue from that comma
902
- pos = lastComma + 1;
903
- }
904
- } else {
905
- pos += 1;
906
- }
907
- }
908
-
909
- if (!cookiesSeparatorFound || pos >= cookiesString.length) {
910
- cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
911
- }
912
- }
913
-
914
- return cookiesStrings;
915
- }
916
-
917
- setCookie.exports = parse$1;
918
- setCookie.exports.parse = parse$1;
919
- setCookie.exports.parseString = parseString;
920
- setCookie.exports.splitCookiesString = splitCookiesString;
921
-
922
- (function (exports) {
923
- var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
924
- var t = {};
925
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
926
- t[p] = s[p];
927
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
928
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
929
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
930
- t[p[i]] = s[p[i]];
931
- }
932
- return t;
933
- };
934
- Object.defineProperty(exports, "__esModule", { value: true });
935
- exports.PERSISTENCY_KEY = void 0;
936
- const set_cookie_parser_1 = setCookie.exports;
937
- exports.PERSISTENCY_KEY = 'MSW_COOKIE_STORE';
938
- const SUPPORTS_LOCAL_STORAGE = typeof localStorage !== 'undefined';
939
- class CookieStore {
940
- constructor() {
941
- this.store = new Map();
942
- }
943
- /**
944
- * Sets the given request cookies into the store.
945
- * Respects the `request.credentials` policy.
946
- */
947
- add(request, response) {
948
- if (request.credentials === 'omit') {
949
- return;
950
- }
951
- const requestUrl = new URL(request.url);
952
- const responseCookies = response.headers.get('set-cookie');
953
- if (!responseCookies) {
954
- return;
955
- }
956
- const now = Date.now();
957
- const parsedResponseCookies = set_cookie_parser_1.parse(responseCookies).map((_a) => {
958
- var { maxAge } = _a, cookie = __rest(_a, ["maxAge"]);
959
- return (Object.assign(Object.assign({}, cookie), { expires: maxAge === undefined ? cookie.expires : new Date(now + maxAge * 1000), maxAge }));
960
- });
961
- const prevCookies = this.store.get(requestUrl.origin) || new Map();
962
- parsedResponseCookies.forEach((cookie) => {
963
- this.store.set(requestUrl.origin, prevCookies.set(cookie.name, cookie));
964
- });
965
- }
966
- /**
967
- * Returns cookies relevant to the given request
968
- * and its `request.credentials` policy.
969
- */
970
- get(request) {
971
- this.deleteExpiredCookies();
972
- const requestUrl = new URL(request.url);
973
- const originCookies = this.store.get(requestUrl.origin) || new Map();
974
- switch (request.credentials) {
975
- case 'include': {
976
- const documentCookies = set_cookie_parser_1.parse(document.cookie);
977
- documentCookies.forEach((cookie) => {
978
- originCookies.set(cookie.name, cookie);
979
- });
980
- return originCookies;
981
- }
982
- case 'same-origin': {
983
- return originCookies;
984
- }
985
- default:
986
- return new Map();
987
- }
988
- }
989
- /**
990
- * Returns a collection of all stored cookies.
991
- */
992
- getAll() {
993
- this.deleteExpiredCookies();
994
- return this.store;
995
- }
996
- /**
997
- * Deletes all cookies associated with the given request.
998
- */
999
- deleteAll(request) {
1000
- const requestUrl = new URL(request.url);
1001
- this.store.delete(requestUrl.origin);
1002
- }
1003
- /**
1004
- * Clears the entire cookie store.
1005
- */
1006
- clear() {
1007
- this.store.clear();
1008
- }
1009
- /**
1010
- * Hydrates the virtual cookie store from the `localStorage` if defined.
1011
- */
1012
- hydrate() {
1013
- if (!SUPPORTS_LOCAL_STORAGE) {
1014
- return;
1015
- }
1016
- const persistedCookies = localStorage.getItem(exports.PERSISTENCY_KEY);
1017
- if (persistedCookies) {
1018
- try {
1019
- const parsedCookies = JSON.parse(persistedCookies);
1020
- parsedCookies.forEach(([origin, cookies]) => {
1021
- this.store.set(origin, new Map(cookies.map((_a) => {
1022
- var [token, _b] = _a, { expires } = _b, cookie = __rest(_b, ["expires"]);
1023
- return [
1024
- token,
1025
- expires === undefined
1026
- ? cookie
1027
- : Object.assign(Object.assign({}, cookie), { expires: new Date(expires) }),
1028
- ];
1029
- })));
1030
- });
1031
- }
1032
- catch (error) {
1033
- console.warn(`
1034
- [virtual-cookie] Failed to parse a stored cookie from the localStorage (key "${exports.PERSISTENCY_KEY}").
1035
-
1036
- Stored value:
1037
- ${localStorage.getItem(exports.PERSISTENCY_KEY)}
1038
-
1039
- Thrown exception:
1040
- ${error}
1041
-
1042
- Invalid value has been removed from localStorage to prevent subsequent failed parsing attempts.`);
1043
- localStorage.removeItem(exports.PERSISTENCY_KEY);
1044
- }
1045
- }
1046
- }
1047
- /**
1048
- * Persists the current virtual cookies into the `localStorage` if defined,
1049
- * so they are available on the next page load.
1050
- */
1051
- persist() {
1052
- if (!SUPPORTS_LOCAL_STORAGE) {
1053
- return;
1054
- }
1055
- const serializedCookies = Array.from(this.store.entries()).map(([origin, cookies]) => {
1056
- return [origin, Array.from(cookies.entries())];
1057
- });
1058
- localStorage.setItem(exports.PERSISTENCY_KEY, JSON.stringify(serializedCookies));
1059
- }
1060
- deleteExpiredCookies() {
1061
- const now = Date.now();
1062
- this.store.forEach((originCookies, origin) => {
1063
- originCookies.forEach(({ expires, name }) => {
1064
- if (expires !== undefined && expires.getTime() <= now) {
1065
- originCookies.delete(name);
1066
- }
1067
- });
1068
- if (originCookies.size === 0) {
1069
- this.store.delete(origin);
1070
- }
1071
- });
1072
- }
1073
- }
1074
- exports.default = new CookieStore();
1075
- }(CookieStore));
1076
-
1077
- (function (exports) {
1078
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
1079
- return (mod && mod.__esModule) ? mod : { "default": mod };
1080
- };
1081
- Object.defineProperty(exports, "__esModule", { value: true });
1082
- exports.PERSISTENCY_KEY = exports.store = void 0;
1083
- var CookieStore_1 = CookieStore;
1084
- Object.defineProperty(exports, "store", { enumerable: true, get: function () { return __importDefault(CookieStore_1).default; } });
1085
- Object.defineProperty(exports, "PERSISTENCY_KEY", { enumerable: true, get: function () { return CookieStore_1.PERSISTENCY_KEY; } });
1086
- }(lib$1));
1087
-
1088
719
  function getAllCookies() {
1089
720
  return parse_1(document.cookie);
1090
721
  }
@@ -1095,7 +726,7 @@ function getRequestCookies(request) {
1095
726
  /**
1096
727
  * @note No cookies persist on the document in Node.js: no document.
1097
728
  */
1098
- if (typeof location === 'undefined') {
729
+ if (typeof document === 'undefined' || typeof location === 'undefined') {
1099
730
  return {};
1100
731
  }
1101
732
  switch (request.credentials) {
@@ -1116,8 +747,8 @@ function getRequestCookies(request) {
1116
747
 
1117
748
  function setRequestCookies(request) {
1118
749
  var _a;
1119
- lib$1.store.hydrate();
1120
- request.cookies = Object.assign(Object.assign({}, getRequestCookies(request)), Array.from((_a = lib$1.store.get(Object.assign(Object.assign({}, request), { url: request.url.toString() }))) === null || _a === void 0 ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => Object.assign(cookies, { [name]: value }), {}));
750
+ store.hydrate();
751
+ request.cookies = Object.assign(Object.assign({}, getRequestCookies(request)), Array.from((_a = store.get(Object.assign(Object.assign({}, request), { url: request.url.toString() }))) === null || _a === void 0 ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => Object.assign(cookies, { [name]: value }), {}));
1121
752
  request.headers.set('cookie', Object.entries(request.cookies)
1122
753
  .map(([name, value]) => `${name}=${value}`)
1123
754
  .join('; '));
@@ -1157,7 +788,7 @@ function parseWorkerRequest(rawRequest) {
1157
788
  destination: rawRequest.destination,
1158
789
  body: pruneGetRequestBody(rawRequest),
1159
790
  bodyUsed: rawRequest.bodyUsed,
1160
- headers: new lib$4.Headers(rawRequest.headers),
791
+ headers: new lib$2.Headers(rawRequest.headers),
1161
792
  };
1162
793
  // Set document cookies on the request.
1163
794
  setRequestCookies(request);
@@ -1169,7 +800,7 @@ function parseWorkerRequest(rawRequest) {
1169
800
  /**
1170
801
  * Returns a mocked response for a given request using following request handlers.
1171
802
  */
1172
- const getResponse = (request, handlers, resolutionContext) => __awaiter$3(void 0, void 0, void 0, function* () {
803
+ const getResponse = (request, handlers, resolutionContext) => __awaiter(void 0, void 0, void 0, function* () {
1173
804
  const relevantHandlers = handlers.filter((handler) => {
1174
805
  return handler.test(request, resolutionContext);
1175
806
  });
@@ -1179,7 +810,7 @@ const getResponse = (request, handlers, resolutionContext) => __awaiter$3(void 0
1179
810
  response: undefined,
1180
811
  };
1181
812
  }
1182
- const result = yield relevantHandlers.reduce((executionResult, handler) => __awaiter$3(void 0, void 0, void 0, function* () {
813
+ const result = yield relevantHandlers.reduce((executionResult, handler) => __awaiter(void 0, void 0, void 0, function* () {
1183
814
  const previousResults = yield executionResult;
1184
815
  if (!!(previousResults === null || previousResults === void 0 ? void 0 : previousResults.response)) {
1185
816
  return executionResult;
@@ -1339,10 +970,10 @@ function groupHandlersByType(handlers) {
1339
970
  graphql: [],
1340
971
  });
1341
972
  }
1342
- function getScoreForRestHandler() {
973
+ function getRestHandlerScore() {
1343
974
  return (request, handler) => {
1344
975
  const { path, method } = handler.info;
1345
- if (path instanceof RegExp) {
976
+ if (path instanceof RegExp || method instanceof RegExp) {
1346
977
  return Infinity;
1347
978
  }
1348
979
  const hasSameMethod = isStringEqual(request.method, method);
@@ -1353,12 +984,15 @@ function getScoreForRestHandler() {
1353
984
  return score - methodScoreDelta;
1354
985
  };
1355
986
  }
1356
- function getScoreForGraphQLHandler(parsedQuery) {
987
+ function getGraphQLHandlerScore(parsedQuery) {
1357
988
  return (_, handler) => {
1358
989
  if (typeof parsedQuery.operationName === 'undefined') {
1359
990
  return Infinity;
1360
991
  }
1361
992
  const { operationType, operationName } = handler.info;
993
+ if (typeof operationName !== 'string') {
994
+ return Infinity;
995
+ }
1362
996
  const hasSameOperationType = parsedQuery.operationType === operationType;
1363
997
  // Always treat a handler with the same operation type as a more similar one.
1364
998
  const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
@@ -1368,16 +1002,12 @@ function getScoreForGraphQLHandler(parsedQuery) {
1368
1002
  }
1369
1003
  function getSuggestedHandler(request, handlers, getScore) {
1370
1004
  const suggestedHandlers = handlers
1371
- .reduce((acc, handler) => {
1005
+ .reduce((suggestions, handler) => {
1372
1006
  const score = getScore(request, handler);
1373
- return acc.concat([[score, handler]]);
1007
+ return suggestions.concat([[score, handler]]);
1374
1008
  }, [])
1375
- .sort(([leftScore], [rightScore]) => {
1376
- return leftScore - rightScore;
1377
- })
1378
- .filter(([score]) => {
1379
- return score <= MAX_MATCH_SCORE;
1380
- })
1009
+ .sort(([leftScore], [rightScore]) => leftScore - rightScore)
1010
+ .filter(([score]) => score <= MAX_MATCH_SCORE)
1381
1011
  .slice(0, MAX_SUGGESTION_COUNT)
1382
1012
  .map(([, handler]) => handler);
1383
1013
  return suggestedHandlers;
@@ -1407,8 +1037,8 @@ function onUnhandledRequest(request, handlers, strategy = 'warn') {
1407
1037
  ? handlerGroups.graphql
1408
1038
  : handlerGroups.rest;
1409
1039
  const suggestedHandlers = getSuggestedHandler(request, relevantHandlers, parsedGraphQLQuery
1410
- ? getScoreForGraphQLHandler(parsedGraphQLQuery)
1411
- : getScoreForRestHandler());
1040
+ ? getGraphQLHandlerScore(parsedGraphQLQuery)
1041
+ : getRestHandlerScore());
1412
1042
  const handlerSuggestion = suggestedHandlers.length > 0
1413
1043
  ? getSuggestedHandlersMessage(suggestedHandlers)
1414
1044
  : '';
@@ -1428,8 +1058,10 @@ Read more: https://mswjs.io/docs/getting-started/mocks\
1428
1058
  const message = messageTemplate.join('\n\n');
1429
1059
  switch (strategy) {
1430
1060
  case 'error': {
1061
+ // Print a developer-friendly error.
1431
1062
  devUtils.error('Error: %s', message);
1432
- break;
1063
+ // Throw an exception to halt request processing and not perform the original request.
1064
+ throw new Error(devUtils.formatMessage('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'));
1433
1065
  }
1434
1066
  case 'warn': {
1435
1067
  devUtils.warn('Warning: %s', message);
@@ -1443,13 +1075,13 @@ Read more: https://mswjs.io/docs/getting-started/mocks\
1443
1075
  }
1444
1076
 
1445
1077
  function readResponseCookies(request, response) {
1446
- lib$1.store.add(Object.assign(Object.assign({}, request), { url: request.url.toString() }), response);
1447
- lib$1.store.persist();
1078
+ store.add(Object.assign(Object.assign({}, request), { url: request.url.toString() }), response);
1079
+ store.persist();
1448
1080
  }
1449
1081
 
1450
1082
  function handleRequest(request, handlers, options, emitter, handleRequestOptions) {
1451
1083
  var _a, _b, _c;
1452
- return __awaiter$3(this, void 0, void 0, function* () {
1084
+ return __awaiter(this, void 0, void 0, function* () {
1453
1085
  emitter.emit('request:start', request);
1454
1086
  // Perform bypassed requests (i.e. issued via "ctx.fetch") as-is.
1455
1087
  if (request.headers.get('x-msw-bypass')) {
@@ -1472,7 +1104,12 @@ function handleRequest(request, handlers, options, emitter, handleRequestOptions
1472
1104
  // When the handled request returned no mocked response, warn the developer,
1473
1105
  // as it may be an oversight on their part. Perform the request as-is.
1474
1106
  if (!response) {
1475
- devUtils.warn('Expected a mocking resolver function to return a mocked response Object, but got: %s. Original response is going to be used instead.', response);
1107
+ devUtils.warn(`\
1108
+ Expected response resolver to return a mocked response Object, but got %s. The original response is going to be used instead.\
1109
+ \n
1110
+ \u2022 %s
1111
+ %s\
1112
+ `, response, handler.info.header, handler.info.callFrame);
1476
1113
  emitter.emit('request:end', request);
1477
1114
  (_c = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onBypassResponse) === null || _c === void 0 ? void 0 : _c.call(handleRequestOptions, request);
1478
1115
  return;
@@ -1497,7 +1134,7 @@ function handleRequest(request, handlers, options, emitter, handleRequestOptions
1497
1134
  }
1498
1135
 
1499
1136
  const createRequestListener = (context, options) => {
1500
- return (event, message) => __awaiter$3(void 0, void 0, void 0, function* () {
1137
+ return (event, message) => __awaiter(void 0, void 0, void 0, function* () {
1501
1138
  const channel = createBroadcastChannel(event);
1502
1139
  try {
1503
1140
  const request = parseWorkerRequest(message.payload);
@@ -1553,14 +1190,14 @@ const createRequestListener = (context, options) => {
1553
1190
  };
1554
1191
 
1555
1192
  function requestIntegrityCheck(context, serviceWorker) {
1556
- return __awaiter$3(this, void 0, void 0, function* () {
1193
+ return __awaiter(this, void 0, void 0, function* () {
1557
1194
  // Signal Service Worker to report back its integrity
1558
1195
  context.workerChannel.send('INTEGRITY_CHECK_REQUEST');
1559
1196
  const { payload: actualChecksum } = yield context.events.once('INTEGRITY_CHECK_RESPONSE');
1560
1197
  // Compare the response from the Service Worker and the
1561
1198
  // global variable set by Rollup during the build.
1562
- if (actualChecksum !== "f0a916b13c8acc2b526a03a6d26df85f") {
1563
- throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"f0a916b13c8acc2b526a03a6d26df85f"}).`);
1199
+ if (actualChecksum !== "02f4ad4a2797f85668baf196e553d929") {
1200
+ throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"02f4ad4a2797f85668baf196e553d929"}).`);
1564
1201
  }
1565
1202
  return serviceWorker;
1566
1203
  });
@@ -1584,7 +1221,7 @@ function deferNetworkRequestsUntil(predicatePromise) {
1584
1221
  };
1585
1222
  // Defer any `fetch` requests until the Service Worker is ready.
1586
1223
  const originalFetch = window.fetch;
1587
- window.fetch = (...args) => __awaiter$3(this, void 0, void 0, function* () {
1224
+ window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {
1588
1225
  yield until(() => predicatePromise);
1589
1226
  window.fetch = originalFetch;
1590
1227
  return window.fetch(...args);
@@ -1629,7 +1266,7 @@ Cannot intercept requests on this page because it's outside of the worker's scop
1629
1266
 
1630
1267
  const createStartHandler = (context) => {
1631
1268
  return function start(options, customOptions) {
1632
- const startWorkerInstance = () => __awaiter$3(this, void 0, void 0, function* () {
1269
+ const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
1633
1270
  // Remove all previously existing event listeners.
1634
1271
  // This way none of the listeners persists between Fast refresh
1635
1272
  // of the application's code.
@@ -1709,16 +1346,14 @@ function printStopMessage(args = {}) {
1709
1346
  }
1710
1347
 
1711
1348
  const createStop = (context) => {
1712
- /**
1713
- * Signal the Service Worker to disable mocking for this client.
1714
- * Use this an an explicit way to stop the mocking, while preserving
1715
- * the worker-client relation. Does not affect the worker's lifecycle.
1716
- */
1717
1349
  return function stop() {
1718
1350
  var _a;
1351
+ /**
1352
+ * Signal the Service Worker to disable mocking for this client.
1353
+ * Use this an an explicit way to stop the mocking, while preserving
1354
+ * the worker-client relation. Does not affect the worker's lifecycle.
1355
+ */
1719
1356
  context.workerChannel.send('MOCK_DEACTIVATE');
1720
- context.events.removeAllListeners();
1721
- context.emitter.removeAllListeners();
1722
1357
  window.clearInterval(context.keepAliveInterval);
1723
1358
  printStopMessage({ quiet: (_a = context.startOptions) === null || _a === void 0 ? void 0 : _a.quiet });
1724
1359
  };
@@ -1762,3465 +1397,6 @@ function prepareStartHandler(handler, context) {
1762
1397
  };
1763
1398
  }
1764
1399
 
1765
- var lib = {};
1766
-
1767
- var createInterceptor$1 = {};
1768
-
1769
- Object.defineProperty(createInterceptor$1, "__esModule", { value: true });
1770
- createInterceptor$1.createInterceptor = void 0;
1771
- var strict_event_emitter_1$1 = lib$3;
1772
- function createInterceptor(options) {
1773
- var observer = new strict_event_emitter_1$1.StrictEventEmitter();
1774
- var cleanupFns = [];
1775
- return {
1776
- apply: function () {
1777
- cleanupFns = options.modules.map(function (interceptor) {
1778
- return interceptor(observer, options.resolver);
1779
- });
1780
- },
1781
- on: function (event, listener) {
1782
- observer.addListener(event, listener);
1783
- },
1784
- restore: function () {
1785
- observer.removeAllListeners();
1786
- if (cleanupFns.length === 0) {
1787
- throw new Error("Failed to restore patched modules: no patches found. Did you forget to run \".apply()\"?");
1788
- }
1789
- cleanupFns.forEach(function (restore) { return restore(); });
1790
- },
1791
- };
1792
- }
1793
- createInterceptor$1.createInterceptor = createInterceptor;
1794
-
1795
- var remote = {};
1796
-
1797
- var toIsoResponse$1 = {};
1798
-
1799
- Object.defineProperty(toIsoResponse$1, "__esModule", { value: true });
1800
- toIsoResponse$1.toIsoResponse = void 0;
1801
- var headers_utils_1$3 = lib$4;
1802
- /**
1803
- * Converts a given mocked response object into an isomorphic response.
1804
- */
1805
- function toIsoResponse(response) {
1806
- return {
1807
- status: response.status || 200,
1808
- statusText: response.statusText || 'OK',
1809
- headers: headers_utils_1$3.objectToHeaders(response.headers || {}),
1810
- body: response.body,
1811
- };
1812
- }
1813
- toIsoResponse$1.toIsoResponse = toIsoResponse;
1814
-
1815
- var __assign$1 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1816
- __assign$1 = Object.assign || function(t) {
1817
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1818
- s = arguments[i];
1819
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1820
- t[p] = s[p];
1821
- }
1822
- return t;
1823
- };
1824
- return __assign$1.apply(this, arguments);
1825
- };
1826
- var __awaiter$2 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
1827
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1828
- return new (P || (P = Promise))(function (resolve, reject) {
1829
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1830
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1831
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1832
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1833
- });
1834
- };
1835
- var __generator$2 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
1836
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1837
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1838
- function verb(n) { return function (v) { return step([n, v]); }; }
1839
- function step(op) {
1840
- if (f) throw new TypeError("Generator is already executing.");
1841
- while (_) try {
1842
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1843
- if (y = 0, t) op = [op[0] & 2, t.value];
1844
- switch (op[0]) {
1845
- case 0: case 1: t = op; break;
1846
- case 4: _.label++; return { value: op[1], done: false };
1847
- case 5: _.label++; y = op[1]; op = [0]; continue;
1848
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1849
- default:
1850
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1851
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1852
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1853
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1854
- if (t[2]) _.ops.pop();
1855
- _.trys.pop(); continue;
1856
- }
1857
- op = body.call(thisArg, _);
1858
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1859
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1860
- }
1861
- };
1862
- var __read$1 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
1863
- var m = typeof Symbol === "function" && o[Symbol.iterator];
1864
- if (!m) return o;
1865
- var i = m.call(o), r, ar = [], e;
1866
- try {
1867
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1868
- }
1869
- catch (error) { e = { error: error }; }
1870
- finally {
1871
- try {
1872
- if (r && !r.done && (m = i["return"])) m.call(i);
1873
- }
1874
- finally { if (e) throw e.error; }
1875
- }
1876
- return ar;
1877
- };
1878
- Object.defineProperty(remote, "__esModule", { value: true });
1879
- remote.createRemoteResolver = remote.createRemoteInterceptor = void 0;
1880
- var headers_utils_1$2 = lib$4;
1881
- var outvariant_1 = lib$5;
1882
- var strict_event_emitter_1 = lib$3;
1883
- var createInterceptor_1 = createInterceptor$1;
1884
- var toIsoResponse_1$2 = toIsoResponse$1;
1885
- function requestReviver(key, value) {
1886
- switch (key) {
1887
- case 'url':
1888
- return new URL(value);
1889
- case 'headers':
1890
- return new headers_utils_1$2.Headers(value);
1891
- default:
1892
- return value;
1893
- }
1894
- }
1895
- /**
1896
- * Creates a remote request interceptor that delegates
1897
- * the mocked response resolution to the parent process.
1898
- * The parent process must establish a remote resolver
1899
- * by calling `createRemoteResolver` function.
1900
- */
1901
- function createRemoteInterceptor(options) {
1902
- outvariant_1.invariant(process.connected, "Failed to create a remote interceptor: the current process (%s) does not have a parent. Please make sure you're spawning this process as a child process in order to use remote request interception.", process.pid);
1903
- if (typeof process.send === 'undefined') {
1904
- throw new Error("Failed to create a remote interceptor: the current process (" + process.pid + ") does not have the IPC enabled. Please make sure you're spawning this process with the \"ipc\" stdio value set:\n\nspawn('node', ['module.js'], { stdio: ['ipc'] })");
1905
- }
1906
- var handleParentMessage;
1907
- var interceptor = createInterceptor_1.createInterceptor(__assign$1(__assign$1({}, options), { resolver: function (request) {
1908
- var _a;
1909
- var serializedRequest = JSON.stringify(request);
1910
- (_a = process.send) === null || _a === void 0 ? void 0 : _a.call(process, "request:" + serializedRequest);
1911
- return new Promise(function (resolve) {
1912
- handleParentMessage = function (message) {
1913
- if (typeof message !== 'string') {
1914
- return;
1915
- }
1916
- if (message.startsWith("response:" + request.id)) {
1917
- var _a = __read$1(message.match(/^response:.+?:(.+)$/) || [], 2), responseString = _a[1];
1918
- if (!responseString) {
1919
- return resolve();
1920
- }
1921
- var mockedResponse = JSON.parse(responseString);
1922
- return resolve(mockedResponse);
1923
- }
1924
- };
1925
- process.addListener('message', handleParentMessage);
1926
- });
1927
- } }));
1928
- return __assign$1(__assign$1({}, interceptor), { restore: function () {
1929
- interceptor.restore();
1930
- process.removeListener('message', handleParentMessage);
1931
- } });
1932
- }
1933
- remote.createRemoteInterceptor = createRemoteInterceptor;
1934
- /**
1935
- * Creates a response resolver function attached to the given `ChildProcess`.
1936
- * The child process must establish a remote interceptor by calling `createRemoteInterceptor` function.
1937
- */
1938
- function createRemoteResolver(options) {
1939
- var _this = this;
1940
- var observer = new strict_event_emitter_1.StrictEventEmitter();
1941
- var handleChildMessage = function (message) { return __awaiter$2(_this, void 0, void 0, function () {
1942
- var _a, requestString, isoRequest_1, mockedResponse_1, serializedResponse;
1943
- return __generator$2(this, function (_b) {
1944
- switch (_b.label) {
1945
- case 0:
1946
- if (typeof message !== 'string') {
1947
- return [2 /*return*/];
1948
- }
1949
- if (!message.startsWith('request:')) return [3 /*break*/, 2];
1950
- _a = __read$1(message.match(/^request:(.+)$/) || [], 2), requestString = _a[1];
1951
- if (!requestString) {
1952
- return [2 /*return*/];
1953
- }
1954
- isoRequest_1 = JSON.parse(requestString, requestReviver);
1955
- observer.emit('request', isoRequest_1);
1956
- return [4 /*yield*/, options.resolver(isoRequest_1, undefined)
1957
- // Send the mocked response to the child process.
1958
- ];
1959
- case 1:
1960
- mockedResponse_1 = _b.sent();
1961
- serializedResponse = JSON.stringify(mockedResponse_1);
1962
- options.process.send("response:" + isoRequest_1.id + ":" + serializedResponse, function (error) {
1963
- if (error) {
1964
- return;
1965
- }
1966
- if (mockedResponse_1) {
1967
- // Emit an optimisting "response" event at this point,
1968
- // not to rely on the back-and-forth signaling for the sake of the event.
1969
- observer.emit('response', isoRequest_1, toIsoResponse_1$2.toIsoResponse(mockedResponse_1));
1970
- }
1971
- });
1972
- _b.label = 2;
1973
- case 2: return [2 /*return*/];
1974
- }
1975
- });
1976
- }); };
1977
- var cleanup = function () {
1978
- options.process.removeListener('message', handleChildMessage);
1979
- };
1980
- options.process.addListener('message', handleChildMessage);
1981
- options.process.addListener('disconnect', cleanup);
1982
- options.process.addListener('error', cleanup);
1983
- options.process.addListener('exit', cleanup);
1984
- return {
1985
- on: function (event, listener) {
1986
- observer.addListener(event, listener);
1987
- },
1988
- };
1989
- }
1990
- remote.createRemoteResolver = createRemoteResolver;
1991
-
1992
- (function (exports) {
1993
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
1994
- if (k2 === undefined) k2 = k;
1995
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
1996
- }) : (function(o, m, k, k2) {
1997
- if (k2 === undefined) k2 = k;
1998
- o[k2] = m[k];
1999
- }));
2000
- var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
2001
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
2002
- };
2003
- Object.defineProperty(exports, "__esModule", { value: true });
2004
- exports.getCleanUrl = void 0;
2005
- __exportStar(createInterceptor$1, exports);
2006
- __exportStar(remote, exports);
2007
- /* Utils */
2008
- var getCleanUrl_1 = getCleanUrl;
2009
- Object.defineProperty(exports, "getCleanUrl", { enumerable: true, get: function () { return getCleanUrl_1.getCleanUrl; } });
2010
-
2011
- }(lib));
2012
-
2013
- var fetch = {};
2014
-
2015
- var uuid = {};
2016
-
2017
- Object.defineProperty(uuid, "__esModule", { value: true });
2018
- uuid.uuidv4 = void 0;
2019
- function uuidv4$1() {
2020
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
2021
- var r = (Math.random() * 16) | 0;
2022
- var v = c == 'x' ? r : (r & 0x3) | 0x8;
2023
- return v.toString(16);
2024
- });
2025
- }
2026
- uuid.uuidv4 = uuidv4$1;
2027
-
2028
- var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2029
- __assign = Object.assign || function(t) {
2030
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2031
- s = arguments[i];
2032
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2033
- t[p] = s[p];
2034
- }
2035
- return t;
2036
- };
2037
- return __assign.apply(this, arguments);
2038
- };
2039
- var __awaiter$1 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2040
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2041
- return new (P || (P = Promise))(function (resolve, reject) {
2042
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2043
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2044
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2045
- step((generator = generator.apply(thisArg, _arguments || [])).next());
2046
- });
2047
- };
2048
- var __generator$1 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2049
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
2050
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2051
- function verb(n) { return function (v) { return step([n, v]); }; }
2052
- function step(op) {
2053
- if (f) throw new TypeError("Generator is already executing.");
2054
- while (_) try {
2055
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2056
- if (y = 0, t) op = [op[0] & 2, t.value];
2057
- switch (op[0]) {
2058
- case 0: case 1: t = op; break;
2059
- case 4: _.label++; return { value: op[1], done: false };
2060
- case 5: _.label++; y = op[1]; op = [0]; continue;
2061
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
2062
- default:
2063
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2064
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2065
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2066
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2067
- if (t[2]) _.ops.pop();
2068
- _.trys.pop(); continue;
2069
- }
2070
- op = body.call(thisArg, _);
2071
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2072
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2073
- }
2074
- };
2075
- Object.defineProperty(fetch, "__esModule", { value: true });
2076
- var interceptFetch_1 = fetch.interceptFetch = void 0;
2077
- var headers_utils_1$1 = lib$4;
2078
- var toIsoResponse_1$1 = toIsoResponse$1;
2079
- var uuid_1$1 = uuid;
2080
- var debug$1 = require$$3('fetch');
2081
- var interceptFetch = function (observer, resolver) {
2082
- var pureFetch = window.fetch;
2083
- debug$1('replacing "window.fetch"...');
2084
- window.fetch = function (input, init) { return __awaiter$1(void 0, void 0, void 0, function () {
2085
- var ref, url, method, isoRequest, response, isomorphicResponse;
2086
- var _a;
2087
- return __generator$1(this, function (_b) {
2088
- switch (_b.label) {
2089
- case 0:
2090
- ref = new Request(input, init);
2091
- url = typeof input === 'string' ? input : input.url;
2092
- method = (init === null || init === void 0 ? void 0 : init.method) || 'GET';
2093
- debug$1('[%s] %s', method, url);
2094
- _a = {
2095
- id: uuid_1$1.uuidv4(),
2096
- url: new URL(url, location.origin),
2097
- method: method,
2098
- headers: new headers_utils_1$1.Headers((init === null || init === void 0 ? void 0 : init.headers) || {})
2099
- };
2100
- return [4 /*yield*/, ref.text()];
2101
- case 1:
2102
- isoRequest = (_a.body = _b.sent(),
2103
- _a);
2104
- debug$1('isomorphic request', isoRequest);
2105
- observer.emit('request', isoRequest);
2106
- debug$1('awaiting for the mocked response...');
2107
- return [4 /*yield*/, resolver(isoRequest, ref)];
2108
- case 2:
2109
- response = _b.sent();
2110
- debug$1('mocked response', response);
2111
- if (response) {
2112
- isomorphicResponse = toIsoResponse_1$1.toIsoResponse(response);
2113
- debug$1('derived isomorphic response', isomorphicResponse);
2114
- observer.emit('response', isoRequest, isomorphicResponse);
2115
- return [2 /*return*/, new Response(response.body, __assign(__assign({}, isomorphicResponse), {
2116
- // `Response.headers` cannot be instantiated with the `Headers` polyfill.
2117
- // Apparently, it halts if the `Headers` class contains unknown properties
2118
- // (i.e. the internal `Headers.map`).
2119
- headers: headers_utils_1$1.flattenHeadersObject(response.headers || {}) }))];
2120
- }
2121
- debug$1('no mocked response found, bypassing...');
2122
- return [2 /*return*/, pureFetch(input, init).then(function (response) { return __awaiter$1(void 0, void 0, void 0, function () {
2123
- var _a, _b, _c;
2124
- return __generator$1(this, function (_d) {
2125
- switch (_d.label) {
2126
- case 0:
2127
- debug$1('original fetch performed', response);
2128
- _b = (_a = observer).emit;
2129
- _c = ['response',
2130
- isoRequest];
2131
- return [4 /*yield*/, normalizeFetchResponse(response)];
2132
- case 1:
2133
- _b.apply(_a, _c.concat([_d.sent()]));
2134
- return [2 /*return*/, response];
2135
- }
2136
- });
2137
- }); })];
2138
- }
2139
- });
2140
- }); };
2141
- return function () {
2142
- debug$1('restoring modules...');
2143
- window.fetch = pureFetch;
2144
- };
2145
- };
2146
- interceptFetch_1 = fetch.interceptFetch = interceptFetch;
2147
- function normalizeFetchResponse(response) {
2148
- return __awaiter$1(this, void 0, void 0, function () {
2149
- var _a;
2150
- return __generator$1(this, function (_b) {
2151
- switch (_b.label) {
2152
- case 0:
2153
- _a = {
2154
- status: response.status,
2155
- statusText: response.statusText,
2156
- headers: headers_utils_1$1.objectToHeaders(headers_utils_1$1.headersToObject(response.headers))
2157
- };
2158
- return [4 /*yield*/, response.text()];
2159
- case 1: return [2 /*return*/, (_a.body = _b.sent(),
2160
- _a)];
2161
- }
2162
- });
2163
- });
2164
- }
2165
-
2166
- var XMLHttpRequest = {};
2167
-
2168
- var XMLHttpRequestOverride = {};
2169
-
2170
- var domParser = {};
2171
-
2172
- var entities = {};
2173
-
2174
- entities.entityMap = {
2175
- lt: '<',
2176
- gt: '>',
2177
- amp: '&',
2178
- quot: '"',
2179
- apos: "'",
2180
- Agrave: "À",
2181
- Aacute: "Á",
2182
- Acirc: "Â",
2183
- Atilde: "Ã",
2184
- Auml: "Ä",
2185
- Aring: "Å",
2186
- AElig: "Æ",
2187
- Ccedil: "Ç",
2188
- Egrave: "È",
2189
- Eacute: "É",
2190
- Ecirc: "Ê",
2191
- Euml: "Ë",
2192
- Igrave: "Ì",
2193
- Iacute: "Í",
2194
- Icirc: "Î",
2195
- Iuml: "Ï",
2196
- ETH: "Ð",
2197
- Ntilde: "Ñ",
2198
- Ograve: "Ò",
2199
- Oacute: "Ó",
2200
- Ocirc: "Ô",
2201
- Otilde: "Õ",
2202
- Ouml: "Ö",
2203
- Oslash: "Ø",
2204
- Ugrave: "Ù",
2205
- Uacute: "Ú",
2206
- Ucirc: "Û",
2207
- Uuml: "Ü",
2208
- Yacute: "Ý",
2209
- THORN: "Þ",
2210
- szlig: "ß",
2211
- agrave: "à",
2212
- aacute: "á",
2213
- acirc: "â",
2214
- atilde: "ã",
2215
- auml: "ä",
2216
- aring: "å",
2217
- aelig: "æ",
2218
- ccedil: "ç",
2219
- egrave: "è",
2220
- eacute: "é",
2221
- ecirc: "ê",
2222
- euml: "ë",
2223
- igrave: "ì",
2224
- iacute: "í",
2225
- icirc: "î",
2226
- iuml: "ï",
2227
- eth: "ð",
2228
- ntilde: "ñ",
2229
- ograve: "ò",
2230
- oacute: "ó",
2231
- ocirc: "ô",
2232
- otilde: "õ",
2233
- ouml: "ö",
2234
- oslash: "ø",
2235
- ugrave: "ù",
2236
- uacute: "ú",
2237
- ucirc: "û",
2238
- uuml: "ü",
2239
- yacute: "ý",
2240
- thorn: "þ",
2241
- yuml: "ÿ",
2242
- nbsp: "\u00a0",
2243
- iexcl: "¡",
2244
- cent: "¢",
2245
- pound: "£",
2246
- curren: "¤",
2247
- yen: "¥",
2248
- brvbar: "¦",
2249
- sect: "§",
2250
- uml: "¨",
2251
- copy: "©",
2252
- ordf: "ª",
2253
- laquo: "«",
2254
- not: "¬",
2255
- shy: "­­",
2256
- reg: "®",
2257
- macr: "¯",
2258
- deg: "°",
2259
- plusmn: "±",
2260
- sup2: "²",
2261
- sup3: "³",
2262
- acute: "´",
2263
- micro: "µ",
2264
- para: "¶",
2265
- middot: "·",
2266
- cedil: "¸",
2267
- sup1: "¹",
2268
- ordm: "º",
2269
- raquo: "»",
2270
- frac14: "¼",
2271
- frac12: "½",
2272
- frac34: "¾",
2273
- iquest: "¿",
2274
- times: "×",
2275
- divide: "÷",
2276
- forall: "∀",
2277
- part: "∂",
2278
- exist: "∃",
2279
- empty: "∅",
2280
- nabla: "∇",
2281
- isin: "∈",
2282
- notin: "∉",
2283
- ni: "∋",
2284
- prod: "∏",
2285
- sum: "∑",
2286
- minus: "−",
2287
- lowast: "∗",
2288
- radic: "√",
2289
- prop: "∝",
2290
- infin: "∞",
2291
- ang: "∠",
2292
- and: "∧",
2293
- or: "∨",
2294
- cap: "∩",
2295
- cup: "∪",
2296
- 'int': "∫",
2297
- there4: "∴",
2298
- sim: "∼",
2299
- cong: "≅",
2300
- asymp: "≈",
2301
- ne: "≠",
2302
- equiv: "≡",
2303
- le: "≤",
2304
- ge: "≥",
2305
- sub: "⊂",
2306
- sup: "⊃",
2307
- nsub: "⊄",
2308
- sube: "⊆",
2309
- supe: "⊇",
2310
- oplus: "⊕",
2311
- otimes: "⊗",
2312
- perp: "⊥",
2313
- sdot: "⋅",
2314
- Alpha: "Α",
2315
- Beta: "Β",
2316
- Gamma: "Γ",
2317
- Delta: "Δ",
2318
- Epsilon: "Ε",
2319
- Zeta: "Ζ",
2320
- Eta: "Η",
2321
- Theta: "Θ",
2322
- Iota: "Ι",
2323
- Kappa: "Κ",
2324
- Lambda: "Λ",
2325
- Mu: "Μ",
2326
- Nu: "Ν",
2327
- Xi: "Ξ",
2328
- Omicron: "Ο",
2329
- Pi: "Π",
2330
- Rho: "Ρ",
2331
- Sigma: "Σ",
2332
- Tau: "Τ",
2333
- Upsilon: "Υ",
2334
- Phi: "Φ",
2335
- Chi: "Χ",
2336
- Psi: "Ψ",
2337
- Omega: "Ω",
2338
- alpha: "α",
2339
- beta: "β",
2340
- gamma: "γ",
2341
- delta: "δ",
2342
- epsilon: "ε",
2343
- zeta: "ζ",
2344
- eta: "η",
2345
- theta: "θ",
2346
- iota: "ι",
2347
- kappa: "κ",
2348
- lambda: "λ",
2349
- mu: "μ",
2350
- nu: "ν",
2351
- xi: "ξ",
2352
- omicron: "ο",
2353
- pi: "π",
2354
- rho: "ρ",
2355
- sigmaf: "ς",
2356
- sigma: "σ",
2357
- tau: "τ",
2358
- upsilon: "υ",
2359
- phi: "φ",
2360
- chi: "χ",
2361
- psi: "ψ",
2362
- omega: "ω",
2363
- thetasym: "ϑ",
2364
- upsih: "ϒ",
2365
- piv: "ϖ",
2366
- OElig: "Œ",
2367
- oelig: "œ",
2368
- Scaron: "Š",
2369
- scaron: "š",
2370
- Yuml: "Ÿ",
2371
- fnof: "ƒ",
2372
- circ: "ˆ",
2373
- tilde: "˜",
2374
- ensp: " ",
2375
- emsp: " ",
2376
- thinsp: " ",
2377
- zwnj: "‌",
2378
- zwj: "‍",
2379
- lrm: "‎",
2380
- rlm: "‏",
2381
- ndash: "–",
2382
- mdash: "—",
2383
- lsquo: "‘",
2384
- rsquo: "’",
2385
- sbquo: "‚",
2386
- ldquo: "“",
2387
- rdquo: "”",
2388
- bdquo: "„",
2389
- dagger: "†",
2390
- Dagger: "‡",
2391
- bull: "•",
2392
- hellip: "…",
2393
- permil: "‰",
2394
- prime: "′",
2395
- Prime: "″",
2396
- lsaquo: "‹",
2397
- rsaquo: "›",
2398
- oline: "‾",
2399
- euro: "€",
2400
- trade: "™",
2401
- larr: "←",
2402
- uarr: "↑",
2403
- rarr: "→",
2404
- darr: "↓",
2405
- harr: "↔",
2406
- crarr: "↵",
2407
- lceil: "⌈",
2408
- rceil: "⌉",
2409
- lfloor: "⌊",
2410
- rfloor: "⌋",
2411
- loz: "◊",
2412
- spades: "♠",
2413
- clubs: "♣",
2414
- hearts: "♥",
2415
- diams: "♦"
2416
- };
2417
-
2418
- var sax$1 = {};
2419
-
2420
- //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
2421
- //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
2422
- //[5] Name ::= NameStartChar (NameChar)*
2423
- var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;//\u10000-\uEFFFF
2424
- var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
2425
- var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
2426
- //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
2427
- //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
2428
-
2429
- //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
2430
- //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
2431
- var S_TAG = 0;//tag name offerring
2432
- var S_ATTR = 1;//attr name offerring
2433
- var S_ATTR_SPACE=2;//attr name end and space offer
2434
- var S_EQ = 3;//=space?
2435
- var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
2436
- var S_ATTR_END = 5;//attr value end and no space(quot end)
2437
- var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
2438
- var S_TAG_CLOSE = 7;//closed el<el />
2439
-
2440
- /**
2441
- * Creates an error that will not be caught by XMLReader aka the SAX parser.
2442
- *
2443
- * @param {string} message
2444
- * @param {any?} locator Optional, can provide details about the location in the source
2445
- * @constructor
2446
- */
2447
- function ParseError$1(message, locator) {
2448
- this.message = message;
2449
- this.locator = locator;
2450
- if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError$1);
2451
- }
2452
- ParseError$1.prototype = new Error();
2453
- ParseError$1.prototype.name = ParseError$1.name;
2454
-
2455
- function XMLReader$1(){
2456
-
2457
- }
2458
-
2459
- XMLReader$1.prototype = {
2460
- parse:function(source,defaultNSMap,entityMap){
2461
- var domBuilder = this.domBuilder;
2462
- domBuilder.startDocument();
2463
- _copy(defaultNSMap ,defaultNSMap = {});
2464
- parse(source,defaultNSMap,entityMap,
2465
- domBuilder,this.errorHandler);
2466
- domBuilder.endDocument();
2467
- }
2468
- };
2469
- function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
2470
- function fixedFromCharCode(code) {
2471
- // String.prototype.fromCharCode does not supports
2472
- // > 2 bytes unicode chars directly
2473
- if (code > 0xffff) {
2474
- code -= 0x10000;
2475
- var surrogate1 = 0xd800 + (code >> 10)
2476
- , surrogate2 = 0xdc00 + (code & 0x3ff);
2477
-
2478
- return String.fromCharCode(surrogate1, surrogate2);
2479
- } else {
2480
- return String.fromCharCode(code);
2481
- }
2482
- }
2483
- function entityReplacer(a){
2484
- var k = a.slice(1,-1);
2485
- if(k in entityMap){
2486
- return entityMap[k];
2487
- }else if(k.charAt(0) === '#'){
2488
- return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
2489
- }else {
2490
- errorHandler.error('entity not found:'+a);
2491
- return a;
2492
- }
2493
- }
2494
- function appendText(end){//has some bugs
2495
- if(end>start){
2496
- var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
2497
- locator&&position(start);
2498
- domBuilder.characters(xt,0,end-start);
2499
- start = end;
2500
- }
2501
- }
2502
- function position(p,m){
2503
- while(p>=lineEnd && (m = linePattern.exec(source))){
2504
- lineStart = m.index;
2505
- lineEnd = lineStart + m[0].length;
2506
- locator.lineNumber++;
2507
- //console.log('line++:',locator,startPos,endPos)
2508
- }
2509
- locator.columnNumber = p-lineStart+1;
2510
- }
2511
- var lineStart = 0;
2512
- var lineEnd = 0;
2513
- var linePattern = /.*(?:\r\n?|\n)|.*$/g;
2514
- var locator = domBuilder.locator;
2515
-
2516
- var parseStack = [{currentNSMap:defaultNSMapCopy}];
2517
- var closeMap = {};
2518
- var start = 0;
2519
- while(true){
2520
- try{
2521
- var tagStart = source.indexOf('<',start);
2522
- if(tagStart<0){
2523
- if(!source.substr(start).match(/^\s*$/)){
2524
- var doc = domBuilder.doc;
2525
- var text = doc.createTextNode(source.substr(start));
2526
- doc.appendChild(text);
2527
- domBuilder.currentElement = text;
2528
- }
2529
- return;
2530
- }
2531
- if(tagStart>start){
2532
- appendText(tagStart);
2533
- }
2534
- switch(source.charAt(tagStart+1)){
2535
- case '/':
2536
- var end = source.indexOf('>',tagStart+3);
2537
- var tagName = source.substring(tagStart+2,end);
2538
- var config = parseStack.pop();
2539
- if(end<0){
2540
-
2541
- tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
2542
- errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
2543
- end = tagStart+1+tagName.length;
2544
- }else if(tagName.match(/\s</)){
2545
- tagName = tagName.replace(/[\s<].*/,'');
2546
- errorHandler.error("end tag name: "+tagName+' maybe not complete');
2547
- end = tagStart+1+tagName.length;
2548
- }
2549
- var localNSMap = config.localNSMap;
2550
- var endMatch = config.tagName == tagName;
2551
- var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase();
2552
- if(endIgnoreCaseMach){
2553
- domBuilder.endElement(config.uri,config.localName,tagName);
2554
- if(localNSMap){
2555
- for(var prefix in localNSMap){
2556
- domBuilder.endPrefixMapping(prefix) ;
2557
- }
2558
- }
2559
- if(!endMatch){
2560
- errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
2561
- }
2562
- }else {
2563
- parseStack.push(config);
2564
- }
2565
-
2566
- end++;
2567
- break;
2568
- // end elment
2569
- case '?':// <?...?>
2570
- locator&&position(tagStart);
2571
- end = parseInstruction(source,tagStart,domBuilder);
2572
- break;
2573
- case '!':// <!doctype,<![CDATA,<!--
2574
- locator&&position(tagStart);
2575
- end = parseDCC(source,tagStart,domBuilder,errorHandler);
2576
- break;
2577
- default:
2578
- locator&&position(tagStart);
2579
- var el = new ElementAttributes();
2580
- var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
2581
- //elStartEnd
2582
- var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
2583
- var len = el.length;
2584
-
2585
-
2586
- if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
2587
- el.closed = true;
2588
- if(!entityMap.nbsp){
2589
- errorHandler.warning('unclosed xml attribute');
2590
- }
2591
- }
2592
- if(locator && len){
2593
- var locator2 = copyLocator(locator,{});
2594
- //try{//attribute position fixed
2595
- for(var i = 0;i<len;i++){
2596
- var a = el[i];
2597
- position(a.offset);
2598
- a.locator = copyLocator(locator,{});
2599
- }
2600
- domBuilder.locator = locator2;
2601
- if(appendElement$1(el,domBuilder,currentNSMap)){
2602
- parseStack.push(el);
2603
- }
2604
- domBuilder.locator = locator;
2605
- }else {
2606
- if(appendElement$1(el,domBuilder,currentNSMap)){
2607
- parseStack.push(el);
2608
- }
2609
- }
2610
-
2611
-
2612
-
2613
- if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
2614
- end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder);
2615
- }else {
2616
- end++;
2617
- }
2618
- }
2619
- }catch(e){
2620
- if (e instanceof ParseError$1) {
2621
- throw e;
2622
- }
2623
- errorHandler.error('element parse error: '+e);
2624
- end = -1;
2625
- }
2626
- if(end>start){
2627
- start = end;
2628
- }else {
2629
- //TODO: 这里有可能sax回退,有位置错误风险
2630
- appendText(Math.max(tagStart,start)+1);
2631
- }
2632
- }
2633
- }
2634
- function copyLocator(f,t){
2635
- t.lineNumber = f.lineNumber;
2636
- t.columnNumber = f.columnNumber;
2637
- return t;
2638
- }
2639
-
2640
- /**
2641
- * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
2642
- * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
2643
- */
2644
- function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
2645
-
2646
- /**
2647
- * @param {string} qname
2648
- * @param {string} value
2649
- * @param {number} startIndex
2650
- */
2651
- function addAttribute(qname, value, startIndex) {
2652
- if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined');
2653
- el.addValue(qname, value, startIndex);
2654
- }
2655
- var attrName;
2656
- var value;
2657
- var p = ++start;
2658
- var s = S_TAG;//status
2659
- while(true){
2660
- var c = source.charAt(p);
2661
- switch(c){
2662
- case '=':
2663
- if(s === S_ATTR){//attrName
2664
- attrName = source.slice(start,p);
2665
- s = S_EQ;
2666
- }else if(s === S_ATTR_SPACE){
2667
- s = S_EQ;
2668
- }else {
2669
- //fatalError: equal must after attrName or space after attrName
2670
- throw new Error('attribute equal must after attrName'); // No known test case
2671
- }
2672
- break;
2673
- case '\'':
2674
- case '"':
2675
- if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
2676
- ){//equal
2677
- if(s === S_ATTR){
2678
- errorHandler.warning('attribute value must after "="');
2679
- attrName = source.slice(start,p);
2680
- }
2681
- start = p+1;
2682
- p = source.indexOf(c,start);
2683
- if(p>0){
2684
- value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
2685
- addAttribute(attrName, value, start-1);
2686
- s = S_ATTR_END;
2687
- }else {
2688
- //fatalError: no end quot match
2689
- throw new Error('attribute value no end \''+c+'\' match');
2690
- }
2691
- }else if(s == S_ATTR_NOQUOT_VALUE){
2692
- value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
2693
- //console.log(attrName,value,start,p)
2694
- addAttribute(attrName, value, start);
2695
- //console.dir(el)
2696
- errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
2697
- start = p+1;
2698
- s = S_ATTR_END;
2699
- }else {
2700
- //fatalError: no equal before
2701
- throw new Error('attribute value must after "="'); // No known test case
2702
- }
2703
- break;
2704
- case '/':
2705
- switch(s){
2706
- case S_TAG:
2707
- el.setTagName(source.slice(start,p));
2708
- case S_ATTR_END:
2709
- case S_TAG_SPACE:
2710
- case S_TAG_CLOSE:
2711
- s =S_TAG_CLOSE;
2712
- el.closed = true;
2713
- case S_ATTR_NOQUOT_VALUE:
2714
- case S_ATTR:
2715
- case S_ATTR_SPACE:
2716
- break;
2717
- //case S_EQ:
2718
- default:
2719
- throw new Error("attribute invalid close char('/')") // No known test case
2720
- }
2721
- break;
2722
- case ''://end document
2723
- errorHandler.error('unexpected end of input');
2724
- if(s == S_TAG){
2725
- el.setTagName(source.slice(start,p));
2726
- }
2727
- return p;
2728
- case '>':
2729
- switch(s){
2730
- case S_TAG:
2731
- el.setTagName(source.slice(start,p));
2732
- case S_ATTR_END:
2733
- case S_TAG_SPACE:
2734
- case S_TAG_CLOSE:
2735
- break;//normal
2736
- case S_ATTR_NOQUOT_VALUE://Compatible state
2737
- case S_ATTR:
2738
- value = source.slice(start,p);
2739
- if(value.slice(-1) === '/'){
2740
- el.closed = true;
2741
- value = value.slice(0,-1);
2742
- }
2743
- case S_ATTR_SPACE:
2744
- if(s === S_ATTR_SPACE){
2745
- value = attrName;
2746
- }
2747
- if(s == S_ATTR_NOQUOT_VALUE){
2748
- errorHandler.warning('attribute "'+value+'" missed quot(")!');
2749
- addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start);
2750
- }else {
2751
- if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
2752
- errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!');
2753
- }
2754
- addAttribute(value, value, start);
2755
- }
2756
- break;
2757
- case S_EQ:
2758
- throw new Error('attribute value missed!!');
2759
- }
2760
- // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
2761
- return p;
2762
- /*xml space '\x20' | #x9 | #xD | #xA; */
2763
- case '\u0080':
2764
- c = ' ';
2765
- default:
2766
- if(c<= ' '){//space
2767
- switch(s){
2768
- case S_TAG:
2769
- el.setTagName(source.slice(start,p));//tagName
2770
- s = S_TAG_SPACE;
2771
- break;
2772
- case S_ATTR:
2773
- attrName = source.slice(start,p);
2774
- s = S_ATTR_SPACE;
2775
- break;
2776
- case S_ATTR_NOQUOT_VALUE:
2777
- var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
2778
- errorHandler.warning('attribute "'+value+'" missed quot(")!!');
2779
- addAttribute(attrName, value, start);
2780
- case S_ATTR_END:
2781
- s = S_TAG_SPACE;
2782
- break;
2783
- //case S_TAG_SPACE:
2784
- //case S_EQ:
2785
- //case S_ATTR_SPACE:
2786
- // void();break;
2787
- //case S_TAG_CLOSE:
2788
- //ignore warning
2789
- }
2790
- }else {//not space
2791
- //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
2792
- //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
2793
- switch(s){
2794
- //case S_TAG:void();break;
2795
- //case S_ATTR:void();break;
2796
- //case S_ATTR_NOQUOT_VALUE:void();break;
2797
- case S_ATTR_SPACE:
2798
- el.tagName;
2799
- if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
2800
- errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!');
2801
- }
2802
- addAttribute(attrName, attrName, start);
2803
- start = p;
2804
- s = S_ATTR;
2805
- break;
2806
- case S_ATTR_END:
2807
- errorHandler.warning('attribute space is required"'+attrName+'"!!');
2808
- case S_TAG_SPACE:
2809
- s = S_ATTR;
2810
- start = p;
2811
- break;
2812
- case S_EQ:
2813
- s = S_ATTR_NOQUOT_VALUE;
2814
- start = p;
2815
- break;
2816
- case S_TAG_CLOSE:
2817
- throw new Error("elements closed character '/' and '>' must be connected to");
2818
- }
2819
- }
2820
- }//end outer switch
2821
- //console.log('p++',p)
2822
- p++;
2823
- }
2824
- }
2825
- /**
2826
- * @return true if has new namespace define
2827
- */
2828
- function appendElement$1(el,domBuilder,currentNSMap){
2829
- var tagName = el.tagName;
2830
- var localNSMap = null;
2831
- //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
2832
- var i = el.length;
2833
- while(i--){
2834
- var a = el[i];
2835
- var qName = a.qName;
2836
- var value = a.value;
2837
- var nsp = qName.indexOf(':');
2838
- if(nsp>0){
2839
- var prefix = a.prefix = qName.slice(0,nsp);
2840
- var localName = qName.slice(nsp+1);
2841
- var nsPrefix = prefix === 'xmlns' && localName;
2842
- }else {
2843
- localName = qName;
2844
- prefix = null;
2845
- nsPrefix = qName === 'xmlns' && '';
2846
- }
2847
- //can not set prefix,because prefix !== ''
2848
- a.localName = localName ;
2849
- //prefix == null for no ns prefix attribute
2850
- if(nsPrefix !== false){//hack!!
2851
- if(localNSMap == null){
2852
- localNSMap = {};
2853
- //console.log(currentNSMap,0)
2854
- _copy(currentNSMap,currentNSMap={});
2855
- //console.log(currentNSMap,1)
2856
- }
2857
- currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
2858
- a.uri = 'http://www.w3.org/2000/xmlns/';
2859
- domBuilder.startPrefixMapping(nsPrefix, value);
2860
- }
2861
- }
2862
- var i = el.length;
2863
- while(i--){
2864
- a = el[i];
2865
- var prefix = a.prefix;
2866
- if(prefix){//no prefix attribute has no namespace
2867
- if(prefix === 'xml'){
2868
- a.uri = 'http://www.w3.org/XML/1998/namespace';
2869
- }if(prefix !== 'xmlns'){
2870
- a.uri = currentNSMap[prefix || ''];
2871
-
2872
- //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
2873
- }
2874
- }
2875
- }
2876
- var nsp = tagName.indexOf(':');
2877
- if(nsp>0){
2878
- prefix = el.prefix = tagName.slice(0,nsp);
2879
- localName = el.localName = tagName.slice(nsp+1);
2880
- }else {
2881
- prefix = null;//important!!
2882
- localName = el.localName = tagName;
2883
- }
2884
- //no prefix element has default namespace
2885
- var ns = el.uri = currentNSMap[prefix || ''];
2886
- domBuilder.startElement(ns,localName,tagName,el);
2887
- //endPrefixMapping and startPrefixMapping have not any help for dom builder
2888
- //localNSMap = null
2889
- if(el.closed){
2890
- domBuilder.endElement(ns,localName,tagName);
2891
- if(localNSMap){
2892
- for(prefix in localNSMap){
2893
- domBuilder.endPrefixMapping(prefix);
2894
- }
2895
- }
2896
- }else {
2897
- el.currentNSMap = currentNSMap;
2898
- el.localNSMap = localNSMap;
2899
- //parseStack.push(el);
2900
- return true;
2901
- }
2902
- }
2903
- function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
2904
- if(/^(?:script|textarea)$/i.test(tagName)){
2905
- var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
2906
- var text = source.substring(elStartEnd+1,elEndStart);
2907
- if(/[&<]/.test(text)){
2908
- if(/^script$/i.test(tagName)){
2909
- //if(!/\]\]>/.test(text)){
2910
- //lexHandler.startCDATA();
2911
- domBuilder.characters(text,0,text.length);
2912
- //lexHandler.endCDATA();
2913
- return elEndStart;
2914
- //}
2915
- }//}else{//text area
2916
- text = text.replace(/&#?\w+;/g,entityReplacer);
2917
- domBuilder.characters(text,0,text.length);
2918
- return elEndStart;
2919
- //}
2920
-
2921
- }
2922
- }
2923
- return elStartEnd+1;
2924
- }
2925
- function fixSelfClosed(source,elStartEnd,tagName,closeMap){
2926
- //if(tagName in closeMap){
2927
- var pos = closeMap[tagName];
2928
- if(pos == null){
2929
- //console.log(tagName)
2930
- pos = source.lastIndexOf('</'+tagName+'>');
2931
- if(pos<elStartEnd){//忘记闭合
2932
- pos = source.lastIndexOf('</'+tagName);
2933
- }
2934
- closeMap[tagName] =pos;
2935
- }
2936
- return pos<elStartEnd;
2937
- //}
2938
- }
2939
- function _copy(source,target){
2940
- for(var n in source){target[n] = source[n];}
2941
- }
2942
- function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
2943
- var next= source.charAt(start+2);
2944
- switch(next){
2945
- case '-':
2946
- if(source.charAt(start + 3) === '-'){
2947
- var end = source.indexOf('-->',start+4);
2948
- //append comment source.substring(4,end)//<!--
2949
- if(end>start){
2950
- domBuilder.comment(source,start+4,end-start-4);
2951
- return end+3;
2952
- }else {
2953
- errorHandler.error("Unclosed comment");
2954
- return -1;
2955
- }
2956
- }else {
2957
- //error
2958
- return -1;
2959
- }
2960
- default:
2961
- if(source.substr(start+3,6) == 'CDATA['){
2962
- var end = source.indexOf(']]>',start+9);
2963
- domBuilder.startCDATA();
2964
- domBuilder.characters(source,start+9,end-start-9);
2965
- domBuilder.endCDATA();
2966
- return end+3;
2967
- }
2968
- //<!DOCTYPE
2969
- //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
2970
- var matchs = split(source,start);
2971
- var len = matchs.length;
2972
- if(len>1 && /!doctype/i.test(matchs[0][0])){
2973
- var name = matchs[1][0];
2974
- var pubid = false;
2975
- var sysid = false;
2976
- if(len>3){
2977
- if(/^public$/i.test(matchs[2][0])){
2978
- pubid = matchs[3][0];
2979
- sysid = len>4 && matchs[4][0];
2980
- }else if(/^system$/i.test(matchs[2][0])){
2981
- sysid = matchs[3][0];
2982
- }
2983
- }
2984
- var lastMatch = matchs[len-1];
2985
- domBuilder.startDTD(name, pubid, sysid);
2986
- domBuilder.endDTD();
2987
-
2988
- return lastMatch.index+lastMatch[0].length
2989
- }
2990
- }
2991
- return -1;
2992
- }
2993
-
2994
-
2995
-
2996
- function parseInstruction(source,start,domBuilder){
2997
- var end = source.indexOf('?>',start);
2998
- if(end){
2999
- var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
3000
- if(match){
3001
- match[0].length;
3002
- domBuilder.processingInstruction(match[1], match[2]) ;
3003
- return end+2;
3004
- }else {//error
3005
- return -1;
3006
- }
3007
- }
3008
- return -1;
3009
- }
3010
-
3011
- function ElementAttributes(){
3012
- this.attributeNames = {};
3013
- }
3014
- ElementAttributes.prototype = {
3015
- setTagName:function(tagName){
3016
- if(!tagNamePattern.test(tagName)){
3017
- throw new Error('invalid tagName:'+tagName)
3018
- }
3019
- this.tagName = tagName;
3020
- },
3021
- addValue:function(qName, value, offset) {
3022
- if(!tagNamePattern.test(qName)){
3023
- throw new Error('invalid attribute:'+qName)
3024
- }
3025
- this.attributeNames[qName] = this.length;
3026
- this[this.length++] = {qName:qName,value:value,offset:offset};
3027
- },
3028
- length:0,
3029
- getLocalName:function(i){return this[i].localName},
3030
- getLocator:function(i){return this[i].locator},
3031
- getQName:function(i){return this[i].qName},
3032
- getURI:function(i){return this[i].uri},
3033
- getValue:function(i){return this[i].value}
3034
- // ,getIndex:function(uri, localName)){
3035
- // if(localName){
3036
- //
3037
- // }else{
3038
- // var qName = uri
3039
- // }
3040
- // },
3041
- // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
3042
- // getType:function(uri,localName){}
3043
- // getType:function(i){},
3044
- };
3045
-
3046
-
3047
-
3048
- function split(source,start){
3049
- var match;
3050
- var buf = [];
3051
- var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
3052
- reg.lastIndex = start;
3053
- reg.exec(source);//skip <
3054
- while(match = reg.exec(source)){
3055
- buf.push(match);
3056
- if(match[1])return buf;
3057
- }
3058
- }
3059
-
3060
- sax$1.XMLReader = XMLReader$1;
3061
- sax$1.ParseError = ParseError$1;
3062
-
3063
- var dom = {};
3064
-
3065
- function copy(src,dest){
3066
- for(var p in src){
3067
- dest[p] = src[p];
3068
- }
3069
- }
3070
- /**
3071
- ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
3072
- ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
3073
- */
3074
- function _extends(Class,Super){
3075
- var pt = Class.prototype;
3076
- if(!(pt instanceof Super)){
3077
- function t(){} t.prototype = Super.prototype;
3078
- t = new t();
3079
- copy(pt,t);
3080
- Class.prototype = pt = t;
3081
- }
3082
- if(pt.constructor != Class){
3083
- if(typeof Class != 'function'){
3084
- console.error("unknow Class:"+Class);
3085
- }
3086
- pt.constructor = Class;
3087
- }
3088
- }
3089
- var htmlns = 'http://www.w3.org/1999/xhtml' ;
3090
- // Node Types
3091
- var NodeType = {};
3092
- var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
3093
- var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
3094
- var TEXT_NODE = NodeType.TEXT_NODE = 3;
3095
- var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
3096
- var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
3097
- var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
3098
- var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
3099
- var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
3100
- var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
3101
- var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
3102
- var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
3103
- var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
3104
-
3105
- // ExceptionCode
3106
- var ExceptionCode = {};
3107
- var ExceptionMessage = {};
3108
- ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
3109
- ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
3110
- var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
3111
- ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
3112
- ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
3113
- ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
3114
- ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
3115
- var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
3116
- ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
3117
- var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
3118
- //level2
3119
- ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
3120
- ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
3121
- ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
3122
- ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
3123
- ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
3124
-
3125
- /**
3126
- * DOM Level 2
3127
- * Object DOMException
3128
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
3129
- * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
3130
- */
3131
- function DOMException(code, message) {
3132
- if(message instanceof Error){
3133
- var error = message;
3134
- }else {
3135
- error = this;
3136
- Error.call(this, ExceptionMessage[code]);
3137
- this.message = ExceptionMessage[code];
3138
- if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
3139
- }
3140
- error.code = code;
3141
- if(message) this.message = this.message + ": " + message;
3142
- return error;
3143
- }DOMException.prototype = Error.prototype;
3144
- copy(ExceptionCode,DOMException);
3145
- /**
3146
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
3147
- * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
3148
- * The items in the NodeList are accessible via an integral index, starting from 0.
3149
- */
3150
- function NodeList() {
3151
- }NodeList.prototype = {
3152
- /**
3153
- * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
3154
- * @standard level1
3155
- */
3156
- length:0,
3157
- /**
3158
- * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
3159
- * @standard level1
3160
- * @param index unsigned long
3161
- * Index into the collection.
3162
- * @return Node
3163
- * The node at the indexth position in the NodeList, or null if that is not a valid index.
3164
- */
3165
- item: function(index) {
3166
- return this[index] || null;
3167
- },
3168
- toString:function(isHTML,nodeFilter){
3169
- for(var buf = [], i = 0;i<this.length;i++){
3170
- serializeToString(this[i],buf,isHTML,nodeFilter);
3171
- }
3172
- return buf.join('');
3173
- }
3174
- };
3175
- function LiveNodeList(node,refresh){
3176
- this._node = node;
3177
- this._refresh = refresh;
3178
- _updateLiveList(this);
3179
- }
3180
- function _updateLiveList(list){
3181
- var inc = list._node._inc || list._node.ownerDocument._inc;
3182
- if(list._inc != inc){
3183
- var ls = list._refresh(list._node);
3184
- //console.log(ls.length)
3185
- __set__(list,'length',ls.length);
3186
- copy(ls,list);
3187
- list._inc = inc;
3188
- }
3189
- }
3190
- LiveNodeList.prototype.item = function(i){
3191
- _updateLiveList(this);
3192
- return this[i];
3193
- };
3194
-
3195
- _extends(LiveNodeList,NodeList);
3196
- /**
3197
- *
3198
- * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
3199
- * NamedNodeMap objects in the DOM are live.
3200
- * used for attributes or DocumentType entities
3201
- */
3202
- function NamedNodeMap() {
3203
- }
3204
- function _findNodeIndex(list,node){
3205
- var i = list.length;
3206
- while(i--){
3207
- if(list[i] === node){return i}
3208
- }
3209
- }
3210
-
3211
- function _addNamedNode(el,list,newAttr,oldAttr){
3212
- if(oldAttr){
3213
- list[_findNodeIndex(list,oldAttr)] = newAttr;
3214
- }else {
3215
- list[list.length++] = newAttr;
3216
- }
3217
- if(el){
3218
- newAttr.ownerElement = el;
3219
- var doc = el.ownerDocument;
3220
- if(doc){
3221
- oldAttr && _onRemoveAttribute(doc,el,oldAttr);
3222
- _onAddAttribute(doc,el,newAttr);
3223
- }
3224
- }
3225
- }
3226
- function _removeNamedNode(el,list,attr){
3227
- //console.log('remove attr:'+attr)
3228
- var i = _findNodeIndex(list,attr);
3229
- if(i>=0){
3230
- var lastIndex = list.length-1;
3231
- while(i<lastIndex){
3232
- list[i] = list[++i];
3233
- }
3234
- list.length = lastIndex;
3235
- if(el){
3236
- var doc = el.ownerDocument;
3237
- if(doc){
3238
- _onRemoveAttribute(doc,el,attr);
3239
- attr.ownerElement = null;
3240
- }
3241
- }
3242
- }else {
3243
- throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
3244
- }
3245
- }
3246
- NamedNodeMap.prototype = {
3247
- length:0,
3248
- item:NodeList.prototype.item,
3249
- getNamedItem: function(key) {
3250
- // if(key.indexOf(':')>0 || key == 'xmlns'){
3251
- // return null;
3252
- // }
3253
- //console.log()
3254
- var i = this.length;
3255
- while(i--){
3256
- var attr = this[i];
3257
- //console.log(attr.nodeName,key)
3258
- if(attr.nodeName == key){
3259
- return attr;
3260
- }
3261
- }
3262
- },
3263
- setNamedItem: function(attr) {
3264
- var el = attr.ownerElement;
3265
- if(el && el!=this._ownerElement){
3266
- throw new DOMException(INUSE_ATTRIBUTE_ERR);
3267
- }
3268
- var oldAttr = this.getNamedItem(attr.nodeName);
3269
- _addNamedNode(this._ownerElement,this,attr,oldAttr);
3270
- return oldAttr;
3271
- },
3272
- /* returns Node */
3273
- setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
3274
- var el = attr.ownerElement, oldAttr;
3275
- if(el && el!=this._ownerElement){
3276
- throw new DOMException(INUSE_ATTRIBUTE_ERR);
3277
- }
3278
- oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
3279
- _addNamedNode(this._ownerElement,this,attr,oldAttr);
3280
- return oldAttr;
3281
- },
3282
-
3283
- /* returns Node */
3284
- removeNamedItem: function(key) {
3285
- var attr = this.getNamedItem(key);
3286
- _removeNamedNode(this._ownerElement,this,attr);
3287
- return attr;
3288
-
3289
-
3290
- },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
3291
-
3292
- //for level2
3293
- removeNamedItemNS:function(namespaceURI,localName){
3294
- var attr = this.getNamedItemNS(namespaceURI,localName);
3295
- _removeNamedNode(this._ownerElement,this,attr);
3296
- return attr;
3297
- },
3298
- getNamedItemNS: function(namespaceURI, localName) {
3299
- var i = this.length;
3300
- while(i--){
3301
- var node = this[i];
3302
- if(node.localName == localName && node.namespaceURI == namespaceURI){
3303
- return node;
3304
- }
3305
- }
3306
- return null;
3307
- }
3308
- };
3309
- /**
3310
- * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
3311
- */
3312
- function DOMImplementation$1(/* Object */ features) {
3313
- this._features = {};
3314
- if (features) {
3315
- for (var feature in features) {
3316
- this._features = features[feature];
3317
- }
3318
- }
3319
- }
3320
- DOMImplementation$1.prototype = {
3321
- hasFeature: function(/* string */ feature, /* string */ version) {
3322
- var versions = this._features[feature.toLowerCase()];
3323
- if (versions && (!version || version in versions)) {
3324
- return true;
3325
- } else {
3326
- return false;
3327
- }
3328
- },
3329
- // Introduced in DOM Level 2:
3330
- createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
3331
- var doc = new Document();
3332
- doc.implementation = this;
3333
- doc.childNodes = new NodeList();
3334
- doc.doctype = doctype;
3335
- if(doctype){
3336
- doc.appendChild(doctype);
3337
- }
3338
- if(qualifiedName){
3339
- var root = doc.createElementNS(namespaceURI,qualifiedName);
3340
- doc.appendChild(root);
3341
- }
3342
- return doc;
3343
- },
3344
- // Introduced in DOM Level 2:
3345
- createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
3346
- var node = new DocumentType();
3347
- node.name = qualifiedName;
3348
- node.nodeName = qualifiedName;
3349
- node.publicId = publicId;
3350
- node.systemId = systemId;
3351
- // Introduced in DOM Level 2:
3352
- //readonly attribute DOMString internalSubset;
3353
-
3354
- //TODO:..
3355
- // readonly attribute NamedNodeMap entities;
3356
- // readonly attribute NamedNodeMap notations;
3357
- return node;
3358
- }
3359
- };
3360
-
3361
-
3362
- /**
3363
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
3364
- */
3365
-
3366
- function Node() {
3367
- }
3368
- Node.prototype = {
3369
- firstChild : null,
3370
- lastChild : null,
3371
- previousSibling : null,
3372
- nextSibling : null,
3373
- attributes : null,
3374
- parentNode : null,
3375
- childNodes : null,
3376
- ownerDocument : null,
3377
- nodeValue : null,
3378
- namespaceURI : null,
3379
- prefix : null,
3380
- localName : null,
3381
- // Modified in DOM Level 2:
3382
- insertBefore:function(newChild, refChild){//raises
3383
- return _insertBefore(this,newChild,refChild);
3384
- },
3385
- replaceChild:function(newChild, oldChild){//raises
3386
- this.insertBefore(newChild,oldChild);
3387
- if(oldChild){
3388
- this.removeChild(oldChild);
3389
- }
3390
- },
3391
- removeChild:function(oldChild){
3392
- return _removeChild(this,oldChild);
3393
- },
3394
- appendChild:function(newChild){
3395
- return this.insertBefore(newChild,null);
3396
- },
3397
- hasChildNodes:function(){
3398
- return this.firstChild != null;
3399
- },
3400
- cloneNode:function(deep){
3401
- return cloneNode(this.ownerDocument||this,this,deep);
3402
- },
3403
- // Modified in DOM Level 2:
3404
- normalize:function(){
3405
- var child = this.firstChild;
3406
- while(child){
3407
- var next = child.nextSibling;
3408
- if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
3409
- this.removeChild(next);
3410
- child.appendData(next.data);
3411
- }else {
3412
- child.normalize();
3413
- child = next;
3414
- }
3415
- }
3416
- },
3417
- // Introduced in DOM Level 2:
3418
- isSupported:function(feature, version){
3419
- return this.ownerDocument.implementation.hasFeature(feature,version);
3420
- },
3421
- // Introduced in DOM Level 2:
3422
- hasAttributes:function(){
3423
- return this.attributes.length>0;
3424
- },
3425
- lookupPrefix:function(namespaceURI){
3426
- var el = this;
3427
- while(el){
3428
- var map = el._nsMap;
3429
- //console.dir(map)
3430
- if(map){
3431
- for(var n in map){
3432
- if(map[n] == namespaceURI){
3433
- return n;
3434
- }
3435
- }
3436
- }
3437
- el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
3438
- }
3439
- return null;
3440
- },
3441
- // Introduced in DOM Level 3:
3442
- lookupNamespaceURI:function(prefix){
3443
- var el = this;
3444
- while(el){
3445
- var map = el._nsMap;
3446
- //console.dir(map)
3447
- if(map){
3448
- if(prefix in map){
3449
- return map[prefix] ;
3450
- }
3451
- }
3452
- el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
3453
- }
3454
- return null;
3455
- },
3456
- // Introduced in DOM Level 3:
3457
- isDefaultNamespace:function(namespaceURI){
3458
- var prefix = this.lookupPrefix(namespaceURI);
3459
- return prefix == null;
3460
- }
3461
- };
3462
-
3463
-
3464
- function _xmlEncoder(c){
3465
- return c == '<' && '&lt;' ||
3466
- c == '>' && '&gt;' ||
3467
- c == '&' && '&amp;' ||
3468
- c == '"' && '&quot;' ||
3469
- '&#'+c.charCodeAt()+';'
3470
- }
3471
-
3472
-
3473
- copy(NodeType,Node);
3474
- copy(NodeType,Node.prototype);
3475
-
3476
- /**
3477
- * @param callback return true for continue,false for break
3478
- * @return boolean true: break visit;
3479
- */
3480
- function _visitNode(node,callback){
3481
- if(callback(node)){
3482
- return true;
3483
- }
3484
- if(node = node.firstChild){
3485
- do{
3486
- if(_visitNode(node,callback)){return true}
3487
- }while(node=node.nextSibling)
3488
- }
3489
- }
3490
-
3491
-
3492
-
3493
- function Document(){
3494
- }
3495
- function _onAddAttribute(doc,el,newAttr){
3496
- doc && doc._inc++;
3497
- var ns = newAttr.namespaceURI ;
3498
- if(ns == 'http://www.w3.org/2000/xmlns/'){
3499
- //update namespace
3500
- el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value;
3501
- }
3502
- }
3503
- function _onRemoveAttribute(doc,el,newAttr,remove){
3504
- doc && doc._inc++;
3505
- var ns = newAttr.namespaceURI ;
3506
- if(ns == 'http://www.w3.org/2000/xmlns/'){
3507
- //update namespace
3508
- delete el._nsMap[newAttr.prefix?newAttr.localName:''];
3509
- }
3510
- }
3511
- function _onUpdateChild(doc,el,newChild){
3512
- if(doc && doc._inc){
3513
- doc._inc++;
3514
- //update childNodes
3515
- var cs = el.childNodes;
3516
- if(newChild){
3517
- cs[cs.length++] = newChild;
3518
- }else {
3519
- //console.log(1)
3520
- var child = el.firstChild;
3521
- var i = 0;
3522
- while(child){
3523
- cs[i++] = child;
3524
- child =child.nextSibling;
3525
- }
3526
- cs.length = i;
3527
- }
3528
- }
3529
- }
3530
-
3531
- /**
3532
- * attributes;
3533
- * children;
3534
- *
3535
- * writeable properties:
3536
- * nodeValue,Attr:value,CharacterData:data
3537
- * prefix
3538
- */
3539
- function _removeChild(parentNode,child){
3540
- var previous = child.previousSibling;
3541
- var next = child.nextSibling;
3542
- if(previous){
3543
- previous.nextSibling = next;
3544
- }else {
3545
- parentNode.firstChild = next;
3546
- }
3547
- if(next){
3548
- next.previousSibling = previous;
3549
- }else {
3550
- parentNode.lastChild = previous;
3551
- }
3552
- _onUpdateChild(parentNode.ownerDocument,parentNode);
3553
- return child;
3554
- }
3555
- /**
3556
- * preformance key(refChild == null)
3557
- */
3558
- function _insertBefore(parentNode,newChild,nextChild){
3559
- var cp = newChild.parentNode;
3560
- if(cp){
3561
- cp.removeChild(newChild);//remove and update
3562
- }
3563
- if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
3564
- var newFirst = newChild.firstChild;
3565
- if (newFirst == null) {
3566
- return newChild;
3567
- }
3568
- var newLast = newChild.lastChild;
3569
- }else {
3570
- newFirst = newLast = newChild;
3571
- }
3572
- var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
3573
-
3574
- newFirst.previousSibling = pre;
3575
- newLast.nextSibling = nextChild;
3576
-
3577
-
3578
- if(pre){
3579
- pre.nextSibling = newFirst;
3580
- }else {
3581
- parentNode.firstChild = newFirst;
3582
- }
3583
- if(nextChild == null){
3584
- parentNode.lastChild = newLast;
3585
- }else {
3586
- nextChild.previousSibling = newLast;
3587
- }
3588
- do{
3589
- newFirst.parentNode = parentNode;
3590
- }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
3591
- _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
3592
- //console.log(parentNode.lastChild.nextSibling == null)
3593
- if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
3594
- newChild.firstChild = newChild.lastChild = null;
3595
- }
3596
- return newChild;
3597
- }
3598
- function _appendSingleChild(parentNode,newChild){
3599
- var cp = newChild.parentNode;
3600
- if(cp){
3601
- var pre = parentNode.lastChild;
3602
- cp.removeChild(newChild);//remove and update
3603
- var pre = parentNode.lastChild;
3604
- }
3605
- var pre = parentNode.lastChild;
3606
- newChild.parentNode = parentNode;
3607
- newChild.previousSibling = pre;
3608
- newChild.nextSibling = null;
3609
- if(pre){
3610
- pre.nextSibling = newChild;
3611
- }else {
3612
- parentNode.firstChild = newChild;
3613
- }
3614
- parentNode.lastChild = newChild;
3615
- _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
3616
- return newChild;
3617
- //console.log("__aa",parentNode.lastChild.nextSibling == null)
3618
- }
3619
- Document.prototype = {
3620
- //implementation : null,
3621
- nodeName : '#document',
3622
- nodeType : DOCUMENT_NODE,
3623
- doctype : null,
3624
- documentElement : null,
3625
- _inc : 1,
3626
-
3627
- insertBefore : function(newChild, refChild){//raises
3628
- if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
3629
- var child = newChild.firstChild;
3630
- while(child){
3631
- var next = child.nextSibling;
3632
- this.insertBefore(child,refChild);
3633
- child = next;
3634
- }
3635
- return newChild;
3636
- }
3637
- if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
3638
- this.documentElement = newChild;
3639
- }
3640
-
3641
- return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
3642
- },
3643
- removeChild : function(oldChild){
3644
- if(this.documentElement == oldChild){
3645
- this.documentElement = null;
3646
- }
3647
- return _removeChild(this,oldChild);
3648
- },
3649
- // Introduced in DOM Level 2:
3650
- importNode : function(importedNode,deep){
3651
- return importNode(this,importedNode,deep);
3652
- },
3653
- // Introduced in DOM Level 2:
3654
- getElementById : function(id){
3655
- var rtv = null;
3656
- _visitNode(this.documentElement,function(node){
3657
- if(node.nodeType == ELEMENT_NODE){
3658
- if(node.getAttribute('id') == id){
3659
- rtv = node;
3660
- return true;
3661
- }
3662
- }
3663
- });
3664
- return rtv;
3665
- },
3666
-
3667
- getElementsByClassName: function(className) {
3668
- var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
3669
- return new LiveNodeList(this, function(base) {
3670
- var ls = [];
3671
- _visitNode(base.documentElement, function(node) {
3672
- if(node !== base && node.nodeType == ELEMENT_NODE) {
3673
- if(pattern.test(node.getAttribute('class'))) {
3674
- ls.push(node);
3675
- }
3676
- }
3677
- });
3678
- return ls;
3679
- });
3680
- },
3681
-
3682
- //document factory method:
3683
- createElement : function(tagName){
3684
- var node = new Element();
3685
- node.ownerDocument = this;
3686
- node.nodeName = tagName;
3687
- node.tagName = tagName;
3688
- node.childNodes = new NodeList();
3689
- var attrs = node.attributes = new NamedNodeMap();
3690
- attrs._ownerElement = node;
3691
- return node;
3692
- },
3693
- createDocumentFragment : function(){
3694
- var node = new DocumentFragment();
3695
- node.ownerDocument = this;
3696
- node.childNodes = new NodeList();
3697
- return node;
3698
- },
3699
- createTextNode : function(data){
3700
- var node = new Text();
3701
- node.ownerDocument = this;
3702
- node.appendData(data);
3703
- return node;
3704
- },
3705
- createComment : function(data){
3706
- var node = new Comment();
3707
- node.ownerDocument = this;
3708
- node.appendData(data);
3709
- return node;
3710
- },
3711
- createCDATASection : function(data){
3712
- var node = new CDATASection();
3713
- node.ownerDocument = this;
3714
- node.appendData(data);
3715
- return node;
3716
- },
3717
- createProcessingInstruction : function(target,data){
3718
- var node = new ProcessingInstruction();
3719
- node.ownerDocument = this;
3720
- node.tagName = node.target = target;
3721
- node.nodeValue= node.data = data;
3722
- return node;
3723
- },
3724
- createAttribute : function(name){
3725
- var node = new Attr();
3726
- node.ownerDocument = this;
3727
- node.name = name;
3728
- node.nodeName = name;
3729
- node.localName = name;
3730
- node.specified = true;
3731
- return node;
3732
- },
3733
- createEntityReference : function(name){
3734
- var node = new EntityReference();
3735
- node.ownerDocument = this;
3736
- node.nodeName = name;
3737
- return node;
3738
- },
3739
- // Introduced in DOM Level 2:
3740
- createElementNS : function(namespaceURI,qualifiedName){
3741
- var node = new Element();
3742
- var pl = qualifiedName.split(':');
3743
- var attrs = node.attributes = new NamedNodeMap();
3744
- node.childNodes = new NodeList();
3745
- node.ownerDocument = this;
3746
- node.nodeName = qualifiedName;
3747
- node.tagName = qualifiedName;
3748
- node.namespaceURI = namespaceURI;
3749
- if(pl.length == 2){
3750
- node.prefix = pl[0];
3751
- node.localName = pl[1];
3752
- }else {
3753
- //el.prefix = null;
3754
- node.localName = qualifiedName;
3755
- }
3756
- attrs._ownerElement = node;
3757
- return node;
3758
- },
3759
- // Introduced in DOM Level 2:
3760
- createAttributeNS : function(namespaceURI,qualifiedName){
3761
- var node = new Attr();
3762
- var pl = qualifiedName.split(':');
3763
- node.ownerDocument = this;
3764
- node.nodeName = qualifiedName;
3765
- node.name = qualifiedName;
3766
- node.namespaceURI = namespaceURI;
3767
- node.specified = true;
3768
- if(pl.length == 2){
3769
- node.prefix = pl[0];
3770
- node.localName = pl[1];
3771
- }else {
3772
- //el.prefix = null;
3773
- node.localName = qualifiedName;
3774
- }
3775
- return node;
3776
- }
3777
- };
3778
- _extends(Document,Node);
3779
-
3780
-
3781
- function Element() {
3782
- this._nsMap = {};
3783
- }Element.prototype = {
3784
- nodeType : ELEMENT_NODE,
3785
- hasAttribute : function(name){
3786
- return this.getAttributeNode(name)!=null;
3787
- },
3788
- getAttribute : function(name){
3789
- var attr = this.getAttributeNode(name);
3790
- return attr && attr.value || '';
3791
- },
3792
- getAttributeNode : function(name){
3793
- return this.attributes.getNamedItem(name);
3794
- },
3795
- setAttribute : function(name, value){
3796
- var attr = this.ownerDocument.createAttribute(name);
3797
- attr.value = attr.nodeValue = "" + value;
3798
- this.setAttributeNode(attr);
3799
- },
3800
- removeAttribute : function(name){
3801
- var attr = this.getAttributeNode(name);
3802
- attr && this.removeAttributeNode(attr);
3803
- },
3804
-
3805
- //four real opeartion method
3806
- appendChild:function(newChild){
3807
- if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
3808
- return this.insertBefore(newChild,null);
3809
- }else {
3810
- return _appendSingleChild(this,newChild);
3811
- }
3812
- },
3813
- setAttributeNode : function(newAttr){
3814
- return this.attributes.setNamedItem(newAttr);
3815
- },
3816
- setAttributeNodeNS : function(newAttr){
3817
- return this.attributes.setNamedItemNS(newAttr);
3818
- },
3819
- removeAttributeNode : function(oldAttr){
3820
- //console.log(this == oldAttr.ownerElement)
3821
- return this.attributes.removeNamedItem(oldAttr.nodeName);
3822
- },
3823
- //get real attribute name,and remove it by removeAttributeNode
3824
- removeAttributeNS : function(namespaceURI, localName){
3825
- var old = this.getAttributeNodeNS(namespaceURI, localName);
3826
- old && this.removeAttributeNode(old);
3827
- },
3828
-
3829
- hasAttributeNS : function(namespaceURI, localName){
3830
- return this.getAttributeNodeNS(namespaceURI, localName)!=null;
3831
- },
3832
- getAttributeNS : function(namespaceURI, localName){
3833
- var attr = this.getAttributeNodeNS(namespaceURI, localName);
3834
- return attr && attr.value || '';
3835
- },
3836
- setAttributeNS : function(namespaceURI, qualifiedName, value){
3837
- var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
3838
- attr.value = attr.nodeValue = "" + value;
3839
- this.setAttributeNode(attr);
3840
- },
3841
- getAttributeNodeNS : function(namespaceURI, localName){
3842
- return this.attributes.getNamedItemNS(namespaceURI, localName);
3843
- },
3844
-
3845
- getElementsByTagName : function(tagName){
3846
- return new LiveNodeList(this,function(base){
3847
- var ls = [];
3848
- _visitNode(base,function(node){
3849
- if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
3850
- ls.push(node);
3851
- }
3852
- });
3853
- return ls;
3854
- });
3855
- },
3856
- getElementsByTagNameNS : function(namespaceURI, localName){
3857
- return new LiveNodeList(this,function(base){
3858
- var ls = [];
3859
- _visitNode(base,function(node){
3860
- if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
3861
- ls.push(node);
3862
- }
3863
- });
3864
- return ls;
3865
-
3866
- });
3867
- }
3868
- };
3869
- Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
3870
- Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
3871
-
3872
-
3873
- _extends(Element,Node);
3874
- function Attr() {
3875
- }Attr.prototype.nodeType = ATTRIBUTE_NODE;
3876
- _extends(Attr,Node);
3877
-
3878
-
3879
- function CharacterData() {
3880
- }CharacterData.prototype = {
3881
- data : '',
3882
- substringData : function(offset, count) {
3883
- return this.data.substring(offset, offset+count);
3884
- },
3885
- appendData: function(text) {
3886
- text = this.data+text;
3887
- this.nodeValue = this.data = text;
3888
- this.length = text.length;
3889
- },
3890
- insertData: function(offset,text) {
3891
- this.replaceData(offset,0,text);
3892
-
3893
- },
3894
- appendChild:function(newChild){
3895
- throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
3896
- },
3897
- deleteData: function(offset, count) {
3898
- this.replaceData(offset,count,"");
3899
- },
3900
- replaceData: function(offset, count, text) {
3901
- var start = this.data.substring(0,offset);
3902
- var end = this.data.substring(offset+count);
3903
- text = start + text + end;
3904
- this.nodeValue = this.data = text;
3905
- this.length = text.length;
3906
- }
3907
- };
3908
- _extends(CharacterData,Node);
3909
- function Text() {
3910
- }Text.prototype = {
3911
- nodeName : "#text",
3912
- nodeType : TEXT_NODE,
3913
- splitText : function(offset) {
3914
- var text = this.data;
3915
- var newText = text.substring(offset);
3916
- text = text.substring(0, offset);
3917
- this.data = this.nodeValue = text;
3918
- this.length = text.length;
3919
- var newNode = this.ownerDocument.createTextNode(newText);
3920
- if(this.parentNode){
3921
- this.parentNode.insertBefore(newNode, this.nextSibling);
3922
- }
3923
- return newNode;
3924
- }
3925
- };
3926
- _extends(Text,CharacterData);
3927
- function Comment() {
3928
- }Comment.prototype = {
3929
- nodeName : "#comment",
3930
- nodeType : COMMENT_NODE
3931
- };
3932
- _extends(Comment,CharacterData);
3933
-
3934
- function CDATASection() {
3935
- }CDATASection.prototype = {
3936
- nodeName : "#cdata-section",
3937
- nodeType : CDATA_SECTION_NODE
3938
- };
3939
- _extends(CDATASection,CharacterData);
3940
-
3941
-
3942
- function DocumentType() {
3943
- }DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
3944
- _extends(DocumentType,Node);
3945
-
3946
- function Notation() {
3947
- }Notation.prototype.nodeType = NOTATION_NODE;
3948
- _extends(Notation,Node);
3949
-
3950
- function Entity() {
3951
- }Entity.prototype.nodeType = ENTITY_NODE;
3952
- _extends(Entity,Node);
3953
-
3954
- function EntityReference() {
3955
- }EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
3956
- _extends(EntityReference,Node);
3957
-
3958
- function DocumentFragment() {
3959
- }DocumentFragment.prototype.nodeName = "#document-fragment";
3960
- DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
3961
- _extends(DocumentFragment,Node);
3962
-
3963
-
3964
- function ProcessingInstruction() {
3965
- }
3966
- ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
3967
- _extends(ProcessingInstruction,Node);
3968
- function XMLSerializer(){}
3969
- XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
3970
- return nodeSerializeToString.call(node,isHtml,nodeFilter);
3971
- };
3972
- Node.prototype.toString = nodeSerializeToString;
3973
- function nodeSerializeToString(isHtml,nodeFilter){
3974
- var buf = [];
3975
- var refNode = this.nodeType == 9 && this.documentElement || this;
3976
- var prefix = refNode.prefix;
3977
- var uri = refNode.namespaceURI;
3978
-
3979
- if(uri && prefix == null){
3980
- //console.log(prefix)
3981
- var prefix = refNode.lookupPrefix(uri);
3982
- if(prefix == null){
3983
- //isHTML = true;
3984
- var visibleNamespaces=[
3985
- {namespace:uri,prefix:null}
3986
- //{namespace:uri,prefix:''}
3987
- ];
3988
- }
3989
- }
3990
- serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
3991
- //console.log('###',this.nodeType,uri,prefix,buf.join(''))
3992
- return buf.join('');
3993
- }
3994
- function needNamespaceDefine(node,isHTML, visibleNamespaces) {
3995
- var prefix = node.prefix||'';
3996
- var uri = node.namespaceURI;
3997
- if (!prefix && !uri){
3998
- return false;
3999
- }
4000
- if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
4001
- || uri == 'http://www.w3.org/2000/xmlns/'){
4002
- return false;
4003
- }
4004
-
4005
- var i = visibleNamespaces.length;
4006
- //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
4007
- while (i--) {
4008
- var ns = visibleNamespaces[i];
4009
- // get namespace prefix
4010
- //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
4011
- if (ns.prefix == prefix){
4012
- return ns.namespace != uri;
4013
- }
4014
- }
4015
- //console.log(isHTML,uri,prefix=='')
4016
- //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
4017
- // return false;
4018
- //}
4019
- //node.flag = '11111'
4020
- //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
4021
- return true;
4022
- }
4023
- function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
4024
- if(nodeFilter){
4025
- node = nodeFilter(node);
4026
- if(node){
4027
- if(typeof node == 'string'){
4028
- buf.push(node);
4029
- return;
4030
- }
4031
- }else {
4032
- return;
4033
- }
4034
- //buf.sort.apply(attrs, attributeSorter);
4035
- }
4036
- switch(node.nodeType){
4037
- case ELEMENT_NODE:
4038
- if (!visibleNamespaces) visibleNamespaces = [];
4039
- visibleNamespaces.length;
4040
- var attrs = node.attributes;
4041
- var len = attrs.length;
4042
- var child = node.firstChild;
4043
- var nodeName = node.tagName;
4044
-
4045
- isHTML = (htmlns === node.namespaceURI) ||isHTML;
4046
- buf.push('<',nodeName);
4047
-
4048
-
4049
-
4050
- for(var i=0;i<len;i++){
4051
- // add namespaces for attributes
4052
- var attr = attrs.item(i);
4053
- if (attr.prefix == 'xmlns') {
4054
- visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
4055
- }else if(attr.nodeName == 'xmlns'){
4056
- visibleNamespaces.push({ prefix: '', namespace: attr.value });
4057
- }
4058
- }
4059
- for(var i=0;i<len;i++){
4060
- var attr = attrs.item(i);
4061
- if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
4062
- var prefix = attr.prefix||'';
4063
- var uri = attr.namespaceURI;
4064
- var ns = prefix ? ' xmlns:' + prefix : " xmlns";
4065
- buf.push(ns, '="' , uri , '"');
4066
- visibleNamespaces.push({ prefix: prefix, namespace:uri });
4067
- }
4068
- serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
4069
- }
4070
- // add namespace for current node
4071
- if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
4072
- var prefix = node.prefix||'';
4073
- var uri = node.namespaceURI;
4074
- if (uri) {
4075
- // Avoid empty namespace value like xmlns:ds=""
4076
- // Empty namespace URL will we produce an invalid XML document
4077
- var ns = prefix ? ' xmlns:' + prefix : " xmlns";
4078
- buf.push(ns, '="' , uri , '"');
4079
- visibleNamespaces.push({ prefix: prefix, namespace:uri });
4080
- }
4081
- }
4082
-
4083
- if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
4084
- buf.push('>');
4085
- //if is cdata child node
4086
- if(isHTML && /^script$/i.test(nodeName)){
4087
- while(child){
4088
- if(child.data){
4089
- buf.push(child.data);
4090
- }else {
4091
- serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
4092
- }
4093
- child = child.nextSibling;
4094
- }
4095
- }else
4096
- {
4097
- while(child){
4098
- serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
4099
- child = child.nextSibling;
4100
- }
4101
- }
4102
- buf.push('</',nodeName,'>');
4103
- }else {
4104
- buf.push('/>');
4105
- }
4106
- // remove added visible namespaces
4107
- //visibleNamespaces.length = startVisibleNamespaces;
4108
- return;
4109
- case DOCUMENT_NODE:
4110
- case DOCUMENT_FRAGMENT_NODE:
4111
- var child = node.firstChild;
4112
- while(child){
4113
- serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
4114
- child = child.nextSibling;
4115
- }
4116
- return;
4117
- case ATTRIBUTE_NODE:
4118
- /**
4119
- * Well-formedness constraint: No < in Attribute Values
4120
- * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
4121
- * @see https://www.w3.org/TR/xml/#CleanAttrVals
4122
- * @see https://www.w3.org/TR/xml/#NT-AttValue
4123
- */
4124
- return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g,_xmlEncoder), '"');
4125
- case TEXT_NODE:
4126
- /**
4127
- * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
4128
- * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
4129
- * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
4130
- * `&amp;` and `&lt;` respectively.
4131
- * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
4132
- * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
4133
- * when that string is not marking the end of a CDATA section.
4134
- *
4135
- * In the content of elements, character data is any string of characters
4136
- * which does not contain the start-delimiter of any markup
4137
- * and does not include the CDATA-section-close delimiter, `]]>`.
4138
- *
4139
- * @see https://www.w3.org/TR/xml/#NT-CharData
4140
- */
4141
- return buf.push(node.data
4142
- .replace(/[<&]/g,_xmlEncoder)
4143
- .replace(/]]>/g, ']]&gt;')
4144
- );
4145
- case CDATA_SECTION_NODE:
4146
- return buf.push( '<![CDATA[',node.data,']]>');
4147
- case COMMENT_NODE:
4148
- return buf.push( "<!--",node.data,"-->");
4149
- case DOCUMENT_TYPE_NODE:
4150
- var pubid = node.publicId;
4151
- var sysid = node.systemId;
4152
- buf.push('<!DOCTYPE ',node.name);
4153
- if(pubid){
4154
- buf.push(' PUBLIC ', pubid);
4155
- if (sysid && sysid!='.') {
4156
- buf.push(' ', sysid);
4157
- }
4158
- buf.push('>');
4159
- }else if(sysid && sysid!='.'){
4160
- buf.push(' SYSTEM ', sysid, '>');
4161
- }else {
4162
- var sub = node.internalSubset;
4163
- if(sub){
4164
- buf.push(" [",sub,"]");
4165
- }
4166
- buf.push(">");
4167
- }
4168
- return;
4169
- case PROCESSING_INSTRUCTION_NODE:
4170
- return buf.push( "<?",node.target," ",node.data,"?>");
4171
- case ENTITY_REFERENCE_NODE:
4172
- return buf.push( '&',node.nodeName,';');
4173
- //case ENTITY_NODE:
4174
- //case NOTATION_NODE:
4175
- default:
4176
- buf.push('??',node.nodeName);
4177
- }
4178
- }
4179
- function importNode(doc,node,deep){
4180
- var node2;
4181
- switch (node.nodeType) {
4182
- case ELEMENT_NODE:
4183
- node2 = node.cloneNode(false);
4184
- node2.ownerDocument = doc;
4185
- //var attrs = node2.attributes;
4186
- //var len = attrs.length;
4187
- //for(var i=0;i<len;i++){
4188
- //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
4189
- //}
4190
- case DOCUMENT_FRAGMENT_NODE:
4191
- break;
4192
- case ATTRIBUTE_NODE:
4193
- deep = true;
4194
- break;
4195
- //case ENTITY_REFERENCE_NODE:
4196
- //case PROCESSING_INSTRUCTION_NODE:
4197
- ////case TEXT_NODE:
4198
- //case CDATA_SECTION_NODE:
4199
- //case COMMENT_NODE:
4200
- // deep = false;
4201
- // break;
4202
- //case DOCUMENT_NODE:
4203
- //case DOCUMENT_TYPE_NODE:
4204
- //cannot be imported.
4205
- //case ENTITY_NODE:
4206
- //case NOTATION_NODE:
4207
- //can not hit in level3
4208
- //default:throw e;
4209
- }
4210
- if(!node2){
4211
- node2 = node.cloneNode(false);//false
4212
- }
4213
- node2.ownerDocument = doc;
4214
- node2.parentNode = null;
4215
- if(deep){
4216
- var child = node.firstChild;
4217
- while(child){
4218
- node2.appendChild(importNode(doc,child,deep));
4219
- child = child.nextSibling;
4220
- }
4221
- }
4222
- return node2;
4223
- }
4224
- //
4225
- //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
4226
- // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
4227
- function cloneNode(doc,node,deep){
4228
- var node2 = new node.constructor();
4229
- for(var n in node){
4230
- var v = node[n];
4231
- if(typeof v != 'object' ){
4232
- if(v != node2[n]){
4233
- node2[n] = v;
4234
- }
4235
- }
4236
- }
4237
- if(node.childNodes){
4238
- node2.childNodes = new NodeList();
4239
- }
4240
- node2.ownerDocument = doc;
4241
- switch (node2.nodeType) {
4242
- case ELEMENT_NODE:
4243
- var attrs = node.attributes;
4244
- var attrs2 = node2.attributes = new NamedNodeMap();
4245
- var len = attrs.length;
4246
- attrs2._ownerElement = node2;
4247
- for(var i=0;i<len;i++){
4248
- node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
4249
- }
4250
- break; case ATTRIBUTE_NODE:
4251
- deep = true;
4252
- }
4253
- if(deep){
4254
- var child = node.firstChild;
4255
- while(child){
4256
- node2.appendChild(cloneNode(doc,child,deep));
4257
- child = child.nextSibling;
4258
- }
4259
- }
4260
- return node2;
4261
- }
4262
-
4263
- function __set__(object,key,value){
4264
- object[key] = value;
4265
- }
4266
- //do dynamic
4267
- try{
4268
- if(Object.defineProperty){
4269
- Object.defineProperty(LiveNodeList.prototype,'length',{
4270
- get:function(){
4271
- _updateLiveList(this);
4272
- return this.$$length;
4273
- }
4274
- });
4275
- Object.defineProperty(Node.prototype,'textContent',{
4276
- get:function(){
4277
- return getTextContent(this);
4278
- },
4279
- set:function(data){
4280
- switch(this.nodeType){
4281
- case ELEMENT_NODE:
4282
- case DOCUMENT_FRAGMENT_NODE:
4283
- while(this.firstChild){
4284
- this.removeChild(this.firstChild);
4285
- }
4286
- if(data || String(data)){
4287
- this.appendChild(this.ownerDocument.createTextNode(data));
4288
- }
4289
- break;
4290
- default:
4291
- //TODO:
4292
- this.data = data;
4293
- this.value = data;
4294
- this.nodeValue = data;
4295
- }
4296
- }
4297
- });
4298
-
4299
- function getTextContent(node){
4300
- switch(node.nodeType){
4301
- case ELEMENT_NODE:
4302
- case DOCUMENT_FRAGMENT_NODE:
4303
- var buf = [];
4304
- node = node.firstChild;
4305
- while(node){
4306
- if(node.nodeType!==7 && node.nodeType !==8){
4307
- buf.push(getTextContent(node));
4308
- }
4309
- node = node.nextSibling;
4310
- }
4311
- return buf.join('');
4312
- default:
4313
- return node.nodeValue;
4314
- }
4315
- }
4316
- __set__ = function(object,key,value){
4317
- //console.log(value)
4318
- object['$$'+key] = value;
4319
- };
4320
- }
4321
- }catch(e){//ie8
4322
- }
4323
-
4324
- //if(typeof require == 'function'){
4325
- dom.Node = Node;
4326
- dom.DOMException = DOMException;
4327
- dom.DOMImplementation = DOMImplementation$1;
4328
- dom.XMLSerializer = XMLSerializer;
4329
-
4330
- function DOMParser(options){
4331
- this.options = options ||{locator:{}};
4332
- }
4333
-
4334
- DOMParser.prototype.parseFromString = function(source,mimeType){
4335
- var options = this.options;
4336
- var sax = new XMLReader();
4337
- var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
4338
- var errorHandler = options.errorHandler;
4339
- var locator = options.locator;
4340
- var defaultNSMap = options.xmlns||{};
4341
- var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
4342
- var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
4343
- if(locator){
4344
- domBuilder.setDocumentLocator(locator);
4345
- }
4346
-
4347
- sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
4348
- sax.domBuilder = options.domBuilder || domBuilder;
4349
- if(isHTML){
4350
- defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
4351
- }
4352
- defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
4353
- if(source && typeof source === 'string'){
4354
- sax.parse(source,defaultNSMap,entityMap);
4355
- }else {
4356
- sax.errorHandler.error("invalid doc source");
4357
- }
4358
- return domBuilder.doc;
4359
- };
4360
- function buildErrorHandler(errorImpl,domBuilder,locator){
4361
- if(!errorImpl){
4362
- if(domBuilder instanceof DOMHandler){
4363
- return domBuilder;
4364
- }
4365
- errorImpl = domBuilder ;
4366
- }
4367
- var errorHandler = {};
4368
- var isCallback = errorImpl instanceof Function;
4369
- locator = locator||{};
4370
- function build(key){
4371
- var fn = errorImpl[key];
4372
- if(!fn && isCallback){
4373
- fn = errorImpl.length == 2?function(msg){errorImpl(key,msg);}:errorImpl;
4374
- }
4375
- errorHandler[key] = fn && function(msg){
4376
- fn('[xmldom '+key+']\t'+msg+_locator(locator));
4377
- }||function(){};
4378
- }
4379
- build('warning');
4380
- build('error');
4381
- build('fatalError');
4382
- return errorHandler;
4383
- }
4384
-
4385
- //console.log('#\n\n\n\n\n\n\n####')
4386
- /**
4387
- * +ContentHandler+ErrorHandler
4388
- * +LexicalHandler+EntityResolver2
4389
- * -DeclHandler-DTDHandler
4390
- *
4391
- * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
4392
- * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
4393
- * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
4394
- */
4395
- function DOMHandler() {
4396
- this.cdata = false;
4397
- }
4398
- function position(locator,node){
4399
- node.lineNumber = locator.lineNumber;
4400
- node.columnNumber = locator.columnNumber;
4401
- }
4402
- /**
4403
- * @see org.xml.sax.ContentHandler#startDocument
4404
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
4405
- */
4406
- DOMHandler.prototype = {
4407
- startDocument : function() {
4408
- this.doc = new DOMImplementation().createDocument(null, null, null);
4409
- if (this.locator) {
4410
- this.doc.documentURI = this.locator.systemId;
4411
- }
4412
- },
4413
- startElement:function(namespaceURI, localName, qName, attrs) {
4414
- var doc = this.doc;
4415
- var el = doc.createElementNS(namespaceURI, qName||localName);
4416
- var len = attrs.length;
4417
- appendElement(this, el);
4418
- this.currentElement = el;
4419
-
4420
- this.locator && position(this.locator,el);
4421
- for (var i = 0 ; i < len; i++) {
4422
- var namespaceURI = attrs.getURI(i);
4423
- var value = attrs.getValue(i);
4424
- var qName = attrs.getQName(i);
4425
- var attr = doc.createAttributeNS(namespaceURI, qName);
4426
- this.locator &&position(attrs.getLocator(i),attr);
4427
- attr.value = attr.nodeValue = value;
4428
- el.setAttributeNode(attr);
4429
- }
4430
- },
4431
- endElement:function(namespaceURI, localName, qName) {
4432
- var current = this.currentElement;
4433
- current.tagName;
4434
- this.currentElement = current.parentNode;
4435
- },
4436
- startPrefixMapping:function(prefix, uri) {
4437
- },
4438
- endPrefixMapping:function(prefix) {
4439
- },
4440
- processingInstruction:function(target, data) {
4441
- var ins = this.doc.createProcessingInstruction(target, data);
4442
- this.locator && position(this.locator,ins);
4443
- appendElement(this, ins);
4444
- },
4445
- ignorableWhitespace:function(ch, start, length) {
4446
- },
4447
- characters:function(chars, start, length) {
4448
- chars = _toString.apply(this,arguments);
4449
- //console.log(chars)
4450
- if(chars){
4451
- if (this.cdata) {
4452
- var charNode = this.doc.createCDATASection(chars);
4453
- } else {
4454
- var charNode = this.doc.createTextNode(chars);
4455
- }
4456
- if(this.currentElement){
4457
- this.currentElement.appendChild(charNode);
4458
- }else if(/^\s*$/.test(chars)){
4459
- this.doc.appendChild(charNode);
4460
- //process xml
4461
- }
4462
- this.locator && position(this.locator,charNode);
4463
- }
4464
- },
4465
- skippedEntity:function(name) {
4466
- },
4467
- endDocument:function() {
4468
- this.doc.normalize();
4469
- },
4470
- setDocumentLocator:function (locator) {
4471
- if(this.locator = locator){// && !('lineNumber' in locator)){
4472
- locator.lineNumber = 0;
4473
- }
4474
- },
4475
- //LexicalHandler
4476
- comment:function(chars, start, length) {
4477
- chars = _toString.apply(this,arguments);
4478
- var comm = this.doc.createComment(chars);
4479
- this.locator && position(this.locator,comm);
4480
- appendElement(this, comm);
4481
- },
4482
-
4483
- startCDATA:function() {
4484
- //used in characters() methods
4485
- this.cdata = true;
4486
- },
4487
- endCDATA:function() {
4488
- this.cdata = false;
4489
- },
4490
-
4491
- startDTD:function(name, publicId, systemId) {
4492
- var impl = this.doc.implementation;
4493
- if (impl && impl.createDocumentType) {
4494
- var dt = impl.createDocumentType(name, publicId, systemId);
4495
- this.locator && position(this.locator,dt);
4496
- appendElement(this, dt);
4497
- }
4498
- },
4499
- /**
4500
- * @see org.xml.sax.ErrorHandler
4501
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
4502
- */
4503
- warning:function(error) {
4504
- console.warn('[xmldom warning]\t'+error,_locator(this.locator));
4505
- },
4506
- error:function(error) {
4507
- console.error('[xmldom error]\t'+error,_locator(this.locator));
4508
- },
4509
- fatalError:function(error) {
4510
- throw new ParseError(error, this.locator);
4511
- }
4512
- };
4513
- function _locator(l){
4514
- if(l){
4515
- return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
4516
- }
4517
- }
4518
- function _toString(chars,start,length){
4519
- if(typeof chars == 'string'){
4520
- return chars.substr(start,length)
4521
- }else {//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
4522
- if(chars.length >= start+length || start){
4523
- return new java.lang.String(chars,start,length)+'';
4524
- }
4525
- return chars;
4526
- }
4527
- }
4528
-
4529
- /*
4530
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
4531
- * used method of org.xml.sax.ext.LexicalHandler:
4532
- * #comment(chars, start, length)
4533
- * #startCDATA()
4534
- * #endCDATA()
4535
- * #startDTD(name, publicId, systemId)
4536
- *
4537
- *
4538
- * IGNORED method of org.xml.sax.ext.LexicalHandler:
4539
- * #endDTD()
4540
- * #startEntity(name)
4541
- * #endEntity(name)
4542
- *
4543
- *
4544
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
4545
- * IGNORED method of org.xml.sax.ext.DeclHandler
4546
- * #attributeDecl(eName, aName, type, mode, value)
4547
- * #elementDecl(name, model)
4548
- * #externalEntityDecl(name, publicId, systemId)
4549
- * #internalEntityDecl(name, value)
4550
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
4551
- * IGNORED method of org.xml.sax.EntityResolver2
4552
- * #resolveEntity(String name,String publicId,String baseURI,String systemId)
4553
- * #resolveEntity(publicId, systemId)
4554
- * #getExternalSubset(name, baseURI)
4555
- * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
4556
- * IGNORED method of org.xml.sax.DTDHandler
4557
- * #notationDecl(name, publicId, systemId) {};
4558
- * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
4559
- */
4560
- "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
4561
- DOMHandler.prototype[key] = function(){return null};
4562
- });
4563
-
4564
- /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
4565
- function appendElement (hander,node) {
4566
- if (!hander.currentElement) {
4567
- hander.doc.appendChild(node);
4568
- } else {
4569
- hander.currentElement.appendChild(node);
4570
- }
4571
- }//appendChild and setAttributeNS are preformance key
4572
-
4573
- //if(typeof require == 'function'){
4574
- var htmlEntity = entities;
4575
- var sax = sax$1;
4576
- var XMLReader = sax.XMLReader;
4577
- var ParseError = sax.ParseError;
4578
- var DOMImplementation = domParser.DOMImplementation = dom.DOMImplementation;
4579
- domParser.XMLSerializer = dom.XMLSerializer ;
4580
- domParser.DOMParser = DOMParser;
4581
- domParser.__DOMHandler = DOMHandler;
4582
-
4583
- var parseJson$1 = {};
4584
-
4585
- Object.defineProperty(parseJson$1, "__esModule", { value: true });
4586
- parseJson$1.parseJson = void 0;
4587
- /**
4588
- * Parses a given string into JSON.
4589
- * Gracefully handles invalid JSON by returning `null`.
4590
- */
4591
- function parseJson(data) {
4592
- try {
4593
- var json = JSON.parse(data);
4594
- return json;
4595
- }
4596
- catch (_) {
4597
- return null;
4598
- }
4599
- }
4600
- parseJson$1.parseJson = parseJson;
4601
-
4602
- var bufferFrom$1 = {};
4603
-
4604
- Object.defineProperty(bufferFrom$1, "__esModule", { value: true });
4605
- bufferFrom$1.bufferFrom = void 0;
4606
- /**
4607
- * Convert a given string into a `Uint8Array`.
4608
- * We don't use `TextEncoder` because it's unavailable in some environments.
4609
- */
4610
- function bufferFrom(init) {
4611
- var encodedString = encodeURIComponent(init);
4612
- var binaryString = encodedString.replace(/%([0-9A-F]{2})/g, function (_, char) {
4613
- return String.fromCharCode(('0x' + char));
4614
- });
4615
- var buffer = new Uint8Array(binaryString.length);
4616
- Array.prototype.forEach.call(binaryString, function (char, index) {
4617
- buffer[index] = char.charCodeAt(0);
4618
- });
4619
- return buffer;
4620
- }
4621
- bufferFrom$1.bufferFrom = bufferFrom;
4622
-
4623
- var createEvent$1 = {};
4624
-
4625
- var EventPolyfill$1 = {};
4626
-
4627
- Object.defineProperty(EventPolyfill$1, "__esModule", { value: true });
4628
- EventPolyfill$1.EventPolyfill = void 0;
4629
- var EventPolyfill = /** @class */ (function () {
4630
- function EventPolyfill(type, options) {
4631
- this.AT_TARGET = 0;
4632
- this.BUBBLING_PHASE = 0;
4633
- this.CAPTURING_PHASE = 0;
4634
- this.NONE = 0;
4635
- this.type = '';
4636
- this.srcElement = null;
4637
- this.currentTarget = null;
4638
- this.eventPhase = 0;
4639
- this.isTrusted = true;
4640
- this.composed = false;
4641
- this.cancelable = true;
4642
- this.defaultPrevented = false;
4643
- this.bubbles = true;
4644
- this.lengthComputable = true;
4645
- this.loaded = 0;
4646
- this.total = 0;
4647
- this.cancelBubble = false;
4648
- this.returnValue = true;
4649
- this.type = type;
4650
- this.target = (options === null || options === void 0 ? void 0 : options.target) || null;
4651
- this.currentTarget = (options === null || options === void 0 ? void 0 : options.currentTarget) || null;
4652
- this.timeStamp = Date.now();
4653
- }
4654
- EventPolyfill.prototype.composedPath = function () {
4655
- return [];
4656
- };
4657
- EventPolyfill.prototype.initEvent = function (type, bubbles, cancelable) {
4658
- this.type = type;
4659
- this.bubbles = !!bubbles;
4660
- this.cancelable = !!cancelable;
4661
- };
4662
- EventPolyfill.prototype.preventDefault = function () {
4663
- this.defaultPrevented = true;
4664
- };
4665
- EventPolyfill.prototype.stopPropagation = function () { };
4666
- EventPolyfill.prototype.stopImmediatePropagation = function () { };
4667
- return EventPolyfill;
4668
- }());
4669
- EventPolyfill$1.EventPolyfill = EventPolyfill;
4670
-
4671
- var ProgressEventPolyfill$1 = {};
4672
-
4673
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
4674
- var extendStatics = function (d, b) {
4675
- extendStatics = Object.setPrototypeOf ||
4676
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
4677
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
4678
- return extendStatics(d, b);
4679
- };
4680
- return function (d, b) {
4681
- if (typeof b !== "function" && b !== null)
4682
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
4683
- extendStatics(d, b);
4684
- function __() { this.constructor = d; }
4685
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4686
- };
4687
- })();
4688
- Object.defineProperty(ProgressEventPolyfill$1, "__esModule", { value: true });
4689
- ProgressEventPolyfill$1.ProgressEventPolyfill = void 0;
4690
- var EventPolyfill_1$1 = EventPolyfill$1;
4691
- var ProgressEventPolyfill = /** @class */ (function (_super) {
4692
- __extends(ProgressEventPolyfill, _super);
4693
- function ProgressEventPolyfill(type, init) {
4694
- var _this = _super.call(this, type) || this;
4695
- _this.lengthComputable = (init === null || init === void 0 ? void 0 : init.lengthComputable) || false;
4696
- _this.composed = (init === null || init === void 0 ? void 0 : init.composed) || false;
4697
- _this.loaded = (init === null || init === void 0 ? void 0 : init.loaded) || 0;
4698
- _this.total = (init === null || init === void 0 ? void 0 : init.total) || 0;
4699
- return _this;
4700
- }
4701
- return ProgressEventPolyfill;
4702
- }(EventPolyfill_1$1.EventPolyfill));
4703
- ProgressEventPolyfill$1.ProgressEventPolyfill = ProgressEventPolyfill;
4704
-
4705
- Object.defineProperty(createEvent$1, "__esModule", { value: true });
4706
- createEvent$1.createEvent = void 0;
4707
- var EventPolyfill_1 = EventPolyfill$1;
4708
- var ProgressEventPolyfill_1 = ProgressEventPolyfill$1;
4709
- var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined';
4710
- function createEvent(target, type, init) {
4711
- var progressEvents = [
4712
- 'error',
4713
- 'progress',
4714
- 'loadstart',
4715
- 'loadend',
4716
- 'load',
4717
- 'timeout',
4718
- 'abort',
4719
- ];
4720
- /**
4721
- * `ProgressEvent` is not supported in React Native.
4722
- * @see https://github.com/mswjs/interceptors/issues/40
4723
- */
4724
- var ProgressEventClass = SUPPORTS_PROGRESS_EVENT
4725
- ? ProgressEvent
4726
- : ProgressEventPolyfill_1.ProgressEventPolyfill;
4727
- var event = progressEvents.includes(type)
4728
- ? new ProgressEventClass(type, {
4729
- lengthComputable: true,
4730
- loaded: (init === null || init === void 0 ? void 0 : init.loaded) || 0,
4731
- total: (init === null || init === void 0 ? void 0 : init.total) || 0,
4732
- })
4733
- : new EventPolyfill_1.EventPolyfill(type, {
4734
- target: target,
4735
- currentTarget: target,
4736
- });
4737
- return event;
4738
- }
4739
- createEvent$1.createEvent = createEvent;
4740
-
4741
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
4742
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4743
- return new (P || (P = Promise))(function (resolve, reject) {
4744
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
4745
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
4746
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
4747
- step((generator = generator.apply(thisArg, _arguments || [])).next());
4748
- });
4749
- };
4750
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
4751
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
4752
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
4753
- function verb(n) { return function (v) { return step([n, v]); }; }
4754
- function step(op) {
4755
- if (f) throw new TypeError("Generator is already executing.");
4756
- while (_) try {
4757
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
4758
- if (y = 0, t) op = [op[0] & 2, t.value];
4759
- switch (op[0]) {
4760
- case 0: case 1: t = op; break;
4761
- case 4: _.label++; return { value: op[1], done: false };
4762
- case 5: _.label++; y = op[1]; op = [0]; continue;
4763
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
4764
- default:
4765
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
4766
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
4767
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
4768
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
4769
- if (t[2]) _.ops.pop();
4770
- _.trys.pop(); continue;
4771
- }
4772
- op = body.call(thisArg, _);
4773
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
4774
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
4775
- }
4776
- };
4777
- var __values = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
4778
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4779
- if (m) return m.call(o);
4780
- if (o && typeof o.length === "number") return {
4781
- next: function () {
4782
- if (o && i >= o.length) o = void 0;
4783
- return { value: o && o[i++], done: !o };
4784
- }
4785
- };
4786
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
4787
- };
4788
- var __read = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
4789
- var m = typeof Symbol === "function" && o[Symbol.iterator];
4790
- if (!m) return o;
4791
- var i = m.call(o), r, ar = [], e;
4792
- try {
4793
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
4794
- }
4795
- catch (error) { e = { error: error }; }
4796
- finally {
4797
- try {
4798
- if (r && !r.done && (m = i["return"])) m.call(i);
4799
- }
4800
- finally { if (e) throw e.error; }
4801
- }
4802
- return ar;
4803
- };
4804
- Object.defineProperty(XMLHttpRequestOverride, "__esModule", { value: true });
4805
- XMLHttpRequestOverride.createXMLHttpRequestOverride = void 0;
4806
- /**
4807
- * XMLHttpRequest override class.
4808
- * Inspired by https://github.com/marvinhagemeister/xhr-mocklet.
4809
- */
4810
- var until_1 = lib$2;
4811
- var headers_utils_1 = lib$4;
4812
- var xmldom_1 = domParser;
4813
- var parseJson_1 = parseJson$1;
4814
- var toIsoResponse_1 = toIsoResponse$1;
4815
- var uuid_1 = uuid;
4816
- var bufferFrom_1 = bufferFrom$1;
4817
- var createEvent_1 = createEvent$1;
4818
- var createDebug = require$$3;
4819
- var createXMLHttpRequestOverride = function (options) {
4820
- var _a;
4821
- var pureXMLHttpRequest = options.pureXMLHttpRequest, observer = options.observer, resolver = options.resolver;
4822
- var debug = createDebug('XHR');
4823
- return _a = /** @class */ (function () {
4824
- function XMLHttpRequestOverride() {
4825
- // Collection of events modified by `addEventListener`/`removeEventListener` calls.
4826
- this._events = [];
4827
- this.UNSENT = 0;
4828
- this.OPENED = 1;
4829
- this.HEADERS_RECEIVED = 2;
4830
- this.LOADING = 3;
4831
- this.DONE = 4;
4832
- this.onreadystatechange = null;
4833
- /* Events */
4834
- this.onabort = null;
4835
- this.onerror = null;
4836
- this.onload = null;
4837
- this.onloadend = null;
4838
- this.onloadstart = null;
4839
- this.onprogress = null;
4840
- this.ontimeout = null;
4841
- this.url = '';
4842
- this.method = 'GET';
4843
- this.readyState = this.UNSENT;
4844
- this.withCredentials = false;
4845
- this.status = 200;
4846
- this.statusText = 'OK';
4847
- this.data = '';
4848
- this.response = '';
4849
- this.responseType = 'text';
4850
- this.responseText = '';
4851
- this.responseXML = null;
4852
- this.responseURL = '';
4853
- this.upload = null;
4854
- this.timeout = 0;
4855
- this._requestHeaders = new headers_utils_1.Headers();
4856
- this._responseHeaders = new headers_utils_1.Headers();
4857
- }
4858
- XMLHttpRequestOverride.prototype.setReadyState = function (nextState) {
4859
- if (nextState === this.readyState) {
4860
- return;
4861
- }
4862
- debug('readyState change %d -> %d', this.readyState, nextState);
4863
- this.readyState = nextState;
4864
- if (nextState !== this.UNSENT) {
4865
- debug('triggerring readystate change...');
4866
- this.trigger('readystatechange');
4867
- }
4868
- };
4869
- /**
4870
- * Triggers both direct callback and attached event listeners
4871
- * for the given event.
4872
- */
4873
- XMLHttpRequestOverride.prototype.trigger = function (eventName, options) {
4874
- var e_1, _a;
4875
- debug('trigger "%s" (%d)', eventName, this.readyState);
4876
- debug('resolve listener for event "%s"', eventName);
4877
- // @ts-expect-error XMLHttpRequest class has no index signature.
4878
- var callback = this["on" + eventName];
4879
- callback === null || callback === void 0 ? void 0 : callback.call(this, createEvent_1.createEvent(this, eventName, options));
4880
- try {
4881
- for (var _b = __values(this._events), _c = _b.next(); !_c.done; _c = _b.next()) {
4882
- var event_1 = _c.value;
4883
- if (event_1.name === eventName) {
4884
- debug('calling mock event listener "%s" (%d)', eventName, this.readyState);
4885
- event_1.listener.call(this, createEvent_1.createEvent(this, eventName, options));
4886
- }
4887
- }
4888
- }
4889
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
4890
- finally {
4891
- try {
4892
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4893
- }
4894
- finally { if (e_1) throw e_1.error; }
4895
- }
4896
- return this;
4897
- };
4898
- XMLHttpRequestOverride.prototype.reset = function () {
4899
- debug('reset');
4900
- this.setReadyState(this.UNSENT);
4901
- this.status = 200;
4902
- this.statusText = 'OK';
4903
- this.data = '';
4904
- this.response = null;
4905
- this.responseText = null;
4906
- this.responseXML = null;
4907
- this._requestHeaders = new headers_utils_1.Headers();
4908
- this._responseHeaders = new headers_utils_1.Headers();
4909
- };
4910
- XMLHttpRequestOverride.prototype.open = function (method, url, async, user, password) {
4911
- if (async === void 0) { async = true; }
4912
- return __awaiter(this, void 0, void 0, function () {
4913
- return __generator(this, function (_a) {
4914
- debug = createDebug("XHR " + method + " " + url);
4915
- debug('open', { method: method, url: url, async: async, user: user, password: password });
4916
- this.reset();
4917
- this.setReadyState(this.OPENED);
4918
- if (typeof url === 'undefined') {
4919
- this.url = method;
4920
- this.method = 'GET';
4921
- }
4922
- else {
4923
- this.url = url;
4924
- this.method = method;
4925
- this.async = async;
4926
- this.user = user;
4927
- this.password = password;
4928
- }
4929
- return [2 /*return*/];
4930
- });
4931
- });
4932
- };
4933
- XMLHttpRequestOverride.prototype.send = function (data) {
4934
- var _this = this;
4935
- debug('send %s %s', this.method, this.url);
4936
- this.data = data || '';
4937
- var url;
4938
- try {
4939
- url = new URL(this.url);
4940
- }
4941
- catch (error) {
4942
- // Assume a relative URL, if construction of a new `URL` instance fails.
4943
- // Since `XMLHttpRequest` always executed in a DOM-like environment,
4944
- // resolve the relative request URL against the current window location.
4945
- url = new URL(this.url, window.location.href);
4946
- }
4947
- debug('request headers', this._requestHeaders);
4948
- // Create an intercepted request instance exposed to the request intercepting middleware.
4949
- var isoRequest = {
4950
- id: uuid_1.uuidv4(),
4951
- url: url,
4952
- method: this.method,
4953
- body: this.data,
4954
- headers: this._requestHeaders,
4955
- };
4956
- observer.emit('request', isoRequest);
4957
- debug('awaiting mocked response...');
4958
- Promise.resolve(until_1.until(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
4959
- return [2 /*return*/, resolver(isoRequest, this)];
4960
- }); }); })).then(function (_a) {
4961
- var _b;
4962
- var _c = __read(_a, 2), middlewareException = _c[0], mockedResponse = _c[1];
4963
- // When the request middleware throws an exception, error the request.
4964
- // This cancels the request and is similar to a network error.
4965
- if (middlewareException) {
4966
- debug('middleware function threw an exception!', middlewareException);
4967
- // No way to propagate the actual error message.
4968
- _this.trigger('error');
4969
- _this.abort();
4970
- return;
4971
- }
4972
- // Return a mocked response, if provided in the middleware.
4973
- if (mockedResponse) {
4974
- debug('received mocked response', mockedResponse);
4975
- // Trigger a loadstart event to indicate the initialization of the fetch.
4976
- _this.trigger('loadstart');
4977
- _this.status = mockedResponse.status || 200;
4978
- _this.statusText = mockedResponse.statusText || 'OK';
4979
- _this._responseHeaders = mockedResponse.headers
4980
- ? headers_utils_1.objectToHeaders(mockedResponse.headers)
4981
- : new headers_utils_1.Headers();
4982
- debug('set response status', _this.status, _this.statusText);
4983
- debug('set response headers', _this._responseHeaders);
4984
- // Mark that response headers has been received
4985
- // and trigger a ready state event to reflect received headers
4986
- // in a custom `onreadystatechange` callback.
4987
- _this.setReadyState(_this.HEADERS_RECEIVED);
4988
- debug('response type', _this.responseType);
4989
- _this.response = _this.getResponseBody(mockedResponse.body);
4990
- _this.responseText = mockedResponse.body || '';
4991
- _this.responseXML = _this.getResponseXML();
4992
- debug('set response body', _this.response);
4993
- if (mockedResponse.body && _this.response) {
4994
- _this.setReadyState(_this.LOADING);
4995
- // Presense of the mocked response implies a response body (not null).
4996
- // Presense of the coerced `this.response` implies the mocked body is valid.
4997
- var bodyBuffer = bufferFrom_1.bufferFrom(mockedResponse.body);
4998
- // Trigger a progress event based on the mocked response body.
4999
- _this.trigger('progress', {
5000
- loaded: bodyBuffer.length,
5001
- total: bodyBuffer.length,
5002
- });
5003
- }
5004
- /**
5005
- * Explicitly mark the request as done so its response never hangs.
5006
- * @see https://github.com/mswjs/interceptors/issues/13
5007
- */
5008
- _this.setReadyState(_this.DONE);
5009
- // Trigger a load event to indicate the fetch has succeeded.
5010
- _this.trigger('load');
5011
- // Trigger a loadend event to indicate the fetch has completed.
5012
- _this.trigger('loadend');
5013
- observer.emit('response', isoRequest, toIsoResponse_1.toIsoResponse(mockedResponse));
5014
- }
5015
- else {
5016
- debug('no mocked response received!');
5017
- // Perform an original request, when the request middleware returned no mocked response.
5018
- var originalRequest_1 = new pureXMLHttpRequest();
5019
- debug('opening an original request %s %s', _this.method, _this.url);
5020
- originalRequest_1.open(_this.method, _this.url, (_b = _this.async) !== null && _b !== void 0 ? _b : true, _this.user, _this.password);
5021
- // Reflect a successful state of the original request
5022
- // on the patched instance.
5023
- originalRequest_1.addEventListener('load', function () {
5024
- debug('original "onload"');
5025
- _this.status = originalRequest_1.status;
5026
- _this.statusText = originalRequest_1.statusText;
5027
- _this.responseURL = originalRequest_1.responseURL;
5028
- _this.responseType = originalRequest_1.responseType;
5029
- _this.response = originalRequest_1.response;
5030
- _this.responseText = originalRequest_1.responseText;
5031
- _this.responseXML = originalRequest_1.responseXML;
5032
- debug('set mock request readyState to DONE');
5033
- // Explicitly mark the mocked request instance as done
5034
- // so the response never hangs.
5035
- /**
5036
- * @note `readystatechange` listener is called TWICE
5037
- * in the case of unhandled request.
5038
- */
5039
- _this.setReadyState(_this.DONE);
5040
- debug('received original response', _this.status, _this.statusText);
5041
- debug('original response body:', _this.response);
5042
- var responseHeaders = originalRequest_1.getAllResponseHeaders();
5043
- debug('original response headers:\n', responseHeaders);
5044
- _this._responseHeaders = headers_utils_1.stringToHeaders(responseHeaders);
5045
- debug('original response headers (normalized)', _this._responseHeaders);
5046
- debug('original response finished');
5047
- observer.emit('response', isoRequest, {
5048
- status: originalRequest_1.status,
5049
- statusText: originalRequest_1.statusText,
5050
- headers: _this._responseHeaders,
5051
- body: originalRequest_1.response,
5052
- });
5053
- });
5054
- // Assign callbacks and event listeners from the intercepted XHR instance
5055
- // to the original XHR instance.
5056
- _this.propagateCallbacks(originalRequest_1);
5057
- _this.propagateListeners(originalRequest_1);
5058
- _this.propagateHeaders(originalRequest_1, _this._requestHeaders);
5059
- if (_this.async) {
5060
- originalRequest_1.timeout = _this.timeout;
5061
- }
5062
- debug('send', _this.data);
5063
- originalRequest_1.send(_this.data);
5064
- }
5065
- });
5066
- };
5067
- XMLHttpRequestOverride.prototype.abort = function () {
5068
- debug('abort');
5069
- if (this.readyState > this.UNSENT && this.readyState < this.DONE) {
5070
- this.setReadyState(this.UNSENT);
5071
- this.trigger('abort');
5072
- }
5073
- };
5074
- XMLHttpRequestOverride.prototype.dispatchEvent = function () {
5075
- return false;
5076
- };
5077
- XMLHttpRequestOverride.prototype.setRequestHeader = function (name, value) {
5078
- debug('set request header "%s" to "%s"', name, value);
5079
- this._requestHeaders.append(name, value);
5080
- };
5081
- XMLHttpRequestOverride.prototype.getResponseHeader = function (name) {
5082
- debug('get response header "%s"', name);
5083
- if (this.readyState < this.HEADERS_RECEIVED) {
5084
- debug('cannot return a header: headers not received (state: %s)', this.readyState);
5085
- return null;
5086
- }
5087
- var headerValue = this._responseHeaders.get(name);
5088
- debug('resolved response header "%s" to "%s"', name, headerValue, this._responseHeaders);
5089
- return headerValue;
5090
- };
5091
- XMLHttpRequestOverride.prototype.getAllResponseHeaders = function () {
5092
- debug('get all response headers');
5093
- if (this.readyState < this.HEADERS_RECEIVED) {
5094
- debug('cannot return headers: headers not received (state: %s)', this.readyState);
5095
- return '';
5096
- }
5097
- return headers_utils_1.headersToString(this._responseHeaders);
5098
- };
5099
- XMLHttpRequestOverride.prototype.addEventListener = function (name, listener) {
5100
- debug('addEventListener', name, listener);
5101
- this._events.push({
5102
- name: name,
5103
- listener: listener,
5104
- });
5105
- };
5106
- XMLHttpRequestOverride.prototype.removeEventListener = function (name, listener) {
5107
- debug('removeEventListener', name, listener);
5108
- this._events = this._events.filter(function (storedEvent) {
5109
- return storedEvent.name !== name && storedEvent.listener !== listener;
5110
- });
5111
- };
5112
- XMLHttpRequestOverride.prototype.overrideMimeType = function () { };
5113
- /**
5114
- * Resolves the response based on the `responseType` value.
5115
- */
5116
- XMLHttpRequestOverride.prototype.getResponseBody = function (body) {
5117
- // Handle an improperly set "null" value of the mocked response body.
5118
- var textBody = body !== null && body !== void 0 ? body : '';
5119
- debug('coerced response body to', textBody);
5120
- switch (this.responseType) {
5121
- case 'json': {
5122
- debug('resolving response body as JSON');
5123
- return parseJson_1.parseJson(textBody);
5124
- }
5125
- case 'blob': {
5126
- var blobType = this.getResponseHeader('content-type') || 'text/plain';
5127
- debug('resolving response body as Blob', { type: blobType });
5128
- return new Blob([textBody], {
5129
- type: blobType,
5130
- });
5131
- }
5132
- case 'arraybuffer': {
5133
- debug('resolving response body as ArrayBuffer');
5134
- var arrayBuffer = bufferFrom_1.bufferFrom(textBody);
5135
- return arrayBuffer;
5136
- }
5137
- default:
5138
- return textBody;
5139
- }
5140
- };
5141
- XMLHttpRequestOverride.prototype.getResponseXML = function () {
5142
- var contentType = this.getResponseHeader('Content-Type');
5143
- if (contentType === 'application/xml' || contentType === 'text/xml') {
5144
- return new xmldom_1.DOMParser().parseFromString(this.responseText, contentType);
5145
- }
5146
- return null;
5147
- };
5148
- /**
5149
- * Propagates mock XMLHttpRequest instance callbacks
5150
- * to the given XMLHttpRequest instance.
5151
- */
5152
- XMLHttpRequestOverride.prototype.propagateCallbacks = function (request) {
5153
- request.onabort = this.abort;
5154
- request.onerror = this.onerror;
5155
- request.ontimeout = this.ontimeout;
5156
- request.onload = this.onload;
5157
- request.onloadstart = this.onloadstart;
5158
- request.onloadend = this.onloadend;
5159
- request.onprogress = this.onprogress;
5160
- request.onreadystatechange = this.onreadystatechange;
5161
- };
5162
- /**
5163
- * Propagates the mock XMLHttpRequest instance listeners
5164
- * to the given XMLHttpRequest instance.
5165
- */
5166
- XMLHttpRequestOverride.prototype.propagateListeners = function (request) {
5167
- debug('propagating request listeners (%d) to the original request', this._events.length, this._events);
5168
- this._events.forEach(function (_a) {
5169
- var name = _a.name, listener = _a.listener;
5170
- request.addEventListener(name, listener);
5171
- });
5172
- };
5173
- XMLHttpRequestOverride.prototype.propagateHeaders = function (request, headers) {
5174
- debug('propagating request headers to the original request', headers);
5175
- // Preserve the request headers casing.
5176
- Object.entries(headers.raw()).forEach(function (_a) {
5177
- var _b = __read(_a, 2), name = _b[0], value = _b[1];
5178
- debug('setting "%s" (%s) header on the original request', name, value);
5179
- request.setRequestHeader(name, value);
5180
- });
5181
- };
5182
- return XMLHttpRequestOverride;
5183
- }()),
5184
- /* Request state */
5185
- _a.UNSENT = 0,
5186
- _a.OPENED = 1,
5187
- _a.HEADERS_RECEIVED = 2,
5188
- _a.LOADING = 3,
5189
- _a.DONE = 4,
5190
- _a;
5191
- };
5192
- XMLHttpRequestOverride.createXMLHttpRequestOverride = createXMLHttpRequestOverride;
5193
-
5194
- Object.defineProperty(XMLHttpRequest, "__esModule", { value: true });
5195
- var interceptXMLHttpRequest_1 = XMLHttpRequest.interceptXMLHttpRequest = void 0;
5196
- var XMLHttpRequestOverride_1 = XMLHttpRequestOverride;
5197
- var debug = require$$3('XHR');
5198
- var pureXMLHttpRequest =
5199
- // Although executed in node, certain processes emulate the DOM-like environment
5200
- // (i.e. `js-dom` in Jest). The `window` object would be avilable in such environments.
5201
- typeof window === 'undefined' ? undefined : window.XMLHttpRequest;
5202
- /**
5203
- * Intercepts requests issued via `XMLHttpRequest`.
5204
- */
5205
- var interceptXMLHttpRequest = function (observer, resolver) {
5206
- if (pureXMLHttpRequest) {
5207
- debug('patching "XMLHttpRequest" module...');
5208
- var XMLHttpRequestOverride = XMLHttpRequestOverride_1.createXMLHttpRequestOverride({
5209
- pureXMLHttpRequest: pureXMLHttpRequest,
5210
- observer: observer,
5211
- resolver: resolver,
5212
- });
5213
- window.XMLHttpRequest = XMLHttpRequestOverride;
5214
- }
5215
- return function () {
5216
- if (pureXMLHttpRequest) {
5217
- debug('restoring modules...');
5218
- window.XMLHttpRequest = pureXMLHttpRequest;
5219
- }
5220
- };
5221
- };
5222
- interceptXMLHttpRequest_1 = XMLHttpRequest.interceptXMLHttpRequest = interceptXMLHttpRequest;
5223
-
5224
1400
  function uuidv4() {
5225
1401
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
5226
1402
  const r = (Math.random() * 16) | 0;
@@ -5270,10 +1446,10 @@ function parseIsomorphicRequest(request) {
5270
1446
  }
5271
1447
 
5272
1448
  function createFallbackRequestListener(context, options) {
5273
- const interceptor = lib.createInterceptor({
5274
- modules: [interceptFetch_1, interceptXMLHttpRequest_1],
1449
+ const interceptor = createInterceptor({
1450
+ modules: [interceptFetch, interceptXMLHttpRequest],
5275
1451
  resolver(request) {
5276
- return __awaiter$3(this, void 0, void 0, function* () {
1452
+ return __awaiter(this, void 0, void 0, function* () {
5277
1453
  const mockedRequest = parseIsomorphicRequest(request);
5278
1454
  return handleRequest(mockedRequest, context.requestHandlers, options, context.emitter, {
5279
1455
  transformResponse(response) {
@@ -5299,7 +1475,7 @@ function createFallbackRequestListener(context, options) {
5299
1475
 
5300
1476
  function createFallbackStart(context) {
5301
1477
  return function start(options) {
5302
- return __awaiter$3(this, void 0, void 0, function* () {
1478
+ return __awaiter(this, void 0, void 0, function* () {
5303
1479
  context.fallbackInterceptor = createFallbackRequestListener(context, options);
5304
1480
  printStartMessage({
5305
1481
  message: 'Mocking enabled (fallback mode).',
@@ -5318,6 +1494,23 @@ function createFallbackStop(context) {
5318
1494
  };
5319
1495
  }
5320
1496
 
1497
+ /**
1498
+ * Pipes all emitted events from one emitter to another.
1499
+ */
1500
+ function pipeEvents(source, destination) {
1501
+ const rawEmit = source.emit;
1502
+ // @ts-ignore
1503
+ if (rawEmit._isPiped) {
1504
+ return;
1505
+ }
1506
+ source.emit = function (event, ...data) {
1507
+ destination.emit(event, ...data);
1508
+ return rawEmit.call(this, event, ...data);
1509
+ };
1510
+ // @ts-ignore
1511
+ source.emit._isPiped = true;
1512
+ }
1513
+
5321
1514
  // Declare the list of event handlers on the module's scope
5322
1515
  // so it persists between Fash refreshes of the application's code.
5323
1516
  let listeners = [];
@@ -5333,15 +1526,18 @@ function setupWorker(...requestHandlers) {
5333
1526
  throw new Error(devUtils.formatMessage('Failed to call "setupWorker" given an Array of request handlers (setupWorker([a, b])), expected to receive each handler individually: setupWorker(a, b).'));
5334
1527
  });
5335
1528
  // Error when attempting to run this function in a Node.js environment.
5336
- if (lib$6.exports.isNodeProcess()) {
1529
+ if (lib$3.exports.isNodeProcess()) {
5337
1530
  throw new Error(devUtils.formatMessage('Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for Node.js environment instead.'));
5338
1531
  }
1532
+ const emitter = new lib$1.StrictEventEmitter();
1533
+ const publicEmitter = new lib$1.StrictEventEmitter();
1534
+ pipeEvents(emitter, publicEmitter);
5339
1535
  const context = {
5340
1536
  startOptions: undefined,
5341
1537
  worker: null,
5342
1538
  registration: null,
5343
1539
  requestHandlers: [...requestHandlers],
5344
- emitter: new lib$3.StrictEventEmitter(),
1540
+ emitter,
5345
1541
  workerChannel: {
5346
1542
  on(eventType, callback) {
5347
1543
  context.events.addListener(navigator.serviceWorker, 'message', (event) => {
@@ -5407,7 +1603,12 @@ function setupWorker(...requestHandlers) {
5407
1603
  : createStop(context);
5408
1604
  return {
5409
1605
  start: prepareStartHandler(startHandler, context),
5410
- stop: stopHandler,
1606
+ stop() {
1607
+ context.events.removeAllListeners();
1608
+ context.emitter.removeAllListeners();
1609
+ publicEmitter.removeAllListeners();
1610
+ stopHandler();
1611
+ },
5411
1612
  use(...handlers) {
5412
1613
  use(context.requestHandlers, ...handlers);
5413
1614
  },
@@ -5434,8 +1635,16 @@ function setupWorker(...requestHandlers) {
5434
1635
  console.groupEnd();
5435
1636
  });
5436
1637
  },
5437
- on(eventType, listener) {
5438
- context.emitter.addListener(eventType, listener);
1638
+ events: {
1639
+ on(...args) {
1640
+ return publicEmitter.on(...args);
1641
+ },
1642
+ removeListener(...args) {
1643
+ return publicEmitter.removeListener(...args);
1644
+ },
1645
+ removeAllListeners(...args) {
1646
+ return publicEmitter.removeAllListeners(...args);
1647
+ },
5439
1648
  },
5440
1649
  };
5441
1650
  }