· 6 years ago · Feb 17, 2020, 06:42 PM
1/**
2* @license
3* Copyright Google Inc. All Rights Reserved.
4*
5* Use of this source code is governed by an MIT-style license that can be
6* found in the LICENSE file at https://angular.io/license
7*/
8(function (global, factory) {
9 typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
10 typeof define === 'function' && define.amd ? define(factory) :
11 (factory());
12}(this, (function () { 'use strict';
13
14/**
15 * @license
16 * Copyright Google Inc. All Rights Reserved.
17 *
18 * Use of this source code is governed by an MIT-style license that can be
19 * found in the LICENSE file at https://angular.io/license
20 */
21var Zone$1 = (function (global) {
22 var performance = global['performance'];
23 function mark(name) {
24 performance && performance['mark'] && performance['mark'](name);
25 }
26 function performanceMeasure(name, label) {
27 performance && performance['measure'] && performance['measure'](name, label);
28 }
29 mark('Zone');
30 var checkDuplicate = global[('__zone_symbol__forceDuplicateZoneCheck')] === true;
31 if (global['Zone']) {
32 // if global['Zone'] already exists (maybe zone.js was already loaded or
33 // some other lib also registered a global object named Zone), we may need
34 // to throw an error, but sometimes user may not want this error.
35 // For example,
36 // we have two web pages, page1 includes zone.js, page2 doesn't.
37 // and the 1st time user load page1 and page2, everything work fine,
38 // but when user load page2 again, error occurs because global['Zone'] already exists.
39 // so we add a flag to let user choose whether to throw this error or not.
40 // By default, if existing Zone is from zone.js, we will not throw the error.
41 if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
42 throw new Error('Zone already loaded.');
43 }
44 else {
45 return global['Zone'];
46 }
47 }
48 var Zone = /** @class */ (function () {
49 function Zone(parent, zoneSpec) {
50 this._parent = parent;
51 this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
52 this._properties = zoneSpec && zoneSpec.properties || {};
53 this._zoneDelegate =
54 new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
55 }
56 Zone.assertZonePatched = function () {
57 if (global['Promise'] !== patches['ZoneAwarePromise']) {
58 throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
59 'has been overwritten.\n' +
60 'Most likely cause is that a Promise polyfill has been loaded ' +
61 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
62 'If you must load one, do so before loading zone.js.)');
63 }
64 };
65 Object.defineProperty(Zone, "root", {
66 get: function () {
67 var zone = Zone.current;
68 while (zone.parent) {
69 zone = zone.parent;
70 }
71 return zone;
72 },
73 enumerable: true,
74 configurable: true
75 });
76 Object.defineProperty(Zone, "current", {
77 get: function () {
78 return _currentZoneFrame.zone;
79 },
80 enumerable: true,
81 configurable: true
82 });
83 Object.defineProperty(Zone, "currentTask", {
84 get: function () {
85 return _currentTask;
86 },
87 enumerable: true,
88 configurable: true
89 });
90 Zone.__load_patch = function (name, fn) {
91 if (patches.hasOwnProperty(name)) {
92 if (checkDuplicate) {
93 throw Error('Already loaded patch: ' + name);
94 }
95 }
96 else if (!global['__Zone_disable_' + name]) {
97 var perfName = 'Zone:' + name;
98 mark(perfName);
99 patches[name] = fn(global, Zone, _api);
100 performanceMeasure(perfName, perfName);
101 }
102 };
103 Object.defineProperty(Zone.prototype, "parent", {
104 get: function () {
105 return this._parent;
106 },
107 enumerable: true,
108 configurable: true
109 });
110 Object.defineProperty(Zone.prototype, "name", {
111 get: function () {
112 return this._name;
113 },
114 enumerable: true,
115 configurable: true
116 });
117 Zone.prototype.get = function (key) {
118 var zone = this.getZoneWith(key);
119 if (zone)
120 return zone._properties[key];
121 };
122 Zone.prototype.getZoneWith = function (key) {
123 var current = this;
124 while (current) {
125 if (current._properties.hasOwnProperty(key)) {
126 return current;
127 }
128 current = current._parent;
129 }
130 return null;
131 };
132 Zone.prototype.fork = function (zoneSpec) {
133 if (!zoneSpec)
134 throw new Error('ZoneSpec required!');
135 return this._zoneDelegate.fork(this, zoneSpec);
136 };
137 Zone.prototype.wrap = function (callback, source) {
138 if (typeof callback !== 'function') {
139 throw new Error('Expecting function got: ' + callback);
140 }
141 var _callback = this._zoneDelegate.intercept(this, callback, source);
142 var zone = this;
143 return function () {
144 return zone.runGuarded(_callback, this, arguments, source);
145 };
146 };
147 Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
148 _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
149 try {
150 return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
151 }
152 finally {
153 _currentZoneFrame = _currentZoneFrame.parent;
154 }
155 };
156 Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
157 if (applyThis === void 0) { applyThis = null; }
158 _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
159 try {
160 try {
161 return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
162 }
163 catch (error) {
164 if (this._zoneDelegate.handleError(this, error)) {
165 throw error;
166 }
167 }
168 }
169 finally {
170 _currentZoneFrame = _currentZoneFrame.parent;
171 }
172 };
173 Zone.prototype.runTask = function (task, applyThis, applyArgs) {
174 if (task.zone != this) {
175 throw new Error('A task can only be run in the zone of creation! (Creation: ' +
176 (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
177 }
178 // https://github.com/angular/zone.js/issues/778, sometimes eventTask
179 // will run in notScheduled(canceled) state, we should not try to
180 // run such kind of task but just return
181 if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
182 return;
183 }
184 var reEntryGuard = task.state != running;
185 reEntryGuard && task._transitionTo(running, scheduled);
186 task.runCount++;
187 var previousTask = _currentTask;
188 _currentTask = task;
189 _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
190 try {
191 if (task.type == macroTask && task.data && !task.data.isPeriodic) {
192 task.cancelFn = undefined;
193 }
194 try {
195 return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
196 }
197 catch (error) {
198 if (this._zoneDelegate.handleError(this, error)) {
199 throw error;
200 }
201 }
202 }
203 finally {
204 // if the task's state is notScheduled or unknown, then it has already been cancelled
205 // we should not reset the state to scheduled
206 if (task.state !== notScheduled && task.state !== unknown) {
207 if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
208 reEntryGuard && task._transitionTo(scheduled, running);
209 }
210 else {
211 task.runCount = 0;
212 this._updateTaskCount(task, -1);
213 reEntryGuard &&
214 task._transitionTo(notScheduled, running, notScheduled);
215 }
216 }
217 _currentZoneFrame = _currentZoneFrame.parent;
218 _currentTask = previousTask;
219 }
220 };
221 Zone.prototype.scheduleTask = function (task) {
222 if (task.zone && task.zone !== this) {
223 // check if the task was rescheduled, the newZone
224 // should not be the children of the original zone
225 var newZone = this;
226 while (newZone) {
227 if (newZone === task.zone) {
228 throw Error("can not reschedule task to " + this.name + " which is descendants of the original zone " + task.zone.name);
229 }
230 newZone = newZone.parent;
231 }
232 }
233 task._transitionTo(scheduling, notScheduled);
234 var zoneDelegates = [];
235 task._zoneDelegates = zoneDelegates;
236 task._zone = this;
237 try {
238 task = this._zoneDelegate.scheduleTask(this, task);
239 }
240 catch (err) {
241 // should set task's state to unknown when scheduleTask throw error
242 // because the err may from reschedule, so the fromState maybe notScheduled
243 task._transitionTo(unknown, scheduling, notScheduled);
244 // TODO: @JiaLiPassion, should we check the result from handleError?
245 this._zoneDelegate.handleError(this, err);
246 throw err;
247 }
248 if (task._zoneDelegates === zoneDelegates) {
249 // we have to check because internally the delegate can reschedule the task.
250 this._updateTaskCount(task, 1);
251 }
252 if (task.state == scheduling) {
253 task._transitionTo(scheduled, scheduling);
254 }
255 return task;
256 };
257 Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
258 return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
259 };
260 Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
261 return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
262 };
263 Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
264 return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
265 };
266 Zone.prototype.cancelTask = function (task) {
267 if (task.zone != this)
268 throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
269 (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
270 task._transitionTo(canceling, scheduled, running);
271 try {
272 this._zoneDelegate.cancelTask(this, task);
273 }
274 catch (err) {
275 // if error occurs when cancelTask, transit the state to unknown
276 task._transitionTo(unknown, canceling);
277 this._zoneDelegate.handleError(this, err);
278 throw err;
279 }
280 this._updateTaskCount(task, -1);
281 task._transitionTo(notScheduled, canceling);
282 task.runCount = 0;
283 return task;
284 };
285 Zone.prototype._updateTaskCount = function (task, count) {
286 var zoneDelegates = task._zoneDelegates;
287 if (count == -1) {
288 task._zoneDelegates = null;
289 }
290 for (var i = 0; i < zoneDelegates.length; i++) {
291 zoneDelegates[i]._updateTaskCount(task.type, count);
292 }
293 };
294 Zone.__symbol__ = __symbol__;
295 return Zone;
296 }());
297 var DELEGATE_ZS = {
298 name: '',
299 onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
300 onScheduleTask: function (delegate, _, target, task) {
301 return delegate.scheduleTask(target, task);
302 },
303 onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) {
304 return delegate.invokeTask(target, task, applyThis, applyArgs);
305 },
306 onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
307 };
308 var ZoneDelegate = /** @class */ (function () {
309 function ZoneDelegate(zone, parentDelegate, zoneSpec) {
310 this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 };
311 this.zone = zone;
312 this._parentDelegate = parentDelegate;
313 this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
314 this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
315 this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate.zone);
316 this._interceptZS =
317 zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
318 this._interceptDlgt =
319 zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
320 this._interceptCurrZone =
321 zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate.zone);
322 this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
323 this._invokeDlgt =
324 zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
325 this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate.zone);
326 this._handleErrorZS =
327 zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
328 this._handleErrorDlgt =
329 zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
330 this._handleErrorCurrZone =
331 zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
332 this._scheduleTaskZS =
333 zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
334 this._scheduleTaskDlgt = zoneSpec &&
335 (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
336 this._scheduleTaskCurrZone =
337 zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
338 this._invokeTaskZS =
339 zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
340 this._invokeTaskDlgt =
341 zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
342 this._invokeTaskCurrZone =
343 zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate.zone);
344 this._cancelTaskZS =
345 zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
346 this._cancelTaskDlgt =
347 zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
348 this._cancelTaskCurrZone =
349 zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate.zone);
350 this._hasTaskZS = null;
351 this._hasTaskDlgt = null;
352 this._hasTaskDlgtOwner = null;
353 this._hasTaskCurrZone = null;
354 var zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
355 var parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
356 if (zoneSpecHasTask || parentHasTask) {
357 // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
358 // a case all task related interceptors must go through this ZD. We can't short circuit it.
359 this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
360 this._hasTaskDlgt = parentDelegate;
361 this._hasTaskDlgtOwner = this;
362 this._hasTaskCurrZone = zone;
363 if (!zoneSpec.onScheduleTask) {
364 this._scheduleTaskZS = DELEGATE_ZS;
365 this._scheduleTaskDlgt = parentDelegate;
366 this._scheduleTaskCurrZone = this.zone;
367 }
368 if (!zoneSpec.onInvokeTask) {
369 this._invokeTaskZS = DELEGATE_ZS;
370 this._invokeTaskDlgt = parentDelegate;
371 this._invokeTaskCurrZone = this.zone;
372 }
373 if (!zoneSpec.onCancelTask) {
374 this._cancelTaskZS = DELEGATE_ZS;
375 this._cancelTaskDlgt = parentDelegate;
376 this._cancelTaskCurrZone = this.zone;
377 }
378 }
379 }
380 ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
381 return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
382 new Zone(targetZone, zoneSpec);
383 };
384 ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
385 return this._interceptZS ?
386 this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
387 callback;
388 };
389 ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
390 return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
391 callback.apply(applyThis, applyArgs);
392 };
393 ZoneDelegate.prototype.handleError = function (targetZone, error) {
394 return this._handleErrorZS ?
395 this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
396 true;
397 };
398 ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
399 var returnTask = task;
400 if (this._scheduleTaskZS) {
401 if (this._hasTaskZS) {
402 returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
403 }
404 returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
405 if (!returnTask)
406 returnTask = task;
407 }
408 else {
409 if (task.scheduleFn) {
410 task.scheduleFn(task);
411 }
412 else if (task.type == microTask) {
413 scheduleMicroTask(task);
414 }
415 else {
416 throw new Error('Task is missing scheduleFn.');
417 }
418 }
419 return returnTask;
420 };
421 ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
422 return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
423 task.callback.apply(applyThis, applyArgs);
424 };
425 ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
426 var value;
427 if (this._cancelTaskZS) {
428 value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
429 }
430 else {
431 if (!task.cancelFn) {
432 throw Error('Task is not cancelable');
433 }
434 value = task.cancelFn(task);
435 }
436 return value;
437 };
438 ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
439 // hasTask should not throw error so other ZoneDelegate
440 // can still trigger hasTask callback
441 try {
442 this._hasTaskZS &&
443 this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
444 }
445 catch (err) {
446 this.handleError(targetZone, err);
447 }
448 };
449 ZoneDelegate.prototype._updateTaskCount = function (type, count) {
450 var counts = this._taskCounts;
451 var prev = counts[type];
452 var next = counts[type] = prev + count;
453 if (next < 0) {
454 throw new Error('More tasks executed then were scheduled.');
455 }
456 if (prev == 0 || next == 0) {
457 var isEmpty = {
458 microTask: counts['microTask'] > 0,
459 macroTask: counts['macroTask'] > 0,
460 eventTask: counts['eventTask'] > 0,
461 change: type
462 };
463 this.hasTask(this.zone, isEmpty);
464 }
465 };
466 return ZoneDelegate;
467 }());
468 var ZoneTask = /** @class */ (function () {
469 function ZoneTask(type, source, callback, options, scheduleFn, cancelFn) {
470 this._zone = null;
471 this.runCount = 0;
472 this._zoneDelegates = null;
473 this._state = 'notScheduled';
474 this.type = type;
475 this.source = source;
476 this.data = options;
477 this.scheduleFn = scheduleFn;
478 this.cancelFn = cancelFn;
479 this.callback = callback;
480 var self = this;
481 // TODO: @JiaLiPassion options should have interface
482 if (type === eventTask && options && options.useG) {
483 this.invoke = ZoneTask.invokeTask;
484 }
485 else {
486 this.invoke = function () {
487 return ZoneTask.invokeTask.call(global, self, this, arguments);
488 };
489 }
490 }
491 ZoneTask.invokeTask = function (task, target, args) {
492 if (!task) {
493 task = this;
494 }
495 _numberOfNestedTaskFrames++;
496 try {
497 task.runCount++;
498 return task.zone.runTask(task, target, args);
499 }
500 finally {
501 if (_numberOfNestedTaskFrames == 1) {
502 drainMicroTaskQueue();
503 }
504 _numberOfNestedTaskFrames--;
505 }
506 };
507 Object.defineProperty(ZoneTask.prototype, "zone", {
508 get: function () {
509 return this._zone;
510 },
511 enumerable: true,
512 configurable: true
513 });
514 Object.defineProperty(ZoneTask.prototype, "state", {
515 get: function () {
516 return this._state;
517 },
518 enumerable: true,
519 configurable: true
520 });
521 ZoneTask.prototype.cancelScheduleRequest = function () {
522 this._transitionTo(notScheduled, scheduling);
523 };
524 ZoneTask.prototype._transitionTo = function (toState, fromState1, fromState2) {
525 if (this._state === fromState1 || this._state === fromState2) {
526 this._state = toState;
527 if (toState == notScheduled) {
528 this._zoneDelegates = null;
529 }
530 }
531 else {
532 throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'.");
533 }
534 };
535 ZoneTask.prototype.toString = function () {
536 if (this.data && typeof this.data.handleId !== 'undefined') {
537 return this.data.handleId.toString();
538 }
539 else {
540 return Object.prototype.toString.call(this);
541 }
542 };
543 // add toJSON method to prevent cyclic error when
544 // call JSON.stringify(zoneTask)
545 ZoneTask.prototype.toJSON = function () {
546 return {
547 type: this.type,
548 state: this.state,
549 source: this.source,
550 zone: this.zone.name,
551 runCount: this.runCount
552 };
553 };
554 return ZoneTask;
555 }());
556 //////////////////////////////////////////////////////
557 //////////////////////////////////////////////////////
558 /// MICROTASK QUEUE
559 //////////////////////////////////////////////////////
560 //////////////////////////////////////////////////////
561 var symbolSetTimeout = __symbol__('setTimeout');
562 var symbolPromise = __symbol__('Promise');
563 var symbolThen = __symbol__('then');
564 var _microTaskQueue = [];
565 var _isDrainingMicrotaskQueue = false;
566 var nativeMicroTaskQueuePromise;
567 function scheduleMicroTask(task) {
568 // if we are not running in any task, and there has not been anything scheduled
569 // we must bootstrap the initial task creation by manually scheduling the drain
570 if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
571 // We are not running in Task, so we need to kickstart the microtask queue.
572 if (!nativeMicroTaskQueuePromise) {
573 if (global[symbolPromise]) {
574 nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
575 }
576 }
577 if (nativeMicroTaskQueuePromise) {
578 var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
579 if (!nativeThen) {
580 // native Promise is not patchable, we need to use `then` directly
581 // issue 1078
582 nativeThen = nativeMicroTaskQueuePromise['then'];
583 }
584 nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
585 }
586 else {
587 global[symbolSetTimeout](drainMicroTaskQueue, 0);
588 }
589 }
590 task && _microTaskQueue.push(task);
591 }
592 function drainMicroTaskQueue() {
593 if (!_isDrainingMicrotaskQueue) {
594 _isDrainingMicrotaskQueue = true;
595 while (_microTaskQueue.length) {
596 var queue = _microTaskQueue;
597 _microTaskQueue = [];
598 for (var i = 0; i < queue.length; i++) {
599 var task = queue[i];
600 try {
601 task.zone.runTask(task, null, null);
602 }
603 catch (error) {
604 _api.onUnhandledError(error);
605 }
606 }
607 }
608 _api.microtaskDrainDone();
609 _isDrainingMicrotaskQueue = false;
610 }
611 }
612 //////////////////////////////////////////////////////
613 //////////////////////////////////////////////////////
614 /// BOOTSTRAP
615 //////////////////////////////////////////////////////
616 //////////////////////////////////////////////////////
617 var NO_ZONE = { name: 'NO ZONE' };
618 var notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
619 var microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
620 var patches = {};
621 var _api = {
622 symbol: __symbol__,
623 currentZoneFrame: function () { return _currentZoneFrame; },
624 onUnhandledError: noop,
625 microtaskDrainDone: noop,
626 scheduleMicroTask: scheduleMicroTask,
627 showUncaughtError: function () { return !Zone[__symbol__('ignoreConsoleErrorUncaughtError')]; },
628 patchEventTarget: function () { return []; },
629 patchOnProperties: noop,
630 patchMethod: function () { return noop; },
631 bindArguments: function () { return []; },
632 patchThen: function () { return noop; },
633 patchMacroTask: function () { return noop; },
634 setNativePromise: function (NativePromise) {
635 // sometimes NativePromise.resolve static function
636 // is not ready yet, (such as core-js/es6.promise)
637 // so we need to check here.
638 if (NativePromise && typeof NativePromise.resolve === 'function') {
639 nativeMicroTaskQueuePromise = NativePromise.resolve(0);
640 }
641 },
642 patchEventPrototype: function () { return noop; },
643 isIEOrEdge: function () { return false; },
644 getGlobalObjects: function () { return undefined; },
645 ObjectDefineProperty: function () { return noop; },
646 ObjectGetOwnPropertyDescriptor: function () { return undefined; },
647 ObjectCreate: function () { return undefined; },
648 ArraySlice: function () { return []; },
649 patchClass: function () { return noop; },
650 wrapWithCurrentZone: function () { return noop; },
651 filterProperties: function () { return []; },
652 attachOriginToPatched: function () { return noop; },
653 _redefineProperty: function () { return noop; },
654 patchCallbacks: function () { return noop; }
655 };
656 var _currentZoneFrame = { parent: null, zone: new Zone(null, null) };
657 var _currentTask = null;
658 var _numberOfNestedTaskFrames = 0;
659 function noop() { }
660 function __symbol__(name) {
661 return '__zone_symbol__' + name;
662 }
663 performanceMeasure('Zone', 'Zone');
664 return global['Zone'] = Zone;
665})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
666
667var __values = (undefined && undefined.__values) || function (o) {
668 var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
669 if (m) return m.call(o);
670 return {
671 next: function () {
672 if (o && i >= o.length) o = void 0;
673 return { value: o && o[i++], done: !o };
674 }
675 };
676};
677/**
678 * @license
679 * Copyright Google Inc. All Rights Reserved.
680 *
681 * Use of this source code is governed by an MIT-style license that can be
682 * found in the LICENSE file at https://angular.io/license
683 */
684Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
685 var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
686 var ObjectDefineProperty = Object.defineProperty;
687 function readableObjectToString(obj) {
688 if (obj && obj.toString === Object.prototype.toString) {
689 var className = obj.constructor && obj.constructor.name;
690 return (className ? className : '') + ': ' + JSON.stringify(obj);
691 }
692 return obj ? obj.toString() : Object.prototype.toString.call(obj);
693 }
694 var __symbol__ = api.symbol;
695 var _uncaughtPromiseErrors = [];
696 var symbolPromise = __symbol__('Promise');
697 var symbolThen = __symbol__('then');
698 var creationTrace = '__creationTrace__';
699 api.onUnhandledError = function (e) {
700 if (api.showUncaughtError()) {
701 var rejection = e && e.rejection;
702 if (rejection) {
703 console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
704 }
705 else {
706 console.error(e);
707 }
708 }
709 };
710 api.microtaskDrainDone = function () {
711 while (_uncaughtPromiseErrors.length) {
712 var _loop_1 = function () {
713 var uncaughtPromiseError = _uncaughtPromiseErrors.shift();
714 try {
715 uncaughtPromiseError.zone.runGuarded(function () {
716 throw uncaughtPromiseError;
717 });
718 }
719 catch (error) {
720 handleUnhandledRejection(error);
721 }
722 };
723 while (_uncaughtPromiseErrors.length) {
724 _loop_1();
725 }
726 }
727 };
728 var UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
729 function handleUnhandledRejection(e) {
730 api.onUnhandledError(e);
731 try {
732 var handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
733 if (handler && typeof handler === 'function') {
734 handler.call(this, e);
735 }
736 }
737 catch (err) {
738 }
739 }
740 function isThenable(value) {
741 return value && value.then;
742 }
743 function forwardResolution(value) {
744 return value;
745 }
746 function forwardRejection(rejection) {
747 return ZoneAwarePromise.reject(rejection);
748 }
749 var symbolState = __symbol__('state');
750 var symbolValue = __symbol__('value');
751 var symbolFinally = __symbol__('finally');
752 var symbolParentPromiseValue = __symbol__('parentPromiseValue');
753 var symbolParentPromiseState = __symbol__('parentPromiseState');
754 var source = 'Promise.then';
755 var UNRESOLVED = null;
756 var RESOLVED = true;
757 var REJECTED = false;
758 var REJECTED_NO_CATCH = 0;
759 function makeResolver(promise, state) {
760 return function (v) {
761 try {
762 resolvePromise(promise, state, v);
763 }
764 catch (err) {
765 resolvePromise(promise, false, err);
766 }
767 // Do not return value or you will break the Promise spec.
768 };
769 }
770 var once = function () {
771 var wasCalled = false;
772 return function wrapper(wrappedFunction) {
773 return function () {
774 if (wasCalled) {
775 return;
776 }
777 wasCalled = true;
778 wrappedFunction.apply(null, arguments);
779 };
780 };
781 };
782 var TYPE_ERROR = 'Promise resolved with itself';
783 var CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
784 // Promise Resolution
785 function resolvePromise(promise, state, value) {
786 var onceWrapper = once();
787 if (promise === value) {
788 throw new TypeError(TYPE_ERROR);
789 }
790 if (promise[symbolState] === UNRESOLVED) {
791 // should only get value.then once based on promise spec.
792 var then = null;
793 try {
794 if (typeof value === 'object' || typeof value === 'function') {
795 then = value && value.then;
796 }
797 }
798 catch (err) {
799 onceWrapper(function () {
800 resolvePromise(promise, false, err);
801 })();
802 return promise;
803 }
804 // if (value instanceof ZoneAwarePromise) {
805 if (state !== REJECTED && value instanceof ZoneAwarePromise &&
806 value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
807 value[symbolState] !== UNRESOLVED) {
808 clearRejectedNoCatch(value);
809 resolvePromise(promise, value[symbolState], value[symbolValue]);
810 }
811 else if (state !== REJECTED && typeof then === 'function') {
812 try {
813 then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
814 }
815 catch (err) {
816 onceWrapper(function () {
817 resolvePromise(promise, false, err);
818 })();
819 }
820 }
821 else {
822 promise[symbolState] = state;
823 var queue = promise[symbolValue];
824 promise[symbolValue] = value;
825 if (promise[symbolFinally] === symbolFinally) {
826 // the promise is generated by Promise.prototype.finally
827 if (state === RESOLVED) {
828 // the state is resolved, should ignore the value
829 // and use parent promise value
830 promise[symbolState] = promise[symbolParentPromiseState];
831 promise[symbolValue] = promise[symbolParentPromiseValue];
832 }
833 }
834 // record task information in value when error occurs, so we can
835 // do some additional work such as render longStackTrace
836 if (state === REJECTED && value instanceof Error) {
837 // check if longStackTraceZone is here
838 var trace = Zone.currentTask && Zone.currentTask.data &&
839 Zone.currentTask.data[creationTrace];
840 if (trace) {
841 // only keep the long stack trace into error when in longStackTraceZone
842 ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
843 }
844 }
845 for (var i = 0; i < queue.length;) {
846 scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
847 }
848 if (queue.length == 0 && state == REJECTED) {
849 promise[symbolState] = REJECTED_NO_CATCH;
850 try {
851 // try to print more readable error log
852 throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
853 (value && value.stack ? '\n' + value.stack : ''));
854 }
855 catch (err) {
856 var error_1 = err;
857 error_1.rejection = value;
858 error_1.promise = promise;
859 error_1.zone = Zone.current;
860 error_1.task = Zone.currentTask;
861 _uncaughtPromiseErrors.push(error_1);
862 api.scheduleMicroTask(); // to make sure that it is running
863 }
864 }
865 }
866 }
867 // Resolving an already resolved promise is a noop.
868 return promise;
869 }
870 var REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
871 function clearRejectedNoCatch(promise) {
872 if (promise[symbolState] === REJECTED_NO_CATCH) {
873 // if the promise is rejected no catch status
874 // and queue.length > 0, means there is a error handler
875 // here to handle the rejected promise, we should trigger
876 // windows.rejectionhandled eventHandler or nodejs rejectionHandled
877 // eventHandler
878 try {
879 var handler = Zone[REJECTION_HANDLED_HANDLER];
880 if (handler && typeof handler === 'function') {
881 handler.call(this, { rejection: promise[symbolValue], promise: promise });
882 }
883 }
884 catch (err) {
885 }
886 promise[symbolState] = REJECTED;
887 for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
888 if (promise === _uncaughtPromiseErrors[i].promise) {
889 _uncaughtPromiseErrors.splice(i, 1);
890 }
891 }
892 }
893 }
894 function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
895 clearRejectedNoCatch(promise);
896 var promiseState = promise[symbolState];
897 var delegate = promiseState ?
898 (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
899 (typeof onRejected === 'function') ? onRejected : forwardRejection;
900 zone.scheduleMicroTask(source, function () {
901 try {
902 var parentPromiseValue = promise[symbolValue];
903 var isFinallyPromise = chainPromise && symbolFinally === chainPromise[symbolFinally];
904 if (isFinallyPromise) {
905 // if the promise is generated from finally call, keep parent promise's state and value
906 chainPromise[symbolParentPromiseValue] = parentPromiseValue;
907 chainPromise[symbolParentPromiseState] = promiseState;
908 }
909 // should not pass value to finally callback
910 var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
911 [] :
912 [parentPromiseValue]);
913 resolvePromise(chainPromise, true, value);
914 }
915 catch (error) {
916 // if error occurs, should always return this error
917 resolvePromise(chainPromise, false, error);
918 }
919 }, chainPromise);
920 }
921 var ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
922 var ZoneAwarePromise = /** @class */ (function () {
923 function ZoneAwarePromise(executor) {
924 var promise = this;
925 if (!(promise instanceof ZoneAwarePromise)) {
926 throw new Error('Must be an instanceof Promise.');
927 }
928 promise[symbolState] = UNRESOLVED;
929 promise[symbolValue] = []; // queue;
930 try {
931 executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
932 }
933 catch (error) {
934 resolvePromise(promise, false, error);
935 }
936 }
937 ZoneAwarePromise.toString = function () {
938 return ZONE_AWARE_PROMISE_TO_STRING;
939 };
940 ZoneAwarePromise.resolve = function (value) {
941 return resolvePromise(new this(null), RESOLVED, value);
942 };
943 ZoneAwarePromise.reject = function (error) {
944 return resolvePromise(new this(null), REJECTED, error);
945 };
946 ZoneAwarePromise.race = function (values) {
947 var e_1, _a;
948 var resolve;
949 var reject;
950 var promise = new this(function (res, rej) {
951 resolve = res;
952 reject = rej;
953 });
954 function onResolve(value) {
955 resolve(value);
956 }
957 function onReject(error) {
958 reject(error);
959 }
960 try {
961 for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
962 var value = values_1_1.value;
963 if (!isThenable(value)) {
964 value = this.resolve(value);
965 }
966 value.then(onResolve, onReject);
967 }
968 }
969 catch (e_1_1) { e_1 = { error: e_1_1 }; }
970 finally {
971 try {
972 if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
973 }
974 finally { if (e_1) throw e_1.error; }
975 }
976 return promise;
977 };
978 ZoneAwarePromise.all = function (values) {
979 var e_2, _a;
980 var resolve;
981 var reject;
982 var promise = new this(function (res, rej) {
983 resolve = res;
984 reject = rej;
985 });
986 // Start at 2 to prevent prematurely resolving if .then is called immediately.
987 var unresolvedCount = 2;
988 var valueIndex = 0;
989 var resolvedValues = [];
990 var _loop_2 = function (value) {
991 if (!isThenable(value)) {
992 value = this_1.resolve(value);
993 }
994 var curValueIndex = valueIndex;
995 value.then(function (value) {
996 resolvedValues[curValueIndex] = value;
997 unresolvedCount--;
998 if (unresolvedCount === 0) {
999 resolve(resolvedValues);
1000 }
1001 }, reject);
1002 unresolvedCount++;
1003 valueIndex++;
1004 };
1005 var this_1 = this;
1006 try {
1007 for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) {
1008 var value = values_2_1.value;
1009 _loop_2(value);
1010 }
1011 }
1012 catch (e_2_1) { e_2 = { error: e_2_1 }; }
1013 finally {
1014 try {
1015 if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2);
1016 }
1017 finally { if (e_2) throw e_2.error; }
1018 }
1019 // Make the unresolvedCount zero-based again.
1020 unresolvedCount -= 2;
1021 if (unresolvedCount === 0) {
1022 resolve(resolvedValues);
1023 }
1024 return promise;
1025 };
1026 Object.defineProperty(ZoneAwarePromise.prototype, Symbol.toStringTag, {
1027 get: function () {
1028 return 'Promise';
1029 },
1030 enumerable: true,
1031 configurable: true
1032 });
1033 ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
1034 var chainPromise = new this.constructor(null);
1035 var zone = Zone.current;
1036 if (this[symbolState] == UNRESOLVED) {
1037 this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
1038 }
1039 else {
1040 scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
1041 }
1042 return chainPromise;
1043 };
1044 ZoneAwarePromise.prototype.catch = function (onRejected) {
1045 return this.then(null, onRejected);
1046 };
1047 ZoneAwarePromise.prototype.finally = function (onFinally) {
1048 var chainPromise = new this.constructor(null);
1049 chainPromise[symbolFinally] = symbolFinally;
1050 var zone = Zone.current;
1051 if (this[symbolState] == UNRESOLVED) {
1052 this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
1053 }
1054 else {
1055 scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
1056 }
1057 return chainPromise;
1058 };
1059 return ZoneAwarePromise;
1060 }());
1061 // Protect against aggressive optimizers dropping seemingly unused properties.
1062 // E.g. Closure Compiler in advanced mode.
1063 ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
1064 ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
1065 ZoneAwarePromise['race'] = ZoneAwarePromise.race;
1066 ZoneAwarePromise['all'] = ZoneAwarePromise.all;
1067 var NativePromise = global[symbolPromise] = global['Promise'];
1068 var ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise');
1069 var desc = ObjectGetOwnPropertyDescriptor(global, 'Promise');
1070 if (!desc || desc.configurable) {
1071 desc && delete desc.writable;
1072 desc && delete desc.value;
1073 if (!desc) {
1074 desc = { configurable: true, enumerable: true };
1075 }
1076 desc.get = function () {
1077 // if we already set ZoneAwarePromise, use patched one
1078 // otherwise return native one.
1079 return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise];
1080 };
1081 desc.set = function (NewNativePromise) {
1082 if (NewNativePromise === ZoneAwarePromise) {
1083 // if the NewNativePromise is ZoneAwarePromise
1084 // save to global
1085 global[ZONE_AWARE_PROMISE] = NewNativePromise;
1086 }
1087 else {
1088 // if the NewNativePromise is not ZoneAwarePromise
1089 // for example: after load zone.js, some library just
1090 // set es6-promise to global, if we set it to global
1091 // directly, assertZonePatched will fail and angular
1092 // will not loaded, so we just set the NewNativePromise
1093 // to global[symbolPromise], so the result is just like
1094 // we load ES6 Promise before zone.js
1095 global[symbolPromise] = NewNativePromise;
1096 if (!NewNativePromise.prototype[symbolThen]) {
1097 patchThen(NewNativePromise);
1098 }
1099 api.setNativePromise(NewNativePromise);
1100 }
1101 };
1102 ObjectDefineProperty(global, 'Promise', desc);
1103 }
1104 global['Promise'] = ZoneAwarePromise;
1105 var symbolThenPatched = __symbol__('thenPatched');
1106 function patchThen(Ctor) {
1107 var proto = Ctor.prototype;
1108 var prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
1109 if (prop && (prop.writable === false || !prop.configurable)) {
1110 // check Ctor.prototype.then propertyDescriptor is writable or not
1111 // in meteor env, writable is false, we should ignore such case
1112 return;
1113 }
1114 var originalThen = proto.then;
1115 // Keep a reference to the original method.
1116 proto[symbolThen] = originalThen;
1117 Ctor.prototype.then = function (onResolve, onReject) {
1118 var _this = this;
1119 var wrapped = new ZoneAwarePromise(function (resolve, reject) {
1120 originalThen.call(_this, resolve, reject);
1121 });
1122 return wrapped.then(onResolve, onReject);
1123 };
1124 Ctor[symbolThenPatched] = true;
1125 }
1126 api.patchThen = patchThen;
1127 function zoneify(fn) {
1128 return function () {
1129 var resultPromise = fn.apply(this, arguments);
1130 if (resultPromise instanceof ZoneAwarePromise) {
1131 return resultPromise;
1132 }
1133 var ctor = resultPromise.constructor;
1134 if (!ctor[symbolThenPatched]) {
1135 patchThen(ctor);
1136 }
1137 return resultPromise;
1138 };
1139 }
1140 if (NativePromise) {
1141 patchThen(NativePromise);
1142 var fetch_1 = global['fetch'];
1143 if (typeof fetch_1 == 'function') {
1144 global[api.symbol('fetch')] = fetch_1;
1145 global['fetch'] = zoneify(fetch_1);
1146 }
1147 }
1148 // This is not part of public API, but it is useful for tests, so we expose it.
1149 Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
1150 return ZoneAwarePromise;
1151});
1152
1153/**
1154 * @license
1155 * Copyright Google Inc. All Rights Reserved.
1156 *
1157 * Use of this source code is governed by an MIT-style license that can be
1158 * found in the LICENSE file at https://angular.io/license
1159 */
1160/**
1161 * Suppress closure compiler errors about unknown 'Zone' variable
1162 * @fileoverview
1163 * @suppress {undefinedVars,globalThis,missingRequire}
1164 */
1165// issue #989, to reduce bundle size, use short name
1166/** Object.getOwnPropertyDescriptor */
1167var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
1168/** Object.defineProperty */
1169var ObjectDefineProperty = Object.defineProperty;
1170/** Object.getPrototypeOf */
1171var ObjectGetPrototypeOf = Object.getPrototypeOf;
1172/** Object.create */
1173var ObjectCreate = Object.create;
1174/** Array.prototype.slice */
1175var ArraySlice = Array.prototype.slice;
1176/** addEventListener string const */
1177var ADD_EVENT_LISTENER_STR = 'addEventListener';
1178/** removeEventListener string const */
1179var REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
1180/** zoneSymbol addEventListener */
1181var ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
1182/** zoneSymbol removeEventListener */
1183var ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
1184/** true string const */
1185var TRUE_STR = 'true';
1186/** false string const */
1187var FALSE_STR = 'false';
1188/** __zone_symbol__ string const */
1189var ZONE_SYMBOL_PREFIX = '__zone_symbol__';
1190function wrapWithCurrentZone(callback, source) {
1191 return Zone.current.wrap(callback, source);
1192}
1193function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
1194 return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
1195}
1196var zoneSymbol = Zone.__symbol__;
1197var isWindowExists = typeof window !== 'undefined';
1198var internalWindow = isWindowExists ? window : undefined;
1199var _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
1200var REMOVE_ATTRIBUTE = 'removeAttribute';
1201var NULL_ON_PROP_VALUE = [null];
1202function bindArguments(args, source) {
1203 for (var i = args.length - 1; i >= 0; i--) {
1204 if (typeof args[i] === 'function') {
1205 args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
1206 }
1207 }
1208 return args;
1209}
1210function patchPrototype(prototype, fnNames) {
1211 var source = prototype.constructor['name'];
1212 var _loop_1 = function (i) {
1213 var name_1 = fnNames[i];
1214 var delegate = prototype[name_1];
1215 if (delegate) {
1216 var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name_1);
1217 if (!isPropertyWritable(prototypeDesc)) {
1218 return "continue";
1219 }
1220 prototype[name_1] = (function (delegate) {
1221 var patched = function () {
1222 return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));
1223 };
1224 attachOriginToPatched(patched, delegate);
1225 return patched;
1226 })(delegate);
1227 }
1228 };
1229 for (var i = 0; i < fnNames.length; i++) {
1230 _loop_1(i);
1231 }
1232}
1233function isPropertyWritable(propertyDesc) {
1234 if (!propertyDesc) {
1235 return true;
1236 }
1237 if (propertyDesc.writable === false) {
1238 return false;
1239 }
1240 return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
1241}
1242var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
1243// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
1244// this code.
1245var isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
1246 {}.toString.call(_global.process) === '[object process]');
1247var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
1248// we are in electron of nw, so we are both browser and nodejs
1249// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
1250// this code.
1251var isMix = typeof _global.process !== 'undefined' &&
1252 {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
1253 !!(isWindowExists && internalWindow['HTMLElement']);
1254var zoneSymbolEventNames = {};
1255var wrapFn = function (event) {
1256 // https://github.com/angular/zone.js/issues/911, in IE, sometimes
1257 // event will be undefined, so we need to use window.event
1258 event = event || _global.event;
1259 if (!event) {
1260 return;
1261 }
1262 var eventNameSymbol = zoneSymbolEventNames[event.type];
1263 if (!eventNameSymbol) {
1264 eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
1265 }
1266 var target = this || event.target || _global;
1267 var listener = target[eventNameSymbol];
1268 var result;
1269 if (isBrowser && target === internalWindow && event.type === 'error') {
1270 // window.onerror have different signiture
1271 // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
1272 // and onerror callback will prevent default when callback return true
1273 var errorEvent = event;
1274 result = listener &&
1275 listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
1276 if (result === true) {
1277 event.preventDefault();
1278 }
1279 }
1280 else {
1281 result = listener && listener.apply(this, arguments);
1282 if (result != undefined && !result) {
1283 event.preventDefault();
1284 }
1285 }
1286 return result;
1287};
1288function patchProperty(obj, prop, prototype) {
1289 var desc = ObjectGetOwnPropertyDescriptor(obj, prop);
1290 if (!desc && prototype) {
1291 // when patch window object, use prototype to check prop exist or not
1292 var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
1293 if (prototypeDesc) {
1294 desc = { enumerable: true, configurable: true };
1295 }
1296 }
1297 // if the descriptor not exists or is not configurable
1298 // just return
1299 if (!desc || !desc.configurable) {
1300 return;
1301 }
1302 var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
1303 if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
1304 return;
1305 }
1306 // A property descriptor cannot have getter/setter and be writable
1307 // deleting the writable and value properties avoids this error:
1308 //
1309 // TypeError: property descriptors must not specify a value or be writable when a
1310 // getter or setter has been specified
1311 delete desc.writable;
1312 delete desc.value;
1313 var originalDescGet = desc.get;
1314 var originalDescSet = desc.set;
1315 // substr(2) cuz 'onclick' -> 'click', etc
1316 var eventName = prop.substr(2);
1317 var eventNameSymbol = zoneSymbolEventNames[eventName];
1318 if (!eventNameSymbol) {
1319 eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
1320 }
1321 desc.set = function (newValue) {
1322 // in some of windows's onproperty callback, this is undefined
1323 // so we need to check it
1324 var target = this;
1325 if (!target && obj === _global) {
1326 target = _global;
1327 }
1328 if (!target) {
1329 return;
1330 }
1331 var previousValue = target[eventNameSymbol];
1332 if (previousValue) {
1333 target.removeEventListener(eventName, wrapFn);
1334 }
1335 // issue #978, when onload handler was added before loading zone.js
1336 // we should remove it with originalDescSet
1337 if (originalDescSet) {
1338 originalDescSet.apply(target, NULL_ON_PROP_VALUE);
1339 }
1340 if (typeof newValue === 'function') {
1341 target[eventNameSymbol] = newValue;
1342 target.addEventListener(eventName, wrapFn, false);
1343 }
1344 else {
1345 target[eventNameSymbol] = null;
1346 }
1347 };
1348 // The getter would return undefined for unassigned properties but the default value of an
1349 // unassigned property is null
1350 desc.get = function () {
1351 // in some of windows's onproperty callback, this is undefined
1352 // so we need to check it
1353 var target = this;
1354 if (!target && obj === _global) {
1355 target = _global;
1356 }
1357 if (!target) {
1358 return null;
1359 }
1360 var listener = target[eventNameSymbol];
1361 if (listener) {
1362 return listener;
1363 }
1364 else if (originalDescGet) {
1365 // result will be null when use inline event attribute,
1366 // such as <button onclick="func();">OK</button>
1367 // because the onclick function is internal raw uncompiled handler
1368 // the onclick will be evaluated when first time event was triggered or
1369 // the property is accessed, https://github.com/angular/zone.js/issues/525
1370 // so we should use original native get to retrieve the handler
1371 var value = originalDescGet && originalDescGet.call(this);
1372 if (value) {
1373 desc.set.call(this, value);
1374 if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
1375 target.removeAttribute(prop);
1376 }
1377 return value;
1378 }
1379 }
1380 return null;
1381 };
1382 ObjectDefineProperty(obj, prop, desc);
1383 obj[onPropPatchedSymbol] = true;
1384}
1385function patchOnProperties(obj, properties, prototype) {
1386 if (properties) {
1387 for (var i = 0; i < properties.length; i++) {
1388 patchProperty(obj, 'on' + properties[i], prototype);
1389 }
1390 }
1391 else {
1392 var onProperties = [];
1393 for (var prop in obj) {
1394 if (prop.substr(0, 2) == 'on') {
1395 onProperties.push(prop);
1396 }
1397 }
1398 for (var j = 0; j < onProperties.length; j++) {
1399 patchProperty(obj, onProperties[j], prototype);
1400 }
1401 }
1402}
1403var originalInstanceKey = zoneSymbol('originalInstance');
1404// wrap some native API on `window`
1405function patchClass(className) {
1406 var OriginalClass = _global[className];
1407 if (!OriginalClass)
1408 return;
1409 // keep original class in global
1410 _global[zoneSymbol(className)] = OriginalClass;
1411 _global[className] = function () {
1412 var a = bindArguments(arguments, className);
1413 switch (a.length) {
1414 case 0:
1415 this[originalInstanceKey] = new OriginalClass();
1416 break;
1417 case 1:
1418 this[originalInstanceKey] = new OriginalClass(a[0]);
1419 break;
1420 case 2:
1421 this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
1422 break;
1423 case 3:
1424 this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
1425 break;
1426 case 4:
1427 this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
1428 break;
1429 default:
1430 throw new Error('Arg list too long.');
1431 }
1432 };
1433 // attach original delegate to patched function
1434 attachOriginToPatched(_global[className], OriginalClass);
1435 var instance = new OriginalClass(function () { });
1436 var prop;
1437 for (prop in instance) {
1438 // https://bugs.webkit.org/show_bug.cgi?id=44721
1439 if (className === 'XMLHttpRequest' && prop === 'responseBlob')
1440 continue;
1441 (function (prop) {
1442 if (typeof instance[prop] === 'function') {
1443 _global[className].prototype[prop] = function () {
1444 return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
1445 };
1446 }
1447 else {
1448 ObjectDefineProperty(_global[className].prototype, prop, {
1449 set: function (fn) {
1450 if (typeof fn === 'function') {
1451 this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
1452 // keep callback in wrapped function so we can
1453 // use it in Function.prototype.toString to return
1454 // the native one.
1455 attachOriginToPatched(this[originalInstanceKey][prop], fn);
1456 }
1457 else {
1458 this[originalInstanceKey][prop] = fn;
1459 }
1460 },
1461 get: function () {
1462 return this[originalInstanceKey][prop];
1463 }
1464 });
1465 }
1466 }(prop));
1467 }
1468 for (prop in OriginalClass) {
1469 if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
1470 _global[className][prop] = OriginalClass[prop];
1471 }
1472 }
1473}
1474function copySymbolProperties(src, dest) {
1475 if (typeof Object.getOwnPropertySymbols !== 'function') {
1476 return;
1477 }
1478 var symbols = Object.getOwnPropertySymbols(src);
1479 symbols.forEach(function (symbol) {
1480 var desc = Object.getOwnPropertyDescriptor(src, symbol);
1481 Object.defineProperty(dest, symbol, {
1482 get: function () {
1483 return src[symbol];
1484 },
1485 set: function (value) {
1486 if (desc && (!desc.writable || typeof desc.set !== 'function')) {
1487 // if src[symbol] is not writable or not have a setter, just return
1488 return;
1489 }
1490 src[symbol] = value;
1491 },
1492 enumerable: desc ? desc.enumerable : true,
1493 configurable: desc ? desc.configurable : true
1494 });
1495 });
1496}
1497var shouldCopySymbolProperties = false;
1498
1499function patchMethod(target, name, patchFn) {
1500 var proto = target;
1501 while (proto && !proto.hasOwnProperty(name)) {
1502 proto = ObjectGetPrototypeOf(proto);
1503 }
1504 if (!proto && target[name]) {
1505 // somehow we did not find it, but we can see it. This happens on IE for Window properties.
1506 proto = target;
1507 }
1508 var delegateName = zoneSymbol(name);
1509 var delegate = null;
1510 if (proto && !(delegate = proto[delegateName])) {
1511 delegate = proto[delegateName] = proto[name];
1512 // check whether proto[name] is writable
1513 // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
1514 var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
1515 if (isPropertyWritable(desc)) {
1516 var patchDelegate_1 = patchFn(delegate, delegateName, name);
1517 proto[name] = function () {
1518 return patchDelegate_1(this, arguments);
1519 };
1520 attachOriginToPatched(proto[name], delegate);
1521 if (shouldCopySymbolProperties) {
1522 copySymbolProperties(delegate, proto[name]);
1523 }
1524 }
1525 }
1526 return delegate;
1527}
1528// TODO: @JiaLiPassion, support cancel task later if necessary
1529function patchMacroTask(obj, funcName, metaCreator) {
1530 var setNative = null;
1531 function scheduleTask(task) {
1532 var data = task.data;
1533 data.args[data.cbIdx] = function () {
1534 task.invoke.apply(this, arguments);
1535 };
1536 setNative.apply(data.target, data.args);
1537 return task;
1538 }
1539 setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
1540 var meta = metaCreator(self, args);
1541 if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
1542 return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
1543 }
1544 else {
1545 // cause an error by calling it directly.
1546 return delegate.apply(self, args);
1547 }
1548 }; });
1549}
1550
1551function attachOriginToPatched(patched, original) {
1552 patched[zoneSymbol('OriginalDelegate')] = original;
1553}
1554var isDetectedIEOrEdge = false;
1555var ieOrEdge = false;
1556function isIE() {
1557 try {
1558 var ua = internalWindow.navigator.userAgent;
1559 if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
1560 return true;
1561 }
1562 }
1563 catch (error) {
1564 }
1565 return false;
1566}
1567function isIEOrEdge() {
1568 if (isDetectedIEOrEdge) {
1569 return ieOrEdge;
1570 }
1571 isDetectedIEOrEdge = true;
1572 try {
1573 var ua = internalWindow.navigator.userAgent;
1574 if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
1575 ieOrEdge = true;
1576 }
1577 }
1578 catch (error) {
1579 }
1580 return ieOrEdge;
1581}
1582
1583/**
1584 * @license
1585 * Copyright Google Inc. All Rights Reserved.
1586 *
1587 * Use of this source code is governed by an MIT-style license that can be
1588 * found in the LICENSE file at https://angular.io/license
1589 */
1590// override Function.prototype.toString to make zone.js patched function
1591// look like native function
1592Zone.__load_patch('toString', function (global) {
1593 // patch Func.prototype.toString to let them look like native
1594 var originalFunctionToString = Function.prototype.toString;
1595 var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
1596 var PROMISE_SYMBOL = zoneSymbol('Promise');
1597 var ERROR_SYMBOL = zoneSymbol('Error');
1598 var newFunctionToString = function toString() {
1599 if (typeof this === 'function') {
1600 var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
1601 if (originalDelegate) {
1602 if (typeof originalDelegate === 'function') {
1603 return originalFunctionToString.call(originalDelegate);
1604 }
1605 else {
1606 return Object.prototype.toString.call(originalDelegate);
1607 }
1608 }
1609 if (this === Promise) {
1610 var nativePromise = global[PROMISE_SYMBOL];
1611 if (nativePromise) {
1612 return originalFunctionToString.call(nativePromise);
1613 }
1614 }
1615 if (this === Error) {
1616 var nativeError = global[ERROR_SYMBOL];
1617 if (nativeError) {
1618 return originalFunctionToString.call(nativeError);
1619 }
1620 }
1621 }
1622 return originalFunctionToString.call(this);
1623 };
1624 newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
1625 Function.prototype.toString = newFunctionToString;
1626 // patch Object.prototype.toString to let them look like native
1627 var originalObjectToString = Object.prototype.toString;
1628 var PROMISE_OBJECT_TO_STRING = '[object Promise]';
1629 Object.prototype.toString = function () {
1630 if (this instanceof Promise) {
1631 return PROMISE_OBJECT_TO_STRING;
1632 }
1633 return originalObjectToString.call(this);
1634 };
1635});
1636
1637/**
1638 * @license
1639 * Copyright Google Inc. All Rights Reserved.
1640 *
1641 * Use of this source code is governed by an MIT-style license that can be
1642 * found in the LICENSE file at https://angular.io/license
1643 */
1644/**
1645 * @fileoverview
1646 * @suppress {missingRequire}
1647 */
1648var passiveSupported = false;
1649if (typeof window !== 'undefined') {
1650 try {
1651 var options = Object.defineProperty({}, 'passive', {
1652 get: function () {
1653 passiveSupported = true;
1654 }
1655 });
1656 window.addEventListener('test', options, options);
1657 window.removeEventListener('test', options, options);
1658 }
1659 catch (err) {
1660 passiveSupported = false;
1661 }
1662}
1663// an identifier to tell ZoneTask do not create a new invoke closure
1664var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
1665 useG: true
1666};
1667var zoneSymbolEventNames$1 = {};
1668var globalSources = {};
1669var EVENT_NAME_SYMBOL_REGX = /^__zone_symbol__(\w+)(true|false)$/;
1670var IMMEDIATE_PROPAGATION_SYMBOL = ('__zone_symbol__propagationStopped');
1671function patchEventTarget(_global, apis, patchOptions) {
1672 var ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
1673 var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
1674 var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
1675 var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
1676 var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
1677 var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
1678 var PREPEND_EVENT_LISTENER = 'prependListener';
1679 var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
1680 var invokeTask = function (task, target, event) {
1681 // for better performance, check isRemoved which is set
1682 // by removeEventListener
1683 if (task.isRemoved) {
1684 return;
1685 }
1686 var delegate = task.callback;
1687 if (typeof delegate === 'object' && delegate.handleEvent) {
1688 // create the bind version of handleEvent when invoke
1689 task.callback = function (event) { return delegate.handleEvent(event); };
1690 task.originalDelegate = delegate;
1691 }
1692 // invoke static task.invoke
1693 task.invoke(task, target, [event]);
1694 var options = task.options;
1695 if (options && typeof options === 'object' && options.once) {
1696 // if options.once is true, after invoke once remove listener here
1697 // only browser need to do this, nodejs eventEmitter will cal removeListener
1698 // inside EventEmitter.once
1699 var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
1700 target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options);
1701 }
1702 };
1703 // global shared zoneAwareCallback to handle all event callback with capture = false
1704 var globalZoneAwareCallback = function (event) {
1705 // https://github.com/angular/zone.js/issues/911, in IE, sometimes
1706 // event will be undefined, so we need to use window.event
1707 event = event || _global.event;
1708 if (!event) {
1709 return;
1710 }
1711 // event.target is needed for Samsung TV and SourceBuffer
1712 // || global is needed https://github.com/angular/zone.js/issues/190
1713 var target = this || event.target || _global;
1714 var tasks = target[zoneSymbolEventNames$1[event.type][FALSE_STR]];
1715 if (tasks) {
1716 // invoke all tasks which attached to current target with given event.type and capture = false
1717 // for performance concern, if task.length === 1, just invoke
1718 if (tasks.length === 1) {
1719 invokeTask(tasks[0], target, event);
1720 }
1721 else {
1722 // https://github.com/angular/zone.js/issues/836
1723 // copy the tasks array before invoke, to avoid
1724 // the callback will remove itself or other listener
1725 var copyTasks = tasks.slice();
1726 for (var i = 0; i < copyTasks.length; i++) {
1727 if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
1728 break;
1729 }
1730 invokeTask(copyTasks[i], target, event);
1731 }
1732 }
1733 }
1734 };
1735 // global shared zoneAwareCallback to handle all event callback with capture = true
1736 var globalZoneAwareCaptureCallback = function (event) {
1737 // https://github.com/angular/zone.js/issues/911, in IE, sometimes
1738 // event will be undefined, so we need to use window.event
1739 event = event || _global.event;
1740 if (!event) {
1741 return;
1742 }
1743 // event.target is needed for Samsung TV and SourceBuffer
1744 // || global is needed https://github.com/angular/zone.js/issues/190
1745 var target = this || event.target || _global;
1746 var tasks = target[zoneSymbolEventNames$1[event.type][TRUE_STR]];
1747 if (tasks) {
1748 // invoke all tasks which attached to current target with given event.type and capture = false
1749 // for performance concern, if task.length === 1, just invoke
1750 if (tasks.length === 1) {
1751 invokeTask(tasks[0], target, event);
1752 }
1753 else {
1754 // https://github.com/angular/zone.js/issues/836
1755 // copy the tasks array before invoke, to avoid
1756 // the callback will remove itself or other listener
1757 var copyTasks = tasks.slice();
1758 for (var i = 0; i < copyTasks.length; i++) {
1759 if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
1760 break;
1761 }
1762 invokeTask(copyTasks[i], target, event);
1763 }
1764 }
1765 }
1766 };
1767 function patchEventTargetMethods(obj, patchOptions) {
1768 if (!obj) {
1769 return false;
1770 }
1771 var useGlobalCallback = true;
1772 if (patchOptions && patchOptions.useG !== undefined) {
1773 useGlobalCallback = patchOptions.useG;
1774 }
1775 var validateHandler = patchOptions && patchOptions.vh;
1776 var checkDuplicate = true;
1777 if (patchOptions && patchOptions.chkDup !== undefined) {
1778 checkDuplicate = patchOptions.chkDup;
1779 }
1780 var returnTarget = false;
1781 if (patchOptions && patchOptions.rt !== undefined) {
1782 returnTarget = patchOptions.rt;
1783 }
1784 var proto = obj;
1785 while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
1786 proto = ObjectGetPrototypeOf(proto);
1787 }
1788 if (!proto && obj[ADD_EVENT_LISTENER]) {
1789 // somehow we did not find it, but we can see it. This happens on IE for Window properties.
1790 proto = obj;
1791 }
1792 if (!proto) {
1793 return false;
1794 }
1795 if (proto[zoneSymbolAddEventListener]) {
1796 return false;
1797 }
1798 var eventNameToString = patchOptions && patchOptions.eventNameToString;
1799 // a shared global taskData to pass data for scheduleEventTask
1800 // so we do not need to create a new object just for pass some data
1801 var taskData = {};
1802 var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
1803 var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
1804 proto[REMOVE_EVENT_LISTENER];
1805 var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
1806 proto[LISTENERS_EVENT_LISTENER];
1807 var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
1808 proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
1809 var nativePrependEventListener;
1810 if (patchOptions && patchOptions.prepend) {
1811 nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
1812 proto[patchOptions.prepend];
1813 }
1814 function checkIsPassive(task) {
1815 if (!passiveSupported && typeof taskData.options !== 'boolean' &&
1816 typeof taskData.options !== 'undefined' && taskData.options !== null) {
1817 // options is a non-null non-undefined object
1818 // passive is not supported
1819 // don't pass options as object
1820 // just pass capture as a boolean
1821 task.options = !!taskData.options.capture;
1822 taskData.options = task.options;
1823 }
1824 }
1825 var customScheduleGlobal = function (task) {
1826 // if there is already a task for the eventName + capture,
1827 // just return, because we use the shared globalZoneAwareCallback here.
1828 if (taskData.isExisting) {
1829 return;
1830 }
1831 checkIsPassive(task);
1832 return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
1833 };
1834 var customCancelGlobal = function (task) {
1835 // if task is not marked as isRemoved, this call is directly
1836 // from Zone.prototype.cancelTask, we should remove the task
1837 // from tasksList of target first
1838 if (!task.isRemoved) {
1839 var symbolEventNames = zoneSymbolEventNames$1[task.eventName];
1840 var symbolEventName = void 0;
1841 if (symbolEventNames) {
1842 symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
1843 }
1844 var existingTasks = symbolEventName && task.target[symbolEventName];
1845 if (existingTasks) {
1846 for (var i = 0; i < existingTasks.length; i++) {
1847 var existingTask = existingTasks[i];
1848 if (existingTask === task) {
1849 existingTasks.splice(i, 1);
1850 // set isRemoved to data for faster invokeTask check
1851 task.isRemoved = true;
1852 if (existingTasks.length === 0) {
1853 // all tasks for the eventName + capture have gone,
1854 // remove globalZoneAwareCallback and remove the task cache from target
1855 task.allRemoved = true;
1856 task.target[symbolEventName] = null;
1857 }
1858 break;
1859 }
1860 }
1861 }
1862 }
1863 // if all tasks for the eventName + capture have gone,
1864 // we will really remove the global event callback,
1865 // if not, return
1866 if (!task.allRemoved) {
1867 return;
1868 }
1869 return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
1870 };
1871 var customScheduleNonGlobal = function (task) {
1872 checkIsPassive(task);
1873 return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
1874 };
1875 var customSchedulePrepend = function (task) {
1876 return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
1877 };
1878 var customCancelNonGlobal = function (task) {
1879 return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
1880 };
1881 var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
1882 var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
1883 var compareTaskCallbackVsDelegate = function (task, delegate) {
1884 var typeOfDelegate = typeof delegate;
1885 return (typeOfDelegate === 'function' && task.callback === delegate) ||
1886 (typeOfDelegate === 'object' && task.originalDelegate === delegate);
1887 };
1888 var compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
1889 var blackListedEvents = Zone[Zone.__symbol__('BLACK_LISTED_EVENTS')];
1890 var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
1891 if (returnTarget === void 0) { returnTarget = false; }
1892 if (prepend === void 0) { prepend = false; }
1893 return function () {
1894 var target = this || _global;
1895 var eventName = arguments[0];
1896 var delegate = arguments[1];
1897 if (!delegate) {
1898 return nativeListener.apply(this, arguments);
1899 }
1900 if (isNode && eventName === 'uncaughtException') {
1901 // don't patch uncaughtException of nodejs to prevent endless loop
1902 return nativeListener.apply(this, arguments);
1903 }
1904 // don't create the bind delegate function for handleEvent
1905 // case here to improve addEventListener performance
1906 // we will create the bind delegate when invoke
1907 var isHandleEvent = false;
1908 if (typeof delegate !== 'function') {
1909 if (!delegate.handleEvent) {
1910 return nativeListener.apply(this, arguments);
1911 }
1912 isHandleEvent = true;
1913 }
1914 if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
1915 return;
1916 }
1917 var options = arguments[2];
1918 if (blackListedEvents) {
1919 // check black list
1920 for (var i = 0; i < blackListedEvents.length; i++) {
1921 if (eventName === blackListedEvents[i]) {
1922 return nativeListener.apply(this, arguments);
1923 }
1924 }
1925 }
1926 var capture;
1927 var once = false;
1928 if (options === undefined) {
1929 capture = false;
1930 }
1931 else if (options === true) {
1932 capture = true;
1933 }
1934 else if (options === false) {
1935 capture = false;
1936 }
1937 else {
1938 capture = options ? !!options.capture : false;
1939 once = options ? !!options.once : false;
1940 }
1941 var zone = Zone.current;
1942 var symbolEventNames = zoneSymbolEventNames$1[eventName];
1943 var symbolEventName;
1944 if (!symbolEventNames) {
1945 // the code is duplicate, but I just want to get some better performance
1946 var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
1947 var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
1948 var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
1949 var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
1950 zoneSymbolEventNames$1[eventName] = {};
1951 zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol;
1952 zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture;
1953 symbolEventName = capture ? symbolCapture : symbol;
1954 }
1955 else {
1956 symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
1957 }
1958 var existingTasks = target[symbolEventName];
1959 var isExisting = false;
1960 if (existingTasks) {
1961 // already have task registered
1962 isExisting = true;
1963 if (checkDuplicate) {
1964 for (var i = 0; i < existingTasks.length; i++) {
1965 if (compare(existingTasks[i], delegate)) {
1966 // same callback, same capture, same event name, just return
1967 return;
1968 }
1969 }
1970 }
1971 }
1972 else {
1973 existingTasks = target[symbolEventName] = [];
1974 }
1975 var source;
1976 var constructorName = target.constructor['name'];
1977 var targetSource = globalSources[constructorName];
1978 if (targetSource) {
1979 source = targetSource[eventName];
1980 }
1981 if (!source) {
1982 source = constructorName + addSource +
1983 (eventNameToString ? eventNameToString(eventName) : eventName);
1984 }
1985 // do not create a new object as task.data to pass those things
1986 // just use the global shared one
1987 taskData.options = options;
1988 if (once) {
1989 // if addEventListener with once options, we don't pass it to
1990 // native addEventListener, instead we keep the once setting
1991 // and handle ourselves.
1992 taskData.options.once = false;
1993 }
1994 taskData.target = target;
1995 taskData.capture = capture;
1996 taskData.eventName = eventName;
1997 taskData.isExisting = isExisting;
1998 var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
1999 // keep taskData into data to allow onScheduleEventTask to access the task information
2000 if (data) {
2001 data.taskData = taskData;
2002 }
2003 var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
2004 // should clear taskData.target to avoid memory leak
2005 // issue, https://github.com/angular/angular/issues/20442
2006 taskData.target = null;
2007 // need to clear up taskData because it is a global object
2008 if (data) {
2009 data.taskData = null;
2010 }
2011 // have to save those information to task in case
2012 // application may call task.zone.cancelTask() directly
2013 if (once) {
2014 options.once = true;
2015 }
2016 if (!(!passiveSupported && typeof task.options === 'boolean')) {
2017 // if not support passive, and we pass an option object
2018 // to addEventListener, we should save the options to task
2019 task.options = options;
2020 }
2021 task.target = target;
2022 task.capture = capture;
2023 task.eventName = eventName;
2024 if (isHandleEvent) {
2025 // save original delegate for compare to check duplicate
2026 task.originalDelegate = delegate;
2027 }
2028 if (!prepend) {
2029 existingTasks.push(task);
2030 }
2031 else {
2032 existingTasks.unshift(task);
2033 }
2034 if (returnTarget) {
2035 return target;
2036 }
2037 };
2038 };
2039 proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
2040 if (nativePrependEventListener) {
2041 proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
2042 }
2043 proto[REMOVE_EVENT_LISTENER] = function () {
2044 var target = this || _global;
2045 var eventName = arguments[0];
2046 var options = arguments[2];
2047 var capture;
2048 if (options === undefined) {
2049 capture = false;
2050 }
2051 else if (options === true) {
2052 capture = true;
2053 }
2054 else if (options === false) {
2055 capture = false;
2056 }
2057 else {
2058 capture = options ? !!options.capture : false;
2059 }
2060 var delegate = arguments[1];
2061 if (!delegate) {
2062 return nativeRemoveEventListener.apply(this, arguments);
2063 }
2064 if (validateHandler &&
2065 !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
2066 return;
2067 }
2068 var symbolEventNames = zoneSymbolEventNames$1[eventName];
2069 var symbolEventName;
2070 if (symbolEventNames) {
2071 symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
2072 }
2073 var existingTasks = symbolEventName && target[symbolEventName];
2074 if (existingTasks) {
2075 for (var i = 0; i < existingTasks.length; i++) {
2076 var existingTask = existingTasks[i];
2077 if (compare(existingTask, delegate)) {
2078 existingTasks.splice(i, 1);
2079 // set isRemoved to data for faster invokeTask check
2080 existingTask.isRemoved = true;
2081 if (existingTasks.length === 0) {
2082 // all tasks for the eventName + capture have gone,
2083 // remove globalZoneAwareCallback and remove the task cache from target
2084 existingTask.allRemoved = true;
2085 target[symbolEventName] = null;
2086 }
2087 existingTask.zone.cancelTask(existingTask);
2088 if (returnTarget) {
2089 return target;
2090 }
2091 return;
2092 }
2093 }
2094 }
2095 // issue 930, didn't find the event name or callback
2096 // from zone kept existingTasks, the callback maybe
2097 // added outside of zone, we need to call native removeEventListener
2098 // to try to remove it.
2099 return nativeRemoveEventListener.apply(this, arguments);
2100 };
2101 proto[LISTENERS_EVENT_LISTENER] = function () {
2102 var target = this || _global;
2103 var eventName = arguments[0];
2104 var listeners = [];
2105 var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
2106 for (var i = 0; i < tasks.length; i++) {
2107 var task = tasks[i];
2108 var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
2109 listeners.push(delegate);
2110 }
2111 return listeners;
2112 };
2113 proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
2114 var target = this || _global;
2115 var eventName = arguments[0];
2116 if (!eventName) {
2117 var keys = Object.keys(target);
2118 for (var i = 0; i < keys.length; i++) {
2119 var prop = keys[i];
2120 var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
2121 var evtName = match && match[1];
2122 // in nodejs EventEmitter, removeListener event is
2123 // used for monitoring the removeListener call,
2124 // so just keep removeListener eventListener until
2125 // all other eventListeners are removed
2126 if (evtName && evtName !== 'removeListener') {
2127 this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
2128 }
2129 }
2130 // remove removeListener listener finally
2131 this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
2132 }
2133 else {
2134 var symbolEventNames = zoneSymbolEventNames$1[eventName];
2135 if (symbolEventNames) {
2136 var symbolEventName = symbolEventNames[FALSE_STR];
2137 var symbolCaptureEventName = symbolEventNames[TRUE_STR];
2138 var tasks = target[symbolEventName];
2139 var captureTasks = target[symbolCaptureEventName];
2140 if (tasks) {
2141 var removeTasks = tasks.slice();
2142 for (var i = 0; i < removeTasks.length; i++) {
2143 var task = removeTasks[i];
2144 var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
2145 this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
2146 }
2147 }
2148 if (captureTasks) {
2149 var removeTasks = captureTasks.slice();
2150 for (var i = 0; i < removeTasks.length; i++) {
2151 var task = removeTasks[i];
2152 var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
2153 this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
2154 }
2155 }
2156 }
2157 }
2158 if (returnTarget) {
2159 return this;
2160 }
2161 };
2162 // for native toString patch
2163 attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
2164 attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
2165 if (nativeRemoveAllListeners) {
2166 attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
2167 }
2168 if (nativeListeners) {
2169 attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
2170 }
2171 return true;
2172 }
2173 var results = [];
2174 for (var i = 0; i < apis.length; i++) {
2175 results[i] = patchEventTargetMethods(apis[i], patchOptions);
2176 }
2177 return results;
2178}
2179function findEventTasks(target, eventName) {
2180 var foundTasks = [];
2181 for (var prop in target) {
2182 var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
2183 var evtName = match && match[1];
2184 if (evtName && (!eventName || evtName === eventName)) {
2185 var tasks = target[prop];
2186 if (tasks) {
2187 for (var i = 0; i < tasks.length; i++) {
2188 foundTasks.push(tasks[i]);
2189 }
2190 }
2191 }
2192 }
2193 return foundTasks;
2194}
2195function patchEventPrototype(global, api) {
2196 var Event = global['Event'];
2197 if (Event && Event.prototype) {
2198 api.patchMethod(Event.prototype, 'stopImmediatePropagation', function (delegate) { return function (self, args) {
2199 self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
2200 // we need to call the native stopImmediatePropagation
2201 // in case in some hybrid application, some part of
2202 // application will be controlled by zone, some are not
2203 delegate && delegate.apply(self, args);
2204 }; });
2205 }
2206}
2207
2208/**
2209 * @license
2210 * Copyright Google Inc. All Rights Reserved.
2211 *
2212 * Use of this source code is governed by an MIT-style license that can be
2213 * found in the LICENSE file at https://angular.io/license
2214 */
2215function patchCallbacks(api, target, targetName, method, callbacks) {
2216 var symbol = Zone.__symbol__(method);
2217 if (target[symbol]) {
2218 return;
2219 }
2220 var nativeDelegate = target[symbol] = target[method];
2221 target[method] = function (name, opts, options) {
2222 if (opts && opts.prototype) {
2223 callbacks.forEach(function (callback) {
2224 var source = targetName + "." + method + "::" + callback;
2225 var prototype = opts.prototype;
2226 if (prototype.hasOwnProperty(callback)) {
2227 var descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
2228 if (descriptor && descriptor.value) {
2229 descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
2230 api._redefineProperty(opts.prototype, callback, descriptor);
2231 }
2232 else if (prototype[callback]) {
2233 prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
2234 }
2235 }
2236 else if (prototype[callback]) {
2237 prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
2238 }
2239 });
2240 }
2241 return nativeDelegate.call(target, name, opts, options);
2242 };
2243 api.attachOriginToPatched(target[method], nativeDelegate);
2244}
2245
2246/**
2247 * @license
2248 * Copyright Google Inc. All Rights Reserved.
2249 *
2250 * Use of this source code is governed by an MIT-style license that can be
2251 * found in the LICENSE file at https://angular.io/license
2252 */
2253/*
2254 * This is necessary for Chrome and Chrome mobile, to enable
2255 * things like redefining `createdCallback` on an element.
2256 */
2257var zoneSymbol$1 = Zone.__symbol__;
2258var _defineProperty = Object[zoneSymbol$1('defineProperty')] = Object.defineProperty;
2259var _getOwnPropertyDescriptor = Object[zoneSymbol$1('getOwnPropertyDescriptor')] =
2260 Object.getOwnPropertyDescriptor;
2261var _create = Object.create;
2262var unconfigurablesKey = zoneSymbol$1('unconfigurables');
2263function propertyPatch() {
2264 Object.defineProperty = function (obj, prop, desc) {
2265 if (isUnconfigurable(obj, prop)) {
2266 throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj);
2267 }
2268 var originalConfigurableFlag = desc.configurable;
2269 if (prop !== 'prototype') {
2270 desc = rewriteDescriptor(obj, prop, desc);
2271 }
2272 return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
2273 };
2274 Object.defineProperties = function (obj, props) {
2275 Object.keys(props).forEach(function (prop) {
2276 Object.defineProperty(obj, prop, props[prop]);
2277 });
2278 return obj;
2279 };
2280 Object.create = function (obj, proto) {
2281 if (typeof proto === 'object' && !Object.isFrozen(proto)) {
2282 Object.keys(proto).forEach(function (prop) {
2283 proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);
2284 });
2285 }
2286 return _create(obj, proto);
2287 };
2288 Object.getOwnPropertyDescriptor = function (obj, prop) {
2289 var desc = _getOwnPropertyDescriptor(obj, prop);
2290 if (desc && isUnconfigurable(obj, prop)) {
2291 desc.configurable = false;
2292 }
2293 return desc;
2294 };
2295}
2296function _redefineProperty(obj, prop, desc) {
2297 var originalConfigurableFlag = desc.configurable;
2298 desc = rewriteDescriptor(obj, prop, desc);
2299 return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
2300}
2301function isUnconfigurable(obj, prop) {
2302 return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];
2303}
2304function rewriteDescriptor(obj, prop, desc) {
2305 // issue-927, if the desc is frozen, don't try to change the desc
2306 if (!Object.isFrozen(desc)) {
2307 desc.configurable = true;
2308 }
2309 if (!desc.configurable) {
2310 // issue-927, if the obj is frozen, don't try to set the desc to obj
2311 if (!obj[unconfigurablesKey] && !Object.isFrozen(obj)) {
2312 _defineProperty(obj, unconfigurablesKey, { writable: true, value: {} });
2313 }
2314 if (obj[unconfigurablesKey]) {
2315 obj[unconfigurablesKey][prop] = true;
2316 }
2317 }
2318 return desc;
2319}
2320function _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) {
2321 try {
2322 return _defineProperty(obj, prop, desc);
2323 }
2324 catch (error) {
2325 if (desc.configurable) {
2326 // In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's
2327 // retry with the original flag value
2328 if (typeof originalConfigurableFlag == 'undefined') {
2329 delete desc.configurable;
2330 }
2331 else {
2332 desc.configurable = originalConfigurableFlag;
2333 }
2334 try {
2335 return _defineProperty(obj, prop, desc);
2336 }
2337 catch (error) {
2338 var descJson = null;
2339 try {
2340 descJson = JSON.stringify(desc);
2341 }
2342 catch (error) {
2343 descJson = desc.toString();
2344 }
2345 console.log("Attempting to configure '" + prop + "' with descriptor '" + descJson + "' on object '" + obj + "' and got error, giving up: " + error);
2346 }
2347 }
2348 else {
2349 throw error;
2350 }
2351 }
2352}
2353
2354/**
2355 * @license
2356 * Copyright Google Inc. All Rights Reserved.
2357 *
2358 * Use of this source code is governed by an MIT-style license that can be
2359 * found in the LICENSE file at https://angular.io/license
2360 */
2361/**
2362 * @fileoverview
2363 * @suppress {globalThis}
2364 */
2365var globalEventHandlersEventNames = [
2366 'abort',
2367 'animationcancel',
2368 'animationend',
2369 'animationiteration',
2370 'auxclick',
2371 'beforeinput',
2372 'blur',
2373 'cancel',
2374 'canplay',
2375 'canplaythrough',
2376 'change',
2377 'compositionstart',
2378 'compositionupdate',
2379 'compositionend',
2380 'cuechange',
2381 'click',
2382 'close',
2383 'contextmenu',
2384 'curechange',
2385 'dblclick',
2386 'drag',
2387 'dragend',
2388 'dragenter',
2389 'dragexit',
2390 'dragleave',
2391 'dragover',
2392 'drop',
2393 'durationchange',
2394 'emptied',
2395 'ended',
2396 'error',
2397 'focus',
2398 'focusin',
2399 'focusout',
2400 'gotpointercapture',
2401 'input',
2402 'invalid',
2403 'keydown',
2404 'keypress',
2405 'keyup',
2406 'load',
2407 'loadstart',
2408 'loadeddata',
2409 'loadedmetadata',
2410 'lostpointercapture',
2411 'mousedown',
2412 'mouseenter',
2413 'mouseleave',
2414 'mousemove',
2415 'mouseout',
2416 'mouseover',
2417 'mouseup',
2418 'mousewheel',
2419 'orientationchange',
2420 'pause',
2421 'play',
2422 'playing',
2423 'pointercancel',
2424 'pointerdown',
2425 'pointerenter',
2426 'pointerleave',
2427 'pointerlockchange',
2428 'mozpointerlockchange',
2429 'webkitpointerlockerchange',
2430 'pointerlockerror',
2431 'mozpointerlockerror',
2432 'webkitpointerlockerror',
2433 'pointermove',
2434 'pointout',
2435 'pointerover',
2436 'pointerup',
2437 'progress',
2438 'ratechange',
2439 'reset',
2440 'resize',
2441 'scroll',
2442 'seeked',
2443 'seeking',
2444 'select',
2445 'selectionchange',
2446 'selectstart',
2447 'show',
2448 'sort',
2449 'stalled',
2450 'submit',
2451 'suspend',
2452 'timeupdate',
2453 'volumechange',
2454 'touchcancel',
2455 'touchmove',
2456 'touchstart',
2457 'touchend',
2458 'transitioncancel',
2459 'transitionend',
2460 'waiting',
2461 'wheel'
2462];
2463var documentEventNames = [
2464 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange',
2465 'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
2466 'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
2467 'visibilitychange', 'resume'
2468];
2469var windowEventNames = [
2470 'absolutedeviceorientation',
2471 'afterinput',
2472 'afterprint',
2473 'appinstalled',
2474 'beforeinstallprompt',
2475 'beforeprint',
2476 'beforeunload',
2477 'devicelight',
2478 'devicemotion',
2479 'deviceorientation',
2480 'deviceorientationabsolute',
2481 'deviceproximity',
2482 'hashchange',
2483 'languagechange',
2484 'message',
2485 'mozbeforepaint',
2486 'offline',
2487 'online',
2488 'paint',
2489 'pageshow',
2490 'pagehide',
2491 'popstate',
2492 'rejectionhandled',
2493 'storage',
2494 'unhandledrejection',
2495 'unload',
2496 'userproximity',
2497 'vrdisplyconnected',
2498 'vrdisplaydisconnected',
2499 'vrdisplaypresentchange'
2500];
2501var htmlElementEventNames = [
2502 'beforecopy', 'beforecut', 'beforepaste', 'copy', 'cut', 'paste', 'dragstart', 'loadend',
2503 'animationstart', 'search', 'transitionrun', 'transitionstart', 'webkitanimationend',
2504 'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend'
2505];
2506var mediaElementEventNames = ['encrypted', 'waitingforkey', 'msneedkey', 'mozinterruptbegin', 'mozinterruptend'];
2507var ieElementEventNames = [
2508 'activate',
2509 'afterupdate',
2510 'ariarequest',
2511 'beforeactivate',
2512 'beforedeactivate',
2513 'beforeeditfocus',
2514 'beforeupdate',
2515 'cellchange',
2516 'controlselect',
2517 'dataavailable',
2518 'datasetchanged',
2519 'datasetcomplete',
2520 'errorupdate',
2521 'filterchange',
2522 'layoutcomplete',
2523 'losecapture',
2524 'move',
2525 'moveend',
2526 'movestart',
2527 'propertychange',
2528 'resizeend',
2529 'resizestart',
2530 'rowenter',
2531 'rowexit',
2532 'rowsdelete',
2533 'rowsinserted',
2534 'command',
2535 'compassneedscalibration',
2536 'deactivate',
2537 'help',
2538 'mscontentzoom',
2539 'msmanipulationstatechanged',
2540 'msgesturechange',
2541 'msgesturedoubletap',
2542 'msgestureend',
2543 'msgesturehold',
2544 'msgesturestart',
2545 'msgesturetap',
2546 'msgotpointercapture',
2547 'msinertiastart',
2548 'mslostpointercapture',
2549 'mspointercancel',
2550 'mspointerdown',
2551 'mspointerenter',
2552 'mspointerhover',
2553 'mspointerleave',
2554 'mspointermove',
2555 'mspointerout',
2556 'mspointerover',
2557 'mspointerup',
2558 'pointerout',
2559 'mssitemodejumplistitemremoved',
2560 'msthumbnailclick',
2561 'stop',
2562 'storagecommit'
2563];
2564var webglEventNames = ['webglcontextrestored', 'webglcontextlost', 'webglcontextcreationerror'];
2565var formEventNames = ['autocomplete', 'autocompleteerror'];
2566var detailEventNames = ['toggle'];
2567var frameEventNames = ['load'];
2568var frameSetEventNames = ['blur', 'error', 'focus', 'load', 'resize', 'scroll', 'messageerror'];
2569var marqueeEventNames = ['bounce', 'finish', 'start'];
2570var XMLHttpRequestEventNames = [
2571 'loadstart', 'progress', 'abort', 'error', 'load', 'progress', 'timeout', 'loadend',
2572 'readystatechange'
2573];
2574var IDBIndexEventNames = ['upgradeneeded', 'complete', 'abort', 'success', 'error', 'blocked', 'versionchange', 'close'];
2575var websocketEventNames = ['close', 'error', 'open', 'message'];
2576var workerEventNames = ['error', 'message'];
2577var eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames);
2578function filterProperties(target, onProperties, ignoreProperties) {
2579 if (!ignoreProperties || ignoreProperties.length === 0) {
2580 return onProperties;
2581 }
2582 var tip = ignoreProperties.filter(function (ip) { return ip.target === target; });
2583 if (!tip || tip.length === 0) {
2584 return onProperties;
2585 }
2586 var targetIgnoreProperties = tip[0].ignoreProperties;
2587 return onProperties.filter(function (op) { return targetIgnoreProperties.indexOf(op) === -1; });
2588}
2589function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
2590 // check whether target is available, sometimes target will be undefined
2591 // because different browser or some 3rd party plugin.
2592 if (!target) {
2593 return;
2594 }
2595 var filteredProperties = filterProperties(target, onProperties, ignoreProperties);
2596 patchOnProperties(target, filteredProperties, prototype);
2597}
2598function propertyDescriptorPatch(api, _global) {
2599 if (isNode && !isMix) {
2600 return;
2601 }
2602 if (Zone[api.symbol('patchEvents')]) {
2603 // events are already been patched by legacy patch.
2604 return;
2605 }
2606 var supportsWebSocket = typeof WebSocket !== 'undefined';
2607 var ignoreProperties = _global['__Zone_ignore_on_properties'];
2608 // for browsers that we can patch the descriptor: Chrome & Firefox
2609 if (isBrowser) {
2610 var internalWindow = window;
2611 var ignoreErrorProperties = isIE ? [{ target: internalWindow, ignoreProperties: ['error'] }] : [];
2612 // in IE/Edge, onProp not exist in window object, but in WindowPrototype
2613 // so we need to pass WindowPrototype to check onProp exist or not
2614 patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
2615 patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
2616 if (typeof internalWindow['SVGElement'] !== 'undefined') {
2617 patchFilteredProperties(internalWindow['SVGElement'].prototype, eventNames, ignoreProperties);
2618 }
2619 patchFilteredProperties(Element.prototype, eventNames, ignoreProperties);
2620 patchFilteredProperties(HTMLElement.prototype, eventNames, ignoreProperties);
2621 patchFilteredProperties(HTMLMediaElement.prototype, mediaElementEventNames, ignoreProperties);
2622 patchFilteredProperties(HTMLFrameSetElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
2623 patchFilteredProperties(HTMLBodyElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
2624 patchFilteredProperties(HTMLFrameElement.prototype, frameEventNames, ignoreProperties);
2625 patchFilteredProperties(HTMLIFrameElement.prototype, frameEventNames, ignoreProperties);
2626 var HTMLMarqueeElement_1 = internalWindow['HTMLMarqueeElement'];
2627 if (HTMLMarqueeElement_1) {
2628 patchFilteredProperties(HTMLMarqueeElement_1.prototype, marqueeEventNames, ignoreProperties);
2629 }
2630 var Worker_1 = internalWindow['Worker'];
2631 if (Worker_1) {
2632 patchFilteredProperties(Worker_1.prototype, workerEventNames, ignoreProperties);
2633 }
2634 }
2635 var XMLHttpRequest = _global['XMLHttpRequest'];
2636 if (XMLHttpRequest) {
2637 // XMLHttpRequest is not available in ServiceWorker, so we need to check here
2638 patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
2639 }
2640 var XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
2641 if (XMLHttpRequestEventTarget) {
2642 patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties);
2643 }
2644 if (typeof IDBIndex !== 'undefined') {
2645 patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
2646 patchFilteredProperties(IDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
2647 patchFilteredProperties(IDBOpenDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
2648 patchFilteredProperties(IDBDatabase.prototype, IDBIndexEventNames, ignoreProperties);
2649 patchFilteredProperties(IDBTransaction.prototype, IDBIndexEventNames, ignoreProperties);
2650 patchFilteredProperties(IDBCursor.prototype, IDBIndexEventNames, ignoreProperties);
2651 }
2652 if (supportsWebSocket) {
2653 patchFilteredProperties(WebSocket.prototype, websocketEventNames, ignoreProperties);
2654 }
2655}
2656
2657/**
2658 * @license
2659 * Copyright Google Inc. All Rights Reserved.
2660 *
2661 * Use of this source code is governed by an MIT-style license that can be
2662 * found in the LICENSE file at https://angular.io/license
2663 */
2664Zone.__load_patch('util', function (global, Zone, api) {
2665 api.patchOnProperties = patchOnProperties;
2666 api.patchMethod = patchMethod;
2667 api.bindArguments = bindArguments;
2668 api.patchMacroTask = patchMacroTask;
2669 // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS` to
2670 // define which events will not be patched by `Zone.js`.
2671 // In newer version (>=0.9.0), we change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep
2672 // the name consistent with angular repo.
2673 // The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be supported for
2674 // backwards compatibility.
2675 var SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
2676 var SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
2677 if (global[SYMBOL_UNPATCHED_EVENTS]) {
2678 global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
2679 }
2680 if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
2681 Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
2682 global[SYMBOL_BLACK_LISTED_EVENTS];
2683 }
2684 api.patchEventPrototype = patchEventPrototype;
2685 api.patchEventTarget = patchEventTarget;
2686 api.isIEOrEdge = isIEOrEdge;
2687 api.ObjectDefineProperty = ObjectDefineProperty;
2688 api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
2689 api.ObjectCreate = ObjectCreate;
2690 api.ArraySlice = ArraySlice;
2691 api.patchClass = patchClass;
2692 api.wrapWithCurrentZone = wrapWithCurrentZone;
2693 api.filterProperties = filterProperties;
2694 api.attachOriginToPatched = attachOriginToPatched;
2695 api._redefineProperty = _redefineProperty;
2696 api.patchCallbacks = patchCallbacks;
2697 api.getGlobalObjects = function () { return ({
2698 globalSources: globalSources,
2699 zoneSymbolEventNames: zoneSymbolEventNames$1,
2700 eventNames: eventNames,
2701 isBrowser: isBrowser,
2702 isMix: isMix,
2703 isNode: isNode,
2704 TRUE_STR: TRUE_STR,
2705 FALSE_STR: FALSE_STR,
2706 ZONE_SYMBOL_PREFIX: ZONE_SYMBOL_PREFIX,
2707 ADD_EVENT_LISTENER_STR: ADD_EVENT_LISTENER_STR,
2708 REMOVE_EVENT_LISTENER_STR: REMOVE_EVENT_LISTENER_STR
2709 }); };
2710});
2711
2712/**
2713 * @license
2714 * Copyright Google Inc. All Rights Reserved.
2715 *
2716 * Use of this source code is governed by an MIT-style license that can be
2717 * found in the LICENSE file at https://angular.io/license
2718 */
2719
2720/**
2721 * @license
2722 * Copyright Google Inc. All Rights Reserved.
2723 *
2724 * Use of this source code is governed by an MIT-style license that can be
2725 * found in the LICENSE file at https://angular.io/license
2726 */
2727function eventTargetLegacyPatch(_global, api) {
2728 var _a = api.getGlobalObjects(), eventNames = _a.eventNames, globalSources = _a.globalSources, zoneSymbolEventNames = _a.zoneSymbolEventNames, TRUE_STR = _a.TRUE_STR, FALSE_STR = _a.FALSE_STR, ZONE_SYMBOL_PREFIX = _a.ZONE_SYMBOL_PREFIX;
2729 var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
2730 var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'
2731 .split(',');
2732 var EVENT_TARGET = 'EventTarget';
2733 var apis = [];
2734 var isWtf = _global['wtf'];
2735 var WTF_ISSUE_555_ARRAY = WTF_ISSUE_555.split(',');
2736 if (isWtf) {
2737 // Workaround for: https://github.com/google/tracing-framework/issues/555
2738 apis = WTF_ISSUE_555_ARRAY.map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET);
2739 }
2740 else if (_global[EVENT_TARGET]) {
2741 apis.push(EVENT_TARGET);
2742 }
2743 else {
2744 // Note: EventTarget is not available in all browsers,
2745 // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
2746 apis = NO_EVENT_TARGET;
2747 }
2748 var isDisableIECheck = _global['__Zone_disable_IE_check'] || false;
2749 var isEnableCrossContextCheck = _global['__Zone_enable_cross_context_check'] || false;
2750 var ieOrEdge = api.isIEOrEdge();
2751 var ADD_EVENT_LISTENER_SOURCE = '.addEventListener:';
2752 var FUNCTION_WRAPPER = '[object FunctionWrapper]';
2753 var BROWSER_TOOLS = 'function __BROWSERTOOLS_CONSOLE_SAFEFUNC() { [native code] }';
2754 // predefine all __zone_symbol__ + eventName + true/false string
2755 for (var i = 0; i < eventNames.length; i++) {
2756 var eventName = eventNames[i];
2757 var falseEventName = eventName + FALSE_STR;
2758 var trueEventName = eventName + TRUE_STR;
2759 var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
2760 var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
2761 zoneSymbolEventNames[eventName] = {};
2762 zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
2763 zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
2764 }
2765 // predefine all task.source string
2766 for (var i = 0; i < WTF_ISSUE_555.length; i++) {
2767 var target = WTF_ISSUE_555_ARRAY[i];
2768 var targets = globalSources[target] = {};
2769 for (var j = 0; j < eventNames.length; j++) {
2770 var eventName = eventNames[j];
2771 targets[eventName] = target + ADD_EVENT_LISTENER_SOURCE + eventName;
2772 }
2773 }
2774 var checkIEAndCrossContext = function (nativeDelegate, delegate, target, args) {
2775 if (!isDisableIECheck && ieOrEdge) {
2776 if (isEnableCrossContextCheck) {
2777 try {
2778 var testString = delegate.toString();
2779 if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
2780 nativeDelegate.apply(target, args);
2781 return false;
2782 }
2783 }
2784 catch (error) {
2785 nativeDelegate.apply(target, args);
2786 return false;
2787 }
2788 }
2789 else {
2790 var testString = delegate.toString();
2791 if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
2792 nativeDelegate.apply(target, args);
2793 return false;
2794 }
2795 }
2796 }
2797 else if (isEnableCrossContextCheck) {
2798 try {
2799 delegate.toString();
2800 }
2801 catch (error) {
2802 nativeDelegate.apply(target, args);
2803 return false;
2804 }
2805 }
2806 return true;
2807 };
2808 var apiTypes = [];
2809 for (var i = 0; i < apis.length; i++) {
2810 var type = _global[apis[i]];
2811 apiTypes.push(type && type.prototype);
2812 }
2813 // vh is validateHandler to check event handler
2814 // is valid or not(for security check)
2815 api.patchEventTarget(_global, apiTypes, { vh: checkIEAndCrossContext });
2816 Zone[api.symbol('patchEventTarget')] = !!_global[EVENT_TARGET];
2817 return true;
2818}
2819
2820/**
2821 * @license
2822 * Copyright Google Inc. All Rights Reserved.
2823 *
2824 * Use of this source code is governed by an MIT-style license that can be
2825 * found in the LICENSE file at https://angular.io/license
2826 */
2827// we have to patch the instance since the proto is non-configurable
2828function apply(api, _global) {
2829 var _a = api.getGlobalObjects(), ADD_EVENT_LISTENER_STR = _a.ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR = _a.REMOVE_EVENT_LISTENER_STR;
2830 var WS = _global.WebSocket;
2831 // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
2832 // On older Chrome, no need since EventTarget was already patched
2833 if (!_global.EventTarget) {
2834 api.patchEventTarget(_global, [WS.prototype]);
2835 }
2836 _global.WebSocket = function (x, y) {
2837 var socket = arguments.length > 1 ? new WS(x, y) : new WS(x);
2838 var proxySocket;
2839 var proxySocketProto;
2840 // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
2841 var onmessageDesc = api.ObjectGetOwnPropertyDescriptor(socket, 'onmessage');
2842 if (onmessageDesc && onmessageDesc.configurable === false) {
2843 proxySocket = api.ObjectCreate(socket);
2844 // socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror'
2845 // but proxySocket not, so we will keep socket as prototype and pass it to
2846 // patchOnProperties method
2847 proxySocketProto = socket;
2848 [ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function (propName) {
2849 proxySocket[propName] = function () {
2850 var args = api.ArraySlice.call(arguments);
2851 if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
2852 var eventName = args.length > 0 ? args[0] : undefined;
2853 if (eventName) {
2854 var propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
2855 socket[propertySymbol] = proxySocket[propertySymbol];
2856 }
2857 }
2858 return socket[propName].apply(socket, args);
2859 };
2860 });
2861 }
2862 else {
2863 // we can patch the real socket
2864 proxySocket = socket;
2865 }
2866 api.patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto);
2867 return proxySocket;
2868 };
2869 var globalWebSocket = _global['WebSocket'];
2870 for (var prop in WS) {
2871 globalWebSocket[prop] = WS[prop];
2872 }
2873}
2874
2875/**
2876 * @license
2877 * Copyright Google Inc. All Rights Reserved.
2878 *
2879 * Use of this source code is governed by an MIT-style license that can be
2880 * found in the LICENSE file at https://angular.io/license
2881 */
2882/**
2883 * @fileoverview
2884 * @suppress {globalThis}
2885 */
2886function propertyDescriptorLegacyPatch(api, _global) {
2887 var _a = api.getGlobalObjects(), isNode = _a.isNode, isMix = _a.isMix;
2888 if (isNode && !isMix) {
2889 return;
2890 }
2891 if (!canPatchViaPropertyDescriptor(api, _global)) {
2892 var supportsWebSocket = typeof WebSocket !== 'undefined';
2893 // Safari, Android browsers (Jelly Bean)
2894 patchViaCapturingAllTheEvents(api);
2895 api.patchClass('XMLHttpRequest');
2896 if (supportsWebSocket) {
2897 apply(api, _global);
2898 }
2899 Zone[api.symbol('patchEvents')] = true;
2900 }
2901}
2902function canPatchViaPropertyDescriptor(api, _global) {
2903 var _a = api.getGlobalObjects(), isBrowser = _a.isBrowser, isMix = _a.isMix;
2904 if ((isBrowser || isMix) &&
2905 !api.ObjectGetOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') &&
2906 typeof Element !== 'undefined') {
2907 // WebKit https://bugs.webkit.org/show_bug.cgi?id=134364
2908 // IDL interface attributes are not configurable
2909 var desc = api.ObjectGetOwnPropertyDescriptor(Element.prototype, 'onclick');
2910 if (desc && !desc.configurable)
2911 return false;
2912 // try to use onclick to detect whether we can patch via propertyDescriptor
2913 // because XMLHttpRequest is not available in service worker
2914 if (desc) {
2915 api.ObjectDefineProperty(Element.prototype, 'onclick', {
2916 enumerable: true,
2917 configurable: true,
2918 get: function () {
2919 return true;
2920 }
2921 });
2922 var div = document.createElement('div');
2923 var result = !!div.onclick;
2924 api.ObjectDefineProperty(Element.prototype, 'onclick', desc);
2925 return result;
2926 }
2927 }
2928 var XMLHttpRequest = _global['XMLHttpRequest'];
2929 if (!XMLHttpRequest) {
2930 // XMLHttpRequest is not available in service worker
2931 return false;
2932 }
2933 var ON_READY_STATE_CHANGE = 'onreadystatechange';
2934 var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
2935 var xhrDesc = api.ObjectGetOwnPropertyDescriptor(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE);
2936 // add enumerable and configurable here because in opera
2937 // by default XMLHttpRequest.prototype.onreadystatechange is undefined
2938 // without adding enumerable and configurable will cause onreadystatechange
2939 // non-configurable
2940 // and if XMLHttpRequest.prototype.onreadystatechange is undefined,
2941 // we should set a real desc instead a fake one
2942 if (xhrDesc) {
2943 api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, {
2944 enumerable: true,
2945 configurable: true,
2946 get: function () {
2947 return true;
2948 }
2949 });
2950 var req = new XMLHttpRequest();
2951 var result = !!req.onreadystatechange;
2952 // restore original desc
2953 api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, xhrDesc || {});
2954 return result;
2955 }
2956 else {
2957 var SYMBOL_FAKE_ONREADYSTATECHANGE_1 = api.symbol('fake');
2958 api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, {
2959 enumerable: true,
2960 configurable: true,
2961 get: function () {
2962 return this[SYMBOL_FAKE_ONREADYSTATECHANGE_1];
2963 },
2964 set: function (value) {
2965 this[SYMBOL_FAKE_ONREADYSTATECHANGE_1] = value;
2966 }
2967 });
2968 var req = new XMLHttpRequest();
2969 var detectFunc = function () { };
2970 req.onreadystatechange = detectFunc;
2971 var result = req[SYMBOL_FAKE_ONREADYSTATECHANGE_1] === detectFunc;
2972 req.onreadystatechange = null;
2973 return result;
2974 }
2975}
2976// Whenever any eventListener fires, we check the eventListener target and all parents
2977// for `onwhatever` properties and replace them with zone-bound functions
2978// - Chrome (for now)
2979function patchViaCapturingAllTheEvents(api) {
2980 var eventNames = api.getGlobalObjects().eventNames;
2981 var unboundKey = api.symbol('unbound');
2982 var _loop_1 = function (i) {
2983 var property = eventNames[i];
2984 var onproperty = 'on' + property;
2985 self.addEventListener(property, function (event) {
2986 var elt = event.target, bound, source;
2987 if (elt) {
2988 source = elt.constructor['name'] + '.' + onproperty;
2989 }
2990 else {
2991 source = 'unknown.' + onproperty;
2992 }
2993 while (elt) {
2994 if (elt[onproperty] && !elt[onproperty][unboundKey]) {
2995 bound = api.wrapWithCurrentZone(elt[onproperty], source);
2996 bound[unboundKey] = elt[onproperty];
2997 elt[onproperty] = bound;
2998 }
2999 elt = elt.parentElement;
3000 }
3001 }, true);
3002 };
3003 for (var i = 0; i < eventNames.length; i++) {
3004 _loop_1(i);
3005 }
3006}
3007
3008/**
3009 * @license
3010 * Copyright Google Inc. All Rights Reserved.
3011 *
3012 * Use of this source code is governed by an MIT-style license that can be
3013 * found in the LICENSE file at https://angular.io/license
3014 */
3015function registerElementPatch(_global, api) {
3016 var _a = api.getGlobalObjects(), isBrowser = _a.isBrowser, isMix = _a.isMix;
3017 if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) {
3018 return;
3019 }
3020 var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
3021 api.patchCallbacks(api, document, 'Document', 'registerElement', callbacks);
3022}
3023
3024/**
3025 * @license
3026 * Copyright Google Inc. All Rights Reserved.
3027 *
3028 * Use of this source code is governed by an MIT-style license that can be
3029 * found in the LICENSE file at https://angular.io/license
3030 */
3031/**
3032 * @fileoverview
3033 * @suppress {missingRequire}
3034 */
3035(function (_global) {
3036 _global['__zone_symbol__legacyPatch'] = function () {
3037 var Zone = _global['Zone'];
3038 Zone.__load_patch('registerElement', function (global, Zone, api) {
3039 registerElementPatch(global, api);
3040 });
3041 Zone.__load_patch('EventTargetLegacy', function (global, Zone, api) {
3042 eventTargetLegacyPatch(global, api);
3043 propertyDescriptorLegacyPatch(api, global);
3044 });
3045 };
3046})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
3047
3048/**
3049 * @license
3050 * Copyright Google Inc. All Rights Reserved.
3051 *
3052 * Use of this source code is governed by an MIT-style license that can be
3053 * found in the LICENSE file at https://angular.io/license
3054 */
3055/**
3056 * @fileoverview
3057 * @suppress {missingRequire}
3058 */
3059var taskSymbol = zoneSymbol('zoneTask');
3060function patchTimer(window, setName, cancelName, nameSuffix) {
3061 var setNative = null;
3062 var clearNative = null;
3063 setName += nameSuffix;
3064 cancelName += nameSuffix;
3065 var tasksByHandleId = {};
3066 function scheduleTask(task) {
3067 var data = task.data;
3068 function timer() {
3069 try {
3070 task.invoke.apply(this, arguments);
3071 }
3072 finally {
3073 // issue-934, task will be cancelled
3074 // even it is a periodic task such as
3075 // setInterval
3076 if (!(task.data && task.data.isPeriodic)) {
3077 if (typeof data.handleId === 'number') {
3078 // in non-nodejs env, we remove timerId
3079 // from local cache
3080 delete tasksByHandleId[data.handleId];
3081 }
3082 else if (data.handleId) {
3083 // Node returns complex objects as handleIds
3084 // we remove task reference from timer object
3085 data.handleId[taskSymbol] = null;
3086 }
3087 }
3088 }
3089 }
3090 data.args[0] = timer;
3091 data.handleId = setNative.apply(window, data.args);
3092 return task;
3093 }
3094 function clearTask(task) {
3095 return clearNative(task.data.handleId);
3096 }
3097 setNative =
3098 patchMethod(window, setName, function (delegate) { return function (self, args) {
3099 if (typeof args[0] === 'function') {
3100 var options = {
3101 isPeriodic: nameSuffix === 'Interval',
3102 delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
3103 undefined,
3104 args: args
3105 };
3106 var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
3107 if (!task) {
3108 return task;
3109 }
3110 // Node.js must additionally support the ref and unref functions.
3111 var handle = task.data.handleId;
3112 if (typeof handle === 'number') {
3113 // for non nodejs env, we save handleId: task
3114 // mapping in local cache for clearTimeout
3115 tasksByHandleId[handle] = task;
3116 }
3117 else if (handle) {
3118 // for nodejs env, we save task
3119 // reference in timerId Object for clearTimeout
3120 handle[taskSymbol] = task;
3121 }
3122 // check whether handle is null, because some polyfill or browser
3123 // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
3124 if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
3125 typeof handle.unref === 'function') {
3126 task.ref = handle.ref.bind(handle);
3127 task.unref = handle.unref.bind(handle);
3128 }
3129 if (typeof handle === 'number' || handle) {
3130 return handle;
3131 }
3132 return task;
3133 }
3134 else {
3135 // cause an error by calling it directly.
3136 return delegate.apply(window, args);
3137 }
3138 }; });
3139 clearNative =
3140 patchMethod(window, cancelName, function (delegate) { return function (self, args) {
3141 var id = args[0];
3142 var task;
3143 if (typeof id === 'number') {
3144 // non nodejs env.
3145 task = tasksByHandleId[id];
3146 }
3147 else {
3148 // nodejs env.
3149 task = id && id[taskSymbol];
3150 // other environments.
3151 if (!task) {
3152 task = id;
3153 }
3154 }
3155 if (task && typeof task.type === 'string') {
3156 if (task.state !== 'notScheduled' &&
3157 (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
3158 if (typeof id === 'number') {
3159 delete tasksByHandleId[id];
3160 }
3161 else if (id) {
3162 id[taskSymbol] = null;
3163 }
3164 // Do not cancel already canceled functions
3165 task.zone.cancelTask(task);
3166 }
3167 }
3168 else {
3169 // cause an error by calling it directly.
3170 delegate.apply(window, args);
3171 }
3172 }; });
3173}
3174
3175/**
3176 * @license
3177 * Copyright Google Inc. All Rights Reserved.
3178 *
3179 * Use of this source code is governed by an MIT-style license that can be
3180 * found in the LICENSE file at https://angular.io/license
3181 */
3182function patchCustomElements(_global, api) {
3183 var _a = api.getGlobalObjects(), isBrowser = _a.isBrowser, isMix = _a.isMix;
3184 if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
3185 return;
3186 }
3187 var callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
3188 api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
3189}
3190
3191/**
3192 * @license
3193 * Copyright Google Inc. All Rights Reserved.
3194 *
3195 * Use of this source code is governed by an MIT-style license that can be
3196 * found in the LICENSE file at https://angular.io/license
3197 */
3198function eventTargetPatch(_global, api) {
3199 if (Zone[api.symbol('patchEventTarget')]) {
3200 // EventTarget is already patched.
3201 return;
3202 }
3203 var _a = api.getGlobalObjects(), eventNames = _a.eventNames, zoneSymbolEventNames = _a.zoneSymbolEventNames, TRUE_STR = _a.TRUE_STR, FALSE_STR = _a.FALSE_STR, ZONE_SYMBOL_PREFIX = _a.ZONE_SYMBOL_PREFIX;
3204 // predefine all __zone_symbol__ + eventName + true/false string
3205 for (var i = 0; i < eventNames.length; i++) {
3206 var eventName = eventNames[i];
3207 var falseEventName = eventName + FALSE_STR;
3208 var trueEventName = eventName + TRUE_STR;
3209 var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
3210 var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
3211 zoneSymbolEventNames[eventName] = {};
3212 zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
3213 zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
3214 }
3215 var EVENT_TARGET = _global['EventTarget'];
3216 if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
3217 return;
3218 }
3219 api.patchEventTarget(_global, [EVENT_TARGET && EVENT_TARGET.prototype]);
3220 return true;
3221}
3222function patchEvent$1(global, api) {
3223 api.patchEventPrototype(global, api);
3224}
3225
3226/**
3227 * @license
3228 * Copyright Google Inc. All Rights Reserved.
3229 *
3230 * Use of this source code is governed by an MIT-style license that can be
3231 * found in the LICENSE file at https://angular.io/license
3232 */
3233/**
3234 * @fileoverview
3235 * @suppress {missingRequire}
3236 */
3237Zone.__load_patch('legacy', function (global) {
3238 var legacyPatch = global[Zone.__symbol__('legacyPatch')];
3239 if (legacyPatch) {
3240 legacyPatch();
3241 }
3242});
3243Zone.__load_patch('timers', function (global) {
3244 var set = 'set';
3245 var clear = 'clear';
3246 patchTimer(global, set, clear, 'Timeout');
3247 patchTimer(global, set, clear, 'Interval');
3248 patchTimer(global, set, clear, 'Immediate');
3249});
3250Zone.__load_patch('requestAnimationFrame', function (global) {
3251 patchTimer(global, 'request', 'cancel', 'AnimationFrame');
3252 patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
3253 patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
3254});
3255Zone.__load_patch('blocking', function (global, Zone) {
3256 var blockingMethods = ['alert', 'prompt', 'confirm'];
3257 for (var i = 0; i < blockingMethods.length; i++) {
3258 var name_1 = blockingMethods[i];
3259 patchMethod(global, name_1, function (delegate, symbol, name) {
3260 return function (s, args) {
3261 return Zone.current.run(delegate, global, args, name);
3262 };
3263 });
3264 }
3265});
3266Zone.__load_patch('EventTarget', function (global, Zone, api) {
3267 patchEvent$1(global, api);
3268 eventTargetPatch(global, api);
3269 // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
3270 var XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
3271 if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
3272 api.patchEventTarget(global, [XMLHttpRequestEventTarget.prototype]);
3273 }
3274 patchClass('MutationObserver');
3275 patchClass('WebKitMutationObserver');
3276 patchClass('IntersectionObserver');
3277 patchClass('FileReader');
3278});
3279Zone.__load_patch('on_property', function (global, Zone, api) {
3280 propertyDescriptorPatch(api, global);
3281 propertyPatch();
3282});
3283Zone.__load_patch('customElements', function (global, Zone, api) {
3284 patchCustomElements(global, api);
3285});
3286Zone.__load_patch('XHR', function (global, Zone) {
3287 // Treat XMLHttpRequest as a macrotask.
3288 patchXHR(global);
3289 var XHR_TASK = zoneSymbol('xhrTask');
3290 var XHR_SYNC = zoneSymbol('xhrSync');
3291 var XHR_LISTENER = zoneSymbol('xhrListener');
3292 var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
3293 var XHR_URL = zoneSymbol('xhrURL');
3294 var XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
3295 function patchXHR(window) {
3296 var XMLHttpRequest = window['XMLHttpRequest'];
3297 if (!XMLHttpRequest) {
3298 // XMLHttpRequest is not available in service worker
3299 return;
3300 }
3301 var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
3302 function findPendingTask(target) {
3303 return target[XHR_TASK];
3304 }
3305 var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
3306 var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
3307 if (!oriAddListener) {
3308 var XMLHttpRequestEventTarget_1 = window['XMLHttpRequestEventTarget'];
3309 if (XMLHttpRequestEventTarget_1) {
3310 var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget_1.prototype;
3311 oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
3312 oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
3313 }
3314 }
3315 var READY_STATE_CHANGE = 'readystatechange';
3316 var SCHEDULED = 'scheduled';
3317 function scheduleTask(task) {
3318 var data = task.data;
3319 var target = data.target;
3320 target[XHR_SCHEDULED] = false;
3321 target[XHR_ERROR_BEFORE_SCHEDULED] = false;
3322 // remove existing event listener
3323 var listener = target[XHR_LISTENER];
3324 if (!oriAddListener) {
3325 oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
3326 oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
3327 }
3328 if (listener) {
3329 oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
3330 }
3331 var newListener = target[XHR_LISTENER] = function () {
3332 if (target.readyState === target.DONE) {
3333 // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
3334 // readyState=4 multiple times, so we need to check task state here
3335 if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
3336 // check whether the xhr has registered onload listener
3337 // if that is the case, the task should invoke after all
3338 // onload listeners finish.
3339 var loadTasks = target['__zone_symbol__loadfalse'];
3340 if (loadTasks && loadTasks.length > 0) {
3341 var oriInvoke_1 = task.invoke;
3342 task.invoke = function () {
3343 // need to load the tasks again, because in other
3344 // load listener, they may remove themselves
3345 var loadTasks = target['__zone_symbol__loadfalse'];
3346 for (var i = 0; i < loadTasks.length; i++) {
3347 if (loadTasks[i] === task) {
3348 loadTasks.splice(i, 1);
3349 }
3350 }
3351 if (!data.aborted && task.state === SCHEDULED) {
3352 oriInvoke_1.call(task);
3353 }
3354 };
3355 loadTasks.push(task);
3356 }
3357 else {
3358 task.invoke();
3359 }
3360 }
3361 else if (!data.aborted && target[XHR_SCHEDULED] === false) {
3362 // error occurs when xhr.send()
3363 target[XHR_ERROR_BEFORE_SCHEDULED] = true;
3364 }
3365 }
3366 };
3367 oriAddListener.call(target, READY_STATE_CHANGE, newListener);
3368 var storedTask = target[XHR_TASK];
3369 if (!storedTask) {
3370 target[XHR_TASK] = task;
3371 }
3372 sendNative.apply(target, data.args);
3373 target[XHR_SCHEDULED] = true;
3374 return task;
3375 }
3376 function placeholderCallback() { }
3377 function clearTask(task) {
3378 var data = task.data;
3379 // Note - ideally, we would call data.target.removeEventListener here, but it's too late
3380 // to prevent it from firing. So instead, we store info for the event listener.
3381 data.aborted = true;
3382 return abortNative.apply(data.target, data.args);
3383 }
3384 var openNative = patchMethod(XMLHttpRequestPrototype, 'open', function () { return function (self, args) {
3385 self[XHR_SYNC] = args[2] == false;
3386 self[XHR_URL] = args[1];
3387 return openNative.apply(self, args);
3388 }; });
3389 var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
3390 var fetchTaskAborting = zoneSymbol('fetchTaskAborting');
3391 var fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
3392 var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () { return function (self, args) {
3393 if (Zone.current[fetchTaskScheduling] === true) {
3394 // a fetch is scheduling, so we are using xhr to polyfill fetch
3395 // and because we already schedule macroTask for fetch, we should
3396 // not schedule a macroTask for xhr again
3397 return sendNative.apply(self, args);
3398 }
3399 if (self[XHR_SYNC]) {
3400 // if the XHR is sync there is no task to schedule, just execute the code.
3401 return sendNative.apply(self, args);
3402 }
3403 else {
3404 var options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
3405 var task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
3406 if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
3407 task.state === SCHEDULED) {
3408 // xhr request throw error when send
3409 // we should invoke task instead of leaving a scheduled
3410 // pending macroTask
3411 task.invoke();
3412 }
3413 }
3414 }; });
3415 var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self, args) {
3416 var task = findPendingTask(self);
3417 if (task && typeof task.type == 'string') {
3418 // If the XHR has already completed, do nothing.
3419 // If the XHR has already been aborted, do nothing.
3420 // Fix #569, call abort multiple times before done will cause
3421 // macroTask task count be negative number
3422 if (task.cancelFn == null || (task.data && task.data.aborted)) {
3423 return;
3424 }
3425 task.zone.cancelTask(task);
3426 }
3427 else if (Zone.current[fetchTaskAborting] === true) {
3428 // the abort is called from fetch polyfill, we need to call native abort of XHR.
3429 return abortNative.apply(self, args);
3430 }
3431 // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
3432 // task
3433 // to cancel. Do nothing.
3434 }; });
3435 }
3436});
3437Zone.__load_patch('geolocation', function (global) {
3438 /// GEO_LOCATION
3439 if (global['navigator'] && global['navigator'].geolocation) {
3440 patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
3441 }
3442});
3443Zone.__load_patch('PromiseRejectionEvent', function (global, Zone) {
3444 // handle unhandled promise rejection
3445 function findPromiseRejectionHandler(evtName) {
3446 return function (e) {
3447 var eventTasks = findEventTasks(global, evtName);
3448 eventTasks.forEach(function (eventTask) {
3449 // windows has added unhandledrejection event listener
3450 // trigger the event listener
3451 var PromiseRejectionEvent = global['PromiseRejectionEvent'];
3452 if (PromiseRejectionEvent) {
3453 var evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection });
3454 eventTask.invoke(evt);
3455 }
3456 });
3457 };
3458 }
3459 if (global['PromiseRejectionEvent']) {
3460 Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
3461 findPromiseRejectionHandler('unhandledrejection');
3462 Zone[zoneSymbol('rejectionHandledHandler')] =
3463 findPromiseRejectionHandler('rejectionhandled');
3464 }
3465});
3466
3467/**
3468 * @license
3469 * Copyright Google Inc. All Rights Reserved.
3470 *
3471 * Use of this source code is governed by an MIT-style license that can be
3472 * found in the LICENSE file at https://angular.io/license
3473 */
3474
3475})));
3476
3477 function ProxyZoneSpec(defaultSpecDelegate) {
3478 if (defaultSpecDelegate === void 0) {
3479 defaultSpecDelegate = null;
3480 }
3481 this.defaultSpecDelegate = defaultSpecDelegate;
3482 this.name = 'ProxyZone';
3483 this._delegateSpec = null;
3484 this.properties = { ProxyZoneSpec: this };
3485 this.propertyKeys = null;
3486 this.lastTaskState = null;
3487 this.isNeedToTriggerHasTask = false;
3488 this.tasks = [];
3489 this.setDelegate(defaultSpecDelegate);
3490 }
3491 ProxyZoneSpec.get = function() {
3492 return Zone.current.get('ProxyZoneSpec');
3493 };
3494 ProxyZoneSpec.isLoaded = function() {
3495 return ProxyZoneSpec.get() instanceof ProxyZoneSpec;
3496 };
3497 ProxyZoneSpec.assertPresent = function() {
3498 if (!ProxyZoneSpec.isLoaded()) {
3499 throw new Error(
3500 "Expected to be running in 'ProxyZone', but it was not found."
3501 );
3502 }
3503 return ProxyZoneSpec.get();
3504 };
3505 ProxyZoneSpec.prototype.setDelegate = function(delegateSpec) {
3506 var _this = this;
3507 var isNewDelegate = this._delegateSpec !== delegateSpec;
3508 this._delegateSpec = delegateSpec;
3509 this.propertyKeys &&
3510 this.propertyKeys.forEach(function(key) {
3511 return delete _this.properties[key];
3512 });
3513 this.propertyKeys = null;
3514 if (delegateSpec && delegateSpec.properties) {
3515 this.propertyKeys = Object.keys(delegateSpec.properties);
3516 this.propertyKeys.forEach(function(k) {
3517 return (_this.properties[k] = delegateSpec.properties[k]);
3518 });
3519 }
3520 // if a new delegateSpec was set, check if we need to trigger hasTask
3521 if (
3522 isNewDelegate &&
3523 this.lastTaskState &&
3524 (this.lastTaskState.macroTask || this.lastTaskState.microTask)
3525 ) {
3526 this.isNeedToTriggerHasTask = true;
3527 }
3528 };
3529 ProxyZoneSpec.prototype.getDelegate = function() {
3530 return this._delegateSpec;
3531 };
3532 ProxyZoneSpec.prototype.resetDelegate = function() {
3533 var delegateSpec = this.getDelegate();
3534 this.setDelegate(this.defaultSpecDelegate);
3535 };
3536 ProxyZoneSpec.prototype.tryTriggerHasTask = function(
3537 parentZoneDelegate,
3538 currentZone,
3539 targetZone
3540 ) {
3541 if (this.isNeedToTriggerHasTask && this.lastTaskState) {
3542 // last delegateSpec has microTask or macroTask
3543 // should call onHasTask in current delegateSpec
3544 this.isNeedToTriggerHasTask = false;
3545 this.onHasTask(
3546 parentZoneDelegate,
3547 currentZone,
3548 targetZone,
3549 this.lastTaskState
3550 );
3551 }
3552 };
3553 ProxyZoneSpec.prototype.removeFromTasks = function(task) {
3554 if (!this.tasks) {
3555 return;
3556 }
3557 for (var i = 0; i < this.tasks.length; i++) {
3558 if (this.tasks[i] === task) {
3559 this.tasks.splice(i, 1);
3560 return;
3561 }
3562 }
3563 };
3564 ProxyZoneSpec.prototype.getAndClearPendingTasksInfo = function() {
3565 if (this.tasks.length === 0) {
3566 return '';
3567 }
3568 var taskInfo = this.tasks.map(function(task) {
3569 var dataInfo =
3570 task.data &&
3571 Object.keys(task.data)
3572 .map(function(key) {
3573 return key + ':' + task.data[key];
3574 })
3575 .join(',');
3576 return (
3577 'type: ' +
3578 task.type +
3579 ', source: ' +
3580 task.source +
3581 ', args: {' +
3582 dataInfo +
3583 '}'
3584 );
3585 });
3586 var pendingTasksInfo = '--Pending async tasks are: [' + taskInfo + ']';
3587 // clear tasks
3588 this.tasks = [];
3589 return pendingTasksInfo;
3590 };
3591 ProxyZoneSpec.prototype.onFork = function(
3592 parentZoneDelegate,
3593 currentZone,
3594 targetZone,
3595 zoneSpec
3596 ) {
3597 if (this._delegateSpec && this._delegateSpec.onFork) {
3598 return this._delegateSpec.onFork(
3599 parentZoneDelegate,
3600 currentZone,
3601 targetZone,
3602 zoneSpec
3603 );
3604 } else {
3605 return parentZoneDelegate.fork(targetZone, zoneSpec);
3606 }
3607 };
3608 ProxyZoneSpec.prototype.onIntercept = function(
3609 parentZoneDelegate,
3610 currentZone,
3611 targetZone,
3612 delegate,
3613 source
3614 ) {
3615 if (this._delegateSpec && this._delegateSpec.onIntercept) {
3616 return this._delegateSpec.onIntercept(
3617 parentZoneDelegate,
3618 currentZone,
3619 targetZone,
3620 delegate,
3621 source
3622 );
3623 } else {
3624 return parentZoneDelegate.intercept(targetZone, delegate, source);
3625 }
3626 };
3627 ProxyZoneSpec.prototype.onInvoke = function(
3628 parentZoneDelegate,
3629 currentZone,
3630 targetZone,
3631 delegate,
3632 applyThis,
3633 applyArgs,
3634 source
3635 ) {
3636 this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
3637 if (this._delegateSpec && this._delegateSpec.onInvoke) {
3638 return this._delegateSpec.onInvoke(
3639 parentZoneDelegate,
3640 currentZone,
3641 targetZone,
3642 delegate,
3643 applyThis,
3644 applyArgs,
3645 source
3646 );
3647 } else {
3648 return parentZoneDelegate.invoke(
3649 targetZone,
3650 delegate,
3651 applyThis,
3652 applyArgs,
3653 source
3654 );
3655 }
3656 };
3657 ProxyZoneSpec.prototype.onHandleError = function(
3658 parentZoneDelegate,
3659 currentZone,
3660 targetZone,
3661 error
3662 ) {
3663 if (this._delegateSpec && this._delegateSpec.onHandleError) {
3664 return this._delegateSpec.onHandleError(
3665 parentZoneDelegate,
3666 currentZone,
3667 targetZone,
3668 error
3669 );
3670 } else {
3671 return parentZoneDelegate.handleError(targetZone, error);
3672 }
3673 };
3674 ProxyZoneSpec.prototype.onScheduleTask = function(
3675 parentZoneDelegate,
3676 currentZone,
3677 targetZone,
3678 task
3679 ) {
3680 if (task.type !== 'eventTask') {
3681 this.tasks.push(task);
3682 }
3683 if (this._delegateSpec && this._delegateSpec.onScheduleTask) {
3684 return this._delegateSpec.onScheduleTask(
3685 parentZoneDelegate,
3686 currentZone,
3687 targetZone,
3688 task
3689 );
3690 } else {
3691 return parentZoneDelegate.scheduleTask(targetZone, task);
3692 }
3693 };
3694 ProxyZoneSpec.prototype.onInvokeTask = function(
3695 parentZoneDelegate,
3696 currentZone,
3697 targetZone,
3698 task,
3699 applyThis,
3700 applyArgs
3701 ) {
3702 if (task.type !== 'eventTask') {
3703 this.removeFromTasks(task);
3704 }
3705 this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
3706 if (this._delegateSpec && this._delegateSpec.onInvokeTask) {
3707 return this._delegateSpec.onInvokeTask(
3708 parentZoneDelegate,
3709 currentZone,
3710 targetZone,
3711 task,
3712 applyThis,
3713 applyArgs
3714 );
3715 } else {
3716 return parentZoneDelegate.invokeTask(
3717 targetZone,
3718 task,
3719 applyThis,
3720 applyArgs
3721 );
3722 }
3723 };
3724 ProxyZoneSpec.prototype.onCancelTask = function(
3725 parentZoneDelegate,
3726 currentZone,
3727 targetZone,
3728 task
3729 ) {
3730 if (task.type !== 'eventTask') {
3731 this.removeFromTasks(task);
3732 }
3733 this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
3734 if (this._delegateSpec && this._delegateSpec.onCancelTask) {
3735 return this._delegateSpec.onCancelTask(
3736 parentZoneDelegate,
3737 currentZone,
3738 targetZone,
3739 task
3740 );
3741 } else {
3742 return parentZoneDelegate.cancelTask(targetZone, task);
3743 }
3744 };
3745 ProxyZoneSpec.prototype.onHasTask = function(
3746 delegate,
3747 current,
3748 target,
3749 hasTaskState
3750 ) {
3751 this.lastTaskState = hasTaskState;
3752 if (this._delegateSpec && this._delegateSpec.onHasTask) {
3753 this._delegateSpec.onHasTask(delegate, current, target, hasTaskState);
3754 } else {
3755 delegate.hasTask(target, hasTaskState);
3756 }
3757 };
3758
3759 Zone['ProxyZoneSpec'] = ProxyZoneSpec;
3760
3761 (function(global) {
3762 var OriginalDate = global.Date;
3763 var FakeDate = /** @class */ (function() {
3764 function FakeDate() {
3765 if (arguments.length === 0) {
3766 var d = new OriginalDate();
3767 d.setTime(FakeDate.now());
3768 return d;
3769 } else {
3770 var args = Array.prototype.slice.call(arguments);
3771 return new (OriginalDate.bind.apply(
3772 OriginalDate,
3773 __spread([void 0], args)
3774 ))();
3775 }
3776 }
3777 FakeDate.now = function() {
3778 var fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
3779 if (fakeAsyncTestZoneSpec) {
3780 return (
3781 fakeAsyncTestZoneSpec.getCurrentRealTime() +
3782 fakeAsyncTestZoneSpec.getCurrentTime()
3783 );
3784 }
3785 return OriginalDate.now.apply(this, arguments);
3786 };
3787 return FakeDate;
3788 })();
3789 FakeDate.UTC = OriginalDate.UTC;
3790 FakeDate.parse = OriginalDate.parse;
3791 // keep a reference for zone patched timer function
3792 var timers = {
3793 setTimeout: global.setTimeout,
3794 setInterval: global.setInterval,
3795 clearTimeout: global.clearTimeout,
3796 clearInterval: global.clearInterval
3797 };
3798 var Scheduler = /** @class */ (function() {
3799 function Scheduler() {
3800 // Scheduler queue with the tuple of end time and callback function - sorted by end time.
3801 this._schedulerQueue = [];
3802 // Current simulated time in millis.
3803 this._currentTime = 0;
3804 // Current real time in millis.
3805 this._currentRealTime = OriginalDate.now();
3806 }
3807 Scheduler.prototype.getCurrentTime = function() {
3808 return this._currentTime;
3809 };
3810 Scheduler.prototype.getCurrentRealTime = function() {
3811 return this._currentRealTime;
3812 };
3813 Scheduler.prototype.setCurrentRealTime = function(realTime) {
3814 this._currentRealTime = realTime;
3815 };
3816 Scheduler.prototype.scheduleFunction = function(
3817 cb,
3818 delay,
3819 args,
3820 isPeriodic,
3821 isRequestAnimationFrame,
3822 id
3823 ) {
3824 if (args === void 0) {
3825 args = [];
3826 }
3827 if (isPeriodic === void 0) {
3828 isPeriodic = false;
3829 }
3830 if (isRequestAnimationFrame === void 0) {
3831 isRequestAnimationFrame = false;
3832 }
3833 if (id === void 0) {
3834 id = -1;
3835 }
3836 var currentId = id < 0 ? Scheduler.nextId++ : id;
3837 var endTime = this._currentTime + delay;
3838 // Insert so that scheduler queue remains sorted by end time.
3839 var newEntry = {
3840 endTime: endTime,
3841 id: currentId,
3842 func: cb,
3843 args: args,
3844 delay: delay,
3845 isPeriodic: isPeriodic,
3846 isRequestAnimationFrame: isRequestAnimationFrame
3847 };
3848 var i = 0;
3849 for (; i < this._schedulerQueue.length; i++) {
3850 var currentEntry = this._schedulerQueue[i];
3851 if (newEntry.endTime < currentEntry.endTime) {
3852 break;
3853 }
3854 }
3855 this._schedulerQueue.splice(i, 0, newEntry);
3856 return currentId;
3857 };
3858 Scheduler.prototype.removeScheduledFunctionWithId = function(id) {
3859 for (var i = 0; i < this._schedulerQueue.length; i++) {
3860 if (this._schedulerQueue[i].id == id) {
3861 this._schedulerQueue.splice(i, 1);
3862 break;
3863 }
3864 }
3865 };
3866 Scheduler.prototype.tick = function(millis, doTick) {
3867 if (millis === void 0) {
3868 millis = 0;
3869 }
3870 var finalTime = this._currentTime + millis;
3871 var lastCurrentTime = 0;
3872 if (this._schedulerQueue.length === 0 && doTick) {
3873 doTick(millis);
3874 return;
3875 }
3876 while (this._schedulerQueue.length > 0) {
3877 var current = this._schedulerQueue[0];
3878 if (finalTime < current.endTime) {
3879 // Done processing the queue since it's sorted by endTime.
3880 break;
3881 } else {
3882 // Time to run scheduled function. Remove it from the head of queue.
3883 var current_1 = this._schedulerQueue.shift();
3884 lastCurrentTime = this._currentTime;
3885 this._currentTime = current_1.endTime;
3886 if (doTick) {
3887 doTick(this._currentTime - lastCurrentTime);
3888 }
3889 var retval = current_1.func.apply(
3890 global,
3891 current_1.isRequestAnimationFrame
3892 ? [this._currentTime]
3893 : current_1.args
3894 );
3895 if (!retval) {
3896 // Uncaught exception in the current scheduled function. Stop processing the queue.
3897 break;
3898 }
3899 }
3900 }
3901 lastCurrentTime = this._currentTime;
3902 this._currentTime = finalTime;
3903 if (doTick) {
3904 doTick(this._currentTime - lastCurrentTime);
3905 }
3906 };
3907 Scheduler.prototype.flush = function(limit, flushPeriodic, doTick) {
3908 if (limit === void 0) {
3909 limit = 20;
3910 }
3911 if (flushPeriodic === void 0) {
3912 flushPeriodic = false;
3913 }
3914 if (flushPeriodic) {
3915 return this.flushPeriodic(doTick);
3916 } else {
3917 return this.flushNonPeriodic(limit, doTick);
3918 }
3919 };
3920 Scheduler.prototype.flushPeriodic = function(doTick) {
3921 if (this._schedulerQueue.length === 0) {
3922 return 0;
3923 }
3924 // Find the last task currently queued in the scheduler queue and tick
3925 // till that time.
3926 var startTime = this._currentTime;
3927 var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
3928 this.tick(lastTask.endTime - startTime, doTick);
3929 return this._currentTime - startTime;
3930 };
3931 Scheduler.prototype.flushNonPeriodic = function(limit, doTick) {
3932 var startTime = this._currentTime;
3933 var lastCurrentTime = 0;
3934 var count = 0;
3935 while (this._schedulerQueue.length > 0) {
3936 count++;
3937 if (count > limit) {
3938 throw new Error(
3939 'flush failed after reaching the limit of ' +
3940 limit +
3941 ' tasks. Does your code use a polling timeout?'
3942 );
3943 }
3944 // flush only non-periodic timers.
3945 // If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
3946 if (
3947 this._schedulerQueue.filter(function(task) {
3948 return !task.isPeriodic && !task.isRequestAnimationFrame;
3949 }).length === 0
3950 ) {
3951 break;
3952 }
3953 var current = this._schedulerQueue.shift();
3954 lastCurrentTime = this._currentTime;
3955 this._currentTime = current.endTime;
3956 if (doTick) {
3957 // Update any secondary schedulers like Jasmine mock Date.
3958 doTick(this._currentTime - lastCurrentTime);
3959 }
3960 var retval = current.func.apply(global, current.args);
3961 if (!retval) {
3962 // Uncaught exception in the current scheduled function. Stop processing the queue.
3963 break;
3964 }
3965 }
3966 return this._currentTime - startTime;
3967 };
3968 return Scheduler;
3969 })();
3970 // Next scheduler id.
3971 Scheduler.nextId = 1;
3972 var FakeAsyncTestZoneSpec = /** @class */ (function() {
3973 function FakeAsyncTestZoneSpec(
3974 namePrefix,
3975 trackPendingRequestAnimationFrame,
3976 macroTaskOptions
3977 ) {
3978 if (trackPendingRequestAnimationFrame === void 0) {
3979 trackPendingRequestAnimationFrame = false;
3980 }
3981 this.trackPendingRequestAnimationFrame = trackPendingRequestAnimationFrame;
3982 this.macroTaskOptions = macroTaskOptions;
3983 this._scheduler = new Scheduler();
3984 this._microtasks = [];
3985 this._lastError = null;
3986 this._uncaughtPromiseErrors =
3987 Promise[Zone.__symbol__('uncaughtPromiseErrors')];
3988 this.pendingPeriodicTimers = [];
3989 this.pendingTimers = [];
3990 this.patchDateLocked = false;
3991 this.properties = { FakeAsyncTestZoneSpec: this };
3992 this.name = 'fakeAsyncTestZone for ' + namePrefix;
3993 // in case user can't access the construction of FakeAsyncTestSpec
3994 // user can also define macroTaskOptions by define a global variable.
3995 if (!this.macroTaskOptions) {
3996 this.macroTaskOptions =
3997 global[Zone.__symbol__('FakeAsyncTestMacroTask')];
3998 }
3999 }
4000 FakeAsyncTestZoneSpec.assertInZone = function() {
4001 if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
4002 throw new Error(
4003 'The code should be running in the fakeAsync zone to call this function'
4004 );
4005 }
4006 };
4007 FakeAsyncTestZoneSpec.prototype._fnAndFlush = function(fn, completers) {
4008 var _this = this;
4009 return function() {
4010 var args = [];
4011 for (var _i = 0; _i < arguments.length; _i++) {
4012 args[_i] = arguments[_i];
4013 }
4014 fn.apply(global, args);
4015 if (_this._lastError === null) {
4016 // Success
4017 if (completers.onSuccess != null) {
4018 completers.onSuccess.apply(global);
4019 }
4020 // Flush microtasks only on success.
4021 _this.flushMicrotasks();
4022 } else {
4023 // Failure
4024 if (completers.onError != null) {
4025 completers.onError.apply(global);
4026 }
4027 }
4028 // Return true if there were no errors, false otherwise.
4029 return _this._lastError === null;
4030 };
4031 };
4032 FakeAsyncTestZoneSpec._removeTimer = function(timers, id) {
4033 var index = timers.indexOf(id);
4034 if (index > -1) {
4035 timers.splice(index, 1);
4036 }
4037 };
4038 FakeAsyncTestZoneSpec.prototype._dequeueTimer = function(id) {
4039 var _this = this;
4040 return function() {
4041 FakeAsyncTestZoneSpec._removeTimer(_this.pendingTimers, id);
4042 };
4043 };
4044 FakeAsyncTestZoneSpec.prototype._requeuePeriodicTimer = function(
4045 fn,
4046 interval,
4047 args,
4048 id
4049 ) {
4050 var _this = this;
4051 return function() {
4052 // Requeue the timer callback if it's not been canceled.
4053 if (_this.pendingPeriodicTimers.indexOf(id) !== -1) {
4054 _this._scheduler.scheduleFunction(
4055 fn,
4056 interval,
4057 args,
4058 true,
4059 false,
4060 id
4061 );
4062 }
4063 };
4064 };
4065 FakeAsyncTestZoneSpec.prototype._dequeuePeriodicTimer = function(id) {
4066 var _this = this;
4067 return function() {
4068 FakeAsyncTestZoneSpec._removeTimer(_this.pendingPeriodicTimers, id);
4069 };
4070 };
4071 FakeAsyncTestZoneSpec.prototype._setTimeout = function(
4072 fn,
4073 delay,
4074 args,
4075 isTimer
4076 ) {
4077 if (isTimer === void 0) {
4078 isTimer = true;
4079 }
4080 var removeTimerFn = this._dequeueTimer(Scheduler.nextId);
4081 // Queue the callback and dequeue the timer on success and error.
4082 var cb = this._fnAndFlush(fn, {
4083 onSuccess: removeTimerFn,
4084 onError: removeTimerFn
4085 });
4086 var id = this._scheduler.scheduleFunction(
4087 cb,
4088 delay,
4089 args,
4090 false,
4091 !isTimer
4092 );
4093 if (isTimer) {
4094 this.pendingTimers.push(id);
4095 }
4096 return id;
4097 };
4098 FakeAsyncTestZoneSpec.prototype._clearTimeout = function(id) {
4099 FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
4100 this._scheduler.removeScheduledFunctionWithId(id);
4101 };
4102 FakeAsyncTestZoneSpec.prototype._setInterval = function(
4103 fn,
4104 interval,
4105 args
4106 ) {
4107 var id = Scheduler.nextId;
4108 var completers = {
4109 onSuccess: null,
4110 onError: this._dequeuePeriodicTimer(id)
4111 };
4112 var cb = this._fnAndFlush(fn, completers);
4113 // Use the callback created above to requeue on success.
4114 completers.onSuccess = this._requeuePeriodicTimer(
4115 cb,
4116 interval,
4117 args,
4118 id
4119 );
4120 // Queue the callback and dequeue the periodic timer only on error.
4121 this._scheduler.scheduleFunction(cb, interval, args, true);
4122 this.pendingPeriodicTimers.push(id);
4123 return id;
4124 };
4125 FakeAsyncTestZoneSpec.prototype._clearInterval = function(id) {
4126 FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
4127 this._scheduler.removeScheduledFunctionWithId(id);
4128 };
4129 FakeAsyncTestZoneSpec.prototype._resetLastErrorAndThrow = function() {
4130 var error = this._lastError || this._uncaughtPromiseErrors[0];
4131 this._uncaughtPromiseErrors.length = 0;
4132 this._lastError = null;
4133 throw error;
4134 };
4135 FakeAsyncTestZoneSpec.prototype.getCurrentTime = function() {
4136 return this._scheduler.getCurrentTime();
4137 };
4138 FakeAsyncTestZoneSpec.prototype.getCurrentRealTime = function() {
4139 return this._scheduler.getCurrentRealTime();
4140 };
4141 FakeAsyncTestZoneSpec.prototype.setCurrentRealTime = function(realTime) {
4142 this._scheduler.setCurrentRealTime(realTime);
4143 };
4144 FakeAsyncTestZoneSpec.patchDate = function() {
4145 if (!!global[Zone.__symbol__('disableDatePatching')]) {
4146 // we don't want to patch global Date
4147 // because in some case, global Date
4148 // is already being patched, we need to provide
4149 // an option to let user still use their
4150 // own version of Date.
4151 return;
4152 }
4153 if (global['Date'] === FakeDate) {
4154 // already patched
4155 return;
4156 }
4157 global['Date'] = FakeDate;
4158 FakeDate.prototype = OriginalDate.prototype;
4159 // try check and reset timers
4160 // because jasmine.clock().install() may
4161 // have replaced the global timer
4162 FakeAsyncTestZoneSpec.checkTimerPatch();
4163 };
4164 FakeAsyncTestZoneSpec.resetDate = function() {
4165 if (global['Date'] === FakeDate) {
4166 global['Date'] = OriginalDate;
4167 }
4168 };
4169 FakeAsyncTestZoneSpec.checkTimerPatch = function() {
4170 if (global.setTimeout !== timers.setTimeout) {
4171 global.setTimeout = timers.setTimeout;
4172 global.clearTimeout = timers.clearTimeout;
4173 }
4174 if (global.setInterval !== timers.setInterval) {
4175 global.setInterval = timers.setInterval;
4176 global.clearInterval = timers.clearInterval;
4177 }
4178 };
4179 FakeAsyncTestZoneSpec.prototype.lockDatePatch = function() {
4180 this.patchDateLocked = true;
4181 FakeAsyncTestZoneSpec.patchDate();
4182 };
4183 FakeAsyncTestZoneSpec.prototype.unlockDatePatch = function() {
4184 this.patchDateLocked = false;
4185 FakeAsyncTestZoneSpec.resetDate();
4186 };
4187 FakeAsyncTestZoneSpec.prototype.tick = function(millis, doTick) {
4188 if (millis === void 0) {
4189 millis = 0;
4190 }
4191 FakeAsyncTestZoneSpec.assertInZone();
4192 this.flushMicrotasks();
4193 this._scheduler.tick(millis, doTick);
4194 if (this._lastError !== null) {
4195 this._resetLastErrorAndThrow();
4196 }
4197 };
4198 FakeAsyncTestZoneSpec.prototype.flushMicrotasks = function() {
4199 var _this = this;
4200 FakeAsyncTestZoneSpec.assertInZone();
4201 var flushErrors = function() {
4202 if (
4203 _this._lastError !== null ||
4204 _this._uncaughtPromiseErrors.length
4205 ) {
4206 // If there is an error stop processing the microtask queue and rethrow the error.
4207 _this._resetLastErrorAndThrow();
4208 }
4209 };
4210 while (this._microtasks.length > 0) {
4211 var microtask = this._microtasks.shift();
4212 microtask.func.apply(microtask.target, microtask.args);
4213 }
4214 flushErrors();
4215 };
4216 FakeAsyncTestZoneSpec.prototype.flush = function(
4217 limit,
4218 flushPeriodic,
4219 doTick
4220 ) {
4221 FakeAsyncTestZoneSpec.assertInZone();
4222 this.flushMicrotasks();
4223 var elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
4224 if (this._lastError !== null) {
4225 this._resetLastErrorAndThrow();
4226 }
4227 return elapsed;
4228 };
4229 FakeAsyncTestZoneSpec.prototype.onScheduleTask = function(
4230 delegate,
4231 current,
4232 target,
4233 task
4234 ) {
4235 switch (task.type) {
4236 case 'microTask':
4237 var args = task.data && task.data.args;
4238 // should pass additional arguments to callback if have any
4239 // currently we know process.nextTick will have such additional
4240 // arguments
4241 var additionalArgs = void 0;
4242 if (args) {
4243 var callbackIndex = task.data.cbIdx;
4244 if (
4245 typeof args.length === 'number' &&
4246 args.length > callbackIndex + 1
4247 ) {
4248 additionalArgs = Array.prototype.slice.call(
4249 args,
4250 callbackIndex + 1
4251 );
4252 }
4253 }
4254 this._microtasks.push({
4255 func: task.invoke,
4256 args: additionalArgs,
4257 target: task.data && task.data.target
4258 });
4259 break;
4260 case 'macroTask':
4261 switch (task.source) {
4262 case 'setTimeout':
4263 task.data['handleId'] = this._setTimeout(
4264 task.invoke,
4265 task.data['delay'],
4266 Array.prototype.slice.call(task.data['args'], 2)
4267 );
4268 break;
4269 case 'setImmediate':
4270 task.data['handleId'] = this._setTimeout(
4271 task.invoke,
4272 0,
4273 Array.prototype.slice.call(task.data['args'], 1)
4274 );
4275 break;
4276 case 'setInterval':
4277 task.data['handleId'] = this._setInterval(
4278 task.invoke,
4279 task.data['delay'],
4280 Array.prototype.slice.call(task.data['args'], 2)
4281 );
4282 break;
4283 case 'XMLHttpRequest.send':
4284 throw new Error(
4285 'Cannot make XHRs from within a fake async test. Request URL: ' +
4286 task.data['url']
4287 );
4288 case 'requestAnimationFrame':
4289 case 'webkitRequestAnimationFrame':
4290 case 'mozRequestAnimationFrame':
4291 // Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
4292 // (60 frames per second)
4293 task.data['handleId'] = this._setTimeout(
4294 task.invoke,
4295 16,
4296 task.data['args'],
4297 this.trackPendingRequestAnimationFrame
4298 );
4299 break;
4300 default:
4301 // user can define which macroTask they want to support by passing
4302 // macroTaskOptions
4303 var macroTaskOption = this.findMacroTaskOption(task);
4304 if (macroTaskOption) {
4305 var args_1 = task.data && task.data['args'];
4306 var delay = args_1 && args_1.length > 1 ? args_1[1] : 0;
4307 var callbackArgs = macroTaskOption.callbackArgs
4308 ? macroTaskOption.callbackArgs
4309 : args_1;
4310 if (!!macroTaskOption.isPeriodic) {
4311 // periodic macroTask, use setInterval to simulate
4312 task.data['handleId'] = this._setInterval(
4313 task.invoke,
4314 delay,
4315 callbackArgs
4316 );
4317 task.data.isPeriodic = true;
4318 } else {
4319 // not periodic, use setTimeout to simulate
4320 task.data['handleId'] = this._setTimeout(
4321 task.invoke,
4322 delay,
4323 callbackArgs
4324 );
4325 }
4326 break;
4327 }
4328 throw new Error(
4329 'Unknown macroTask scheduled in fake async test: ' +
4330 task.source
4331 );
4332 }
4333 break;
4334 case 'eventTask':
4335 task = delegate.scheduleTask(target, task);
4336 break;
4337 }
4338 return task;
4339 };
4340 FakeAsyncTestZoneSpec.prototype.onCancelTask = function(
4341 delegate,
4342 current,
4343 target,
4344 task
4345 ) {
4346 switch (task.source) {
4347 case 'setTimeout':
4348 case 'requestAnimationFrame':
4349 case 'webkitRequestAnimationFrame':
4350 case 'mozRequestAnimationFrame':
4351 return this._clearTimeout(task.data['handleId']);
4352 case 'setInterval':
4353 return this._clearInterval(task.data['handleId']);
4354 default:
4355 // user can define which macroTask they want to support by passing
4356 // macroTaskOptions
4357 var macroTaskOption = this.findMacroTaskOption(task);
4358 if (macroTaskOption) {
4359 var handleId = task.data['handleId'];
4360 return macroTaskOption.isPeriodic
4361 ? this._clearInterval(handleId)
4362 : this._clearTimeout(handleId);
4363 }
4364 return delegate.cancelTask(target, task);
4365 }
4366 };
4367 FakeAsyncTestZoneSpec.prototype.onInvoke = function(
4368 delegate,
4369 current,
4370 target,
4371 callback,
4372 applyThis,
4373 applyArgs,
4374 source
4375 ) {
4376 try {
4377 FakeAsyncTestZoneSpec.patchDate();
4378 return delegate.invoke(
4379 target,
4380 callback,
4381 applyThis,
4382 applyArgs,
4383 source
4384 );
4385 } finally {
4386 if (!this.patchDateLocked) {
4387 FakeAsyncTestZoneSpec.resetDate();
4388 }
4389 }
4390 };
4391 FakeAsyncTestZoneSpec.prototype.findMacroTaskOption = function(task) {
4392 if (!this.macroTaskOptions) {
4393 return null;
4394 }
4395 for (var i = 0; i < this.macroTaskOptions.length; i++) {
4396 var macroTaskOption = this.macroTaskOptions[i];
4397 if (macroTaskOption.source === task.source) {
4398 return macroTaskOption;
4399 }
4400 }
4401 return null;
4402 };
4403 FakeAsyncTestZoneSpec.prototype.onHandleError = function(
4404 parentZoneDelegate,
4405 currentZone,
4406 targetZone,
4407 error
4408 ) {
4409 this._lastError = error;
4410 return false; // Don't propagate error to parent zone.
4411 };
4412 return FakeAsyncTestZoneSpec;
4413 })();
4414 // Export the class so that new instances can be created with proper
4415 // constructor params.
4416 Zone['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
4417 })(window);
4418
4419 Zone.__load_patch('fakeasync', function(global, Zone, api) {
4420 var FakeAsyncTestZoneSpec = Zone && Zone['FakeAsyncTestZoneSpec'];
4421 var ProxyZoneSpec = Zone && Zone['ProxyZoneSpec'];
4422 var _fakeAsyncTestZoneSpec = null;
4423 /**
4424 * Clears out the shared fake async zone for a test.
4425 * To be called in a global `beforeEach`.
4426 *
4427 * @experimental
4428 */
4429 function resetFakeAsyncZone() {
4430 if (_fakeAsyncTestZoneSpec) {
4431 _fakeAsyncTestZoneSpec.unlockDatePatch();
4432 }
4433 _fakeAsyncTestZoneSpec = null;
4434 // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
4435 ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
4436 }
4437 /**
4438 * Wraps a function to be executed in the fakeAsync zone:
4439 * - microtasks are manually executed by calling `flushMicrotasks()`,
4440 * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
4441 *
4442 * If there are any pending timers at the end of the function, an exception will be thrown.
4443 *
4444 * Can be used to wrap inject() calls.
4445 *
4446 * ## Example
4447 *
4448 * {@example core/testing/ts/fake_async.ts region='basic'}
4449 *
4450 * @param fn
4451 * @returns The function wrapped to be executed in the fakeAsync zone
4452 *
4453 * @experimental
4454 */
4455 function fakeAsync(fn) {
4456 // Not using an arrow function to preserve context passed from call site
4457 return function() {
4458 var args = [];
4459 for (var _i = 0; _i < arguments.length; _i++) {
4460 args[_i] = arguments[_i];
4461 }
4462 var proxyZoneSpec = ProxyZoneSpec.assertPresent();
4463 if (Zone.current.get('FakeAsyncTestZoneSpec')) {
4464 throw new Error('fakeAsync() calls can not be nested');
4465 }
4466 try {
4467 // in case jasmine.clock init a fakeAsyncTestZoneSpec
4468 if (!_fakeAsyncTestZoneSpec) {
4469 if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
4470 throw new Error('fakeAsync() calls can not be nested');
4471 }
4472 _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
4473 }
4474 var res = void 0;
4475 var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
4476 proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
4477 _fakeAsyncTestZoneSpec.lockDatePatch();
4478 try {
4479 res = fn.apply(this, args);
4480 flushMicrotasks();
4481 } finally {
4482 proxyZoneSpec.setDelegate(lastProxyZoneSpec);
4483 }
4484 if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
4485 throw new Error(
4486 _fakeAsyncTestZoneSpec.pendingPeriodicTimers.length +
4487 ' ' +
4488 'periodic timer(s) still in the queue.'
4489 );
4490 }
4491 if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
4492 throw new Error(
4493 _fakeAsyncTestZoneSpec.pendingTimers.length +
4494 ' timer(s) still in the queue.'
4495 );
4496 }
4497 return res;
4498 } finally {
4499 resetFakeAsyncZone();
4500 }
4501 };
4502 }
4503 function _getFakeAsyncZoneSpec() {
4504 if (_fakeAsyncTestZoneSpec == null) {
4505 _fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
4506 if (_fakeAsyncTestZoneSpec == null) {
4507 throw new Error(
4508 'The code should be running in the fakeAsync zone to call this function'
4509 );
4510 }
4511 }
4512 return _fakeAsyncTestZoneSpec;
4513 }
4514 /**
4515 * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
4516 *
4517 * The microtasks queue is drained at the very start of this function and after any timer callback
4518 * has been executed.
4519 *
4520 * ## Example
4521 *
4522 * {@example core/testing/ts/fake_async.ts region='basic'}
4523 *
4524 * @experimental
4525 */
4526 function tick(millis) {
4527 if (millis === void 0) {
4528 millis = 0;
4529 }
4530 _getFakeAsyncZoneSpec().tick(millis);
4531 }
4532 /**
4533 * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
4534 * draining the macrotask queue until it is empty. The returned value is the milliseconds
4535 * of time that would have been elapsed.
4536 *
4537 * @param maxTurns
4538 * @returns The simulated time elapsed, in millis.
4539 *
4540 * @experimental
4541 */
4542 function flush(maxTurns) {
4543 return _getFakeAsyncZoneSpec().flush(maxTurns);
4544 }
4545 /**
4546 * Discard all remaining periodic tasks.
4547 *
4548 * @experimental
4549 */
4550 function discardPeriodicTasks() {
4551 var zoneSpec = _getFakeAsyncZoneSpec();
4552 var pendingTimers = zoneSpec.pendingPeriodicTimers;
4553 zoneSpec.pendingPeriodicTimers.length = 0;
4554 }
4555 /**
4556 * Flush any pending microtasks.
4557 *
4558 * @experimental
4559 */
4560 function flushMicrotasks() {
4561 _getFakeAsyncZoneSpec().flushMicrotasks();
4562 }
4563 Zone[api.symbol('fakeAsyncTest')] = {
4564 resetFakeAsyncZone: resetFakeAsyncZone,
4565 flushMicrotasks: flushMicrotasks,
4566 discardPeriodicTasks: discardPeriodicTasks,
4567 tick: tick,
4568 flush: flush,
4569 fakeAsync: fakeAsync
4570 };
4571 });
4572
4573function equal(a, b) {
4574 const isArray = Array.isArray;
4575 const keyList = Object.keys;
4576 const hasProp = Object.prototype.hasOwnProperty;
4577
4578 if (a === b) return true;
4579
4580 if (a && b && typeof a == 'object' && typeof b == 'object') {
4581 var arrA = isArray(a)
4582 , arrB = isArray(b)
4583 , i
4584 , length
4585 , key;
4586
4587 if (arrA && arrB) {
4588 length = a.length;
4589 if (length != b.length) return false;
4590 for (i = length; i-- !== 0;)
4591 if (!equal(a[i], b[i])) return false;
4592 return true;
4593 }
4594
4595 if (arrA != arrB) return false;
4596
4597 var dateA = a instanceof Date
4598 , dateB = b instanceof Date;
4599 if (dateA != dateB) return false;
4600 if (dateA && dateB) return a.getTime() == b.getTime();
4601
4602 var regexpA = a instanceof RegExp
4603 , regexpB = b instanceof RegExp;
4604 if (regexpA != regexpB) return false;
4605 if (regexpA && regexpB) return a.toString() == b.toString();
4606
4607 var keys = keyList(a);
4608 length = keys.length;
4609
4610 if (length !== keyList(b).length)
4611 return false;
4612
4613 for (i = length; i-- !== 0;)
4614 if (!hasProp.call(b, keys[i])) return false;
4615
4616 for (i = length; i-- !== 0;) {
4617 key = keys[i];
4618 if (a[key] !== b[key]) return false;
4619 }
4620
4621 return true;
4622 }
4623
4624 return a!==a && b!==b;
4625}
4626
4627function Should(message, func) {
4628 try {
4629 func();
4630 } catch (e) {
4631 let fullMessage = ''.concat('Fails: ',message,' \n',e.message);
4632 throw new Error(fullMessage);
4633 }
4634
4635 globalDispatch('[TEST_UTIL_EVENTS__SUCCESS]', ''.concat('Pass: ',message));
4636}
4637
4638function assert(val) {
4639 return {
4640 toBe: function(expected) {
4641 if (!equal(val, expected)) {
4642 let act = val;
4643 let exp = expected;
4644 try {
4645 act = (Object.prototype.toString.call(val) === '[object Object]') ? JSON.stringify(val) : val;
4646 exp = (Object.prototype.toString.call(expected) === '[object Object]') ? JSON.stringify(expected) : expected;
4647 } catch (e) {
4648 console.warn('Stringify error', e);
4649 }
4650
4651 throw new Error(''.concat('Values must be equal. Expected to equal: ',exp,', actual: ',act));
4652 }
4653 },
4654 notToBe: function(expected) {
4655 if (equal(val, expected)) {
4656 let act = val;
4657 let exp = expected;
4658 try {
4659 act = (Object.prototype.toString.call(val) === '[object Object]') ? JSON.stringify(val) : val;
4660 exp = (Object.prototype.toString.call(expected) === '[object Object]') ? JSON.stringify(expected) : expected;
4661 } catch (e) {
4662 console.warn('Stringify error', e);
4663 }
4664
4665 throw new Error(''.concat('Values must not be equal. Expected not to equal: ',exp,', actual: ',act));
4666 }
4667 },
4668 };
4669}