zone.js 120 KB

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