zone-mix.js 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019
  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. /** Object.create */
  650. const ObjectCreate = Object.create;
  651. /** Array.prototype.slice */
  652. const ArraySlice = Array.prototype.slice;
  653. /** addEventListener string const */
  654. const ADD_EVENT_LISTENER_STR = 'addEventListener';
  655. /** removeEventListener string const */
  656. const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  657. /** zoneSymbol addEventListener */
  658. const ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
  659. /** zoneSymbol removeEventListener */
  660. const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
  661. /** true string const */
  662. const TRUE_STR = 'true';
  663. /** false string const */
  664. const FALSE_STR = 'false';
  665. /** Zone symbol prefix string const. */
  666. const ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
  667. function wrapWithCurrentZone(callback, source) {
  668. return Zone.current.wrap(callback, source);
  669. }
  670. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  671. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  672. }
  673. const zoneSymbol = Zone.__symbol__;
  674. const isWindowExists = typeof window !== 'undefined';
  675. const internalWindow = isWindowExists ? window : undefined;
  676. const _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
  677. const REMOVE_ATTRIBUTE = 'removeAttribute';
  678. function bindArguments(args, source) {
  679. for (let i = args.length - 1; i >= 0; i--) {
  680. if (typeof args[i] === 'function') {
  681. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  682. }
  683. }
  684. return args;
  685. }
  686. function patchPrototype(prototype, fnNames) {
  687. const source = prototype.constructor['name'];
  688. for (let i = 0; i < fnNames.length; i++) {
  689. const name = fnNames[i];
  690. const delegate = prototype[name];
  691. if (delegate) {
  692. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name);
  693. if (!isPropertyWritable(prototypeDesc)) {
  694. continue;
  695. }
  696. prototype[name] = ((delegate) => {
  697. const patched = function () {
  698. return delegate.apply(this, bindArguments(arguments, source + '.' + name));
  699. };
  700. attachOriginToPatched(patched, delegate);
  701. return patched;
  702. })(delegate);
  703. }
  704. }
  705. }
  706. function isPropertyWritable(propertyDesc) {
  707. if (!propertyDesc) {
  708. return true;
  709. }
  710. if (propertyDesc.writable === false) {
  711. return false;
  712. }
  713. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  714. }
  715. const isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
  716. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  717. // this code.
  718. const isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
  719. {}.toString.call(_global.process) === '[object process]');
  720. const isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  721. // we are in electron of nw, so we are both browser and nodejs
  722. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  723. // this code.
  724. const isMix = typeof _global.process !== 'undefined' &&
  725. {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
  726. !!(isWindowExists && internalWindow['HTMLElement']);
  727. const zoneSymbolEventNames$1 = {};
  728. const wrapFn = function (event) {
  729. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  730. // event will be undefined, so we need to use window.event
  731. event = event || _global.event;
  732. if (!event) {
  733. return;
  734. }
  735. let eventNameSymbol = zoneSymbolEventNames$1[event.type];
  736. if (!eventNameSymbol) {
  737. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  738. }
  739. const target = this || event.target || _global;
  740. const listener = target[eventNameSymbol];
  741. let result;
  742. if (isBrowser && target === internalWindow && event.type === 'error') {
  743. // window.onerror have different signature
  744. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  745. // and onerror callback will prevent default when callback return true
  746. const errorEvent = event;
  747. result = listener &&
  748. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  749. if (result === true) {
  750. event.preventDefault();
  751. }
  752. }
  753. else {
  754. result = listener && listener.apply(this, arguments);
  755. if (result != undefined && !result) {
  756. event.preventDefault();
  757. }
  758. }
  759. return result;
  760. };
  761. function patchProperty(obj, prop, prototype) {
  762. let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  763. if (!desc && prototype) {
  764. // when patch window object, use prototype to check prop exist or not
  765. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  766. if (prototypeDesc) {
  767. desc = { enumerable: true, configurable: true };
  768. }
  769. }
  770. // if the descriptor not exists or is not configurable
  771. // just return
  772. if (!desc || !desc.configurable) {
  773. return;
  774. }
  775. const onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  776. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  777. return;
  778. }
  779. // A property descriptor cannot have getter/setter and be writable
  780. // deleting the writable and value properties avoids this error:
  781. //
  782. // TypeError: property descriptors must not specify a value or be writable when a
  783. // getter or setter has been specified
  784. delete desc.writable;
  785. delete desc.value;
  786. const originalDescGet = desc.get;
  787. const originalDescSet = desc.set;
  788. // slice(2) cuz 'onclick' -> 'click', etc
  789. const eventName = prop.slice(2);
  790. let eventNameSymbol = zoneSymbolEventNames$1[eventName];
  791. if (!eventNameSymbol) {
  792. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  793. }
  794. desc.set = function (newValue) {
  795. // in some of windows's onproperty callback, this is undefined
  796. // so we need to check it
  797. let target = this;
  798. if (!target && obj === _global) {
  799. target = _global;
  800. }
  801. if (!target) {
  802. return;
  803. }
  804. const previousValue = target[eventNameSymbol];
  805. if (typeof previousValue === 'function') {
  806. target.removeEventListener(eventName, wrapFn);
  807. }
  808. // issue #978, when onload handler was added before loading zone.js
  809. // we should remove it with originalDescSet
  810. originalDescSet && originalDescSet.call(target, null);
  811. target[eventNameSymbol] = newValue;
  812. if (typeof newValue === 'function') {
  813. target.addEventListener(eventName, wrapFn, false);
  814. }
  815. };
  816. // The getter would return undefined for unassigned properties but the default value of an
  817. // unassigned property is null
  818. desc.get = function () {
  819. // in some of windows's onproperty callback, this is undefined
  820. // so we need to check it
  821. let target = this;
  822. if (!target && obj === _global) {
  823. target = _global;
  824. }
  825. if (!target) {
  826. return null;
  827. }
  828. const listener = target[eventNameSymbol];
  829. if (listener) {
  830. return listener;
  831. }
  832. else if (originalDescGet) {
  833. // result will be null when use inline event attribute,
  834. // such as <button onclick="func();">OK</button>
  835. // because the onclick function is internal raw uncompiled handler
  836. // the onclick will be evaluated when first time event was triggered or
  837. // the property is accessed, https://github.com/angular/zone.js/issues/525
  838. // so we should use original native get to retrieve the handler
  839. let value = originalDescGet.call(this);
  840. if (value) {
  841. desc.set.call(this, value);
  842. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  843. target.removeAttribute(prop);
  844. }
  845. return value;
  846. }
  847. }
  848. return null;
  849. };
  850. ObjectDefineProperty(obj, prop, desc);
  851. obj[onPropPatchedSymbol] = true;
  852. }
  853. function patchOnProperties(obj, properties, prototype) {
  854. if (properties) {
  855. for (let i = 0; i < properties.length; i++) {
  856. patchProperty(obj, 'on' + properties[i], prototype);
  857. }
  858. }
  859. else {
  860. const onProperties = [];
  861. for (const prop in obj) {
  862. if (prop.slice(0, 2) == 'on') {
  863. onProperties.push(prop);
  864. }
  865. }
  866. for (let j = 0; j < onProperties.length; j++) {
  867. patchProperty(obj, onProperties[j], prototype);
  868. }
  869. }
  870. }
  871. const originalInstanceKey = zoneSymbol('originalInstance');
  872. // wrap some native API on `window`
  873. function patchClass(className) {
  874. const OriginalClass = _global[className];
  875. if (!OriginalClass)
  876. return;
  877. // keep original class in global
  878. _global[zoneSymbol(className)] = OriginalClass;
  879. _global[className] = function () {
  880. const a = bindArguments(arguments, className);
  881. switch (a.length) {
  882. case 0:
  883. this[originalInstanceKey] = new OriginalClass();
  884. break;
  885. case 1:
  886. this[originalInstanceKey] = new OriginalClass(a[0]);
  887. break;
  888. case 2:
  889. this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
  890. break;
  891. case 3:
  892. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
  893. break;
  894. case 4:
  895. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
  896. break;
  897. default:
  898. throw new Error('Arg list too long.');
  899. }
  900. };
  901. // attach original delegate to patched function
  902. attachOriginToPatched(_global[className], OriginalClass);
  903. const instance = new OriginalClass(function () { });
  904. let prop;
  905. for (prop in instance) {
  906. // https://bugs.webkit.org/show_bug.cgi?id=44721
  907. if (className === 'XMLHttpRequest' && prop === 'responseBlob')
  908. continue;
  909. (function (prop) {
  910. if (typeof instance[prop] === 'function') {
  911. _global[className].prototype[prop] = function () {
  912. return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
  913. };
  914. }
  915. else {
  916. ObjectDefineProperty(_global[className].prototype, prop, {
  917. set: function (fn) {
  918. if (typeof fn === 'function') {
  919. this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
  920. // keep callback in wrapped function so we can
  921. // use it in Function.prototype.toString to return
  922. // the native one.
  923. attachOriginToPatched(this[originalInstanceKey][prop], fn);
  924. }
  925. else {
  926. this[originalInstanceKey][prop] = fn;
  927. }
  928. },
  929. get: function () {
  930. return this[originalInstanceKey][prop];
  931. }
  932. });
  933. }
  934. }(prop));
  935. }
  936. for (prop in OriginalClass) {
  937. if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
  938. _global[className][prop] = OriginalClass[prop];
  939. }
  940. }
  941. }
  942. function copySymbolProperties(src, dest) {
  943. if (typeof Object.getOwnPropertySymbols !== 'function') {
  944. return;
  945. }
  946. const symbols = Object.getOwnPropertySymbols(src);
  947. symbols.forEach((symbol) => {
  948. const desc = Object.getOwnPropertyDescriptor(src, symbol);
  949. Object.defineProperty(dest, symbol, {
  950. get: function () {
  951. return src[symbol];
  952. },
  953. set: function (value) {
  954. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  955. // if src[symbol] is not writable or not have a setter, just return
  956. return;
  957. }
  958. src[symbol] = value;
  959. },
  960. enumerable: desc ? desc.enumerable : true,
  961. configurable: desc ? desc.configurable : true
  962. });
  963. });
  964. }
  965. let shouldCopySymbolProperties = false;
  966. function setShouldCopySymbolProperties(flag) {
  967. shouldCopySymbolProperties = flag;
  968. }
  969. function patchMethod(target, name, patchFn) {
  970. let proto = target;
  971. while (proto && !proto.hasOwnProperty(name)) {
  972. proto = ObjectGetPrototypeOf(proto);
  973. }
  974. if (!proto && target[name]) {
  975. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  976. proto = target;
  977. }
  978. const delegateName = zoneSymbol(name);
  979. let delegate = null;
  980. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  981. delegate = proto[delegateName] = proto[name];
  982. // check whether proto[name] is writable
  983. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  984. const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  985. if (isPropertyWritable(desc)) {
  986. const patchDelegate = patchFn(delegate, delegateName, name);
  987. proto[name] = function () {
  988. return patchDelegate(this, arguments);
  989. };
  990. attachOriginToPatched(proto[name], delegate);
  991. if (shouldCopySymbolProperties) {
  992. copySymbolProperties(delegate, proto[name]);
  993. }
  994. }
  995. }
  996. return delegate;
  997. }
  998. // TODO: @JiaLiPassion, support cancel task later if necessary
  999. function patchMacroTask(obj, funcName, metaCreator) {
  1000. let setNative = null;
  1001. function scheduleTask(task) {
  1002. const data = task.data;
  1003. data.args[data.cbIdx] = function () {
  1004. task.invoke.apply(this, arguments);
  1005. };
  1006. setNative.apply(data.target, data.args);
  1007. return task;
  1008. }
  1009. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1010. const meta = metaCreator(self, args);
  1011. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1012. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1013. }
  1014. else {
  1015. // cause an error by calling it directly.
  1016. return delegate.apply(self, args);
  1017. }
  1018. });
  1019. }
  1020. function patchMicroTask(obj, funcName, metaCreator) {
  1021. let setNative = null;
  1022. function scheduleTask(task) {
  1023. const data = task.data;
  1024. data.args[data.cbIdx] = function () {
  1025. task.invoke.apply(this, arguments);
  1026. };
  1027. setNative.apply(data.target, data.args);
  1028. return task;
  1029. }
  1030. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1031. const meta = metaCreator(self, args);
  1032. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1033. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1034. }
  1035. else {
  1036. // cause an error by calling it directly.
  1037. return delegate.apply(self, args);
  1038. }
  1039. });
  1040. }
  1041. function attachOriginToPatched(patched, original) {
  1042. patched[zoneSymbol('OriginalDelegate')] = original;
  1043. }
  1044. let isDetectedIEOrEdge = false;
  1045. let ieOrEdge = false;
  1046. function isIE() {
  1047. try {
  1048. const ua = internalWindow.navigator.userAgent;
  1049. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
  1050. return true;
  1051. }
  1052. }
  1053. catch (error) {
  1054. }
  1055. return false;
  1056. }
  1057. function isIEOrEdge() {
  1058. if (isDetectedIEOrEdge) {
  1059. return ieOrEdge;
  1060. }
  1061. isDetectedIEOrEdge = true;
  1062. try {
  1063. const ua = internalWindow.navigator.userAgent;
  1064. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
  1065. ieOrEdge = true;
  1066. }
  1067. }
  1068. catch (error) {
  1069. }
  1070. return ieOrEdge;
  1071. }
  1072. Zone.__load_patch('ZoneAwarePromise', (global, Zone, api) => {
  1073. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1074. const ObjectDefineProperty = Object.defineProperty;
  1075. function readableObjectToString(obj) {
  1076. if (obj && obj.toString === Object.prototype.toString) {
  1077. const className = obj.constructor && obj.constructor.name;
  1078. return (className ? className : '') + ': ' + JSON.stringify(obj);
  1079. }
  1080. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  1081. }
  1082. const __symbol__ = api.symbol;
  1083. const _uncaughtPromiseErrors = [];
  1084. const isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] === true;
  1085. const symbolPromise = __symbol__('Promise');
  1086. const symbolThen = __symbol__('then');
  1087. const creationTrace = '__creationTrace__';
  1088. api.onUnhandledError = (e) => {
  1089. if (api.showUncaughtError()) {
  1090. const rejection = e && e.rejection;
  1091. if (rejection) {
  1092. 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);
  1093. }
  1094. else {
  1095. console.error(e);
  1096. }
  1097. }
  1098. };
  1099. api.microtaskDrainDone = () => {
  1100. while (_uncaughtPromiseErrors.length) {
  1101. const uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  1102. try {
  1103. uncaughtPromiseError.zone.runGuarded(() => {
  1104. if (uncaughtPromiseError.throwOriginal) {
  1105. throw uncaughtPromiseError.rejection;
  1106. }
  1107. throw uncaughtPromiseError;
  1108. });
  1109. }
  1110. catch (error) {
  1111. handleUnhandledRejection(error);
  1112. }
  1113. }
  1114. };
  1115. const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  1116. function handleUnhandledRejection(e) {
  1117. api.onUnhandledError(e);
  1118. try {
  1119. const handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  1120. if (typeof handler === 'function') {
  1121. handler.call(this, e);
  1122. }
  1123. }
  1124. catch (err) {
  1125. }
  1126. }
  1127. function isThenable(value) {
  1128. return value && value.then;
  1129. }
  1130. function forwardResolution(value) {
  1131. return value;
  1132. }
  1133. function forwardRejection(rejection) {
  1134. return ZoneAwarePromise.reject(rejection);
  1135. }
  1136. const symbolState = __symbol__('state');
  1137. const symbolValue = __symbol__('value');
  1138. const symbolFinally = __symbol__('finally');
  1139. const symbolParentPromiseValue = __symbol__('parentPromiseValue');
  1140. const symbolParentPromiseState = __symbol__('parentPromiseState');
  1141. const source = 'Promise.then';
  1142. const UNRESOLVED = null;
  1143. const RESOLVED = true;
  1144. const REJECTED = false;
  1145. const REJECTED_NO_CATCH = 0;
  1146. function makeResolver(promise, state) {
  1147. return (v) => {
  1148. try {
  1149. resolvePromise(promise, state, v);
  1150. }
  1151. catch (err) {
  1152. resolvePromise(promise, false, err);
  1153. }
  1154. // Do not return value or you will break the Promise spec.
  1155. };
  1156. }
  1157. const once = function () {
  1158. let wasCalled = false;
  1159. return function wrapper(wrappedFunction) {
  1160. return function () {
  1161. if (wasCalled) {
  1162. return;
  1163. }
  1164. wasCalled = true;
  1165. wrappedFunction.apply(null, arguments);
  1166. };
  1167. };
  1168. };
  1169. const TYPE_ERROR = 'Promise resolved with itself';
  1170. const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  1171. // Promise Resolution
  1172. function resolvePromise(promise, state, value) {
  1173. const onceWrapper = once();
  1174. if (promise === value) {
  1175. throw new TypeError(TYPE_ERROR);
  1176. }
  1177. if (promise[symbolState] === UNRESOLVED) {
  1178. // should only get value.then once based on promise spec.
  1179. let then = null;
  1180. try {
  1181. if (typeof value === 'object' || typeof value === 'function') {
  1182. then = value && value.then;
  1183. }
  1184. }
  1185. catch (err) {
  1186. onceWrapper(() => {
  1187. resolvePromise(promise, false, err);
  1188. })();
  1189. return promise;
  1190. }
  1191. // if (value instanceof ZoneAwarePromise) {
  1192. if (state !== REJECTED && value instanceof ZoneAwarePromise &&
  1193. value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
  1194. value[symbolState] !== UNRESOLVED) {
  1195. clearRejectedNoCatch(value);
  1196. resolvePromise(promise, value[symbolState], value[symbolValue]);
  1197. }
  1198. else if (state !== REJECTED && typeof then === 'function') {
  1199. try {
  1200. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  1201. }
  1202. catch (err) {
  1203. onceWrapper(() => {
  1204. resolvePromise(promise, false, err);
  1205. })();
  1206. }
  1207. }
  1208. else {
  1209. promise[symbolState] = state;
  1210. const queue = promise[symbolValue];
  1211. promise[symbolValue] = value;
  1212. if (promise[symbolFinally] === symbolFinally) {
  1213. // the promise is generated by Promise.prototype.finally
  1214. if (state === RESOLVED) {
  1215. // the state is resolved, should ignore the value
  1216. // and use parent promise value
  1217. promise[symbolState] = promise[symbolParentPromiseState];
  1218. promise[symbolValue] = promise[symbolParentPromiseValue];
  1219. }
  1220. }
  1221. // record task information in value when error occurs, so we can
  1222. // do some additional work such as render longStackTrace
  1223. if (state === REJECTED && value instanceof Error) {
  1224. // check if longStackTraceZone is here
  1225. const trace = Zone.currentTask && Zone.currentTask.data &&
  1226. Zone.currentTask.data[creationTrace];
  1227. if (trace) {
  1228. // only keep the long stack trace into error when in longStackTraceZone
  1229. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
  1230. }
  1231. }
  1232. for (let i = 0; i < queue.length;) {
  1233. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  1234. }
  1235. if (queue.length == 0 && state == REJECTED) {
  1236. promise[symbolState] = REJECTED_NO_CATCH;
  1237. let uncaughtPromiseError = value;
  1238. try {
  1239. // Here we throws a new Error to print more readable error log
  1240. // and if the value is not an error, zone.js builds an `Error`
  1241. // Object here to attach the stack information.
  1242. throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
  1243. (value && value.stack ? '\n' + value.stack : ''));
  1244. }
  1245. catch (err) {
  1246. uncaughtPromiseError = err;
  1247. }
  1248. if (isDisableWrappingUncaughtPromiseRejection) {
  1249. // If disable wrapping uncaught promise reject
  1250. // use the value instead of wrapping it.
  1251. uncaughtPromiseError.throwOriginal = true;
  1252. }
  1253. uncaughtPromiseError.rejection = value;
  1254. uncaughtPromiseError.promise = promise;
  1255. uncaughtPromiseError.zone = Zone.current;
  1256. uncaughtPromiseError.task = Zone.currentTask;
  1257. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  1258. api.scheduleMicroTask(); // to make sure that it is running
  1259. }
  1260. }
  1261. }
  1262. // Resolving an already resolved promise is a noop.
  1263. return promise;
  1264. }
  1265. const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  1266. function clearRejectedNoCatch(promise) {
  1267. if (promise[symbolState] === REJECTED_NO_CATCH) {
  1268. // if the promise is rejected no catch status
  1269. // and queue.length > 0, means there is a error handler
  1270. // here to handle the rejected promise, we should trigger
  1271. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  1272. // eventHandler
  1273. try {
  1274. const handler = Zone[REJECTION_HANDLED_HANDLER];
  1275. if (handler && typeof handler === 'function') {
  1276. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  1277. }
  1278. }
  1279. catch (err) {
  1280. }
  1281. promise[symbolState] = REJECTED;
  1282. for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
  1283. if (promise === _uncaughtPromiseErrors[i].promise) {
  1284. _uncaughtPromiseErrors.splice(i, 1);
  1285. }
  1286. }
  1287. }
  1288. }
  1289. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  1290. clearRejectedNoCatch(promise);
  1291. const promiseState = promise[symbolState];
  1292. const delegate = promiseState ?
  1293. (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
  1294. (typeof onRejected === 'function') ? onRejected :
  1295. forwardRejection;
  1296. zone.scheduleMicroTask(source, () => {
  1297. try {
  1298. const parentPromiseValue = promise[symbolValue];
  1299. const isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  1300. if (isFinallyPromise) {
  1301. // if the promise is generated from finally call, keep parent promise's state and value
  1302. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  1303. chainPromise[symbolParentPromiseState] = promiseState;
  1304. }
  1305. // should not pass value to finally callback
  1306. const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
  1307. [] :
  1308. [parentPromiseValue]);
  1309. resolvePromise(chainPromise, true, value);
  1310. }
  1311. catch (error) {
  1312. // if error occurs, should always return this error
  1313. resolvePromise(chainPromise, false, error);
  1314. }
  1315. }, chainPromise);
  1316. }
  1317. const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  1318. const noop = function () { };
  1319. const AggregateError = global.AggregateError;
  1320. class ZoneAwarePromise {
  1321. static toString() {
  1322. return ZONE_AWARE_PROMISE_TO_STRING;
  1323. }
  1324. static resolve(value) {
  1325. return resolvePromise(new this(null), RESOLVED, value);
  1326. }
  1327. static reject(error) {
  1328. return resolvePromise(new this(null), REJECTED, error);
  1329. }
  1330. static any(values) {
  1331. if (!values || typeof values[Symbol.iterator] !== 'function') {
  1332. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1333. }
  1334. const promises = [];
  1335. let count = 0;
  1336. try {
  1337. for (let v of values) {
  1338. count++;
  1339. promises.push(ZoneAwarePromise.resolve(v));
  1340. }
  1341. }
  1342. catch (err) {
  1343. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1344. }
  1345. if (count === 0) {
  1346. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1347. }
  1348. let finished = false;
  1349. const errors = [];
  1350. return new ZoneAwarePromise((resolve, reject) => {
  1351. for (let i = 0; i < promises.length; i++) {
  1352. promises[i].then(v => {
  1353. if (finished) {
  1354. return;
  1355. }
  1356. finished = true;
  1357. resolve(v);
  1358. }, err => {
  1359. errors.push(err);
  1360. count--;
  1361. if (count === 0) {
  1362. finished = true;
  1363. reject(new AggregateError(errors, 'All promises were rejected'));
  1364. }
  1365. });
  1366. }
  1367. });
  1368. }
  1369. ;
  1370. static race(values) {
  1371. let resolve;
  1372. let reject;
  1373. let promise = new this((res, rej) => {
  1374. resolve = res;
  1375. reject = rej;
  1376. });
  1377. function onResolve(value) {
  1378. resolve(value);
  1379. }
  1380. function onReject(error) {
  1381. reject(error);
  1382. }
  1383. for (let value of values) {
  1384. if (!isThenable(value)) {
  1385. value = this.resolve(value);
  1386. }
  1387. value.then(onResolve, onReject);
  1388. }
  1389. return promise;
  1390. }
  1391. static all(values) {
  1392. return ZoneAwarePromise.allWithCallback(values);
  1393. }
  1394. static allSettled(values) {
  1395. const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  1396. return P.allWithCallback(values, {
  1397. thenCallback: (value) => ({ status: 'fulfilled', value }),
  1398. errorCallback: (err) => ({ status: 'rejected', reason: err })
  1399. });
  1400. }
  1401. static allWithCallback(values, callback) {
  1402. let resolve;
  1403. let reject;
  1404. let promise = new this((res, rej) => {
  1405. resolve = res;
  1406. reject = rej;
  1407. });
  1408. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  1409. let unresolvedCount = 2;
  1410. let valueIndex = 0;
  1411. const resolvedValues = [];
  1412. for (let value of values) {
  1413. if (!isThenable(value)) {
  1414. value = this.resolve(value);
  1415. }
  1416. const curValueIndex = valueIndex;
  1417. try {
  1418. value.then((value) => {
  1419. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  1420. unresolvedCount--;
  1421. if (unresolvedCount === 0) {
  1422. resolve(resolvedValues);
  1423. }
  1424. }, (err) => {
  1425. if (!callback) {
  1426. reject(err);
  1427. }
  1428. else {
  1429. resolvedValues[curValueIndex] = callback.errorCallback(err);
  1430. unresolvedCount--;
  1431. if (unresolvedCount === 0) {
  1432. resolve(resolvedValues);
  1433. }
  1434. }
  1435. });
  1436. }
  1437. catch (thenErr) {
  1438. reject(thenErr);
  1439. }
  1440. unresolvedCount++;
  1441. valueIndex++;
  1442. }
  1443. // Make the unresolvedCount zero-based again.
  1444. unresolvedCount -= 2;
  1445. if (unresolvedCount === 0) {
  1446. resolve(resolvedValues);
  1447. }
  1448. return promise;
  1449. }
  1450. constructor(executor) {
  1451. const promise = this;
  1452. if (!(promise instanceof ZoneAwarePromise)) {
  1453. throw new Error('Must be an instanceof Promise.');
  1454. }
  1455. promise[symbolState] = UNRESOLVED;
  1456. promise[symbolValue] = []; // queue;
  1457. try {
  1458. const onceWrapper = once();
  1459. executor &&
  1460. executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
  1461. }
  1462. catch (error) {
  1463. resolvePromise(promise, false, error);
  1464. }
  1465. }
  1466. get [Symbol.toStringTag]() {
  1467. return 'Promise';
  1468. }
  1469. get [Symbol.species]() {
  1470. return ZoneAwarePromise;
  1471. }
  1472. then(onFulfilled, onRejected) {
  1473. // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
  1474. // may be an object without a prototype (created through `Object.create(null)`); thus
  1475. // `this.constructor` will be undefined. One of the use cases is SystemJS creating
  1476. // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
  1477. // object and copies promise properties into that object (within the `getOrCreateLoad`
  1478. // function). The zone.js then checks if the resolved value has the `then` method and invokes
  1479. // it with the `value` context. Otherwise, this will throw an error: `TypeError: Cannot read
  1480. // properties of undefined (reading 'Symbol(Symbol.species)')`.
  1481. let C = this.constructor?.[Symbol.species];
  1482. if (!C || typeof C !== 'function') {
  1483. C = this.constructor || ZoneAwarePromise;
  1484. }
  1485. const chainPromise = new C(noop);
  1486. const zone = Zone.current;
  1487. if (this[symbolState] == UNRESOLVED) {
  1488. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  1489. }
  1490. else {
  1491. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  1492. }
  1493. return chainPromise;
  1494. }
  1495. catch(onRejected) {
  1496. return this.then(null, onRejected);
  1497. }
  1498. finally(onFinally) {
  1499. // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
  1500. let C = this.constructor?.[Symbol.species];
  1501. if (!C || typeof C !== 'function') {
  1502. C = ZoneAwarePromise;
  1503. }
  1504. const chainPromise = new C(noop);
  1505. chainPromise[symbolFinally] = symbolFinally;
  1506. const zone = Zone.current;
  1507. if (this[symbolState] == UNRESOLVED) {
  1508. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  1509. }
  1510. else {
  1511. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  1512. }
  1513. return chainPromise;
  1514. }
  1515. }
  1516. // Protect against aggressive optimizers dropping seemingly unused properties.
  1517. // E.g. Closure Compiler in advanced mode.
  1518. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  1519. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  1520. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  1521. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  1522. const NativePromise = global[symbolPromise] = global['Promise'];
  1523. global['Promise'] = ZoneAwarePromise;
  1524. const symbolThenPatched = __symbol__('thenPatched');
  1525. function patchThen(Ctor) {
  1526. const proto = Ctor.prototype;
  1527. const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  1528. if (prop && (prop.writable === false || !prop.configurable)) {
  1529. // check Ctor.prototype.then propertyDescriptor is writable or not
  1530. // in meteor env, writable is false, we should ignore such case
  1531. return;
  1532. }
  1533. const originalThen = proto.then;
  1534. // Keep a reference to the original method.
  1535. proto[symbolThen] = originalThen;
  1536. Ctor.prototype.then = function (onResolve, onReject) {
  1537. const wrapped = new ZoneAwarePromise((resolve, reject) => {
  1538. originalThen.call(this, resolve, reject);
  1539. });
  1540. return wrapped.then(onResolve, onReject);
  1541. };
  1542. Ctor[symbolThenPatched] = true;
  1543. }
  1544. api.patchThen = patchThen;
  1545. function zoneify(fn) {
  1546. return function (self, args) {
  1547. let resultPromise = fn.apply(self, args);
  1548. if (resultPromise instanceof ZoneAwarePromise) {
  1549. return resultPromise;
  1550. }
  1551. let ctor = resultPromise.constructor;
  1552. if (!ctor[symbolThenPatched]) {
  1553. patchThen(ctor);
  1554. }
  1555. return resultPromise;
  1556. };
  1557. }
  1558. if (NativePromise) {
  1559. patchThen(NativePromise);
  1560. patchMethod(global, 'fetch', delegate => zoneify(delegate));
  1561. }
  1562. // This is not part of public API, but it is useful for tests, so we expose it.
  1563. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  1564. return ZoneAwarePromise;
  1565. });
  1566. // override Function.prototype.toString to make zone.js patched function
  1567. // look like native function
  1568. Zone.__load_patch('toString', (global) => {
  1569. // patch Func.prototype.toString to let them look like native
  1570. const originalFunctionToString = Function.prototype.toString;
  1571. const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1572. const PROMISE_SYMBOL = zoneSymbol('Promise');
  1573. const ERROR_SYMBOL = zoneSymbol('Error');
  1574. const newFunctionToString = function toString() {
  1575. if (typeof this === 'function') {
  1576. const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1577. if (originalDelegate) {
  1578. if (typeof originalDelegate === 'function') {
  1579. return originalFunctionToString.call(originalDelegate);
  1580. }
  1581. else {
  1582. return Object.prototype.toString.call(originalDelegate);
  1583. }
  1584. }
  1585. if (this === Promise) {
  1586. const nativePromise = global[PROMISE_SYMBOL];
  1587. if (nativePromise) {
  1588. return originalFunctionToString.call(nativePromise);
  1589. }
  1590. }
  1591. if (this === Error) {
  1592. const nativeError = global[ERROR_SYMBOL];
  1593. if (nativeError) {
  1594. return originalFunctionToString.call(nativeError);
  1595. }
  1596. }
  1597. }
  1598. return originalFunctionToString.call(this);
  1599. };
  1600. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1601. Function.prototype.toString = newFunctionToString;
  1602. // patch Object.prototype.toString to let them look like native
  1603. const originalObjectToString = Object.prototype.toString;
  1604. const PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1605. Object.prototype.toString = function () {
  1606. if (typeof Promise === 'function' && this instanceof Promise) {
  1607. return PROMISE_OBJECT_TO_STRING;
  1608. }
  1609. return originalObjectToString.call(this);
  1610. };
  1611. });
  1612. /**
  1613. * @fileoverview
  1614. * @suppress {missingRequire}
  1615. */
  1616. let passiveSupported = false;
  1617. if (typeof window !== 'undefined') {
  1618. try {
  1619. const options = Object.defineProperty({}, 'passive', {
  1620. get: function () {
  1621. passiveSupported = true;
  1622. }
  1623. });
  1624. // Note: We pass the `options` object as the event handler too. This is not compatible with the
  1625. // signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
  1626. // without an actual handler.
  1627. window.addEventListener('test', options, options);
  1628. window.removeEventListener('test', options, options);
  1629. }
  1630. catch (err) {
  1631. passiveSupported = false;
  1632. }
  1633. }
  1634. // an identifier to tell ZoneTask do not create a new invoke closure
  1635. const OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1636. useG: true
  1637. };
  1638. const zoneSymbolEventNames = {};
  1639. const globalSources = {};
  1640. const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1641. const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1642. function prepareEventNames(eventName, eventNameToString) {
  1643. const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1644. const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1645. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1646. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1647. zoneSymbolEventNames[eventName] = {};
  1648. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1649. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1650. }
  1651. function patchEventTarget(_global, api, apis, patchOptions) {
  1652. const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1653. const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1654. const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1655. const REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1656. const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1657. const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1658. const PREPEND_EVENT_LISTENER = 'prependListener';
  1659. const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1660. const invokeTask = function (task, target, event) {
  1661. // for better performance, check isRemoved which is set
  1662. // by removeEventListener
  1663. if (task.isRemoved) {
  1664. return;
  1665. }
  1666. const delegate = task.callback;
  1667. if (typeof delegate === 'object' && delegate.handleEvent) {
  1668. // create the bind version of handleEvent when invoke
  1669. task.callback = (event) => delegate.handleEvent(event);
  1670. task.originalDelegate = delegate;
  1671. }
  1672. // invoke static task.invoke
  1673. // need to try/catch error here, otherwise, the error in one event listener
  1674. // will break the executions of the other event listeners. Also error will
  1675. // not remove the event listener when `once` options is true.
  1676. let error;
  1677. try {
  1678. task.invoke(task, target, [event]);
  1679. }
  1680. catch (err) {
  1681. error = err;
  1682. }
  1683. const options = task.options;
  1684. if (options && typeof options === 'object' && options.once) {
  1685. // if options.once is true, after invoke once remove listener here
  1686. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1687. // inside EventEmitter.once
  1688. const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1689. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
  1690. }
  1691. return error;
  1692. };
  1693. function globalCallback(context, event, isCapture) {
  1694. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1695. // event will be undefined, so we need to use window.event
  1696. event = event || _global.event;
  1697. if (!event) {
  1698. return;
  1699. }
  1700. // event.target is needed for Samsung TV and SourceBuffer
  1701. // || global is needed https://github.com/angular/zone.js/issues/190
  1702. const target = context || event.target || _global;
  1703. const tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1704. if (tasks) {
  1705. const errors = [];
  1706. // invoke all tasks which attached to current target with given event.type and capture = false
  1707. // for performance concern, if task.length === 1, just invoke
  1708. if (tasks.length === 1) {
  1709. const err = invokeTask(tasks[0], target, event);
  1710. err && errors.push(err);
  1711. }
  1712. else {
  1713. // https://github.com/angular/zone.js/issues/836
  1714. // copy the tasks array before invoke, to avoid
  1715. // the callback will remove itself or other listener
  1716. const copyTasks = tasks.slice();
  1717. for (let i = 0; i < copyTasks.length; i++) {
  1718. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1719. break;
  1720. }
  1721. const err = invokeTask(copyTasks[i], target, event);
  1722. err && errors.push(err);
  1723. }
  1724. }
  1725. // Since there is only one error, we don't need to schedule microTask
  1726. // to throw the error.
  1727. if (errors.length === 1) {
  1728. throw errors[0];
  1729. }
  1730. else {
  1731. for (let i = 0; i < errors.length; i++) {
  1732. const err = errors[i];
  1733. api.nativeScheduleMicroTask(() => {
  1734. throw err;
  1735. });
  1736. }
  1737. }
  1738. }
  1739. }
  1740. // global shared zoneAwareCallback to handle all event callback with capture = false
  1741. const globalZoneAwareCallback = function (event) {
  1742. return globalCallback(this, event, false);
  1743. };
  1744. // global shared zoneAwareCallback to handle all event callback with capture = true
  1745. const globalZoneAwareCaptureCallback = function (event) {
  1746. return globalCallback(this, event, true);
  1747. };
  1748. function patchEventTargetMethods(obj, patchOptions) {
  1749. if (!obj) {
  1750. return false;
  1751. }
  1752. let useGlobalCallback = true;
  1753. if (patchOptions && patchOptions.useG !== undefined) {
  1754. useGlobalCallback = patchOptions.useG;
  1755. }
  1756. const validateHandler = patchOptions && patchOptions.vh;
  1757. let checkDuplicate = true;
  1758. if (patchOptions && patchOptions.chkDup !== undefined) {
  1759. checkDuplicate = patchOptions.chkDup;
  1760. }
  1761. let returnTarget = false;
  1762. if (patchOptions && patchOptions.rt !== undefined) {
  1763. returnTarget = patchOptions.rt;
  1764. }
  1765. let proto = obj;
  1766. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1767. proto = ObjectGetPrototypeOf(proto);
  1768. }
  1769. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1770. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1771. proto = obj;
  1772. }
  1773. if (!proto) {
  1774. return false;
  1775. }
  1776. if (proto[zoneSymbolAddEventListener]) {
  1777. return false;
  1778. }
  1779. const eventNameToString = patchOptions && patchOptions.eventNameToString;
  1780. // a shared global taskData to pass data for scheduleEventTask
  1781. // so we do not need to create a new object just for pass some data
  1782. const taskData = {};
  1783. const nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
  1784. const nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1785. proto[REMOVE_EVENT_LISTENER];
  1786. const nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1787. proto[LISTENERS_EVENT_LISTENER];
  1788. const nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1789. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
  1790. let nativePrependEventListener;
  1791. if (patchOptions && patchOptions.prepend) {
  1792. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1793. proto[patchOptions.prepend];
  1794. }
  1795. /**
  1796. * This util function will build an option object with passive option
  1797. * to handle all possible input from the user.
  1798. */
  1799. function buildEventListenerOptions(options, passive) {
  1800. if (!passiveSupported && typeof options === 'object' && options) {
  1801. // doesn't support passive but user want to pass an object as options.
  1802. // this will not work on some old browser, so we just pass a boolean
  1803. // as useCapture parameter
  1804. return !!options.capture;
  1805. }
  1806. if (!passiveSupported || !passive) {
  1807. return options;
  1808. }
  1809. if (typeof options === 'boolean') {
  1810. return { capture: options, passive: true };
  1811. }
  1812. if (!options) {
  1813. return { passive: true };
  1814. }
  1815. if (typeof options === 'object' && options.passive !== false) {
  1816. return { ...options, passive: true };
  1817. }
  1818. return options;
  1819. }
  1820. const customScheduleGlobal = function (task) {
  1821. // if there is already a task for the eventName + capture,
  1822. // just return, because we use the shared globalZoneAwareCallback here.
  1823. if (taskData.isExisting) {
  1824. return;
  1825. }
  1826. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1827. };
  1828. const customCancelGlobal = function (task) {
  1829. // if task is not marked as isRemoved, this call is directly
  1830. // from Zone.prototype.cancelTask, we should remove the task
  1831. // from tasksList of target first
  1832. if (!task.isRemoved) {
  1833. const symbolEventNames = zoneSymbolEventNames[task.eventName];
  1834. let symbolEventName;
  1835. if (symbolEventNames) {
  1836. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1837. }
  1838. const existingTasks = symbolEventName && task.target[symbolEventName];
  1839. if (existingTasks) {
  1840. for (let i = 0; i < existingTasks.length; i++) {
  1841. const existingTask = existingTasks[i];
  1842. if (existingTask === task) {
  1843. existingTasks.splice(i, 1);
  1844. // set isRemoved to data for faster invokeTask check
  1845. task.isRemoved = true;
  1846. if (existingTasks.length === 0) {
  1847. // all tasks for the eventName + capture have gone,
  1848. // remove globalZoneAwareCallback and remove the task cache from target
  1849. task.allRemoved = true;
  1850. task.target[symbolEventName] = null;
  1851. }
  1852. break;
  1853. }
  1854. }
  1855. }
  1856. }
  1857. // if all tasks for the eventName + capture have gone,
  1858. // we will really remove the global event callback,
  1859. // if not, return
  1860. if (!task.allRemoved) {
  1861. return;
  1862. }
  1863. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1864. };
  1865. const customScheduleNonGlobal = function (task) {
  1866. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1867. };
  1868. const customSchedulePrepend = function (task) {
  1869. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1870. };
  1871. const customCancelNonGlobal = function (task) {
  1872. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1873. };
  1874. const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1875. const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1876. const compareTaskCallbackVsDelegate = function (task, delegate) {
  1877. const typeOfDelegate = typeof delegate;
  1878. return (typeOfDelegate === 'function' && task.callback === delegate) ||
  1879. (typeOfDelegate === 'object' && task.originalDelegate === delegate);
  1880. };
  1881. const compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
  1882. const unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1883. const passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1884. const makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget = false, prepend = false) {
  1885. return function () {
  1886. const target = this || _global;
  1887. let eventName = arguments[0];
  1888. if (patchOptions && patchOptions.transferEventName) {
  1889. eventName = patchOptions.transferEventName(eventName);
  1890. }
  1891. let delegate = arguments[1];
  1892. if (!delegate) {
  1893. return nativeListener.apply(this, arguments);
  1894. }
  1895. if (isNode && eventName === 'uncaughtException') {
  1896. // don't patch uncaughtException of nodejs to prevent endless loop
  1897. return nativeListener.apply(this, arguments);
  1898. }
  1899. // don't create the bind delegate function for handleEvent
  1900. // case here to improve addEventListener performance
  1901. // we will create the bind delegate when invoke
  1902. let isHandleEvent = false;
  1903. if (typeof delegate !== 'function') {
  1904. if (!delegate.handleEvent) {
  1905. return nativeListener.apply(this, arguments);
  1906. }
  1907. isHandleEvent = true;
  1908. }
  1909. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1910. return;
  1911. }
  1912. const passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1913. const options = buildEventListenerOptions(arguments[2], passive);
  1914. if (unpatchedEvents) {
  1915. // check unpatched list
  1916. for (let i = 0; i < unpatchedEvents.length; i++) {
  1917. if (eventName === unpatchedEvents[i]) {
  1918. if (passive) {
  1919. return nativeListener.call(target, eventName, delegate, options);
  1920. }
  1921. else {
  1922. return nativeListener.apply(this, arguments);
  1923. }
  1924. }
  1925. }
  1926. }
  1927. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1928. const once = options && typeof options === 'object' ? options.once : false;
  1929. const zone = Zone.current;
  1930. let symbolEventNames = zoneSymbolEventNames[eventName];
  1931. if (!symbolEventNames) {
  1932. prepareEventNames(eventName, eventNameToString);
  1933. symbolEventNames = zoneSymbolEventNames[eventName];
  1934. }
  1935. const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1936. let existingTasks = target[symbolEventName];
  1937. let isExisting = false;
  1938. if (existingTasks) {
  1939. // already have task registered
  1940. isExisting = true;
  1941. if (checkDuplicate) {
  1942. for (let i = 0; i < existingTasks.length; i++) {
  1943. if (compare(existingTasks[i], delegate)) {
  1944. // same callback, same capture, same event name, just return
  1945. return;
  1946. }
  1947. }
  1948. }
  1949. }
  1950. else {
  1951. existingTasks = target[symbolEventName] = [];
  1952. }
  1953. let source;
  1954. const constructorName = target.constructor['name'];
  1955. const targetSource = globalSources[constructorName];
  1956. if (targetSource) {
  1957. source = targetSource[eventName];
  1958. }
  1959. if (!source) {
  1960. source = constructorName + addSource +
  1961. (eventNameToString ? eventNameToString(eventName) : eventName);
  1962. }
  1963. // do not create a new object as task.data to pass those things
  1964. // just use the global shared one
  1965. taskData.options = options;
  1966. if (once) {
  1967. // if addEventListener with once options, we don't pass it to
  1968. // native addEventListener, instead we keep the once setting
  1969. // and handle ourselves.
  1970. taskData.options.once = false;
  1971. }
  1972. taskData.target = target;
  1973. taskData.capture = capture;
  1974. taskData.eventName = eventName;
  1975. taskData.isExisting = isExisting;
  1976. const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1977. // keep taskData into data to allow onScheduleEventTask to access the task information
  1978. if (data) {
  1979. data.taskData = taskData;
  1980. }
  1981. const task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1982. // should clear taskData.target to avoid memory leak
  1983. // issue, https://github.com/angular/angular/issues/20442
  1984. taskData.target = null;
  1985. // need to clear up taskData because it is a global object
  1986. if (data) {
  1987. data.taskData = null;
  1988. }
  1989. // have to save those information to task in case
  1990. // application may call task.zone.cancelTask() directly
  1991. if (once) {
  1992. options.once = true;
  1993. }
  1994. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  1995. // if not support passive, and we pass an option object
  1996. // to addEventListener, we should save the options to task
  1997. task.options = options;
  1998. }
  1999. task.target = target;
  2000. task.capture = capture;
  2001. task.eventName = eventName;
  2002. if (isHandleEvent) {
  2003. // save original delegate for compare to check duplicate
  2004. task.originalDelegate = delegate;
  2005. }
  2006. if (!prepend) {
  2007. existingTasks.push(task);
  2008. }
  2009. else {
  2010. existingTasks.unshift(task);
  2011. }
  2012. if (returnTarget) {
  2013. return target;
  2014. }
  2015. };
  2016. };
  2017. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  2018. if (nativePrependEventListener) {
  2019. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  2020. }
  2021. proto[REMOVE_EVENT_LISTENER] = function () {
  2022. const target = this || _global;
  2023. let eventName = arguments[0];
  2024. if (patchOptions && patchOptions.transferEventName) {
  2025. eventName = patchOptions.transferEventName(eventName);
  2026. }
  2027. const options = arguments[2];
  2028. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  2029. const delegate = arguments[1];
  2030. if (!delegate) {
  2031. return nativeRemoveEventListener.apply(this, arguments);
  2032. }
  2033. if (validateHandler &&
  2034. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  2035. return;
  2036. }
  2037. const symbolEventNames = zoneSymbolEventNames[eventName];
  2038. let symbolEventName;
  2039. if (symbolEventNames) {
  2040. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  2041. }
  2042. const existingTasks = symbolEventName && target[symbolEventName];
  2043. if (existingTasks) {
  2044. for (let i = 0; i < existingTasks.length; i++) {
  2045. const existingTask = existingTasks[i];
  2046. if (compare(existingTask, delegate)) {
  2047. existingTasks.splice(i, 1);
  2048. // set isRemoved to data for faster invokeTask check
  2049. existingTask.isRemoved = true;
  2050. if (existingTasks.length === 0) {
  2051. // all tasks for the eventName + capture have gone,
  2052. // remove globalZoneAwareCallback and remove the task cache from target
  2053. existingTask.allRemoved = true;
  2054. target[symbolEventName] = null;
  2055. // in the target, we have an event listener which is added by on_property
  2056. // such as target.onclick = function() {}, so we need to clear this internal
  2057. // property too if all delegates all removed
  2058. if (typeof eventName === 'string') {
  2059. const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  2060. target[onPropertySymbol] = null;
  2061. }
  2062. }
  2063. existingTask.zone.cancelTask(existingTask);
  2064. if (returnTarget) {
  2065. return target;
  2066. }
  2067. return;
  2068. }
  2069. }
  2070. }
  2071. // issue 930, didn't find the event name or callback
  2072. // from zone kept existingTasks, the callback maybe
  2073. // added outside of zone, we need to call native removeEventListener
  2074. // to try to remove it.
  2075. return nativeRemoveEventListener.apply(this, arguments);
  2076. };
  2077. proto[LISTENERS_EVENT_LISTENER] = function () {
  2078. const target = this || _global;
  2079. let eventName = arguments[0];
  2080. if (patchOptions && patchOptions.transferEventName) {
  2081. eventName = patchOptions.transferEventName(eventName);
  2082. }
  2083. const listeners = [];
  2084. const tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  2085. for (let i = 0; i < tasks.length; i++) {
  2086. const task = tasks[i];
  2087. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2088. listeners.push(delegate);
  2089. }
  2090. return listeners;
  2091. };
  2092. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  2093. const target = this || _global;
  2094. let eventName = arguments[0];
  2095. if (!eventName) {
  2096. const keys = Object.keys(target);
  2097. for (let i = 0; i < keys.length; i++) {
  2098. const prop = keys[i];
  2099. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2100. let evtName = match && match[1];
  2101. // in nodejs EventEmitter, removeListener event is
  2102. // used for monitoring the removeListener call,
  2103. // so just keep removeListener eventListener until
  2104. // all other eventListeners are removed
  2105. if (evtName && evtName !== 'removeListener') {
  2106. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  2107. }
  2108. }
  2109. // remove removeListener listener finally
  2110. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  2111. }
  2112. else {
  2113. if (patchOptions && patchOptions.transferEventName) {
  2114. eventName = patchOptions.transferEventName(eventName);
  2115. }
  2116. const symbolEventNames = zoneSymbolEventNames[eventName];
  2117. if (symbolEventNames) {
  2118. const symbolEventName = symbolEventNames[FALSE_STR];
  2119. const symbolCaptureEventName = symbolEventNames[TRUE_STR];
  2120. const tasks = target[symbolEventName];
  2121. const captureTasks = target[symbolCaptureEventName];
  2122. if (tasks) {
  2123. const removeTasks = tasks.slice();
  2124. for (let i = 0; i < removeTasks.length; i++) {
  2125. const task = removeTasks[i];
  2126. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2127. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2128. }
  2129. }
  2130. if (captureTasks) {
  2131. const removeTasks = captureTasks.slice();
  2132. for (let i = 0; i < removeTasks.length; i++) {
  2133. const task = removeTasks[i];
  2134. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2135. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2136. }
  2137. }
  2138. }
  2139. }
  2140. if (returnTarget) {
  2141. return this;
  2142. }
  2143. };
  2144. // for native toString patch
  2145. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  2146. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  2147. if (nativeRemoveAllListeners) {
  2148. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  2149. }
  2150. if (nativeListeners) {
  2151. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  2152. }
  2153. return true;
  2154. }
  2155. let results = [];
  2156. for (let i = 0; i < apis.length; i++) {
  2157. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  2158. }
  2159. return results;
  2160. }
  2161. function findEventTasks(target, eventName) {
  2162. if (!eventName) {
  2163. const foundTasks = [];
  2164. for (let prop in target) {
  2165. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2166. let evtName = match && match[1];
  2167. if (evtName && (!eventName || evtName === eventName)) {
  2168. const tasks = target[prop];
  2169. if (tasks) {
  2170. for (let i = 0; i < tasks.length; i++) {
  2171. foundTasks.push(tasks[i]);
  2172. }
  2173. }
  2174. }
  2175. }
  2176. return foundTasks;
  2177. }
  2178. let symbolEventName = zoneSymbolEventNames[eventName];
  2179. if (!symbolEventName) {
  2180. prepareEventNames(eventName);
  2181. symbolEventName = zoneSymbolEventNames[eventName];
  2182. }
  2183. const captureFalseTasks = target[symbolEventName[FALSE_STR]];
  2184. const captureTrueTasks = target[symbolEventName[TRUE_STR]];
  2185. if (!captureFalseTasks) {
  2186. return captureTrueTasks ? captureTrueTasks.slice() : [];
  2187. }
  2188. else {
  2189. return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
  2190. captureFalseTasks.slice();
  2191. }
  2192. }
  2193. function patchEventPrototype(global, api) {
  2194. const Event = global['Event'];
  2195. if (Event && Event.prototype) {
  2196. api.patchMethod(Event.prototype, 'stopImmediatePropagation', (delegate) => function (self, args) {
  2197. self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
  2198. // we need to call the native stopImmediatePropagation
  2199. // in case in some hybrid application, some part of
  2200. // application will be controlled by zone, some are not
  2201. delegate && delegate.apply(self, args);
  2202. });
  2203. }
  2204. }
  2205. function patchCallbacks(api, target, targetName, method, callbacks) {
  2206. const symbol = Zone.__symbol__(method);
  2207. if (target[symbol]) {
  2208. return;
  2209. }
  2210. const nativeDelegate = target[symbol] = target[method];
  2211. target[method] = function (name, opts, options) {
  2212. if (opts && opts.prototype) {
  2213. callbacks.forEach(function (callback) {
  2214. const source = `${targetName}.${method}::` + callback;
  2215. const prototype = opts.prototype;
  2216. // Note: the `patchCallbacks` is used for patching the `document.registerElement` and
  2217. // `customElements.define`. We explicitly wrap the patching code into try-catch since
  2218. // callbacks may be already patched by other web components frameworks (e.g. LWC), and they
  2219. // make those properties non-writable. This means that patching callback will throw an error
  2220. // `cannot assign to read-only property`. See this code as an example:
  2221. // https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
  2222. // We don't want to stop the application rendering if we couldn't patch some
  2223. // callback, e.g. `attributeChangedCallback`.
  2224. try {
  2225. if (prototype.hasOwnProperty(callback)) {
  2226. const descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
  2227. if (descriptor && descriptor.value) {
  2228. descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
  2229. api._redefineProperty(opts.prototype, callback, descriptor);
  2230. }
  2231. else if (prototype[callback]) {
  2232. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2233. }
  2234. }
  2235. else if (prototype[callback]) {
  2236. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2237. }
  2238. }
  2239. catch {
  2240. // Note: we leave the catch block empty since there's no way to handle the error related
  2241. // to non-writable property.
  2242. }
  2243. });
  2244. }
  2245. return nativeDelegate.call(target, name, opts, options);
  2246. };
  2247. api.attachOriginToPatched(target[method], nativeDelegate);
  2248. }
  2249. /**
  2250. * @fileoverview
  2251. * @suppress {globalThis}
  2252. */
  2253. function filterProperties(target, onProperties, ignoreProperties) {
  2254. if (!ignoreProperties || ignoreProperties.length === 0) {
  2255. return onProperties;
  2256. }
  2257. const tip = ignoreProperties.filter(ip => ip.target === target);
  2258. if (!tip || tip.length === 0) {
  2259. return onProperties;
  2260. }
  2261. const targetIgnoreProperties = tip[0].ignoreProperties;
  2262. return onProperties.filter(op => targetIgnoreProperties.indexOf(op) === -1);
  2263. }
  2264. function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
  2265. // check whether target is available, sometimes target will be undefined
  2266. // because different browser or some 3rd party plugin.
  2267. if (!target) {
  2268. return;
  2269. }
  2270. const filteredProperties = filterProperties(target, onProperties, ignoreProperties);
  2271. patchOnProperties(target, filteredProperties, prototype);
  2272. }
  2273. /**
  2274. * Get all event name properties which the event name startsWith `on`
  2275. * from the target object itself, inherited properties are not considered.
  2276. */
  2277. function getOnEventNames(target) {
  2278. return Object.getOwnPropertyNames(target)
  2279. .filter(name => name.startsWith('on') && name.length > 2)
  2280. .map(name => name.substring(2));
  2281. }
  2282. function propertyDescriptorPatch(api, _global) {
  2283. if (isNode && !isMix) {
  2284. return;
  2285. }
  2286. if (Zone[api.symbol('patchEvents')]) {
  2287. // events are already been patched by legacy patch.
  2288. return;
  2289. }
  2290. const ignoreProperties = _global['__Zone_ignore_on_properties'];
  2291. // for browsers that we can patch the descriptor: Chrome & Firefox
  2292. let patchTargets = [];
  2293. if (isBrowser) {
  2294. const internalWindow = window;
  2295. patchTargets = patchTargets.concat([
  2296. 'Document', 'SVGElement', 'Element', 'HTMLElement', 'HTMLBodyElement', 'HTMLMediaElement',
  2297. 'HTMLFrameSetElement', 'HTMLFrameElement', 'HTMLIFrameElement', 'HTMLMarqueeElement', 'Worker'
  2298. ]);
  2299. const ignoreErrorProperties = isIE() ? [{ target: internalWindow, ignoreProperties: ['error'] }] : [];
  2300. // in IE/Edge, onProp not exist in window object, but in WindowPrototype
  2301. // so we need to pass WindowPrototype to check onProp exist or not
  2302. patchFilteredProperties(internalWindow, getOnEventNames(internalWindow), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
  2303. }
  2304. patchTargets = patchTargets.concat([
  2305. 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'IDBIndex', 'IDBRequest', 'IDBOpenDBRequest',
  2306. 'IDBDatabase', 'IDBTransaction', 'IDBCursor', 'WebSocket'
  2307. ]);
  2308. for (let i = 0; i < patchTargets.length; i++) {
  2309. const target = _global[patchTargets[i]];
  2310. target && target.prototype &&
  2311. patchFilteredProperties(target.prototype, getOnEventNames(target.prototype), ignoreProperties);
  2312. }
  2313. }
  2314. Zone.__load_patch('util', (global, Zone, api) => {
  2315. // Collect native event names by looking at properties
  2316. // on the global namespace, e.g. 'onclick'.
  2317. const eventNames = getOnEventNames(global);
  2318. api.patchOnProperties = patchOnProperties;
  2319. api.patchMethod = patchMethod;
  2320. api.bindArguments = bindArguments;
  2321. api.patchMacroTask = patchMacroTask;
  2322. // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS` to
  2323. // define which events will not be patched by `Zone.js`.
  2324. // In newer version (>=0.9.0), we change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep
  2325. // the name consistent with angular repo.
  2326. // The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be supported for
  2327. // backwards compatibility.
  2328. const SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
  2329. const SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
  2330. if (global[SYMBOL_UNPATCHED_EVENTS]) {
  2331. global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
  2332. }
  2333. if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
  2334. Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
  2335. global[SYMBOL_BLACK_LISTED_EVENTS];
  2336. }
  2337. api.patchEventPrototype = patchEventPrototype;
  2338. api.patchEventTarget = patchEventTarget;
  2339. api.isIEOrEdge = isIEOrEdge;
  2340. api.ObjectDefineProperty = ObjectDefineProperty;
  2341. api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
  2342. api.ObjectCreate = ObjectCreate;
  2343. api.ArraySlice = ArraySlice;
  2344. api.patchClass = patchClass;
  2345. api.wrapWithCurrentZone = wrapWithCurrentZone;
  2346. api.filterProperties = filterProperties;
  2347. api.attachOriginToPatched = attachOriginToPatched;
  2348. api._redefineProperty = Object.defineProperty;
  2349. api.patchCallbacks = patchCallbacks;
  2350. api.getGlobalObjects = () => ({
  2351. globalSources,
  2352. zoneSymbolEventNames,
  2353. eventNames,
  2354. isBrowser,
  2355. isMix,
  2356. isNode,
  2357. TRUE_STR,
  2358. FALSE_STR,
  2359. ZONE_SYMBOL_PREFIX,
  2360. ADD_EVENT_LISTENER_STR,
  2361. REMOVE_EVENT_LISTENER_STR
  2362. });
  2363. });
  2364. /**
  2365. * @fileoverview
  2366. * @suppress {missingRequire}
  2367. */
  2368. function patchQueueMicrotask(global, api) {
  2369. api.patchMethod(global, 'queueMicrotask', (delegate) => {
  2370. return function (self, args) {
  2371. Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
  2372. };
  2373. });
  2374. }
  2375. /**
  2376. * @fileoverview
  2377. * @suppress {missingRequire}
  2378. */
  2379. const taskSymbol = zoneSymbol('zoneTask');
  2380. function patchTimer(window, setName, cancelName, nameSuffix) {
  2381. let setNative = null;
  2382. let clearNative = null;
  2383. setName += nameSuffix;
  2384. cancelName += nameSuffix;
  2385. const tasksByHandleId = {};
  2386. function scheduleTask(task) {
  2387. const data = task.data;
  2388. data.args[0] = function () {
  2389. return task.invoke.apply(this, arguments);
  2390. };
  2391. data.handleId = setNative.apply(window, data.args);
  2392. return task;
  2393. }
  2394. function clearTask(task) {
  2395. return clearNative.call(window, task.data.handleId);
  2396. }
  2397. setNative =
  2398. patchMethod(window, setName, (delegate) => function (self, args) {
  2399. if (typeof args[0] === 'function') {
  2400. const options = {
  2401. isPeriodic: nameSuffix === 'Interval',
  2402. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  2403. undefined,
  2404. args: args
  2405. };
  2406. const callback = args[0];
  2407. args[0] = function timer() {
  2408. try {
  2409. return callback.apply(this, arguments);
  2410. }
  2411. finally {
  2412. // issue-934, task will be cancelled
  2413. // even it is a periodic task such as
  2414. // setInterval
  2415. // https://github.com/angular/angular/issues/40387
  2416. // Cleanup tasksByHandleId should be handled before scheduleTask
  2417. // Since some zoneSpec may intercept and doesn't trigger
  2418. // scheduleFn(scheduleTask) provided here.
  2419. if (!(options.isPeriodic)) {
  2420. if (typeof options.handleId === 'number') {
  2421. // in non-nodejs env, we remove timerId
  2422. // from local cache
  2423. delete tasksByHandleId[options.handleId];
  2424. }
  2425. else if (options.handleId) {
  2426. // Node returns complex objects as handleIds
  2427. // we remove task reference from timer object
  2428. options.handleId[taskSymbol] = null;
  2429. }
  2430. }
  2431. }
  2432. };
  2433. const task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
  2434. if (!task) {
  2435. return task;
  2436. }
  2437. // Node.js must additionally support the ref and unref functions.
  2438. const handle = task.data.handleId;
  2439. if (typeof handle === 'number') {
  2440. // for non nodejs env, we save handleId: task
  2441. // mapping in local cache for clearTimeout
  2442. tasksByHandleId[handle] = task;
  2443. }
  2444. else if (handle) {
  2445. // for nodejs env, we save task
  2446. // reference in timerId Object for clearTimeout
  2447. handle[taskSymbol] = task;
  2448. }
  2449. // check whether handle is null, because some polyfill or browser
  2450. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  2451. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  2452. typeof handle.unref === 'function') {
  2453. task.ref = handle.ref.bind(handle);
  2454. task.unref = handle.unref.bind(handle);
  2455. }
  2456. if (typeof handle === 'number' || handle) {
  2457. return handle;
  2458. }
  2459. return task;
  2460. }
  2461. else {
  2462. // cause an error by calling it directly.
  2463. return delegate.apply(window, args);
  2464. }
  2465. });
  2466. clearNative =
  2467. patchMethod(window, cancelName, (delegate) => function (self, args) {
  2468. const id = args[0];
  2469. let task;
  2470. if (typeof id === 'number') {
  2471. // non nodejs env.
  2472. task = tasksByHandleId[id];
  2473. }
  2474. else {
  2475. // nodejs env.
  2476. task = id && id[taskSymbol];
  2477. // other environments.
  2478. if (!task) {
  2479. task = id;
  2480. }
  2481. }
  2482. if (task && typeof task.type === 'string') {
  2483. if (task.state !== 'notScheduled' &&
  2484. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  2485. if (typeof id === 'number') {
  2486. delete tasksByHandleId[id];
  2487. }
  2488. else if (id) {
  2489. id[taskSymbol] = null;
  2490. }
  2491. // Do not cancel already canceled functions
  2492. task.zone.cancelTask(task);
  2493. }
  2494. }
  2495. else {
  2496. // cause an error by calling it directly.
  2497. delegate.apply(window, args);
  2498. }
  2499. });
  2500. }
  2501. function patchCustomElements(_global, api) {
  2502. const { isBrowser, isMix } = api.getGlobalObjects();
  2503. if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
  2504. return;
  2505. }
  2506. const callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
  2507. api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
  2508. }
  2509. function eventTargetPatch(_global, api) {
  2510. if (Zone[api.symbol('patchEventTarget')]) {
  2511. // EventTarget is already patched.
  2512. return;
  2513. }
  2514. const { eventNames, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX } = api.getGlobalObjects();
  2515. // predefine all __zone_symbol__ + eventName + true/false string
  2516. for (let i = 0; i < eventNames.length; i++) {
  2517. const eventName = eventNames[i];
  2518. const falseEventName = eventName + FALSE_STR;
  2519. const trueEventName = eventName + TRUE_STR;
  2520. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  2521. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  2522. zoneSymbolEventNames[eventName] = {};
  2523. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  2524. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  2525. }
  2526. const EVENT_TARGET = _global['EventTarget'];
  2527. if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
  2528. return;
  2529. }
  2530. api.patchEventTarget(_global, api, [EVENT_TARGET && EVENT_TARGET.prototype]);
  2531. return true;
  2532. }
  2533. function patchEvent(global, api) {
  2534. api.patchEventPrototype(global, api);
  2535. }
  2536. /**
  2537. * @fileoverview
  2538. * @suppress {missingRequire}
  2539. */
  2540. Zone.__load_patch('legacy', (global) => {
  2541. const legacyPatch = global[Zone.__symbol__('legacyPatch')];
  2542. if (legacyPatch) {
  2543. legacyPatch();
  2544. }
  2545. });
  2546. Zone.__load_patch('timers', (global) => {
  2547. const set = 'set';
  2548. const clear = 'clear';
  2549. patchTimer(global, set, clear, 'Timeout');
  2550. patchTimer(global, set, clear, 'Interval');
  2551. patchTimer(global, set, clear, 'Immediate');
  2552. });
  2553. Zone.__load_patch('requestAnimationFrame', (global) => {
  2554. patchTimer(global, 'request', 'cancel', 'AnimationFrame');
  2555. patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
  2556. patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
  2557. });
  2558. Zone.__load_patch('blocking', (global, Zone) => {
  2559. const blockingMethods = ['alert', 'prompt', 'confirm'];
  2560. for (let i = 0; i < blockingMethods.length; i++) {
  2561. const name = blockingMethods[i];
  2562. patchMethod(global, name, (delegate, symbol, name) => {
  2563. return function (s, args) {
  2564. return Zone.current.run(delegate, global, args, name);
  2565. };
  2566. });
  2567. }
  2568. });
  2569. Zone.__load_patch('EventTarget', (global, Zone, api) => {
  2570. patchEvent(global, api);
  2571. eventTargetPatch(global, api);
  2572. // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
  2573. const XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
  2574. if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
  2575. api.patchEventTarget(global, api, [XMLHttpRequestEventTarget.prototype]);
  2576. }
  2577. });
  2578. Zone.__load_patch('MutationObserver', (global, Zone, api) => {
  2579. patchClass('MutationObserver');
  2580. patchClass('WebKitMutationObserver');
  2581. });
  2582. Zone.__load_patch('IntersectionObserver', (global, Zone, api) => {
  2583. patchClass('IntersectionObserver');
  2584. });
  2585. Zone.__load_patch('FileReader', (global, Zone, api) => {
  2586. patchClass('FileReader');
  2587. });
  2588. Zone.__load_patch('on_property', (global, Zone, api) => {
  2589. propertyDescriptorPatch(api, global);
  2590. });
  2591. Zone.__load_patch('customElements', (global, Zone, api) => {
  2592. patchCustomElements(global, api);
  2593. });
  2594. Zone.__load_patch('XHR', (global, Zone) => {
  2595. // Treat XMLHttpRequest as a macrotask.
  2596. patchXHR(global);
  2597. const XHR_TASK = zoneSymbol('xhrTask');
  2598. const XHR_SYNC = zoneSymbol('xhrSync');
  2599. const XHR_LISTENER = zoneSymbol('xhrListener');
  2600. const XHR_SCHEDULED = zoneSymbol('xhrScheduled');
  2601. const XHR_URL = zoneSymbol('xhrURL');
  2602. const XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
  2603. function patchXHR(window) {
  2604. const XMLHttpRequest = window['XMLHttpRequest'];
  2605. if (!XMLHttpRequest) {
  2606. // XMLHttpRequest is not available in service worker
  2607. return;
  2608. }
  2609. const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
  2610. function findPendingTask(target) {
  2611. return target[XHR_TASK];
  2612. }
  2613. let oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2614. let oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2615. if (!oriAddListener) {
  2616. const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
  2617. if (XMLHttpRequestEventTarget) {
  2618. const XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
  2619. oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2620. oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2621. }
  2622. }
  2623. const READY_STATE_CHANGE = 'readystatechange';
  2624. const SCHEDULED = 'scheduled';
  2625. function scheduleTask(task) {
  2626. const data = task.data;
  2627. const target = data.target;
  2628. target[XHR_SCHEDULED] = false;
  2629. target[XHR_ERROR_BEFORE_SCHEDULED] = false;
  2630. // remove existing event listener
  2631. const listener = target[XHR_LISTENER];
  2632. if (!oriAddListener) {
  2633. oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2634. oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2635. }
  2636. if (listener) {
  2637. oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
  2638. }
  2639. const newListener = target[XHR_LISTENER] = () => {
  2640. if (target.readyState === target.DONE) {
  2641. // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
  2642. // readyState=4 multiple times, so we need to check task state here
  2643. if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
  2644. // check whether the xhr has registered onload listener
  2645. // if that is the case, the task should invoke after all
  2646. // onload listeners finish.
  2647. // Also if the request failed without response (status = 0), the load event handler
  2648. // will not be triggered, in that case, we should also invoke the placeholder callback
  2649. // to close the XMLHttpRequest::send macroTask.
  2650. // https://github.com/angular/angular/issues/38795
  2651. const loadTasks = target[Zone.__symbol__('loadfalse')];
  2652. if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
  2653. const oriInvoke = task.invoke;
  2654. task.invoke = function () {
  2655. // need to load the tasks again, because in other
  2656. // load listener, they may remove themselves
  2657. const loadTasks = target[Zone.__symbol__('loadfalse')];
  2658. for (let i = 0; i < loadTasks.length; i++) {
  2659. if (loadTasks[i] === task) {
  2660. loadTasks.splice(i, 1);
  2661. }
  2662. }
  2663. if (!data.aborted && task.state === SCHEDULED) {
  2664. oriInvoke.call(task);
  2665. }
  2666. };
  2667. loadTasks.push(task);
  2668. }
  2669. else {
  2670. task.invoke();
  2671. }
  2672. }
  2673. else if (!data.aborted && target[XHR_SCHEDULED] === false) {
  2674. // error occurs when xhr.send()
  2675. target[XHR_ERROR_BEFORE_SCHEDULED] = true;
  2676. }
  2677. }
  2678. };
  2679. oriAddListener.call(target, READY_STATE_CHANGE, newListener);
  2680. const storedTask = target[XHR_TASK];
  2681. if (!storedTask) {
  2682. target[XHR_TASK] = task;
  2683. }
  2684. sendNative.apply(target, data.args);
  2685. target[XHR_SCHEDULED] = true;
  2686. return task;
  2687. }
  2688. function placeholderCallback() { }
  2689. function clearTask(task) {
  2690. const data = task.data;
  2691. // Note - ideally, we would call data.target.removeEventListener here, but it's too late
  2692. // to prevent it from firing. So instead, we store info for the event listener.
  2693. data.aborted = true;
  2694. return abortNative.apply(data.target, data.args);
  2695. }
  2696. const openNative = patchMethod(XMLHttpRequestPrototype, 'open', () => function (self, args) {
  2697. self[XHR_SYNC] = args[2] == false;
  2698. self[XHR_URL] = args[1];
  2699. return openNative.apply(self, args);
  2700. });
  2701. const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
  2702. const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
  2703. const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
  2704. const sendNative = patchMethod(XMLHttpRequestPrototype, 'send', () => function (self, args) {
  2705. if (Zone.current[fetchTaskScheduling] === true) {
  2706. // a fetch is scheduling, so we are using xhr to polyfill fetch
  2707. // and because we already schedule macroTask for fetch, we should
  2708. // not schedule a macroTask for xhr again
  2709. return sendNative.apply(self, args);
  2710. }
  2711. if (self[XHR_SYNC]) {
  2712. // if the XHR is sync there is no task to schedule, just execute the code.
  2713. return sendNative.apply(self, args);
  2714. }
  2715. else {
  2716. const options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
  2717. const task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
  2718. if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
  2719. task.state === SCHEDULED) {
  2720. // xhr request throw error when send
  2721. // we should invoke task instead of leaving a scheduled
  2722. // pending macroTask
  2723. task.invoke();
  2724. }
  2725. }
  2726. });
  2727. const abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', () => function (self, args) {
  2728. const task = findPendingTask(self);
  2729. if (task && typeof task.type == 'string') {
  2730. // If the XHR has already completed, do nothing.
  2731. // If the XHR has already been aborted, do nothing.
  2732. // Fix #569, call abort multiple times before done will cause
  2733. // macroTask task count be negative number
  2734. if (task.cancelFn == null || (task.data && task.data.aborted)) {
  2735. return;
  2736. }
  2737. task.zone.cancelTask(task);
  2738. }
  2739. else if (Zone.current[fetchTaskAborting] === true) {
  2740. // the abort is called from fetch polyfill, we need to call native abort of XHR.
  2741. return abortNative.apply(self, args);
  2742. }
  2743. // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
  2744. // task
  2745. // to cancel. Do nothing.
  2746. });
  2747. }
  2748. });
  2749. Zone.__load_patch('geolocation', (global) => {
  2750. /// GEO_LOCATION
  2751. if (global['navigator'] && global['navigator'].geolocation) {
  2752. patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
  2753. }
  2754. });
  2755. Zone.__load_patch('PromiseRejectionEvent', (global, Zone) => {
  2756. // handle unhandled promise rejection
  2757. function findPromiseRejectionHandler(evtName) {
  2758. return function (e) {
  2759. const eventTasks = findEventTasks(global, evtName);
  2760. eventTasks.forEach(eventTask => {
  2761. // windows has added unhandledrejection event listener
  2762. // trigger the event listener
  2763. const PromiseRejectionEvent = global['PromiseRejectionEvent'];
  2764. if (PromiseRejectionEvent) {
  2765. const evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection });
  2766. eventTask.invoke(evt);
  2767. }
  2768. });
  2769. };
  2770. }
  2771. if (global['PromiseRejectionEvent']) {
  2772. Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
  2773. findPromiseRejectionHandler('unhandledrejection');
  2774. Zone[zoneSymbol('rejectionHandledHandler')] =
  2775. findPromiseRejectionHandler('rejectionhandled');
  2776. }
  2777. });
  2778. Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
  2779. patchQueueMicrotask(global, api);
  2780. });
  2781. Zone.__load_patch('node_util', (global, Zone, api) => {
  2782. api.patchOnProperties = patchOnProperties;
  2783. api.patchMethod = patchMethod;
  2784. api.bindArguments = bindArguments;
  2785. api.patchMacroTask = patchMacroTask;
  2786. setShouldCopySymbolProperties(true);
  2787. });
  2788. Zone.__load_patch('EventEmitter', (global, Zone, api) => {
  2789. // For EventEmitter
  2790. const EE_ADD_LISTENER = 'addListener';
  2791. const EE_PREPEND_LISTENER = 'prependListener';
  2792. const EE_REMOVE_LISTENER = 'removeListener';
  2793. const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  2794. const EE_LISTENERS = 'listeners';
  2795. const EE_ON = 'on';
  2796. const EE_OFF = 'off';
  2797. const compareTaskCallbackVsDelegate = function (task, delegate) {
  2798. // same callback, same capture, same event name, just return
  2799. return task.callback === delegate || task.callback.listener === delegate;
  2800. };
  2801. const eventNameToString = function (eventName) {
  2802. if (typeof eventName === 'string') {
  2803. return eventName;
  2804. }
  2805. if (!eventName) {
  2806. return '';
  2807. }
  2808. return eventName.toString().replace('(', '_').replace(')', '_');
  2809. };
  2810. function patchEventEmitterMethods(obj) {
  2811. const result = patchEventTarget(global, api, [obj], {
  2812. useG: false,
  2813. add: EE_ADD_LISTENER,
  2814. rm: EE_REMOVE_LISTENER,
  2815. prepend: EE_PREPEND_LISTENER,
  2816. rmAll: EE_REMOVE_ALL_LISTENER,
  2817. listeners: EE_LISTENERS,
  2818. chkDup: false,
  2819. rt: true,
  2820. diff: compareTaskCallbackVsDelegate,
  2821. eventNameToString: eventNameToString
  2822. });
  2823. if (result && result[0]) {
  2824. obj[EE_ON] = obj[EE_ADD_LISTENER];
  2825. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  2826. }
  2827. }
  2828. // EventEmitter
  2829. let events;
  2830. try {
  2831. events = require('events');
  2832. }
  2833. catch (err) {
  2834. }
  2835. if (events && events.EventEmitter) {
  2836. patchEventEmitterMethods(events.EventEmitter.prototype);
  2837. }
  2838. });
  2839. Zone.__load_patch('fs', () => {
  2840. let fs;
  2841. try {
  2842. fs = require('fs');
  2843. }
  2844. catch (err) {
  2845. }
  2846. // watch, watchFile, unwatchFile has been patched
  2847. // because EventEmitter has been patched
  2848. const TO_PATCH_MACROTASK_METHODS = [
  2849. 'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
  2850. 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
  2851. 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
  2852. 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
  2853. 'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
  2854. ];
  2855. if (fs) {
  2856. TO_PATCH_MACROTASK_METHODS.filter(name => !!fs[name] && typeof fs[name] === 'function')
  2857. .forEach(name => {
  2858. patchMacroTask(fs, name, (self, args) => {
  2859. return {
  2860. name: 'fs.' + name,
  2861. args: args,
  2862. cbIdx: args.length > 0 ? args.length - 1 : -1,
  2863. target: self
  2864. };
  2865. });
  2866. });
  2867. }
  2868. });
  2869. const set = 'set';
  2870. const clear = 'clear';
  2871. Zone.__load_patch('node_timers', (global, Zone) => {
  2872. // Timers
  2873. let globalUseTimeoutFromTimer = false;
  2874. try {
  2875. const timers = require('timers');
  2876. let globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  2877. if (!globalEqualTimersTimeout && !isMix) {
  2878. // 1. if isMix, then we are in mix environment such as Electron
  2879. // we should only patch timers.setTimeout because global.setTimeout
  2880. // have been patched
  2881. // 2. if global.setTimeout not equal timers.setTimeout, check
  2882. // whether global.setTimeout use timers.setTimeout or not
  2883. const originSetTimeout = timers.setTimeout;
  2884. timers.setTimeout = function () {
  2885. globalUseTimeoutFromTimer = true;
  2886. return originSetTimeout.apply(this, arguments);
  2887. };
  2888. const detectTimeout = global.setTimeout(() => { }, 100);
  2889. clearTimeout(detectTimeout);
  2890. timers.setTimeout = originSetTimeout;
  2891. }
  2892. patchTimer(timers, set, clear, 'Timeout');
  2893. patchTimer(timers, set, clear, 'Interval');
  2894. patchTimer(timers, set, clear, 'Immediate');
  2895. }
  2896. catch (error) {
  2897. // timers module not exists, for example, when we using nativeScript
  2898. // timers is not available
  2899. }
  2900. if (isMix) {
  2901. // if we are in mix environment, such as Electron,
  2902. // the global.setTimeout has already been patched,
  2903. // so we just patch timers.setTimeout
  2904. return;
  2905. }
  2906. if (!globalUseTimeoutFromTimer) {
  2907. // 1. global setTimeout equals timers setTimeout
  2908. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  2909. // 3. or load timers module error happens, we should patch global setTimeout
  2910. patchTimer(global, set, clear, 'Timeout');
  2911. patchTimer(global, set, clear, 'Interval');
  2912. patchTimer(global, set, clear, 'Immediate');
  2913. }
  2914. else {
  2915. // global use timers setTimeout, but not equals
  2916. // this happens when use nodejs v0.10.x, global setTimeout will
  2917. // use a lazy load version of timers setTimeout
  2918. // we should not double patch timer's setTimeout
  2919. // so we only store the __symbol__ for consistency
  2920. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  2921. global[Zone.__symbol__('setInterval')] = global.setInterval;
  2922. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  2923. }
  2924. });
  2925. // patch process related methods
  2926. Zone.__load_patch('nextTick', () => {
  2927. // patch nextTick as microTask
  2928. patchMicroTask(process, 'nextTick', (self, args) => {
  2929. return {
  2930. name: 'process.nextTick',
  2931. args: args,
  2932. cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
  2933. target: process
  2934. };
  2935. });
  2936. });
  2937. Zone.__load_patch('handleUnhandledPromiseRejection', (global, Zone, api) => {
  2938. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  2939. findProcessPromiseRejectionHandler('unhandledRejection');
  2940. Zone[api.symbol('rejectionHandledHandler')] =
  2941. findProcessPromiseRejectionHandler('rejectionHandled');
  2942. // handle unhandled promise rejection
  2943. function findProcessPromiseRejectionHandler(evtName) {
  2944. return function (e) {
  2945. const eventTasks = findEventTasks(process, evtName);
  2946. eventTasks.forEach(eventTask => {
  2947. // process has added unhandledrejection event listener
  2948. // trigger the event listener
  2949. if (evtName === 'unhandledRejection') {
  2950. eventTask.invoke(e.rejection, e.promise);
  2951. }
  2952. else if (evtName === 'rejectionHandled') {
  2953. eventTask.invoke(e.promise);
  2954. }
  2955. });
  2956. };
  2957. }
  2958. });
  2959. // Crypto
  2960. Zone.__load_patch('crypto', () => {
  2961. let crypto;
  2962. try {
  2963. crypto = require('crypto');
  2964. }
  2965. catch (err) {
  2966. }
  2967. // use the generic patchMacroTask to patch crypto
  2968. if (crypto) {
  2969. const methodNames = ['randomBytes', 'pbkdf2'];
  2970. methodNames.forEach(name => {
  2971. patchMacroTask(crypto, name, (self, args) => {
  2972. return {
  2973. name: 'crypto.' + name,
  2974. args: args,
  2975. cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
  2976. args.length - 1 :
  2977. -1,
  2978. target: crypto
  2979. };
  2980. });
  2981. });
  2982. }
  2983. });
  2984. Zone.__load_patch('console', (global, Zone) => {
  2985. const consoleMethods = ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
  2986. consoleMethods.forEach((m) => {
  2987. const originalMethod = console[Zone.__symbol__(m)] = console[m];
  2988. if (originalMethod) {
  2989. console[m] = function () {
  2990. const args = ArraySlice.call(arguments);
  2991. if (Zone.current === Zone.root) {
  2992. return originalMethod.apply(this, args);
  2993. }
  2994. else {
  2995. return Zone.root.run(originalMethod, this, args);
  2996. }
  2997. };
  2998. }
  2999. });
  3000. });
  3001. Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
  3002. patchQueueMicrotask(global, api);
  3003. });