zone-node.js 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  1. 'use strict';
  2. var __assign = (this && this.__assign) || function () {
  3. __assign = Object.assign || function(t) {
  4. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5. s = arguments[i];
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  7. t[p] = s[p];
  8. }
  9. return t;
  10. };
  11. return __assign.apply(this, arguments);
  12. };
  13. /**
  14. * @license Angular v<unknown>
  15. * (c) 2010-2022 Google LLC. https://angular.io/
  16. * License: MIT
  17. */
  18. (function (factory) {
  19. typeof define === 'function' && define.amd ? define(factory) :
  20. factory();
  21. })((function () {
  22. 'use strict';
  23. ((function (global) {
  24. var performance = global['performance'];
  25. function mark(name) {
  26. performance && performance['mark'] && performance['mark'](name);
  27. }
  28. function performanceMeasure(name, label) {
  29. performance && performance['measure'] && performance['measure'](name, label);
  30. }
  31. mark('Zone');
  32. // Initialize before it's accessed below.
  33. // __Zone_symbol_prefix global can be used to override the default zone
  34. // symbol prefix with a custom one if needed.
  35. var symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
  36. function __symbol__(name) {
  37. return symbolPrefix + name;
  38. }
  39. var checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  40. if (global['Zone']) {
  41. // if global['Zone'] already exists (maybe zone.js was already loaded or
  42. // some other lib also registered a global object named Zone), we may need
  43. // to throw an error, but sometimes user may not want this error.
  44. // For example,
  45. // we have two web pages, page1 includes zone.js, page2 doesn't.
  46. // and the 1st time user load page1 and page2, everything work fine,
  47. // but when user load page2 again, error occurs because global['Zone'] already exists.
  48. // so we add a flag to let user choose whether to throw this error or not.
  49. // By default, if existing Zone is from zone.js, we will not throw the error.
  50. if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
  51. throw new Error('Zone already loaded.');
  52. }
  53. else {
  54. return global['Zone'];
  55. }
  56. }
  57. var Zone = /** @class */ (function () {
  58. function Zone(parent, zoneSpec) {
  59. this._parent = parent;
  60. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  61. this._properties = zoneSpec && zoneSpec.properties || {};
  62. this._zoneDelegate =
  63. new _ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  64. }
  65. Zone.assertZonePatched = function () {
  66. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  67. throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  68. 'has been overwritten.\n' +
  69. 'Most likely cause is that a Promise polyfill has been loaded ' +
  70. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  71. 'If you must load one, do so before loading zone.js.)');
  72. }
  73. };
  74. Object.defineProperty(Zone, "root", {
  75. get: function () {
  76. var zone = Zone.current;
  77. while (zone.parent) {
  78. zone = zone.parent;
  79. }
  80. return zone;
  81. },
  82. enumerable: false,
  83. configurable: true
  84. });
  85. Object.defineProperty(Zone, "current", {
  86. get: function () {
  87. return _currentZoneFrame.zone;
  88. },
  89. enumerable: false,
  90. configurable: true
  91. });
  92. Object.defineProperty(Zone, "currentTask", {
  93. get: function () {
  94. return _currentTask;
  95. },
  96. enumerable: false,
  97. configurable: true
  98. });
  99. // tslint:disable-next-line:require-internal-with-underscore
  100. Zone.__load_patch = function (name, fn, ignoreDuplicate) {
  101. if (ignoreDuplicate === void 0) { ignoreDuplicate = false; }
  102. if (patches.hasOwnProperty(name)) {
  103. // `checkDuplicate` option is defined from global variable
  104. // so it works for all modules.
  105. // `ignoreDuplicate` can work for the specified module
  106. if (!ignoreDuplicate && checkDuplicate) {
  107. throw Error('Already loaded patch: ' + name);
  108. }
  109. }
  110. else if (!global['__Zone_disable_' + name]) {
  111. var perfName = 'Zone:' + name;
  112. mark(perfName);
  113. patches[name] = fn(global, Zone, _api);
  114. performanceMeasure(perfName, perfName);
  115. }
  116. };
  117. Object.defineProperty(Zone.prototype, "parent", {
  118. get: function () {
  119. return this._parent;
  120. },
  121. enumerable: false,
  122. configurable: true
  123. });
  124. Object.defineProperty(Zone.prototype, "name", {
  125. get: function () {
  126. return this._name;
  127. },
  128. enumerable: false,
  129. configurable: true
  130. });
  131. Zone.prototype.get = function (key) {
  132. var zone = this.getZoneWith(key);
  133. if (zone)
  134. return zone._properties[key];
  135. };
  136. Zone.prototype.getZoneWith = function (key) {
  137. var current = this;
  138. while (current) {
  139. if (current._properties.hasOwnProperty(key)) {
  140. return current;
  141. }
  142. current = current._parent;
  143. }
  144. return null;
  145. };
  146. Zone.prototype.fork = function (zoneSpec) {
  147. if (!zoneSpec)
  148. throw new Error('ZoneSpec required!');
  149. return this._zoneDelegate.fork(this, zoneSpec);
  150. };
  151. Zone.prototype.wrap = function (callback, source) {
  152. if (typeof callback !== 'function') {
  153. throw new Error('Expecting function got: ' + callback);
  154. }
  155. var _callback = this._zoneDelegate.intercept(this, callback, source);
  156. var zone = this;
  157. return function () {
  158. return zone.runGuarded(_callback, this, arguments, source);
  159. };
  160. };
  161. Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
  162. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  163. try {
  164. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  165. }
  166. finally {
  167. _currentZoneFrame = _currentZoneFrame.parent;
  168. }
  169. };
  170. Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
  171. if (applyThis === void 0) { applyThis = null; }
  172. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  173. try {
  174. try {
  175. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  176. }
  177. catch (error) {
  178. if (this._zoneDelegate.handleError(this, error)) {
  179. throw error;
  180. }
  181. }
  182. }
  183. finally {
  184. _currentZoneFrame = _currentZoneFrame.parent;
  185. }
  186. };
  187. Zone.prototype.runTask = function (task, applyThis, applyArgs) {
  188. if (task.zone != this) {
  189. throw new Error('A task can only be run in the zone of creation! (Creation: ' +
  190. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  191. }
  192. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  193. // will run in notScheduled(canceled) state, we should not try to
  194. // run such kind of task but just return
  195. if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
  196. return;
  197. }
  198. var reEntryGuard = task.state != running;
  199. reEntryGuard && task._transitionTo(running, scheduled);
  200. task.runCount++;
  201. var previousTask = _currentTask;
  202. _currentTask = task;
  203. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  204. try {
  205. if (task.type == macroTask && task.data && !task.data.isPeriodic) {
  206. task.cancelFn = undefined;
  207. }
  208. try {
  209. return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
  210. }
  211. catch (error) {
  212. if (this._zoneDelegate.handleError(this, error)) {
  213. throw error;
  214. }
  215. }
  216. }
  217. finally {
  218. // if the task's state is notScheduled or unknown, then it has already been cancelled
  219. // we should not reset the state to scheduled
  220. if (task.state !== notScheduled && task.state !== unknown) {
  221. if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
  222. reEntryGuard && task._transitionTo(scheduled, running);
  223. }
  224. else {
  225. task.runCount = 0;
  226. this._updateTaskCount(task, -1);
  227. reEntryGuard &&
  228. task._transitionTo(notScheduled, running, notScheduled);
  229. }
  230. }
  231. _currentZoneFrame = _currentZoneFrame.parent;
  232. _currentTask = previousTask;
  233. }
  234. };
  235. Zone.prototype.scheduleTask = function (task) {
  236. if (task.zone && task.zone !== this) {
  237. // check if the task was rescheduled, the newZone
  238. // should not be the children of the original zone
  239. var newZone = this;
  240. while (newZone) {
  241. if (newZone === task.zone) {
  242. throw Error("can not reschedule task to ".concat(this.name, " which is descendants of the original zone ").concat(task.zone.name));
  243. }
  244. newZone = newZone.parent;
  245. }
  246. }
  247. task._transitionTo(scheduling, notScheduled);
  248. var zoneDelegates = [];
  249. task._zoneDelegates = zoneDelegates;
  250. task._zone = this;
  251. try {
  252. task = this._zoneDelegate.scheduleTask(this, task);
  253. }
  254. catch (err) {
  255. // should set task's state to unknown when scheduleTask throw error
  256. // because the err may from reschedule, so the fromState maybe notScheduled
  257. task._transitionTo(unknown, scheduling, notScheduled);
  258. // TODO: @JiaLiPassion, should we check the result from handleError?
  259. this._zoneDelegate.handleError(this, err);
  260. throw err;
  261. }
  262. if (task._zoneDelegates === zoneDelegates) {
  263. // we have to check because internally the delegate can reschedule the task.
  264. this._updateTaskCount(task, 1);
  265. }
  266. if (task.state == scheduling) {
  267. task._transitionTo(scheduled, scheduling);
  268. }
  269. return task;
  270. };
  271. Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
  272. return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
  273. };
  274. Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
  275. return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  276. };
  277. Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
  278. return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  279. };
  280. Zone.prototype.cancelTask = function (task) {
  281. if (task.zone != this)
  282. throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
  283. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  284. if (task.state !== scheduled && task.state !== running) {
  285. return;
  286. }
  287. task._transitionTo(canceling, scheduled, running);
  288. try {
  289. this._zoneDelegate.cancelTask(this, task);
  290. }
  291. catch (err) {
  292. // if error occurs when cancelTask, transit the state to unknown
  293. task._transitionTo(unknown, canceling);
  294. this._zoneDelegate.handleError(this, err);
  295. throw err;
  296. }
  297. this._updateTaskCount(task, -1);
  298. task._transitionTo(notScheduled, canceling);
  299. task.runCount = 0;
  300. return task;
  301. };
  302. Zone.prototype._updateTaskCount = function (task, count) {
  303. var zoneDelegates = task._zoneDelegates;
  304. if (count == -1) {
  305. task._zoneDelegates = null;
  306. }
  307. for (var i = 0; i < zoneDelegates.length; i++) {
  308. zoneDelegates[i]._updateTaskCount(task.type, count);
  309. }
  310. };
  311. return Zone;
  312. }());
  313. // tslint:disable-next-line:require-internal-with-underscore
  314. Zone.__symbol__ = __symbol__;
  315. var DELEGATE_ZS = {
  316. name: '',
  317. onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
  318. onScheduleTask: function (delegate, _, target, task) { return delegate.scheduleTask(target, task); },
  319. onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
  320. onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
  321. };
  322. var _ZoneDelegate = /** @class */ (function () {
  323. function _ZoneDelegate(zone, parentDelegate, zoneSpec) {
  324. this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 };
  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 = zoneSpec &&
  351. (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 = 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. _ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
  397. return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
  398. new Zone(targetZone, zoneSpec);
  399. };
  400. _ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
  401. return this._interceptZS ?
  402. this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
  403. callback;
  404. };
  405. _ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
  406. return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
  407. callback.apply(applyThis, applyArgs);
  408. };
  409. _ZoneDelegate.prototype.handleError = function (targetZone, error) {
  410. return this._handleErrorZS ?
  411. this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
  412. true;
  413. };
  414. _ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
  415. var returnTask = task;
  416. if (this._scheduleTaskZS) {
  417. if (this._hasTaskZS) {
  418. returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
  419. }
  420. // clang-format off
  421. returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
  422. // clang-format on
  423. if (!returnTask)
  424. returnTask = task;
  425. }
  426. else {
  427. if (task.scheduleFn) {
  428. task.scheduleFn(task);
  429. }
  430. else if (task.type == microTask) {
  431. scheduleMicroTask(task);
  432. }
  433. else {
  434. throw new Error('Task is missing scheduleFn.');
  435. }
  436. }
  437. return returnTask;
  438. };
  439. _ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
  440. return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
  441. task.callback.apply(applyThis, applyArgs);
  442. };
  443. _ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
  444. var value;
  445. if (this._cancelTaskZS) {
  446. value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
  447. }
  448. else {
  449. if (!task.cancelFn) {
  450. throw Error('Task is not cancelable');
  451. }
  452. value = task.cancelFn(task);
  453. }
  454. return value;
  455. };
  456. _ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
  457. // hasTask should not throw error so other ZoneDelegate
  458. // can still trigger hasTask callback
  459. try {
  460. this._hasTaskZS &&
  461. this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
  462. }
  463. catch (err) {
  464. this.handleError(targetZone, err);
  465. }
  466. };
  467. // tslint:disable-next-line:require-internal-with-underscore
  468. _ZoneDelegate.prototype._updateTaskCount = function (type, count) {
  469. var counts = this._taskCounts;
  470. var prev = counts[type];
  471. var next = counts[type] = prev + count;
  472. if (next < 0) {
  473. throw new Error('More tasks executed then were scheduled.');
  474. }
  475. if (prev == 0 || next == 0) {
  476. var isEmpty = {
  477. microTask: counts['microTask'] > 0,
  478. macroTask: counts['macroTask'] > 0,
  479. eventTask: counts['eventTask'] > 0,
  480. change: type
  481. };
  482. this.hasTask(this.zone, isEmpty);
  483. }
  484. };
  485. return _ZoneDelegate;
  486. }());
  487. var ZoneTask = /** @class */ (function () {
  488. function ZoneTask(type, source, callback, options, scheduleFn, cancelFn) {
  489. // tslint:disable-next-line:require-internal-with-underscore
  490. this._zone = null;
  491. this.runCount = 0;
  492. // tslint:disable-next-line:require-internal-with-underscore
  493. this._zoneDelegates = null;
  494. // tslint:disable-next-line:require-internal-with-underscore
  495. this._state = 'notScheduled';
  496. this.type = type;
  497. this.source = source;
  498. this.data = options;
  499. this.scheduleFn = scheduleFn;
  500. this.cancelFn = cancelFn;
  501. if (!callback) {
  502. throw new Error('callback is not defined');
  503. }
  504. this.callback = callback;
  505. var self = this;
  506. // TODO: @JiaLiPassion options should have interface
  507. if (type === eventTask && options && options.useG) {
  508. this.invoke = ZoneTask.invokeTask;
  509. }
  510. else {
  511. this.invoke = function () {
  512. return ZoneTask.invokeTask.call(global, self, this, arguments);
  513. };
  514. }
  515. }
  516. ZoneTask.invokeTask = function (task, target, args) {
  517. if (!task) {
  518. task = this;
  519. }
  520. _numberOfNestedTaskFrames++;
  521. try {
  522. task.runCount++;
  523. return task.zone.runTask(task, target, args);
  524. }
  525. finally {
  526. if (_numberOfNestedTaskFrames == 1) {
  527. drainMicroTaskQueue();
  528. }
  529. _numberOfNestedTaskFrames--;
  530. }
  531. };
  532. Object.defineProperty(ZoneTask.prototype, "zone", {
  533. get: function () {
  534. return this._zone;
  535. },
  536. enumerable: false,
  537. configurable: true
  538. });
  539. Object.defineProperty(ZoneTask.prototype, "state", {
  540. get: function () {
  541. return this._state;
  542. },
  543. enumerable: false,
  544. configurable: true
  545. });
  546. ZoneTask.prototype.cancelScheduleRequest = function () {
  547. this._transitionTo(notScheduled, scheduling);
  548. };
  549. // tslint:disable-next-line:require-internal-with-underscore
  550. ZoneTask.prototype._transitionTo = function (toState, fromState1, fromState2) {
  551. if (this._state === fromState1 || this._state === fromState2) {
  552. this._state = toState;
  553. if (toState == notScheduled) {
  554. this._zoneDelegates = null;
  555. }
  556. }
  557. else {
  558. 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, "'."));
  559. }
  560. };
  561. ZoneTask.prototype.toString = function () {
  562. if (this.data && typeof this.data.handleId !== 'undefined') {
  563. return this.data.handleId.toString();
  564. }
  565. else {
  566. return Object.prototype.toString.call(this);
  567. }
  568. };
  569. // add toJSON method to prevent cyclic error when
  570. // call JSON.stringify(zoneTask)
  571. ZoneTask.prototype.toJSON = function () {
  572. return {
  573. type: this.type,
  574. state: this.state,
  575. source: this.source,
  576. zone: this.zone.name,
  577. runCount: this.runCount
  578. };
  579. };
  580. return ZoneTask;
  581. }());
  582. //////////////////////////////////////////////////////
  583. //////////////////////////////////////////////////////
  584. /// MICROTASK QUEUE
  585. //////////////////////////////////////////////////////
  586. //////////////////////////////////////////////////////
  587. var symbolSetTimeout = __symbol__('setTimeout');
  588. var symbolPromise = __symbol__('Promise');
  589. var symbolThen = __symbol__('then');
  590. var _microTaskQueue = [];
  591. var _isDrainingMicrotaskQueue = false;
  592. var nativeMicroTaskQueuePromise;
  593. function nativeScheduleMicroTask(func) {
  594. if (!nativeMicroTaskQueuePromise) {
  595. if (global[symbolPromise]) {
  596. nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
  597. }
  598. }
  599. if (nativeMicroTaskQueuePromise) {
  600. var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
  601. if (!nativeThen) {
  602. // native Promise is not patchable, we need to use `then` directly
  603. // issue 1078
  604. nativeThen = nativeMicroTaskQueuePromise['then'];
  605. }
  606. nativeThen.call(nativeMicroTaskQueuePromise, func);
  607. }
  608. else {
  609. global[symbolSetTimeout](func, 0);
  610. }
  611. }
  612. function scheduleMicroTask(task) {
  613. // if we are not running in any task, and there has not been anything scheduled
  614. // we must bootstrap the initial task creation by manually scheduling the drain
  615. if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
  616. // We are not running in Task, so we need to kickstart the microtask queue.
  617. nativeScheduleMicroTask(drainMicroTaskQueue);
  618. }
  619. task && _microTaskQueue.push(task);
  620. }
  621. function drainMicroTaskQueue() {
  622. if (!_isDrainingMicrotaskQueue) {
  623. _isDrainingMicrotaskQueue = true;
  624. while (_microTaskQueue.length) {
  625. var queue = _microTaskQueue;
  626. _microTaskQueue = [];
  627. for (var i = 0; i < queue.length; i++) {
  628. var task = queue[i];
  629. try {
  630. task.zone.runTask(task, null, null);
  631. }
  632. catch (error) {
  633. _api.onUnhandledError(error);
  634. }
  635. }
  636. }
  637. _api.microtaskDrainDone();
  638. _isDrainingMicrotaskQueue = false;
  639. }
  640. }
  641. //////////////////////////////////////////////////////
  642. //////////////////////////////////////////////////////
  643. /// BOOTSTRAP
  644. //////////////////////////////////////////////////////
  645. //////////////////////////////////////////////////////
  646. var NO_ZONE = { name: 'NO ZONE' };
  647. var notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
  648. var microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
  649. var patches = {};
  650. var _api = {
  651. symbol: __symbol__,
  652. currentZoneFrame: function () { return _currentZoneFrame; },
  653. onUnhandledError: noop,
  654. microtaskDrainDone: noop,
  655. scheduleMicroTask: scheduleMicroTask,
  656. showUncaughtError: function () { return !Zone[__symbol__('ignoreConsoleErrorUncaughtError')]; },
  657. patchEventTarget: function () { return []; },
  658. patchOnProperties: noop,
  659. patchMethod: function () { return noop; },
  660. bindArguments: function () { return []; },
  661. patchThen: function () { return noop; },
  662. patchMacroTask: function () { return noop; },
  663. patchEventPrototype: function () { return noop; },
  664. isIEOrEdge: function () { return false; },
  665. getGlobalObjects: function () { return undefined; },
  666. ObjectDefineProperty: function () { return noop; },
  667. ObjectGetOwnPropertyDescriptor: function () { return undefined; },
  668. ObjectCreate: function () { return undefined; },
  669. ArraySlice: function () { return []; },
  670. patchClass: function () { return noop; },
  671. wrapWithCurrentZone: function () { return noop; },
  672. filterProperties: function () { return []; },
  673. attachOriginToPatched: function () { return noop; },
  674. _redefineProperty: function () { return noop; },
  675. patchCallbacks: function () { return noop; },
  676. nativeScheduleMicroTask: nativeScheduleMicroTask
  677. };
  678. var _currentZoneFrame = { parent: null, zone: new Zone(null, null) };
  679. var _currentTask = null;
  680. var _numberOfNestedTaskFrames = 0;
  681. function noop() { }
  682. performanceMeasure('Zone', 'Zone');
  683. return global['Zone'] = Zone;
  684. }))(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
  685. /**
  686. * A different implementation for monkey patching Promise.
  687. * Currently Zone.js patches Promise itself with ZoneAwarePromise and also Promise.prototype.then
  688. * The reason is:
  689. *
  690. * 1. Promise.prototype.then should trigger ZoneSpec.scheduleTask and acts as a microTask
  691. * 2. Promise should be able to controlled by fakeAsync(), so Promise.prototype.then can work as
  692. * sync operation in fakeAsync()
  693. * 3. Promise unhandledRejection can be handled by ZoneSpec.onHandleError hook
  694. *
  695. * And this implementation also has it's disadvantage.
  696. *
  697. * 1. We need to implement a full Promise spec by ourselves.
  698. * 2. We need to implement the new APIs for Promise such as (all, allSettled, any...) when the new
  699. * APIs are available.
  700. * 3. Promise behavior is different with the native one, such as the timing of then callback.
  701. * 4. Can not handle the some vm operation requires native Promise such as async/await or
  702. * SafePromise.
  703. *
  704. * And this new implementation try to address most of these disadvantages.
  705. * 1. We don't monkey patch Promise itself any longer.
  706. * 2. We only monkey patches Promise.prototype.then and schedule microTask from there.
  707. * 3. The Promise APIs are all using native ones.
  708. * 4. SafePromise issues are gone, and the timing will be the same with the native one.
  709. *
  710. * Also this new implementation introduces breaking changes.
  711. *
  712. * 1. Promise can not be easily handled by fakeAsync(), and since we will deprecate fakeAsync() in
  713. * the future, this is the first step.
  714. * 2. Promise unhandled rejection happened inside new Promise(callback) will not be handled by
  715. * ZoneSpec.onHandleError(thenCallback error will not be be impacted).
  716. *
  717. * So now we only introduces this change to `zone-node` bundle, since the breaking change will be
  718. * minor for NodeJS environment,
  719. * @TODO: JiaLiPassion, we will introduce this change to browser later.
  720. */
  721. Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
  722. var __symbol__ = api.symbol;
  723. var symbolThen = __symbol__('then');
  724. api.onUnhandledError = function (e) {
  725. if (api.showUncaughtError()) {
  726. var rejection = e && e.rejection;
  727. if (rejection) {
  728. console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection === null || rejection === void 0 ? void 0 : rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
  729. }
  730. else {
  731. console.error(e);
  732. }
  733. }
  734. };
  735. api.microtaskDrainDone = function () { };
  736. var symbolThenPatched = __symbol__('thenPatched');
  737. function patchThen(Ctor) {
  738. var proto = Ctor.prototype;
  739. if (Ctor[symbolThenPatched] === true) {
  740. return;
  741. }
  742. var prop = Object.getOwnPropertyDescriptor(proto, 'then');
  743. if (prop && (prop.writable === false || !prop.configurable)) {
  744. // check Ctor.prototype.then propertyDescriptor is writable or not
  745. // in meteor env, writable is false, we should ignore such case
  746. return;
  747. }
  748. var originalThen = proto.then;
  749. // Keep a reference to the original method.
  750. proto[symbolThen] = originalThen;
  751. var makeResolver = function (resolveFunc, zone, source, isReject) {
  752. if (!resolveFunc) {
  753. return resolveFunc;
  754. }
  755. return function (val) {
  756. var task = zone.scheduleMicroTask(source, function () {
  757. return typeof resolveFunc === 'function' ? resolveFunc(val) :
  758. (isReject ? Promise.reject(val) : val);
  759. }, undefined, function () { });
  760. return zone.runGuarded(function () {
  761. return task.invoke();
  762. }, undefined, []);
  763. };
  764. };
  765. Ctor.prototype.then = function (onResolve, onReject) {
  766. var zone = Zone.current;
  767. return originalThen.call(this, makeResolver(onResolve, zone, 'Promise.prototype.then', false), makeResolver(onReject, zone, 'Promise.prototype.reject', true));
  768. };
  769. Ctor[symbolThenPatched] = true;
  770. }
  771. api.patchThen = patchThen;
  772. if (Promise) {
  773. patchThen(Promise);
  774. }
  775. global[api.symbol('Promise')] = Promise;
  776. return Promise;
  777. });
  778. /**
  779. * Suppress closure compiler errors about unknown 'Zone' variable
  780. * @fileoverview
  781. * @suppress {undefinedVars,globalThis,missingRequire}
  782. */
  783. /// <reference types="node"/>
  784. // issue #989, to reduce bundle size, use short name
  785. /** Object.getOwnPropertyDescriptor */
  786. var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  787. /** Object.defineProperty */
  788. var ObjectDefineProperty = Object.defineProperty;
  789. /** Object.getPrototypeOf */
  790. var ObjectGetPrototypeOf = Object.getPrototypeOf;
  791. /** Array.prototype.slice */
  792. var ArraySlice = Array.prototype.slice;
  793. /** addEventListener string const */
  794. var ADD_EVENT_LISTENER_STR = 'addEventListener';
  795. /** removeEventListener string const */
  796. var REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  797. /** zoneSymbol addEventListener */
  798. Zone.__symbol__(ADD_EVENT_LISTENER_STR);
  799. /** zoneSymbol removeEventListener */
  800. Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
  801. /** true string const */
  802. var TRUE_STR = 'true';
  803. /** false string const */
  804. var FALSE_STR = 'false';
  805. /** Zone symbol prefix string const. */
  806. var ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
  807. function wrapWithCurrentZone(callback, source) {
  808. return Zone.current.wrap(callback, source);
  809. }
  810. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  811. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  812. }
  813. var zoneSymbol = Zone.__symbol__;
  814. var isWindowExists = typeof window !== 'undefined';
  815. var internalWindow = isWindowExists ? window : undefined;
  816. var _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
  817. var REMOVE_ATTRIBUTE = 'removeAttribute';
  818. function bindArguments(args, source) {
  819. for (var i = args.length - 1; i >= 0; i--) {
  820. if (typeof args[i] === 'function') {
  821. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  822. }
  823. }
  824. return args;
  825. }
  826. function isPropertyWritable(propertyDesc) {
  827. if (!propertyDesc) {
  828. return true;
  829. }
  830. if (propertyDesc.writable === false) {
  831. return false;
  832. }
  833. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  834. }
  835. var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
  836. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  837. // this code.
  838. var isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
  839. {}.toString.call(_global.process) === '[object process]');
  840. var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  841. // we are in electron of nw, so we are both browser and nodejs
  842. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  843. // this code.
  844. var isMix = typeof _global.process !== 'undefined' &&
  845. {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
  846. !!(isWindowExists && internalWindow['HTMLElement']);
  847. var zoneSymbolEventNames$1 = {};
  848. var wrapFn = function (event) {
  849. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  850. // event will be undefined, so we need to use window.event
  851. event = event || _global.event;
  852. if (!event) {
  853. return;
  854. }
  855. var eventNameSymbol = zoneSymbolEventNames$1[event.type];
  856. if (!eventNameSymbol) {
  857. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  858. }
  859. var target = this || event.target || _global;
  860. var listener = target[eventNameSymbol];
  861. var result;
  862. if (isBrowser && target === internalWindow && event.type === 'error') {
  863. // window.onerror have different signature
  864. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  865. // and onerror callback will prevent default when callback return true
  866. var errorEvent = event;
  867. result = listener &&
  868. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  869. if (result === true) {
  870. event.preventDefault();
  871. }
  872. }
  873. else {
  874. result = listener && listener.apply(this, arguments);
  875. if (result != undefined && !result) {
  876. event.preventDefault();
  877. }
  878. }
  879. return result;
  880. };
  881. function patchProperty(obj, prop, prototype) {
  882. var desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  883. if (!desc && prototype) {
  884. // when patch window object, use prototype to check prop exist or not
  885. var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  886. if (prototypeDesc) {
  887. desc = { enumerable: true, configurable: true };
  888. }
  889. }
  890. // if the descriptor not exists or is not configurable
  891. // just return
  892. if (!desc || !desc.configurable) {
  893. return;
  894. }
  895. var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  896. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  897. return;
  898. }
  899. // A property descriptor cannot have getter/setter and be writable
  900. // deleting the writable and value properties avoids this error:
  901. //
  902. // TypeError: property descriptors must not specify a value or be writable when a
  903. // getter or setter has been specified
  904. delete desc.writable;
  905. delete desc.value;
  906. var originalDescGet = desc.get;
  907. var originalDescSet = desc.set;
  908. // slice(2) cuz 'onclick' -> 'click', etc
  909. var eventName = prop.slice(2);
  910. var eventNameSymbol = zoneSymbolEventNames$1[eventName];
  911. if (!eventNameSymbol) {
  912. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  913. }
  914. desc.set = function (newValue) {
  915. // in some of windows's onproperty callback, this is undefined
  916. // so we need to check it
  917. var target = this;
  918. if (!target && obj === _global) {
  919. target = _global;
  920. }
  921. if (!target) {
  922. return;
  923. }
  924. var previousValue = target[eventNameSymbol];
  925. if (typeof previousValue === 'function') {
  926. target.removeEventListener(eventName, wrapFn);
  927. }
  928. // issue #978, when onload handler was added before loading zone.js
  929. // we should remove it with originalDescSet
  930. originalDescSet && originalDescSet.call(target, null);
  931. target[eventNameSymbol] = newValue;
  932. if (typeof newValue === 'function') {
  933. target.addEventListener(eventName, wrapFn, false);
  934. }
  935. };
  936. // The getter would return undefined for unassigned properties but the default value of an
  937. // unassigned property is null
  938. desc.get = function () {
  939. // in some of windows's onproperty callback, this is undefined
  940. // so we need to check it
  941. var target = this;
  942. if (!target && obj === _global) {
  943. target = _global;
  944. }
  945. if (!target) {
  946. return null;
  947. }
  948. var listener = target[eventNameSymbol];
  949. if (listener) {
  950. return listener;
  951. }
  952. else if (originalDescGet) {
  953. // result will be null when use inline event attribute,
  954. // such as <button onclick="func();">OK</button>
  955. // because the onclick function is internal raw uncompiled handler
  956. // the onclick will be evaluated when first time event was triggered or
  957. // the property is accessed, https://github.com/angular/zone.js/issues/525
  958. // so we should use original native get to retrieve the handler
  959. var value = originalDescGet.call(this);
  960. if (value) {
  961. desc.set.call(this, value);
  962. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  963. target.removeAttribute(prop);
  964. }
  965. return value;
  966. }
  967. }
  968. return null;
  969. };
  970. ObjectDefineProperty(obj, prop, desc);
  971. obj[onPropPatchedSymbol] = true;
  972. }
  973. function patchOnProperties(obj, properties, prototype) {
  974. if (properties) {
  975. for (var i = 0; i < properties.length; i++) {
  976. patchProperty(obj, 'on' + properties[i], prototype);
  977. }
  978. }
  979. else {
  980. var onProperties = [];
  981. for (var prop in obj) {
  982. if (prop.slice(0, 2) == 'on') {
  983. onProperties.push(prop);
  984. }
  985. }
  986. for (var j = 0; j < onProperties.length; j++) {
  987. patchProperty(obj, onProperties[j], prototype);
  988. }
  989. }
  990. }
  991. zoneSymbol('originalInstance');
  992. function copySymbolProperties(src, dest) {
  993. if (typeof Object.getOwnPropertySymbols !== 'function') {
  994. return;
  995. }
  996. var symbols = Object.getOwnPropertySymbols(src);
  997. symbols.forEach(function (symbol) {
  998. var desc = Object.getOwnPropertyDescriptor(src, symbol);
  999. Object.defineProperty(dest, symbol, {
  1000. get: function () {
  1001. return src[symbol];
  1002. },
  1003. set: function (value) {
  1004. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  1005. // if src[symbol] is not writable or not have a setter, just return
  1006. return;
  1007. }
  1008. src[symbol] = value;
  1009. },
  1010. enumerable: desc ? desc.enumerable : true,
  1011. configurable: desc ? desc.configurable : true
  1012. });
  1013. });
  1014. }
  1015. var shouldCopySymbolProperties = false;
  1016. function setShouldCopySymbolProperties(flag) {
  1017. shouldCopySymbolProperties = flag;
  1018. }
  1019. function patchMethod(target, name, patchFn) {
  1020. var proto = target;
  1021. while (proto && !proto.hasOwnProperty(name)) {
  1022. proto = ObjectGetPrototypeOf(proto);
  1023. }
  1024. if (!proto && target[name]) {
  1025. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1026. proto = target;
  1027. }
  1028. var delegateName = zoneSymbol(name);
  1029. var delegate = null;
  1030. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  1031. delegate = proto[delegateName] = proto[name];
  1032. // check whether proto[name] is writable
  1033. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  1034. var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  1035. if (isPropertyWritable(desc)) {
  1036. var patchDelegate_1 = patchFn(delegate, delegateName, name);
  1037. proto[name] = function () {
  1038. return patchDelegate_1(this, arguments);
  1039. };
  1040. attachOriginToPatched(proto[name], delegate);
  1041. if (shouldCopySymbolProperties) {
  1042. copySymbolProperties(delegate, proto[name]);
  1043. }
  1044. }
  1045. }
  1046. return delegate;
  1047. }
  1048. // TODO: @JiaLiPassion, support cancel task later if necessary
  1049. function patchMacroTask(obj, funcName, metaCreator) {
  1050. var setNative = null;
  1051. function scheduleTask(task) {
  1052. var data = task.data;
  1053. data.args[data.cbIdx] = function () {
  1054. task.invoke.apply(this, arguments);
  1055. };
  1056. setNative.apply(data.target, data.args);
  1057. return task;
  1058. }
  1059. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1060. var meta = metaCreator(self, args);
  1061. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1062. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1063. }
  1064. else {
  1065. // cause an error by calling it directly.
  1066. return delegate.apply(self, args);
  1067. }
  1068. }; });
  1069. }
  1070. function patchMicroTask(obj, funcName, metaCreator) {
  1071. var setNative = null;
  1072. function scheduleTask(task) {
  1073. var data = task.data;
  1074. data.args[data.cbIdx] = function () {
  1075. task.invoke.apply(this, arguments);
  1076. };
  1077. setNative.apply(data.target, data.args);
  1078. return task;
  1079. }
  1080. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1081. var meta = metaCreator(self, args);
  1082. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1083. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1084. }
  1085. else {
  1086. // cause an error by calling it directly.
  1087. return delegate.apply(self, args);
  1088. }
  1089. }; });
  1090. }
  1091. function attachOriginToPatched(patched, original) {
  1092. patched[zoneSymbol('OriginalDelegate')] = original;
  1093. }
  1094. // override Function.prototype.toString to make zone.js patched function
  1095. // look like native function
  1096. Zone.__load_patch('toString', function (global) {
  1097. // patch Func.prototype.toString to let them look like native
  1098. var originalFunctionToString = Function.prototype.toString;
  1099. var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1100. var PROMISE_SYMBOL = zoneSymbol('Promise');
  1101. var ERROR_SYMBOL = zoneSymbol('Error');
  1102. var newFunctionToString = function toString() {
  1103. if (typeof this === 'function') {
  1104. var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1105. if (originalDelegate) {
  1106. if (typeof originalDelegate === 'function') {
  1107. return originalFunctionToString.call(originalDelegate);
  1108. }
  1109. else {
  1110. return Object.prototype.toString.call(originalDelegate);
  1111. }
  1112. }
  1113. if (this === Promise) {
  1114. var nativePromise = global[PROMISE_SYMBOL];
  1115. if (nativePromise) {
  1116. return originalFunctionToString.call(nativePromise);
  1117. }
  1118. }
  1119. if (this === Error) {
  1120. var nativeError = global[ERROR_SYMBOL];
  1121. if (nativeError) {
  1122. return originalFunctionToString.call(nativeError);
  1123. }
  1124. }
  1125. }
  1126. return originalFunctionToString.call(this);
  1127. };
  1128. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1129. Function.prototype.toString = newFunctionToString;
  1130. // patch Object.prototype.toString to let them look like native
  1131. var originalObjectToString = Object.prototype.toString;
  1132. var PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1133. Object.prototype.toString = function () {
  1134. if (typeof Promise === 'function' && this instanceof Promise) {
  1135. return PROMISE_OBJECT_TO_STRING;
  1136. }
  1137. return originalObjectToString.call(this);
  1138. };
  1139. });
  1140. Zone.__load_patch('node_util', function (global, Zone, api) {
  1141. api.patchOnProperties = patchOnProperties;
  1142. api.patchMethod = patchMethod;
  1143. api.bindArguments = bindArguments;
  1144. api.patchMacroTask = patchMacroTask;
  1145. setShouldCopySymbolProperties(true);
  1146. });
  1147. /**
  1148. * @fileoverview
  1149. * @suppress {missingRequire}
  1150. */
  1151. var passiveSupported = false;
  1152. if (typeof window !== 'undefined') {
  1153. try {
  1154. var options = Object.defineProperty({}, 'passive', {
  1155. get: function () {
  1156. passiveSupported = true;
  1157. }
  1158. });
  1159. // Note: We pass the `options` object as the event handler too. This is not compatible with the
  1160. // signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
  1161. // without an actual handler.
  1162. window.addEventListener('test', options, options);
  1163. window.removeEventListener('test', options, options);
  1164. }
  1165. catch (err) {
  1166. passiveSupported = false;
  1167. }
  1168. }
  1169. // an identifier to tell ZoneTask do not create a new invoke closure
  1170. var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1171. useG: true
  1172. };
  1173. var zoneSymbolEventNames = {};
  1174. var globalSources = {};
  1175. var EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1176. var IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1177. function prepareEventNames(eventName, eventNameToString) {
  1178. var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1179. var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1180. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1181. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1182. zoneSymbolEventNames[eventName] = {};
  1183. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1184. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1185. }
  1186. function patchEventTarget(_global, api, apis, patchOptions) {
  1187. var ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1188. var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1189. var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1190. var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1191. var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1192. var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1193. var PREPEND_EVENT_LISTENER = 'prependListener';
  1194. var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1195. var invokeTask = function (task, target, event) {
  1196. // for better performance, check isRemoved which is set
  1197. // by removeEventListener
  1198. if (task.isRemoved) {
  1199. return;
  1200. }
  1201. var delegate = task.callback;
  1202. if (typeof delegate === 'object' && delegate.handleEvent) {
  1203. // create the bind version of handleEvent when invoke
  1204. task.callback = function (event) { return delegate.handleEvent(event); };
  1205. task.originalDelegate = delegate;
  1206. }
  1207. // invoke static task.invoke
  1208. // need to try/catch error here, otherwise, the error in one event listener
  1209. // will break the executions of the other event listeners. Also error will
  1210. // not remove the event listener when `once` options is true.
  1211. var error;
  1212. try {
  1213. task.invoke(task, target, [event]);
  1214. }
  1215. catch (err) {
  1216. error = err;
  1217. }
  1218. var options = task.options;
  1219. if (options && typeof options === 'object' && options.once) {
  1220. // if options.once is true, after invoke once remove listener here
  1221. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1222. // inside EventEmitter.once
  1223. var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
  1224. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options);
  1225. }
  1226. return error;
  1227. };
  1228. function globalCallback(context, event, isCapture) {
  1229. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1230. // event will be undefined, so we need to use window.event
  1231. event = event || _global.event;
  1232. if (!event) {
  1233. return;
  1234. }
  1235. // event.target is needed for Samsung TV and SourceBuffer
  1236. // || global is needed https://github.com/angular/zone.js/issues/190
  1237. var target = context || event.target || _global;
  1238. var tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1239. if (tasks) {
  1240. var errors = [];
  1241. // invoke all tasks which attached to current target with given event.type and capture = false
  1242. // for performance concern, if task.length === 1, just invoke
  1243. if (tasks.length === 1) {
  1244. var err = invokeTask(tasks[0], target, event);
  1245. err && errors.push(err);
  1246. }
  1247. else {
  1248. // https://github.com/angular/zone.js/issues/836
  1249. // copy the tasks array before invoke, to avoid
  1250. // the callback will remove itself or other listener
  1251. var copyTasks = tasks.slice();
  1252. for (var i = 0; i < copyTasks.length; i++) {
  1253. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1254. break;
  1255. }
  1256. var err = invokeTask(copyTasks[i], target, event);
  1257. err && errors.push(err);
  1258. }
  1259. }
  1260. // Since there is only one error, we don't need to schedule microTask
  1261. // to throw the error.
  1262. if (errors.length === 1) {
  1263. throw errors[0];
  1264. }
  1265. else {
  1266. var _loop_1 = function (i) {
  1267. var err = errors[i];
  1268. api.nativeScheduleMicroTask(function () {
  1269. throw err;
  1270. });
  1271. };
  1272. for (var i = 0; i < errors.length; i++) {
  1273. _loop_1(i);
  1274. }
  1275. }
  1276. }
  1277. }
  1278. // global shared zoneAwareCallback to handle all event callback with capture = false
  1279. var globalZoneAwareCallback = function (event) {
  1280. return globalCallback(this, event, false);
  1281. };
  1282. // global shared zoneAwareCallback to handle all event callback with capture = true
  1283. var globalZoneAwareCaptureCallback = function (event) {
  1284. return globalCallback(this, event, true);
  1285. };
  1286. function patchEventTargetMethods(obj, patchOptions) {
  1287. if (!obj) {
  1288. return false;
  1289. }
  1290. var useGlobalCallback = true;
  1291. if (patchOptions && patchOptions.useG !== undefined) {
  1292. useGlobalCallback = patchOptions.useG;
  1293. }
  1294. var validateHandler = patchOptions && patchOptions.vh;
  1295. var checkDuplicate = true;
  1296. if (patchOptions && patchOptions.chkDup !== undefined) {
  1297. checkDuplicate = patchOptions.chkDup;
  1298. }
  1299. var returnTarget = false;
  1300. if (patchOptions && patchOptions.rt !== undefined) {
  1301. returnTarget = patchOptions.rt;
  1302. }
  1303. var proto = obj;
  1304. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1305. proto = ObjectGetPrototypeOf(proto);
  1306. }
  1307. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1308. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1309. proto = obj;
  1310. }
  1311. if (!proto) {
  1312. return false;
  1313. }
  1314. if (proto[zoneSymbolAddEventListener]) {
  1315. return false;
  1316. }
  1317. var eventNameToString = patchOptions && patchOptions.eventNameToString;
  1318. // a shared global taskData to pass data for scheduleEventTask
  1319. // so we do not need to create a new object just for pass some data
  1320. var taskData = {};
  1321. var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
  1322. var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1323. proto[REMOVE_EVENT_LISTENER];
  1324. var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1325. proto[LISTENERS_EVENT_LISTENER];
  1326. var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1327. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
  1328. var nativePrependEventListener;
  1329. if (patchOptions && patchOptions.prepend) {
  1330. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1331. proto[patchOptions.prepend];
  1332. }
  1333. /**
  1334. * This util function will build an option object with passive option
  1335. * to handle all possible input from the user.
  1336. */
  1337. function buildEventListenerOptions(options, passive) {
  1338. if (!passiveSupported && typeof options === 'object' && options) {
  1339. // doesn't support passive but user want to pass an object as options.
  1340. // this will not work on some old browser, so we just pass a boolean
  1341. // as useCapture parameter
  1342. return !!options.capture;
  1343. }
  1344. if (!passiveSupported || !passive) {
  1345. return options;
  1346. }
  1347. if (typeof options === 'boolean') {
  1348. return { capture: options, passive: true };
  1349. }
  1350. if (!options) {
  1351. return { passive: true };
  1352. }
  1353. if (typeof options === 'object' && options.passive !== false) {
  1354. return __assign(__assign({}, options), { passive: true });
  1355. }
  1356. return options;
  1357. }
  1358. var customScheduleGlobal = function (task) {
  1359. // if there is already a task for the eventName + capture,
  1360. // just return, because we use the shared globalZoneAwareCallback here.
  1361. if (taskData.isExisting) {
  1362. return;
  1363. }
  1364. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1365. };
  1366. var customCancelGlobal = function (task) {
  1367. // if task is not marked as isRemoved, this call is directly
  1368. // from Zone.prototype.cancelTask, we should remove the task
  1369. // from tasksList of target first
  1370. if (!task.isRemoved) {
  1371. var symbolEventNames = zoneSymbolEventNames[task.eventName];
  1372. var symbolEventName = void 0;
  1373. if (symbolEventNames) {
  1374. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1375. }
  1376. var existingTasks = symbolEventName && task.target[symbolEventName];
  1377. if (existingTasks) {
  1378. for (var i = 0; i < existingTasks.length; i++) {
  1379. var existingTask = existingTasks[i];
  1380. if (existingTask === task) {
  1381. existingTasks.splice(i, 1);
  1382. // set isRemoved to data for faster invokeTask check
  1383. task.isRemoved = true;
  1384. if (existingTasks.length === 0) {
  1385. // all tasks for the eventName + capture have gone,
  1386. // remove globalZoneAwareCallback and remove the task cache from target
  1387. task.allRemoved = true;
  1388. task.target[symbolEventName] = null;
  1389. }
  1390. break;
  1391. }
  1392. }
  1393. }
  1394. }
  1395. // if all tasks for the eventName + capture have gone,
  1396. // we will really remove the global event callback,
  1397. // if not, return
  1398. if (!task.allRemoved) {
  1399. return;
  1400. }
  1401. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1402. };
  1403. var customScheduleNonGlobal = function (task) {
  1404. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1405. };
  1406. var customSchedulePrepend = function (task) {
  1407. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1408. };
  1409. var customCancelNonGlobal = function (task) {
  1410. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1411. };
  1412. var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1413. var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1414. var compareTaskCallbackVsDelegate = function (task, delegate) {
  1415. var typeOfDelegate = typeof delegate;
  1416. return (typeOfDelegate === 'function' && task.callback === delegate) ||
  1417. (typeOfDelegate === 'object' && task.originalDelegate === delegate);
  1418. };
  1419. var compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
  1420. var unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1421. var passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1422. var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
  1423. if (returnTarget === void 0) { returnTarget = false; }
  1424. if (prepend === void 0) { prepend = false; }
  1425. return function () {
  1426. var target = this || _global;
  1427. var eventName = arguments[0];
  1428. if (patchOptions && patchOptions.transferEventName) {
  1429. eventName = patchOptions.transferEventName(eventName);
  1430. }
  1431. var delegate = arguments[1];
  1432. if (!delegate) {
  1433. return nativeListener.apply(this, arguments);
  1434. }
  1435. if (isNode && eventName === 'uncaughtException') {
  1436. // don't patch uncaughtException of nodejs to prevent endless loop
  1437. return nativeListener.apply(this, arguments);
  1438. }
  1439. // don't create the bind delegate function for handleEvent
  1440. // case here to improve addEventListener performance
  1441. // we will create the bind delegate when invoke
  1442. var isHandleEvent = false;
  1443. if (typeof delegate !== 'function') {
  1444. if (!delegate.handleEvent) {
  1445. return nativeListener.apply(this, arguments);
  1446. }
  1447. isHandleEvent = true;
  1448. }
  1449. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1450. return;
  1451. }
  1452. var passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1453. var options = buildEventListenerOptions(arguments[2], passive);
  1454. if (unpatchedEvents) {
  1455. // check unpatched list
  1456. for (var i = 0; i < unpatchedEvents.length; i++) {
  1457. if (eventName === unpatchedEvents[i]) {
  1458. if (passive) {
  1459. return nativeListener.call(target, eventName, delegate, options);
  1460. }
  1461. else {
  1462. return nativeListener.apply(this, arguments);
  1463. }
  1464. }
  1465. }
  1466. }
  1467. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1468. var once = options && typeof options === 'object' ? options.once : false;
  1469. var zone = Zone.current;
  1470. var symbolEventNames = zoneSymbolEventNames[eventName];
  1471. if (!symbolEventNames) {
  1472. prepareEventNames(eventName, eventNameToString);
  1473. symbolEventNames = zoneSymbolEventNames[eventName];
  1474. }
  1475. var symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1476. var existingTasks = target[symbolEventName];
  1477. var isExisting = false;
  1478. if (existingTasks) {
  1479. // already have task registered
  1480. isExisting = true;
  1481. if (checkDuplicate) {
  1482. for (var i = 0; i < existingTasks.length; i++) {
  1483. if (compare(existingTasks[i], delegate)) {
  1484. // same callback, same capture, same event name, just return
  1485. return;
  1486. }
  1487. }
  1488. }
  1489. }
  1490. else {
  1491. existingTasks = target[symbolEventName] = [];
  1492. }
  1493. var source;
  1494. var constructorName = target.constructor['name'];
  1495. var targetSource = globalSources[constructorName];
  1496. if (targetSource) {
  1497. source = targetSource[eventName];
  1498. }
  1499. if (!source) {
  1500. source = constructorName + addSource +
  1501. (eventNameToString ? eventNameToString(eventName) : eventName);
  1502. }
  1503. // do not create a new object as task.data to pass those things
  1504. // just use the global shared one
  1505. taskData.options = options;
  1506. if (once) {
  1507. // if addEventListener with once options, we don't pass it to
  1508. // native addEventListener, instead we keep the once setting
  1509. // and handle ourselves.
  1510. taskData.options.once = false;
  1511. }
  1512. taskData.target = target;
  1513. taskData.capture = capture;
  1514. taskData.eventName = eventName;
  1515. taskData.isExisting = isExisting;
  1516. var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1517. // keep taskData into data to allow onScheduleEventTask to access the task information
  1518. if (data) {
  1519. data.taskData = taskData;
  1520. }
  1521. var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1522. // should clear taskData.target to avoid memory leak
  1523. // issue, https://github.com/angular/angular/issues/20442
  1524. taskData.target = null;
  1525. // need to clear up taskData because it is a global object
  1526. if (data) {
  1527. data.taskData = null;
  1528. }
  1529. // have to save those information to task in case
  1530. // application may call task.zone.cancelTask() directly
  1531. if (once) {
  1532. options.once = true;
  1533. }
  1534. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  1535. // if not support passive, and we pass an option object
  1536. // to addEventListener, we should save the options to task
  1537. task.options = options;
  1538. }
  1539. task.target = target;
  1540. task.capture = capture;
  1541. task.eventName = eventName;
  1542. if (isHandleEvent) {
  1543. // save original delegate for compare to check duplicate
  1544. task.originalDelegate = delegate;
  1545. }
  1546. if (!prepend) {
  1547. existingTasks.push(task);
  1548. }
  1549. else {
  1550. existingTasks.unshift(task);
  1551. }
  1552. if (returnTarget) {
  1553. return target;
  1554. }
  1555. };
  1556. };
  1557. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  1558. if (nativePrependEventListener) {
  1559. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  1560. }
  1561. proto[REMOVE_EVENT_LISTENER] = function () {
  1562. var target = this || _global;
  1563. var eventName = arguments[0];
  1564. if (patchOptions && patchOptions.transferEventName) {
  1565. eventName = patchOptions.transferEventName(eventName);
  1566. }
  1567. var options = arguments[2];
  1568. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1569. var delegate = arguments[1];
  1570. if (!delegate) {
  1571. return nativeRemoveEventListener.apply(this, arguments);
  1572. }
  1573. if (validateHandler &&
  1574. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  1575. return;
  1576. }
  1577. var symbolEventNames = zoneSymbolEventNames[eventName];
  1578. var symbolEventName;
  1579. if (symbolEventNames) {
  1580. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1581. }
  1582. var existingTasks = symbolEventName && target[symbolEventName];
  1583. if (existingTasks) {
  1584. for (var i = 0; i < existingTasks.length; i++) {
  1585. var existingTask = existingTasks[i];
  1586. if (compare(existingTask, delegate)) {
  1587. existingTasks.splice(i, 1);
  1588. // set isRemoved to data for faster invokeTask check
  1589. existingTask.isRemoved = true;
  1590. if (existingTasks.length === 0) {
  1591. // all tasks for the eventName + capture have gone,
  1592. // remove globalZoneAwareCallback and remove the task cache from target
  1593. existingTask.allRemoved = true;
  1594. target[symbolEventName] = null;
  1595. // in the target, we have an event listener which is added by on_property
  1596. // such as target.onclick = function() {}, so we need to clear this internal
  1597. // property too if all delegates all removed
  1598. if (typeof eventName === 'string') {
  1599. var onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  1600. target[onPropertySymbol] = null;
  1601. }
  1602. }
  1603. existingTask.zone.cancelTask(existingTask);
  1604. if (returnTarget) {
  1605. return target;
  1606. }
  1607. return;
  1608. }
  1609. }
  1610. }
  1611. // issue 930, didn't find the event name or callback
  1612. // from zone kept existingTasks, the callback maybe
  1613. // added outside of zone, we need to call native removeEventListener
  1614. // to try to remove it.
  1615. return nativeRemoveEventListener.apply(this, arguments);
  1616. };
  1617. proto[LISTENERS_EVENT_LISTENER] = function () {
  1618. var target = this || _global;
  1619. var eventName = arguments[0];
  1620. if (patchOptions && patchOptions.transferEventName) {
  1621. eventName = patchOptions.transferEventName(eventName);
  1622. }
  1623. var listeners = [];
  1624. var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  1625. for (var i = 0; i < tasks.length; i++) {
  1626. var task = tasks[i];
  1627. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1628. listeners.push(delegate);
  1629. }
  1630. return listeners;
  1631. };
  1632. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  1633. var target = this || _global;
  1634. var eventName = arguments[0];
  1635. if (!eventName) {
  1636. var keys = Object.keys(target);
  1637. for (var i = 0; i < keys.length; i++) {
  1638. var prop = keys[i];
  1639. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  1640. var evtName = match && match[1];
  1641. // in nodejs EventEmitter, removeListener event is
  1642. // used for monitoring the removeListener call,
  1643. // so just keep removeListener eventListener until
  1644. // all other eventListeners are removed
  1645. if (evtName && evtName !== 'removeListener') {
  1646. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  1647. }
  1648. }
  1649. // remove removeListener listener finally
  1650. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  1651. }
  1652. else {
  1653. if (patchOptions && patchOptions.transferEventName) {
  1654. eventName = patchOptions.transferEventName(eventName);
  1655. }
  1656. var symbolEventNames = zoneSymbolEventNames[eventName];
  1657. if (symbolEventNames) {
  1658. var symbolEventName = symbolEventNames[FALSE_STR];
  1659. var symbolCaptureEventName = symbolEventNames[TRUE_STR];
  1660. var tasks = target[symbolEventName];
  1661. var captureTasks = target[symbolCaptureEventName];
  1662. if (tasks) {
  1663. var removeTasks = tasks.slice();
  1664. for (var i = 0; i < removeTasks.length; i++) {
  1665. var task = removeTasks[i];
  1666. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1667. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  1668. }
  1669. }
  1670. if (captureTasks) {
  1671. var removeTasks = captureTasks.slice();
  1672. for (var i = 0; i < removeTasks.length; i++) {
  1673. var task = removeTasks[i];
  1674. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1675. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  1676. }
  1677. }
  1678. }
  1679. }
  1680. if (returnTarget) {
  1681. return this;
  1682. }
  1683. };
  1684. // for native toString patch
  1685. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  1686. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  1687. if (nativeRemoveAllListeners) {
  1688. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  1689. }
  1690. if (nativeListeners) {
  1691. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  1692. }
  1693. return true;
  1694. }
  1695. var results = [];
  1696. for (var i = 0; i < apis.length; i++) {
  1697. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  1698. }
  1699. return results;
  1700. }
  1701. function findEventTasks(target, eventName) {
  1702. if (!eventName) {
  1703. var foundTasks = [];
  1704. for (var prop in target) {
  1705. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  1706. var evtName = match && match[1];
  1707. if (evtName && (!eventName || evtName === eventName)) {
  1708. var tasks = target[prop];
  1709. if (tasks) {
  1710. for (var i = 0; i < tasks.length; i++) {
  1711. foundTasks.push(tasks[i]);
  1712. }
  1713. }
  1714. }
  1715. }
  1716. return foundTasks;
  1717. }
  1718. var symbolEventName = zoneSymbolEventNames[eventName];
  1719. if (!symbolEventName) {
  1720. prepareEventNames(eventName);
  1721. symbolEventName = zoneSymbolEventNames[eventName];
  1722. }
  1723. var captureFalseTasks = target[symbolEventName[FALSE_STR]];
  1724. var captureTrueTasks = target[symbolEventName[TRUE_STR]];
  1725. if (!captureFalseTasks) {
  1726. return captureTrueTasks ? captureTrueTasks.slice() : [];
  1727. }
  1728. else {
  1729. return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
  1730. captureFalseTasks.slice();
  1731. }
  1732. }
  1733. Zone.__load_patch('EventEmitter', function (global, Zone, api) {
  1734. // For EventEmitter
  1735. var EE_ADD_LISTENER = 'addListener';
  1736. var EE_PREPEND_LISTENER = 'prependListener';
  1737. var EE_REMOVE_LISTENER = 'removeListener';
  1738. var EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  1739. var EE_LISTENERS = 'listeners';
  1740. var EE_ON = 'on';
  1741. var EE_OFF = 'off';
  1742. var compareTaskCallbackVsDelegate = function (task, delegate) {
  1743. // same callback, same capture, same event name, just return
  1744. return task.callback === delegate || task.callback.listener === delegate;
  1745. };
  1746. var eventNameToString = function (eventName) {
  1747. if (typeof eventName === 'string') {
  1748. return eventName;
  1749. }
  1750. if (!eventName) {
  1751. return '';
  1752. }
  1753. return eventName.toString().replace('(', '_').replace(')', '_');
  1754. };
  1755. function patchEventEmitterMethods(obj) {
  1756. var result = patchEventTarget(global, api, [obj], {
  1757. useG: false,
  1758. add: EE_ADD_LISTENER,
  1759. rm: EE_REMOVE_LISTENER,
  1760. prepend: EE_PREPEND_LISTENER,
  1761. rmAll: EE_REMOVE_ALL_LISTENER,
  1762. listeners: EE_LISTENERS,
  1763. chkDup: false,
  1764. rt: true,
  1765. diff: compareTaskCallbackVsDelegate,
  1766. eventNameToString: eventNameToString
  1767. });
  1768. if (result && result[0]) {
  1769. obj[EE_ON] = obj[EE_ADD_LISTENER];
  1770. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  1771. }
  1772. }
  1773. // EventEmitter
  1774. var events;
  1775. try {
  1776. events = require('events');
  1777. }
  1778. catch (err) {
  1779. }
  1780. if (events && events.EventEmitter) {
  1781. patchEventEmitterMethods(events.EventEmitter.prototype);
  1782. }
  1783. });
  1784. Zone.__load_patch('fs', function () {
  1785. var fs;
  1786. try {
  1787. fs = require('fs');
  1788. }
  1789. catch (err) {
  1790. }
  1791. // watch, watchFile, unwatchFile has been patched
  1792. // because EventEmitter has been patched
  1793. var TO_PATCH_MACROTASK_METHODS = [
  1794. 'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
  1795. 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
  1796. 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
  1797. 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
  1798. 'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
  1799. ];
  1800. if (fs) {
  1801. TO_PATCH_MACROTASK_METHODS.filter(function (name) { return !!fs[name] && typeof fs[name] === 'function'; })
  1802. .forEach(function (name) {
  1803. patchMacroTask(fs, name, function (self, args) {
  1804. return {
  1805. name: 'fs.' + name,
  1806. args: args,
  1807. cbIdx: args.length > 0 ? args.length - 1 : -1,
  1808. target: self
  1809. };
  1810. });
  1811. });
  1812. }
  1813. });
  1814. /**
  1815. * @fileoverview
  1816. * @suppress {missingRequire}
  1817. */
  1818. var taskSymbol = zoneSymbol('zoneTask');
  1819. function patchTimer(window, setName, cancelName, nameSuffix) {
  1820. var setNative = null;
  1821. var clearNative = null;
  1822. setName += nameSuffix;
  1823. cancelName += nameSuffix;
  1824. var tasksByHandleId = {};
  1825. function scheduleTask(task) {
  1826. var data = task.data;
  1827. data.args[0] = function () {
  1828. return task.invoke.apply(this, arguments);
  1829. };
  1830. data.handleId = setNative.apply(window, data.args);
  1831. return task;
  1832. }
  1833. function clearTask(task) {
  1834. return clearNative.call(window, task.data.handleId);
  1835. }
  1836. setNative =
  1837. patchMethod(window, setName, function (delegate) { return function (self, args) {
  1838. if (typeof args[0] === 'function') {
  1839. var options_1 = {
  1840. isPeriodic: nameSuffix === 'Interval',
  1841. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  1842. undefined,
  1843. args: args
  1844. };
  1845. var callback_1 = args[0];
  1846. args[0] = function timer() {
  1847. try {
  1848. return callback_1.apply(this, arguments);
  1849. }
  1850. finally {
  1851. // issue-934, task will be cancelled
  1852. // even it is a periodic task such as
  1853. // setInterval
  1854. // https://github.com/angular/angular/issues/40387
  1855. // Cleanup tasksByHandleId should be handled before scheduleTask
  1856. // Since some zoneSpec may intercept and doesn't trigger
  1857. // scheduleFn(scheduleTask) provided here.
  1858. if (!(options_1.isPeriodic)) {
  1859. if (typeof options_1.handleId === 'number') {
  1860. // in non-nodejs env, we remove timerId
  1861. // from local cache
  1862. delete tasksByHandleId[options_1.handleId];
  1863. }
  1864. else if (options_1.handleId) {
  1865. // Node returns complex objects as handleIds
  1866. // we remove task reference from timer object
  1867. options_1.handleId[taskSymbol] = null;
  1868. }
  1869. }
  1870. }
  1871. };
  1872. var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options_1, scheduleTask, clearTask);
  1873. if (!task) {
  1874. return task;
  1875. }
  1876. // Node.js must additionally support the ref and unref functions.
  1877. var handle = task.data.handleId;
  1878. if (typeof handle === 'number') {
  1879. // for non nodejs env, we save handleId: task
  1880. // mapping in local cache for clearTimeout
  1881. tasksByHandleId[handle] = task;
  1882. }
  1883. else if (handle) {
  1884. // for nodejs env, we save task
  1885. // reference in timerId Object for clearTimeout
  1886. handle[taskSymbol] = task;
  1887. }
  1888. // check whether handle is null, because some polyfill or browser
  1889. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  1890. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  1891. typeof handle.unref === 'function') {
  1892. task.ref = handle.ref.bind(handle);
  1893. task.unref = handle.unref.bind(handle);
  1894. }
  1895. if (typeof handle === 'number' || handle) {
  1896. return handle;
  1897. }
  1898. return task;
  1899. }
  1900. else {
  1901. // cause an error by calling it directly.
  1902. return delegate.apply(window, args);
  1903. }
  1904. }; });
  1905. clearNative =
  1906. patchMethod(window, cancelName, function (delegate) { return function (self, args) {
  1907. var id = args[0];
  1908. var task;
  1909. if (typeof id === 'number') {
  1910. // non nodejs env.
  1911. task = tasksByHandleId[id];
  1912. }
  1913. else {
  1914. // nodejs env.
  1915. task = id && id[taskSymbol];
  1916. // other environments.
  1917. if (!task) {
  1918. task = id;
  1919. }
  1920. }
  1921. if (task && typeof task.type === 'string') {
  1922. if (task.state !== 'notScheduled' &&
  1923. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  1924. if (typeof id === 'number') {
  1925. delete tasksByHandleId[id];
  1926. }
  1927. else if (id) {
  1928. id[taskSymbol] = null;
  1929. }
  1930. // Do not cancel already canceled functions
  1931. task.zone.cancelTask(task);
  1932. }
  1933. }
  1934. else {
  1935. // cause an error by calling it directly.
  1936. delegate.apply(window, args);
  1937. }
  1938. }; });
  1939. }
  1940. var set = 'set';
  1941. var clear = 'clear';
  1942. Zone.__load_patch('node_timers', function (global, Zone) {
  1943. // Timers
  1944. var globalUseTimeoutFromTimer = false;
  1945. try {
  1946. var timers = require('timers');
  1947. var globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  1948. if (!globalEqualTimersTimeout && !isMix) {
  1949. // 1. if isMix, then we are in mix environment such as Electron
  1950. // we should only patch timers.setTimeout because global.setTimeout
  1951. // have been patched
  1952. // 2. if global.setTimeout not equal timers.setTimeout, check
  1953. // whether global.setTimeout use timers.setTimeout or not
  1954. var originSetTimeout_1 = timers.setTimeout;
  1955. timers.setTimeout = function () {
  1956. globalUseTimeoutFromTimer = true;
  1957. return originSetTimeout_1.apply(this, arguments);
  1958. };
  1959. var detectTimeout = global.setTimeout(function () { }, 100);
  1960. clearTimeout(detectTimeout);
  1961. timers.setTimeout = originSetTimeout_1;
  1962. }
  1963. patchTimer(timers, set, clear, 'Timeout');
  1964. patchTimer(timers, set, clear, 'Interval');
  1965. patchTimer(timers, set, clear, 'Immediate');
  1966. }
  1967. catch (error) {
  1968. // timers module not exists, for example, when we using nativeScript
  1969. // timers is not available
  1970. }
  1971. if (isMix) {
  1972. // if we are in mix environment, such as Electron,
  1973. // the global.setTimeout has already been patched,
  1974. // so we just patch timers.setTimeout
  1975. return;
  1976. }
  1977. if (!globalUseTimeoutFromTimer) {
  1978. // 1. global setTimeout equals timers setTimeout
  1979. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  1980. // 3. or load timers module error happens, we should patch global setTimeout
  1981. patchTimer(global, set, clear, 'Timeout');
  1982. patchTimer(global, set, clear, 'Interval');
  1983. patchTimer(global, set, clear, 'Immediate');
  1984. }
  1985. else {
  1986. // global use timers setTimeout, but not equals
  1987. // this happens when use nodejs v0.10.x, global setTimeout will
  1988. // use a lazy load version of timers setTimeout
  1989. // we should not double patch timer's setTimeout
  1990. // so we only store the __symbol__ for consistency
  1991. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  1992. global[Zone.__symbol__('setInterval')] = global.setInterval;
  1993. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  1994. }
  1995. });
  1996. // patch process related methods
  1997. Zone.__load_patch('nextTick', function () {
  1998. // patch nextTick as microTask
  1999. patchMicroTask(process, 'nextTick', function (self, args) {
  2000. return {
  2001. name: 'process.nextTick',
  2002. args: args,
  2003. cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
  2004. target: process
  2005. };
  2006. });
  2007. });
  2008. Zone.__load_patch('handleUnhandledPromiseRejection', function (global, Zone, api) {
  2009. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  2010. findProcessPromiseRejectionHandler('unhandledRejection');
  2011. Zone[api.symbol('rejectionHandledHandler')] =
  2012. findProcessPromiseRejectionHandler('rejectionHandled');
  2013. // handle unhandled promise rejection
  2014. function findProcessPromiseRejectionHandler(evtName) {
  2015. return function (e) {
  2016. var eventTasks = findEventTasks(process, evtName);
  2017. eventTasks.forEach(function (eventTask) {
  2018. // process has added unhandledrejection event listener
  2019. // trigger the event listener
  2020. if (evtName === 'unhandledRejection') {
  2021. eventTask.invoke(e.rejection, e.promise);
  2022. }
  2023. else if (evtName === 'rejectionHandled') {
  2024. eventTask.invoke(e.promise);
  2025. }
  2026. });
  2027. };
  2028. }
  2029. });
  2030. // Crypto
  2031. Zone.__load_patch('crypto', function () {
  2032. var crypto;
  2033. try {
  2034. crypto = require('crypto');
  2035. }
  2036. catch (err) {
  2037. }
  2038. // use the generic patchMacroTask to patch crypto
  2039. if (crypto) {
  2040. var methodNames = ['randomBytes', 'pbkdf2'];
  2041. methodNames.forEach(function (name) {
  2042. patchMacroTask(crypto, name, function (self, args) {
  2043. return {
  2044. name: 'crypto.' + name,
  2045. args: args,
  2046. cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
  2047. args.length - 1 :
  2048. -1,
  2049. target: crypto
  2050. };
  2051. });
  2052. });
  2053. }
  2054. });
  2055. Zone.__load_patch('console', function (global, Zone) {
  2056. var consoleMethods = ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
  2057. consoleMethods.forEach(function (m) {
  2058. var originalMethod = console[Zone.__symbol__(m)] = console[m];
  2059. if (originalMethod) {
  2060. console[m] = function () {
  2061. var args = ArraySlice.call(arguments);
  2062. if (Zone.current === Zone.root) {
  2063. return originalMethod.apply(this, args);
  2064. }
  2065. else {
  2066. return Zone.root.run(originalMethod, this, args);
  2067. }
  2068. };
  2069. }
  2070. });
  2071. });
  2072. }));