zone.umd.js 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813
  1. 'use strict';
  2. var __assign = (this && this.__assign) || function () {
  3. __assign = Object.assign || function(t) {
  4. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5. s = arguments[i];
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  7. t[p] = s[p];
  8. }
  9. return t;
  10. };
  11. return __assign.apply(this, arguments);
  12. };
  13. /**
  14. * @license Angular v<unknown>
  15. * (c) 2010-2022 Google LLC. https://angular.io/
  16. * License: MIT
  17. */
  18. (function (factory) {
  19. typeof define === 'function' && define.amd ? define(factory) :
  20. factory();
  21. })((function () {
  22. 'use strict';
  23. ((function (global) {
  24. var _a;
  25. var performance = global['performance'];
  26. function mark(name) {
  27. performance && performance['mark'] && performance['mark'](name);
  28. }
  29. function performanceMeasure(name, label) {
  30. performance && performance['measure'] && performance['measure'](name, label);
  31. }
  32. mark('Zone');
  33. // Initialize before it's accessed below.
  34. // __Zone_symbol_prefix global can be used to override the default zone
  35. // symbol prefix with a custom one if needed.
  36. var symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
  37. function __symbol__(name) {
  38. return symbolPrefix + name;
  39. }
  40. var checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  41. if (global['Zone']) {
  42. // if global['Zone'] already exists (maybe zone.js was already loaded or
  43. // some other lib also registered a global object named Zone), we may need
  44. // to throw an error, but sometimes user may not want this error.
  45. // For example,
  46. // we have two web pages, page1 includes zone.js, page2 doesn't.
  47. // and the 1st time user load page1 and page2, everything work fine,
  48. // but when user load page2 again, error occurs because global['Zone'] already exists.
  49. // so we add a flag to let user choose whether to throw this error or not.
  50. // By default, if existing Zone is from zone.js, we will not throw the error.
  51. if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
  52. throw new Error('Zone already loaded.');
  53. }
  54. else {
  55. return global['Zone'];
  56. }
  57. }
  58. var Zone = /** @class */ (function () {
  59. function Zone(parent, zoneSpec) {
  60. this._parent = parent;
  61. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  62. this._properties = zoneSpec && zoneSpec.properties || {};
  63. this._zoneDelegate =
  64. new _ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  65. }
  66. Zone.assertZonePatched = function () {
  67. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  68. throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  69. 'has been overwritten.\n' +
  70. 'Most likely cause is that a Promise polyfill has been loaded ' +
  71. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  72. 'If you must load one, do so before loading zone.js.)');
  73. }
  74. };
  75. Object.defineProperty(Zone, "root", {
  76. get: function () {
  77. var zone = _a.current;
  78. while (zone.parent) {
  79. zone = zone.parent;
  80. }
  81. return zone;
  82. },
  83. enumerable: false,
  84. configurable: true
  85. });
  86. Object.defineProperty(Zone, "current", {
  87. get: function () {
  88. return _currentZoneFrame.zone;
  89. },
  90. enumerable: false,
  91. configurable: true
  92. });
  93. Object.defineProperty(Zone, "currentTask", {
  94. get: function () {
  95. return _currentTask;
  96. },
  97. enumerable: false,
  98. configurable: true
  99. });
  100. // tslint:disable-next-line:require-internal-with-underscore
  101. Zone.__load_patch = function (name, fn, ignoreDuplicate) {
  102. if (ignoreDuplicate === void 0) { ignoreDuplicate = false; }
  103. if (patches.hasOwnProperty(name)) {
  104. // `checkDuplicate` option is defined from global variable
  105. // so it works for all modules.
  106. // `ignoreDuplicate` can work for the specified module
  107. if (!ignoreDuplicate && checkDuplicate) {
  108. throw Error('Already loaded patch: ' + name);
  109. }
  110. }
  111. else if (!global['__Zone_disable_' + name]) {
  112. var perfName = 'Zone:' + name;
  113. mark(perfName);
  114. patches[name] = fn(global, _a, _api);
  115. performanceMeasure(perfName, perfName);
  116. }
  117. };
  118. Object.defineProperty(Zone.prototype, "parent", {
  119. get: function () {
  120. return this._parent;
  121. },
  122. enumerable: false,
  123. configurable: true
  124. });
  125. Object.defineProperty(Zone.prototype, "name", {
  126. get: function () {
  127. return this._name;
  128. },
  129. enumerable: false,
  130. configurable: true
  131. });
  132. Zone.prototype.get = function (key) {
  133. var zone = this.getZoneWith(key);
  134. if (zone)
  135. return zone._properties[key];
  136. };
  137. Zone.prototype.getZoneWith = function (key) {
  138. var current = this;
  139. while (current) {
  140. if (current._properties.hasOwnProperty(key)) {
  141. return current;
  142. }
  143. current = current._parent;
  144. }
  145. return null;
  146. };
  147. Zone.prototype.fork = function (zoneSpec) {
  148. if (!zoneSpec)
  149. throw new Error('ZoneSpec required!');
  150. return this._zoneDelegate.fork(this, zoneSpec);
  151. };
  152. Zone.prototype.wrap = function (callback, source) {
  153. if (typeof callback !== 'function') {
  154. throw new Error('Expecting function got: ' + callback);
  155. }
  156. var _callback = this._zoneDelegate.intercept(this, callback, source);
  157. var zone = this;
  158. return function () {
  159. return zone.runGuarded(_callback, this, arguments, source);
  160. };
  161. };
  162. Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
  163. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  164. try {
  165. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  166. }
  167. finally {
  168. _currentZoneFrame = _currentZoneFrame.parent;
  169. }
  170. };
  171. Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
  172. if (applyThis === void 0) { applyThis = null; }
  173. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  174. try {
  175. try {
  176. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  177. }
  178. catch (error) {
  179. if (this._zoneDelegate.handleError(this, error)) {
  180. throw error;
  181. }
  182. }
  183. }
  184. finally {
  185. _currentZoneFrame = _currentZoneFrame.parent;
  186. }
  187. };
  188. Zone.prototype.runTask = function (task, applyThis, applyArgs) {
  189. if (task.zone != this) {
  190. throw new Error('A task can only be run in the zone of creation! (Creation: ' +
  191. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  192. }
  193. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  194. // will run in notScheduled(canceled) state, we should not try to
  195. // run such kind of task but just return
  196. if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
  197. return;
  198. }
  199. var reEntryGuard = task.state != running;
  200. reEntryGuard && task._transitionTo(running, scheduled);
  201. task.runCount++;
  202. var previousTask = _currentTask;
  203. _currentTask = task;
  204. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  205. try {
  206. if (task.type == macroTask && task.data && !task.data.isPeriodic) {
  207. task.cancelFn = undefined;
  208. }
  209. try {
  210. return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
  211. }
  212. catch (error) {
  213. if (this._zoneDelegate.handleError(this, error)) {
  214. throw error;
  215. }
  216. }
  217. }
  218. finally {
  219. // if the task's state is notScheduled or unknown, then it has already been cancelled
  220. // we should not reset the state to scheduled
  221. if (task.state !== notScheduled && task.state !== unknown) {
  222. if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
  223. reEntryGuard && task._transitionTo(scheduled, running);
  224. }
  225. else {
  226. task.runCount = 0;
  227. this._updateTaskCount(task, -1);
  228. reEntryGuard &&
  229. task._transitionTo(notScheduled, running, notScheduled);
  230. }
  231. }
  232. _currentZoneFrame = _currentZoneFrame.parent;
  233. _currentTask = previousTask;
  234. }
  235. };
  236. Zone.prototype.scheduleTask = function (task) {
  237. if (task.zone && task.zone !== this) {
  238. // check if the task was rescheduled, the newZone
  239. // should not be the children of the original zone
  240. var newZone = this;
  241. while (newZone) {
  242. if (newZone === task.zone) {
  243. throw Error("can not reschedule task to ".concat(this.name, " which is descendants of the original zone ").concat(task.zone.name));
  244. }
  245. newZone = newZone.parent;
  246. }
  247. }
  248. task._transitionTo(scheduling, notScheduled);
  249. var zoneDelegates = [];
  250. task._zoneDelegates = zoneDelegates;
  251. task._zone = this;
  252. try {
  253. task = this._zoneDelegate.scheduleTask(this, task);
  254. }
  255. catch (err) {
  256. // should set task's state to unknown when scheduleTask throw error
  257. // because the err may from reschedule, so the fromState maybe notScheduled
  258. task._transitionTo(unknown, scheduling, notScheduled);
  259. // TODO: @JiaLiPassion, should we check the result from handleError?
  260. this._zoneDelegate.handleError(this, err);
  261. throw err;
  262. }
  263. if (task._zoneDelegates === zoneDelegates) {
  264. // we have to check because internally the delegate can reschedule the task.
  265. this._updateTaskCount(task, 1);
  266. }
  267. if (task.state == scheduling) {
  268. task._transitionTo(scheduled, scheduling);
  269. }
  270. return task;
  271. };
  272. Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
  273. return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
  274. };
  275. Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
  276. return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  277. };
  278. Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
  279. return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  280. };
  281. Zone.prototype.cancelTask = function (task) {
  282. if (task.zone != this)
  283. throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
  284. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  285. if (task.state !== scheduled && task.state !== running) {
  286. return;
  287. }
  288. task._transitionTo(canceling, scheduled, running);
  289. try {
  290. this._zoneDelegate.cancelTask(this, task);
  291. }
  292. catch (err) {
  293. // if error occurs when cancelTask, transit the state to unknown
  294. task._transitionTo(unknown, canceling);
  295. this._zoneDelegate.handleError(this, err);
  296. throw err;
  297. }
  298. this._updateTaskCount(task, -1);
  299. task._transitionTo(notScheduled, canceling);
  300. task.runCount = 0;
  301. return task;
  302. };
  303. Zone.prototype._updateTaskCount = function (task, count) {
  304. var zoneDelegates = task._zoneDelegates;
  305. if (count == -1) {
  306. task._zoneDelegates = null;
  307. }
  308. for (var i = 0; i < zoneDelegates.length; i++) {
  309. zoneDelegates[i]._updateTaskCount(task.type, count);
  310. }
  311. };
  312. return Zone;
  313. }());
  314. _a = Zone;
  315. // tslint:disable-next-line:require-internal-with-underscore
  316. (function () {
  317. _a.__symbol__ = __symbol__;
  318. })();
  319. var DELEGATE_ZS = {
  320. name: '',
  321. onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
  322. onScheduleTask: function (delegate, _, target, task) { return delegate.scheduleTask(target, task); },
  323. onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
  324. onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
  325. };
  326. var _ZoneDelegate = /** @class */ (function () {
  327. function _ZoneDelegate(zone, parentDelegate, zoneSpec) {
  328. this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 };
  329. this.zone = zone;
  330. this._parentDelegate = parentDelegate;
  331. this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
  332. this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
  333. this._forkCurrZone =
  334. zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate._forkCurrZone);
  335. this._interceptZS =
  336. zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
  337. this._interceptDlgt =
  338. zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
  339. this._interceptCurrZone =
  340. zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate._interceptCurrZone);
  341. this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
  342. this._invokeDlgt =
  343. zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
  344. this._invokeCurrZone =
  345. zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate._invokeCurrZone);
  346. this._handleErrorZS =
  347. zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
  348. this._handleErrorDlgt =
  349. zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
  350. this._handleErrorCurrZone =
  351. zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate._handleErrorCurrZone);
  352. this._scheduleTaskZS =
  353. zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
  354. this._scheduleTaskDlgt = zoneSpec &&
  355. (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
  356. this._scheduleTaskCurrZone =
  357. zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate._scheduleTaskCurrZone);
  358. this._invokeTaskZS =
  359. zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
  360. this._invokeTaskDlgt =
  361. zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
  362. this._invokeTaskCurrZone =
  363. zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate._invokeTaskCurrZone);
  364. this._cancelTaskZS =
  365. zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
  366. this._cancelTaskDlgt =
  367. zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
  368. this._cancelTaskCurrZone =
  369. zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate._cancelTaskCurrZone);
  370. this._hasTaskZS = null;
  371. this._hasTaskDlgt = null;
  372. this._hasTaskDlgtOwner = null;
  373. this._hasTaskCurrZone = null;
  374. var zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
  375. var parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
  376. if (zoneSpecHasTask || parentHasTask) {
  377. // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
  378. // a case all task related interceptors must go through this ZD. We can't short circuit it.
  379. this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
  380. this._hasTaskDlgt = parentDelegate;
  381. this._hasTaskDlgtOwner = this;
  382. this._hasTaskCurrZone = zone;
  383. if (!zoneSpec.onScheduleTask) {
  384. this._scheduleTaskZS = DELEGATE_ZS;
  385. this._scheduleTaskDlgt = parentDelegate;
  386. this._scheduleTaskCurrZone = this.zone;
  387. }
  388. if (!zoneSpec.onInvokeTask) {
  389. this._invokeTaskZS = DELEGATE_ZS;
  390. this._invokeTaskDlgt = parentDelegate;
  391. this._invokeTaskCurrZone = this.zone;
  392. }
  393. if (!zoneSpec.onCancelTask) {
  394. this._cancelTaskZS = DELEGATE_ZS;
  395. this._cancelTaskDlgt = parentDelegate;
  396. this._cancelTaskCurrZone = this.zone;
  397. }
  398. }
  399. }
  400. _ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
  401. return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
  402. new Zone(targetZone, zoneSpec);
  403. };
  404. _ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
  405. return this._interceptZS ?
  406. this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
  407. callback;
  408. };
  409. _ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
  410. return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
  411. callback.apply(applyThis, applyArgs);
  412. };
  413. _ZoneDelegate.prototype.handleError = function (targetZone, error) {
  414. return this._handleErrorZS ?
  415. this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
  416. true;
  417. };
  418. _ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
  419. var returnTask = task;
  420. if (this._scheduleTaskZS) {
  421. if (this._hasTaskZS) {
  422. returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
  423. }
  424. // clang-format off
  425. returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
  426. // clang-format on
  427. if (!returnTask)
  428. returnTask = task;
  429. }
  430. else {
  431. if (task.scheduleFn) {
  432. task.scheduleFn(task);
  433. }
  434. else if (task.type == microTask) {
  435. scheduleMicroTask(task);
  436. }
  437. else {
  438. throw new Error('Task is missing scheduleFn.');
  439. }
  440. }
  441. return returnTask;
  442. };
  443. _ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
  444. return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
  445. task.callback.apply(applyThis, applyArgs);
  446. };
  447. _ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
  448. var value;
  449. if (this._cancelTaskZS) {
  450. value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
  451. }
  452. else {
  453. if (!task.cancelFn) {
  454. throw Error('Task is not cancelable');
  455. }
  456. value = task.cancelFn(task);
  457. }
  458. return value;
  459. };
  460. _ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
  461. // hasTask should not throw error so other ZoneDelegate
  462. // can still trigger hasTask callback
  463. try {
  464. this._hasTaskZS &&
  465. this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
  466. }
  467. catch (err) {
  468. this.handleError(targetZone, err);
  469. }
  470. };
  471. // tslint:disable-next-line:require-internal-with-underscore
  472. _ZoneDelegate.prototype._updateTaskCount = function (type, count) {
  473. var counts = this._taskCounts;
  474. var prev = counts[type];
  475. var next = counts[type] = prev + count;
  476. if (next < 0) {
  477. throw new Error('More tasks executed then were scheduled.');
  478. }
  479. if (prev == 0 || next == 0) {
  480. var isEmpty = {
  481. microTask: counts['microTask'] > 0,
  482. macroTask: counts['macroTask'] > 0,
  483. eventTask: counts['eventTask'] > 0,
  484. change: type
  485. };
  486. this.hasTask(this.zone, isEmpty);
  487. }
  488. };
  489. return _ZoneDelegate;
  490. }());
  491. var ZoneTask = /** @class */ (function () {
  492. function ZoneTask(type, source, callback, options, scheduleFn, cancelFn) {
  493. // tslint:disable-next-line:require-internal-with-underscore
  494. this._zone = null;
  495. this.runCount = 0;
  496. // tslint:disable-next-line:require-internal-with-underscore
  497. this._zoneDelegates = null;
  498. // tslint:disable-next-line:require-internal-with-underscore
  499. this._state = 'notScheduled';
  500. this.type = type;
  501. this.source = source;
  502. this.data = options;
  503. this.scheduleFn = scheduleFn;
  504. this.cancelFn = cancelFn;
  505. if (!callback) {
  506. throw new Error('callback is not defined');
  507. }
  508. this.callback = callback;
  509. var self = this;
  510. // TODO: @JiaLiPassion options should have interface
  511. if (type === eventTask && options && options.useG) {
  512. this.invoke = ZoneTask.invokeTask;
  513. }
  514. else {
  515. this.invoke = function () {
  516. return ZoneTask.invokeTask.call(global, self, this, arguments);
  517. };
  518. }
  519. }
  520. ZoneTask.invokeTask = function (task, target, args) {
  521. if (!task) {
  522. task = this;
  523. }
  524. _numberOfNestedTaskFrames++;
  525. try {
  526. task.runCount++;
  527. return task.zone.runTask(task, target, args);
  528. }
  529. finally {
  530. if (_numberOfNestedTaskFrames == 1) {
  531. drainMicroTaskQueue();
  532. }
  533. _numberOfNestedTaskFrames--;
  534. }
  535. };
  536. Object.defineProperty(ZoneTask.prototype, "zone", {
  537. get: function () {
  538. return this._zone;
  539. },
  540. enumerable: false,
  541. configurable: true
  542. });
  543. Object.defineProperty(ZoneTask.prototype, "state", {
  544. get: function () {
  545. return this._state;
  546. },
  547. enumerable: false,
  548. configurable: true
  549. });
  550. ZoneTask.prototype.cancelScheduleRequest = function () {
  551. this._transitionTo(notScheduled, scheduling);
  552. };
  553. // tslint:disable-next-line:require-internal-with-underscore
  554. ZoneTask.prototype._transitionTo = function (toState, fromState1, fromState2) {
  555. if (this._state === fromState1 || this._state === fromState2) {
  556. this._state = toState;
  557. if (toState == notScheduled) {
  558. this._zoneDelegates = null;
  559. }
  560. }
  561. else {
  562. throw new Error("".concat(this.type, " '").concat(this.source, "': can not transition to '").concat(toState, "', expecting state '").concat(fromState1, "'").concat(fromState2 ? ' or \'' + fromState2 + '\'' : '', ", was '").concat(this._state, "'."));
  563. }
  564. };
  565. ZoneTask.prototype.toString = function () {
  566. if (this.data && typeof this.data.handleId !== 'undefined') {
  567. return this.data.handleId.toString();
  568. }
  569. else {
  570. return Object.prototype.toString.call(this);
  571. }
  572. };
  573. // add toJSON method to prevent cyclic error when
  574. // call JSON.stringify(zoneTask)
  575. ZoneTask.prototype.toJSON = function () {
  576. return {
  577. type: this.type,
  578. state: this.state,
  579. source: this.source,
  580. zone: this.zone.name,
  581. runCount: this.runCount
  582. };
  583. };
  584. return ZoneTask;
  585. }());
  586. //////////////////////////////////////////////////////
  587. //////////////////////////////////////////////////////
  588. /// MICROTASK QUEUE
  589. //////////////////////////////////////////////////////
  590. //////////////////////////////////////////////////////
  591. var symbolSetTimeout = __symbol__('setTimeout');
  592. var symbolPromise = __symbol__('Promise');
  593. var symbolThen = __symbol__('then');
  594. var _microTaskQueue = [];
  595. var _isDrainingMicrotaskQueue = false;
  596. var nativeMicroTaskQueuePromise;
  597. function nativeScheduleMicroTask(func) {
  598. if (!nativeMicroTaskQueuePromise) {
  599. if (global[symbolPromise]) {
  600. nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
  601. }
  602. }
  603. if (nativeMicroTaskQueuePromise) {
  604. var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
  605. if (!nativeThen) {
  606. // native Promise is not patchable, we need to use `then` directly
  607. // issue 1078
  608. nativeThen = nativeMicroTaskQueuePromise['then'];
  609. }
  610. nativeThen.call(nativeMicroTaskQueuePromise, func);
  611. }
  612. else {
  613. global[symbolSetTimeout](func, 0);
  614. }
  615. }
  616. function scheduleMicroTask(task) {
  617. // if we are not running in any task, and there has not been anything scheduled
  618. // we must bootstrap the initial task creation by manually scheduling the drain
  619. if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
  620. // We are not running in Task, so we need to kickstart the microtask queue.
  621. nativeScheduleMicroTask(drainMicroTaskQueue);
  622. }
  623. task && _microTaskQueue.push(task);
  624. }
  625. function drainMicroTaskQueue() {
  626. if (!_isDrainingMicrotaskQueue) {
  627. _isDrainingMicrotaskQueue = true;
  628. while (_microTaskQueue.length) {
  629. var queue = _microTaskQueue;
  630. _microTaskQueue = [];
  631. for (var i = 0; i < queue.length; i++) {
  632. var task = queue[i];
  633. try {
  634. task.zone.runTask(task, null, null);
  635. }
  636. catch (error) {
  637. _api.onUnhandledError(error);
  638. }
  639. }
  640. }
  641. _api.microtaskDrainDone();
  642. _isDrainingMicrotaskQueue = false;
  643. }
  644. }
  645. //////////////////////////////////////////////////////
  646. //////////////////////////////////////////////////////
  647. /// BOOTSTRAP
  648. //////////////////////////////////////////////////////
  649. //////////////////////////////////////////////////////
  650. var NO_ZONE = { name: 'NO ZONE' };
  651. var notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
  652. var microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
  653. var patches = {};
  654. var _api = {
  655. symbol: __symbol__,
  656. currentZoneFrame: function () { return _currentZoneFrame; },
  657. onUnhandledError: noop,
  658. microtaskDrainDone: noop,
  659. scheduleMicroTask: scheduleMicroTask,
  660. showUncaughtError: function () { return !Zone[__symbol__('ignoreConsoleErrorUncaughtError')]; },
  661. patchEventTarget: function () { return []; },
  662. patchOnProperties: noop,
  663. patchMethod: function () { return noop; },
  664. bindArguments: function () { return []; },
  665. patchThen: function () { return noop; },
  666. patchMacroTask: function () { return noop; },
  667. patchEventPrototype: function () { return noop; },
  668. isIEOrEdge: function () { return false; },
  669. getGlobalObjects: function () { return undefined; },
  670. ObjectDefineProperty: function () { return noop; },
  671. ObjectGetOwnPropertyDescriptor: function () { return undefined; },
  672. ObjectCreate: function () { return undefined; },
  673. ArraySlice: function () { return []; },
  674. patchClass: function () { return noop; },
  675. wrapWithCurrentZone: function () { return noop; },
  676. filterProperties: function () { return []; },
  677. attachOriginToPatched: function () { return noop; },
  678. _redefineProperty: function () { return noop; },
  679. patchCallbacks: function () { return noop; },
  680. nativeScheduleMicroTask: nativeScheduleMicroTask
  681. };
  682. var _currentZoneFrame = { parent: null, zone: new Zone(null, null) };
  683. var _currentTask = null;
  684. var _numberOfNestedTaskFrames = 0;
  685. function noop() { }
  686. performanceMeasure('Zone', 'Zone');
  687. return global['Zone'] = Zone;
  688. }))(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
  689. /**
  690. * Suppress closure compiler errors about unknown 'Zone' variable
  691. * @fileoverview
  692. * @suppress {undefinedVars,globalThis,missingRequire}
  693. */
  694. /// <reference types="node"/>
  695. // issue #989, to reduce bundle size, use short name
  696. /** Object.getOwnPropertyDescriptor */
  697. var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  698. /** Object.defineProperty */
  699. var ObjectDefineProperty = Object.defineProperty;
  700. /** Object.getPrototypeOf */
  701. var ObjectGetPrototypeOf = Object.getPrototypeOf;
  702. /** Object.create */
  703. var ObjectCreate = Object.create;
  704. /** Array.prototype.slice */
  705. var ArraySlice = Array.prototype.slice;
  706. /** addEventListener string const */
  707. var ADD_EVENT_LISTENER_STR = 'addEventListener';
  708. /** removeEventListener string const */
  709. var REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  710. /** zoneSymbol addEventListener */
  711. var ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
  712. /** zoneSymbol removeEventListener */
  713. var ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
  714. /** true string const */
  715. var TRUE_STR = 'true';
  716. /** false string const */
  717. var FALSE_STR = 'false';
  718. /** Zone symbol prefix string const. */
  719. var ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
  720. function wrapWithCurrentZone(callback, source) {
  721. return Zone.current.wrap(callback, source);
  722. }
  723. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  724. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  725. }
  726. var zoneSymbol = Zone.__symbol__;
  727. var isWindowExists = typeof window !== 'undefined';
  728. var internalWindow = isWindowExists ? window : undefined;
  729. var _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
  730. var REMOVE_ATTRIBUTE = 'removeAttribute';
  731. function bindArguments(args, source) {
  732. for (var i = args.length - 1; i >= 0; i--) {
  733. if (typeof args[i] === 'function') {
  734. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  735. }
  736. }
  737. return args;
  738. }
  739. function patchPrototype(prototype, fnNames) {
  740. var source = prototype.constructor['name'];
  741. var _loop_1 = function (i) {
  742. var name_1 = fnNames[i];
  743. var delegate = prototype[name_1];
  744. if (delegate) {
  745. var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name_1);
  746. if (!isPropertyWritable(prototypeDesc)) {
  747. return "continue";
  748. }
  749. prototype[name_1] = (function (delegate) {
  750. var patched = function () {
  751. return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));
  752. };
  753. attachOriginToPatched(patched, delegate);
  754. return patched;
  755. })(delegate);
  756. }
  757. };
  758. for (var i = 0; i < fnNames.length; i++) {
  759. _loop_1(i);
  760. }
  761. }
  762. function isPropertyWritable(propertyDesc) {
  763. if (!propertyDesc) {
  764. return true;
  765. }
  766. if (propertyDesc.writable === false) {
  767. return false;
  768. }
  769. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  770. }
  771. var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
  772. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  773. // this code.
  774. var isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
  775. {}.toString.call(_global.process) === '[object process]');
  776. var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  777. // we are in electron of nw, so we are both browser and nodejs
  778. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  779. // this code.
  780. var isMix = typeof _global.process !== 'undefined' &&
  781. {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
  782. !!(isWindowExists && internalWindow['HTMLElement']);
  783. var zoneSymbolEventNames$1 = {};
  784. var wrapFn = function (event) {
  785. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  786. // event will be undefined, so we need to use window.event
  787. event = event || _global.event;
  788. if (!event) {
  789. return;
  790. }
  791. var eventNameSymbol = zoneSymbolEventNames$1[event.type];
  792. if (!eventNameSymbol) {
  793. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  794. }
  795. var target = this || event.target || _global;
  796. var listener = target[eventNameSymbol];
  797. var result;
  798. if (isBrowser && target === internalWindow && event.type === 'error') {
  799. // window.onerror have different signature
  800. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  801. // and onerror callback will prevent default when callback return true
  802. var errorEvent = event;
  803. result = listener &&
  804. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  805. if (result === true) {
  806. event.preventDefault();
  807. }
  808. }
  809. else {
  810. result = listener && listener.apply(this, arguments);
  811. if (result != undefined && !result) {
  812. event.preventDefault();
  813. }
  814. }
  815. return result;
  816. };
  817. function patchProperty(obj, prop, prototype) {
  818. var desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  819. if (!desc && prototype) {
  820. // when patch window object, use prototype to check prop exist or not
  821. var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  822. if (prototypeDesc) {
  823. desc = { enumerable: true, configurable: true };
  824. }
  825. }
  826. // if the descriptor not exists or is not configurable
  827. // just return
  828. if (!desc || !desc.configurable) {
  829. return;
  830. }
  831. var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  832. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  833. return;
  834. }
  835. // A property descriptor cannot have getter/setter and be writable
  836. // deleting the writable and value properties avoids this error:
  837. //
  838. // TypeError: property descriptors must not specify a value or be writable when a
  839. // getter or setter has been specified
  840. delete desc.writable;
  841. delete desc.value;
  842. var originalDescGet = desc.get;
  843. var originalDescSet = desc.set;
  844. // slice(2) cuz 'onclick' -> 'click', etc
  845. var eventName = prop.slice(2);
  846. var eventNameSymbol = zoneSymbolEventNames$1[eventName];
  847. if (!eventNameSymbol) {
  848. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  849. }
  850. desc.set = function (newValue) {
  851. // in some of windows's onproperty callback, this is undefined
  852. // so we need to check it
  853. var target = this;
  854. if (!target && obj === _global) {
  855. target = _global;
  856. }
  857. if (!target) {
  858. return;
  859. }
  860. var previousValue = target[eventNameSymbol];
  861. if (typeof previousValue === 'function') {
  862. target.removeEventListener(eventName, wrapFn);
  863. }
  864. // issue #978, when onload handler was added before loading zone.js
  865. // we should remove it with originalDescSet
  866. originalDescSet && originalDescSet.call(target, null);
  867. target[eventNameSymbol] = newValue;
  868. if (typeof newValue === 'function') {
  869. target.addEventListener(eventName, wrapFn, false);
  870. }
  871. };
  872. // The getter would return undefined for unassigned properties but the default value of an
  873. // unassigned property is null
  874. desc.get = function () {
  875. // in some of windows's onproperty callback, this is undefined
  876. // so we need to check it
  877. var target = this;
  878. if (!target && obj === _global) {
  879. target = _global;
  880. }
  881. if (!target) {
  882. return null;
  883. }
  884. var listener = target[eventNameSymbol];
  885. if (listener) {
  886. return listener;
  887. }
  888. else if (originalDescGet) {
  889. // result will be null when use inline event attribute,
  890. // such as <button onclick="func();">OK</button>
  891. // because the onclick function is internal raw uncompiled handler
  892. // the onclick will be evaluated when first time event was triggered or
  893. // the property is accessed, https://github.com/angular/zone.js/issues/525
  894. // so we should use original native get to retrieve the handler
  895. var value = originalDescGet.call(this);
  896. if (value) {
  897. desc.set.call(this, value);
  898. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  899. target.removeAttribute(prop);
  900. }
  901. return value;
  902. }
  903. }
  904. return null;
  905. };
  906. ObjectDefineProperty(obj, prop, desc);
  907. obj[onPropPatchedSymbol] = true;
  908. }
  909. function patchOnProperties(obj, properties, prototype) {
  910. if (properties) {
  911. for (var i = 0; i < properties.length; i++) {
  912. patchProperty(obj, 'on' + properties[i], prototype);
  913. }
  914. }
  915. else {
  916. var onProperties = [];
  917. for (var prop in obj) {
  918. if (prop.slice(0, 2) == 'on') {
  919. onProperties.push(prop);
  920. }
  921. }
  922. for (var j = 0; j < onProperties.length; j++) {
  923. patchProperty(obj, onProperties[j], prototype);
  924. }
  925. }
  926. }
  927. var originalInstanceKey = zoneSymbol('originalInstance');
  928. // wrap some native API on `window`
  929. function patchClass(className) {
  930. var OriginalClass = _global[className];
  931. if (!OriginalClass)
  932. return;
  933. // keep original class in global
  934. _global[zoneSymbol(className)] = OriginalClass;
  935. _global[className] = function () {
  936. var a = bindArguments(arguments, className);
  937. switch (a.length) {
  938. case 0:
  939. this[originalInstanceKey] = new OriginalClass();
  940. break;
  941. case 1:
  942. this[originalInstanceKey] = new OriginalClass(a[0]);
  943. break;
  944. case 2:
  945. this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
  946. break;
  947. case 3:
  948. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
  949. break;
  950. case 4:
  951. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
  952. break;
  953. default:
  954. throw new Error('Arg list too long.');
  955. }
  956. };
  957. // attach original delegate to patched function
  958. attachOriginToPatched(_global[className], OriginalClass);
  959. var instance = new OriginalClass(function () { });
  960. var prop;
  961. for (prop in instance) {
  962. // https://bugs.webkit.org/show_bug.cgi?id=44721
  963. if (className === 'XMLHttpRequest' && prop === 'responseBlob')
  964. continue;
  965. (function (prop) {
  966. if (typeof instance[prop] === 'function') {
  967. _global[className].prototype[prop] = function () {
  968. return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
  969. };
  970. }
  971. else {
  972. ObjectDefineProperty(_global[className].prototype, prop, {
  973. set: function (fn) {
  974. if (typeof fn === 'function') {
  975. this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
  976. // keep callback in wrapped function so we can
  977. // use it in Function.prototype.toString to return
  978. // the native one.
  979. attachOriginToPatched(this[originalInstanceKey][prop], fn);
  980. }
  981. else {
  982. this[originalInstanceKey][prop] = fn;
  983. }
  984. },
  985. get: function () {
  986. return this[originalInstanceKey][prop];
  987. }
  988. });
  989. }
  990. }(prop));
  991. }
  992. for (prop in OriginalClass) {
  993. if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
  994. _global[className][prop] = OriginalClass[prop];
  995. }
  996. }
  997. }
  998. function patchMethod(target, name, patchFn) {
  999. var proto = target;
  1000. while (proto && !proto.hasOwnProperty(name)) {
  1001. proto = ObjectGetPrototypeOf(proto);
  1002. }
  1003. if (!proto && target[name]) {
  1004. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1005. proto = target;
  1006. }
  1007. var delegateName = zoneSymbol(name);
  1008. var delegate = null;
  1009. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  1010. delegate = proto[delegateName] = proto[name];
  1011. // check whether proto[name] is writable
  1012. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  1013. var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  1014. if (isPropertyWritable(desc)) {
  1015. var patchDelegate_1 = patchFn(delegate, delegateName, name);
  1016. proto[name] = function () {
  1017. return patchDelegate_1(this, arguments);
  1018. };
  1019. attachOriginToPatched(proto[name], delegate);
  1020. }
  1021. }
  1022. return delegate;
  1023. }
  1024. // TODO: @JiaLiPassion, support cancel task later if necessary
  1025. function patchMacroTask(obj, funcName, metaCreator) {
  1026. var setNative = null;
  1027. function scheduleTask(task) {
  1028. var data = task.data;
  1029. data.args[data.cbIdx] = function () {
  1030. task.invoke.apply(this, arguments);
  1031. };
  1032. setNative.apply(data.target, data.args);
  1033. return task;
  1034. }
  1035. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1036. var meta = metaCreator(self, args);
  1037. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1038. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1039. }
  1040. else {
  1041. // cause an error by calling it directly.
  1042. return delegate.apply(self, args);
  1043. }
  1044. }; });
  1045. }
  1046. function attachOriginToPatched(patched, original) {
  1047. patched[zoneSymbol('OriginalDelegate')] = original;
  1048. }
  1049. var isDetectedIEOrEdge = false;
  1050. var ieOrEdge = false;
  1051. function isIE() {
  1052. try {
  1053. var ua = internalWindow.navigator.userAgent;
  1054. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
  1055. return true;
  1056. }
  1057. }
  1058. catch (error) {
  1059. }
  1060. return false;
  1061. }
  1062. function isIEOrEdge() {
  1063. if (isDetectedIEOrEdge) {
  1064. return ieOrEdge;
  1065. }
  1066. isDetectedIEOrEdge = true;
  1067. try {
  1068. var ua = internalWindow.navigator.userAgent;
  1069. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
  1070. ieOrEdge = true;
  1071. }
  1072. }
  1073. catch (error) {
  1074. }
  1075. return ieOrEdge;
  1076. }
  1077. Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
  1078. var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1079. var ObjectDefineProperty = Object.defineProperty;
  1080. function readableObjectToString(obj) {
  1081. if (obj && obj.toString === Object.prototype.toString) {
  1082. var className = obj.constructor && obj.constructor.name;
  1083. return (className ? className : '') + ': ' + JSON.stringify(obj);
  1084. }
  1085. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  1086. }
  1087. var __symbol__ = api.symbol;
  1088. var _uncaughtPromiseErrors = [];
  1089. var isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] === true;
  1090. var symbolPromise = __symbol__('Promise');
  1091. var symbolThen = __symbol__('then');
  1092. var creationTrace = '__creationTrace__';
  1093. api.onUnhandledError = function (e) {
  1094. if (api.showUncaughtError()) {
  1095. var rejection = e && e.rejection;
  1096. if (rejection) {
  1097. 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);
  1098. }
  1099. else {
  1100. console.error(e);
  1101. }
  1102. }
  1103. };
  1104. api.microtaskDrainDone = function () {
  1105. var _loop_2 = function () {
  1106. var uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  1107. try {
  1108. uncaughtPromiseError.zone.runGuarded(function () {
  1109. if (uncaughtPromiseError.throwOriginal) {
  1110. throw uncaughtPromiseError.rejection;
  1111. }
  1112. throw uncaughtPromiseError;
  1113. });
  1114. }
  1115. catch (error) {
  1116. handleUnhandledRejection(error);
  1117. }
  1118. };
  1119. while (_uncaughtPromiseErrors.length) {
  1120. _loop_2();
  1121. }
  1122. };
  1123. var UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  1124. function handleUnhandledRejection(e) {
  1125. api.onUnhandledError(e);
  1126. try {
  1127. var handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  1128. if (typeof handler === 'function') {
  1129. handler.call(this, e);
  1130. }
  1131. }
  1132. catch (err) {
  1133. }
  1134. }
  1135. function isThenable(value) {
  1136. return value && value.then;
  1137. }
  1138. function forwardResolution(value) {
  1139. return value;
  1140. }
  1141. function forwardRejection(rejection) {
  1142. return ZoneAwarePromise.reject(rejection);
  1143. }
  1144. var symbolState = __symbol__('state');
  1145. var symbolValue = __symbol__('value');
  1146. var symbolFinally = __symbol__('finally');
  1147. var symbolParentPromiseValue = __symbol__('parentPromiseValue');
  1148. var symbolParentPromiseState = __symbol__('parentPromiseState');
  1149. var source = 'Promise.then';
  1150. var UNRESOLVED = null;
  1151. var RESOLVED = true;
  1152. var REJECTED = false;
  1153. var REJECTED_NO_CATCH = 0;
  1154. function makeResolver(promise, state) {
  1155. return function (v) {
  1156. try {
  1157. resolvePromise(promise, state, v);
  1158. }
  1159. catch (err) {
  1160. resolvePromise(promise, false, err);
  1161. }
  1162. // Do not return value or you will break the Promise spec.
  1163. };
  1164. }
  1165. var once = function () {
  1166. var wasCalled = false;
  1167. return function wrapper(wrappedFunction) {
  1168. return function () {
  1169. if (wasCalled) {
  1170. return;
  1171. }
  1172. wasCalled = true;
  1173. wrappedFunction.apply(null, arguments);
  1174. };
  1175. };
  1176. };
  1177. var TYPE_ERROR = 'Promise resolved with itself';
  1178. var CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  1179. // Promise Resolution
  1180. function resolvePromise(promise, state, value) {
  1181. var onceWrapper = once();
  1182. if (promise === value) {
  1183. throw new TypeError(TYPE_ERROR);
  1184. }
  1185. if (promise[symbolState] === UNRESOLVED) {
  1186. // should only get value.then once based on promise spec.
  1187. var then = null;
  1188. try {
  1189. if (typeof value === 'object' || typeof value === 'function') {
  1190. then = value && value.then;
  1191. }
  1192. }
  1193. catch (err) {
  1194. onceWrapper(function () {
  1195. resolvePromise(promise, false, err);
  1196. })();
  1197. return promise;
  1198. }
  1199. // if (value instanceof ZoneAwarePromise) {
  1200. if (state !== REJECTED && value instanceof ZoneAwarePromise &&
  1201. value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
  1202. value[symbolState] !== UNRESOLVED) {
  1203. clearRejectedNoCatch(value);
  1204. resolvePromise(promise, value[symbolState], value[symbolValue]);
  1205. }
  1206. else if (state !== REJECTED && typeof then === 'function') {
  1207. try {
  1208. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  1209. }
  1210. catch (err) {
  1211. onceWrapper(function () {
  1212. resolvePromise(promise, false, err);
  1213. })();
  1214. }
  1215. }
  1216. else {
  1217. promise[symbolState] = state;
  1218. var queue = promise[symbolValue];
  1219. promise[symbolValue] = value;
  1220. if (promise[symbolFinally] === symbolFinally) {
  1221. // the promise is generated by Promise.prototype.finally
  1222. if (state === RESOLVED) {
  1223. // the state is resolved, should ignore the value
  1224. // and use parent promise value
  1225. promise[symbolState] = promise[symbolParentPromiseState];
  1226. promise[symbolValue] = promise[symbolParentPromiseValue];
  1227. }
  1228. }
  1229. // record task information in value when error occurs, so we can
  1230. // do some additional work such as render longStackTrace
  1231. if (state === REJECTED && value instanceof Error) {
  1232. // check if longStackTraceZone is here
  1233. var trace = Zone.currentTask && Zone.currentTask.data &&
  1234. Zone.currentTask.data[creationTrace];
  1235. if (trace) {
  1236. // only keep the long stack trace into error when in longStackTraceZone
  1237. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
  1238. }
  1239. }
  1240. for (var i = 0; i < queue.length;) {
  1241. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  1242. }
  1243. if (queue.length == 0 && state == REJECTED) {
  1244. promise[symbolState] = REJECTED_NO_CATCH;
  1245. var uncaughtPromiseError = value;
  1246. try {
  1247. // Here we throws a new Error to print more readable error log
  1248. // and if the value is not an error, zone.js builds an `Error`
  1249. // Object here to attach the stack information.
  1250. throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
  1251. (value && value.stack ? '\n' + value.stack : ''));
  1252. }
  1253. catch (err) {
  1254. uncaughtPromiseError = err;
  1255. }
  1256. if (isDisableWrappingUncaughtPromiseRejection) {
  1257. // If disable wrapping uncaught promise reject
  1258. // use the value instead of wrapping it.
  1259. uncaughtPromiseError.throwOriginal = true;
  1260. }
  1261. uncaughtPromiseError.rejection = value;
  1262. uncaughtPromiseError.promise = promise;
  1263. uncaughtPromiseError.zone = Zone.current;
  1264. uncaughtPromiseError.task = Zone.currentTask;
  1265. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  1266. api.scheduleMicroTask(); // to make sure that it is running
  1267. }
  1268. }
  1269. }
  1270. // Resolving an already resolved promise is a noop.
  1271. return promise;
  1272. }
  1273. var REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  1274. function clearRejectedNoCatch(promise) {
  1275. if (promise[symbolState] === REJECTED_NO_CATCH) {
  1276. // if the promise is rejected no catch status
  1277. // and queue.length > 0, means there is a error handler
  1278. // here to handle the rejected promise, we should trigger
  1279. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  1280. // eventHandler
  1281. try {
  1282. var handler = Zone[REJECTION_HANDLED_HANDLER];
  1283. if (handler && typeof handler === 'function') {
  1284. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  1285. }
  1286. }
  1287. catch (err) {
  1288. }
  1289. promise[symbolState] = REJECTED;
  1290. for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
  1291. if (promise === _uncaughtPromiseErrors[i].promise) {
  1292. _uncaughtPromiseErrors.splice(i, 1);
  1293. }
  1294. }
  1295. }
  1296. }
  1297. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  1298. clearRejectedNoCatch(promise);
  1299. var promiseState = promise[symbolState];
  1300. var delegate = promiseState ?
  1301. (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
  1302. (typeof onRejected === 'function') ? onRejected :
  1303. forwardRejection;
  1304. zone.scheduleMicroTask(source, function () {
  1305. try {
  1306. var parentPromiseValue = promise[symbolValue];
  1307. var isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  1308. if (isFinallyPromise) {
  1309. // if the promise is generated from finally call, keep parent promise's state and value
  1310. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  1311. chainPromise[symbolParentPromiseState] = promiseState;
  1312. }
  1313. // should not pass value to finally callback
  1314. var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
  1315. [] :
  1316. [parentPromiseValue]);
  1317. resolvePromise(chainPromise, true, value);
  1318. }
  1319. catch (error) {
  1320. // if error occurs, should always return this error
  1321. resolvePromise(chainPromise, false, error);
  1322. }
  1323. }, chainPromise);
  1324. }
  1325. var ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  1326. var noop = function () { };
  1327. var AggregateError = global.AggregateError;
  1328. var ZoneAwarePromise = /** @class */ (function () {
  1329. function ZoneAwarePromise(executor) {
  1330. var promise = this;
  1331. if (!(promise instanceof ZoneAwarePromise)) {
  1332. throw new Error('Must be an instanceof Promise.');
  1333. }
  1334. promise[symbolState] = UNRESOLVED;
  1335. promise[symbolValue] = []; // queue;
  1336. try {
  1337. var onceWrapper = once();
  1338. executor &&
  1339. executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
  1340. }
  1341. catch (error) {
  1342. resolvePromise(promise, false, error);
  1343. }
  1344. }
  1345. ZoneAwarePromise.toString = function () {
  1346. return ZONE_AWARE_PROMISE_TO_STRING;
  1347. };
  1348. ZoneAwarePromise.resolve = function (value) {
  1349. return resolvePromise(new this(null), RESOLVED, value);
  1350. };
  1351. ZoneAwarePromise.reject = function (error) {
  1352. return resolvePromise(new this(null), REJECTED, error);
  1353. };
  1354. ZoneAwarePromise.any = function (values) {
  1355. if (!values || typeof values[Symbol.iterator] !== 'function') {
  1356. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1357. }
  1358. var promises = [];
  1359. var count = 0;
  1360. try {
  1361. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  1362. var v = values_1[_i];
  1363. count++;
  1364. promises.push(ZoneAwarePromise.resolve(v));
  1365. }
  1366. }
  1367. catch (err) {
  1368. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1369. }
  1370. if (count === 0) {
  1371. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1372. }
  1373. var finished = false;
  1374. var errors = [];
  1375. return new ZoneAwarePromise(function (resolve, reject) {
  1376. for (var i = 0; i < promises.length; i++) {
  1377. promises[i].then(function (v) {
  1378. if (finished) {
  1379. return;
  1380. }
  1381. finished = true;
  1382. resolve(v);
  1383. }, function (err) {
  1384. errors.push(err);
  1385. count--;
  1386. if (count === 0) {
  1387. finished = true;
  1388. reject(new AggregateError(errors, 'All promises were rejected'));
  1389. }
  1390. });
  1391. }
  1392. });
  1393. };
  1394. ;
  1395. ZoneAwarePromise.race = function (values) {
  1396. var resolve;
  1397. var reject;
  1398. var promise = new this(function (res, rej) {
  1399. resolve = res;
  1400. reject = rej;
  1401. });
  1402. function onResolve(value) {
  1403. resolve(value);
  1404. }
  1405. function onReject(error) {
  1406. reject(error);
  1407. }
  1408. for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
  1409. var value = values_2[_i];
  1410. if (!isThenable(value)) {
  1411. value = this.resolve(value);
  1412. }
  1413. value.then(onResolve, onReject);
  1414. }
  1415. return promise;
  1416. };
  1417. ZoneAwarePromise.all = function (values) {
  1418. return ZoneAwarePromise.allWithCallback(values);
  1419. };
  1420. ZoneAwarePromise.allSettled = function (values) {
  1421. var P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  1422. return P.allWithCallback(values, {
  1423. thenCallback: function (value) { return ({ status: 'fulfilled', value: value }); },
  1424. errorCallback: function (err) { return ({ status: 'rejected', reason: err }); }
  1425. });
  1426. };
  1427. ZoneAwarePromise.allWithCallback = function (values, callback) {
  1428. var resolve;
  1429. var reject;
  1430. var promise = new this(function (res, rej) {
  1431. resolve = res;
  1432. reject = rej;
  1433. });
  1434. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  1435. var unresolvedCount = 2;
  1436. var valueIndex = 0;
  1437. var resolvedValues = [];
  1438. var _loop_3 = function (value) {
  1439. if (!isThenable(value)) {
  1440. value = this_1.resolve(value);
  1441. }
  1442. var curValueIndex = valueIndex;
  1443. try {
  1444. value.then(function (value) {
  1445. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  1446. unresolvedCount--;
  1447. if (unresolvedCount === 0) {
  1448. resolve(resolvedValues);
  1449. }
  1450. }, function (err) {
  1451. if (!callback) {
  1452. reject(err);
  1453. }
  1454. else {
  1455. resolvedValues[curValueIndex] = callback.errorCallback(err);
  1456. unresolvedCount--;
  1457. if (unresolvedCount === 0) {
  1458. resolve(resolvedValues);
  1459. }
  1460. }
  1461. });
  1462. }
  1463. catch (thenErr) {
  1464. reject(thenErr);
  1465. }
  1466. unresolvedCount++;
  1467. valueIndex++;
  1468. };
  1469. var this_1 = this;
  1470. for (var _i = 0, values_3 = values; _i < values_3.length; _i++) {
  1471. var value = values_3[_i];
  1472. _loop_3(value);
  1473. }
  1474. // Make the unresolvedCount zero-based again.
  1475. unresolvedCount -= 2;
  1476. if (unresolvedCount === 0) {
  1477. resolve(resolvedValues);
  1478. }
  1479. return promise;
  1480. };
  1481. Object.defineProperty(ZoneAwarePromise.prototype, Symbol.toStringTag, {
  1482. get: function () {
  1483. return 'Promise';
  1484. },
  1485. enumerable: false,
  1486. configurable: true
  1487. });
  1488. Object.defineProperty(ZoneAwarePromise.prototype, Symbol.species, {
  1489. get: function () {
  1490. return ZoneAwarePromise;
  1491. },
  1492. enumerable: false,
  1493. configurable: true
  1494. });
  1495. ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
  1496. var _a;
  1497. // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
  1498. // may be an object without a prototype (created through `Object.create(null)`); thus
  1499. // `this.constructor` will be undefined. One of the use cases is SystemJS creating
  1500. // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
  1501. // object and copies promise properties into that object (within the `getOrCreateLoad`
  1502. // function). The zone.js then checks if the resolved value has the `then` method and invokes
  1503. // it with the `value` context. Otherwise, this will throw an error: `TypeError: Cannot read
  1504. // properties of undefined (reading 'Symbol(Symbol.species)')`.
  1505. var C = (_a = this.constructor) === null || _a === void 0 ? void 0 : _a[Symbol.species];
  1506. if (!C || typeof C !== 'function') {
  1507. C = this.constructor || ZoneAwarePromise;
  1508. }
  1509. var chainPromise = new C(noop);
  1510. var zone = Zone.current;
  1511. if (this[symbolState] == UNRESOLVED) {
  1512. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  1513. }
  1514. else {
  1515. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  1516. }
  1517. return chainPromise;
  1518. };
  1519. ZoneAwarePromise.prototype.catch = function (onRejected) {
  1520. return this.then(null, onRejected);
  1521. };
  1522. ZoneAwarePromise.prototype.finally = function (onFinally) {
  1523. var _a;
  1524. // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
  1525. var C = (_a = this.constructor) === null || _a === void 0 ? void 0 : _a[Symbol.species];
  1526. if (!C || typeof C !== 'function') {
  1527. C = ZoneAwarePromise;
  1528. }
  1529. var chainPromise = new C(noop);
  1530. chainPromise[symbolFinally] = symbolFinally;
  1531. var zone = Zone.current;
  1532. if (this[symbolState] == UNRESOLVED) {
  1533. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  1534. }
  1535. else {
  1536. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  1537. }
  1538. return chainPromise;
  1539. };
  1540. return ZoneAwarePromise;
  1541. }());
  1542. // Protect against aggressive optimizers dropping seemingly unused properties.
  1543. // E.g. Closure Compiler in advanced mode.
  1544. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  1545. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  1546. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  1547. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  1548. var NativePromise = global[symbolPromise] = global['Promise'];
  1549. global['Promise'] = ZoneAwarePromise;
  1550. var symbolThenPatched = __symbol__('thenPatched');
  1551. function patchThen(Ctor) {
  1552. var proto = Ctor.prototype;
  1553. var prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  1554. if (prop && (prop.writable === false || !prop.configurable)) {
  1555. // check Ctor.prototype.then propertyDescriptor is writable or not
  1556. // in meteor env, writable is false, we should ignore such case
  1557. return;
  1558. }
  1559. var originalThen = proto.then;
  1560. // Keep a reference to the original method.
  1561. proto[symbolThen] = originalThen;
  1562. Ctor.prototype.then = function (onResolve, onReject) {
  1563. var _this = this;
  1564. var wrapped = new ZoneAwarePromise(function (resolve, reject) {
  1565. originalThen.call(_this, resolve, reject);
  1566. });
  1567. return wrapped.then(onResolve, onReject);
  1568. };
  1569. Ctor[symbolThenPatched] = true;
  1570. }
  1571. api.patchThen = patchThen;
  1572. function zoneify(fn) {
  1573. return function (self, args) {
  1574. var resultPromise = fn.apply(self, args);
  1575. if (resultPromise instanceof ZoneAwarePromise) {
  1576. return resultPromise;
  1577. }
  1578. var ctor = resultPromise.constructor;
  1579. if (!ctor[symbolThenPatched]) {
  1580. patchThen(ctor);
  1581. }
  1582. return resultPromise;
  1583. };
  1584. }
  1585. if (NativePromise) {
  1586. patchThen(NativePromise);
  1587. patchMethod(global, 'fetch', function (delegate) { return zoneify(delegate); });
  1588. }
  1589. // This is not part of public API, but it is useful for tests, so we expose it.
  1590. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  1591. return ZoneAwarePromise;
  1592. });
  1593. // override Function.prototype.toString to make zone.js patched function
  1594. // look like native function
  1595. Zone.__load_patch('toString', function (global) {
  1596. // patch Func.prototype.toString to let them look like native
  1597. var originalFunctionToString = Function.prototype.toString;
  1598. var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1599. var PROMISE_SYMBOL = zoneSymbol('Promise');
  1600. var ERROR_SYMBOL = zoneSymbol('Error');
  1601. var newFunctionToString = function toString() {
  1602. if (typeof this === 'function') {
  1603. var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1604. if (originalDelegate) {
  1605. if (typeof originalDelegate === 'function') {
  1606. return originalFunctionToString.call(originalDelegate);
  1607. }
  1608. else {
  1609. return Object.prototype.toString.call(originalDelegate);
  1610. }
  1611. }
  1612. if (this === Promise) {
  1613. var nativePromise = global[PROMISE_SYMBOL];
  1614. if (nativePromise) {
  1615. return originalFunctionToString.call(nativePromise);
  1616. }
  1617. }
  1618. if (this === Error) {
  1619. var nativeError = global[ERROR_SYMBOL];
  1620. if (nativeError) {
  1621. return originalFunctionToString.call(nativeError);
  1622. }
  1623. }
  1624. }
  1625. return originalFunctionToString.call(this);
  1626. };
  1627. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1628. Function.prototype.toString = newFunctionToString;
  1629. // patch Object.prototype.toString to let them look like native
  1630. var originalObjectToString = Object.prototype.toString;
  1631. var PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1632. Object.prototype.toString = function () {
  1633. if (typeof Promise === 'function' && this instanceof Promise) {
  1634. return PROMISE_OBJECT_TO_STRING;
  1635. }
  1636. return originalObjectToString.call(this);
  1637. };
  1638. });
  1639. /**
  1640. * @fileoverview
  1641. * @suppress {missingRequire}
  1642. */
  1643. var passiveSupported = false;
  1644. if (typeof window !== 'undefined') {
  1645. try {
  1646. var options = Object.defineProperty({}, 'passive', {
  1647. get: function () {
  1648. passiveSupported = true;
  1649. }
  1650. });
  1651. // Note: We pass the `options` object as the event handler too. This is not compatible with the
  1652. // signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
  1653. // without an actual handler.
  1654. window.addEventListener('test', options, options);
  1655. window.removeEventListener('test', options, options);
  1656. }
  1657. catch (err) {
  1658. passiveSupported = false;
  1659. }
  1660. }
  1661. // an identifier to tell ZoneTask do not create a new invoke closure
  1662. var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1663. useG: true
  1664. };
  1665. var zoneSymbolEventNames = {};
  1666. var globalSources = {};
  1667. var EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1668. var IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1669. function prepareEventNames(eventName, eventNameToString) {
  1670. var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1671. var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1672. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1673. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1674. zoneSymbolEventNames[eventName] = {};
  1675. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1676. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1677. }
  1678. function patchEventTarget(_global, api, apis, patchOptions) {
  1679. var ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1680. var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1681. var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1682. var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1683. var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1684. var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1685. var PREPEND_EVENT_LISTENER = 'prependListener';
  1686. var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1687. var invokeTask = function (task, target, event) {
  1688. // for better performance, check isRemoved which is set
  1689. // by removeEventListener
  1690. if (task.isRemoved) {
  1691. return;
  1692. }
  1693. var delegate = task.callback;
  1694. if (typeof delegate === 'object' && delegate.handleEvent) {
  1695. // create the bind version of handleEvent when invoke
  1696. task.callback = function (event) { return delegate.handleEvent(event); };
  1697. task.originalDelegate = delegate;
  1698. }
  1699. // invoke static task.invoke
  1700. // need to try/catch error here, otherwise, the error in one event listener
  1701. // will break the executions of the other event listeners. Also error will
  1702. // not remove the event listener when `once` options is true.
  1703. var error;
  1704. try {
  1705. task.invoke(task, target, [event]);
  1706. }
  1707. catch (err) {
  1708. error = err;
  1709. }
  1710. var options = task.options;
  1711. if (options && typeof options === 'object' && options.once) {
  1712. // if options.once is true, after invoke once remove listener here
  1713. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1714. // inside EventEmitter.once
  1715. var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
  1716. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options);
  1717. }
  1718. return error;
  1719. };
  1720. function globalCallback(context, event, isCapture) {
  1721. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1722. // event will be undefined, so we need to use window.event
  1723. event = event || _global.event;
  1724. if (!event) {
  1725. return;
  1726. }
  1727. // event.target is needed for Samsung TV and SourceBuffer
  1728. // || global is needed https://github.com/angular/zone.js/issues/190
  1729. var target = context || event.target || _global;
  1730. var tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1731. if (tasks) {
  1732. var errors = [];
  1733. // invoke all tasks which attached to current target with given event.type and capture = false
  1734. // for performance concern, if task.length === 1, just invoke
  1735. if (tasks.length === 1) {
  1736. var err = invokeTask(tasks[0], target, event);
  1737. err && errors.push(err);
  1738. }
  1739. else {
  1740. // https://github.com/angular/zone.js/issues/836
  1741. // copy the tasks array before invoke, to avoid
  1742. // the callback will remove itself or other listener
  1743. var copyTasks = tasks.slice();
  1744. for (var i = 0; i < copyTasks.length; i++) {
  1745. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1746. break;
  1747. }
  1748. var err = invokeTask(copyTasks[i], target, event);
  1749. err && errors.push(err);
  1750. }
  1751. }
  1752. // Since there is only one error, we don't need to schedule microTask
  1753. // to throw the error.
  1754. if (errors.length === 1) {
  1755. throw errors[0];
  1756. }
  1757. else {
  1758. var _loop_4 = function (i) {
  1759. var err = errors[i];
  1760. api.nativeScheduleMicroTask(function () {
  1761. throw err;
  1762. });
  1763. };
  1764. for (var i = 0; i < errors.length; i++) {
  1765. _loop_4(i);
  1766. }
  1767. }
  1768. }
  1769. }
  1770. // global shared zoneAwareCallback to handle all event callback with capture = false
  1771. var globalZoneAwareCallback = function (event) {
  1772. return globalCallback(this, event, false);
  1773. };
  1774. // global shared zoneAwareCallback to handle all event callback with capture = true
  1775. var globalZoneAwareCaptureCallback = function (event) {
  1776. return globalCallback(this, event, true);
  1777. };
  1778. function patchEventTargetMethods(obj, patchOptions) {
  1779. if (!obj) {
  1780. return false;
  1781. }
  1782. var useGlobalCallback = true;
  1783. if (patchOptions && patchOptions.useG !== undefined) {
  1784. useGlobalCallback = patchOptions.useG;
  1785. }
  1786. var validateHandler = patchOptions && patchOptions.vh;
  1787. var checkDuplicate = true;
  1788. if (patchOptions && patchOptions.chkDup !== undefined) {
  1789. checkDuplicate = patchOptions.chkDup;
  1790. }
  1791. var returnTarget = false;
  1792. if (patchOptions && patchOptions.rt !== undefined) {
  1793. returnTarget = patchOptions.rt;
  1794. }
  1795. var proto = obj;
  1796. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1797. proto = ObjectGetPrototypeOf(proto);
  1798. }
  1799. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1800. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1801. proto = obj;
  1802. }
  1803. if (!proto) {
  1804. return false;
  1805. }
  1806. if (proto[zoneSymbolAddEventListener]) {
  1807. return false;
  1808. }
  1809. var eventNameToString = patchOptions && patchOptions.eventNameToString;
  1810. // a shared global taskData to pass data for scheduleEventTask
  1811. // so we do not need to create a new object just for pass some data
  1812. var taskData = {};
  1813. var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
  1814. var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1815. proto[REMOVE_EVENT_LISTENER];
  1816. var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1817. proto[LISTENERS_EVENT_LISTENER];
  1818. var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1819. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
  1820. var nativePrependEventListener;
  1821. if (patchOptions && patchOptions.prepend) {
  1822. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1823. proto[patchOptions.prepend];
  1824. }
  1825. /**
  1826. * This util function will build an option object with passive option
  1827. * to handle all possible input from the user.
  1828. */
  1829. function buildEventListenerOptions(options, passive) {
  1830. if (!passiveSupported && typeof options === 'object' && options) {
  1831. // doesn't support passive but user want to pass an object as options.
  1832. // this will not work on some old browser, so we just pass a boolean
  1833. // as useCapture parameter
  1834. return !!options.capture;
  1835. }
  1836. if (!passiveSupported || !passive) {
  1837. return options;
  1838. }
  1839. if (typeof options === 'boolean') {
  1840. return { capture: options, passive: true };
  1841. }
  1842. if (!options) {
  1843. return { passive: true };
  1844. }
  1845. if (typeof options === 'object' && options.passive !== false) {
  1846. return __assign(__assign({}, options), { passive: true });
  1847. }
  1848. return options;
  1849. }
  1850. var customScheduleGlobal = function (task) {
  1851. // if there is already a task for the eventName + capture,
  1852. // just return, because we use the shared globalZoneAwareCallback here.
  1853. if (taskData.isExisting) {
  1854. return;
  1855. }
  1856. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1857. };
  1858. var customCancelGlobal = function (task) {
  1859. // if task is not marked as isRemoved, this call is directly
  1860. // from Zone.prototype.cancelTask, we should remove the task
  1861. // from tasksList of target first
  1862. if (!task.isRemoved) {
  1863. var symbolEventNames = zoneSymbolEventNames[task.eventName];
  1864. var symbolEventName = void 0;
  1865. if (symbolEventNames) {
  1866. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1867. }
  1868. var existingTasks = symbolEventName && task.target[symbolEventName];
  1869. if (existingTasks) {
  1870. for (var i = 0; i < existingTasks.length; i++) {
  1871. var existingTask = existingTasks[i];
  1872. if (existingTask === task) {
  1873. existingTasks.splice(i, 1);
  1874. // set isRemoved to data for faster invokeTask check
  1875. task.isRemoved = true;
  1876. if (existingTasks.length === 0) {
  1877. // all tasks for the eventName + capture have gone,
  1878. // remove globalZoneAwareCallback and remove the task cache from target
  1879. task.allRemoved = true;
  1880. task.target[symbolEventName] = null;
  1881. }
  1882. break;
  1883. }
  1884. }
  1885. }
  1886. }
  1887. // if all tasks for the eventName + capture have gone,
  1888. // we will really remove the global event callback,
  1889. // if not, return
  1890. if (!task.allRemoved) {
  1891. return;
  1892. }
  1893. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1894. };
  1895. var customScheduleNonGlobal = function (task) {
  1896. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1897. };
  1898. var customSchedulePrepend = function (task) {
  1899. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1900. };
  1901. var customCancelNonGlobal = function (task) {
  1902. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1903. };
  1904. var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1905. var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1906. var compareTaskCallbackVsDelegate = function (task, delegate) {
  1907. var typeOfDelegate = typeof delegate;
  1908. return (typeOfDelegate === 'function' && task.callback === delegate) ||
  1909. (typeOfDelegate === 'object' && task.originalDelegate === delegate);
  1910. };
  1911. var compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
  1912. var unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1913. var passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1914. var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
  1915. if (returnTarget === void 0) { returnTarget = false; }
  1916. if (prepend === void 0) { prepend = false; }
  1917. return function () {
  1918. var target = this || _global;
  1919. var eventName = arguments[0];
  1920. if (patchOptions && patchOptions.transferEventName) {
  1921. eventName = patchOptions.transferEventName(eventName);
  1922. }
  1923. var delegate = arguments[1];
  1924. if (!delegate) {
  1925. return nativeListener.apply(this, arguments);
  1926. }
  1927. if (isNode && eventName === 'uncaughtException') {
  1928. // don't patch uncaughtException of nodejs to prevent endless loop
  1929. return nativeListener.apply(this, arguments);
  1930. }
  1931. // don't create the bind delegate function for handleEvent
  1932. // case here to improve addEventListener performance
  1933. // we will create the bind delegate when invoke
  1934. var isHandleEvent = false;
  1935. if (typeof delegate !== 'function') {
  1936. if (!delegate.handleEvent) {
  1937. return nativeListener.apply(this, arguments);
  1938. }
  1939. isHandleEvent = true;
  1940. }
  1941. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1942. return;
  1943. }
  1944. var passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1945. var options = buildEventListenerOptions(arguments[2], passive);
  1946. if (unpatchedEvents) {
  1947. // check unpatched list
  1948. for (var i = 0; i < unpatchedEvents.length; i++) {
  1949. if (eventName === unpatchedEvents[i]) {
  1950. if (passive) {
  1951. return nativeListener.call(target, eventName, delegate, options);
  1952. }
  1953. else {
  1954. return nativeListener.apply(this, arguments);
  1955. }
  1956. }
  1957. }
  1958. }
  1959. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1960. var once = options && typeof options === 'object' ? options.once : false;
  1961. var zone = Zone.current;
  1962. var symbolEventNames = zoneSymbolEventNames[eventName];
  1963. if (!symbolEventNames) {
  1964. prepareEventNames(eventName, eventNameToString);
  1965. symbolEventNames = zoneSymbolEventNames[eventName];
  1966. }
  1967. var symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1968. var existingTasks = target[symbolEventName];
  1969. var isExisting = false;
  1970. if (existingTasks) {
  1971. // already have task registered
  1972. isExisting = true;
  1973. if (checkDuplicate) {
  1974. for (var i = 0; i < existingTasks.length; i++) {
  1975. if (compare(existingTasks[i], delegate)) {
  1976. // same callback, same capture, same event name, just return
  1977. return;
  1978. }
  1979. }
  1980. }
  1981. }
  1982. else {
  1983. existingTasks = target[symbolEventName] = [];
  1984. }
  1985. var source;
  1986. var constructorName = target.constructor['name'];
  1987. var targetSource = globalSources[constructorName];
  1988. if (targetSource) {
  1989. source = targetSource[eventName];
  1990. }
  1991. if (!source) {
  1992. source = constructorName + addSource +
  1993. (eventNameToString ? eventNameToString(eventName) : eventName);
  1994. }
  1995. // do not create a new object as task.data to pass those things
  1996. // just use the global shared one
  1997. taskData.options = options;
  1998. if (once) {
  1999. // if addEventListener with once options, we don't pass it to
  2000. // native addEventListener, instead we keep the once setting
  2001. // and handle ourselves.
  2002. taskData.options.once = false;
  2003. }
  2004. taskData.target = target;
  2005. taskData.capture = capture;
  2006. taskData.eventName = eventName;
  2007. taskData.isExisting = isExisting;
  2008. var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  2009. // keep taskData into data to allow onScheduleEventTask to access the task information
  2010. if (data) {
  2011. data.taskData = taskData;
  2012. }
  2013. var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  2014. // should clear taskData.target to avoid memory leak
  2015. // issue, https://github.com/angular/angular/issues/20442
  2016. taskData.target = null;
  2017. // need to clear up taskData because it is a global object
  2018. if (data) {
  2019. data.taskData = null;
  2020. }
  2021. // have to save those information to task in case
  2022. // application may call task.zone.cancelTask() directly
  2023. if (once) {
  2024. options.once = true;
  2025. }
  2026. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  2027. // if not support passive, and we pass an option object
  2028. // to addEventListener, we should save the options to task
  2029. task.options = options;
  2030. }
  2031. task.target = target;
  2032. task.capture = capture;
  2033. task.eventName = eventName;
  2034. if (isHandleEvent) {
  2035. // save original delegate for compare to check duplicate
  2036. task.originalDelegate = delegate;
  2037. }
  2038. if (!prepend) {
  2039. existingTasks.push(task);
  2040. }
  2041. else {
  2042. existingTasks.unshift(task);
  2043. }
  2044. if (returnTarget) {
  2045. return target;
  2046. }
  2047. };
  2048. };
  2049. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  2050. if (nativePrependEventListener) {
  2051. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  2052. }
  2053. proto[REMOVE_EVENT_LISTENER] = function () {
  2054. var target = this || _global;
  2055. var eventName = arguments[0];
  2056. if (patchOptions && patchOptions.transferEventName) {
  2057. eventName = patchOptions.transferEventName(eventName);
  2058. }
  2059. var options = arguments[2];
  2060. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  2061. var delegate = arguments[1];
  2062. if (!delegate) {
  2063. return nativeRemoveEventListener.apply(this, arguments);
  2064. }
  2065. if (validateHandler &&
  2066. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  2067. return;
  2068. }
  2069. var symbolEventNames = zoneSymbolEventNames[eventName];
  2070. var symbolEventName;
  2071. if (symbolEventNames) {
  2072. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  2073. }
  2074. var existingTasks = symbolEventName && target[symbolEventName];
  2075. if (existingTasks) {
  2076. for (var i = 0; i < existingTasks.length; i++) {
  2077. var existingTask = existingTasks[i];
  2078. if (compare(existingTask, delegate)) {
  2079. existingTasks.splice(i, 1);
  2080. // set isRemoved to data for faster invokeTask check
  2081. existingTask.isRemoved = true;
  2082. if (existingTasks.length === 0) {
  2083. // all tasks for the eventName + capture have gone,
  2084. // remove globalZoneAwareCallback and remove the task cache from target
  2085. existingTask.allRemoved = true;
  2086. target[symbolEventName] = null;
  2087. // in the target, we have an event listener which is added by on_property
  2088. // such as target.onclick = function() {}, so we need to clear this internal
  2089. // property too if all delegates all removed
  2090. if (typeof eventName === 'string') {
  2091. var onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  2092. target[onPropertySymbol] = null;
  2093. }
  2094. }
  2095. existingTask.zone.cancelTask(existingTask);
  2096. if (returnTarget) {
  2097. return target;
  2098. }
  2099. return;
  2100. }
  2101. }
  2102. }
  2103. // issue 930, didn't find the event name or callback
  2104. // from zone kept existingTasks, the callback maybe
  2105. // added outside of zone, we need to call native removeEventListener
  2106. // to try to remove it.
  2107. return nativeRemoveEventListener.apply(this, arguments);
  2108. };
  2109. proto[LISTENERS_EVENT_LISTENER] = function () {
  2110. var target = this || _global;
  2111. var eventName = arguments[0];
  2112. if (patchOptions && patchOptions.transferEventName) {
  2113. eventName = patchOptions.transferEventName(eventName);
  2114. }
  2115. var listeners = [];
  2116. var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  2117. for (var i = 0; i < tasks.length; i++) {
  2118. var task = tasks[i];
  2119. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2120. listeners.push(delegate);
  2121. }
  2122. return listeners;
  2123. };
  2124. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  2125. var target = this || _global;
  2126. var eventName = arguments[0];
  2127. if (!eventName) {
  2128. var keys = Object.keys(target);
  2129. for (var i = 0; i < keys.length; i++) {
  2130. var prop = keys[i];
  2131. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2132. var evtName = match && match[1];
  2133. // in nodejs EventEmitter, removeListener event is
  2134. // used for monitoring the removeListener call,
  2135. // so just keep removeListener eventListener until
  2136. // all other eventListeners are removed
  2137. if (evtName && evtName !== 'removeListener') {
  2138. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  2139. }
  2140. }
  2141. // remove removeListener listener finally
  2142. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  2143. }
  2144. else {
  2145. if (patchOptions && patchOptions.transferEventName) {
  2146. eventName = patchOptions.transferEventName(eventName);
  2147. }
  2148. var symbolEventNames = zoneSymbolEventNames[eventName];
  2149. if (symbolEventNames) {
  2150. var symbolEventName = symbolEventNames[FALSE_STR];
  2151. var symbolCaptureEventName = symbolEventNames[TRUE_STR];
  2152. var tasks = target[symbolEventName];
  2153. var captureTasks = target[symbolCaptureEventName];
  2154. if (tasks) {
  2155. var removeTasks = tasks.slice();
  2156. for (var i = 0; i < removeTasks.length; i++) {
  2157. var task = removeTasks[i];
  2158. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2159. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2160. }
  2161. }
  2162. if (captureTasks) {
  2163. var removeTasks = captureTasks.slice();
  2164. for (var i = 0; i < removeTasks.length; i++) {
  2165. var task = removeTasks[i];
  2166. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2167. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2168. }
  2169. }
  2170. }
  2171. }
  2172. if (returnTarget) {
  2173. return this;
  2174. }
  2175. };
  2176. // for native toString patch
  2177. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  2178. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  2179. if (nativeRemoveAllListeners) {
  2180. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  2181. }
  2182. if (nativeListeners) {
  2183. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  2184. }
  2185. return true;
  2186. }
  2187. var results = [];
  2188. for (var i = 0; i < apis.length; i++) {
  2189. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  2190. }
  2191. return results;
  2192. }
  2193. function findEventTasks(target, eventName) {
  2194. if (!eventName) {
  2195. var foundTasks = [];
  2196. for (var prop in target) {
  2197. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2198. var evtName = match && match[1];
  2199. if (evtName && (!eventName || evtName === eventName)) {
  2200. var tasks = target[prop];
  2201. if (tasks) {
  2202. for (var i = 0; i < tasks.length; i++) {
  2203. foundTasks.push(tasks[i]);
  2204. }
  2205. }
  2206. }
  2207. }
  2208. return foundTasks;
  2209. }
  2210. var symbolEventName = zoneSymbolEventNames[eventName];
  2211. if (!symbolEventName) {
  2212. prepareEventNames(eventName);
  2213. symbolEventName = zoneSymbolEventNames[eventName];
  2214. }
  2215. var captureFalseTasks = target[symbolEventName[FALSE_STR]];
  2216. var captureTrueTasks = target[symbolEventName[TRUE_STR]];
  2217. if (!captureFalseTasks) {
  2218. return captureTrueTasks ? captureTrueTasks.slice() : [];
  2219. }
  2220. else {
  2221. return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
  2222. captureFalseTasks.slice();
  2223. }
  2224. }
  2225. function patchEventPrototype(global, api) {
  2226. var Event = global['Event'];
  2227. if (Event && Event.prototype) {
  2228. api.patchMethod(Event.prototype, 'stopImmediatePropagation', function (delegate) { return function (self, args) {
  2229. self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
  2230. // we need to call the native stopImmediatePropagation
  2231. // in case in some hybrid application, some part of
  2232. // application will be controlled by zone, some are not
  2233. delegate && delegate.apply(self, args);
  2234. }; });
  2235. }
  2236. }
  2237. function patchCallbacks(api, target, targetName, method, callbacks) {
  2238. var symbol = Zone.__symbol__(method);
  2239. if (target[symbol]) {
  2240. return;
  2241. }
  2242. var nativeDelegate = target[symbol] = target[method];
  2243. target[method] = function (name, opts, options) {
  2244. if (opts && opts.prototype) {
  2245. callbacks.forEach(function (callback) {
  2246. var source = "".concat(targetName, ".").concat(method, "::") + callback;
  2247. var prototype = opts.prototype;
  2248. // Note: the `patchCallbacks` is used for patching the `document.registerElement` and
  2249. // `customElements.define`. We explicitly wrap the patching code into try-catch since
  2250. // callbacks may be already patched by other web components frameworks (e.g. LWC), and they
  2251. // make those properties non-writable. This means that patching callback will throw an error
  2252. // `cannot assign to read-only property`. See this code as an example:
  2253. // https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
  2254. // We don't want to stop the application rendering if we couldn't patch some
  2255. // callback, e.g. `attributeChangedCallback`.
  2256. try {
  2257. if (prototype.hasOwnProperty(callback)) {
  2258. var descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
  2259. if (descriptor && descriptor.value) {
  2260. descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
  2261. api._redefineProperty(opts.prototype, callback, descriptor);
  2262. }
  2263. else if (prototype[callback]) {
  2264. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2265. }
  2266. }
  2267. else if (prototype[callback]) {
  2268. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2269. }
  2270. }
  2271. catch (_a) {
  2272. // Note: we leave the catch block empty since there's no way to handle the error related
  2273. // to non-writable property.
  2274. }
  2275. });
  2276. }
  2277. return nativeDelegate.call(target, name, opts, options);
  2278. };
  2279. api.attachOriginToPatched(target[method], nativeDelegate);
  2280. }
  2281. /**
  2282. * @fileoverview
  2283. * @suppress {globalThis}
  2284. */
  2285. function filterProperties(target, onProperties, ignoreProperties) {
  2286. if (!ignoreProperties || ignoreProperties.length === 0) {
  2287. return onProperties;
  2288. }
  2289. var tip = ignoreProperties.filter(function (ip) { return ip.target === target; });
  2290. if (!tip || tip.length === 0) {
  2291. return onProperties;
  2292. }
  2293. var targetIgnoreProperties = tip[0].ignoreProperties;
  2294. return onProperties.filter(function (op) { return targetIgnoreProperties.indexOf(op) === -1; });
  2295. }
  2296. function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
  2297. // check whether target is available, sometimes target will be undefined
  2298. // because different browser or some 3rd party plugin.
  2299. if (!target) {
  2300. return;
  2301. }
  2302. var filteredProperties = filterProperties(target, onProperties, ignoreProperties);
  2303. patchOnProperties(target, filteredProperties, prototype);
  2304. }
  2305. /**
  2306. * Get all event name properties which the event name startsWith `on`
  2307. * from the target object itself, inherited properties are not considered.
  2308. */
  2309. function getOnEventNames(target) {
  2310. return Object.getOwnPropertyNames(target)
  2311. .filter(function (name) { return name.startsWith('on') && name.length > 2; })
  2312. .map(function (name) { return name.substring(2); });
  2313. }
  2314. function propertyDescriptorPatch(api, _global) {
  2315. if (isNode && !isMix) {
  2316. return;
  2317. }
  2318. if (Zone[api.symbol('patchEvents')]) {
  2319. // events are already been patched by legacy patch.
  2320. return;
  2321. }
  2322. var ignoreProperties = _global['__Zone_ignore_on_properties'];
  2323. // for browsers that we can patch the descriptor: Chrome & Firefox
  2324. var patchTargets = [];
  2325. if (isBrowser) {
  2326. var internalWindow_1 = window;
  2327. patchTargets = patchTargets.concat([
  2328. 'Document', 'SVGElement', 'Element', 'HTMLElement', 'HTMLBodyElement', 'HTMLMediaElement',
  2329. 'HTMLFrameSetElement', 'HTMLFrameElement', 'HTMLIFrameElement', 'HTMLMarqueeElement', 'Worker'
  2330. ]);
  2331. var ignoreErrorProperties = isIE() ? [{ target: internalWindow_1, ignoreProperties: ['error'] }] : [];
  2332. // in IE/Edge, onProp not exist in window object, but in WindowPrototype
  2333. // so we need to pass WindowPrototype to check onProp exist or not
  2334. patchFilteredProperties(internalWindow_1, getOnEventNames(internalWindow_1), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow_1));
  2335. }
  2336. patchTargets = patchTargets.concat([
  2337. 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'IDBIndex', 'IDBRequest', 'IDBOpenDBRequest',
  2338. 'IDBDatabase', 'IDBTransaction', 'IDBCursor', 'WebSocket'
  2339. ]);
  2340. for (var i = 0; i < patchTargets.length; i++) {
  2341. var target = _global[patchTargets[i]];
  2342. target && target.prototype &&
  2343. patchFilteredProperties(target.prototype, getOnEventNames(target.prototype), ignoreProperties);
  2344. }
  2345. }
  2346. Zone.__load_patch('util', function (global, Zone, api) {
  2347. // Collect native event names by looking at properties
  2348. // on the global namespace, e.g. 'onclick'.
  2349. var eventNames = getOnEventNames(global);
  2350. api.patchOnProperties = patchOnProperties;
  2351. api.patchMethod = patchMethod;
  2352. api.bindArguments = bindArguments;
  2353. api.patchMacroTask = patchMacroTask;
  2354. // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS` to
  2355. // define which events will not be patched by `Zone.js`.
  2356. // In newer version (>=0.9.0), we change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep
  2357. // the name consistent with angular repo.
  2358. // The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be supported for
  2359. // backwards compatibility.
  2360. var SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
  2361. var SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
  2362. if (global[SYMBOL_UNPATCHED_EVENTS]) {
  2363. global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
  2364. }
  2365. if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
  2366. Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
  2367. global[SYMBOL_BLACK_LISTED_EVENTS];
  2368. }
  2369. api.patchEventPrototype = patchEventPrototype;
  2370. api.patchEventTarget = patchEventTarget;
  2371. api.isIEOrEdge = isIEOrEdge;
  2372. api.ObjectDefineProperty = ObjectDefineProperty;
  2373. api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
  2374. api.ObjectCreate = ObjectCreate;
  2375. api.ArraySlice = ArraySlice;
  2376. api.patchClass = patchClass;
  2377. api.wrapWithCurrentZone = wrapWithCurrentZone;
  2378. api.filterProperties = filterProperties;
  2379. api.attachOriginToPatched = attachOriginToPatched;
  2380. api._redefineProperty = Object.defineProperty;
  2381. api.patchCallbacks = patchCallbacks;
  2382. api.getGlobalObjects = function () { return ({
  2383. globalSources: globalSources,
  2384. zoneSymbolEventNames: zoneSymbolEventNames,
  2385. eventNames: eventNames,
  2386. isBrowser: isBrowser,
  2387. isMix: isMix,
  2388. isNode: isNode,
  2389. TRUE_STR: TRUE_STR,
  2390. FALSE_STR: FALSE_STR,
  2391. ZONE_SYMBOL_PREFIX: ZONE_SYMBOL_PREFIX,
  2392. ADD_EVENT_LISTENER_STR: ADD_EVENT_LISTENER_STR,
  2393. REMOVE_EVENT_LISTENER_STR: REMOVE_EVENT_LISTENER_STR
  2394. }); };
  2395. });
  2396. /**
  2397. * @fileoverview
  2398. * @suppress {missingRequire}
  2399. */
  2400. function patchQueueMicrotask(global, api) {
  2401. api.patchMethod(global, 'queueMicrotask', function (delegate) {
  2402. return function (self, args) {
  2403. Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
  2404. };
  2405. });
  2406. }
  2407. /**
  2408. * @fileoverview
  2409. * @suppress {missingRequire}
  2410. */
  2411. var taskSymbol = zoneSymbol('zoneTask');
  2412. function patchTimer(window, setName, cancelName, nameSuffix) {
  2413. var setNative = null;
  2414. var clearNative = null;
  2415. setName += nameSuffix;
  2416. cancelName += nameSuffix;
  2417. var tasksByHandleId = {};
  2418. function scheduleTask(task) {
  2419. var data = task.data;
  2420. data.args[0] = function () {
  2421. return task.invoke.apply(this, arguments);
  2422. };
  2423. data.handleId = setNative.apply(window, data.args);
  2424. return task;
  2425. }
  2426. function clearTask(task) {
  2427. return clearNative.call(window, task.data.handleId);
  2428. }
  2429. setNative =
  2430. patchMethod(window, setName, function (delegate) { return function (self, args) {
  2431. if (typeof args[0] === 'function') {
  2432. var options_1 = {
  2433. isPeriodic: nameSuffix === 'Interval',
  2434. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  2435. undefined,
  2436. args: args
  2437. };
  2438. var callback_1 = args[0];
  2439. args[0] = function timer() {
  2440. try {
  2441. return callback_1.apply(this, arguments);
  2442. }
  2443. finally {
  2444. // issue-934, task will be cancelled
  2445. // even it is a periodic task such as
  2446. // setInterval
  2447. // https://github.com/angular/angular/issues/40387
  2448. // Cleanup tasksByHandleId should be handled before scheduleTask
  2449. // Since some zoneSpec may intercept and doesn't trigger
  2450. // scheduleFn(scheduleTask) provided here.
  2451. if (!(options_1.isPeriodic)) {
  2452. if (typeof options_1.handleId === 'number') {
  2453. // in non-nodejs env, we remove timerId
  2454. // from local cache
  2455. delete tasksByHandleId[options_1.handleId];
  2456. }
  2457. else if (options_1.handleId) {
  2458. // Node returns complex objects as handleIds
  2459. // we remove task reference from timer object
  2460. options_1.handleId[taskSymbol] = null;
  2461. }
  2462. }
  2463. }
  2464. };
  2465. var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options_1, scheduleTask, clearTask);
  2466. if (!task) {
  2467. return task;
  2468. }
  2469. // Node.js must additionally support the ref and unref functions.
  2470. var handle = task.data.handleId;
  2471. if (typeof handle === 'number') {
  2472. // for non nodejs env, we save handleId: task
  2473. // mapping in local cache for clearTimeout
  2474. tasksByHandleId[handle] = task;
  2475. }
  2476. else if (handle) {
  2477. // for nodejs env, we save task
  2478. // reference in timerId Object for clearTimeout
  2479. handle[taskSymbol] = task;
  2480. }
  2481. // check whether handle is null, because some polyfill or browser
  2482. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  2483. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  2484. typeof handle.unref === 'function') {
  2485. task.ref = handle.ref.bind(handle);
  2486. task.unref = handle.unref.bind(handle);
  2487. }
  2488. if (typeof handle === 'number' || handle) {
  2489. return handle;
  2490. }
  2491. return task;
  2492. }
  2493. else {
  2494. // cause an error by calling it directly.
  2495. return delegate.apply(window, args);
  2496. }
  2497. }; });
  2498. clearNative =
  2499. patchMethod(window, cancelName, function (delegate) { return function (self, args) {
  2500. var id = args[0];
  2501. var task;
  2502. if (typeof id === 'number') {
  2503. // non nodejs env.
  2504. task = tasksByHandleId[id];
  2505. }
  2506. else {
  2507. // nodejs env.
  2508. task = id && id[taskSymbol];
  2509. // other environments.
  2510. if (!task) {
  2511. task = id;
  2512. }
  2513. }
  2514. if (task && typeof task.type === 'string') {
  2515. if (task.state !== 'notScheduled' &&
  2516. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  2517. if (typeof id === 'number') {
  2518. delete tasksByHandleId[id];
  2519. }
  2520. else if (id) {
  2521. id[taskSymbol] = null;
  2522. }
  2523. // Do not cancel already canceled functions
  2524. task.zone.cancelTask(task);
  2525. }
  2526. }
  2527. else {
  2528. // cause an error by calling it directly.
  2529. delegate.apply(window, args);
  2530. }
  2531. }; });
  2532. }
  2533. function patchCustomElements(_global, api) {
  2534. var _a = api.getGlobalObjects(), isBrowser = _a.isBrowser, isMix = _a.isMix;
  2535. if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
  2536. return;
  2537. }
  2538. var callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
  2539. api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
  2540. }
  2541. function eventTargetPatch(_global, api) {
  2542. if (Zone[api.symbol('patchEventTarget')]) {
  2543. // EventTarget is already patched.
  2544. return;
  2545. }
  2546. 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;
  2547. // predefine all __zone_symbol__ + eventName + true/false string
  2548. for (var i = 0; i < eventNames.length; i++) {
  2549. var eventName = eventNames[i];
  2550. var falseEventName = eventName + FALSE_STR;
  2551. var trueEventName = eventName + TRUE_STR;
  2552. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  2553. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  2554. zoneSymbolEventNames[eventName] = {};
  2555. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  2556. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  2557. }
  2558. var EVENT_TARGET = _global['EventTarget'];
  2559. if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
  2560. return;
  2561. }
  2562. api.patchEventTarget(_global, api, [EVENT_TARGET && EVENT_TARGET.prototype]);
  2563. return true;
  2564. }
  2565. function patchEvent(global, api) {
  2566. api.patchEventPrototype(global, api);
  2567. }
  2568. /**
  2569. * @fileoverview
  2570. * @suppress {missingRequire}
  2571. */
  2572. Zone.__load_patch('legacy', function (global) {
  2573. var legacyPatch = global[Zone.__symbol__('legacyPatch')];
  2574. if (legacyPatch) {
  2575. legacyPatch();
  2576. }
  2577. });
  2578. Zone.__load_patch('timers', function (global) {
  2579. var set = 'set';
  2580. var clear = 'clear';
  2581. patchTimer(global, set, clear, 'Timeout');
  2582. patchTimer(global, set, clear, 'Interval');
  2583. patchTimer(global, set, clear, 'Immediate');
  2584. });
  2585. Zone.__load_patch('requestAnimationFrame', function (global) {
  2586. patchTimer(global, 'request', 'cancel', 'AnimationFrame');
  2587. patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
  2588. patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
  2589. });
  2590. Zone.__load_patch('blocking', function (global, Zone) {
  2591. var blockingMethods = ['alert', 'prompt', 'confirm'];
  2592. for (var i = 0; i < blockingMethods.length; i++) {
  2593. var name_2 = blockingMethods[i];
  2594. patchMethod(global, name_2, function (delegate, symbol, name) {
  2595. return function (s, args) {
  2596. return Zone.current.run(delegate, global, args, name);
  2597. };
  2598. });
  2599. }
  2600. });
  2601. Zone.__load_patch('EventTarget', function (global, Zone, api) {
  2602. patchEvent(global, api);
  2603. eventTargetPatch(global, api);
  2604. // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
  2605. var XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
  2606. if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
  2607. api.patchEventTarget(global, api, [XMLHttpRequestEventTarget.prototype]);
  2608. }
  2609. });
  2610. Zone.__load_patch('MutationObserver', function (global, Zone, api) {
  2611. patchClass('MutationObserver');
  2612. patchClass('WebKitMutationObserver');
  2613. });
  2614. Zone.__load_patch('IntersectionObserver', function (global, Zone, api) {
  2615. patchClass('IntersectionObserver');
  2616. });
  2617. Zone.__load_patch('FileReader', function (global, Zone, api) {
  2618. patchClass('FileReader');
  2619. });
  2620. Zone.__load_patch('on_property', function (global, Zone, api) {
  2621. propertyDescriptorPatch(api, global);
  2622. });
  2623. Zone.__load_patch('customElements', function (global, Zone, api) {
  2624. patchCustomElements(global, api);
  2625. });
  2626. Zone.__load_patch('XHR', function (global, Zone) {
  2627. // Treat XMLHttpRequest as a macrotask.
  2628. patchXHR(global);
  2629. var XHR_TASK = zoneSymbol('xhrTask');
  2630. var XHR_SYNC = zoneSymbol('xhrSync');
  2631. var XHR_LISTENER = zoneSymbol('xhrListener');
  2632. var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
  2633. var XHR_URL = zoneSymbol('xhrURL');
  2634. var XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
  2635. function patchXHR(window) {
  2636. var XMLHttpRequest = window['XMLHttpRequest'];
  2637. if (!XMLHttpRequest) {
  2638. // XMLHttpRequest is not available in service worker
  2639. return;
  2640. }
  2641. var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
  2642. function findPendingTask(target) {
  2643. return target[XHR_TASK];
  2644. }
  2645. var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2646. var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2647. if (!oriAddListener) {
  2648. var XMLHttpRequestEventTarget_1 = window['XMLHttpRequestEventTarget'];
  2649. if (XMLHttpRequestEventTarget_1) {
  2650. var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget_1.prototype;
  2651. oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2652. oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2653. }
  2654. }
  2655. var READY_STATE_CHANGE = 'readystatechange';
  2656. var SCHEDULED = 'scheduled';
  2657. function scheduleTask(task) {
  2658. var data = task.data;
  2659. var target = data.target;
  2660. target[XHR_SCHEDULED] = false;
  2661. target[XHR_ERROR_BEFORE_SCHEDULED] = false;
  2662. // remove existing event listener
  2663. var listener = target[XHR_LISTENER];
  2664. if (!oriAddListener) {
  2665. oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2666. oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2667. }
  2668. if (listener) {
  2669. oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
  2670. }
  2671. var newListener = target[XHR_LISTENER] = function () {
  2672. if (target.readyState === target.DONE) {
  2673. // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
  2674. // readyState=4 multiple times, so we need to check task state here
  2675. if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
  2676. // check whether the xhr has registered onload listener
  2677. // if that is the case, the task should invoke after all
  2678. // onload listeners finish.
  2679. // Also if the request failed without response (status = 0), the load event handler
  2680. // will not be triggered, in that case, we should also invoke the placeholder callback
  2681. // to close the XMLHttpRequest::send macroTask.
  2682. // https://github.com/angular/angular/issues/38795
  2683. var loadTasks = target[Zone.__symbol__('loadfalse')];
  2684. if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
  2685. var oriInvoke_1 = task.invoke;
  2686. task.invoke = function () {
  2687. // need to load the tasks again, because in other
  2688. // load listener, they may remove themselves
  2689. var loadTasks = target[Zone.__symbol__('loadfalse')];
  2690. for (var i = 0; i < loadTasks.length; i++) {
  2691. if (loadTasks[i] === task) {
  2692. loadTasks.splice(i, 1);
  2693. }
  2694. }
  2695. if (!data.aborted && task.state === SCHEDULED) {
  2696. oriInvoke_1.call(task);
  2697. }
  2698. };
  2699. loadTasks.push(task);
  2700. }
  2701. else {
  2702. task.invoke();
  2703. }
  2704. }
  2705. else if (!data.aborted && target[XHR_SCHEDULED] === false) {
  2706. // error occurs when xhr.send()
  2707. target[XHR_ERROR_BEFORE_SCHEDULED] = true;
  2708. }
  2709. }
  2710. };
  2711. oriAddListener.call(target, READY_STATE_CHANGE, newListener);
  2712. var storedTask = target[XHR_TASK];
  2713. if (!storedTask) {
  2714. target[XHR_TASK] = task;
  2715. }
  2716. sendNative.apply(target, data.args);
  2717. target[XHR_SCHEDULED] = true;
  2718. return task;
  2719. }
  2720. function placeholderCallback() { }
  2721. function clearTask(task) {
  2722. var data = task.data;
  2723. // Note - ideally, we would call data.target.removeEventListener here, but it's too late
  2724. // to prevent it from firing. So instead, we store info for the event listener.
  2725. data.aborted = true;
  2726. return abortNative.apply(data.target, data.args);
  2727. }
  2728. var openNative = patchMethod(XMLHttpRequestPrototype, 'open', function () { return function (self, args) {
  2729. self[XHR_SYNC] = args[2] == false;
  2730. self[XHR_URL] = args[1];
  2731. return openNative.apply(self, args);
  2732. }; });
  2733. var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
  2734. var fetchTaskAborting = zoneSymbol('fetchTaskAborting');
  2735. var fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
  2736. var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () { return function (self, args) {
  2737. if (Zone.current[fetchTaskScheduling] === true) {
  2738. // a fetch is scheduling, so we are using xhr to polyfill fetch
  2739. // and because we already schedule macroTask for fetch, we should
  2740. // not schedule a macroTask for xhr again
  2741. return sendNative.apply(self, args);
  2742. }
  2743. if (self[XHR_SYNC]) {
  2744. // if the XHR is sync there is no task to schedule, just execute the code.
  2745. return sendNative.apply(self, args);
  2746. }
  2747. else {
  2748. var options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
  2749. var task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
  2750. if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
  2751. task.state === SCHEDULED) {
  2752. // xhr request throw error when send
  2753. // we should invoke task instead of leaving a scheduled
  2754. // pending macroTask
  2755. task.invoke();
  2756. }
  2757. }
  2758. }; });
  2759. var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self, args) {
  2760. var task = findPendingTask(self);
  2761. if (task && typeof task.type == 'string') {
  2762. // If the XHR has already completed, do nothing.
  2763. // If the XHR has already been aborted, do nothing.
  2764. // Fix #569, call abort multiple times before done will cause
  2765. // macroTask task count be negative number
  2766. if (task.cancelFn == null || (task.data && task.data.aborted)) {
  2767. return;
  2768. }
  2769. task.zone.cancelTask(task);
  2770. }
  2771. else if (Zone.current[fetchTaskAborting] === true) {
  2772. // the abort is called from fetch polyfill, we need to call native abort of XHR.
  2773. return abortNative.apply(self, args);
  2774. }
  2775. // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
  2776. // task
  2777. // to cancel. Do nothing.
  2778. }; });
  2779. }
  2780. });
  2781. Zone.__load_patch('geolocation', function (global) {
  2782. /// GEO_LOCATION
  2783. if (global['navigator'] && global['navigator'].geolocation) {
  2784. patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
  2785. }
  2786. });
  2787. Zone.__load_patch('PromiseRejectionEvent', function (global, Zone) {
  2788. // handle unhandled promise rejection
  2789. function findPromiseRejectionHandler(evtName) {
  2790. return function (e) {
  2791. var eventTasks = findEventTasks(global, evtName);
  2792. eventTasks.forEach(function (eventTask) {
  2793. // windows has added unhandledrejection event listener
  2794. // trigger the event listener
  2795. var PromiseRejectionEvent = global['PromiseRejectionEvent'];
  2796. if (PromiseRejectionEvent) {
  2797. var evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection });
  2798. eventTask.invoke(evt);
  2799. }
  2800. });
  2801. };
  2802. }
  2803. if (global['PromiseRejectionEvent']) {
  2804. Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
  2805. findPromiseRejectionHandler('unhandledrejection');
  2806. Zone[zoneSymbol('rejectionHandledHandler')] =
  2807. findPromiseRejectionHandler('rejectionhandled');
  2808. }
  2809. });
  2810. Zone.__load_patch('queueMicrotask', function (global, Zone, api) {
  2811. patchQueueMicrotask(global, api);
  2812. });
  2813. }));