zone-node.js 105 KB

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