zone-mix.umd.js 147 KB

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