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