zone-node.umd.js 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513
  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. /** Array.prototype.slice */
  703. var ArraySlice = Array.prototype.slice;
  704. /** addEventListener string const */
  705. var ADD_EVENT_LISTENER_STR = 'addEventListener';
  706. /** removeEventListener string const */
  707. var REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  708. /** zoneSymbol addEventListener */
  709. Zone.__symbol__(ADD_EVENT_LISTENER_STR);
  710. /** zoneSymbol removeEventListener */
  711. Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
  712. /** true string const */
  713. var TRUE_STR = 'true';
  714. /** false string const */
  715. var FALSE_STR = 'false';
  716. /** Zone symbol prefix string const. */
  717. var ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
  718. function wrapWithCurrentZone(callback, source) {
  719. return Zone.current.wrap(callback, source);
  720. }
  721. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  722. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  723. }
  724. var zoneSymbol = Zone.__symbol__;
  725. var isWindowExists = typeof window !== 'undefined';
  726. var internalWindow = isWindowExists ? window : undefined;
  727. var _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
  728. var REMOVE_ATTRIBUTE = 'removeAttribute';
  729. function bindArguments(args, source) {
  730. for (var i = args.length - 1; i >= 0; i--) {
  731. if (typeof args[i] === 'function') {
  732. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  733. }
  734. }
  735. return args;
  736. }
  737. function isPropertyWritable(propertyDesc) {
  738. if (!propertyDesc) {
  739. return true;
  740. }
  741. if (propertyDesc.writable === false) {
  742. return false;
  743. }
  744. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  745. }
  746. var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
  747. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  748. // this code.
  749. var isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
  750. {}.toString.call(_global.process) === '[object process]');
  751. var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  752. // we are in electron of nw, so we are both browser and nodejs
  753. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  754. // this code.
  755. var isMix = typeof _global.process !== 'undefined' &&
  756. {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
  757. !!(isWindowExists && internalWindow['HTMLElement']);
  758. var zoneSymbolEventNames$1 = {};
  759. var wrapFn = function (event) {
  760. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  761. // event will be undefined, so we need to use window.event
  762. event = event || _global.event;
  763. if (!event) {
  764. return;
  765. }
  766. var eventNameSymbol = zoneSymbolEventNames$1[event.type];
  767. if (!eventNameSymbol) {
  768. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  769. }
  770. var target = this || event.target || _global;
  771. var listener = target[eventNameSymbol];
  772. var result;
  773. if (isBrowser && target === internalWindow && event.type === 'error') {
  774. // window.onerror have different signature
  775. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  776. // and onerror callback will prevent default when callback return true
  777. var errorEvent = event;
  778. result = listener &&
  779. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  780. if (result === true) {
  781. event.preventDefault();
  782. }
  783. }
  784. else {
  785. result = listener && listener.apply(this, arguments);
  786. if (result != undefined && !result) {
  787. event.preventDefault();
  788. }
  789. }
  790. return result;
  791. };
  792. function patchProperty(obj, prop, prototype) {
  793. var desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  794. if (!desc && prototype) {
  795. // when patch window object, use prototype to check prop exist or not
  796. var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  797. if (prototypeDesc) {
  798. desc = { enumerable: true, configurable: true };
  799. }
  800. }
  801. // if the descriptor not exists or is not configurable
  802. // just return
  803. if (!desc || !desc.configurable) {
  804. return;
  805. }
  806. var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  807. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  808. return;
  809. }
  810. // A property descriptor cannot have getter/setter and be writable
  811. // deleting the writable and value properties avoids this error:
  812. //
  813. // TypeError: property descriptors must not specify a value or be writable when a
  814. // getter or setter has been specified
  815. delete desc.writable;
  816. delete desc.value;
  817. var originalDescGet = desc.get;
  818. var originalDescSet = desc.set;
  819. // slice(2) cuz 'onclick' -> 'click', etc
  820. var eventName = prop.slice(2);
  821. var eventNameSymbol = zoneSymbolEventNames$1[eventName];
  822. if (!eventNameSymbol) {
  823. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  824. }
  825. desc.set = function (newValue) {
  826. // in some of windows's onproperty callback, this is undefined
  827. // so we need to check it
  828. var target = this;
  829. if (!target && obj === _global) {
  830. target = _global;
  831. }
  832. if (!target) {
  833. return;
  834. }
  835. var previousValue = target[eventNameSymbol];
  836. if (typeof previousValue === 'function') {
  837. target.removeEventListener(eventName, wrapFn);
  838. }
  839. // issue #978, when onload handler was added before loading zone.js
  840. // we should remove it with originalDescSet
  841. originalDescSet && originalDescSet.call(target, null);
  842. target[eventNameSymbol] = newValue;
  843. if (typeof newValue === 'function') {
  844. target.addEventListener(eventName, wrapFn, false);
  845. }
  846. };
  847. // The getter would return undefined for unassigned properties but the default value of an
  848. // unassigned property is null
  849. desc.get = function () {
  850. // in some of windows's onproperty callback, this is undefined
  851. // so we need to check it
  852. var target = this;
  853. if (!target && obj === _global) {
  854. target = _global;
  855. }
  856. if (!target) {
  857. return null;
  858. }
  859. var listener = target[eventNameSymbol];
  860. if (listener) {
  861. return listener;
  862. }
  863. else if (originalDescGet) {
  864. // result will be null when use inline event attribute,
  865. // such as <button onclick="func();">OK</button>
  866. // because the onclick function is internal raw uncompiled handler
  867. // the onclick will be evaluated when first time event was triggered or
  868. // the property is accessed, https://github.com/angular/zone.js/issues/525
  869. // so we should use original native get to retrieve the handler
  870. var value = originalDescGet.call(this);
  871. if (value) {
  872. desc.set.call(this, value);
  873. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  874. target.removeAttribute(prop);
  875. }
  876. return value;
  877. }
  878. }
  879. return null;
  880. };
  881. ObjectDefineProperty(obj, prop, desc);
  882. obj[onPropPatchedSymbol] = true;
  883. }
  884. function patchOnProperties(obj, properties, prototype) {
  885. if (properties) {
  886. for (var i = 0; i < properties.length; i++) {
  887. patchProperty(obj, 'on' + properties[i], prototype);
  888. }
  889. }
  890. else {
  891. var onProperties = [];
  892. for (var prop in obj) {
  893. if (prop.slice(0, 2) == 'on') {
  894. onProperties.push(prop);
  895. }
  896. }
  897. for (var j = 0; j < onProperties.length; j++) {
  898. patchProperty(obj, onProperties[j], prototype);
  899. }
  900. }
  901. }
  902. zoneSymbol('originalInstance');
  903. function copySymbolProperties(src, dest) {
  904. if (typeof Object.getOwnPropertySymbols !== 'function') {
  905. return;
  906. }
  907. var symbols = Object.getOwnPropertySymbols(src);
  908. symbols.forEach(function (symbol) {
  909. var desc = Object.getOwnPropertyDescriptor(src, symbol);
  910. Object.defineProperty(dest, symbol, {
  911. get: function () {
  912. return src[symbol];
  913. },
  914. set: function (value) {
  915. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  916. // if src[symbol] is not writable or not have a setter, just return
  917. return;
  918. }
  919. src[symbol] = value;
  920. },
  921. enumerable: desc ? desc.enumerable : true,
  922. configurable: desc ? desc.configurable : true
  923. });
  924. });
  925. }
  926. var shouldCopySymbolProperties = false;
  927. function setShouldCopySymbolProperties(flag) {
  928. shouldCopySymbolProperties = flag;
  929. }
  930. function patchMethod(target, name, patchFn) {
  931. var proto = target;
  932. while (proto && !proto.hasOwnProperty(name)) {
  933. proto = ObjectGetPrototypeOf(proto);
  934. }
  935. if (!proto && target[name]) {
  936. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  937. proto = target;
  938. }
  939. var delegateName = zoneSymbol(name);
  940. var delegate = null;
  941. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  942. delegate = proto[delegateName] = proto[name];
  943. // check whether proto[name] is writable
  944. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  945. var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  946. if (isPropertyWritable(desc)) {
  947. var patchDelegate_1 = patchFn(delegate, delegateName, name);
  948. proto[name] = function () {
  949. return patchDelegate_1(this, arguments);
  950. };
  951. attachOriginToPatched(proto[name], delegate);
  952. if (shouldCopySymbolProperties) {
  953. copySymbolProperties(delegate, proto[name]);
  954. }
  955. }
  956. }
  957. return delegate;
  958. }
  959. // TODO: @JiaLiPassion, support cancel task later if necessary
  960. function patchMacroTask(obj, funcName, metaCreator) {
  961. var setNative = null;
  962. function scheduleTask(task) {
  963. var data = task.data;
  964. data.args[data.cbIdx] = function () {
  965. task.invoke.apply(this, arguments);
  966. };
  967. setNative.apply(data.target, data.args);
  968. return task;
  969. }
  970. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  971. var meta = metaCreator(self, args);
  972. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  973. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  974. }
  975. else {
  976. // cause an error by calling it directly.
  977. return delegate.apply(self, args);
  978. }
  979. }; });
  980. }
  981. function patchMicroTask(obj, funcName, metaCreator) {
  982. var setNative = null;
  983. function scheduleTask(task) {
  984. var data = task.data;
  985. data.args[data.cbIdx] = function () {
  986. task.invoke.apply(this, arguments);
  987. };
  988. setNative.apply(data.target, data.args);
  989. return task;
  990. }
  991. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  992. var meta = metaCreator(self, args);
  993. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  994. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  995. }
  996. else {
  997. // cause an error by calling it directly.
  998. return delegate.apply(self, args);
  999. }
  1000. }; });
  1001. }
  1002. function attachOriginToPatched(patched, original) {
  1003. patched[zoneSymbol('OriginalDelegate')] = original;
  1004. }
  1005. Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
  1006. var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1007. var ObjectDefineProperty = Object.defineProperty;
  1008. function readableObjectToString(obj) {
  1009. if (obj && obj.toString === Object.prototype.toString) {
  1010. var className = obj.constructor && obj.constructor.name;
  1011. return (className ? className : '') + ': ' + JSON.stringify(obj);
  1012. }
  1013. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  1014. }
  1015. var __symbol__ = api.symbol;
  1016. var _uncaughtPromiseErrors = [];
  1017. var isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] === true;
  1018. var symbolPromise = __symbol__('Promise');
  1019. var symbolThen = __symbol__('then');
  1020. var creationTrace = '__creationTrace__';
  1021. api.onUnhandledError = function (e) {
  1022. if (api.showUncaughtError()) {
  1023. var rejection = e && e.rejection;
  1024. if (rejection) {
  1025. 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);
  1026. }
  1027. else {
  1028. console.error(e);
  1029. }
  1030. }
  1031. };
  1032. api.microtaskDrainDone = function () {
  1033. var _loop_1 = function () {
  1034. var uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  1035. try {
  1036. uncaughtPromiseError.zone.runGuarded(function () {
  1037. if (uncaughtPromiseError.throwOriginal) {
  1038. throw uncaughtPromiseError.rejection;
  1039. }
  1040. throw uncaughtPromiseError;
  1041. });
  1042. }
  1043. catch (error) {
  1044. handleUnhandledRejection(error);
  1045. }
  1046. };
  1047. while (_uncaughtPromiseErrors.length) {
  1048. _loop_1();
  1049. }
  1050. };
  1051. var UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  1052. function handleUnhandledRejection(e) {
  1053. api.onUnhandledError(e);
  1054. try {
  1055. var handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  1056. if (typeof handler === 'function') {
  1057. handler.call(this, e);
  1058. }
  1059. }
  1060. catch (err) {
  1061. }
  1062. }
  1063. function isThenable(value) {
  1064. return value && value.then;
  1065. }
  1066. function forwardResolution(value) {
  1067. return value;
  1068. }
  1069. function forwardRejection(rejection) {
  1070. return ZoneAwarePromise.reject(rejection);
  1071. }
  1072. var symbolState = __symbol__('state');
  1073. var symbolValue = __symbol__('value');
  1074. var symbolFinally = __symbol__('finally');
  1075. var symbolParentPromiseValue = __symbol__('parentPromiseValue');
  1076. var symbolParentPromiseState = __symbol__('parentPromiseState');
  1077. var source = 'Promise.then';
  1078. var UNRESOLVED = null;
  1079. var RESOLVED = true;
  1080. var REJECTED = false;
  1081. var REJECTED_NO_CATCH = 0;
  1082. function makeResolver(promise, state) {
  1083. return function (v) {
  1084. try {
  1085. resolvePromise(promise, state, v);
  1086. }
  1087. catch (err) {
  1088. resolvePromise(promise, false, err);
  1089. }
  1090. // Do not return value or you will break the Promise spec.
  1091. };
  1092. }
  1093. var once = function () {
  1094. var wasCalled = false;
  1095. return function wrapper(wrappedFunction) {
  1096. return function () {
  1097. if (wasCalled) {
  1098. return;
  1099. }
  1100. wasCalled = true;
  1101. wrappedFunction.apply(null, arguments);
  1102. };
  1103. };
  1104. };
  1105. var TYPE_ERROR = 'Promise resolved with itself';
  1106. var CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  1107. // Promise Resolution
  1108. function resolvePromise(promise, state, value) {
  1109. var onceWrapper = once();
  1110. if (promise === value) {
  1111. throw new TypeError(TYPE_ERROR);
  1112. }
  1113. if (promise[symbolState] === UNRESOLVED) {
  1114. // should only get value.then once based on promise spec.
  1115. var then = null;
  1116. try {
  1117. if (typeof value === 'object' || typeof value === 'function') {
  1118. then = value && value.then;
  1119. }
  1120. }
  1121. catch (err) {
  1122. onceWrapper(function () {
  1123. resolvePromise(promise, false, err);
  1124. })();
  1125. return promise;
  1126. }
  1127. // if (value instanceof ZoneAwarePromise) {
  1128. if (state !== REJECTED && value instanceof ZoneAwarePromise &&
  1129. value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
  1130. value[symbolState] !== UNRESOLVED) {
  1131. clearRejectedNoCatch(value);
  1132. resolvePromise(promise, value[symbolState], value[symbolValue]);
  1133. }
  1134. else if (state !== REJECTED && typeof then === 'function') {
  1135. try {
  1136. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  1137. }
  1138. catch (err) {
  1139. onceWrapper(function () {
  1140. resolvePromise(promise, false, err);
  1141. })();
  1142. }
  1143. }
  1144. else {
  1145. promise[symbolState] = state;
  1146. var queue = promise[symbolValue];
  1147. promise[symbolValue] = value;
  1148. if (promise[symbolFinally] === symbolFinally) {
  1149. // the promise is generated by Promise.prototype.finally
  1150. if (state === RESOLVED) {
  1151. // the state is resolved, should ignore the value
  1152. // and use parent promise value
  1153. promise[symbolState] = promise[symbolParentPromiseState];
  1154. promise[symbolValue] = promise[symbolParentPromiseValue];
  1155. }
  1156. }
  1157. // record task information in value when error occurs, so we can
  1158. // do some additional work such as render longStackTrace
  1159. if (state === REJECTED && value instanceof Error) {
  1160. // check if longStackTraceZone is here
  1161. var trace = Zone.currentTask && Zone.currentTask.data &&
  1162. Zone.currentTask.data[creationTrace];
  1163. if (trace) {
  1164. // only keep the long stack trace into error when in longStackTraceZone
  1165. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
  1166. }
  1167. }
  1168. for (var i = 0; i < queue.length;) {
  1169. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  1170. }
  1171. if (queue.length == 0 && state == REJECTED) {
  1172. promise[symbolState] = REJECTED_NO_CATCH;
  1173. var uncaughtPromiseError = value;
  1174. try {
  1175. // Here we throws a new Error to print more readable error log
  1176. // and if the value is not an error, zone.js builds an `Error`
  1177. // Object here to attach the stack information.
  1178. throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
  1179. (value && value.stack ? '\n' + value.stack : ''));
  1180. }
  1181. catch (err) {
  1182. uncaughtPromiseError = err;
  1183. }
  1184. if (isDisableWrappingUncaughtPromiseRejection) {
  1185. // If disable wrapping uncaught promise reject
  1186. // use the value instead of wrapping it.
  1187. uncaughtPromiseError.throwOriginal = true;
  1188. }
  1189. uncaughtPromiseError.rejection = value;
  1190. uncaughtPromiseError.promise = promise;
  1191. uncaughtPromiseError.zone = Zone.current;
  1192. uncaughtPromiseError.task = Zone.currentTask;
  1193. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  1194. api.scheduleMicroTask(); // to make sure that it is running
  1195. }
  1196. }
  1197. }
  1198. // Resolving an already resolved promise is a noop.
  1199. return promise;
  1200. }
  1201. var REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  1202. function clearRejectedNoCatch(promise) {
  1203. if (promise[symbolState] === REJECTED_NO_CATCH) {
  1204. // if the promise is rejected no catch status
  1205. // and queue.length > 0, means there is a error handler
  1206. // here to handle the rejected promise, we should trigger
  1207. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  1208. // eventHandler
  1209. try {
  1210. var handler = Zone[REJECTION_HANDLED_HANDLER];
  1211. if (handler && typeof handler === 'function') {
  1212. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  1213. }
  1214. }
  1215. catch (err) {
  1216. }
  1217. promise[symbolState] = REJECTED;
  1218. for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
  1219. if (promise === _uncaughtPromiseErrors[i].promise) {
  1220. _uncaughtPromiseErrors.splice(i, 1);
  1221. }
  1222. }
  1223. }
  1224. }
  1225. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  1226. clearRejectedNoCatch(promise);
  1227. var promiseState = promise[symbolState];
  1228. var delegate = promiseState ?
  1229. (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
  1230. (typeof onRejected === 'function') ? onRejected :
  1231. forwardRejection;
  1232. zone.scheduleMicroTask(source, function () {
  1233. try {
  1234. var parentPromiseValue = promise[symbolValue];
  1235. var isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  1236. if (isFinallyPromise) {
  1237. // if the promise is generated from finally call, keep parent promise's state and value
  1238. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  1239. chainPromise[symbolParentPromiseState] = promiseState;
  1240. }
  1241. // should not pass value to finally callback
  1242. var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
  1243. [] :
  1244. [parentPromiseValue]);
  1245. resolvePromise(chainPromise, true, value);
  1246. }
  1247. catch (error) {
  1248. // if error occurs, should always return this error
  1249. resolvePromise(chainPromise, false, error);
  1250. }
  1251. }, chainPromise);
  1252. }
  1253. var ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  1254. var noop = function () { };
  1255. var AggregateError = global.AggregateError;
  1256. var ZoneAwarePromise = /** @class */ (function () {
  1257. function ZoneAwarePromise(executor) {
  1258. var promise = this;
  1259. if (!(promise instanceof ZoneAwarePromise)) {
  1260. throw new Error('Must be an instanceof Promise.');
  1261. }
  1262. promise[symbolState] = UNRESOLVED;
  1263. promise[symbolValue] = []; // queue;
  1264. try {
  1265. var onceWrapper = once();
  1266. executor &&
  1267. executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
  1268. }
  1269. catch (error) {
  1270. resolvePromise(promise, false, error);
  1271. }
  1272. }
  1273. ZoneAwarePromise.toString = function () {
  1274. return ZONE_AWARE_PROMISE_TO_STRING;
  1275. };
  1276. ZoneAwarePromise.resolve = function (value) {
  1277. return resolvePromise(new this(null), RESOLVED, value);
  1278. };
  1279. ZoneAwarePromise.reject = function (error) {
  1280. return resolvePromise(new this(null), REJECTED, error);
  1281. };
  1282. ZoneAwarePromise.any = function (values) {
  1283. if (!values || typeof values[Symbol.iterator] !== 'function') {
  1284. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1285. }
  1286. var promises = [];
  1287. var count = 0;
  1288. try {
  1289. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  1290. var v = values_1[_i];
  1291. count++;
  1292. promises.push(ZoneAwarePromise.resolve(v));
  1293. }
  1294. }
  1295. catch (err) {
  1296. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1297. }
  1298. if (count === 0) {
  1299. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1300. }
  1301. var finished = false;
  1302. var errors = [];
  1303. return new ZoneAwarePromise(function (resolve, reject) {
  1304. for (var i = 0; i < promises.length; i++) {
  1305. promises[i].then(function (v) {
  1306. if (finished) {
  1307. return;
  1308. }
  1309. finished = true;
  1310. resolve(v);
  1311. }, function (err) {
  1312. errors.push(err);
  1313. count--;
  1314. if (count === 0) {
  1315. finished = true;
  1316. reject(new AggregateError(errors, 'All promises were rejected'));
  1317. }
  1318. });
  1319. }
  1320. });
  1321. };
  1322. ;
  1323. ZoneAwarePromise.race = function (values) {
  1324. var resolve;
  1325. var reject;
  1326. var promise = new this(function (res, rej) {
  1327. resolve = res;
  1328. reject = rej;
  1329. });
  1330. function onResolve(value) {
  1331. resolve(value);
  1332. }
  1333. function onReject(error) {
  1334. reject(error);
  1335. }
  1336. for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
  1337. var value = values_2[_i];
  1338. if (!isThenable(value)) {
  1339. value = this.resolve(value);
  1340. }
  1341. value.then(onResolve, onReject);
  1342. }
  1343. return promise;
  1344. };
  1345. ZoneAwarePromise.all = function (values) {
  1346. return ZoneAwarePromise.allWithCallback(values);
  1347. };
  1348. ZoneAwarePromise.allSettled = function (values) {
  1349. var P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  1350. return P.allWithCallback(values, {
  1351. thenCallback: function (value) { return ({ status: 'fulfilled', value: value }); },
  1352. errorCallback: function (err) { return ({ status: 'rejected', reason: err }); }
  1353. });
  1354. };
  1355. ZoneAwarePromise.allWithCallback = function (values, callback) {
  1356. var resolve;
  1357. var reject;
  1358. var promise = new this(function (res, rej) {
  1359. resolve = res;
  1360. reject = rej;
  1361. });
  1362. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  1363. var unresolvedCount = 2;
  1364. var valueIndex = 0;
  1365. var resolvedValues = [];
  1366. var _loop_2 = function (value) {
  1367. if (!isThenable(value)) {
  1368. value = this_1.resolve(value);
  1369. }
  1370. var curValueIndex = valueIndex;
  1371. try {
  1372. value.then(function (value) {
  1373. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  1374. unresolvedCount--;
  1375. if (unresolvedCount === 0) {
  1376. resolve(resolvedValues);
  1377. }
  1378. }, function (err) {
  1379. if (!callback) {
  1380. reject(err);
  1381. }
  1382. else {
  1383. resolvedValues[curValueIndex] = callback.errorCallback(err);
  1384. unresolvedCount--;
  1385. if (unresolvedCount === 0) {
  1386. resolve(resolvedValues);
  1387. }
  1388. }
  1389. });
  1390. }
  1391. catch (thenErr) {
  1392. reject(thenErr);
  1393. }
  1394. unresolvedCount++;
  1395. valueIndex++;
  1396. };
  1397. var this_1 = this;
  1398. for (var _i = 0, values_3 = values; _i < values_3.length; _i++) {
  1399. var value = values_3[_i];
  1400. _loop_2(value);
  1401. }
  1402. // Make the unresolvedCount zero-based again.
  1403. unresolvedCount -= 2;
  1404. if (unresolvedCount === 0) {
  1405. resolve(resolvedValues);
  1406. }
  1407. return promise;
  1408. };
  1409. Object.defineProperty(ZoneAwarePromise.prototype, Symbol.toStringTag, {
  1410. get: function () {
  1411. return 'Promise';
  1412. },
  1413. enumerable: false,
  1414. configurable: true
  1415. });
  1416. Object.defineProperty(ZoneAwarePromise.prototype, Symbol.species, {
  1417. get: function () {
  1418. return ZoneAwarePromise;
  1419. },
  1420. enumerable: false,
  1421. configurable: true
  1422. });
  1423. ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
  1424. var _a;
  1425. // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
  1426. // may be an object without a prototype (created through `Object.create(null)`); thus
  1427. // `this.constructor` will be undefined. One of the use cases is SystemJS creating
  1428. // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
  1429. // object and copies promise properties into that object (within the `getOrCreateLoad`
  1430. // function). The zone.js then checks if the resolved value has the `then` method and invokes
  1431. // it with the `value` context. Otherwise, this will throw an error: `TypeError: Cannot read
  1432. // properties of undefined (reading 'Symbol(Symbol.species)')`.
  1433. var C = (_a = this.constructor) === null || _a === void 0 ? void 0 : _a[Symbol.species];
  1434. if (!C || typeof C !== 'function') {
  1435. C = this.constructor || ZoneAwarePromise;
  1436. }
  1437. var chainPromise = new C(noop);
  1438. var zone = Zone.current;
  1439. if (this[symbolState] == UNRESOLVED) {
  1440. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  1441. }
  1442. else {
  1443. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  1444. }
  1445. return chainPromise;
  1446. };
  1447. ZoneAwarePromise.prototype.catch = function (onRejected) {
  1448. return this.then(null, onRejected);
  1449. };
  1450. ZoneAwarePromise.prototype.finally = function (onFinally) {
  1451. var _a;
  1452. // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
  1453. var C = (_a = this.constructor) === null || _a === void 0 ? void 0 : _a[Symbol.species];
  1454. if (!C || typeof C !== 'function') {
  1455. C = ZoneAwarePromise;
  1456. }
  1457. var chainPromise = new C(noop);
  1458. chainPromise[symbolFinally] = symbolFinally;
  1459. var zone = Zone.current;
  1460. if (this[symbolState] == UNRESOLVED) {
  1461. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  1462. }
  1463. else {
  1464. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  1465. }
  1466. return chainPromise;
  1467. };
  1468. return ZoneAwarePromise;
  1469. }());
  1470. // Protect against aggressive optimizers dropping seemingly unused properties.
  1471. // E.g. Closure Compiler in advanced mode.
  1472. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  1473. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  1474. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  1475. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  1476. var NativePromise = global[symbolPromise] = global['Promise'];
  1477. global['Promise'] = ZoneAwarePromise;
  1478. var symbolThenPatched = __symbol__('thenPatched');
  1479. function patchThen(Ctor) {
  1480. var proto = Ctor.prototype;
  1481. var prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  1482. if (prop && (prop.writable === false || !prop.configurable)) {
  1483. // check Ctor.prototype.then propertyDescriptor is writable or not
  1484. // in meteor env, writable is false, we should ignore such case
  1485. return;
  1486. }
  1487. var originalThen = proto.then;
  1488. // Keep a reference to the original method.
  1489. proto[symbolThen] = originalThen;
  1490. Ctor.prototype.then = function (onResolve, onReject) {
  1491. var _this = this;
  1492. var wrapped = new ZoneAwarePromise(function (resolve, reject) {
  1493. originalThen.call(_this, resolve, reject);
  1494. });
  1495. return wrapped.then(onResolve, onReject);
  1496. };
  1497. Ctor[symbolThenPatched] = true;
  1498. }
  1499. api.patchThen = patchThen;
  1500. function zoneify(fn) {
  1501. return function (self, args) {
  1502. var resultPromise = fn.apply(self, args);
  1503. if (resultPromise instanceof ZoneAwarePromise) {
  1504. return resultPromise;
  1505. }
  1506. var ctor = resultPromise.constructor;
  1507. if (!ctor[symbolThenPatched]) {
  1508. patchThen(ctor);
  1509. }
  1510. return resultPromise;
  1511. };
  1512. }
  1513. if (NativePromise) {
  1514. patchThen(NativePromise);
  1515. patchMethod(global, 'fetch', function (delegate) { return zoneify(delegate); });
  1516. }
  1517. // This is not part of public API, but it is useful for tests, so we expose it.
  1518. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  1519. return ZoneAwarePromise;
  1520. });
  1521. // override Function.prototype.toString to make zone.js patched function
  1522. // look like native function
  1523. Zone.__load_patch('toString', function (global) {
  1524. // patch Func.prototype.toString to let them look like native
  1525. var originalFunctionToString = Function.prototype.toString;
  1526. var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1527. var PROMISE_SYMBOL = zoneSymbol('Promise');
  1528. var ERROR_SYMBOL = zoneSymbol('Error');
  1529. var newFunctionToString = function toString() {
  1530. if (typeof this === 'function') {
  1531. var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1532. if (originalDelegate) {
  1533. if (typeof originalDelegate === 'function') {
  1534. return originalFunctionToString.call(originalDelegate);
  1535. }
  1536. else {
  1537. return Object.prototype.toString.call(originalDelegate);
  1538. }
  1539. }
  1540. if (this === Promise) {
  1541. var nativePromise = global[PROMISE_SYMBOL];
  1542. if (nativePromise) {
  1543. return originalFunctionToString.call(nativePromise);
  1544. }
  1545. }
  1546. if (this === Error) {
  1547. var nativeError = global[ERROR_SYMBOL];
  1548. if (nativeError) {
  1549. return originalFunctionToString.call(nativeError);
  1550. }
  1551. }
  1552. }
  1553. return originalFunctionToString.call(this);
  1554. };
  1555. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1556. Function.prototype.toString = newFunctionToString;
  1557. // patch Object.prototype.toString to let them look like native
  1558. var originalObjectToString = Object.prototype.toString;
  1559. var PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1560. Object.prototype.toString = function () {
  1561. if (typeof Promise === 'function' && this instanceof Promise) {
  1562. return PROMISE_OBJECT_TO_STRING;
  1563. }
  1564. return originalObjectToString.call(this);
  1565. };
  1566. });
  1567. Zone.__load_patch('node_util', function (global, Zone, api) {
  1568. api.patchOnProperties = patchOnProperties;
  1569. api.patchMethod = patchMethod;
  1570. api.bindArguments = bindArguments;
  1571. api.patchMacroTask = patchMacroTask;
  1572. setShouldCopySymbolProperties(true);
  1573. });
  1574. /**
  1575. * @fileoverview
  1576. * @suppress {missingRequire}
  1577. */
  1578. var passiveSupported = false;
  1579. if (typeof window !== 'undefined') {
  1580. try {
  1581. var options = Object.defineProperty({}, 'passive', {
  1582. get: function () {
  1583. passiveSupported = true;
  1584. }
  1585. });
  1586. // Note: We pass the `options` object as the event handler too. This is not compatible with the
  1587. // signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
  1588. // without an actual handler.
  1589. window.addEventListener('test', options, options);
  1590. window.removeEventListener('test', options, options);
  1591. }
  1592. catch (err) {
  1593. passiveSupported = false;
  1594. }
  1595. }
  1596. // an identifier to tell ZoneTask do not create a new invoke closure
  1597. var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1598. useG: true
  1599. };
  1600. var zoneSymbolEventNames = {};
  1601. var globalSources = {};
  1602. var EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1603. var IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1604. function prepareEventNames(eventName, eventNameToString) {
  1605. var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1606. var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1607. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1608. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1609. zoneSymbolEventNames[eventName] = {};
  1610. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1611. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1612. }
  1613. function patchEventTarget(_global, api, apis, patchOptions) {
  1614. var ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1615. var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1616. var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1617. var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1618. var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1619. var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1620. var PREPEND_EVENT_LISTENER = 'prependListener';
  1621. var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1622. var invokeTask = function (task, target, event) {
  1623. // for better performance, check isRemoved which is set
  1624. // by removeEventListener
  1625. if (task.isRemoved) {
  1626. return;
  1627. }
  1628. var delegate = task.callback;
  1629. if (typeof delegate === 'object' && delegate.handleEvent) {
  1630. // create the bind version of handleEvent when invoke
  1631. task.callback = function (event) { return delegate.handleEvent(event); };
  1632. task.originalDelegate = delegate;
  1633. }
  1634. // invoke static task.invoke
  1635. // need to try/catch error here, otherwise, the error in one event listener
  1636. // will break the executions of the other event listeners. Also error will
  1637. // not remove the event listener when `once` options is true.
  1638. var error;
  1639. try {
  1640. task.invoke(task, target, [event]);
  1641. }
  1642. catch (err) {
  1643. error = err;
  1644. }
  1645. var options = task.options;
  1646. if (options && typeof options === 'object' && options.once) {
  1647. // if options.once is true, after invoke once remove listener here
  1648. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1649. // inside EventEmitter.once
  1650. var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
  1651. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options);
  1652. }
  1653. return error;
  1654. };
  1655. function globalCallback(context, event, isCapture) {
  1656. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1657. // event will be undefined, so we need to use window.event
  1658. event = event || _global.event;
  1659. if (!event) {
  1660. return;
  1661. }
  1662. // event.target is needed for Samsung TV and SourceBuffer
  1663. // || global is needed https://github.com/angular/zone.js/issues/190
  1664. var target = context || event.target || _global;
  1665. var tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1666. if (tasks) {
  1667. var errors = [];
  1668. // invoke all tasks which attached to current target with given event.type and capture = false
  1669. // for performance concern, if task.length === 1, just invoke
  1670. if (tasks.length === 1) {
  1671. var err = invokeTask(tasks[0], target, event);
  1672. err && errors.push(err);
  1673. }
  1674. else {
  1675. // https://github.com/angular/zone.js/issues/836
  1676. // copy the tasks array before invoke, to avoid
  1677. // the callback will remove itself or other listener
  1678. var copyTasks = tasks.slice();
  1679. for (var i = 0; i < copyTasks.length; i++) {
  1680. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1681. break;
  1682. }
  1683. var err = invokeTask(copyTasks[i], target, event);
  1684. err && errors.push(err);
  1685. }
  1686. }
  1687. // Since there is only one error, we don't need to schedule microTask
  1688. // to throw the error.
  1689. if (errors.length === 1) {
  1690. throw errors[0];
  1691. }
  1692. else {
  1693. var _loop_3 = function (i) {
  1694. var err = errors[i];
  1695. api.nativeScheduleMicroTask(function () {
  1696. throw err;
  1697. });
  1698. };
  1699. for (var i = 0; i < errors.length; i++) {
  1700. _loop_3(i);
  1701. }
  1702. }
  1703. }
  1704. }
  1705. // global shared zoneAwareCallback to handle all event callback with capture = false
  1706. var globalZoneAwareCallback = function (event) {
  1707. return globalCallback(this, event, false);
  1708. };
  1709. // global shared zoneAwareCallback to handle all event callback with capture = true
  1710. var globalZoneAwareCaptureCallback = function (event) {
  1711. return globalCallback(this, event, true);
  1712. };
  1713. function patchEventTargetMethods(obj, patchOptions) {
  1714. if (!obj) {
  1715. return false;
  1716. }
  1717. var useGlobalCallback = true;
  1718. if (patchOptions && patchOptions.useG !== undefined) {
  1719. useGlobalCallback = patchOptions.useG;
  1720. }
  1721. var validateHandler = patchOptions && patchOptions.vh;
  1722. var checkDuplicate = true;
  1723. if (patchOptions && patchOptions.chkDup !== undefined) {
  1724. checkDuplicate = patchOptions.chkDup;
  1725. }
  1726. var returnTarget = false;
  1727. if (patchOptions && patchOptions.rt !== undefined) {
  1728. returnTarget = patchOptions.rt;
  1729. }
  1730. var proto = obj;
  1731. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1732. proto = ObjectGetPrototypeOf(proto);
  1733. }
  1734. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1735. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1736. proto = obj;
  1737. }
  1738. if (!proto) {
  1739. return false;
  1740. }
  1741. if (proto[zoneSymbolAddEventListener]) {
  1742. return false;
  1743. }
  1744. var eventNameToString = patchOptions && patchOptions.eventNameToString;
  1745. // a shared global taskData to pass data for scheduleEventTask
  1746. // so we do not need to create a new object just for pass some data
  1747. var taskData = {};
  1748. var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
  1749. var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1750. proto[REMOVE_EVENT_LISTENER];
  1751. var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1752. proto[LISTENERS_EVENT_LISTENER];
  1753. var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1754. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
  1755. var nativePrependEventListener;
  1756. if (patchOptions && patchOptions.prepend) {
  1757. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1758. proto[patchOptions.prepend];
  1759. }
  1760. /**
  1761. * This util function will build an option object with passive option
  1762. * to handle all possible input from the user.
  1763. */
  1764. function buildEventListenerOptions(options, passive) {
  1765. if (!passiveSupported && typeof options === 'object' && options) {
  1766. // doesn't support passive but user want to pass an object as options.
  1767. // this will not work on some old browser, so we just pass a boolean
  1768. // as useCapture parameter
  1769. return !!options.capture;
  1770. }
  1771. if (!passiveSupported || !passive) {
  1772. return options;
  1773. }
  1774. if (typeof options === 'boolean') {
  1775. return { capture: options, passive: true };
  1776. }
  1777. if (!options) {
  1778. return { passive: true };
  1779. }
  1780. if (typeof options === 'object' && options.passive !== false) {
  1781. return __assign(__assign({}, options), { passive: true });
  1782. }
  1783. return options;
  1784. }
  1785. var customScheduleGlobal = function (task) {
  1786. // if there is already a task for the eventName + capture,
  1787. // just return, because we use the shared globalZoneAwareCallback here.
  1788. if (taskData.isExisting) {
  1789. return;
  1790. }
  1791. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1792. };
  1793. var customCancelGlobal = function (task) {
  1794. // if task is not marked as isRemoved, this call is directly
  1795. // from Zone.prototype.cancelTask, we should remove the task
  1796. // from tasksList of target first
  1797. if (!task.isRemoved) {
  1798. var symbolEventNames = zoneSymbolEventNames[task.eventName];
  1799. var symbolEventName = void 0;
  1800. if (symbolEventNames) {
  1801. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1802. }
  1803. var existingTasks = symbolEventName && task.target[symbolEventName];
  1804. if (existingTasks) {
  1805. for (var i = 0; i < existingTasks.length; i++) {
  1806. var existingTask = existingTasks[i];
  1807. if (existingTask === task) {
  1808. existingTasks.splice(i, 1);
  1809. // set isRemoved to data for faster invokeTask check
  1810. task.isRemoved = true;
  1811. if (existingTasks.length === 0) {
  1812. // all tasks for the eventName + capture have gone,
  1813. // remove globalZoneAwareCallback and remove the task cache from target
  1814. task.allRemoved = true;
  1815. task.target[symbolEventName] = null;
  1816. }
  1817. break;
  1818. }
  1819. }
  1820. }
  1821. }
  1822. // if all tasks for the eventName + capture have gone,
  1823. // we will really remove the global event callback,
  1824. // if not, return
  1825. if (!task.allRemoved) {
  1826. return;
  1827. }
  1828. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1829. };
  1830. var customScheduleNonGlobal = function (task) {
  1831. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1832. };
  1833. var customSchedulePrepend = function (task) {
  1834. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1835. };
  1836. var customCancelNonGlobal = function (task) {
  1837. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1838. };
  1839. var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1840. var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1841. var compareTaskCallbackVsDelegate = function (task, delegate) {
  1842. var typeOfDelegate = typeof delegate;
  1843. return (typeOfDelegate === 'function' && task.callback === delegate) ||
  1844. (typeOfDelegate === 'object' && task.originalDelegate === delegate);
  1845. };
  1846. var compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
  1847. var unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1848. var passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1849. var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
  1850. if (returnTarget === void 0) { returnTarget = false; }
  1851. if (prepend === void 0) { prepend = false; }
  1852. return function () {
  1853. var target = this || _global;
  1854. var eventName = arguments[0];
  1855. if (patchOptions && patchOptions.transferEventName) {
  1856. eventName = patchOptions.transferEventName(eventName);
  1857. }
  1858. var delegate = arguments[1];
  1859. if (!delegate) {
  1860. return nativeListener.apply(this, arguments);
  1861. }
  1862. if (isNode && eventName === 'uncaughtException') {
  1863. // don't patch uncaughtException of nodejs to prevent endless loop
  1864. return nativeListener.apply(this, arguments);
  1865. }
  1866. // don't create the bind delegate function for handleEvent
  1867. // case here to improve addEventListener performance
  1868. // we will create the bind delegate when invoke
  1869. var isHandleEvent = false;
  1870. if (typeof delegate !== 'function') {
  1871. if (!delegate.handleEvent) {
  1872. return nativeListener.apply(this, arguments);
  1873. }
  1874. isHandleEvent = true;
  1875. }
  1876. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1877. return;
  1878. }
  1879. var passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1880. var options = buildEventListenerOptions(arguments[2], passive);
  1881. if (unpatchedEvents) {
  1882. // check unpatched list
  1883. for (var i = 0; i < unpatchedEvents.length; i++) {
  1884. if (eventName === unpatchedEvents[i]) {
  1885. if (passive) {
  1886. return nativeListener.call(target, eventName, delegate, options);
  1887. }
  1888. else {
  1889. return nativeListener.apply(this, arguments);
  1890. }
  1891. }
  1892. }
  1893. }
  1894. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1895. var once = options && typeof options === 'object' ? options.once : false;
  1896. var zone = Zone.current;
  1897. var symbolEventNames = zoneSymbolEventNames[eventName];
  1898. if (!symbolEventNames) {
  1899. prepareEventNames(eventName, eventNameToString);
  1900. symbolEventNames = zoneSymbolEventNames[eventName];
  1901. }
  1902. var symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1903. var existingTasks = target[symbolEventName];
  1904. var isExisting = false;
  1905. if (existingTasks) {
  1906. // already have task registered
  1907. isExisting = true;
  1908. if (checkDuplicate) {
  1909. for (var i = 0; i < existingTasks.length; i++) {
  1910. if (compare(existingTasks[i], delegate)) {
  1911. // same callback, same capture, same event name, just return
  1912. return;
  1913. }
  1914. }
  1915. }
  1916. }
  1917. else {
  1918. existingTasks = target[symbolEventName] = [];
  1919. }
  1920. var source;
  1921. var constructorName = target.constructor['name'];
  1922. var targetSource = globalSources[constructorName];
  1923. if (targetSource) {
  1924. source = targetSource[eventName];
  1925. }
  1926. if (!source) {
  1927. source = constructorName + addSource +
  1928. (eventNameToString ? eventNameToString(eventName) : eventName);
  1929. }
  1930. // do not create a new object as task.data to pass those things
  1931. // just use the global shared one
  1932. taskData.options = options;
  1933. if (once) {
  1934. // if addEventListener with once options, we don't pass it to
  1935. // native addEventListener, instead we keep the once setting
  1936. // and handle ourselves.
  1937. taskData.options.once = false;
  1938. }
  1939. taskData.target = target;
  1940. taskData.capture = capture;
  1941. taskData.eventName = eventName;
  1942. taskData.isExisting = isExisting;
  1943. var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1944. // keep taskData into data to allow onScheduleEventTask to access the task information
  1945. if (data) {
  1946. data.taskData = taskData;
  1947. }
  1948. var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1949. // should clear taskData.target to avoid memory leak
  1950. // issue, https://github.com/angular/angular/issues/20442
  1951. taskData.target = null;
  1952. // need to clear up taskData because it is a global object
  1953. if (data) {
  1954. data.taskData = null;
  1955. }
  1956. // have to save those information to task in case
  1957. // application may call task.zone.cancelTask() directly
  1958. if (once) {
  1959. options.once = true;
  1960. }
  1961. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  1962. // if not support passive, and we pass an option object
  1963. // to addEventListener, we should save the options to task
  1964. task.options = options;
  1965. }
  1966. task.target = target;
  1967. task.capture = capture;
  1968. task.eventName = eventName;
  1969. if (isHandleEvent) {
  1970. // save original delegate for compare to check duplicate
  1971. task.originalDelegate = delegate;
  1972. }
  1973. if (!prepend) {
  1974. existingTasks.push(task);
  1975. }
  1976. else {
  1977. existingTasks.unshift(task);
  1978. }
  1979. if (returnTarget) {
  1980. return target;
  1981. }
  1982. };
  1983. };
  1984. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  1985. if (nativePrependEventListener) {
  1986. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  1987. }
  1988. proto[REMOVE_EVENT_LISTENER] = function () {
  1989. var target = this || _global;
  1990. var eventName = arguments[0];
  1991. if (patchOptions && patchOptions.transferEventName) {
  1992. eventName = patchOptions.transferEventName(eventName);
  1993. }
  1994. var options = arguments[2];
  1995. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1996. var delegate = arguments[1];
  1997. if (!delegate) {
  1998. return nativeRemoveEventListener.apply(this, arguments);
  1999. }
  2000. if (validateHandler &&
  2001. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  2002. return;
  2003. }
  2004. var symbolEventNames = zoneSymbolEventNames[eventName];
  2005. var symbolEventName;
  2006. if (symbolEventNames) {
  2007. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  2008. }
  2009. var existingTasks = symbolEventName && target[symbolEventName];
  2010. if (existingTasks) {
  2011. for (var i = 0; i < existingTasks.length; i++) {
  2012. var existingTask = existingTasks[i];
  2013. if (compare(existingTask, delegate)) {
  2014. existingTasks.splice(i, 1);
  2015. // set isRemoved to data for faster invokeTask check
  2016. existingTask.isRemoved = true;
  2017. if (existingTasks.length === 0) {
  2018. // all tasks for the eventName + capture have gone,
  2019. // remove globalZoneAwareCallback and remove the task cache from target
  2020. existingTask.allRemoved = true;
  2021. target[symbolEventName] = null;
  2022. // in the target, we have an event listener which is added by on_property
  2023. // such as target.onclick = function() {}, so we need to clear this internal
  2024. // property too if all delegates all removed
  2025. if (typeof eventName === 'string') {
  2026. var onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  2027. target[onPropertySymbol] = null;
  2028. }
  2029. }
  2030. existingTask.zone.cancelTask(existingTask);
  2031. if (returnTarget) {
  2032. return target;
  2033. }
  2034. return;
  2035. }
  2036. }
  2037. }
  2038. // issue 930, didn't find the event name or callback
  2039. // from zone kept existingTasks, the callback maybe
  2040. // added outside of zone, we need to call native removeEventListener
  2041. // to try to remove it.
  2042. return nativeRemoveEventListener.apply(this, arguments);
  2043. };
  2044. proto[LISTENERS_EVENT_LISTENER] = function () {
  2045. var target = this || _global;
  2046. var eventName = arguments[0];
  2047. if (patchOptions && patchOptions.transferEventName) {
  2048. eventName = patchOptions.transferEventName(eventName);
  2049. }
  2050. var listeners = [];
  2051. var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  2052. for (var i = 0; i < tasks.length; i++) {
  2053. var task = tasks[i];
  2054. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2055. listeners.push(delegate);
  2056. }
  2057. return listeners;
  2058. };
  2059. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  2060. var target = this || _global;
  2061. var eventName = arguments[0];
  2062. if (!eventName) {
  2063. var keys = Object.keys(target);
  2064. for (var i = 0; i < keys.length; i++) {
  2065. var prop = keys[i];
  2066. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2067. var evtName = match && match[1];
  2068. // in nodejs EventEmitter, removeListener event is
  2069. // used for monitoring the removeListener call,
  2070. // so just keep removeListener eventListener until
  2071. // all other eventListeners are removed
  2072. if (evtName && evtName !== 'removeListener') {
  2073. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  2074. }
  2075. }
  2076. // remove removeListener listener finally
  2077. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  2078. }
  2079. else {
  2080. if (patchOptions && patchOptions.transferEventName) {
  2081. eventName = patchOptions.transferEventName(eventName);
  2082. }
  2083. var symbolEventNames = zoneSymbolEventNames[eventName];
  2084. if (symbolEventNames) {
  2085. var symbolEventName = symbolEventNames[FALSE_STR];
  2086. var symbolCaptureEventName = symbolEventNames[TRUE_STR];
  2087. var tasks = target[symbolEventName];
  2088. var captureTasks = target[symbolCaptureEventName];
  2089. if (tasks) {
  2090. var removeTasks = tasks.slice();
  2091. for (var i = 0; i < removeTasks.length; i++) {
  2092. var task = removeTasks[i];
  2093. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2094. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2095. }
  2096. }
  2097. if (captureTasks) {
  2098. var removeTasks = captureTasks.slice();
  2099. for (var i = 0; i < removeTasks.length; i++) {
  2100. var task = removeTasks[i];
  2101. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2102. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2103. }
  2104. }
  2105. }
  2106. }
  2107. if (returnTarget) {
  2108. return this;
  2109. }
  2110. };
  2111. // for native toString patch
  2112. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  2113. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  2114. if (nativeRemoveAllListeners) {
  2115. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  2116. }
  2117. if (nativeListeners) {
  2118. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  2119. }
  2120. return true;
  2121. }
  2122. var results = [];
  2123. for (var i = 0; i < apis.length; i++) {
  2124. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  2125. }
  2126. return results;
  2127. }
  2128. function findEventTasks(target, eventName) {
  2129. if (!eventName) {
  2130. var foundTasks = [];
  2131. for (var prop in target) {
  2132. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2133. var evtName = match && match[1];
  2134. if (evtName && (!eventName || evtName === eventName)) {
  2135. var tasks = target[prop];
  2136. if (tasks) {
  2137. for (var i = 0; i < tasks.length; i++) {
  2138. foundTasks.push(tasks[i]);
  2139. }
  2140. }
  2141. }
  2142. }
  2143. return foundTasks;
  2144. }
  2145. var symbolEventName = zoneSymbolEventNames[eventName];
  2146. if (!symbolEventName) {
  2147. prepareEventNames(eventName);
  2148. symbolEventName = zoneSymbolEventNames[eventName];
  2149. }
  2150. var captureFalseTasks = target[symbolEventName[FALSE_STR]];
  2151. var captureTrueTasks = target[symbolEventName[TRUE_STR]];
  2152. if (!captureFalseTasks) {
  2153. return captureTrueTasks ? captureTrueTasks.slice() : [];
  2154. }
  2155. else {
  2156. return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
  2157. captureFalseTasks.slice();
  2158. }
  2159. }
  2160. Zone.__load_patch('EventEmitter', function (global, Zone, api) {
  2161. // For EventEmitter
  2162. var EE_ADD_LISTENER = 'addListener';
  2163. var EE_PREPEND_LISTENER = 'prependListener';
  2164. var EE_REMOVE_LISTENER = 'removeListener';
  2165. var EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  2166. var EE_LISTENERS = 'listeners';
  2167. var EE_ON = 'on';
  2168. var EE_OFF = 'off';
  2169. var compareTaskCallbackVsDelegate = function (task, delegate) {
  2170. // same callback, same capture, same event name, just return
  2171. return task.callback === delegate || task.callback.listener === delegate;
  2172. };
  2173. var eventNameToString = function (eventName) {
  2174. if (typeof eventName === 'string') {
  2175. return eventName;
  2176. }
  2177. if (!eventName) {
  2178. return '';
  2179. }
  2180. return eventName.toString().replace('(', '_').replace(')', '_');
  2181. };
  2182. function patchEventEmitterMethods(obj) {
  2183. var result = patchEventTarget(global, api, [obj], {
  2184. useG: false,
  2185. add: EE_ADD_LISTENER,
  2186. rm: EE_REMOVE_LISTENER,
  2187. prepend: EE_PREPEND_LISTENER,
  2188. rmAll: EE_REMOVE_ALL_LISTENER,
  2189. listeners: EE_LISTENERS,
  2190. chkDup: false,
  2191. rt: true,
  2192. diff: compareTaskCallbackVsDelegate,
  2193. eventNameToString: eventNameToString
  2194. });
  2195. if (result && result[0]) {
  2196. obj[EE_ON] = obj[EE_ADD_LISTENER];
  2197. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  2198. }
  2199. }
  2200. // EventEmitter
  2201. var events;
  2202. try {
  2203. events = require('events');
  2204. }
  2205. catch (err) {
  2206. }
  2207. if (events && events.EventEmitter) {
  2208. patchEventEmitterMethods(events.EventEmitter.prototype);
  2209. }
  2210. });
  2211. Zone.__load_patch('fs', function () {
  2212. var fs;
  2213. try {
  2214. fs = require('fs');
  2215. }
  2216. catch (err) {
  2217. }
  2218. // watch, watchFile, unwatchFile has been patched
  2219. // because EventEmitter has been patched
  2220. var TO_PATCH_MACROTASK_METHODS = [
  2221. 'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
  2222. 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
  2223. 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
  2224. 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
  2225. 'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
  2226. ];
  2227. if (fs) {
  2228. TO_PATCH_MACROTASK_METHODS.filter(function (name) { return !!fs[name] && typeof fs[name] === 'function'; })
  2229. .forEach(function (name) {
  2230. patchMacroTask(fs, name, function (self, args) {
  2231. return {
  2232. name: 'fs.' + name,
  2233. args: args,
  2234. cbIdx: args.length > 0 ? args.length - 1 : -1,
  2235. target: self
  2236. };
  2237. });
  2238. });
  2239. }
  2240. });
  2241. /**
  2242. * @fileoverview
  2243. * @suppress {missingRequire}
  2244. */
  2245. function patchQueueMicrotask(global, api) {
  2246. api.patchMethod(global, 'queueMicrotask', function (delegate) {
  2247. return function (self, args) {
  2248. Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
  2249. };
  2250. });
  2251. }
  2252. /**
  2253. * @fileoverview
  2254. * @suppress {missingRequire}
  2255. */
  2256. var taskSymbol = zoneSymbol('zoneTask');
  2257. function patchTimer(window, setName, cancelName, nameSuffix) {
  2258. var setNative = null;
  2259. var clearNative = null;
  2260. setName += nameSuffix;
  2261. cancelName += nameSuffix;
  2262. var tasksByHandleId = {};
  2263. function scheduleTask(task) {
  2264. var data = task.data;
  2265. data.args[0] = function () {
  2266. return task.invoke.apply(this, arguments);
  2267. };
  2268. data.handleId = setNative.apply(window, data.args);
  2269. return task;
  2270. }
  2271. function clearTask(task) {
  2272. return clearNative.call(window, task.data.handleId);
  2273. }
  2274. setNative =
  2275. patchMethod(window, setName, function (delegate) { return function (self, args) {
  2276. if (typeof args[0] === 'function') {
  2277. var options_1 = {
  2278. isPeriodic: nameSuffix === 'Interval',
  2279. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  2280. undefined,
  2281. args: args
  2282. };
  2283. var callback_1 = args[0];
  2284. args[0] = function timer() {
  2285. try {
  2286. return callback_1.apply(this, arguments);
  2287. }
  2288. finally {
  2289. // issue-934, task will be cancelled
  2290. // even it is a periodic task such as
  2291. // setInterval
  2292. // https://github.com/angular/angular/issues/40387
  2293. // Cleanup tasksByHandleId should be handled before scheduleTask
  2294. // Since some zoneSpec may intercept and doesn't trigger
  2295. // scheduleFn(scheduleTask) provided here.
  2296. if (!(options_1.isPeriodic)) {
  2297. if (typeof options_1.handleId === 'number') {
  2298. // in non-nodejs env, we remove timerId
  2299. // from local cache
  2300. delete tasksByHandleId[options_1.handleId];
  2301. }
  2302. else if (options_1.handleId) {
  2303. // Node returns complex objects as handleIds
  2304. // we remove task reference from timer object
  2305. options_1.handleId[taskSymbol] = null;
  2306. }
  2307. }
  2308. }
  2309. };
  2310. var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options_1, scheduleTask, clearTask);
  2311. if (!task) {
  2312. return task;
  2313. }
  2314. // Node.js must additionally support the ref and unref functions.
  2315. var handle = task.data.handleId;
  2316. if (typeof handle === 'number') {
  2317. // for non nodejs env, we save handleId: task
  2318. // mapping in local cache for clearTimeout
  2319. tasksByHandleId[handle] = task;
  2320. }
  2321. else if (handle) {
  2322. // for nodejs env, we save task
  2323. // reference in timerId Object for clearTimeout
  2324. handle[taskSymbol] = task;
  2325. }
  2326. // check whether handle is null, because some polyfill or browser
  2327. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  2328. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  2329. typeof handle.unref === 'function') {
  2330. task.ref = handle.ref.bind(handle);
  2331. task.unref = handle.unref.bind(handle);
  2332. }
  2333. if (typeof handle === 'number' || handle) {
  2334. return handle;
  2335. }
  2336. return task;
  2337. }
  2338. else {
  2339. // cause an error by calling it directly.
  2340. return delegate.apply(window, args);
  2341. }
  2342. }; });
  2343. clearNative =
  2344. patchMethod(window, cancelName, function (delegate) { return function (self, args) {
  2345. var id = args[0];
  2346. var task;
  2347. if (typeof id === 'number') {
  2348. // non nodejs env.
  2349. task = tasksByHandleId[id];
  2350. }
  2351. else {
  2352. // nodejs env.
  2353. task = id && id[taskSymbol];
  2354. // other environments.
  2355. if (!task) {
  2356. task = id;
  2357. }
  2358. }
  2359. if (task && typeof task.type === 'string') {
  2360. if (task.state !== 'notScheduled' &&
  2361. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  2362. if (typeof id === 'number') {
  2363. delete tasksByHandleId[id];
  2364. }
  2365. else if (id) {
  2366. id[taskSymbol] = null;
  2367. }
  2368. // Do not cancel already canceled functions
  2369. task.zone.cancelTask(task);
  2370. }
  2371. }
  2372. else {
  2373. // cause an error by calling it directly.
  2374. delegate.apply(window, args);
  2375. }
  2376. }; });
  2377. }
  2378. var set = 'set';
  2379. var clear = 'clear';
  2380. Zone.__load_patch('node_timers', function (global, Zone) {
  2381. // Timers
  2382. var globalUseTimeoutFromTimer = false;
  2383. try {
  2384. var timers = require('timers');
  2385. var globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  2386. if (!globalEqualTimersTimeout && !isMix) {
  2387. // 1. if isMix, then we are in mix environment such as Electron
  2388. // we should only patch timers.setTimeout because global.setTimeout
  2389. // have been patched
  2390. // 2. if global.setTimeout not equal timers.setTimeout, check
  2391. // whether global.setTimeout use timers.setTimeout or not
  2392. var originSetTimeout_1 = timers.setTimeout;
  2393. timers.setTimeout = function () {
  2394. globalUseTimeoutFromTimer = true;
  2395. return originSetTimeout_1.apply(this, arguments);
  2396. };
  2397. var detectTimeout = global.setTimeout(function () { }, 100);
  2398. clearTimeout(detectTimeout);
  2399. timers.setTimeout = originSetTimeout_1;
  2400. }
  2401. patchTimer(timers, set, clear, 'Timeout');
  2402. patchTimer(timers, set, clear, 'Interval');
  2403. patchTimer(timers, set, clear, 'Immediate');
  2404. }
  2405. catch (error) {
  2406. // timers module not exists, for example, when we using nativeScript
  2407. // timers is not available
  2408. }
  2409. if (isMix) {
  2410. // if we are in mix environment, such as Electron,
  2411. // the global.setTimeout has already been patched,
  2412. // so we just patch timers.setTimeout
  2413. return;
  2414. }
  2415. if (!globalUseTimeoutFromTimer) {
  2416. // 1. global setTimeout equals timers setTimeout
  2417. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  2418. // 3. or load timers module error happens, we should patch global setTimeout
  2419. patchTimer(global, set, clear, 'Timeout');
  2420. patchTimer(global, set, clear, 'Interval');
  2421. patchTimer(global, set, clear, 'Immediate');
  2422. }
  2423. else {
  2424. // global use timers setTimeout, but not equals
  2425. // this happens when use nodejs v0.10.x, global setTimeout will
  2426. // use a lazy load version of timers setTimeout
  2427. // we should not double patch timer's setTimeout
  2428. // so we only store the __symbol__ for consistency
  2429. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  2430. global[Zone.__symbol__('setInterval')] = global.setInterval;
  2431. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  2432. }
  2433. });
  2434. // patch process related methods
  2435. Zone.__load_patch('nextTick', function () {
  2436. // patch nextTick as microTask
  2437. patchMicroTask(process, 'nextTick', function (self, args) {
  2438. return {
  2439. name: 'process.nextTick',
  2440. args: args,
  2441. cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
  2442. target: process
  2443. };
  2444. });
  2445. });
  2446. Zone.__load_patch('handleUnhandledPromiseRejection', function (global, Zone, api) {
  2447. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  2448. findProcessPromiseRejectionHandler('unhandledRejection');
  2449. Zone[api.symbol('rejectionHandledHandler')] =
  2450. findProcessPromiseRejectionHandler('rejectionHandled');
  2451. // handle unhandled promise rejection
  2452. function findProcessPromiseRejectionHandler(evtName) {
  2453. return function (e) {
  2454. var eventTasks = findEventTasks(process, evtName);
  2455. eventTasks.forEach(function (eventTask) {
  2456. // process has added unhandledrejection event listener
  2457. // trigger the event listener
  2458. if (evtName === 'unhandledRejection') {
  2459. eventTask.invoke(e.rejection, e.promise);
  2460. }
  2461. else if (evtName === 'rejectionHandled') {
  2462. eventTask.invoke(e.promise);
  2463. }
  2464. });
  2465. };
  2466. }
  2467. });
  2468. // Crypto
  2469. Zone.__load_patch('crypto', function () {
  2470. var crypto;
  2471. try {
  2472. crypto = require('crypto');
  2473. }
  2474. catch (err) {
  2475. }
  2476. // use the generic patchMacroTask to patch crypto
  2477. if (crypto) {
  2478. var methodNames = ['randomBytes', 'pbkdf2'];
  2479. methodNames.forEach(function (name) {
  2480. patchMacroTask(crypto, name, function (self, args) {
  2481. return {
  2482. name: 'crypto.' + name,
  2483. args: args,
  2484. cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
  2485. args.length - 1 :
  2486. -1,
  2487. target: crypto
  2488. };
  2489. });
  2490. });
  2491. }
  2492. });
  2493. Zone.__load_patch('console', function (global, Zone) {
  2494. var consoleMethods = ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
  2495. consoleMethods.forEach(function (m) {
  2496. var originalMethod = console[Zone.__symbol__(m)] = console[m];
  2497. if (originalMethod) {
  2498. console[m] = function () {
  2499. var args = ArraySlice.call(arguments);
  2500. if (Zone.current === Zone.root) {
  2501. return originalMethod.apply(this, args);
  2502. }
  2503. else {
  2504. return Zone.root.run(originalMethod, this, args);
  2505. }
  2506. };
  2507. }
  2508. });
  2509. });
  2510. Zone.__load_patch('queueMicrotask', function (global, Zone, api) {
  2511. patchQueueMicrotask(global, api);
  2512. });
  2513. }));