zone-node.umd.js 134 KB

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