zone-node.js 87 KB

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