zone-mix.umd.js 164 KB

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