zone-mix.js 147 KB

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