zone-node.js 105 KB

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